Skip to content

Commit 805a42f

Browse files
authored
fix(process-daemon): stop cleanly on SIGTERM and SIGINT (#60691)
1 parent d074773 commit 805a42f

2 files changed

Lines changed: 137 additions & 0 deletions

File tree

‎packages/process-daemon/src/daemon/server.rs‎

Lines changed: 98 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -19,14 +19,112 @@ const ACCEPT_BACKOFF: Duration = Duration::from_millis(100);
1919
const MAX_ACCEPTS_PER_PASS: usize = 64;
2020

2121
pub fn run(directory: &Path) -> Result<()> {
22+
// First, before bind starts the sweeper thread: every thread created after
23+
// this inherits the mask, so only the signal thread ever receives them.
24+
#[cfg(unix)]
25+
let signals = signals::block()?;
2226
// Before bind, so a failure here leaves nothing to clean up.
2327
let wake = Wake::new()?;
2428
let (runtime, listener) = platform::Runtime::bind(directory)?;
2529
// Created after bind so bind I/O does not consume the acquire window.
2630
let control = Arc::new(Control::new(wake, Ownership::new(Instant::now())));
31+
#[cfg(unix)]
32+
if let Err(error) = signals::stop_on(signals, &control) {
33+
let _ = runtime.finish();
34+
return Err(error);
35+
}
2736
serve(runtime, listener, control, Settings::default())
2837
}
2938

39+
/// Turns SIGTERM and SIGINT into an orderly stop, so children are killed and
40+
/// the runtime directory is removed instead of the daemon dying with both left
41+
/// behind.
42+
///
43+
/// Children inherit the signal mask across `exec`. portable-pty resets it for
44+
/// PTY children; anything else the daemon spawns must reset it itself.
45+
#[cfg(unix)]
46+
mod signals {
47+
use std::io;
48+
use std::sync::Arc;
49+
use std::thread;
50+
use std::time::{Duration, Instant};
51+
52+
use anyhow::{Context, Result};
53+
54+
use super::Control;
55+
56+
const STOP: [libc::c_int; 2] = [libc::SIGTERM, libc::SIGINT];
57+
/// A second signal this soon after the first is part of the same stop
58+
/// (Ctrl-C plus a wrapper's SIGTERM), not a sign that the stop is stuck.
59+
const REPEAT_GRACE: Duration = Duration::from_secs(1);
60+
61+
pub(super) struct Blocked(libc::sigset_t);
62+
63+
/// Blocks the stop signals on the calling thread, and restores their
64+
/// default action: macOS never delivers an ignored signal to `sigwait`,
65+
/// and a launcher may have left SIGINT ignored.
66+
pub(super) fn block() -> Result<Blocked> {
67+
// SAFETY: plain libc calls on a local, initialized signal set.
68+
unsafe {
69+
let mut set: libc::sigset_t = std::mem::zeroed();
70+
libc::sigemptyset(&mut set);
71+
for signal in STOP {
72+
libc::sigaddset(&mut set, signal);
73+
}
74+
let result = libc::pthread_sigmask(libc::SIG_BLOCK, &set, std::ptr::null_mut());
75+
if result != 0 {
76+
return Err(io::Error::from_raw_os_error(result))
77+
.context("failed to block stop signals");
78+
}
79+
// Only after blocking, so there is no window where the default
80+
// action could kill the daemon.
81+
for signal in STOP {
82+
libc::signal(signal, libc::SIG_DFL);
83+
}
84+
Ok(Blocked(set))
85+
}
86+
}
87+
88+
pub(super) fn stop_on(signals: Blocked, control: &Arc<Control>) -> Result<()> {
89+
let control = Arc::clone(control);
90+
thread::Builder::new()
91+
.name("opencode-pty-signals".into())
92+
.spawn(move || {
93+
wait(&signals);
94+
let stopped = Instant::now();
95+
control.request_stop();
96+
loop {
97+
let signal = wait(&signals);
98+
if stopped.elapsed() >= REPEAT_GRACE {
99+
// The orderly stop is stuck. Exit without running exit
100+
// handlers, which other threads may be blocking.
101+
// SAFETY: `_exit` is always safe to call.
102+
unsafe { libc::_exit(128 + signal) };
103+
}
104+
}
105+
})
106+
.context("failed to start the signal thread")?;
107+
Ok(())
108+
}
109+
110+
fn wait(signals: &Blocked) -> libc::c_int {
111+
loop {
112+
let mut signal = 0;
113+
// SAFETY: valid set and out pointer; `sigwait` returns an error
114+
// number instead of setting errno, and fills `signal` on success.
115+
let result = unsafe { libc::sigwait(&signals.0, &mut signal) };
116+
if result == 0 {
117+
return signal;
118+
}
119+
// EINTR (after SIGSTOP and SIGCONT) just retries. Nothing else is
120+
// expected for valid signals; pause so it can't spin.
121+
if result != libc::EINTR {
122+
thread::sleep(Duration::from_millis(100));
123+
}
124+
}
125+
}
126+
}
127+
30128
struct Settings {
31129
/// Longest the loop sleeps without a wake or deadline.
32130
safety_net: Duration,

‎packages/process-daemon/tests/ownership.rs‎

Lines changed: 39 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -536,3 +536,42 @@ fn shutdown_keeps_a_replaced_socket() {
536536
drop(replacement);
537537
std::fs::remove_file(&daemon.registration.socket).unwrap();
538538
}
539+
540+
#[test]
541+
fn stop_signals_stop_terminals_and_clean_up() {
542+
for signal in [libc::SIGTERM, libc::SIGINT] {
543+
let mut daemon = Daemon::start();
544+
let (_owner, response) = daemon.own(None);
545+
assert!(matches!(response, Response::Owned));
546+
let terminal = daemon.terminal("exec sleep 1000");
547+
548+
// The daemon blocks these signals on its own threads; its children must not
549+
// inherit that mask, so a terminal's process still dies from the signal.
550+
let probe = daemon.terminal("exec sleep 1000");
551+
// SAFETY: the probe PID belongs to this test's live terminal.
552+
assert_eq!(unsafe { libc::kill(probe.pid.unwrap() as i32, signal) }, 0);
553+
let deadline = Instant::now() + Duration::from_secs(3);
554+
loop {
555+
let Response::Terminals { terminals } = daemon.request(Request::List) else {
556+
panic!("list failed");
557+
};
558+
let exited = terminals.iter().any(|value| {
559+
value.id == probe.id
560+
&& !matches!(
561+
value.lifecycle,
562+
opencode_pty::service::TerminalLifecycle::Running
563+
)
564+
});
565+
if exited {
566+
break;
567+
}
568+
assert!(Instant::now() < deadline, "probe ignored signal {signal}");
569+
thread::sleep(Duration::from_millis(10));
570+
}
571+
572+
// SAFETY: the PID belongs to the daemon this test spawned.
573+
assert_eq!(unsafe { libc::kill(daemon.child.id() as i32, signal) }, 0);
574+
daemon.wait();
575+
assert_terminal_stopped(&terminal);
576+
}
577+
}

0 commit comments

Comments
 (0)