agentmux_launcher/
stale_srv.rs1use std::os::unix::io::AsRawFd;
21use std::path::Path;
22use std::time::{Duration, Instant};
23
24const SRV_LOCK_FILE: &str = "srv.lock";
27
28const TERM_GRACE: Duration = Duration::from_secs(10);
31
32#[derive(Debug, PartialEq, Eq)]
34pub enum Reclaim {
35 Free,
37 HeadlessRunning { pid: i32 },
40 Left,
43}
44
45pub fn headless_running_words(pid: i32) -> (&'static str, String) {
48 (
49 "AgentMux is already running",
50 format!(
51 "AgentMux is already running without a window on this computer (process {pid}).\n\nOpen it in your browser with `agentmux open` in a terminal.\n\nTo use the app window instead, stop it with `agentmux stop`, then open AgentMux again."
52 ),
53 )
54}
55
56pub fn reclaim_or_say_headless_running(data_dir: &Path) {
59 if let Reclaim::HeadlessRunning { pid } = reclaim_stale_srv_lock(data_dir) {
60 let (title, body) = headless_running_words(pid);
61 crate::log(&format!("a headless srv (pid {pid}) holds the data dir; told the person and exiting"));
62 tell_the_person(title, &body);
63 std::process::exit(0);
64 }
65}
66
67fn tell_the_person(title: &str, body: &str) {
71 eprintln!("{body}");
72 #[cfg(target_os = "macos")]
73 {
74 let _ = std::process::Command::new("/usr/bin/osascript")
75 .args([
76 "-e",
77 "on run argv",
78 "-e",
79 "display dialog (item 2 of argv) with title (item 1 of argv) buttons {\"OK\"} default button \"OK\" with icon caution",
80 "-e",
81 "end run",
82 ])
83 .arg(title)
84 .arg(body)
85 .stdin(std::process::Stdio::null())
86 .output();
87 }
88 #[cfg(not(target_os = "macos"))]
89 let _ = title;
90}
91
92fn started_headless(args: Option<&str>, with_env: Option<&str>) -> bool {
95 let env = with_env.is_some_and(|c| c.split_whitespace().any(|w| w == "AGENTMUX_HEADLESS=1" || w == "AGENTMUX_HEADLESS=true"));
96 let arg = args.is_some_and(|c| c.split_whitespace().any(|a| a == "--headless"));
97 env || arg
98}
99
100pub fn reclaim_stale_srv_lock(data_dir: &Path) -> Reclaim {
105 let lock_path = data_dir.join(SRV_LOCK_FILE);
106 if lock_is_free(&lock_path) {
107 return Reclaim::Free;
108 }
109 let recorded = std::fs::read_to_string(&lock_path)
112 .ok()
113 .and_then(|s| s.trim().parse::<i32>().ok())
114 .filter(|pid| *pid > 1);
115 let Some(pid) = recorded.or_else(|| lock_holder_via_lsof(&lock_path)) else {
116 crate::log(&format!(
117 "stale-srv: {} is held but its holder can't be identified; leaving it",
118 lock_path.display()
119 ));
120 return Reclaim::Left;
121 };
122 let Some(comm) = ps_field(pid, "comm=", false) else {
127 crate::log(&format!("stale-srv: lock names pid {pid}, which isn't running; leaving it"));
128 return Reclaim::Left;
129 };
130 let exe_name = Path::new(&comm)
131 .file_name()
132 .map(|n| n.to_string_lossy().into_owned())
133 .unwrap_or_default();
134 if !exe_name.starts_with("agentmux-srv") {
135 crate::log(&format!("stale-srv: lock names pid {pid} ({exe_name}), which isn't agentmux-srv; leaving it"));
136 return Reclaim::Left;
137 }
138 if started_headless(ps_field(pid, "command=", false).as_deref(), ps_field(pid, "command=", true).as_deref()) {
139 crate::log(&format!("stale-srv: pid {pid} is a headless srv using this data dir; leaving it"));
140 return Reclaim::HeadlessRunning { pid };
141 }
142
143 let ppid = ps_field(pid, "ppid=", false).and_then(|p| p.trim().parse::<i32>().ok());
149 if let Some(ppid) = ppid.filter(|p| *p > 1) {
150 let parent = ps_field(ppid, "comm=", false)
151 .and_then(|c| Path::new(&c).file_name().map(|n| n.to_string_lossy().into_owned()))
152 .unwrap_or_default();
153 if parent.to_ascii_lowercase().contains("agentmux") {
154 crate::log(&format!(
155 "stale-srv: srv pid {pid} still has its launcher (pid {ppid}, {parent}); another instance owns this data dir, leaving it"
156 ));
157 return Reclaim::Left;
158 }
159 }
160
161 crate::log(&format!(
162 "stale-srv: srv pid {pid} still holds {} with no launcher; stopping it so this launch can start",
163 lock_path.display()
164 ));
165 unsafe { libc::kill(pid, libc::SIGTERM) };
166 if wait_for_free(&lock_path, TERM_GRACE) {
167 crate::log(&format!("stale-srv: pid {pid} exited after SIGTERM; lock is free"));
168 kill_orphaned_agents(data_dir, pid);
169 return Reclaim::Free;
170 }
171 let target = if unsafe { libc::getpgid(pid) } == pid { -pid } else { pid };
174 unsafe { libc::kill(target, libc::SIGKILL) };
175 if wait_for_free(&lock_path, Duration::from_secs(3)) {
176 crate::log(&format!("stale-srv: pid {pid} killed; lock is free"));
177 kill_orphaned_agents(data_dir, pid);
178 Reclaim::Free
179 } else {
180 crate::log(&format!("stale-srv: lock still held after killing pid {pid}"));
181 Reclaim::Left
182 }
183}
184
185fn kill_orphaned_agents(data_dir: &Path, pid: i32) {
188 let Ok(pid) = u32::try_from(pid) else { return };
189 if let Some(done) = agentmux_common::agent_roots::kill_orphans(data_dir, pid) {
190 crate::log(&format!(
191 "stale-srv: ended its agent CLIs: {} agent cgroup(s), {} CLI process group(s); {} had already exited",
192 done.cgroups, done.groups, done.gone
193 ));
194 }
195}
196
197fn lock_is_free(lock_path: &Path) -> bool {
200 let Ok(file) = std::fs::OpenOptions::new().read(true).open(lock_path) else {
201 return true;
202 };
203 let fd = file.as_raw_fd();
204 if unsafe { libc::flock(fd, libc::LOCK_EX | libc::LOCK_NB) } == 0 {
205 unsafe { libc::flock(fd, libc::LOCK_UN) };
206 true
207 } else {
208 false
209 }
210}
211
212fn wait_for_free(lock_path: &Path, within: Duration) -> bool {
213 let deadline = Instant::now() + within;
214 while Instant::now() < deadline {
215 if lock_is_free(lock_path) {
216 return true;
217 }
218 std::thread::sleep(Duration::from_millis(100));
219 }
220 lock_is_free(lock_path)
221}
222
223fn lock_holder_via_lsof(lock_path: &Path) -> Option<i32> {
227 let pids: Vec<i32> = processes_with_file_open(lock_path)
228 .into_iter()
229 .filter(|pid| *pid > 1 && *pid != std::process::id() as i32)
230 .collect();
231 pids.iter()
232 .copied()
233 .find(|pid| {
234 ps_field(*pid, "comm=", false)
235 .and_then(|c| Path::new(&c).file_name().map(|n| n.to_string_lossy().starts_with("agentmux-srv")))
236 .unwrap_or(false)
237 })
238 .or_else(|| pids.first().copied())
239}
240
241#[cfg(not(target_os = "linux"))]
243fn processes_with_file_open(path: &Path) -> Vec<i32> {
244 let Ok(out) = std::process::Command::new("/usr/sbin/lsof")
245 .arg("-t")
246 .arg("--")
247 .arg(path)
248 .output()
249 else {
250 return Vec::new();
251 };
252 String::from_utf8_lossy(&out.stdout)
253 .lines()
254 .filter_map(|l| l.trim().parse::<i32>().ok())
255 .collect()
256}
257
258#[cfg(target_os = "linux")]
263fn processes_with_file_open(path: &Path) -> Vec<i32> {
264 let Ok(target) = std::fs::canonicalize(path) else {
265 return Vec::new();
266 };
267 let Ok(procs) = std::fs::read_dir("/proc") else {
268 return Vec::new();
269 };
270 procs
271 .flatten()
272 .filter_map(|entry| entry.file_name().to_str()?.parse::<i32>().ok())
273 .filter(|pid| {
274 std::fs::read_dir(format!("/proc/{pid}/fd"))
275 .map(|fds| fds.flatten().any(|fd| std::fs::read_link(fd.path()).is_ok_and(|l| l == target)))
276 .unwrap_or(false)
277 })
278 .collect()
279}
280
281fn ps_field(pid: i32, field: &str, with_env: bool) -> Option<String> {
285 let flags = if with_env { "eww" } else { "ww" };
286 let out = std::process::Command::new("/bin/ps")
287 .args([flags, "-o", field, "-p", &pid.to_string()])
288 .output()
289 .ok()?;
290 let s = String::from_utf8_lossy(&out.stdout).trim().to_string();
291 (out.status.success() && !s.is_empty()).then_some(s)
292}
293
294#[cfg(test)]
295mod tests {
296 use super::*;
297
298 #[test]
299 fn a_missing_or_unheld_lock_is_free() {
300 let dir = tempfile::tempdir().unwrap();
301 let lock = dir.path().join(SRV_LOCK_FILE);
302 assert!(lock_is_free(&lock), "missing file");
303 std::fs::write(&lock, "12345").unwrap();
304 assert!(lock_is_free(&lock), "file nobody holds");
305 }
306
307 #[test]
308 fn a_held_lock_is_not_free_and_is_left_alone_without_a_live_srv() {
309 let dir = tempfile::tempdir().unwrap();
310 let lock = dir.path().join(SRV_LOCK_FILE);
311 let holder = std::fs::OpenOptions::new()
312 .create(true)
313 .write(true)
314 .open(&lock)
315 .unwrap();
316 assert_eq!(unsafe { libc::flock(holder.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) }, 0);
317 assert!(!lock_is_free(&lock));
318
319 std::fs::write(&lock, std::process::id().to_string()).unwrap();
322 assert_eq!(reclaim_stale_srv_lock(dir.path()), Reclaim::Left);
323 assert!(!lock_is_free(&lock));
324 }
325
326 #[test]
327 fn a_free_lock_is_free() {
328 let dir = tempfile::tempdir().unwrap();
329 assert_eq!(reclaim_stale_srv_lock(dir.path()), Reclaim::Free);
330 }
331
332 #[test]
333 fn an_srv_started_headless_is_told_from_either_its_arguments_or_its_environment() {
334 assert!(started_headless(Some("/x/agentmux-srv --headless --web-port 7380"), None));
335 assert!(started_headless(None, Some("/x/agentmux-srv HOME=/h AGENTMUX_HEADLESS=1 PATH=/bin")));
336 assert!(started_headless(None, Some("/x/agentmux-srv AGENTMUX_HEADLESS=true")));
337 assert!(!started_headless(Some("/x/agentmux-srv --wavedata /d"), Some("/x/agentmux-srv HOME=/h AGENTMUX_HEADLESS=0")));
338 assert!(!started_headless(None, None), "nothing read is not headless");
339 }
340
341 #[test]
342 fn the_words_for_a_running_headless_srv_say_what_it_is_and_what_to_do() {
343 let (title, body) = headless_running_words(4242);
344 assert_eq!(title, "AgentMux is already running");
345 assert!(body.contains("without a window") && body.contains("4242"), "{body}");
346 assert!(body.contains("`agentmux open`") && body.contains("`agentmux stop`"), "{body}");
347 assert!(!body.to_lowercase().contains("interrupted"));
348 }
349}