bynk/stop.rs
1//! Stopping `bynk dev` from outside (#1955).
2//!
3//! Without a handler, a SIGTERM or SIGINT sent to `bynk dev` alone (by a CI
4//! step, a test harness, an editor task) killed it on the spot, and its
5//! wranglers and their `workerd`s ran on with their ports bound. A Ctrl-C in a
6//! terminal never showed it, because the terminal signals the whole foreground
7//! group, wranglers included.
8//!
9//! [`install`] replaces the default action with one that only records the
10//! signal. `bynk dev`'s watch loop sees it on its next tick and stops its
11//! contexts the way it does when one of them exits: SIGTERM to each wrangler,
12//! then the sweep of what they leave behind ([`crate::sweep`]). The wranglers
13//! stay in `bynk dev`'s process group, because the sweep finds orphaned
14//! `workerd`s by that group and a Ctrl-C must still reach them all.
15//!
16//! The handler is one-shot (`SA_RESETHAND`): a second Ctrl-C while the
17//! contexts are stopping takes the default action and ends `bynk dev` at once.
18//!
19//! Unix only. On Windows each wrangler's job object holds its tree (#1762), and
20//! [`install`] does nothing.
21
22use bynk_driver::emsg;
23use std::sync::atomic::{AtomicI32, Ordering};
24
25/// The signal received since [`install`], or 0 for none.
26static RECEIVED: AtomicI32 = AtomicI32::new(0);
27
28/// Record SIGINT and SIGTERM instead of dying of them, for [`received`] to
29/// report. Children spawned afterwards are unaffected: `exec` resets a caught
30/// signal to its default action.
31pub fn install() {
32 #[cfg(unix)]
33 for sig in [libc::SIGINT, libc::SIGTERM] {
34 // SAFETY: `record` only stores to an atomic, which is
35 // async-signal-safe, and `action` is fully initialised before use.
36 unsafe {
37 let mut action: libc::sigaction = std::mem::zeroed();
38 action.sa_sigaction = record as extern "C" fn(libc::c_int) as libc::sighandler_t;
39 action.sa_flags = libc::SA_RESTART | libc::SA_RESETHAND;
40 libc::sigemptyset(&mut action.sa_mask);
41 if libc::sigaction(sig, &action, std::ptr::null_mut()) != 0 {
42 emsg!(
43 "bynk dev: warning: could not install a handler for signal {sig}; stopping \
44 `bynk dev` with it may leave its workerd processes running."
45 );
46 }
47 }
48 }
49}
50
51#[cfg(unix)]
52extern "C" fn record(sig: libc::c_int) {
53 RECEIVED.store(sig, Ordering::SeqCst);
54}
55
56/// The signal that asked `bynk dev` to stop, if one has arrived.
57pub fn received() -> Option<i32> {
58 match RECEIVED.load(Ordering::SeqCst) {
59 0 => None,
60 sig => Some(sig),
61 }
62}
63
64/// #2055: SIGINT and SIGTERM recorded rather than fatal for as long as the
65/// returned guard lives, then the dispositions in force before restored.
66///
67/// `bynk deploy` holds one while a first deploy's `wrangler deploy
68/// --secrets-file` runs, so a Ctrl-C (which the terminal sends to the whole
69/// foreground group, wrangler included) or a SIGTERM sent to `bynk` alone
70/// cannot end `bynk` before it removes the secrets file. A caught signal is
71/// reset to its default by `exec`, so wrangler itself still dies of them as it
72/// would have. Unlike [`install`], the handler is not one-shot: a second
73/// Ctrl-C must not end `bynk` with the file on disk either. Only SIGKILL can,
74/// and the next deploy's sweep removes what that leaves.
75///
76/// Clears any earlier recorded signal, so [`received`] reports only what
77/// arrived under this guard. On Windows it changes nothing.
78#[must_use = "the signals are restored when the guard drops"]
79pub(crate) fn defer() -> Deferred {
80 RECEIVED.store(0, Ordering::SeqCst);
81 #[cfg(unix)]
82 {
83 let mut previous: [Option<libc::sigaction>; 2] = [None, None];
84 for (slot, sig) in previous.iter_mut().zip([libc::SIGINT, libc::SIGTERM]) {
85 // SAFETY: `record` only stores to an atomic, which is
86 // async-signal-safe; both structs are fully initialised before use,
87 // and `old` is only kept when the call succeeded.
88 unsafe {
89 let mut action: libc::sigaction = std::mem::zeroed();
90 action.sa_sigaction = record as extern "C" fn(libc::c_int) as libc::sighandler_t;
91 action.sa_flags = libc::SA_RESTART;
92 libc::sigemptyset(&mut action.sa_mask);
93 let mut old: libc::sigaction = std::mem::zeroed();
94 if libc::sigaction(sig, &action, &mut old) == 0 {
95 *slot = Some(old);
96 }
97 }
98 }
99 Deferred { previous }
100 }
101 #[cfg(not(unix))]
102 Deferred {}
103}
104
105/// The guard [`defer`] returns. Dropping it puts back the SIGINT and SIGTERM
106/// dispositions [`defer`] replaced.
107pub(crate) struct Deferred {
108 #[cfg(unix)]
109 previous: [Option<libc::sigaction>; 2],
110}
111
112impl Drop for Deferred {
113 fn drop(&mut self) {
114 #[cfg(unix)]
115 for (old, sig) in self.previous.iter().zip([libc::SIGINT, libc::SIGTERM]) {
116 if let Some(old) = old {
117 // SAFETY: `old` is the disposition `sigaction` returned.
118 unsafe {
119 libc::sigaction(sig, old, std::ptr::null_mut());
120 }
121 }
122 }
123 }
124}
125
126/// Serialises the tests that change this process's signal dispositions or
127/// signal it, which would otherwise race in the shared test binary.
128#[cfg(test)]
129pub(crate) static TEST_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
130
131/// Undo [`install`] and forget any recorded signal, so a test that installs
132/// the handler leaves nothing behind in the shared test process.
133#[cfg(test)]
134pub(crate) fn reset() {
135 #[cfg(unix)]
136 for sig in [libc::SIGINT, libc::SIGTERM] {
137 // SAFETY: restoring the default disposition.
138 unsafe {
139 libc::signal(sig, libc::SIG_DFL);
140 }
141 }
142 RECEIVED.store(0, Ordering::SeqCst);
143}
144
145/// The exit byte for a session stopped by `sig`, as [`crate::shell::exit_status_byte`]
146/// maps a child's signal death: SIGINT is a clean stop (it is what Ctrl-C
147/// sends), anything else `128 + sig`, the shell convention.
148pub fn exit_byte(sig: i32) -> u8 {
149 // SIGINT is 2 on every Unix.
150 if sig == 2 {
151 0
152 } else {
153 128u8.saturating_add(sig.clamp(0, 127) as u8)
154 }
155}
156
157/// How to name `sig` in `bynk dev`'s stop notice.
158pub fn name(sig: i32) -> String {
159 match sig {
160 2 => "SIGINT".to_string(),
161 15 => "SIGTERM".to_string(),
162 n => format!("signal {n}"),
163 }
164}
165
166#[cfg(test)]
167mod tests {
168 use super::*;
169
170 /// The handler `sig` currently has.
171 #[cfg(unix)]
172 fn disposition(sig: libc::c_int) -> libc::sighandler_t {
173 // SAFETY: a query; `current` is written by the call.
174 unsafe {
175 let mut current: libc::sigaction = std::mem::zeroed();
176 assert_eq!(libc::sigaction(sig, std::ptr::null(), &mut current), 0);
177 current.sa_sigaction
178 }
179 }
180
181 #[cfg(unix)]
182 #[test]
183 fn a_deferred_signal_is_recorded_and_the_old_disposition_comes_back() {
184 // #2055: what keeps `bynk deploy` alive to remove a secrets file.
185 let _lock = TEST_LOCK.lock().unwrap_or_else(|e| e.into_inner());
186 let before = [disposition(libc::SIGINT), disposition(libc::SIGTERM)];
187 {
188 let _deferred = defer();
189 assert_eq!(received(), None, "nothing carried over");
190 // Without the handler this would end the test binary.
191 // SAFETY: signalling this process, whose handler only records.
192 unsafe {
193 libc::raise(libc::SIGTERM);
194 libc::raise(libc::SIGINT);
195 }
196 assert!(received().is_some(), "the signals were recorded");
197 // SAFETY: as above; the handler is not one-shot.
198 unsafe {
199 libc::raise(libc::SIGINT);
200 }
201 }
202 assert_eq!(
203 [disposition(libc::SIGINT), disposition(libc::SIGTERM)],
204 before,
205 "the dispositions in force before are restored"
206 );
207 RECEIVED.store(0, Ordering::SeqCst);
208 }
209
210 #[test]
211 fn a_signal_stop_exits_like_a_signalled_child() {
212 assert_eq!(exit_byte(2), 0, "Ctrl-C is a clean stop");
213 assert_eq!(exit_byte(15), 143);
214 }
215}