1use crate::logging::log;
9use crate::{data_dir, mem_supervisor, srv_spawner, startup_events};
10use std::time::Instant;
11
12#[derive(Debug, PartialEq, Eq)]
14pub(super) enum SrvExit {
15 Shutdown,
17 WaitForMemory,
19 Respawn,
21 GiveUp,
23 GiveUpLowMemory,
25}
26
27fn is_group_shutdown(signal: Option<i32>) -> bool {
29 matches!(signal, Some(sig) if sig == libc::SIGINT || sig == libc::SIGTERM || sig == libc::SIGHUP)
30}
31
32pub(super) fn classify_srv_exit(
37 code: Option<i32>,
38 signal: Option<i32>,
39 commit_free_mb: u64,
40 now: Instant,
41 srv_restarts: &mut Vec<Instant>,
42 srv_oom_restarts: &mut Vec<Instant>,
43) -> SrvExit {
44 if code == Some(0) || is_group_shutdown(signal) {
45 return SrvExit::Shutdown;
46 }
47 let low_memory = matches!(
48 mem_supervisor::classify_host_exit(code.unwrap_or(1), commit_free_mb),
49 mem_supervisor::HostExitClass::SystemOom
50 );
51 if low_memory {
52 if mem_supervisor::budget_exhausted(
53 srv_oom_restarts,
54 now,
55 mem_supervisor::OOM_RESTART_WINDOW,
56 mem_supervisor::OOM_RESTART_BUDGET,
57 ) {
58 return SrvExit::GiveUpLowMemory;
59 }
60 return SrvExit::WaitForMemory;
61 }
62 if mem_supervisor::budget_exhausted(srv_restarts, now, super::SRV_RESTART_WINDOW, super::SRV_RESTART_BUDGET) {
63 return SrvExit::GiveUp;
64 }
65 SrvExit::Respawn
66}
67
68pub(super) enum SrvAction {
70 Stop(i32),
72 GiveUp(i32),
75 Restart { why: crate::incidents::SrvStop, wait_for_memory: bool },
77}
78
79pub(super) fn srv_exit_action(
82 status: std::io::Result<std::process::ExitStatus>,
83 srv_restarts: &mut Vec<Instant>,
84 srv_oom_restarts: &mut Vec<Instant>,
85) -> SrvAction {
86 use std::os::unix::process::ExitStatusExt;
87 let status = match status {
88 Ok(s) => s,
89 Err(e) => {
90 log(&format!("FATAL: srv wait failed: {e}"));
91 return SrvAction::Stop(1);
92 }
93 };
94 let (code, signal) = (status.code(), status.signal());
95 let text = super::unix::srv_exit_text(&status);
96 let commit_free = mem_supervisor::commit_free_mb();
97 match classify_srv_exit(code, signal, commit_free, Instant::now(), srv_restarts, srv_oom_restarts) {
98 SrvExit::Shutdown => {
99 log("srv exited as part of shutdown — shutting down");
100 SrvAction::Stop(0)
101 }
102 SrvExit::GiveUpLowMemory => {
103 log(&format!(
104 "srv exited {text} while the computer was out of memory ({commit_free} MB commit-free); \
105 the memory restart budget is spent ({} in {}s) — giving up",
106 mem_supervisor::OOM_RESTART_BUDGET,
107 mem_supervisor::OOM_RESTART_WINDOW.as_secs()
108 ));
109 crate::incidents::record(&crate::incidents::memory_give_up());
110 crate::show_fatal_dialog(mem_supervisor::OOM_GIVEUP_TITLE, mem_supervisor::OOM_GIVEUP_BODY);
111 SrvAction::Stop(code.unwrap_or(1))
112 }
113 SrvExit::GiveUp => {
114 log(&format!(
115 "srv exited {text}; the srv restart budget is spent ({} in {}s) — terminating launcher",
116 super::SRV_RESTART_BUDGET,
117 super::SRV_RESTART_WINDOW.as_secs()
118 ));
119 crate::incidents::record(&crate::incidents::crash_give_up(
120 crate::incidents::GaveUpOn::Service,
121 code.unwrap_or(1),
122 super::SRV_RESTART_BUDGET,
123 super::SRV_RESTART_WINDOW.as_secs(),
124 ));
125 SrvAction::GiveUp(1)
126 }
127 SrvExit::WaitForMemory => {
128 log(&format!(
129 "srv exited {text} while the computer was out of memory ({commit_free} MB commit-free) — \
130 waiting for memory to recover before starting it again"
131 ));
132 SrvAction::Restart { why: crate::incidents::SrvStop::LowMemory, wait_for_memory: true }
133 }
134 SrvExit::Respawn => {
135 log(&format!(
136 "srv exited UNEXPECTEDLY {text} — starting it again (restart {}/{})",
137 srv_restarts.len(),
138 super::SRV_RESTART_BUDGET
139 ));
140 let why = match signal {
141 Some(sig) => crate::incidents::SrvStop::Signal(sig, signal_name(sig)),
142 None => crate::incidents::SrvStop::Exited(code.unwrap_or(1)),
143 };
144 SrvAction::Restart { why, wait_for_memory: false }
145 }
146 }
147}
148
149pub(super) fn signal_name(sig: i32) -> &'static str {
151 match sig {
152 libc::SIGHUP => "SIGHUP",
153 libc::SIGINT => "SIGINT",
154 libc::SIGQUIT => "SIGQUIT",
155 libc::SIGILL => "SIGILL",
156 libc::SIGTRAP => "SIGTRAP",
157 libc::SIGABRT => "SIGABRT",
158 libc::SIGBUS => "SIGBUS",
159 libc::SIGFPE => "SIGFPE",
160 libc::SIGKILL => "SIGKILL",
161 libc::SIGSEGV => "SIGSEGV",
162 libc::SIGPIPE => "SIGPIPE",
163 libc::SIGTERM => "SIGTERM",
164 _ => "",
165 }
166}
167
168pub(super) struct Srv {
170 pub result: srv_spawner::SrvSpawnResult,
171 pub child: tokio::process::Child,
172 pub stdin: Option<tokio::process::ChildStdin>,
174 pub pid: Option<u32>,
176}
177
178impl Srv {
179 pub(super) fn new(result: srv_spawner::SrvSpawnResult, mut child: tokio::process::Child) -> Self {
180 let stdin = child.stdin.take();
181 let pid = child.id();
182 Srv { result, child, stdin, pid }
183 }
184}
185
186pub(super) async fn respawn_srv(
190 launcher_exe_dir: &std::path::Path,
191 paths: &data_dir::DataPaths,
192 sink: &startup_events::StartupEventSink,
193 why: crate::incidents::SrvStop,
194 srv: &mut Srv,
195) -> Result<(), srv_spawner::SrvSpawnError> {
196 super::unix::end_agents_left_by_srv(&paths.data_dir, srv.pid);
197 if let Some(pid) = srv.pid {
200 if agentmux_common::process::orphaned_group_alive(pid) {
201 let _ = agentmux_common::process::signal_process_group(pid, libc::SIGKILL);
202 }
203 }
204 let incident = crate::incidents::srv_restarted(why);
207 let (result, child) = srv_spawner::spawn_srv(launcher_exe_dir, paths, "", sink, Some(&incident.id)).await?;
208 *srv = Srv::new(result, child);
209 crate::notify::update_endpoint(&srv.result.ws_endpoint, &srv.result.auth_key, &srv.result.host_reg_secret);
210 crate::incidents::record(&incident);
211 log(&format!(
212 "srv respawned (pid {}) — new endpoints ws={} web={}",
213 srv.result.pid, srv.result.ws_endpoint, srv.result.web_endpoint
214 ));
215 Ok(())
216}
217
218#[cfg(test)]
219mod tests {
220 use super::*;
221 use std::time::Duration;
222
223 const PLENTY: u64 = 100_000;
224
225 fn classify(code: Option<i32>, signal: Option<i32>, commit: u64, now: Instant, b: &mut Vec<Instant>) -> SrvExit {
226 classify_srv_exit(code, signal, commit, now, b, &mut Vec::new())
227 }
228
229 #[test]
230 fn a_clean_exit_and_the_group_shutdown_signals_stop_the_app() {
231 let (now, mut b) = (Instant::now(), Vec::new());
232 assert_eq!(classify(Some(0), None, PLENTY, now, &mut b), SrvExit::Shutdown);
233 for sig in [libc::SIGINT, libc::SIGTERM, libc::SIGHUP] {
234 assert_eq!(classify(None, Some(sig), PLENTY, now, &mut b), SrvExit::Shutdown, "signal {sig}");
235 }
236 assert!(b.is_empty(), "a shutdown is not charged to the budget");
237 }
238
239 #[test]
240 fn a_crash_signal_or_a_failure_code_starts_srv_again() {
241 let (now, mut b) = (Instant::now(), Vec::new());
242 for (code, sig) in [(None, Some(libc::SIGKILL)), (None, Some(libc::SIGSEGV)), (Some(1), None), (Some(101), None)] {
243 assert_eq!(classify(code, sig, PLENTY, now, &mut b), SrvExit::Respawn, "{code:?} {sig:?}");
244 b.clear();
245 }
246 }
247
248 #[test]
249 fn the_fourth_crash_within_the_window_gives_up() {
250 let (t0, mut b) = (Instant::now(), Vec::new());
251 for i in 0..super::super::SRV_RESTART_BUDGET {
252 let now = t0 + Duration::from_secs(i as u64 * 10);
253 assert_eq!(classify(None, Some(libc::SIGKILL), PLENTY, now, &mut b), SrvExit::Respawn);
254 }
255 let now = t0 + Duration::from_secs(40);
256 assert_eq!(classify(None, Some(libc::SIGKILL), PLENTY, now, &mut b), SrvExit::GiveUp);
257 }
258
259 #[test]
260 fn a_spent_budget_is_a_give_up_the_supervisor_can_tell_from_a_shutdown() {
261 use std::os::unix::process::ExitStatusExt;
262 let killed = || Ok(std::process::ExitStatus::from_raw(libc::SIGKILL));
263 let mut b: Vec<Instant> = (0..super::super::SRV_RESTART_BUDGET).map(|_| Instant::now()).collect();
264 assert!(matches!(srv_exit_action(killed(), &mut b, &mut Vec::new()), SrvAction::GiveUp(1)));
265 let clean = Ok(std::process::ExitStatus::from_raw(0));
267 assert!(matches!(srv_exit_action(clean, &mut Vec::new(), &mut Vec::new()), SrvAction::Stop(0)));
268 }
269
270 #[test]
271 fn the_budget_refills_once_the_window_has_passed() {
272 let (t0, mut b) = (Instant::now(), Vec::new());
273 for _ in 0..super::super::SRV_RESTART_BUDGET {
274 classify(None, Some(libc::SIGKILL), PLENTY, t0, &mut b);
275 }
276 let later = t0 + super::super::SRV_RESTART_WINDOW + Duration::from_secs(1);
277 assert_eq!(classify(None, Some(libc::SIGKILL), PLENTY, later, &mut b), SrvExit::Respawn);
278 }
279
280 #[test]
281 fn low_memory_waits_and_has_a_budget_of_its_own() {
282 let (t0, mut crashes, mut ooms) = (Instant::now(), Vec::new(), Vec::new());
283 for _ in 0..mem_supervisor::OOM_RESTART_BUDGET {
284 let a = classify_srv_exit(None, Some(libc::SIGKILL), 0, t0, &mut crashes, &mut ooms);
285 assert_eq!(a, SrvExit::WaitForMemory);
286 }
287 assert_eq!(classify_srv_exit(None, Some(libc::SIGKILL), 0, t0, &mut crashes, &mut ooms), SrvExit::GiveUpLowMemory);
288 assert!(crashes.is_empty(), "memory exits are not charged to the crash budget");
289 }
290
291 #[test]
292 fn signals_have_names() {
293 assert_eq!(signal_name(libc::SIGKILL), "SIGKILL");
294 assert_eq!(signal_name(libc::SIGUSR2), "");
295 }
296}