Skip to main content

bynk/
sweep.rs

1//! Stopping what `bynk dev`'s wranglers leave behind (#1742).
2//!
3//! `bynk dev` stops each `wrangler dev` by signalling the child it spawned.
4//! That child is rarely the server. Resolved via npx, it is `npx`, and the
5//! server is four processes further down (`sh -c wrangler` → wrangler's `node`
6//! launcher → its CLI → two `workerd serve`s); a signal to `npx` reaches none of
7//! them. Resolved on PATH, the child is the launcher, which does pass SIGTERM
8//! on. But when a context's wrangler *crashes*, its `workerd`s are re-parented
9//! to init before `bynk dev` ever acts, and nothing walks from a child to them
10//! any more. Either way the survivors keep their ports, and the next `bynk dev`
11//! fails at boot with `bind(): Address already in use`.
12//!
13//! Two properties of those survivors outlast the re-parenting:
14//!
15//! - **Process group.** Nothing in the chain leaves the group it was spawned
16//!   into, which is `bynk dev`'s own: they share it so a Ctrl-C reaches them
17//!   all.
18//! - **Working directory.** `bynk dev` starts each wrangler inside its worker
19//!   dir under the managed build dir, and every descendant inherits it.
20//!
21//! [`sweep`] stops the processes that have both, so it reaches orphans without
22//! guessing by name. The working directory is what keeps it from touching an
23//! unrelated process: when `bynk dev` is not a group leader (a script without
24//! job control runs it), its group can hold the script's other jobs. Neither
25//! `bynk dev` itself nor its ancestors are ever selected.
26//!
27//! Unix only. Windows has neither process groups nor a working directory to
28//! read. There, `bynk dev` puts each wrangler in a job object instead, which
29//! holds the whole tree, orphans included, and stops it as one (#1762).
30
31use bynk_driver::emsg;
32use std::path::{Path, PathBuf};
33use std::time::Duration;
34
35/// Stop every process in this process group whose working directory is under
36/// `root`: SIGTERM first, then SIGKILL for what is still running after
37/// `grace`. Returns once none is left, or after SIGKILL has been given a moment
38/// to land.
39///
40/// Best effort, but never silently. If there is something to stop, it says
41/// so, because the wait can be long and would otherwise read as a hang. If
42/// anything is still running at the end, or `kill(1)` cannot be run, it names
43/// the survivors: they hold ports, and the next `bynk dev` would otherwise fail
44/// with a bind error and nothing pointing back here. If `ps` cannot be run
45/// there is nothing to select from, and this does nothing, as `bynk dev` did
46/// before #1742.
47pub fn sweep(root: &Path, grace: Duration) {
48    #[cfg(unix)]
49    {
50        let deadline = std::time::Instant::now() + grace;
51        let mut termed = false;
52        loop {
53            let left = stragglers(root);
54            if left.is_empty() {
55                return;
56            }
57            if !termed {
58                eprintln!(
59                    "bynk dev: stopping {} leftover process(es) under {}…",
60                    left.len(),
61                    root.display()
62                );
63                // Without `kill(1)` nothing can be signalled (std signals only
64                // its own children), so waiting out the grace would be wasted.
65                if !signal("TERM", &left) {
66                    report_survivors("could not run `kill`", &left);
67                    return;
68                }
69                termed = true;
70            } else if std::time::Instant::now() >= deadline {
71                signal("KILL", &left);
72                // SIGKILL is delivered asynchronously. Wait briefly for it to
73                // land, so a caller checking straight afterwards sees it.
74                let soon = std::time::Instant::now() + Duration::from_secs(1);
75                let mut left = stragglers(root);
76                while !left.is_empty() && std::time::Instant::now() < soon {
77                    std::thread::sleep(Duration::from_millis(20));
78                    left = stragglers(root);
79                }
80                if !left.is_empty() {
81                    report_survivors("they survived SIGKILL", &left);
82                }
83                return;
84            }
85            std::thread::sleep(Duration::from_millis(100));
86        }
87    }
88    // Windows: each wrangler's job object has already stopped its tree (#1762).
89    #[cfg(not(unix))]
90    let _ = (root, grace);
91}
92
93/// Name the processes [`sweep`] could not stop, and why.
94#[cfg(unix)]
95fn report_survivors(why: &str, pids: &[u32]) {
96    let pids = pids
97        .iter()
98        .map(u32::to_string)
99        .collect::<Vec<_>>()
100        .join(" ");
101    emsg!(
102        "bynk dev: warning: could not stop leftover processes ({why}): {pids}. They may hold \
103         ports the next `bynk dev` needs; stop them by hand."
104    );
105}
106
107/// The processes [`sweep`] would stop now.
108#[cfg(unix)]
109pub fn stragglers(root: &Path) -> Vec<u32> {
110    let Some(table) = process_table() else {
111        return Vec::new();
112    };
113    // Compare canonical paths: a process's cwd is reported resolved, and the
114    // build dir may sit behind a symlink (macOS's `/tmp` is `/private/tmp`).
115    let root = root.canonicalize().unwrap_or_else(|_| root.to_path_buf());
116    let candidates = in_own_group(&table, std::process::id());
117    let cwds = cwds(&candidates);
118    candidates
119        .into_iter()
120        .filter(|pid| {
121            cwds.iter()
122                .any(|(p, cwd)| p == pid && cwd.starts_with(&root))
123        })
124        .collect()
125}
126
127/// One row of `ps`: a process, its parent and its process group.
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129#[cfg_attr(not(unix), allow(dead_code))]
130struct Row {
131    pid: u32,
132    ppid: u32,
133    pgid: u32,
134}
135
136/// Every process on the system, from `ps` (POSIX `-A -o`, so Linux and macOS
137/// alike). `None` when `ps` cannot be run.
138#[cfg(unix)]
139fn process_table() -> Option<Vec<Row>> {
140    let out = std::process::Command::new("ps")
141        .args(["-A", "-o", "pid=,ppid=,pgid="])
142        .stderr(std::process::Stdio::null())
143        .output()
144        .ok()?;
145    out.status
146        .success()
147        .then(|| parse_ps(&String::from_utf8_lossy(&out.stdout)))
148}
149
150#[cfg_attr(not(unix), allow(dead_code))]
151fn parse_ps(text: &str) -> Vec<Row> {
152    text.lines()
153        .filter_map(|line| {
154            let mut fields = line.split_whitespace().map(str::parse::<u32>);
155            let row = Row {
156                pid: fields.next()?.ok()?,
157                ppid: fields.next()?.ok()?,
158                pgid: fields.next()?.ok()?,
159            };
160            Some(row)
161        })
162        .collect()
163}
164
165/// The other members of `me`'s process group, leaving out `me` and its
166/// ancestors. An ancestor shares the group when nothing between it and `me`
167/// started a new one, and stopping the shell or script that ran `bynk dev`
168/// would be the worst possible outcome.
169#[cfg_attr(not(unix), allow(dead_code))]
170fn in_own_group(table: &[Row], me: u32) -> Vec<u32> {
171    let Some(own) = table.iter().find(|r| r.pid == me) else {
172        return Vec::new();
173    };
174    let mut ancestors = vec![me];
175    let mut at = own.ppid;
176    // Bounded, so a malformed table with a cycle cannot loop forever.
177    for _ in 0..table.len() {
178        if at == 0 || ancestors.contains(&at) {
179            break;
180        }
181        ancestors.push(at);
182        match table.iter().find(|r| r.pid == at) {
183            Some(r) => at = r.ppid,
184            None => break,
185        }
186    }
187    table
188        .iter()
189        .filter(|r| r.pgid == own.pgid && !ancestors.contains(&r.pid))
190        .map(|r| r.pid)
191        .collect()
192}
193
194/// The working directory of each of `pids` that still exists and can be read.
195#[cfg(target_os = "linux")]
196fn cwds(pids: &[u32]) -> Vec<(u32, PathBuf)> {
197    pids.iter()
198        .filter_map(|&pid| Some((pid, std::fs::read_link(format!("/proc/{pid}/cwd")).ok()?)))
199        .collect()
200}
201
202/// The working directory of each of `pids`, from one `lsof` call: there is no
203/// `/proc` here (macOS, the BSDs). Empty when `lsof` cannot be run.
204#[cfg(all(unix, not(target_os = "linux")))]
205fn cwds(pids: &[u32]) -> Vec<(u32, PathBuf)> {
206    if pids.is_empty() {
207        return Vec::new();
208    }
209    let list = pids
210        .iter()
211        .map(u32::to_string)
212        .collect::<Vec<_>>()
213        .join(",");
214    // `-a` ANDs the selections: only these pids, and only their cwd. `lsof`
215    // exits 1 when some pid has gone, so its status says nothing; parse what
216    // it printed.
217    match std::process::Command::new("lsof")
218        .args(["-a", "-p", &list, "-d", "cwd", "-F", "pn"])
219        .stderr(std::process::Stdio::null())
220        .output()
221    {
222        Ok(out) => parse_lsof(&String::from_utf8_lossy(&out.stdout)),
223        Err(_) => Vec::new(),
224    }
225}
226
227/// Parse `lsof -F pn` output: a `p<pid>` line opens each process, and each
228/// `n<path>` line after it names one of its files (here, only its cwd). Other
229/// field lines (`lsof` adds `f<fd>`) are skipped.
230#[cfg_attr(not(all(unix, not(target_os = "linux"))), allow(dead_code))]
231fn parse_lsof(text: &str) -> Vec<(u32, PathBuf)> {
232    let mut pid = None;
233    let mut found = Vec::new();
234    for line in text.lines() {
235        if let Some(p) = line.strip_prefix('p') {
236            pid = p.parse::<u32>().ok();
237        } else if let (Some(path), Some(pid)) = (line.strip_prefix('n'), pid) {
238            found.push((pid, PathBuf::from(path)));
239        }
240    }
241    found
242}
243
244/// Send `signal` to `pids` with `kill(1)`; std can send only SIGKILL, and only
245/// to its own children.
246///
247/// `false` when `kill` could not be run at all. Its exit status is no test: a
248/// pid that has exited in the meantime makes it fail as well.
249#[cfg(unix)]
250fn signal(signal: &str, pids: &[u32]) -> bool {
251    std::process::Command::new("kill")
252        .arg(format!("-{signal}"))
253        .args(pids.iter().map(u32::to_string))
254        .stderr(std::process::Stdio::null())
255        .status()
256        .is_ok()
257}
258
259#[cfg(test)]
260mod tests {
261    use super::*;
262
263    fn row(pid: u32, ppid: u32, pgid: u32) -> Row {
264        Row { pid, ppid, pgid }
265    }
266
267    #[test]
268    fn ps_rows_parse_and_junk_lines_are_skipped() {
269        let text = "    1     0     1\n  200     1   200\nnot a row\n  201   200   200\n";
270        assert_eq!(
271            parse_ps(text),
272            vec![row(1, 0, 1), row(200, 1, 200), row(201, 200, 200)]
273        );
274    }
275
276    /// `bynk dev` (300) run by a script (200) that has no job control, so all
277    /// three share the script's group with a sibling job (301). The orphan
278    /// (400, re-parented to init) is still in the group.
279    #[test]
280    fn the_group_leaves_out_self_and_ancestors_but_keeps_orphans() {
281        let table = [
282            row(1, 0, 1),
283            row(100, 1, 100),   // the login shell, its own group
284            row(200, 100, 200), // the script
285            row(300, 200, 200), // bynk dev
286            row(301, 200, 200), // another job of the script
287            row(310, 300, 200), // a wrangler bynk dev spawned
288            row(400, 1, 200),   // an orphaned workerd
289            row(500, 1, 500),   // unrelated
290        ];
291        let mut got = in_own_group(&table, 300);
292        got.sort_unstable();
293        // 301 is in the group too: the cwd filter, not the group, is what
294        // leaves it alone.
295        assert_eq!(got, vec![301, 310, 400]);
296    }
297
298    #[test]
299    fn an_unlisted_self_selects_nothing() {
300        assert!(in_own_group(&[row(1, 0, 1)], 999).is_empty());
301    }
302
303    #[test]
304    fn lsof_output_parses_pid_and_cwd() {
305        let text = "p310\nfcwd\nn/private/tmp/p/.bynk/dev/workers/a\np400\nfcwd\nn/Users/me\n";
306        assert_eq!(
307            parse_lsof(text),
308            vec![
309                (310, PathBuf::from("/private/tmp/p/.bynk/dev/workers/a")),
310                (400, PathBuf::from("/Users/me")),
311            ]
312        );
313    }
314
315    /// The #1742 regression, with `sh` in place of wrangler. Killing the `sh`
316    /// outright orphans its `sleep`s, the way a crashed wrangler orphans its
317    /// `workerd`s. Nothing reaches them from the child any more, and the sweep
318    /// must still stop them.
319    #[cfg(unix)]
320    fn orphans_are_swept(tag: &str, script: &str, grace: Duration) {
321        use std::process::{Command, Stdio};
322        let root = std::env::temp_dir().join(format!("bynk-sweep-{tag}-{}", std::process::id()));
323        let _ = std::fs::remove_dir_all(&root);
324        let worker = root.join("workers/ctx");
325        std::fs::create_dir_all(&worker).unwrap();
326        let mut sh = Command::new("sh")
327            .args(["-c", script])
328            .current_dir(&worker)
329            .stdin(Stdio::null())
330            .stdout(Stdio::null())
331            .stderr(Stdio::null())
332            .spawn()
333            .expect("sh spawns");
334        let started = std::time::Instant::now();
335        while stragglers(&root).len() < 3 {
336            assert!(
337                started.elapsed() < Duration::from_secs(10),
338                "the script never started its background processes"
339            );
340            std::thread::sleep(Duration::from_millis(20));
341        }
342        // A bystander: in the same process group (the test's), but working
343        // elsewhere, like a script's other job. The sweep must not touch it.
344        let mut bystander = Command::new("sleep")
345            .arg("300")
346            .current_dir(std::env::temp_dir())
347            .stdin(Stdio::null())
348            .stdout(Stdio::null())
349            .stderr(Stdio::null())
350            .spawn()
351            .expect("sleep spawns");
352        let _ = sh.kill();
353        let _ = sh.wait();
354        let orphans = stragglers(&root);
355        assert_eq!(
356            orphans.len(),
357            2,
358            "the sleeps outlive their parent: {orphans:?}"
359        );
360        assert!(
361            !orphans.contains(&bystander.id()),
362            "a process outside the root was selected"
363        );
364        sweep(&root, grace);
365        let left = stragglers(&root);
366        let spared = bystander.try_wait().is_ok_and(|s| s.is_none());
367        let _ = bystander.kill();
368        let _ = bystander.wait();
369        assert!(spared, "the sweep stopped a process outside the root");
370        let _ = std::fs::remove_dir_all(&root);
371        assert!(left.is_empty(), "processes survived the sweep: {left:?}");
372    }
373
374    #[cfg(unix)]
375    #[test]
376    fn a_crashed_childs_orphans_are_swept() {
377        orphans_are_swept(
378            "term",
379            "sleep 300 & sleep 300 & wait",
380            Duration::from_secs(10),
381        );
382    }
383
384    /// Orphans that ignore SIGTERM are killed once the grace period is over.
385    #[cfg(unix)]
386    #[test]
387    fn orphans_that_ignore_sigterm_are_killed_after_the_grace_period() {
388        orphans_are_swept(
389            "kill",
390            "trap '' TERM; sleep 300 & sleep 300 & wait",
391            Duration::from_millis(300),
392        );
393    }
394}