1use super::*;
2
3pub const DEFAULT_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
14
15const DRAIN_BUSY_REPROBE_INTERVAL: Duration = Duration::from_millis(250);
27
28impl SupervisedChild {
29 pub(super) fn group_drain_budget(&self, budget: Duration, _notice: StopNotice) -> Duration {
30 #[cfg(unix)]
31 if self.child.plain_group.is_some() && _notice != StopNotice::SentOverConnection {
32 return budget.min(plain_group::TERM_GRACE);
33 }
34 budget
35 }
36}
37
38impl Supervisor {
39 pub(crate) fn daemon_shutdown_flag(&self) -> crate::child_roster::DaemonShutdownFlag {
42 self.child_roster.shutdown_flag()
43 }
44
45 #[cfg(unix)]
55 pub(crate) fn begin_daemon_shutdown(&self) {
56 self.child_roster.close();
57 if let Some(journal) = &self.terminal_journal {
58 journal.stamp_shutdown();
59 }
60 }
61
62 #[cfg(unix)]
67 pub(crate) async fn drain_for_daemon_shutdown(&self) -> Result<(), SuperviseError> {
68 const NOTICE_BUDGET: Duration = Duration::from_millis(500);
69 const DRAIN_BUDGET: Duration = Duration::from_secs(2);
70 let Some(forwarding) = &self.forwarding else {
71 return Ok(());
72 };
73 let notice_started = Instant::now();
74 let modules = forwarding
75 .begin_daemon_drain()
76 .map_err(SuperviseError::Forwarding)?;
77 let deadline_ms =
78 unix_ms_now().saturating_add((NOTICE_BUDGET + DRAIN_BUDGET).as_millis() as u64);
79 let shutdown_reason = self
80 .supervisor_handle
81 .as_ref()
82 .map(SupervisorHandle::take_daemon_shutdown_reason)
83 .unwrap_or(RouteCloseReason::Disable);
84 let mut modules_told = 0;
85 let mut notices = tokio::task::JoinSet::new();
86 let mut drains = Vec::new();
87 for connection in forwarding
88 .module_connections()
89 .map_err(SuperviseError::Forwarding)?
90 {
91 let target = ModuleDrainTarget {
92 endpoint: connection.endpoint,
93 sink: connection.sink,
94 negotiated_ver: connection.negotiated_ver,
95 abandoned_bindings: Vec::new(),
96 excluded_subscriptions: 0,
97 };
98 notices.spawn(async move {
99 (
100 true,
101 send_module_draining(
102 &connection.module_id,
103 shutdown_reason,
104 deadline_ms,
105 &target,
106 true,
107 )
108 .await,
109 )
110 });
111 }
112 for (module_id, endpoint) in modules {
113 let Some(target) = forwarding
114 .begin_endpoint_drain(endpoint, RouteCloseReason::Restart)
115 .map_err(SuperviseError::Forwarding)?
116 else {
117 continue;
118 };
119 let routes = forwarding
120 .endpoint_routes(target.endpoint)
121 .map_err(SuperviseError::Forwarding)?;
122 let mut recipients = Vec::new();
125 let mut clients: Vec<(crate::forwarding::GoodbyeTarget, Vec<u16>)> = Vec::new();
126 for route in routes {
127 let client = route.goodbye_target;
128 if let Some((_, channels)) = clients
129 .iter_mut()
130 .find(|(existing, _)| existing.connection_id == client.connection_id)
131 {
132 channels.push(client.channel);
133 } else {
134 let channel = client.channel;
135 clients.push((client, vec![channel]));
136 }
137 }
138 for (client, mut channels) in clients {
139 channels.sort_unstable();
140 channels.dedup();
141 let closing = serde_json::to_vec(&ClientControlPush::RouteClosing {
142 module_id: module_id.clone(),
143 channels,
144 reason: RouteCloseReason::Restart,
145 })
146 .expect("route closing serializes");
147 recipients.push((client.sink, client.negotiated_ver, closing));
148 }
149 for (sink, version, body) in recipients {
150 notices.spawn(async move {
151 let frame = Frame::build_with_version(
152 version,
153 FrameType::Push,
154 control_flags(),
155 0,
156 0,
157 0,
158 body,
159 )
160 .expect("bounded lifecycle notice frame builds");
161 (false, sink.send_flushed(frame).await.is_ok())
162 });
163 }
164 let gauges = declared_busy_gauges(&self.registry, &module_id)?;
165 drains.push((module_id, target.endpoint, gauges));
166 }
167 let notice_deadline = Instant::now() + NOTICE_BUDGET;
170 while let Ok(Some(result)) = timeout_at(notice_deadline, notices.join_next()).await {
171 match result {
172 Ok((true, true)) => modules_told += 1,
173 Ok((false, true)) => {}
174 result => warn!(?result, "daemon shutdown notice delivery failed"),
175 }
176 }
177 notices.abort_all();
178 info!(
179 ?shutdown_reason,
180 modules_told, "daemon shutdown module notices delivered"
181 );
182 let notice_elapsed = notice_started.elapsed();
183 let drain_started = Instant::now();
184 let deadline = drain_started + DRAIN_BUDGET;
185 let mut waits = tokio::task::JoinSet::new();
186 for (module_id, endpoint, gauges) in drains {
187 let forwarding = Arc::clone(forwarding);
188 let mut runtime = self.runtime_config();
189 runtime.health.cadence = Duration::from_millis(100);
190 waits.spawn(async move {
191 let wait_result = wait_for_forwarding_quiescence(
192 &forwarding,
193 &module_id,
194 &runtime,
195 endpoint,
196 deadline,
197 &gauges,
198 DrainScope::Endpoint(endpoint),
199 &mut DrainGaugeTrace::new(&gauges),
200 )
201 .await;
202 forwarding
206 .record_daemon_drain_result(
207 endpoint,
208 drained_after_quiescence_wait(&wait_result),
209 )
210 .map_err(SuperviseError::Forwarding)?;
211 wait_result
212 });
213 }
214 while let Ok(Some(result)) = timeout_at(deadline, waits.join_next()).await {
215 if !matches!(result, Ok(Ok(true))) {
216 warn!(?result, "daemon shutdown drain did not reach quiescence");
217 }
218 }
219 info!(
222 notice_elapsed_ms = notice_elapsed.as_millis() as u64,
223 drain_elapsed_ms = drain_started.elapsed().as_millis() as u64,
224 "daemon shutdown forwarding drain complete"
225 );
226 Ok(())
227 }
228
229 #[cfg(unix)]
241 pub(crate) async fn end_children_for_daemon_shutdown(
242 &self,
243 already_escalated: bool,
244 escalate: impl std::future::Future<Output = ()>,
245 ) {
246 tokio::pin!(escalate);
247 let mut escalated = already_escalated;
248 if let Some(forwarding) = &self.forwarding {
249 let reason = CloseReason::new(
250 "daemon_shutdown",
251 "the daemon is exiting after its shutdown notice and drain",
252 );
253 if escalated {
254 send_module_goodbyes_for_daemon_shutdown(forwarding, &reason, false).await;
257 } else {
258 tokio::select! {
259 biased;
260 _ = escalate.as_mut() => {
261 info!("second SIGTERM: abandoning module GOODBYE delivery");
262 escalated = true;
263 }
264 _ = send_module_goodbyes_for_daemon_shutdown(forwarding, &reason, true) => {}
265 }
266 }
267 let closed = forwarding.close_all_connections(&reason);
268 debug!(closed, "closed established connections for daemon shutdown");
269 }
270 let escalated_here = escalated && !already_escalated;
274 let remaining_escalate = async move {
275 if escalated_here {
276 std::future::pending::<()>().await;
277 } else {
278 escalate.await;
279 }
280 };
281 crate::child_roster::end_children_for_daemon_shutdown(
282 &self.child_roster,
283 escalated,
284 remaining_escalate,
285 )
286 .await;
287 if let Some(journal) = &self.terminal_journal {
288 journal.flush_shutdown().await;
289 }
290 }
291}
292
293impl SupervisedModule {
294 pub async fn drain(&self) -> Result<(), SuperviseError> {
296 self.stop().await
297 }
298
299 pub(crate) async fn retire_requested(
300 &self,
301 requester: Option<Principal>,
302 ) -> Result<(), SuperviseError> {
303 match self.state()? {
304 ModuleState::Stopped => return Ok(()),
305 ModuleState::Failed
306 if lock_snapshot(&self.inner.snapshot)?
307 .failed_retry
308 .pending
309 .is_none() =>
310 {
311 return Ok(())
312 }
313 ModuleState::Failed
314 | ModuleState::Starting
315 | ModuleState::Running
316 | ModuleState::Unresponsive
317 | ModuleState::Restarting
318 | ModuleState::Draining
319 | ModuleState::Disabled => {}
320 }
321
322 let (reply_tx, reply_rx) = oneshot::channel();
323 self.inner
324 .commands
325 .send(SupervisorCommand::Retire {
326 requester,
327 reply: reply_tx,
328 })
329 .await
330 .map_err(|_| SuperviseError::CommandClosed {
331 module_id: self.inner.module_id.clone(),
332 })?;
333 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
334 module_id: self.inner.module_id.clone(),
335 })?
336 }
337
338 pub async fn stop(&self) -> Result<(), SuperviseError> {
339 self.stop_requested(None).await
340 }
341
342 pub(crate) async fn stop_requested(
343 &self,
344 requester: Option<Principal>,
345 ) -> Result<(), SuperviseError> {
346 match self.state()? {
347 ModuleState::Stopped => return Ok(()),
348 ModuleState::Failed
349 if lock_snapshot(&self.inner.snapshot)?
350 .failed_retry
351 .pending
352 .is_none() =>
353 {
354 return Ok(())
355 }
356 ModuleState::Failed
357 | ModuleState::Starting
358 | ModuleState::Running
359 | ModuleState::Unresponsive
360 | ModuleState::Restarting
361 | ModuleState::Draining
362 | ModuleState::Disabled => {}
363 }
364
365 let (reply_tx, reply_rx) = oneshot::channel();
366 self.inner
367 .commands
368 .send(SupervisorCommand::Drain {
369 requester,
370 reply: reply_tx,
371 })
372 .await
373 .map_err(|_| SuperviseError::CommandClosed {
374 module_id: self.inner.module_id.clone(),
375 })?;
376 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
377 module_id: self.inner.module_id.clone(),
378 })?
379 }
380}
381
382#[derive(Debug, Clone, Copy, PartialEq, Eq)]
383pub(super) enum BusyGaugeObservation {
384 Quiescent,
385 Busy,
386 Omitted,
387}
388
389#[derive(Debug, Clone, PartialEq, Eq)]
391pub(super) enum GaugeVerdict {
392 Zero,
394 NonZero(u64),
396 NotACount(String),
400 Missing,
402 ProbeFailed(&'static str),
405}
406
407impl GaugeVerdict {
408 fn reads_quiet(&self) -> bool {
409 matches!(self, Self::Zero)
410 }
411}
412
413impl fmt::Display for GaugeVerdict {
414 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
415 match self {
416 Self::Zero => f.write_str("zero"),
417 Self::NonZero(value) => write!(f, "non_zero({value})"),
418 Self::NotACount(value) => write!(f, "not_a_count({value})"),
419 Self::Missing => f.write_str("missing_from_health_body"),
420 Self::ProbeFailed(kind) => write!(f, "probe_failed({kind})"),
421 }
422 }
423}
424
425const GAUGE_VALUE_TEXT_LIMIT: usize = 32;
428
429pub(super) fn gauge_verdicts(metrics: Option<&Value>, gauges: &[String]) -> Vec<GaugeVerdict> {
431 let metrics = metrics.and_then(Value::as_object);
432 gauges
433 .iter()
434 .map(
435 |gauge| match metrics.and_then(|metrics| metrics.get(gauge)) {
436 None => GaugeVerdict::Missing,
437 Some(value) => match value.as_u64() {
438 Some(0) => GaugeVerdict::Zero,
439 Some(count) => GaugeVerdict::NonZero(count),
440 None => {
441 let mut text = value.to_string();
442 if text.len() > GAUGE_VALUE_TEXT_LIMIT {
443 let mut end = GAUGE_VALUE_TEXT_LIMIT;
444 while !text.is_char_boundary(end) {
445 end -= 1;
446 }
447 text.truncate(end);
448 text.push_str("...");
449 }
450 GaugeVerdict::NotACount(text)
451 }
452 },
453 },
454 )
455 .collect()
456}
457
458pub(super) fn busy_gauge_observation(verdicts: &[GaugeVerdict]) -> BusyGaugeObservation {
461 if verdicts
462 .iter()
463 .any(|verdict| matches!(verdict, GaugeVerdict::Missing))
464 {
465 BusyGaugeObservation::Omitted
466 } else if verdicts.iter().all(GaugeVerdict::reads_quiet) {
467 BusyGaugeObservation::Quiescent
468 } else {
469 BusyGaugeObservation::Busy
470 }
471}
472
473#[derive(Debug, Clone, Default, PartialEq, Eq)]
478pub(super) struct GaugeTrace {
479 pub(super) latest: Option<(GaugeVerdict, Duration)>,
480 pub(super) last_value: Option<(GaugeVerdict, Duration)>,
481}
482
483#[derive(Debug, Clone, Default, PartialEq, Eq)]
489pub(super) struct DrainGaugeTrace {
490 pub(super) probes: u32,
492 pub(super) gauges: Vec<(String, GaugeTrace)>,
494}
495
496impl DrainGaugeTrace {
497 pub(super) fn new(gauges: &[String]) -> Self {
498 Self {
499 probes: 0,
500 gauges: gauges
501 .iter()
502 .map(|gauge| (gauge.clone(), GaugeTrace::default()))
503 .collect(),
504 }
505 }
506
507 fn record(&mut self, verdicts: &[GaugeVerdict], at: Duration) {
509 self.probes = self.probes.saturating_add(1);
510 for ((_, trace), verdict) in self.gauges.iter_mut().zip(verdicts) {
511 trace.latest = Some((verdict.clone(), at));
512 if matches!(
513 verdict,
514 GaugeVerdict::Zero | GaugeVerdict::NonZero(_) | GaugeVerdict::NotACount(_)
515 ) {
516 trace.last_value = Some((verdict.clone(), at));
517 }
518 }
519 }
520}
521
522impl fmt::Display for DrainGaugeTrace {
527 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
528 if self.gauges.is_empty() {
529 return f.write_str("none declared");
530 }
531 for (index, (name, trace)) in self.gauges.iter().enumerate() {
532 if index > 0 {
533 f.write_str(" | ")?;
534 }
535 write!(f, "{name}: ")?;
536 match &trace.latest {
537 Some((verdict, at)) => write!(f, "{verdict} @{}ms", at.as_millis())?,
538 None => f.write_str("never probed")?,
539 }
540 match &trace.last_value {
541 Some((value, at)) => write!(f, "; last value {value} @{}ms", at.as_millis())?,
542 None => f.write_str("; no value ever read")?,
543 }
544 }
545 Ok(())
546 }
547}
548
549pub(crate) fn declared_busy_gauges(
550 registry: &Registry,
551 module_id: &str,
552) -> Result<Vec<String>, SuperviseError> {
553 busy_gauges_of(
554 registry
555 .get_module(module_id)
556 .map_err(SuperviseError::Registry)?,
557 )
558}
559
560fn declared_busy_gauges_for_connection(
564 registry: &Registry,
565 connection_id: ConnectionId,
566) -> Result<Vec<String>, SuperviseError> {
567 busy_gauges_of(
568 registry
569 .get_module_by_connection(connection_id)
570 .map_err(SuperviseError::Registry)?,
571 )
572}
573
574fn busy_gauges_of(
575 registration: Option<crate::registry::ModuleRegistration>,
576) -> Result<Vec<String>, SuperviseError> {
577 let Some(registration) = registration else {
578 return Ok(Vec::new());
579 };
580 let Some(self_signals) = registration.manifest.self_signals else {
581 return Ok(Vec::new());
582 };
583
584 let mut gauges = Vec::new();
585 for declaration in self_signals {
586 if declaration.kind != SelfSignalKind::Busy {
587 continue;
588 }
589 match declaration.anchored_to {
590 SignalAnchor::HealthGauges { gauges: declared } if !declared.is_empty() => {
591 gauges.extend(declared)
592 }
593 _ => {
594 gauges.push(String::new());
597 }
598 }
599 }
600 Ok(gauges)
601}
602
603#[allow(clippy::too_many_arguments)]
612pub(super) async fn wait_for_forwarding_quiescence(
613 forwarding: &ForwardingTable,
614 module_id: &str,
615 runtime: &SupervisorRuntimeConfig,
616 endpoint: crate::ModuleEndpointId,
617 deadline: Instant,
618 busy_gauges: &[String],
619 scope: DrainScope,
620 trace: &mut DrainGaugeTrace,
621) -> Result<bool, SuperviseError> {
622 let wait_started = Instant::now();
623 let mut gauges_quiescent = busy_gauges.is_empty();
624 let mut next_probe_at = wait_started;
625 let mut omission_reported = false;
626
627 loop {
628 let now = Instant::now();
629 if !busy_gauges.is_empty() && now >= next_probe_at && now < deadline {
630 let report = match scope {
631 DrainScope::Active => probe_module_health(module_id, runtime, Some(deadline)).await,
632 DrainScope::Endpoint(endpoint) => {
633 probe_endpoint_health(endpoint, runtime, Some(deadline)).await
634 }
635 };
636 let verdicts = match &report {
637 Ok(report) => gauge_verdicts(report.metrics.as_ref(), busy_gauges),
638 Err(err) => vec![GaugeVerdict::ProbeFailed(err.label()); busy_gauges.len()],
639 };
640 trace.record(&verdicts, wait_started.elapsed());
641 gauges_quiescent = match report {
642 Ok(_) => match busy_gauge_observation(&verdicts) {
643 BusyGaugeObservation::Quiescent => true,
644 BusyGaugeObservation::Busy => false,
645 BusyGaugeObservation::Omitted => {
646 if !omission_reported {
649 forwarding
650 .counters()
651 .increment_drains_with_undeclared_gauge();
652 let missing = busy_gauges
653 .iter()
654 .zip(&verdicts)
655 .filter(|(_, verdict)| matches!(verdict, GaugeVerdict::Missing))
656 .map(|(gauge, _)| gauge.as_str())
657 .collect::<Vec<_>>()
658 .join(",");
659 warn!(
660 module_id,
661 missing_gauges = %missing,
662 "drain health.check answer lacks a declared busy gauge; the drain treats the module as busy until it reports it"
663 );
664 omission_reported = true;
665 }
666 false
667 }
668 },
669 Err(err) => {
670 warn!(
671 module_id,
672 error = %err,
673 "drain health.check did not produce declared busy gauges; treating module as busy"
674 );
675 false
676 }
677 };
678 next_probe_at = Instant::now() + drain_busy_reprobe_interval();
681 }
682
683 let in_flight = forwarding
684 .endpoint_in_flight_count(endpoint)
685 .map_err(SuperviseError::Forwarding)?;
686 if in_flight == 0 && gauges_quiescent {
687 return Ok(true);
688 }
689
690 let now = Instant::now();
691 if now >= deadline {
692 return Ok(false);
693 }
694 let mut wait = deadline
695 .saturating_duration_since(now)
696 .min(REGISTRY_RELEASE_POLL);
697 if !busy_gauges.is_empty() {
698 wait = wait.min(next_probe_at.saturating_duration_since(now));
699 }
700 sleep(wait).await;
701 }
702}
703
704pub(super) fn drain_busy_reprobe_interval() -> Duration {
708 DRAIN_BUSY_REPROBE_INTERVAL.max(REGISTRY_RELEASE_POLL)
709}
710
711pub(super) fn warn_drain_timed_out(
726 module_id: &str,
727 drain_timeout: Duration,
728 reason: RouteCloseReason,
729 holdouts: &crate::forwarding::DrainHoldouts,
730 gauges: &DrainGaugeTrace,
731) {
732 warn!(
733 module_id = %module_id,
734 waited = ?drain_timeout,
735 ?reason,
736 held_requests = holdouts.requests,
737 held_routes = holdouts.routes,
738 total_routes = holdouts.total_routes,
739 top_connections = ?holdouts.top_connections,
740 held = %holdouts
743 .held
744 .iter()
745 .map(|(channel, corr)| format!("{channel}:{corr}"))
746 .collect::<Vec<_>>()
747 .join(","),
748 gauge_probes = gauges.probes,
749 busy_gauges = %gauges,
750 "route drain timed out before request quiescence; forcing teardown"
751 );
752}
753
754pub(super) fn drained_after_quiescence_wait(wait_result: &Result<bool, SuperviseError>) -> bool {
762 match wait_result {
763 Ok(drained) => *drained,
764 Err(_) => false,
765 }
766}
767
768fn send_route_goodbyes(forwarding: &ForwardingTable, released_routes: Vec<GoodbyeTarget>) {
769 for released in released_routes {
770 let frame = match Frame::build_with_version(
771 released.negotiated_ver,
772 FrameType::Goodbye,
773 control_flags(),
774 released.channel,
775 released.epoch,
776 0,
777 Vec::new(),
778 ) {
779 Ok(frame) => frame,
780 Err(err) => {
781 warn!(
782 route_channel = released.channel,
783 error = %err,
784 "failed to build supervisor drain route GOODBYE frame"
785 );
786 continue;
787 }
788 };
789 if !released.close_on_delivery_failure() {
790 crate::forwarding::send_module_route_goodbye(
791 &forwarding.counters(),
792 &released.sink,
793 frame,
794 released.module_id.as_deref(),
795 "supervisor drain",
796 );
797 continue;
798 }
799 if let Err(err) = released.sink.try_send(frame) {
800 warn!(
801 target_connection_id = released.connection_id.get(),
802 route_channel = released.channel,
803 error = %err,
804 "supervisor drain route GOODBYE was not delivered to client; closing target connection"
805 );
806 let _ = forwarding.escalate_client_delivery_failure(
807 released.connection_id,
808 released.channel,
809 released.epoch,
810 CloseReason::new(
811 "route_goodbye_delivery_failed",
812 format!(
813 "failed to enqueue supervisor drain route GOODBYE for channel {}: {err}",
814 released.channel
815 ),
816 ),
817 crate::forwarding::UndeliveredFrame {
818 module_id: released.module_id.as_deref(),
819 sink: &released.sink,
820 },
821 );
822 }
823 }
824}
825
826async fn send_module_draining(
827 module_id: &str,
828 reason: RouteCloseReason,
829 deadline_ms: u64,
830 target: &ModuleDrainTarget,
831 _wait_for_flush: bool,
832) -> bool {
833 let body = match serde_json::to_vec(&ModuleControlCommand::Draining {
834 reason,
835 deadline_ms,
836 }) {
837 Ok(body) => body,
838 Err(err) => {
839 warn!(
840 module_id,
841 error = %err,
842 "failed to encode module draining command"
843 );
844 return false;
845 }
846 };
847 let frame = match Frame::build_with_version(
848 target.negotiated_ver,
849 FrameType::Push,
850 control_flags(),
851 0,
852 0,
853 0,
854 body,
855 ) {
856 Ok(frame) => frame,
857 Err(err) => {
858 warn!(
859 module_id,
860 error = %err,
861 "failed to build module draining command frame"
862 );
863 return false;
864 }
865 };
866 #[cfg(unix)]
867 if _wait_for_flush {
868 return target.sink.send_flushed(frame).await.is_ok();
869 }
870 if let Err(err) = target.sink.try_send(frame) {
871 warn!(
872 module_id,
873 target_connection_id = target.endpoint.connection_id.get(),
874 error = %err,
875 "module draining command was not delivered to peer"
876 );
877 return false;
878 }
879 true
880}
881
882fn module_goodbye_frame(module_id: &str, negotiated_ver: u8) -> Option<Frame> {
884 match Frame::build_with_version(
885 negotiated_ver,
886 FrameType::Goodbye,
887 control_flags(),
888 0,
889 0,
890 0,
891 Vec::new(),
892 ) {
893 Ok(frame) => Some(frame),
894 Err(err) => {
895 warn!(
896 module_id,
897 error = %err,
898 "failed to build module GOODBYE frame"
899 );
900 None
901 }
902 }
903}
904
905#[cfg(unix)]
919async fn send_module_goodbyes_for_daemon_shutdown(
920 forwarding: &Arc<ForwardingTable>,
921 reason: &CloseReason,
922 wait_for_flush: bool,
923) {
924 const GOODBYE_BUDGET: Duration = Duration::from_millis(500);
925 let targets = match forwarding.module_connections() {
926 Ok(targets) => targets,
927 Err(err) => {
928 warn!(error = %err, "could not list module connections for shutdown GOODBYE");
929 return;
930 }
931 };
932 let deadline = Instant::now() + GOODBYE_BUDGET;
933 let mut sends = tokio::task::JoinSet::new();
934 for target in targets {
935 let Some(frame) = module_goodbye_frame(&target.module_id, target.negotiated_ver) else {
936 continue;
937 };
938 if !wait_for_flush {
939 if let Err(err) = target.sink.try_send(frame) {
940 debug!(
941 module_id = %target.module_id,
942 error = %err,
943 "shutdown module GOODBYE was not queued"
944 );
945 }
946 continue;
947 }
948 let forwarding = Arc::clone(forwarding);
949 let reason = reason.clone();
950 sends.spawn(async move {
951 match timeout_at(deadline, target.sink.send_flushed(frame)).await {
952 Ok(Ok(())) => {}
953 Ok(Err(err)) => debug!(
954 module_id = %target.module_id,
955 error = %err,
956 "module connection closed before its shutdown GOODBYE was written"
957 ),
958 Err(_) => warn!(
959 module_id = %target.module_id,
960 budget = ?GOODBYE_BUDGET,
961 "shutdown module GOODBYE was not written within its budget; closing anyway"
962 ),
963 }
964 forwarding.request_connection_close(target.endpoint.connection_id, reason);
965 });
966 }
967 while sends.join_next().await.is_some() {}
969}
970
971async fn send_module_goodbye(
972 module_id: &str,
973 forwarding: &ForwardingTable,
974 target: &ModuleDrainTarget,
975 wait_for_flush: bool,
976) {
977 let Some(frame) = module_goodbye_frame(module_id, target.negotiated_ver) else {
978 return;
979 };
980 let sent = if wait_for_flush {
983 timeout(Duration::from_millis(500), target.sink.send_flushed(frame))
984 .await
985 .map_err(|_| "module GOODBYE flush exceeded 500ms".to_owned())
986 .and_then(|result| result.map_err(|err| err.to_string()))
987 } else {
988 target.sink.try_send(frame).map_err(|err| err.to_string())
989 };
990 if let Err(err) = sent {
991 warn!(
992 module_id,
993 target_connection_id = target.endpoint.connection_id.get(),
994 error = %err,
995 "supervisor drain module GOODBYE was not delivered to peer; closing module connection"
996 );
997 forwarding.request_connection_close(
998 target.endpoint.connection_id,
999 CloseReason::new(
1000 "module_goodbye_delivery_failed",
1001 format!("failed to enqueue supervisor drain module GOODBYE for module '{module_id}': {err}"),
1002 ),
1003 );
1004 }
1005}
1006
1007#[derive(Clone, Copy)]
1008pub(super) struct ForwardingDrainContext<'a> {
1009 pub(super) spec: &'a ModuleSpec,
1010 pub(super) runtime: &'a SupervisorRuntimeConfig,
1011 pub(super) registry: &'a Registry,
1012 pub(super) scope: DrainScope,
1013}
1014
1015#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1017pub(super) enum DrainScope {
1018 Active,
1021 Endpoint(crate::ModuleEndpointId),
1026}
1027
1028#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1036pub(super) enum StopNotice {
1037 SentOverConnection,
1040 NoConnection,
1044 NotSent,
1048}
1049
1050pub(super) async fn begin_forwarding_drain(
1051 spec: &ModuleSpec,
1052 runtime: &SupervisorRuntimeConfig,
1053 registry: &Registry,
1054 snapshot: &SharedSnapshot,
1055 enabled: Option<bool>,
1056 reason: RouteCloseReason,
1057) -> Result<StopNotice, SuperviseError> {
1058 let Some(forwarding) = runtime.forwarding.as_ref() else {
1059 return Err(SuperviseError::ReloadUnavailable {
1060 module_id: spec.module_id.clone(),
1061 reason: "supervisor was not configured with a forwarding table".to_string(),
1062 });
1063 };
1064
1065 begin_forwarding_drain_with(
1066 forwarding,
1067 ForwardingDrainContext {
1068 spec,
1069 runtime,
1070 registry,
1071 scope: DrainScope::Active,
1072 },
1073 snapshot,
1074 enabled,
1075 reason,
1076 runtime.drain_timeout,
1077 )
1078 .await
1079}
1080
1081pub(super) async fn begin_forwarding_drain_if_configured(
1082 spec: &ModuleSpec,
1083 runtime: &SupervisorRuntimeConfig,
1084 registry: &Registry,
1085 snapshot: &SharedSnapshot,
1086 enabled: Option<bool>,
1087 reason: RouteCloseReason,
1088) -> Result<StopNotice, SuperviseError> {
1089 begin_forwarding_drain_with_timeout(
1090 spec,
1091 runtime,
1092 registry,
1093 snapshot,
1094 enabled,
1095 reason,
1096 runtime.drain_timeout,
1097 )
1098 .await
1099}
1100
1101pub(super) async fn begin_forwarding_drain_with_timeout(
1105 spec: &ModuleSpec,
1106 runtime: &SupervisorRuntimeConfig,
1107 registry: &Registry,
1108 snapshot: &SharedSnapshot,
1109 enabled: Option<bool>,
1110 reason: RouteCloseReason,
1111 drain_timeout: Duration,
1112) -> Result<StopNotice, SuperviseError> {
1113 let Some(forwarding) = runtime.forwarding.as_ref() else {
1114 return Ok(StopNotice::NotSent);
1115 };
1116
1117 begin_forwarding_drain_with(
1118 forwarding,
1119 ForwardingDrainContext {
1120 spec,
1121 runtime,
1122 registry,
1123 scope: DrainScope::Active,
1124 },
1125 snapshot,
1126 enabled,
1127 reason,
1128 drain_timeout,
1129 )
1130 .await
1131}
1132
1133pub(super) async fn begin_forwarding_drain_with(
1134 forwarding: &ForwardingTable,
1135 context: ForwardingDrainContext<'_>,
1136 snapshot: &SharedSnapshot,
1137 enabled: Option<bool>,
1138 reason: RouteCloseReason,
1139 drain_timeout: Duration,
1140) -> Result<StopNotice, SuperviseError> {
1141 let ForwardingDrainContext {
1142 spec,
1143 runtime,
1144 registry,
1145 scope,
1146 } = context;
1147 debug_assert_ne!(reason, RouteCloseReason::Crash);
1148 let terminal = matches!(reason, RouteCloseReason::Disable);
1149 let drain_started_at = Instant::now();
1150 let drain_deadline = drain_started_at + drain_timeout;
1151 let deadline_ms =
1152 unix_ms_now().saturating_add(u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX));
1153 let busy_gauges = match scope {
1154 DrainScope::Active => declared_busy_gauges(registry, &spec.module_id)?,
1155 DrainScope::Endpoint(endpoint) => {
1156 declared_busy_gauges_for_connection(registry, endpoint.connection_id)?
1157 }
1158 };
1159
1160 let gate_started = Instant::now();
1163 let drain_target = match scope {
1164 DrainScope::Active => forwarding.begin_module_drain(&spec.module_id, reason),
1165 DrainScope::Endpoint(endpoint) => forwarding.begin_endpoint_drain(endpoint, reason),
1166 }
1167 .map_err(SuperviseError::Forwarding)?;
1168 info!(
1173 module_id = %spec.module_id,
1174 ?reason,
1175 gate_ms = u64::try_from(gate_started.elapsed().as_millis()).unwrap_or(u64::MAX),
1176 connected = drain_target.is_some(),
1177 "module drain began; route admission closed"
1178 );
1179 if scope == DrainScope::Active {
1180 update_snapshot(snapshot, Some(&spec.module_id), |state| {
1181 state.state = ModuleState::Draining;
1182 state.draining_to_replace =
1183 matches!(reason, RouteCloseReason::Restart | RouteCloseReason::Reload);
1184 if let Some(enabled) = enabled {
1185 state.enabled = enabled;
1186 }
1187 })?;
1188 }
1189
1190 let Some(target) = drain_target.as_ref() else {
1191 return Ok(StopNotice::NoConnection);
1195 };
1196 let flush_goodbye = runtime.supervisor_handle.as_ref().is_some_and(|handle| {
1197 handle
1198 .registration_spawn(target.endpoint.connection_id)
1199 .is_some()
1200 });
1201 {
1202 send_module_draining(&spec.module_id, reason, deadline_ms, target, false).await;
1203 #[cfg(feature = "test-support")]
1204 forwarding.wait_before_route_closing_for_test().await;
1205 let routes = forwarding
1206 .endpoint_routes(target.endpoint)
1207 .map_err(SuperviseError::Forwarding)?;
1208 let routes_notified = routes.len();
1209 crate::control::send_route_control_pushes(
1210 forwarding,
1211 routes.clone(),
1212 ClientControlPush::RouteClosing {
1213 module_id: spec.module_id.clone(),
1214 channels: Vec::new(),
1215 reason,
1216 },
1217 );
1218 send_route_goodbyes(forwarding, target.abandoned_bindings.clone());
1219
1220 let mut gauge_trace = DrainGaugeTrace::new(&busy_gauges);
1226 let wait_result = wait_for_forwarding_quiescence(
1227 forwarding,
1228 &spec.module_id,
1229 runtime,
1230 target.endpoint,
1231 drain_deadline,
1232 &busy_gauges,
1233 scope,
1234 &mut gauge_trace,
1235 )
1236 .await;
1237 let drained = drained_after_quiescence_wait(&wait_result);
1238 if let Err(err) = &wait_result {
1239 error!(
1240 module_id = %spec.module_id,
1241 ?reason,
1242 error = %err,
1243 "forwarding quiescence wait failed after route.closing; forcing route.closed(drained: false) so the client is not left waiting on an unfulfilled promise"
1244 );
1245 } else if !drained {
1246 let holdouts = forwarding
1248 .endpoint_drain_holdouts(target.endpoint)
1249 .unwrap_or_default();
1250 warn_drain_timed_out(
1251 &spec.module_id,
1252 drain_timeout,
1253 reason,
1254 &holdouts,
1255 &gauge_trace,
1256 );
1257 }
1258 crate::control::send_route_control_pushes(
1259 forwarding,
1260 routes,
1261 ClientControlPush::RouteClosed {
1262 module_id: spec.module_id.clone(),
1263 channels: Vec::new(),
1264 reason,
1265 drained,
1266 abandoned: target.abandoned_bindings.len() as u32,
1267 excluded_subscriptions: target.excluded_subscriptions,
1268 terminal: Some(terminal),
1269 },
1270 );
1271 wait_result?;
1272
1273 let released_routes = match forwarding.release_module_endpoint_routes(target.endpoint) {
1279 Ok(routes) => routes,
1280 Err(err) => {
1281 warn!(
1282 module_id = %spec.module_id,
1283 ?reason,
1284 error = %err,
1285 "failed to release module endpoint routes after route.closed; module GOODBYE will still be sent"
1286 );
1287 send_module_goodbye(&spec.module_id, forwarding, target, flush_goodbye).await;
1288 return Err(SuperviseError::Forwarding(err));
1289 }
1290 };
1291 let route_goodbye_count = released_routes.len();
1292 send_route_goodbyes(forwarding, released_routes);
1293 send_module_goodbye(&spec.module_id, forwarding, target, flush_goodbye).await;
1294
1295 info!(
1301 module_id = %spec.module_id,
1302 ?reason,
1303 routes_notified,
1304 route_goodbyes = route_goodbye_count,
1305 abandoned_reservations = target.abandoned_bindings.len(),
1306 excluded_subscriptions = target.excluded_subscriptions,
1307 drained,
1308 "module drain complete; consumers notified via route.closing/route.closed pushes and per-route GOODBYE frames"
1309 );
1310 }
1311
1312 Ok(StopNotice::SentOverConnection)
1313}
1314
1315pub(super) fn control_flags() -> Flags {
1316 Flags::new(false, Priority::Passive, false)
1317}
1318
1319#[allow(clippy::too_many_arguments)]
1320pub(super) async fn drain_optional_child(
1321 module_id: &str,
1322 protocol: ModuleProtocol,
1323 stop_notice: StopNotice,
1324 registry: &Registry,
1325 forwarding: Option<&ForwardingTable>,
1326 snapshot: &SharedSnapshot,
1327 terminal_ring: &Arc<Mutex<TerminalRing>>,
1328 spawn_events: &SpawnEventFeed,
1329 child: &mut Option<SupervisedChild>,
1330 drain_timeout: Duration,
1331 final_state: ModuleState,
1332 enabled: Option<bool>,
1333 failure: &FailureContext,
1334) -> Result<(), SuperviseError> {
1335 if let Some(child) = child.take() {
1336 drain_child_to_state(
1337 module_id,
1338 protocol,
1339 stop_notice,
1340 registry,
1341 forwarding,
1342 snapshot,
1343 terminal_ring,
1344 spawn_events,
1345 child,
1346 drain_timeout,
1347 final_state,
1348 enabled,
1349 failure,
1350 )
1351 .await
1352 } else {
1353 update_snapshot(snapshot, Some(module_id), |state| {
1354 state.state = final_state;
1355 if final_state == ModuleState::Failed {
1356 state.failed_retry.failed_at = Some(Instant::now());
1357 }
1358 if let Some(enabled) = enabled {
1359 state.enabled = enabled;
1360 }
1361 clear_current_process_facts(state);
1362 })?;
1363 release_dead_registration(registry, forwarding, snapshot, module_id, failure).await
1364 }
1365}
1366
1367#[allow(clippy::too_many_arguments)]
1368pub(super) async fn drain_child_to_state(
1369 module_id: &str,
1370 _protocol: ModuleProtocol,
1371 stop_notice: StopNotice,
1372 registry: &Registry,
1373 forwarding: Option<&ForwardingTable>,
1374 snapshot: &SharedSnapshot,
1375 terminal_ring: &Arc<Mutex<TerminalRing>>,
1376 spawn_events: &SpawnEventFeed,
1377 mut child: SupervisedChild,
1378 drain_timeout: Duration,
1379 final_state: ModuleState,
1380 enabled: Option<bool>,
1381 failure: &FailureContext,
1382) -> Result<(), SuperviseError> {
1383 let protocol = child.protocol;
1384 child.retire_registration();
1385 update_snapshot(snapshot, Some(module_id), |state| {
1386 state.state = ModuleState::Draining;
1387 state.draining_to_replace = final_state == ModuleState::Restarting;
1388 if let Some(enabled) = enabled {
1389 state.enabled = enabled;
1390 }
1391 })?;
1392
1393 if stop_notice != StopNotice::SentOverConnection {
1404 if protocol == ModuleProtocol::Subc && stop_notice == StopNotice::NoConnection {
1405 info!(
1406 module_id,
1407 pid = child.pid,
1408 budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
1409 "module has no connection yet; requesting stop by signal"
1410 );
1411 }
1412 request_graceful_stop(module_id, &child);
1413 }
1414
1415 let drain_timeout = child.group_drain_budget(drain_timeout, stop_notice);
1416 let exit_report = match timeout(drain_timeout, child.wait()).await {
1417 Ok(Ok(status)) => classify_reaped_child_exit(snapshot, &child, &status),
1418 Ok(Err(source)) => {
1419 fail_after_wait_error(
1420 module_id,
1421 snapshot,
1422 terminal_ring,
1423 spawn_events,
1424 format!("failed to wait during drain: {source}"),
1425 failure,
1426 );
1427 return Err(SuperviseError::Wait {
1428 module_id: module_id.to_string(),
1429 source,
1430 });
1431 }
1432 Err(_) => {
1433 warn!(
1446 module_id,
1447 pid = child.pid,
1448 budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
1449 reason = ?final_state,
1450 ?stop_notice,
1451 "drain budget expired before the module exited; killing it"
1452 );
1453 let kill =
1454 if final_state == ModuleState::Restarting && child.child.container().is_some() {
1455 child.kill_leader()
1456 } else {
1457 child.start_kill()
1458 };
1459 kill.map_err(|source| {
1460 fail_after_wait_error(
1461 module_id,
1462 snapshot,
1463 terminal_ring,
1464 spawn_events,
1465 format!("failed to kill during drain: {source}"),
1466 failure,
1467 );
1468 SuperviseError::Kill {
1469 module_id: module_id.to_string(),
1470 source,
1471 }
1472 })?;
1473 let status = child.wait().await.map_err(|source| {
1474 fail_after_wait_error(
1475 module_id,
1476 snapshot,
1477 terminal_ring,
1478 spawn_events,
1479 format!("failed to wait after drain kill: {source}"),
1480 failure,
1481 );
1482 SuperviseError::Wait {
1483 module_id: module_id.to_string(),
1484 source,
1485 }
1486 })?;
1487 classify_reaped_child_exit(snapshot, &child, &status)
1488 }
1489 };
1490
1491 child.drain_stderr(module_id).await;
1492 let detail =
1493 child.exit_cleanup_detail(lock_snapshot(snapshot)?.drain_disposition_detail.take());
1494 publish_after_terminal_record(
1495 module_id,
1496 || {
1497 record_terminal_with_detail(
1498 module_id,
1499 terminal_ring,
1500 spawn_events,
1501 &exit_report,
1502 terminal_disposition(final_state),
1503 detail,
1504 )
1505 },
1506 || {
1507 update_snapshot(snapshot, Some(module_id), |state| {
1508 state.state = final_state;
1509 if final_state == ModuleState::Failed {
1510 state.failed_retry.failed_at = Some(Instant::now());
1511 }
1512 if let Some(enabled) = enabled {
1513 state.enabled = enabled;
1514 }
1515 clear_current_process_facts(state);
1516 state.last_exit = Some(exit_report.clone());
1517 if exit_report.kind == ExitKind::DeliberateSeverance {
1518 state.lifetime_restarts += 1;
1519 }
1520 })
1521 },
1522 )?;
1523 let released =
1524 release_dead_registration(registry, forwarding, snapshot, module_id, failure).await;
1525 child
1526 .finish_exit(
1527 released.is_ok()
1528 && final_state == ModuleState::Restarting
1529 && child.spawn_failure.is_none(),
1530 )
1531 .await
1532 .map_err(|source| SuperviseError::Wait {
1533 module_id: module_id.to_owned(),
1534 source,
1535 })?;
1536 released
1537}
1538
1539#[cfg(unix)]
1559pub(super) fn request_graceful_stop(module_id: &str, child: &SupervisedChild) {
1560 if let Some(group) = &child.child.plain_group {
1561 if let Err(error) = group.signal(rustix::process::Signal::TERM) {
1562 debug!(module_id, %error, "group TERM was not delivered; the drain wait and kill still apply");
1563 }
1564 return;
1565 }
1566 let Some(pid) = child
1567 .id()
1568 .and_then(|pid| i32::try_from(pid).ok())
1569 .filter(|pid| *pid > 1)
1570 .and_then(rustix::process::Pid::from_raw)
1571 else {
1572 debug!(
1573 module_id,
1574 "no pid to signal for teardown; falling through to the drain wait"
1575 );
1576 return;
1577 };
1578 match rustix::process::kill_process(pid, rustix::process::Signal::TERM) {
1579 Ok(()) => debug!(
1580 module_id,
1581 "sent SIGTERM to a module nothing else asked to stop"
1582 ),
1583 Err(err) => debug!(
1584 module_id,
1585 error = %err,
1586 "SIGTERM to module failed; the drain wait and kill still apply"
1587 ),
1588 }
1589}
1590
1591#[cfg(not(unix))]
1599pub(super) fn request_graceful_stop(module_id: &str, _child: &SupervisedChild) {
1600 debug!(
1601 module_id,
1602 "no graceful stop signal exists on this platform; teardown of a module nothing asked to stop waits, then kills"
1603 );
1604}
1605
1606pub(super) fn terminal_disposition(final_state: ModuleState) -> TerminalDisposition {
1607 match final_state {
1608 ModuleState::Stopped => TerminalDisposition::Stopped,
1609 ModuleState::Disabled => TerminalDisposition::Disabled,
1610 ModuleState::Restarting => TerminalDisposition::Restarting,
1611 ModuleState::Failed => TerminalDisposition::Failed,
1612 ModuleState::Starting
1613 | ModuleState::Running
1614 | ModuleState::Unresponsive
1615 | ModuleState::Draining => {
1616 unreachable!("terminal exits only finish in terminal or restarting states")
1617 }
1618 }
1619}