|
| 1 | +// SPDX-FileCopyrightText: Copyright (c) 2026 NVIDIA CORPORATION & AFFILIATES. All rights reserved. |
| 2 | +// SPDX-License-Identifier: Apache-2.0 |
| 3 | + |
| 4 | +//! Keeping QEMU from outliving tmachine. |
| 5 | +//! |
| 6 | +//! Dropping a VM handle stops QEMU, but a destructor never runs when the |
| 7 | +//! process is killed by a signal. Two mechanisms cover that: |
| 8 | +//! |
| 9 | +//! - On Linux, QEMU asks the kernel to kill it when its parent dies |
| 10 | +//! (`PR_SET_PDEATHSIG`), whatever the reason, including `SIGKILL`. |
| 11 | +//! - [`cleanup_on_signals`] kills every tracked QEMU on `SIGTERM`, `SIGINT` |
| 12 | +//! and `SIGHUP` and exits, which also covers hosts without that kernel |
| 13 | +//! feature. |
| 14 | +//! |
| 15 | +//! A leaked QEMU holds the SSH forward port, so the next run on that host |
| 16 | +//! fails until someone kills it by hand. |
| 17 | +
|
| 18 | +use std::sync::Mutex; |
| 19 | + |
| 20 | +use tokio::process::Command; |
| 21 | +use tokio::signal::unix::{SignalKind, signal}; |
| 22 | + |
| 23 | +static LIVE: Mutex<Vec<u32>> = Mutex::new(Vec::new()); |
| 24 | + |
| 25 | +pub(super) fn track(pid: u32) { |
| 26 | + if let Ok(mut live) = LIVE.lock() { |
| 27 | + live.push(pid); |
| 28 | + } |
| 29 | +} |
| 30 | + |
| 31 | +pub(super) fn forget(pid: u32) { |
| 32 | + if let Ok(mut live) = LIVE.lock() { |
| 33 | + live.retain(|candidate| *candidate != pid); |
| 34 | + } |
| 35 | +} |
| 36 | + |
| 37 | +/// Kill every QEMU this process started and has not yet reaped. |
| 38 | +fn kill_all() { |
| 39 | + let pids = LIVE.lock().map(|live| live.clone()).unwrap_or_default(); |
| 40 | + for pid in pids { |
| 41 | + if let Ok(pid) = libc::pid_t::try_from(pid) { |
| 42 | + // SAFETY: `kill` has no memory-safety preconditions. A recycled |
| 43 | + // PID is not a concern: entries are removed when the VM handle |
| 44 | + // that owns the child is dropped, and the child is reaped by it. |
| 45 | + unsafe { libc::kill(pid, libc::SIGKILL) }; |
| 46 | + } |
| 47 | + } |
| 48 | +} |
| 49 | + |
| 50 | +/// Make a child die when this process dies, on platforms that support it. |
| 51 | +#[cfg(target_os = "linux")] |
| 52 | +pub(super) fn die_with_parent(command: &mut Command) { |
| 53 | + // SAFETY: the closure runs between fork and exec and calls only |
| 54 | + // `prctl`, which is async-signal-safe. |
| 55 | + unsafe { |
| 56 | + command.pre_exec(|| { |
| 57 | + // PR_SET_PDEATHSIG fires when the thread that spawned the child |
| 58 | + // exits, so the runtime must keep its spawning thread alive: |
| 59 | + // tmachine's binaries use a current-thread runtime. |
| 60 | + if libc::prctl(libc::PR_SET_PDEATHSIG, libc::SIGKILL) == -1 { |
| 61 | + return Err(std::io::Error::last_os_error()); |
| 62 | + } |
| 63 | + Ok(()) |
| 64 | + }); |
| 65 | + } |
| 66 | +} |
| 67 | + |
| 68 | +#[cfg(not(target_os = "linux"))] |
| 69 | +pub(super) fn die_with_parent(_command: &mut Command) {} |
| 70 | + |
| 71 | +/// Kill every VM started through tmachine when the process receives |
| 72 | +/// `SIGTERM`, `SIGINT` or `SIGHUP`, then exit with the conventional status. |
| 73 | +/// |
| 74 | +/// Call once from a binary's `main`, inside the Tokio runtime. |
| 75 | +pub fn cleanup_on_signals() { |
| 76 | + for (kind, number) in [ |
| 77 | + (SignalKind::terminate(), libc::SIGTERM), |
| 78 | + (SignalKind::interrupt(), libc::SIGINT), |
| 79 | + (SignalKind::hangup(), libc::SIGHUP), |
| 80 | + ] { |
| 81 | + let Ok(mut stream) = signal(kind) else { |
| 82 | + eprintln!("tmachine: could not install the signal {number} handler; VMs may leak"); |
| 83 | + continue; |
| 84 | + }; |
| 85 | + tokio::spawn(async move { |
| 86 | + stream.recv().await; |
| 87 | + kill_all(); |
| 88 | + std::process::exit(128 + number); |
| 89 | + }); |
| 90 | + } |
| 91 | +} |
| 92 | + |
| 93 | +#[cfg(test)] |
| 94 | +mod tests { |
| 95 | + use super::*; |
| 96 | + |
| 97 | + #[test] |
| 98 | + fn tracks_and_forgets_pids() { |
| 99 | + // Out of range for a `pid_t`, so a concurrent `kill_all` skips them. |
| 100 | + let (kept, dropped) = (u32::MAX - 1, u32::MAX - 2); |
| 101 | + track(kept); |
| 102 | + track(dropped); |
| 103 | + forget(dropped); |
| 104 | + let live = LIVE.lock().unwrap().clone(); |
| 105 | + assert!(live.contains(&kept)); |
| 106 | + assert!(!live.contains(&dropped)); |
| 107 | + forget(kept); |
| 108 | + } |
| 109 | + |
| 110 | + #[tokio::test(flavor = "current_thread")] |
| 111 | + async fn kill_all_stops_tracked_children_and_handlers_install() { |
| 112 | + // Installing handlers must not change behavior until a signal arrives. |
| 113 | + cleanup_on_signals(); |
| 114 | + let child = Command::new("sleep") |
| 115 | + .arg("60") |
| 116 | + .kill_on_drop(true) |
| 117 | + .spawn() |
| 118 | + .unwrap(); |
| 119 | + let pid = child.id().unwrap(); |
| 120 | + track(pid); |
| 121 | + kill_all(); |
| 122 | + let mut child = child; |
| 123 | + let status = child.wait().await.unwrap(); |
| 124 | + assert!(!status.success()); |
| 125 | + forget(pid); |
| 126 | + } |
| 127 | +} |
0 commit comments