1use super::*;
2
3#[cfg(test)]
4#[derive(Debug, Default)]
5pub(super) struct ReloadExitRecordGate {
6 pub(super) reached: tokio::sync::Notify,
7 pub(super) resume: tokio::sync::Notify,
8}
9
10impl SupervisedModule {
11 pub async fn restart(&self, drain_timeout_ms: Option<u64>) -> Result<(), SuperviseError> {
12 self.restart_requested(drain_timeout_ms, None).await
13 }
14
15 pub(crate) async fn restart_requested(
16 &self,
17 drain_timeout_ms: Option<u64>,
18 requester: Option<Principal>,
19 ) -> Result<(), SuperviseError> {
20 let queued_at = Instant::now();
21 let received_at_generation = lock_snapshot(&self.inner.snapshot)?.spawn_generation;
22 let (reply_tx, reply_rx) = oneshot::channel();
23 self.inner
24 .commands
25 .send(SupervisorCommand::Restart {
26 requester,
27 drain_timeout_ms,
28 received_at_generation,
29 queued_at,
30 reply: reply_tx,
31 })
32 .await
33 .map_err(|_| SuperviseError::CommandClosed {
34 module_id: self.inner.module_id.clone(),
35 })?;
36 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
37 module_id: self.inner.module_id.clone(),
38 })?
39 }
40}
41
42impl SupervisedModule {
43 pub async fn reload(&self) -> Result<(), SuperviseError> {
44 self.reload_requested(None).await
45 }
46
47 pub(crate) async fn reload_requested(
48 &self,
49 requester: Option<Principal>,
50 ) -> Result<(), SuperviseError> {
51 let (reply_tx, reply_rx) = oneshot::channel();
52 self.inner
53 .commands
54 .send(SupervisorCommand::Reload {
55 requester,
56 reply: reply_tx,
57 })
58 .await
59 .map_err(|_| SuperviseError::CommandClosed {
60 module_id: self.inner.module_id.clone(),
61 })?;
62 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
63 module_id: self.inner.module_id.clone(),
64 })?
65 }
66
67 pub async fn set_enabled(&self, enabled: bool) -> Result<bool, SuperviseError> {
68 self.set_enabled_requested(enabled, None).await
69 }
70
71 pub(crate) async fn set_enabled_requested(
72 &self,
73 enabled: bool,
74 requester: Option<Principal>,
75 ) -> Result<bool, SuperviseError> {
76 self.set_enabled_with_budget_policy(enabled, requester, true)
77 .await
78 }
79
80 pub(crate) async fn release_config_hold(&self) -> Result<bool, SuperviseError> {
81 self.set_enabled_with_budget_policy(true, None, false).await
82 }
83}
84
85impl SupervisedModule {
86 async fn set_enabled_with_budget_policy(
87 &self,
88 enabled: bool,
89 requester: Option<Principal>,
90 reset_budget: bool,
91 ) -> Result<bool, SuperviseError> {
92 let (reply_tx, reply_rx) = oneshot::channel();
93 self.inner
94 .commands
95 .send(SupervisorCommand::SetEnabled {
96 requester,
97 enabled,
98 reset_budget,
99 reply: reply_tx,
100 })
101 .await
102 .map_err(|_| SuperviseError::CommandClosed {
103 module_id: self.inner.module_id.clone(),
104 })?;
105 reply_rx.await.map_err(|_| SuperviseError::CommandClosed {
106 module_id: self.inner.module_id.clone(),
107 })?
108 }
109}
110
111pub(super) async fn restart_child(
112 spec: &ModuleSpec,
113 runtime: &SupervisorRuntimeConfig,
114 registry: &Registry,
115 process_liveness: &SupervisorProcessLiveness,
116 snapshot: &SharedSnapshot,
117 child: &mut Option<SupervisedChild>,
118 drain_timeout: Duration,
119) -> Result<(), SuperviseError> {
120 restart_child_with_budget_policy(
121 spec,
122 runtime,
123 registry,
124 process_liveness,
125 snapshot,
126 child,
127 drain_timeout,
128 true,
129 )
130 .await
131}
132
133#[allow(clippy::too_many_arguments)]
134pub(super) async fn restart_child_with_budget_policy(
135 spec: &ModuleSpec,
136 runtime: &SupervisorRuntimeConfig,
137 registry: &Registry,
138 process_liveness: &SupervisorProcessLiveness,
139 snapshot: &SharedSnapshot,
140 child: &mut Option<SupervisedChild>,
141 drain_timeout: Duration,
142 reset_budget: bool,
143) -> Result<(), SuperviseError> {
144 if !lock_snapshot(snapshot)?.enabled {
146 return Err(SuperviseError::Disabled {
147 module_id: spec.module_id.clone(),
148 });
149 }
150 let stop_notice = begin_forwarding_drain_with_timeout(
151 spec,
152 runtime,
153 registry,
154 snapshot,
155 None,
156 RouteCloseReason::Restart,
157 drain_timeout,
158 )
159 .await?;
160 if stop_notice == StopNotice::DaemonShutdown {
161 return Ok(());
162 }
163
164 if child.is_some() {
165 drain_optional_child(
166 &spec.module_id,
167 spec.protocol,
168 stop_notice,
169 registry,
170 runtime.forwarding.as_deref(),
171 snapshot,
172 &runtime.terminal_ring,
173 &runtime.spawn_events,
174 child,
175 drain_timeout,
176 ModuleState::Restarting,
177 Some(true),
178 &FailureContext::operator(),
179 )
180 .await?;
181 } else {
182 update_snapshot(snapshot, Some(&spec.module_id), |state| {
183 state.enabled = true;
184 state.state = ModuleState::Restarting;
185 clear_current_process_facts(state);
186 })?;
187 release_dead_registration(
188 registry,
189 runtime.forwarding.as_deref(),
190 snapshot,
191 &spec.module_id,
192 &runtime.failure_context(false),
193 )
194 .await?;
195 }
196
197 if reset_budget {
198 reset_restart_count(snapshot, &spec.module_id)?;
199 }
200 process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
201 schedule_respawn(
202 runtime,
203 snapshot,
204 &spec.module_id,
205 runtime.restart_policy.backoff,
206 RespawnKind::Spawn,
207 false,
208 )
209}
210
211pub(super) async fn reload_child(
212 spec: &ModuleSpec,
213 runtime: &SupervisorRuntimeConfig,
214 registry: &Registry,
215 process_liveness: &SupervisorProcessLiveness,
216 snapshot: &SharedSnapshot,
217 child: &mut Option<SupervisedChild>,
218) -> Result<(), SuperviseError> {
219 if !lock_snapshot(snapshot)?.enabled {
221 return Err(SuperviseError::Disabled {
222 module_id: spec.module_id.clone(),
223 });
224 }
225 let stop_notice = begin_forwarding_drain(
226 spec,
227 runtime,
228 registry,
229 snapshot,
230 Some(true),
231 RouteCloseReason::Reload,
232 )
233 .await?;
234 if stop_notice == StopNotice::DaemonShutdown {
235 return Err(SuperviseError::CommandClosed {
236 module_id: spec.module_id.clone(),
237 });
238 }
239
240 if child.is_some() {
241 drain_optional_child(
242 &spec.module_id,
243 spec.protocol,
244 stop_notice,
245 registry,
246 runtime.forwarding.as_deref(),
247 snapshot,
248 &runtime.terminal_ring,
249 &runtime.spawn_events,
250 child,
251 runtime.drain_timeout,
252 ModuleState::Restarting,
253 Some(true),
254 &FailureContext::operator(),
255 )
256 .await?;
257 } else {
258 update_snapshot(snapshot, Some(&spec.module_id), |state| {
259 state.enabled = true;
260 state.state = ModuleState::Restarting;
261 clear_current_process_facts(state);
262 })?;
263 release_dead_registration(
264 registry,
265 runtime.forwarding.as_deref(),
266 snapshot,
267 &spec.module_id,
268 &runtime.failure_context(false),
269 )
270 .await?;
271 }
272
273 reset_restart_count(snapshot, &spec.module_id)?;
274 process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
275 schedule_respawn(
276 runtime,
277 snapshot,
278 &spec.module_id,
279 runtime.restart_policy.backoff,
280 RespawnKind::Reload,
281 false,
282 )
283}
284
285pub(super) async fn finish_reload_child(
286 spec: &ModuleSpec,
287 runtime: &SupervisorRuntimeConfig,
288 registry: &Registry,
289 process_liveness: &SupervisorProcessLiveness,
290 snapshot: &SharedSnapshot,
291 child: &mut Option<SupervisedChild>,
292) -> Result<(), SuperviseError> {
293 process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
294 let next_child = match spawn_and_mark_running_async(spec, runtime, snapshot).await {
295 Ok(next_child) => next_child,
296 Err(error @ SuperviseError::ConfigDeliveryDeferred { .. }) => {
297 defer_config_spawn(
298 spec,
299 runtime,
300 snapshot,
301 RespawnKind::Reload,
302 &runtime.failure_context(runtime.recovery_is_daemon),
303 )?;
304 return Err(error);
305 }
306 Err(error @ SuperviseError::ConfigHeld { .. }) => {
307 let failure = runtime.failure_context(runtime.recovery_is_daemon);
308 if try_park_config_attempt(spec, runtime, snapshot, &failure, None)? {
309 return Err(error);
310 }
311 defer_config_spawn(spec, runtime, snapshot, RespawnKind::Reload, &failure)?;
312 return Err(SuperviseError::ConfigDeliveryDeferred {
313 module_id: spec.module_id.clone(),
314 });
315 }
316 Err(err) => {
317 return handle_reload_spawn_failure(
318 spec,
319 runtime,
320 process_liveness,
321 snapshot,
322 child,
323 format!("new child failed to spawn: {err}"),
324 )
325 .await;
326 }
327 };
328 *child = Some(next_child);
329
330 let wait_outcome = {
331 let active_child = child.as_mut().expect("new reload child was just stored");
332 wait_for_registration_after_reload(
333 registry,
334 &spec.module_id,
335 snapshot,
336 active_child,
337 REGISTRY_RELEASE_TIMEOUT,
338 )
339 .await?
340 };
341
342 match wait_outcome {
343 RegistrationWaitOutcome::Registered => {
344 child
345 .as_mut()
346 .expect("registered reload child")
347 .registration_deadline = None;
348 debug!(module_id = %spec.module_id, "supervised module reloaded and registered");
349 Ok(())
350 }
351 RegistrationWaitOutcome::Exited(exit_report) => {
352 if let Some(active_child) = child.as_mut() {
353 active_child.drain_stderr(&spec.module_id).await;
354 }
355 let mut exited_child = child.take().expect("exited reload child is still stored");
358 #[cfg(test)]
359 if let Some(gate) = &runtime.test_reload_exit_record_gate {
360 gate.reached.notify_one();
361 gate.resume.notified().await;
362 }
363 let result = handle_reload_child_registration_failure(
364 spec,
365 runtime,
366 registry,
367 process_liveness,
368 snapshot,
369 child,
370 ReloadRegistrationFailure {
371 exit_report: registration_failure_exit_report(exit_report),
372 cleanup_detail: exited_child.exit_cleanup_detail(None),
373 reason: exited_child
374 .spawn_failure
375 .clone()
376 .unwrap_or_else(|| "new child exited before registering".to_string()),
377 },
378 )
379 .await;
380 exited_child
381 .finish_exit(false)
382 .await
383 .map_err(|source| SuperviseError::Wait {
384 module_id: spec.module_id.clone(),
385 source,
386 })?;
387 result
388 }
389 RegistrationWaitOutcome::TimedOut => {
390 let mut timed_out_child = child
391 .take()
392 .expect("timed-out reload child is still running");
393 timed_out_child
394 .start_kill()
395 .map_err(|source| SuperviseError::Kill {
396 module_id: spec.module_id.clone(),
397 source,
398 })?;
399 let status = timed_out_child
400 .wait()
401 .await
402 .map_err(|source| SuperviseError::Wait {
403 module_id: spec.module_id.clone(),
404 source,
405 })?;
406 timed_out_child.drain_stderr(&spec.module_id).await;
407 let result = handle_reload_child_registration_failure(
408 spec,
409 runtime,
410 registry,
411 process_liveness,
412 snapshot,
413 child,
414 ReloadRegistrationFailure {
415 exit_report: registration_failure_exit_report(classify_reaped_child_exit(
416 snapshot,
417 &timed_out_child,
418 &status,
419 )),
420 cleanup_detail: timed_out_child.exit_cleanup_detail(None),
421 reason: format!(
422 "new child did not register within {:?}",
423 REGISTRY_RELEASE_TIMEOUT
424 ),
425 },
426 )
427 .await;
428 timed_out_child
429 .finish_exit(false)
430 .await
431 .map_err(|source| SuperviseError::Wait {
432 module_id: spec.module_id.clone(),
433 source,
434 })?;
435 result
436 }
437 }
438}
439
440#[allow(clippy::too_many_arguments)]
441pub(super) async fn set_child_enabled(
442 spec: &ModuleSpec,
443 runtime: &SupervisorRuntimeConfig,
444 registry: &Registry,
445 process_liveness: &SupervisorProcessLiveness,
446 snapshot: &SharedSnapshot,
447 child: &mut Option<SupervisedChild>,
448 enabled: bool,
449 failure: &FailureContext,
450) -> Result<bool, SuperviseError> {
451 set_child_enabled_with_budget_policy(
452 spec,
453 runtime,
454 registry,
455 process_liveness,
456 snapshot,
457 child,
458 enabled,
459 failure,
460 true,
461 )
462 .await
463}
464
465#[allow(clippy::too_many_arguments)]
466pub(super) async fn set_child_enabled_with_budget_policy(
467 spec: &ModuleSpec,
468 runtime: &SupervisorRuntimeConfig,
469 registry: &Registry,
470 process_liveness: &SupervisorProcessLiveness,
471 snapshot: &SharedSnapshot,
472 child: &mut Option<SupervisedChild>,
473 enabled: bool,
474 failure: &FailureContext,
475 reset_budget: bool,
476) -> Result<bool, SuperviseError> {
477 let (current_enabled, current_state, respawn_pending) = {
478 let state = lock_snapshot(snapshot)?;
479 (state.enabled, state.state, state.respawn_pending)
480 };
481 let revive_terminal = enabled
489 && current_enabled
490 && child.is_none()
491 && (matches!(current_state, ModuleState::Failed | ModuleState::Stopped)
492 || (current_state == ModuleState::Restarting && !respawn_pending));
493 if current_enabled == enabled && !revive_terminal {
494 return Ok(false);
495 }
496
497 if enabled {
498 update_snapshot(snapshot, Some(&spec.module_id), |state| {
499 state.enabled = true;
500 state.state = ModuleState::Starting;
501 clear_current_process_facts(state);
502 })?;
503 #[cfg(test)]
504 if runtime.test_seed_stale_facts_before_enable_spawn {
505 update_snapshot(snapshot, Some(&spec.module_id), |state| {
506 state.process_alive = true;
507 state.pid = Some(41);
508 state.spawned_at_ms = Some(42);
509 state.spawned_from = Some(PathBuf::from("/spawned/module"));
510 state.spawned_file_identity = Some(SpawnedFileIdentity {
511 device: 43,
512 inode: 44,
513 #[cfg(windows)]
514 windows_image: None,
515 });
516 })?;
517 }
518 release_dead_registration(
519 registry,
520 runtime.forwarding.as_deref(),
521 snapshot,
522 &spec.module_id,
523 failure,
524 )
525 .await?;
526 if reset_budget {
527 reset_restart_count(snapshot, &spec.module_id)?;
528 }
529 process_liveness.track(spec.module_id.clone(), Arc::clone(snapshot));
530 let next_child = match spawn_and_mark_running_async(spec, runtime, snapshot).await {
531 Ok(next_child) => next_child,
532 Err(SuperviseError::ConfigDeliveryDeferred { .. }) => {
533 defer_config_spawn(spec, runtime, snapshot, RespawnKind::Spawn, failure)?;
534 return Ok(true);
535 }
536 Err(error @ SuperviseError::ConfigHeld { .. }) => {
537 if let Err(parking_error) = hold_config_spawn(spec, runtime, snapshot, failure) {
538 process_liveness.untrack_if_current(&spec.module_id, snapshot);
539 return Err(parking_error);
540 }
541 return Err(error);
542 }
543 Err(err) => {
544 fail_snapshot(snapshot, Some(&spec.module_id), None, failure);
545 process_liveness.untrack_if_current(&spec.module_id, snapshot);
546 return Err(err);
547 }
548 };
549 *child = Some(next_child);
550 debug!(module_id = %spec.module_id, "supervised module enabled");
551 Ok(true)
552 } else {
553 update_snapshot(snapshot, Some(&spec.module_id), |state| {
554 state.config_hold_parked = false;
555 state.config_hold_daemon_initiated = false;
556 state.config_hold_approval = None;
557 })?;
558 let stop_notice = begin_forwarding_drain_if_configured(
559 spec,
560 runtime,
561 registry,
562 snapshot,
563 Some(false),
564 RouteCloseReason::Disable,
565 )
566 .await?;
567 drain_optional_child(
568 &spec.module_id,
569 spec.protocol,
570 stop_notice,
571 registry,
572 runtime.forwarding.as_deref(),
573 snapshot,
574 &runtime.terminal_ring,
575 &runtime.spawn_events,
576 child,
577 runtime.drain_timeout,
578 ModuleState::Disabled,
579 Some(false),
580 failure,
581 )
582 .await?;
583 debug!(module_id = %spec.module_id, "supervised module disabled");
584 Ok(true)
585 }
586}