1use super::*;
2
3pub const DEFAULT_DRAIN_TIMEOUT: Duration = Duration::from_secs(30);
14
15const ACCEPTING_DRAIN_IN_FLIGHT_WINDOW: Duration = Duration::from_secs(5);
18
19const DRAIN_BUSY_REPROBE_INTERVAL: Duration = Duration::from_millis(250);
31
32impl SupervisedChild {
33 pub(super) fn group_drain_budget(&self, budget: Duration, _notice: StopNotice) -> Duration {
34 #[cfg(unix)]
35 if self.child.plain_group.is_some() && !_notice.sent_over_connection() {
36 return budget.min(plain_group::TERM_GRACE);
37 }
38 budget
39 }
40}
41
42impl Supervisor {
43 pub(crate) fn daemon_shutdown_flag(&self) -> crate::child_roster::DaemonShutdownFlag {
46 self.child_roster.shutdown_flag()
47 }
48
49 #[cfg(unix)]
59 pub(crate) fn begin_daemon_shutdown(&self) {
60 self.child_roster.close();
61 if let Some(journal) = &self.terminal_journal {
62 journal.stamp_shutdown();
63 }
64 }
65
66 #[cfg(unix)]
71 pub(crate) async fn drain_for_daemon_shutdown(&self) -> Result<(), SuperviseError> {
72 const NOTICE_BUDGET: Duration = Duration::from_millis(500);
73 const DRAIN_BUDGET: Duration = Duration::from_secs(2);
74 const MARKER_BUDGET: Duration = Duration::from_millis(500);
75 let Some(forwarding) = &self.forwarding else {
76 return Ok(());
77 };
78 if let Some(journal) = &self.terminal_journal {
83 if !journal.flush_within(MARKER_BUDGET).await {
84 warn!(
85 "shutdown marker not written within its budget; announcing the shutdown anyway"
86 );
87 }
88 }
89 let notice_started = Instant::now();
90 let modules = forwarding
91 .begin_daemon_drain()
92 .map_err(SuperviseError::Forwarding)?;
93 let deadline_ms =
94 unix_ms_now().saturating_add((NOTICE_BUDGET + DRAIN_BUDGET).as_millis() as u64);
95 let shutdown_reason = self
96 .supervisor_handle
97 .as_ref()
98 .map(SupervisorHandle::take_daemon_shutdown_reason)
99 .unwrap_or(RouteCloseReason::Disable);
100 let mut modules_told = 0;
101 let mut notices = tokio::task::JoinSet::new();
102 let mut drains = Vec::new();
103 for connection in forwarding
104 .module_connections()
105 .map_err(SuperviseError::Forwarding)?
106 {
107 let target = ModuleDrainTarget {
108 endpoint: connection.endpoint,
109 sink: connection.sink,
110 negotiated_ver: connection.negotiated_ver,
111 abandoned_bindings: Vec::new(),
112 excluded_subscriptions: 0,
113 };
114 notices.spawn(async move {
115 (
116 true,
117 send_module_draining(
118 &connection.module_id,
119 shutdown_reason,
120 deadline_ms,
121 &target,
122 true,
123 false,
124 )
125 .await,
126 )
127 });
128 }
129 for (module_id, endpoint) in modules {
130 let Some(target) = forwarding
131 .begin_endpoint_drain(endpoint, RouteCloseReason::Restart)
132 .map_err(SuperviseError::Forwarding)?
133 else {
134 continue;
135 };
136 let routes = forwarding
137 .endpoint_routes(target.endpoint)
138 .map_err(SuperviseError::Forwarding)?;
139 let mut recipients = Vec::new();
142 let mut clients: Vec<(crate::forwarding::GoodbyeTarget, Vec<u16>)> = Vec::new();
143 for route in routes {
144 let client = route.goodbye_target;
145 if let Some((_, channels)) = clients
146 .iter_mut()
147 .find(|(existing, _)| existing.connection_id == client.connection_id)
148 {
149 channels.push(client.channel);
150 } else {
151 let channel = client.channel;
152 clients.push((client, vec![channel]));
153 }
154 }
155 for (client, mut channels) in clients {
156 channels.sort_unstable();
157 channels.dedup();
158 let closing = serde_json::to_vec(&ClientControlPush::RouteClosing {
159 module_id: module_id.clone(),
160 channels,
161 reason: RouteCloseReason::Restart,
162 })
163 .expect("route closing serializes");
164 recipients.push((client.sink, client.negotiated_ver, closing));
165 }
166 for (sink, version, body) in recipients {
167 notices.spawn(async move {
168 let frame = Frame::build_with_version(
169 version,
170 FrameType::Push,
171 control_flags(),
172 0,
173 0,
174 0,
175 body,
176 )
177 .expect("bounded lifecycle notice frame builds");
178 (false, sink.send_flushed(frame).await.is_ok())
179 });
180 }
181 let gauges = declared_busy_gauges(&self.registry, &module_id)?;
182 drains.push((module_id, target.endpoint, gauges));
183 }
184 let notice_deadline = Instant::now() + NOTICE_BUDGET;
187 while let Ok(Some(result)) = timeout_at(notice_deadline, notices.join_next()).await {
188 match result {
189 Ok((true, true)) => modules_told += 1,
190 Ok((false, true)) => {}
191 result => warn!(?result, "daemon shutdown notice delivery failed"),
192 }
193 }
194 notices.abort_all();
195 info!(
196 ?shutdown_reason,
197 modules_told, "daemon shutdown module notices delivered"
198 );
199 let notice_elapsed = notice_started.elapsed();
200 let drain_started = Instant::now();
201 let deadline = drain_started + DRAIN_BUDGET;
202 let mut waits = tokio::task::JoinSet::new();
203 for (module_id, endpoint, gauges) in drains {
204 let forwarding = Arc::clone(forwarding);
205 let mut runtime = self.runtime_config();
206 runtime.health.cadence = Duration::from_millis(100);
207 waits.spawn(async move {
208 let wait_result = wait_for_forwarding_quiescence(
209 &forwarding,
210 &module_id,
211 &runtime,
212 endpoint,
213 deadline,
214 &gauges,
215 DrainScope::Endpoint(endpoint),
216 &mut DrainGaugeTrace::new(&gauges),
217 )
218 .await;
219 forwarding
223 .record_daemon_drain_result(
224 endpoint,
225 drained_after_quiescence_wait(&wait_result),
226 )
227 .map_err(SuperviseError::Forwarding)?;
228 wait_result
229 });
230 }
231 while let Ok(Some(result)) = timeout_at(deadline, waits.join_next()).await {
232 if !matches!(result, Ok(Ok(true))) {
233 warn!(?result, "daemon shutdown drain did not reach quiescence");
234 }
235 }
236 info!(
239 notice_elapsed_ms = notice_elapsed.as_millis() as u64,
240 drain_elapsed_ms = drain_started.elapsed().as_millis() as u64,
241 "daemon shutdown forwarding drain complete"
242 );
243 Ok(())
244 }
245
246 #[cfg(unix)]
258 pub(crate) async fn end_children_for_daemon_shutdown(
259 &self,
260 already_escalated: bool,
261 escalate: impl std::future::Future<Output = ()>,
262 ) {
263 tokio::pin!(escalate);
264 let mut escalated = already_escalated;
265 if let Some(forwarding) = &self.forwarding {
266 let reason = CloseReason::new(
267 "daemon_shutdown",
268 "the daemon is exiting after its shutdown notice and drain",
269 );
270 if escalated {
271 send_module_goodbyes_for_daemon_shutdown(forwarding, &reason, false).await;
274 } else {
275 tokio::select! {
276 biased;
277 _ = escalate.as_mut() => {
278 info!("second SIGTERM: abandoning module GOODBYE delivery");
279 escalated = true;
280 }
281 _ = send_module_goodbyes_for_daemon_shutdown(forwarding, &reason, true) => {}
282 }
283 }
284 let closed = forwarding.close_all_connections(&reason);
285 debug!(closed, "closed established connections for daemon shutdown");
286 }
287 let escalated_here = escalated && !already_escalated;
291 let remaining_escalate = async move {
292 if escalated_here {
293 std::future::pending::<()>().await;
294 } else {
295 escalate.await;
296 }
297 };
298 crate::child_roster::end_children_for_daemon_shutdown(
299 &self.child_roster,
300 escalated,
301 remaining_escalate,
302 )
303 .await;
304 if let Some(journal) = &self.terminal_journal {
305 journal.flush_shutdown().await;
306 }
307 }
308}
309
310impl SupervisedModule {
311 pub async fn drain(&self) -> Result<(), SuperviseError> {
313 self.stop().await
314 }
315
316 pub(crate) async fn retire_requested(
317 &self,
318 requester: Option<Principal>,
319 ) -> Result<(), SuperviseError> {
320 match self.state()? {
321 ModuleState::Stopped => return Ok(()),
322 ModuleState::Failed
323 if lock_snapshot(&self.inner.snapshot)?
324 .failed_retry
325 .pending
326 .is_none() =>
327 {
328 return Ok(())
329 }
330 ModuleState::Failed
331 | ModuleState::Starting
332 | ModuleState::Running
333 | ModuleState::Unresponsive
334 | ModuleState::Restarting
335 | ModuleState::Draining
336 | ModuleState::Disabled => {}
337 }
338
339 let (reply_tx, reply_rx) = oneshot::channel();
340 self.inner
341 .commands
342 .send(SupervisorCommand::Retire {
343 requester,
344 reply: reply_tx,
345 })
346 .await
347 .map_err(|_| SuperviseError::CommandClosed {
348 module_id: self.inner.module_id.clone(),
349 })?;
350 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
351 module_id: self.inner.module_id.clone(),
352 })?
353 }
354
355 pub async fn stop(&self) -> Result<(), SuperviseError> {
356 self.stop_requested(None).await
357 }
358
359 pub(crate) async fn stop_requested(
360 &self,
361 requester: Option<Principal>,
362 ) -> Result<(), SuperviseError> {
363 match self.state()? {
364 ModuleState::Stopped => return Ok(()),
365 ModuleState::Failed
366 if lock_snapshot(&self.inner.snapshot)?
367 .failed_retry
368 .pending
369 .is_none() =>
370 {
371 return Ok(())
372 }
373 ModuleState::Failed
374 | ModuleState::Starting
375 | ModuleState::Running
376 | ModuleState::Unresponsive
377 | ModuleState::Restarting
378 | ModuleState::Draining
379 | ModuleState::Disabled => {}
380 }
381
382 let (reply_tx, reply_rx) = oneshot::channel();
383 self.inner
384 .commands
385 .send(SupervisorCommand::Drain {
386 requester,
387 reply: reply_tx,
388 })
389 .await
390 .map_err(|_| SuperviseError::CommandClosed {
391 module_id: self.inner.module_id.clone(),
392 })?;
393 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
394 module_id: self.inner.module_id.clone(),
395 })?
396 }
397}
398
399#[derive(Debug, Clone, Copy, PartialEq, Eq)]
400pub(super) enum BusyGaugeObservation {
401 Quiescent,
402 Busy,
403 Omitted,
404}
405
406#[derive(Debug, Clone, PartialEq, Eq)]
408pub(super) enum GaugeVerdict {
409 Zero,
411 NonZero(u64),
413 NotACount(String),
417 Missing,
419 ProbeFailed(&'static str),
422}
423
424impl GaugeVerdict {
425 fn reads_quiet(&self) -> bool {
426 matches!(self, Self::Zero)
427 }
428}
429
430impl fmt::Display for GaugeVerdict {
431 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
432 match self {
433 Self::Zero => f.write_str("zero"),
434 Self::NonZero(value) => write!(f, "non_zero({value})"),
435 Self::NotACount(value) => write!(f, "not_a_count({value})"),
436 Self::Missing => f.write_str("missing_from_health_body"),
437 Self::ProbeFailed(kind) => write!(f, "probe_failed({kind})"),
438 }
439 }
440}
441
442const GAUGE_VALUE_TEXT_LIMIT: usize = 32;
445
446pub(super) fn gauge_verdicts(metrics: Option<&Value>, gauges: &[String]) -> Vec<GaugeVerdict> {
448 let metrics = metrics.and_then(Value::as_object);
449 gauges
450 .iter()
451 .map(
452 |gauge| match metrics.and_then(|metrics| metrics.get(gauge)) {
453 None => GaugeVerdict::Missing,
454 Some(value) => match value.as_u64() {
455 Some(0) => GaugeVerdict::Zero,
456 Some(count) => GaugeVerdict::NonZero(count),
457 None => {
458 let mut text = value.to_string();
459 if text.len() > GAUGE_VALUE_TEXT_LIMIT {
460 let mut end = GAUGE_VALUE_TEXT_LIMIT;
461 while !text.is_char_boundary(end) {
462 end -= 1;
463 }
464 text.truncate(end);
465 text.push_str("...");
466 }
467 GaugeVerdict::NotACount(text)
468 }
469 },
470 },
471 )
472 .collect()
473}
474
475pub(super) fn busy_gauge_observation(verdicts: &[GaugeVerdict]) -> BusyGaugeObservation {
478 if verdicts
479 .iter()
480 .any(|verdict| matches!(verdict, GaugeVerdict::Missing))
481 {
482 BusyGaugeObservation::Omitted
483 } else if verdicts.iter().all(GaugeVerdict::reads_quiet) {
484 BusyGaugeObservation::Quiescent
485 } else {
486 BusyGaugeObservation::Busy
487 }
488}
489
490#[derive(Debug, Clone, Default, PartialEq, Eq)]
495pub(super) struct GaugeTrace {
496 pub(super) latest: Option<(GaugeVerdict, Duration)>,
497 pub(super) last_value: Option<(GaugeVerdict, Duration)>,
498}
499
500#[derive(Debug, Clone, Default, PartialEq, Eq)]
506pub(super) struct DrainGaugeTrace {
507 pub(super) probes: u32,
509 pub(super) gauges: Vec<(String, GaugeTrace)>,
511}
512
513impl DrainGaugeTrace {
514 pub(super) fn new(gauges: &[String]) -> Self {
515 Self {
516 probes: 0,
517 gauges: gauges
518 .iter()
519 .map(|gauge| (gauge.clone(), GaugeTrace::default()))
520 .collect(),
521 }
522 }
523
524 fn record(&mut self, verdicts: &[GaugeVerdict], at: Duration) {
526 self.probes = self.probes.saturating_add(1);
527 for ((_, trace), verdict) in self.gauges.iter_mut().zip(verdicts) {
528 trace.latest = Some((verdict.clone(), at));
529 if matches!(
530 verdict,
531 GaugeVerdict::Zero | GaugeVerdict::NonZero(_) | GaugeVerdict::NotACount(_)
532 ) {
533 trace.last_value = Some((verdict.clone(), at));
534 }
535 }
536 }
537}
538
539impl fmt::Display for DrainGaugeTrace {
544 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
545 if self.gauges.is_empty() {
546 return f.write_str("none declared");
547 }
548 for (index, (name, trace)) in self.gauges.iter().enumerate() {
549 if index > 0 {
550 f.write_str(" | ")?;
551 }
552 write!(f, "{name}: ")?;
553 match &trace.latest {
554 Some((verdict, at)) => write!(f, "{verdict} @{}ms", at.as_millis())?,
555 None => f.write_str("never probed")?,
556 }
557 match &trace.last_value {
558 Some((value, at)) => write!(f, "; last value {value} @{}ms", at.as_millis())?,
559 None => f.write_str("; no value ever read")?,
560 }
561 }
562 Ok(())
563 }
564}
565
566pub(crate) fn declared_busy_gauges(
567 registry: &Registry,
568 module_id: &str,
569) -> Result<Vec<String>, SuperviseError> {
570 busy_gauges_of(
571 registry
572 .get_module(module_id)
573 .map_err(SuperviseError::Registry)?,
574 )
575}
576
577fn declared_busy_gauges_for_connection(
581 registry: &Registry,
582 connection_id: ConnectionId,
583) -> Result<Vec<String>, SuperviseError> {
584 busy_gauges_of(
585 registry
586 .get_module_by_connection(connection_id)
587 .map_err(SuperviseError::Registry)?,
588 )
589}
590
591fn busy_gauges_of(
592 registration: Option<crate::registry::ModuleRegistration>,
593) -> Result<Vec<String>, SuperviseError> {
594 let Some(registration) = registration else {
595 return Ok(Vec::new());
596 };
597 let Some(self_signals) = registration.manifest.self_signals else {
598 return Ok(Vec::new());
599 };
600
601 let mut gauges = Vec::new();
602 for declaration in self_signals {
603 if declaration.kind != SelfSignalKind::Busy {
604 continue;
605 }
606 match declaration.anchored_to {
607 SignalAnchor::HealthGauges { gauges: declared } if !declared.is_empty() => {
608 gauges.extend(declared)
609 }
610 _ => {
611 gauges.push(String::new());
614 }
615 }
616 }
617 Ok(gauges)
618}
619
620#[allow(clippy::too_many_arguments)]
629pub(super) async fn wait_for_forwarding_quiescence(
630 forwarding: &ForwardingTable,
631 module_id: &str,
632 runtime: &SupervisorRuntimeConfig,
633 endpoint: crate::ModuleEndpointId,
634 deadline: Instant,
635 busy_gauges: &[String],
636 scope: DrainScope,
637 trace: &mut DrainGaugeTrace,
638) -> Result<bool, SuperviseError> {
639 let wait_started = Instant::now();
640 let mut gauges_quiescent = busy_gauges.is_empty();
641 let mut next_probe_at = wait_started;
642 let mut omission_reported = false;
643
644 loop {
645 let now = Instant::now();
646 if !busy_gauges.is_empty() && now >= next_probe_at && now < deadline {
647 let report = match scope {
648 DrainScope::Active => probe_module_health(module_id, runtime, Some(deadline)).await,
649 DrainScope::Endpoint(endpoint) => {
650 probe_endpoint_health(endpoint, runtime, Some(deadline)).await
651 }
652 };
653 let verdicts = match &report {
654 Ok(report) => gauge_verdicts(report.metrics.as_ref(), busy_gauges),
655 Err(err) => vec![GaugeVerdict::ProbeFailed(err.label()); busy_gauges.len()],
656 };
657 trace.record(&verdicts, wait_started.elapsed());
658 gauges_quiescent = match report {
659 Ok(_) => match busy_gauge_observation(&verdicts) {
660 BusyGaugeObservation::Quiescent => true,
661 BusyGaugeObservation::Busy => false,
662 BusyGaugeObservation::Omitted => {
663 if !omission_reported {
666 forwarding
667 .counters()
668 .increment_drains_with_undeclared_gauge();
669 let missing = busy_gauges
670 .iter()
671 .zip(&verdicts)
672 .filter(|(_, verdict)| matches!(verdict, GaugeVerdict::Missing))
673 .map(|(gauge, _)| gauge.as_str())
674 .collect::<Vec<_>>()
675 .join(",");
676 warn!(
677 module_id,
678 missing_gauges = %missing,
679 "drain health.check answer lacks a declared busy gauge; the drain treats the module as busy until it reports it"
680 );
681 omission_reported = true;
682 }
683 false
684 }
685 },
686 Err(err) => {
687 warn!(
688 module_id,
689 error = %err,
690 "drain health.check did not produce declared busy gauges; treating module as busy"
691 );
692 false
693 }
694 };
695 next_probe_at = Instant::now() + drain_busy_reprobe_interval();
698 }
699
700 let in_flight = forwarding
701 .endpoint_in_flight_count(endpoint)
702 .map_err(SuperviseError::Forwarding)?;
703 if in_flight == 0 && gauges_quiescent {
704 return Ok(true);
705 }
706
707 let now = Instant::now();
708 if now >= deadline {
709 return Ok(false);
710 }
711 let mut wait = deadline
712 .saturating_duration_since(now)
713 .min(REGISTRY_RELEASE_POLL);
714 if !busy_gauges.is_empty() {
715 wait = wait.min(next_probe_at.saturating_duration_since(now));
716 }
717 sleep(wait).await;
718 }
719}
720
721pub(super) fn drain_busy_reprobe_interval() -> Duration {
725 DRAIN_BUSY_REPROBE_INTERVAL.max(REGISTRY_RELEASE_POLL)
726}
727
728pub(super) fn warn_drain_timed_out(
743 module_id: &str,
744 drain_timeout: Duration,
745 reason: RouteCloseReason,
746 holdouts: &crate::forwarding::DrainHoldouts,
747 gauges: &DrainGaugeTrace,
748) {
749 warn!(
750 module_id = %module_id,
751 waited = ?drain_timeout,
752 ?reason,
753 held_requests = holdouts.requests,
754 held_routes = holdouts.routes,
755 total_routes = holdouts.total_routes,
756 top_connections = ?holdouts.top_connections,
757 held = %holdouts
760 .held
761 .iter()
762 .map(|(channel, corr)| format!("{channel}:{corr}"))
763 .collect::<Vec<_>>()
764 .join(","),
765 gauge_probes = gauges.probes,
766 busy_gauges = %gauges,
767 "route drain timed out before request quiescence; forcing teardown"
768 );
769}
770
771pub(super) fn drained_after_quiescence_wait(wait_result: &Result<bool, SuperviseError>) -> bool {
779 match wait_result {
780 Ok(drained) => *drained,
781 Err(_) => false,
782 }
783}
784
785fn send_route_goodbyes(forwarding: &ForwardingTable, released_routes: Vec<GoodbyeTarget>) {
786 for released in released_routes {
787 let frame = match Frame::build_with_version(
788 released.negotiated_ver,
789 FrameType::Goodbye,
790 control_flags(),
791 released.channel,
792 released.epoch,
793 0,
794 Vec::new(),
795 ) {
796 Ok(frame) => frame,
797 Err(err) => {
798 warn!(
799 route_channel = released.channel,
800 error = %err,
801 "failed to build supervisor drain route GOODBYE frame"
802 );
803 continue;
804 }
805 };
806 if !released.close_on_delivery_failure() {
807 crate::forwarding::send_module_route_goodbye(
808 &forwarding.counters(),
809 &released.sink,
810 frame,
811 released.module_id.as_deref(),
812 "supervisor drain",
813 );
814 continue;
815 }
816 if let Err(err) = released.sink.try_send(frame) {
817 warn!(
818 target_connection_id = released.connection_id.get(),
819 route_channel = released.channel,
820 error = %err,
821 "supervisor drain route GOODBYE was not delivered to client; closing target connection"
822 );
823 let _ = forwarding.escalate_client_delivery_failure(
824 released.connection_id,
825 released.channel,
826 released.epoch,
827 CloseReason::new(
828 "route_goodbye_delivery_failed",
829 format!(
830 "failed to enqueue supervisor drain route GOODBYE for channel {}: {err}",
831 released.channel
832 ),
833 ),
834 crate::forwarding::UndeliveredFrame {
835 module_id: released.module_id.as_deref(),
836 sink: &released.sink,
837 },
838 );
839 }
840 }
841}
842
843async fn send_module_draining(
844 module_id: &str,
845 reason: RouteCloseReason,
846 deadline_ms: u64,
847 target: &ModuleDrainTarget,
848 _wait_for_flush: bool,
849 accepting: bool,
850) -> bool {
851 let body = if accepting {
852 serde_json::to_vec(&subc_protocol::session::AcceptingDrainCommand::Draining {
853 reason,
854 deadline_ms,
855 accepting: true,
856 })
857 } else {
858 serde_json::to_vec(&ModuleControlCommand::Draining {
859 reason,
860 deadline_ms,
861 })
862 };
863 let body = match body {
864 Ok(body) => body,
865 Err(err) => {
866 warn!(
867 module_id,
868 error = %err,
869 "failed to encode module draining command"
870 );
871 return false;
872 }
873 };
874 let frame = match Frame::build_with_version(
875 target.negotiated_ver,
876 FrameType::Push,
877 control_flags(),
878 0,
879 0,
880 0,
881 body,
882 ) {
883 Ok(frame) => frame,
884 Err(err) => {
885 warn!(
886 module_id,
887 error = %err,
888 "failed to build module draining command frame"
889 );
890 return false;
891 }
892 };
893 #[cfg(unix)]
894 if _wait_for_flush {
895 return target.sink.send_flushed(frame).await.is_ok();
896 }
897 if let Err(err) = target.sink.try_send(frame) {
898 warn!(
899 module_id,
900 target_connection_id = target.endpoint.connection_id.get(),
901 error = %err,
902 "module draining command was not delivered to peer"
903 );
904 return false;
905 }
906 true
907}
908
909fn module_goodbye_frame(module_id: &str, negotiated_ver: u8) -> Option<Frame> {
911 match Frame::build_with_version(
912 negotiated_ver,
913 FrameType::Goodbye,
914 control_flags(),
915 0,
916 0,
917 0,
918 Vec::new(),
919 ) {
920 Ok(frame) => Some(frame),
921 Err(err) => {
922 warn!(
923 module_id,
924 error = %err,
925 "failed to build module GOODBYE frame"
926 );
927 None
928 }
929 }
930}
931
932#[cfg(unix)]
946async fn send_module_goodbyes_for_daemon_shutdown(
947 forwarding: &Arc<ForwardingTable>,
948 reason: &CloseReason,
949 wait_for_flush: bool,
950) {
951 const GOODBYE_BUDGET: Duration = Duration::from_millis(500);
952 let targets = match forwarding.module_connections() {
953 Ok(targets) => targets,
954 Err(err) => {
955 warn!(error = %err, "could not list module connections for shutdown GOODBYE");
956 return;
957 }
958 };
959 let deadline = Instant::now() + GOODBYE_BUDGET;
960 let mut sends = tokio::task::JoinSet::new();
961 for target in targets {
962 let Some(frame) = module_goodbye_frame(&target.module_id, target.negotiated_ver) else {
963 continue;
964 };
965 if !wait_for_flush {
966 if let Err(err) = target.sink.try_send(frame) {
967 debug!(
968 module_id = %target.module_id,
969 error = %err,
970 "shutdown module GOODBYE was not queued"
971 );
972 }
973 continue;
974 }
975 let forwarding = Arc::clone(forwarding);
976 let reason = reason.clone();
977 sends.spawn(async move {
978 match timeout_at(deadline, target.sink.send_flushed(frame)).await {
979 Ok(Ok(())) => {}
980 Ok(Err(err)) => debug!(
981 module_id = %target.module_id,
982 error = %err,
983 "module connection closed before its shutdown GOODBYE was written"
984 ),
985 Err(_) => warn!(
986 module_id = %target.module_id,
987 budget = ?GOODBYE_BUDGET,
988 "shutdown module GOODBYE was not written within its budget; closing anyway"
989 ),
990 }
991 forwarding.request_connection_close(target.endpoint.connection_id, reason);
992 });
993 }
994 while sends.join_next().await.is_some() {}
996}
997
998async fn send_module_goodbye(
999 module_id: &str,
1000 forwarding: &ForwardingTable,
1001 target: &ModuleDrainTarget,
1002 wait_for_flush: bool,
1003) {
1004 let Some(frame) = module_goodbye_frame(module_id, target.negotiated_ver) else {
1005 return;
1006 };
1007 let sent = if wait_for_flush {
1010 timeout(Duration::from_millis(500), target.sink.send_flushed(frame))
1011 .await
1012 .map_err(|_| "module GOODBYE flush exceeded 500ms".to_owned())
1013 .and_then(|result| result.map_err(|err| err.to_string()))
1014 } else {
1015 target.sink.try_send(frame).map_err(|err| err.to_string())
1016 };
1017 if let Err(err) = sent {
1018 warn!(
1019 module_id,
1020 target_connection_id = target.endpoint.connection_id.get(),
1021 error = %err,
1022 "supervisor drain module GOODBYE was not delivered to peer; closing module connection"
1023 );
1024 forwarding.request_connection_close(
1025 target.endpoint.connection_id,
1026 CloseReason::new(
1027 "module_goodbye_delivery_failed",
1028 format!("failed to enqueue supervisor drain module GOODBYE for module '{module_id}': {err}"),
1029 ),
1030 );
1031 }
1032}
1033
1034#[derive(Clone, Copy)]
1035pub(super) struct ForwardingDrainContext<'a> {
1036 pub(super) spec: &'a ModuleSpec,
1037 pub(super) runtime: &'a SupervisorRuntimeConfig,
1038 pub(super) registry: &'a Registry,
1039 pub(super) scope: DrainScope,
1040}
1041
1042#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1044pub(super) enum DrainScope {
1045 Active,
1048 Endpoint(crate::ModuleEndpointId),
1053}
1054
1055#[derive(Debug, Clone, Copy, PartialEq, Eq)]
1063pub(super) enum StopNotice {
1064 SentOverConnection,
1067 AcceptingDrain { sent_over_connection: bool },
1069 DaemonShutdown,
1071 NoConnection,
1075 NotSent,
1079}
1080
1081impl StopNotice {
1082 fn sent_over_connection(self) -> bool {
1083 matches!(
1084 self,
1085 Self::SentOverConnection
1086 | Self::AcceptingDrain {
1087 sent_over_connection: true
1088 }
1089 )
1090 }
1091}
1092
1093pub(super) async fn begin_forwarding_drain(
1094 spec: &ModuleSpec,
1095 runtime: &SupervisorRuntimeConfig,
1096 registry: &Registry,
1097 snapshot: &SharedSnapshot,
1098 enabled: Option<bool>,
1099 reason: RouteCloseReason,
1100) -> Result<StopNotice, SuperviseError> {
1101 let Some(forwarding) = runtime.forwarding.as_ref() else {
1102 return Err(SuperviseError::ReloadUnavailable {
1103 module_id: spec.module_id.clone(),
1104 reason: "supervisor was not configured with a forwarding table".to_string(),
1105 });
1106 };
1107
1108 begin_forwarding_drain_with(
1109 forwarding,
1110 ForwardingDrainContext {
1111 spec,
1112 runtime,
1113 registry,
1114 scope: DrainScope::Active,
1115 },
1116 snapshot,
1117 enabled,
1118 reason,
1119 runtime.drain_timeout,
1120 )
1121 .await
1122}
1123
1124pub(super) async fn begin_forwarding_drain_if_configured(
1125 spec: &ModuleSpec,
1126 runtime: &SupervisorRuntimeConfig,
1127 registry: &Registry,
1128 snapshot: &SharedSnapshot,
1129 enabled: Option<bool>,
1130 reason: RouteCloseReason,
1131) -> Result<StopNotice, SuperviseError> {
1132 begin_forwarding_drain_with_timeout(
1133 spec,
1134 runtime,
1135 registry,
1136 snapshot,
1137 enabled,
1138 reason,
1139 runtime.drain_timeout,
1140 )
1141 .await
1142}
1143
1144pub(super) async fn begin_forwarding_drain_with_timeout(
1148 spec: &ModuleSpec,
1149 runtime: &SupervisorRuntimeConfig,
1150 registry: &Registry,
1151 snapshot: &SharedSnapshot,
1152 enabled: Option<bool>,
1153 reason: RouteCloseReason,
1154 drain_timeout: Duration,
1155) -> Result<StopNotice, SuperviseError> {
1156 let Some(forwarding) = runtime.forwarding.as_ref() else {
1157 return Ok(StopNotice::NotSent);
1158 };
1159
1160 begin_forwarding_drain_with(
1161 forwarding,
1162 ForwardingDrainContext {
1163 spec,
1164 runtime,
1165 registry,
1166 scope: DrainScope::Active,
1167 },
1168 snapshot,
1169 enabled,
1170 reason,
1171 drain_timeout,
1172 )
1173 .await
1174}
1175
1176pub(super) async fn begin_forwarding_drain_with(
1177 forwarding: &ForwardingTable,
1178 context: ForwardingDrainContext<'_>,
1179 snapshot: &SharedSnapshot,
1180 enabled: Option<bool>,
1181 reason: RouteCloseReason,
1182 drain_timeout: Duration,
1183) -> Result<StopNotice, SuperviseError> {
1184 let ForwardingDrainContext {
1185 spec,
1186 runtime,
1187 registry,
1188 scope,
1189 } = context;
1190 debug_assert_ne!(reason, RouteCloseReason::Crash);
1191 let terminal = matches!(reason, RouteCloseReason::Disable);
1192 let drain_started_at = Instant::now();
1193 let mut drain_deadline = drain_started_at + drain_timeout;
1194 let deadline_ms =
1195 unix_ms_now().saturating_add(u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX));
1196 let set_draining = || {
1197 update_snapshot(snapshot, Some(&spec.module_id), |state| {
1198 state.state = ModuleState::Draining;
1199 state.draining_to_replace =
1200 matches!(reason, RouteCloseReason::Restart | RouteCloseReason::Reload);
1201 if let Some(enabled) = enabled {
1202 state.enabled = enabled;
1203 }
1204 })
1205 };
1206
1207 let mut accepting_drain = None;
1208 if scope == DrainScope::Active
1209 && !drain_timeout.is_zero()
1210 && matches!(reason, RouteCloseReason::Restart | RouteCloseReason::Reload)
1211 {
1212 let registration = registry
1213 .get_module(&spec.module_id)
1214 .map_err(SuperviseError::Registry)?;
1215 if let Some(registration) = registration.filter(|entry| {
1216 entry.manifest.capabilities.as_ref().is_some_and(|caps| {
1217 caps.provides
1218 .iter()
1219 .any(|cap| cap == subc_protocol::session::ACCEPTING_DRAIN_CAPABILITY)
1220 })
1221 }) {
1222 accepting_drain = forwarding
1223 .begin_accepting_drain(&spec.module_id, registration.connection_id, reason)
1224 .map_err(SuperviseError::Forwarding)?;
1225 }
1226 }
1227 let accepting = accepting_drain.is_some();
1228 let busy_gauges = if accepting {
1229 Vec::new()
1230 } else {
1231 match scope {
1232 DrainScope::Active => declared_busy_gauges(registry, &spec.module_id)?,
1233 DrainScope::Endpoint(endpoint) => {
1234 declared_busy_gauges_for_connection(registry, endpoint.connection_id)?
1235 }
1236 }
1237 };
1238
1239 if let Some((target, phase_ended)) = &mut accepting_drain {
1240 set_draining()?;
1241 info!(module_id = %spec.module_id, budget_ms = drain_timeout.as_millis() as u64, "module accepting drain began");
1242 send_module_draining(&spec.module_id, reason, deadline_ms, target, false, true).await;
1243 let _ = tokio::time::timeout_at(drain_deadline, phase_ended.wait_for(|ended| *ended)).await;
1244 }
1245
1246 let gate_started = Instant::now();
1249 let drain_target = if let Some((target, _)) = accepting_drain {
1250 let finished = forwarding
1251 .finish_accepting_drain(target.endpoint)
1252 .map_err(SuperviseError::Forwarding)?;
1253 let (target, signalled) = match finished {
1254 crate::forwarding::AcceptingDrainFinish::Ready { target, signalled } => {
1255 (target, signalled)
1256 }
1257 crate::forwarding::AcceptingDrainFinish::Disconnected => {
1258 info!(module_id = %spec.module_id, elapsed_ms = drain_started_at.elapsed().as_millis() as u64, "module accepting drain lost its connection");
1259 return Ok(StopNotice::AcceptingDrain {
1260 sent_over_connection: false,
1261 });
1262 }
1263 crate::forwarding::AcceptingDrainFinish::DaemonShutdown => {
1264 info!(module_id = %spec.module_id, "daemon shutdown took over the module accepting drain");
1265 return Ok(StopNotice::DaemonShutdown);
1266 }
1267 };
1268 let cause = if signalled { "drain_ready" } else { "budget" };
1269 info!(module_id = %spec.module_id, cause, elapsed_ms = drain_started_at.elapsed().as_millis() as u64, "module accepting drain ready");
1270 drain_deadline = Instant::now() + ACCEPTING_DRAIN_IN_FLIGHT_WINDOW;
1271 Some(target)
1272 } else {
1273 match scope {
1274 DrainScope::Active => forwarding.begin_module_drain(&spec.module_id, reason),
1275 DrainScope::Endpoint(endpoint) => forwarding.begin_endpoint_drain(endpoint, reason),
1276 }
1277 .map_err(SuperviseError::Forwarding)?
1278 };
1279 if accepting {
1280 info!(module_id = %spec.module_id, ?reason, "module accepting drain closed route admission");
1281 } else {
1282 info!(
1285 module_id = %spec.module_id,
1286 ?reason,
1287 gate_ms = u64::try_from(gate_started.elapsed().as_millis()).unwrap_or(u64::MAX),
1288 connected = drain_target.is_some(),
1289 "module drain began; route admission closed"
1290 );
1291 }
1292 if scope == DrainScope::Active && !accepting {
1293 set_draining()?;
1294 }
1295
1296 let Some(target) = drain_target.as_ref() else {
1297 return Ok(StopNotice::NoConnection);
1301 };
1302 let flush_goodbye = runtime.supervisor_handle.as_ref().is_some_and(|handle| {
1303 handle
1304 .registration_spawn(target.endpoint.connection_id)
1305 .is_some()
1306 });
1307 {
1308 if !accepting {
1309 send_module_draining(&spec.module_id, reason, deadline_ms, target, false, false).await;
1310 }
1311 #[cfg(feature = "test-support")]
1312 forwarding.wait_before_route_closing_for_test().await;
1313 let routes = forwarding
1314 .endpoint_routes(target.endpoint)
1315 .map_err(SuperviseError::Forwarding)?;
1316 let routes_notified = routes.len();
1317 crate::control::send_route_control_pushes(
1318 forwarding,
1319 routes.clone(),
1320 ClientControlPush::RouteClosing {
1321 module_id: spec.module_id.clone(),
1322 channels: Vec::new(),
1323 reason,
1324 },
1325 );
1326 send_route_goodbyes(forwarding, target.abandoned_bindings.clone());
1327
1328 let mut gauge_trace = DrainGaugeTrace::new(&busy_gauges);
1334 let in_flight_wait_started = Instant::now();
1335 let wait_result = wait_for_forwarding_quiescence(
1336 forwarding,
1337 &spec.module_id,
1338 runtime,
1339 target.endpoint,
1340 drain_deadline,
1341 &busy_gauges,
1342 scope,
1343 &mut gauge_trace,
1344 )
1345 .await;
1346 let drained = drained_after_quiescence_wait(&wait_result);
1347 if accepting {
1348 info!(module_id = %spec.module_id, elapsed_ms = in_flight_wait_started.elapsed().as_millis() as u64, drained, "module accepting drain in-flight wait finished");
1349 }
1350 if let Err(err) = &wait_result {
1351 error!(
1352 module_id = %spec.module_id,
1353 ?reason,
1354 error = %err,
1355 "forwarding quiescence wait failed after route.closing; forcing route.closed(drained: false) so the client is not left waiting on an unfulfilled promise"
1356 );
1357 } else if !drained {
1358 let holdouts = forwarding
1360 .endpoint_drain_holdouts(target.endpoint)
1361 .unwrap_or_default();
1362 warn_drain_timed_out(
1363 &spec.module_id,
1364 if accepting {
1365 ACCEPTING_DRAIN_IN_FLIGHT_WINDOW
1366 } else {
1367 drain_timeout
1368 },
1369 reason,
1370 &holdouts,
1371 &gauge_trace,
1372 );
1373 }
1374 crate::control::send_route_control_pushes(
1375 forwarding,
1376 routes,
1377 ClientControlPush::RouteClosed {
1378 module_id: spec.module_id.clone(),
1379 channels: Vec::new(),
1380 reason,
1381 drained,
1382 abandoned: target.abandoned_bindings.len() as u32,
1383 excluded_subscriptions: target.excluded_subscriptions,
1384 terminal: Some(terminal),
1385 },
1386 );
1387 wait_result?;
1388
1389 let released_routes = match forwarding.release_module_endpoint_routes(target.endpoint) {
1395 Ok(routes) => routes,
1396 Err(err) => {
1397 warn!(
1398 module_id = %spec.module_id,
1399 ?reason,
1400 error = %err,
1401 "failed to release module endpoint routes after route.closed; module GOODBYE will still be sent"
1402 );
1403 send_module_goodbye(&spec.module_id, forwarding, target, flush_goodbye).await;
1404 return Err(SuperviseError::Forwarding(err));
1405 }
1406 };
1407 let route_goodbye_count = released_routes.len();
1408 send_route_goodbyes(forwarding, released_routes);
1409 send_module_goodbye(&spec.module_id, forwarding, target, flush_goodbye).await;
1410
1411 info!(
1417 module_id = %spec.module_id,
1418 ?reason,
1419 routes_notified,
1420 route_goodbyes = route_goodbye_count,
1421 abandoned_reservations = target.abandoned_bindings.len(),
1422 excluded_subscriptions = target.excluded_subscriptions,
1423 drained,
1424 "module drain complete; consumers notified via route.closing/route.closed pushes and per-route GOODBYE frames"
1425 );
1426 }
1427
1428 Ok(if accepting {
1429 StopNotice::AcceptingDrain {
1430 sent_over_connection: true,
1431 }
1432 } else {
1433 StopNotice::SentOverConnection
1434 })
1435}
1436
1437pub(super) fn control_flags() -> Flags {
1438 Flags::new(false, Priority::Passive, false)
1439}
1440
1441#[allow(clippy::too_many_arguments)]
1442pub(super) async fn drain_optional_child(
1443 module_id: &str,
1444 protocol: ModuleProtocol,
1445 stop_notice: StopNotice,
1446 registry: &Registry,
1447 forwarding: Option<&ForwardingTable>,
1448 snapshot: &SharedSnapshot,
1449 terminal_ring: &Arc<Mutex<TerminalRing>>,
1450 spawn_events: &SpawnEventFeed,
1451 child: &mut Option<SupervisedChild>,
1452 drain_timeout: Duration,
1453 final_state: ModuleState,
1454 enabled: Option<bool>,
1455 failure: &FailureContext,
1456) -> Result<(), SuperviseError> {
1457 if let Some(child) = child.take() {
1458 drain_child_to_state(
1459 module_id,
1460 protocol,
1461 stop_notice,
1462 registry,
1463 forwarding,
1464 snapshot,
1465 terminal_ring,
1466 spawn_events,
1467 child,
1468 drain_timeout,
1469 final_state,
1470 enabled,
1471 failure,
1472 )
1473 .await
1474 } else {
1475 update_snapshot(snapshot, Some(module_id), |state| {
1476 state.state = final_state;
1477 if final_state == ModuleState::Failed {
1478 state.failed_retry.failed_at = Some(Instant::now());
1479 }
1480 if let Some(enabled) = enabled {
1481 state.enabled = enabled;
1482 }
1483 clear_current_process_facts(state);
1484 })?;
1485 release_dead_registration(registry, forwarding, snapshot, module_id, failure).await
1486 }
1487}
1488
1489#[allow(clippy::too_many_arguments)]
1490pub(super) async fn drain_child_to_state(
1491 module_id: &str,
1492 _protocol: ModuleProtocol,
1493 stop_notice: StopNotice,
1494 registry: &Registry,
1495 forwarding: Option<&ForwardingTable>,
1496 snapshot: &SharedSnapshot,
1497 terminal_ring: &Arc<Mutex<TerminalRing>>,
1498 spawn_events: &SpawnEventFeed,
1499 mut child: SupervisedChild,
1500 drain_timeout: Duration,
1501 final_state: ModuleState,
1502 enabled: Option<bool>,
1503 failure: &FailureContext,
1504) -> Result<(), SuperviseError> {
1505 drain_child_to_state_inner(
1506 module_id,
1507 stop_notice,
1508 registry,
1509 forwarding,
1510 snapshot,
1511 terminal_ring,
1512 spawn_events,
1513 &mut child,
1514 drain_timeout,
1515 final_state,
1516 enabled,
1517 failure,
1518 None,
1519 &mut false,
1520 )
1521 .await
1522}
1523
1524#[cfg(any(target_os = "linux", target_os = "macos"))]
1525pub(super) const UPGRADE_KILL_GRACE: Duration = Duration::from_secs(2);
1526
1527#[cfg(any(target_os = "linux", target_os = "macos"))]
1529pub(super) async fn drain_for_upgrade(
1530 spec: &ModuleSpec,
1531 runtime: &SupervisorRuntimeConfig,
1532 registry: &Registry,
1533 snapshot: &SharedSnapshot,
1534 child: &mut Option<SupervisedChild>,
1535 stop_notice: StopNotice,
1536) -> Result<(), SuperviseError> {
1537 let failure = runtime.failure_context(true);
1538 let Some(active) = child.as_mut() else {
1539 return drain_optional_child(
1540 &spec.module_id,
1541 spec.protocol,
1542 stop_notice,
1543 registry,
1544 runtime.forwarding.as_deref(),
1545 snapshot,
1546 &runtime.terminal_ring,
1547 &runtime.spawn_events,
1548 child,
1549 runtime.drain_timeout,
1550 ModuleState::Stopped,
1551 None,
1552 &failure,
1553 )
1554 .await;
1555 };
1556 let mut exit_finalized = false;
1557 let result = drain_child_to_state_inner(
1558 &spec.module_id,
1559 stop_notice,
1560 registry,
1561 runtime.forwarding.as_deref(),
1562 snapshot,
1563 &runtime.terminal_ring,
1564 &runtime.spawn_events,
1565 active,
1566 runtime.drain_timeout,
1567 ModuleState::Stopped,
1568 None,
1569 &failure,
1570 Some(UPGRADE_KILL_GRACE),
1571 &mut exit_finalized,
1572 )
1573 .await;
1574 let stuck = matches!(&result, Err(SuperviseError::Wait { source, .. }) if source.kind() == io::ErrorKind::TimedOut);
1575 if exit_finalized || (!stuck && active.child.verified_adoptee().is_some()) {
1578 *child = None;
1579 }
1580 result
1581}
1582
1583#[allow(clippy::too_many_arguments)]
1584async fn drain_child_to_state_inner(
1585 module_id: &str,
1586 stop_notice: StopNotice,
1587 registry: &Registry,
1588 forwarding: Option<&ForwardingTable>,
1589 snapshot: &SharedSnapshot,
1590 terminal_ring: &Arc<Mutex<TerminalRing>>,
1591 spawn_events: &SpawnEventFeed,
1592 child: &mut SupervisedChild,
1593 drain_timeout: Duration,
1594 final_state: ModuleState,
1595 enabled: Option<bool>,
1596 failure: &FailureContext,
1597 kill_grace: Option<Duration>,
1598 exit_finalized: &mut bool,
1599) -> Result<(), SuperviseError> {
1600 let protocol = child.protocol;
1601 #[cfg(any(target_os = "linux", target_os = "macos"))]
1602 if kill_grace.is_none() && final_state != ModuleState::Restarting {
1603 if let Some(guard) = &mut child.roster_guard {
1604 guard.stop_adoption_without_replacement();
1605 }
1606 }
1607 child.retire_registration();
1608 update_snapshot(snapshot, Some(module_id), |state| {
1609 state.state = ModuleState::Draining;
1610 state.draining_to_replace = final_state == ModuleState::Restarting;
1611 if let Some(enabled) = enabled {
1612 state.enabled = enabled;
1613 }
1614 })?;
1615
1616 if !stop_notice.sent_over_connection() {
1627 if protocol == ModuleProtocol::Subc && stop_notice == StopNotice::NoConnection {
1628 info!(
1629 module_id,
1630 pid = child.pid,
1631 budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
1632 "module has no connection yet; requesting stop by signal"
1633 );
1634 }
1635 request_graceful_stop(module_id, child);
1636 }
1637
1638 let accepting = matches!(stop_notice, StopNotice::AcceptingDrain { .. });
1639 let drain_timeout = if accepting {
1640 DEFAULT_DRAIN_TIMEOUT
1641 } else {
1642 drain_timeout
1643 };
1644 let drain_timeout = child.group_drain_budget(drain_timeout, stop_notice);
1645 let exit_wait_started = Instant::now();
1646 let waited = timeout(drain_timeout, child.wait()).await;
1647 if accepting {
1648 info!(
1649 module_id,
1650 elapsed_ms = exit_wait_started.elapsed().as_millis() as u64,
1651 timed_out = waited.is_err(),
1652 "module accepting drain graceful-exit wait finished"
1653 );
1654 }
1655 let exit_report = match waited {
1656 Ok(Ok(status)) => classify_reaped_child_exit(snapshot, child, &status),
1657 Ok(Err(source)) => {
1658 fail_after_wait_error(
1659 module_id,
1660 snapshot,
1661 terminal_ring,
1662 spawn_events,
1663 format!("failed to wait during drain: {source}"),
1664 failure,
1665 );
1666 return Err(SuperviseError::Wait {
1667 module_id: module_id.to_string(),
1668 source,
1669 });
1670 }
1671 Err(_) => {
1672 warn!(
1685 module_id,
1686 pid = child.pid,
1687 budget_ms = u64::try_from(drain_timeout.as_millis()).unwrap_or(u64::MAX),
1688 reason = ?final_state,
1689 ?stop_notice,
1690 "drain budget expired before the module exited; killing it"
1691 );
1692 let kill =
1693 if final_state == ModuleState::Restarting && child.child.container().is_some() {
1694 child.kill_leader()
1695 } else {
1696 child.start_kill()
1697 };
1698 kill.map_err(|source| {
1699 fail_after_wait_error(
1700 module_id,
1701 snapshot,
1702 terminal_ring,
1703 spawn_events,
1704 format!("failed to kill during drain: {source}"),
1705 failure,
1706 );
1707 SuperviseError::Kill {
1708 module_id: module_id.to_string(),
1709 source,
1710 }
1711 })?;
1712 let waited = match kill_grace {
1713 Some(grace) => timeout(grace, child.wait()).await.unwrap_or_else(|_| {
1714 Err(io::Error::new(io::ErrorKind::TimedOut, "upgrade stop did not reap the child within the kill grace; child remains owned"))
1715 }),
1716 None => child.wait().await,
1717 };
1718 let status = waited.map_err(|source| {
1719 fail_after_wait_error(
1720 module_id,
1721 snapshot,
1722 terminal_ring,
1723 spawn_events,
1724 format!("failed to wait after drain kill: {source}"),
1725 failure,
1726 );
1727 SuperviseError::Wait {
1728 module_id: module_id.to_string(),
1729 source,
1730 }
1731 })?;
1732 classify_reaped_child_exit(snapshot, child, &status)
1733 }
1734 };
1735
1736 child.drain_stderr(module_id).await;
1737 let detail =
1738 child.exit_cleanup_detail(lock_snapshot(snapshot)?.drain_disposition_detail.take());
1739 publish_after_terminal_record(
1740 module_id,
1741 || {
1742 record_terminal_with_detail(
1743 module_id,
1744 terminal_ring,
1745 spawn_events,
1746 &exit_report,
1747 terminal_disposition(final_state),
1748 detail,
1749 )
1750 },
1751 || {
1752 update_snapshot(snapshot, Some(module_id), |state| {
1753 state.state = final_state;
1754 if final_state == ModuleState::Failed {
1755 state.failed_retry.failed_at = Some(Instant::now());
1756 }
1757 if let Some(enabled) = enabled {
1758 state.enabled = enabled;
1759 }
1760 clear_current_process_facts(state);
1761 state.last_exit = Some(exit_report.clone());
1762 if exit_report.kind == ExitKind::DeliberateSeverance {
1763 state.lifetime_restarts += 1;
1764 }
1765 })
1766 },
1767 )?;
1768 let released =
1769 release_dead_registration(registry, forwarding, snapshot, module_id, failure).await;
1770 child
1771 .finish_exit(
1772 released.is_ok()
1773 && final_state == ModuleState::Restarting
1774 && child.spawn_failure.is_none(),
1775 )
1776 .await
1777 .map_err(|source| SuperviseError::Wait {
1778 module_id: module_id.to_owned(),
1779 source,
1780 })?;
1781 *exit_finalized = true;
1782 released
1783}
1784
1785#[cfg(unix)]
1805pub(super) fn request_graceful_stop(module_id: &str, child: &SupervisedChild) {
1806 if let Some(group) = &child.child.plain_group {
1807 if let Err(error) = group.signal(rustix::process::Signal::TERM) {
1808 debug!(module_id, %error, "group TERM was not delivered; the drain wait and kill still apply");
1809 }
1810 return;
1811 }
1812 #[cfg(any(target_os = "linux", target_os = "macos"))]
1813 if let Some(verified) = child.child.verified_adoptee() {
1814 if let Err(error) = verified.signal(rustix::process::Signal::TERM) {
1815 debug!(module_id, %error, "verified adopted child TERM was not delivered");
1816 }
1817 return;
1818 }
1819 let Some(pid) = child
1820 .id()
1821 .and_then(|pid| i32::try_from(pid).ok())
1822 .filter(|pid| *pid > 1)
1823 .and_then(rustix::process::Pid::from_raw)
1824 else {
1825 debug!(
1826 module_id,
1827 "no pid to signal for teardown; falling through to the drain wait"
1828 );
1829 return;
1830 };
1831 match rustix::process::kill_process(pid, rustix::process::Signal::TERM) {
1832 Ok(()) => debug!(
1833 module_id,
1834 "sent SIGTERM to a module nothing else asked to stop"
1835 ),
1836 Err(err) => debug!(
1837 module_id,
1838 error = %err,
1839 "SIGTERM to module failed; the drain wait and kill still apply"
1840 ),
1841 }
1842}
1843
1844#[cfg(not(unix))]
1852pub(super) fn request_graceful_stop(module_id: &str, _child: &SupervisedChild) {
1853 debug!(
1854 module_id,
1855 "no graceful stop signal exists on this platform; teardown of a module nothing asked to stop waits, then kills"
1856 );
1857}
1858
1859pub(super) fn terminal_disposition(final_state: ModuleState) -> TerminalDisposition {
1860 match final_state {
1861 ModuleState::Stopped => TerminalDisposition::Stopped,
1862 ModuleState::Disabled => TerminalDisposition::Disabled,
1863 ModuleState::Restarting => TerminalDisposition::Restarting,
1864 ModuleState::Failed => TerminalDisposition::Failed,
1865 ModuleState::Starting
1866 | ModuleState::Running
1867 | ModuleState::Unresponsive
1868 | ModuleState::Draining => {
1869 unreachable!("terminal exits only finish in terminal or restarting states")
1870 }
1871 }
1872}