|
| 1 | +//! Capture who sent SIGTERM/SIGINT (`si_pid`) without fighting tokio's waiter. |
| 2 | +//! |
| 3 | +//! A `SA_SIGINFO` handler records the sender, then writes one byte to a socket |
| 4 | +//! pair so the async setup task can log and exit. We do not use `tokio::signal` |
| 5 | +//! on Unix — the last `sigaction` wins, and we need `si_pid`. |
| 6 | +
|
| 7 | +use std::os::fd::AsRawFd; |
| 8 | +use std::os::unix::net::UnixStream; |
| 9 | +use std::sync::atomic::{AtomicI32, Ordering}; |
| 10 | + |
| 11 | +use tracing::info; |
| 12 | + |
| 13 | +static SENDER_PID: AtomicI32 = AtomicI32::new(0); |
| 14 | +static SIGNAL_NO: AtomicI32 = AtomicI32::new(0); |
| 15 | +static SIGNAL_CODE: AtomicI32 = AtomicI32::new(0); |
| 16 | +static PIPE_WRITE_FD: AtomicI32 = AtomicI32::new(-1); |
| 17 | + |
| 18 | +/// Install the recorder and wait until SIGTERM or SIGINT arrives. |
| 19 | +/// |
| 20 | +/// Returns after the first termination signal. Caller should then exit. |
| 21 | +pub async fn wait_for_term() { |
| 22 | + let read_end = match install() { |
| 23 | + Ok(fd) => fd, |
| 24 | + Err(e) => { |
| 25 | + tracing::warn!("[Signal] Failed to install SA_SIGINFO handler: {e}"); |
| 26 | + return; |
| 27 | + } |
| 28 | + }; |
| 29 | + |
| 30 | + let mut reader = match tokio::net::UnixStream::from_std(read_end) { |
| 31 | + Ok(s) => s, |
| 32 | + Err(e) => { |
| 33 | + tracing::warn!("[Signal] Failed to wrap self-pipe: {e}"); |
| 34 | + return; |
| 35 | + } |
| 36 | + }; |
| 37 | + let mut buf = [0u8; 1]; |
| 38 | + use tokio::io::AsyncReadExt; |
| 39 | + let _ = reader.read_exact(&mut buf).await; |
| 40 | + |
| 41 | + let pid = std::process::id(); |
| 42 | + let ppid = unsafe { libc::getppid() }; |
| 43 | + let sender = SENDER_PID.load(Ordering::SeqCst); |
| 44 | + let sig = SIGNAL_NO.load(Ordering::SeqCst); |
| 45 | + let code = SIGNAL_CODE.load(Ordering::SeqCst); |
| 46 | + let name = if sig == libc::SIGINT { "SIGINT" } else { "SIGTERM" }; |
| 47 | + |
| 48 | + info!( |
| 49 | + pid, |
| 50 | + ppid, |
| 51 | + parent = %describe_pid(ppid), |
| 52 | + sender_pid = sender, |
| 53 | + sender = %describe_pid(sender), |
| 54 | + si_code = code, |
| 55 | + "[Signal] {name} — requesting exit" |
| 56 | + ); |
| 57 | +} |
| 58 | + |
| 59 | +fn install() -> std::io::Result<UnixStream> { |
| 60 | + let (read, write) = UnixStream::pair()?; |
| 61 | + read.set_nonblocking(true)?; |
| 62 | + write.set_nonblocking(true)?; |
| 63 | + PIPE_WRITE_FD.store(write.as_raw_fd(), Ordering::SeqCst); |
| 64 | + // Handler writes to this fd for the life of the process. |
| 65 | + std::mem::forget(write); |
| 66 | + |
| 67 | + unsafe { |
| 68 | + let mut sa: libc::sigaction = std::mem::zeroed(); |
| 69 | + sa.sa_sigaction = record_sender as *const () as usize; |
| 70 | + sa.sa_flags = libc::SA_SIGINFO | libc::SA_RESTART; |
| 71 | + libc::sigemptyset(&mut sa.sa_mask); |
| 72 | + if libc::sigaction(libc::SIGTERM, &sa, std::ptr::null_mut()) != 0 { |
| 73 | + return Err(std::io::Error::last_os_error()); |
| 74 | + } |
| 75 | + if libc::sigaction(libc::SIGINT, &sa, std::ptr::null_mut()) != 0 { |
| 76 | + return Err(std::io::Error::last_os_error()); |
| 77 | + } |
| 78 | + } |
| 79 | + Ok(read) |
| 80 | +} |
| 81 | + |
| 82 | +unsafe extern "C" fn record_sender( |
| 83 | + sig: libc::c_int, |
| 84 | + info: *mut libc::siginfo_t, |
| 85 | + _ctx: *mut libc::c_void, |
| 86 | +) { |
| 87 | + if !info.is_null() { |
| 88 | + // SAFETY: kernel-filled siginfo for this delivery. |
| 89 | + let info = unsafe { &*info }; |
| 90 | + SENDER_PID.store(unsafe { info.si_pid() }, Ordering::SeqCst); |
| 91 | + SIGNAL_CODE.store(info.si_code, Ordering::SeqCst); |
| 92 | + } |
| 93 | + SIGNAL_NO.store(sig, Ordering::SeqCst); |
| 94 | + let fd = PIPE_WRITE_FD.load(Ordering::SeqCst); |
| 95 | + if fd >= 0 { |
| 96 | + let byte = [1u8]; |
| 97 | + unsafe { |
| 98 | + libc::write(fd, byte.as_ptr() as *const libc::c_void, 1); |
| 99 | + } |
| 100 | + } |
| 101 | +} |
| 102 | + |
| 103 | +/// Best-effort path/name for a live pid. `"unknown"` if pid is empty or gone. |
| 104 | +fn describe_pid(pid: libc::pid_t) -> String { |
| 105 | + if pid <= 0 { |
| 106 | + return "unknown".to_string(); |
| 107 | + } |
| 108 | + #[cfg(target_os = "macos")] |
| 109 | + { |
| 110 | + let mut buf = [0u8; 4096]; |
| 111 | + extern "C" { |
| 112 | + fn proc_pidpath(pid: i32, buffer: *mut libc::c_void, buffersize: u32) -> i32; |
| 113 | + } |
| 114 | + let n = unsafe { proc_pidpath(pid, buf.as_mut_ptr() as *mut _, buf.len() as u32) }; |
| 115 | + if n > 0 { |
| 116 | + return String::from_utf8_lossy(&buf[..n as usize]).into_owned(); |
| 117 | + } |
| 118 | + } |
| 119 | + #[cfg(target_os = "linux")] |
| 120 | + { |
| 121 | + if let Ok(path) = std::fs::read_link(format!("/proc/{pid}/exe")) { |
| 122 | + return path.display().to_string(); |
| 123 | + } |
| 124 | + if let Ok(comm) = std::fs::read_to_string(format!("/proc/{pid}/comm")) { |
| 125 | + return comm.trim().to_string(); |
| 126 | + } |
| 127 | + } |
| 128 | + format!("pid:{pid}") |
| 129 | +} |
| 130 | + |
| 131 | +#[cfg(test)] |
| 132 | +mod tests { |
| 133 | + use super::*; |
| 134 | + |
| 135 | + #[test] |
| 136 | + fn describe_pid_self_is_nonempty() { |
| 137 | + let me = std::process::id() as libc::pid_t; |
| 138 | + let desc = describe_pid(me); |
| 139 | + assert!(!desc.is_empty(), "self pid should resolve"); |
| 140 | + assert_ne!(desc, "unknown"); |
| 141 | + } |
| 142 | + |
| 143 | + #[test] |
| 144 | + fn describe_pid_zero_is_unknown() { |
| 145 | + assert_eq!(describe_pid(0), "unknown"); |
| 146 | + } |
| 147 | +} |
0 commit comments