mirror of
https://github.com/anomalyco/opencode.git
synced 2026-11-19 17:01:37 +03:00
fix(process-daemon): reap shell commands at exit (protocol 9, release 0.6.0) (#64266)
This commit is contained in:
committed by
GitHub
Unverified
parent
c0a7beb6d9
commit
03d848f7b8
Generated
+2
-1
@@ -184,11 +184,12 @@ dependencies = [
|
||||
|
||||
[[package]]
|
||||
name = "opencode-pty"
|
||||
version = "0.5.2"
|
||||
version = "0.6.0"
|
||||
dependencies = [
|
||||
"anyhow",
|
||||
"base64",
|
||||
"crossbeam-channel",
|
||||
"crossbeam-utils",
|
||||
"fs2",
|
||||
"libc",
|
||||
"nix",
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "opencode-pty"
|
||||
version = "0.5.2"
|
||||
version = "0.6.0"
|
||||
edition = "2024"
|
||||
rust-version = "1.90"
|
||||
description = "Persistent PTY service for OpenCode"
|
||||
@@ -20,6 +20,7 @@ serde_json = "1.0"
|
||||
shell-words = "1.1"
|
||||
|
||||
[target.'cfg(unix)'.dependencies]
|
||||
crossbeam-utils = "0.8"
|
||||
libc = "0.2"
|
||||
nix = { version = "0.28", features = ["poll", "process", "term", "user"] }
|
||||
sha2 = "0.10"
|
||||
|
||||
@@ -17,7 +17,7 @@ terminals. Observer commands connect to an existing daemon without taking owners
|
||||
The service uses a private authenticated local byte stream (Unix socket or Windows
|
||||
named pipe) and an atomic registration file.
|
||||
|
||||
Integrations launch `opencode-pty daemon --name NAME [--runtime-dir DIR]` (protocol 8).
|
||||
Integrations launch `opencode-pty daemon --name NAME [--runtime-dir DIR]` (protocol 9).
|
||||
The server must claim the daemon within 5 seconds by sending the authenticated
|
||||
framed envelope `{"token":"...","request":{"op":"own","instance_id":"..."}}`.
|
||||
The response is `{"type":"owned"}`; that connection stays open as the sole
|
||||
@@ -70,7 +70,7 @@ socket pair until a connection arrives, a stop or ownership change wakes it, an
|
||||
ownership deadline is due, or a two-second safety net elapses. Windows still
|
||||
polls every 25 ms.
|
||||
|
||||
The Windows named-pipe backend keeps protocol 8 and the registration fields
|
||||
The Windows named-pipe backend uses protocol 9 and the registration fields
|
||||
`instance_id`, `pid`, `protocol`, `socket`, `token`, and `features`. Treat `socket` as an opaque
|
||||
local endpoint: on Windows it is `\\.\pipe\opencode-pty-<instance_id>`, not a
|
||||
filesystem socket. A random per-instance name, exclusive first pipe instance,
|
||||
@@ -111,7 +111,7 @@ so the runtime directory must be on a local NTFS volume (Windows 10 1709 or
|
||||
later); there is no non-atomic fallback.
|
||||
|
||||
The Windows Rust `TerminalClient` and interactive CLI are not ported. Integrations
|
||||
can use protocol 8 directly and the minimal `daemon::PipeConnection` byte-stream
|
||||
can use protocol 9 directly and the minimal `daemon::PipeConnection` byte-stream
|
||||
helper. Connect with `PipeConnection::connect_to(socket, pid)`, which rejects a
|
||||
pipe whose server is not the registered daemon process: after a crash the stale
|
||||
registration's pipe name is free for another local user to create. Integrations
|
||||
@@ -211,7 +211,7 @@ return all available rows. Soft-wrapped rows stay separate, trailing whitespace
|
||||
is trimmed, and blank rows (including trailing blank rows) are empty strings.
|
||||
The alternate screen never exposes primary-screen history.
|
||||
|
||||
The protocol 8 request is `{"op":"read_rows","id":1,"rows":30}`;
|
||||
The protocol 9 request is `{"op":"read_rows","id":1,"rows":30}`;
|
||||
omitted or `null` `rows` uses the current height. Its response is
|
||||
`{"type":"rows","process":{...},"lines":[...],"cursor_x":0,"cursor_y":0}`.
|
||||
Metadata, lines, and zero-based active-screen cursor coordinates come from one
|
||||
|
||||
@@ -181,14 +181,16 @@ starts a pipe process: any command without a terminal. Both return
|
||||
`"SIGTERM"`, when a signal ended the process (on Windows, when the daemon
|
||||
signalled it); `exit_code` is then null. `signal` is left out when there is
|
||||
none.
|
||||
- On Unix an exited pipe process stays listed, as a zombie, until `terminate`.
|
||||
The zombie keeps its PID and process group ID reserved, so killing the group
|
||||
can never reach an unrelated process. On Windows the process object and job
|
||||
handle stay open until `terminate`, so the PID is not reused either.
|
||||
`terminate` kills the whole tree (SIGKILL on Unix; the job on Windows),
|
||||
reaps it and removes the process; it never waits on a descendant that left
|
||||
the process group or job and still holds the pipe. The daemon never deletes
|
||||
output files.
|
||||
- A successful command may leave background processes running untracked.
|
||||
On Unix a non-zero exit code sends SIGTERM to the process group before the
|
||||
waiter reaps the leader, then SIGKILL after three seconds if the group
|
||||
survives. A signal death has no numeric exit code and does not trigger this
|
||||
cleanup. On Windows a non-zero exit terminates the job immediately. The
|
||||
waiter clears kill-on-close and releases the job and process handles at exit.
|
||||
- The finished record (including exit status, output path and metadata) stays
|
||||
listed until `terminate`. Its PID is historical metadata. `terminate` kills
|
||||
a running tree and removes its record; after exit it only removes the record.
|
||||
The daemon never deletes output files.
|
||||
|
||||
### Line count
|
||||
|
||||
@@ -225,9 +227,8 @@ process group and the child, as a real signal. **On Windows every signal is a
|
||||
hard kill** of the job: there is no console, so SIGTERM and SIGINT cannot be
|
||||
caught, and the exit reports the signal that was sent, not a platform exit
|
||||
code. Unlike `terminate`, `signal` keeps the process: `wait` then gets a normal
|
||||
`Exited` with `signal`. Signalling an exited process is allowed and reaches
|
||||
whatever is left of its group or job (an empty group is not an error); after
|
||||
`terminate` the process is gone and `signal` fails.
|
||||
`Exited` with `signal`. Signalling an exited process returns `Ok` without
|
||||
sending a signal; after `terminate` the record is gone and `signal` fails.
|
||||
|
||||
If an outer job refuses the child (`ERROR_ACCESS_DENIED`, for example a job
|
||||
with UI restrictions), the daemon runs the command anyway without a job, logs
|
||||
@@ -256,7 +257,7 @@ connected owner; the superseded connection can no longer prepare handoffs or
|
||||
stop the daemon, and its disconnect does not affect the new owner. The playground holds ownership until it exits; other CLI commands
|
||||
only observe or operate an existing daemon and never start one.
|
||||
|
||||
Protocol v8 uses four-byte big-endian framing with bounded UTF-8 JSON control
|
||||
Protocol v9 uses four-byte big-endian framing with bounded UTF-8 JSON control
|
||||
frames and tagged raw binary output frames. Requests (`op`): `ping`, `own`,
|
||||
`prepare_handoff`, `create_pty`, `create_pipe`, `list`, `get`, `wait`,
|
||||
`signal`, `set_metadata`, `write`, `resize`, `control` (atomic interaction
|
||||
@@ -271,7 +272,7 @@ connection, once the token has been checked. Clients can therefore probe for
|
||||
a request.
|
||||
|
||||
`Pong` and the registration carry `features` (required), the daemon's additive
|
||||
capabilities. Protocol 8 needs none, so the list is empty. Later additive
|
||||
capabilities. Protocol 9 needs none, so the list is empty. Later additive
|
||||
changes, such as a new request or field older clients can ignore, extend
|
||||
`features` and keep the protocol version. Only breaking changes bump
|
||||
`PROTOCOL_VERSION`, which clients reject on mismatch.
|
||||
@@ -310,3 +311,8 @@ the database. It starts the daemon only when the first terminal or pipe
|
||||
process is created.
|
||||
Only an explicit restart handoff descriptor lets a replacement server reuse
|
||||
the previous daemon's runtime directory and claim its ownership.
|
||||
|
||||
On upgrade to protocol 9, OpenCode discovers protocol-8 daemons under its
|
||||
runtime root and in its inherited handoff directory. It authenticates each
|
||||
live instance and requests shutdown. This one-time replacement ends its
|
||||
running commands and persistent terminals. A new daemon still starts lazily.
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "@opencode/pty",
|
||||
"version": "0.5.2",
|
||||
"version": "0.6.0",
|
||||
"description": "Persistent PTY service for OpenCode",
|
||||
"type": "module",
|
||||
"license": "MIT",
|
||||
@@ -25,14 +25,14 @@
|
||||
"index.js"
|
||||
],
|
||||
"optionalDependencies": {
|
||||
"@opencode/pty-darwin-arm64": "0.5.2",
|
||||
"@opencode/pty-darwin-x64": "0.5.2",
|
||||
"@opencode/pty-linux-arm64-gnu": "0.5.2",
|
||||
"@opencode/pty-linux-arm64-musl": "0.5.2",
|
||||
"@opencode/pty-linux-x64-gnu": "0.5.2",
|
||||
"@opencode/pty-linux-x64-musl": "0.5.2",
|
||||
"@opencode/pty-win32-arm64": "0.5.2",
|
||||
"@opencode/pty-win32-x64": "0.5.2"
|
||||
"@opencode/pty-darwin-arm64": "0.6.0",
|
||||
"@opencode/pty-darwin-x64": "0.6.0",
|
||||
"@opencode/pty-linux-arm64-gnu": "0.6.0",
|
||||
"@opencode/pty-linux-arm64-musl": "0.6.0",
|
||||
"@opencode/pty-linux-x64-gnu": "0.6.0",
|
||||
"@opencode/pty-linux-x64-musl": "0.6.0",
|
||||
"@opencode/pty-win32-arm64": "0.6.0",
|
||||
"@opencode/pty-win32-x64": "0.6.0"
|
||||
},
|
||||
"publishConfig": {
|
||||
"access": "public"
|
||||
|
||||
@@ -894,7 +894,7 @@ mod tests {
|
||||
let _ = std::fs::remove_dir_all(&directory);
|
||||
assert_eq!(
|
||||
error.to_string(),
|
||||
"opencode-pty protocol mismatch: service=7, client=8"
|
||||
"opencode-pty protocol mismatch: service=7, client=9"
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
@@ -9,9 +9,9 @@ use crate::service::{
|
||||
PipeMetadata, ProcessExit, ProcessInfo, ProcessMode, ProcessSignal, TerminalId,
|
||||
};
|
||||
|
||||
pub const PROTOCOL_VERSION: u32 = 8;
|
||||
pub const PROTOCOL_VERSION: u32 = 9;
|
||||
/// Additive capabilities of this daemon. Breaking changes bump
|
||||
/// `PROTOCOL_VERSION`; everything in protocol 8 needs no feature.
|
||||
/// `PROTOCOL_VERSION`; everything in protocol 9 needs no feature.
|
||||
pub const FEATURES: &[&str] = &[];
|
||||
|
||||
pub fn features() -> Vec<String> {
|
||||
@@ -363,18 +363,18 @@ mod tests {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn version_8_has_no_features() {
|
||||
assert_eq!(PROTOCOL_VERSION, 8);
|
||||
fn version_9_has_no_features() {
|
||||
assert_eq!(PROTOCOL_VERSION, 9);
|
||||
assert!(features().is_empty());
|
||||
// `features` is required.
|
||||
assert!(
|
||||
serde_json::from_value::<Response>(
|
||||
json!({"type": "pong", "instance_id": "a", "pid": 1, "protocol": 8})
|
||||
json!({"type": "pong", "instance_id": "a", "pid": 1, "protocol": 9})
|
||||
)
|
||||
.is_err()
|
||||
);
|
||||
round_trip::<Response>(
|
||||
json!({"type": "pong", "instance_id": "a", "pid": 1, "protocol": 8, "features": []}),
|
||||
json!({"type": "pong", "instance_id": "a", "pid": 1, "protocol": 9, "features": []}),
|
||||
);
|
||||
}
|
||||
|
||||
|
||||
@@ -11,6 +11,8 @@ use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result, anyhow, bail};
|
||||
use crossbeam_channel::{Receiver, Sender, bounded};
|
||||
#[cfg(unix)]
|
||||
use crossbeam_utils::sync::WaitGroup;
|
||||
use portable_pty::{ChildKiller, CommandBuilder, MasterPty, PtySize, native_pty_system};
|
||||
use serde::{Deserialize, Serialize};
|
||||
|
||||
@@ -284,6 +286,9 @@ pub struct CreatePipe {
|
||||
|
||||
pub struct TerminalService {
|
||||
terminals: Mutex<HashMap<TerminalId, Arc<TerminalHandle>>>,
|
||||
/// Failed-command escalation outlives record deletion. Shutdown waits for it.
|
||||
#[cfg(unix)]
|
||||
escalations: WaitGroup,
|
||||
created: AtomicU64,
|
||||
replay_capacity: usize,
|
||||
}
|
||||
@@ -298,6 +303,8 @@ impl TerminalService {
|
||||
pub fn new(replay_capacity: usize) -> Self {
|
||||
Self {
|
||||
terminals: Mutex::new(HashMap::new()),
|
||||
#[cfg(unix)]
|
||||
escalations: WaitGroup::new(),
|
||||
created: AtomicU64::new(0),
|
||||
replay_capacity,
|
||||
}
|
||||
@@ -322,7 +329,15 @@ impl TerminalService {
|
||||
bail!("output_path must be absolute");
|
||||
}
|
||||
validate_metadata(&request.metadata)?;
|
||||
self.insert(|id, order| TerminalHandle::spawn_pipe(id, order, request))
|
||||
self.insert(|id, order| {
|
||||
TerminalHandle::spawn_pipe(
|
||||
id,
|
||||
order,
|
||||
request,
|
||||
#[cfg(unix)]
|
||||
self.escalations.clone(),
|
||||
)
|
||||
})
|
||||
}
|
||||
|
||||
fn insert(
|
||||
@@ -393,7 +408,7 @@ impl TerminalService {
|
||||
}
|
||||
|
||||
/// Signals a pipe process and its process group. The process stays
|
||||
/// listed; signalling one that already exited is allowed.
|
||||
/// listed; signalling one that already exited is a no-op.
|
||||
pub fn signal(&self, id: TerminalId, signal: ProcessSignal) -> Result<()> {
|
||||
self.pipe(id)?
|
||||
.process
|
||||
@@ -615,6 +630,8 @@ impl TerminalService {
|
||||
impl Drop for TerminalService {
|
||||
fn drop(&mut self) {
|
||||
self.shutdown();
|
||||
#[cfg(unix)]
|
||||
std::mem::take(&mut self.escalations).wait();
|
||||
}
|
||||
}
|
||||
|
||||
@@ -630,8 +647,6 @@ struct TerminalHandle {
|
||||
/// Dropped at shutdown, before the joins, to cancel a pipe reader that a
|
||||
/// surviving descendant would otherwise keep blocked.
|
||||
cancel: Mutex<Option<Box<dyn Send>>>,
|
||||
/// Runs after the joins; reaps a pipe process kept as a zombie until now.
|
||||
reap: Mutex<Option<Box<dyn FnOnce() + Send>>>,
|
||||
/// Pipe only: the child, for `signal`.
|
||||
process: Option<Arc<pipe::Process>>,
|
||||
info: Arc<RwLock<ProcessInfo>>,
|
||||
@@ -867,7 +882,6 @@ impl TerminalHandle {
|
||||
shutdown_tx: Mutex::new(Some(actor.shutdown_tx)),
|
||||
killer: Mutex::new(killer),
|
||||
cancel: Mutex::new(None),
|
||||
reap: Mutex::new(None),
|
||||
process: None,
|
||||
info,
|
||||
joins: Mutex::new(Some(vec![
|
||||
@@ -929,14 +943,6 @@ impl TerminalHandle {
|
||||
for join in handles {
|
||||
let _ = join.join();
|
||||
}
|
||||
if let Some(reap) = self
|
||||
.reap
|
||||
.lock()
|
||||
.unwrap_or_else(|poisoned| poisoned.into_inner())
|
||||
.take()
|
||||
{
|
||||
reap();
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
@@ -2270,7 +2276,6 @@ mod tests {
|
||||
shutdown_tx: Mutex::new(Some(shutdown_tx)),
|
||||
killer: Mutex::new(Box::new(TestKiller)),
|
||||
cancel: Mutex::new(None),
|
||||
reap: Mutex::new(None),
|
||||
process: None,
|
||||
info,
|
||||
joins: Mutex::new(Some(vec![
|
||||
|
||||
@@ -1,10 +1,8 @@
|
||||
//! Non-PTY ("pipe") processes: a command with no terminal, stdin closed and
|
||||
//! stdout and stderr sharing one pipe so their bytes keep their order.
|
||||
//!
|
||||
//! The platform modules own the child, its process tree and the output pipe:
|
||||
//! Unix keeps a zombie so the PID and process group stay reserved, and Windows
|
||||
//! keeps the process and its kill-on-close job. Everything the two must do the
|
||||
//! same way lives here:
|
||||
//! The platform waiters clean up a failed command's tree and release the
|
||||
//! child at exit. The actor keeps its record available for late waiters.
|
||||
//!
|
||||
//! - The reader writes every byte to the output file before handing it to the
|
||||
//! actor, which keeps no replay buffer: the file is the only copy of the
|
||||
@@ -105,7 +103,7 @@ impl OutputSink {
|
||||
/// How a pipe child ended.
|
||||
enum Exit {
|
||||
Code(u32),
|
||||
/// The daemon terminated the process; the value is the signal it sent.
|
||||
/// The Unix terminating signal, or the signal sent by the daemon on Windows.
|
||||
Signal(String),
|
||||
}
|
||||
|
||||
@@ -149,16 +147,8 @@ fn new_pipe_info(id: TerminalId, pid: u32, request: CreatePipe) -> ProcessInfo {
|
||||
}
|
||||
}
|
||||
|
||||
/// The waiter's result, and something dropped only after the exit message is
|
||||
/// sent (Unix starts the reader's drain by dropping a pipe writer).
|
||||
struct Waiter {
|
||||
exit: io::Result<Exit>,
|
||||
after: Box<dyn Send>,
|
||||
}
|
||||
|
||||
/// Registers a spawned pipe process with its actor, then runs the platform's
|
||||
/// reader and waiter. Both are started in that order, and the waiter last, so
|
||||
/// it is joined before the process is reaped.
|
||||
/// reader and waiter. If startup fails before the waiter starts, reap here.
|
||||
fn start_pipe(
|
||||
id: TerminalId,
|
||||
order: u64,
|
||||
@@ -166,7 +156,7 @@ fn start_pipe(
|
||||
process: Arc<Process>,
|
||||
cancel: Box<dyn Send>,
|
||||
reader: impl FnOnce(Sender<ActorMessage>) + Send + 'static,
|
||||
waiter: impl FnOnce() -> Waiter + Send + 'static,
|
||||
waiter: impl FnOnce(Sender<ActorMessage>) + Send + 'static,
|
||||
) -> Result<TerminalHandle> {
|
||||
let info = Arc::new(RwLock::new(new_pipe_info(id, process.pid(), request)));
|
||||
// Nothing is ever written to a pipe process; a disconnected queue
|
||||
@@ -213,11 +203,7 @@ fn start_pipe(
|
||||
let wait_actor_tx = actor_tx.clone();
|
||||
let waiter = thread::Builder::new()
|
||||
.name(format!("opencode-pty-wait-{id}"))
|
||||
.spawn(move || {
|
||||
let Waiter { exit, after } = waiter();
|
||||
let _ = wait_actor_tx.send(exit_message(exit));
|
||||
drop(after);
|
||||
})
|
||||
.spawn(move || waiter(wait_actor_tx))
|
||||
.context("failed to spawn terminal child waiter");
|
||||
let waiter = match waiter {
|
||||
Ok(waiter) => waiter,
|
||||
@@ -227,7 +213,6 @@ fn start_pipe(
|
||||
}
|
||||
};
|
||||
joins.push(waiter);
|
||||
let reap = Arc::clone(&process);
|
||||
Ok(TerminalHandle {
|
||||
order,
|
||||
mode: ProcessMode::Pipe,
|
||||
@@ -236,7 +221,6 @@ fn start_pipe(
|
||||
shutdown_tx: Mutex::new(Some(shutdown_tx)),
|
||||
killer: Mutex::new(Box::new(ProcessKiller(Arc::clone(&process)))),
|
||||
cancel: Mutex::new(Some(cancel)),
|
||||
reap: Mutex::new(Some(Box::new(move || reap.reap()))),
|
||||
process: Some(process),
|
||||
info,
|
||||
joins: Mutex::new(Some(joins)),
|
||||
|
||||
@@ -3,10 +3,8 @@
|
||||
//! The child runs in its own process group with stdin on `/dev/null`. Three
|
||||
//! choices keep the daemon safe from what the child leaves behind:
|
||||
//!
|
||||
//! - The waiter observes the exit with `WNOWAIT` and leaves the child as a
|
||||
//! zombie until shutdown. While the zombie exists, its PID and process group
|
||||
//! ID cannot be reused, so killing the group can never hit an unrelated
|
||||
//! process, even long after the exit.
|
||||
//! - The waiter observes the exit with `WNOWAIT` so it can signal a failed
|
||||
//! command's group while the leader still reserves its ID, then reaps it.
|
||||
//! - The reader polls a cancel pipe as well as the output pipe, so shutdown
|
||||
//! never waits on a pipe that a descendant which left the process group
|
||||
//! still holds open.
|
||||
@@ -18,15 +16,16 @@ use std::io::{self, PipeReader, PipeWriter, Read};
|
||||
use std::os::fd::AsFd;
|
||||
use std::os::unix::fs::OpenOptionsExt;
|
||||
use std::os::unix::process::CommandExt;
|
||||
use std::process::{Command, Stdio};
|
||||
use std::process::{Child, Command, Stdio};
|
||||
use std::sync::{Arc, Mutex, PoisonError, RwLock};
|
||||
use std::time::Instant;
|
||||
use std::time::{Duration, Instant};
|
||||
|
||||
use anyhow::{Context, Result, bail};
|
||||
use anyhow::{Context, Result};
|
||||
use crossbeam_utils::sync::WaitGroup;
|
||||
use nix::errno::Errno;
|
||||
use nix::poll::{PollFd, PollFlags, PollTimeout, poll};
|
||||
|
||||
use super::{DRAIN_AFTER_EXIT, Exit, OutputSink, start_pipe};
|
||||
use super::{DRAIN_AFTER_EXIT, Exit, OutputSink, exit_message, start_pipe};
|
||||
use crate::service::{CreatePipe, ProcessSignal, TerminalHandle, TerminalId};
|
||||
|
||||
/// Serializes pipe creation against `spawn`. macOS has no `pipe2`, so std
|
||||
@@ -72,6 +71,7 @@ impl TerminalHandle {
|
||||
id: TerminalId,
|
||||
order: u64,
|
||||
request: CreatePipe,
|
||||
escalations: WaitGroup,
|
||||
) -> Result<Self> {
|
||||
let Pipes {
|
||||
output,
|
||||
@@ -121,12 +121,9 @@ impl TerminalHandle {
|
||||
drop(command);
|
||||
let process = Arc::new(Process {
|
||||
pid: child.id(),
|
||||
reaped: Mutex::new(false),
|
||||
child: Mutex::new(Some(child)),
|
||||
});
|
||||
// Dropping `Child` neither waits nor kills; `Process` reaps it.
|
||||
drop(child);
|
||||
|
||||
let pid = process.pid;
|
||||
start_pipe(
|
||||
id,
|
||||
order,
|
||||
@@ -134,10 +131,9 @@ impl TerminalHandle {
|
||||
Arc::clone(&process),
|
||||
Box::new(cancel_writer),
|
||||
move |actor| read_output(output, OutputSink::new(sink, actor), cancel, exited),
|
||||
move || super::Waiter {
|
||||
exit: wait_exit(pid),
|
||||
// Starts the reader's drain deadline, after the exit message.
|
||||
after: Box::new(exited_writer),
|
||||
move |actor| {
|
||||
let _ = actor.send(exit_message(process.wait(escalations)));
|
||||
drop(exited_writer); // start the reader's drain deadline
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -170,11 +166,11 @@ fn reset_signals() -> io::Result<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// A pipe child that stays a zombie after it exits, until `reap`.
|
||||
/// The PID is metadata. Only the live child under the lock can be signalled.
|
||||
#[derive(Debug)]
|
||||
pub(in crate::service) struct Process {
|
||||
pid: u32,
|
||||
reaped: Mutex<bool>,
|
||||
child: Mutex<Option<Child>>,
|
||||
}
|
||||
|
||||
impl Process {
|
||||
@@ -182,11 +178,31 @@ impl Process {
|
||||
self.pid
|
||||
}
|
||||
|
||||
fn wait(&self, escalations: WaitGroup) -> io::Result<Exit> {
|
||||
let exit = wait_exit(self.pid);
|
||||
// Like the old spawner, leave background processes alone on a signal
|
||||
// death (no numeric code). Only a non-zero exit code stops them.
|
||||
let failed = matches!(exit, Ok(Exit::Code(code)) if code != 0);
|
||||
let pgid = self.pid as libc::pid_t;
|
||||
if failed {
|
||||
// SAFETY: the unreaped leader still reserves its group ID.
|
||||
unsafe { libc::killpg(pgid, libc::SIGTERM) };
|
||||
}
|
||||
self.reap();
|
||||
if failed && unsafe { libc::killpg(pgid, 0) } == 0 {
|
||||
escalate(pgid, escalations);
|
||||
}
|
||||
exit
|
||||
}
|
||||
|
||||
/// Kills the whole process group. Never signals after `reap`, when the
|
||||
/// group ID may belong to someone else.
|
||||
pub(super) fn kill(&self) {
|
||||
let reaped = self.reaped.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if !*reaped && let Ok(pid) = i32::try_from(self.pid) {
|
||||
let child = self.child.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if child.is_some()
|
||||
&& !has_exited(self.pid)
|
||||
&& let Ok(pid) = i32::try_from(self.pid)
|
||||
{
|
||||
// SAFETY: the unreaped child keeps its PID and group ID reserved.
|
||||
// Signal the child directly too, in case it moved to another group.
|
||||
unsafe {
|
||||
@@ -196,17 +212,16 @@ impl Process {
|
||||
}
|
||||
}
|
||||
|
||||
/// Sends `signal` to the process group and the child. Allowed after the
|
||||
/// exit, to reach what is left of the group; refused after `reap`.
|
||||
/// Sends `signal` to the process group and the child until the waiter reaps it.
|
||||
pub(in crate::service) fn signal(&self, signal: ProcessSignal) -> Result<()> {
|
||||
let signal = match signal {
|
||||
ProcessSignal::Term => libc::SIGTERM,
|
||||
ProcessSignal::Int => libc::SIGINT,
|
||||
ProcessSignal::Kill => libc::SIGKILL,
|
||||
};
|
||||
let reaped = self.reaped.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if *reaped {
|
||||
bail!("process has been reaped");
|
||||
let child = self.child.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if child.is_none() || has_exited(self.pid) {
|
||||
return Ok(());
|
||||
}
|
||||
let pid = i32::try_from(self.pid).context("invalid pid")?;
|
||||
// SAFETY: the unreaped child keeps its PID and group ID reserved.
|
||||
@@ -216,24 +231,31 @@ impl Process {
|
||||
check_signal(unsafe { libc::kill(pid, signal) }, self.pid)
|
||||
}
|
||||
|
||||
/// Call only after the waiter has returned: kill the group first, so the
|
||||
/// child has exited and this does not block.
|
||||
/// Called by the waiter after observing exit, or after a startup failure
|
||||
/// has killed the child. Serialize waitpid with all client signals.
|
||||
pub(super) fn reap(&self) {
|
||||
let mut reaped = self.reaped.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if *reaped {
|
||||
return;
|
||||
let mut child = self.child.lock().unwrap_or_else(PoisonError::into_inner);
|
||||
if let Some(mut child) = child.take() {
|
||||
let _ = child.wait();
|
||||
}
|
||||
let Ok(pid) = i32::try_from(self.pid) else {
|
||||
return;
|
||||
};
|
||||
loop {
|
||||
// SAFETY: waits only for this daemon's own child.
|
||||
let result = unsafe { libc::waitpid(pid, std::ptr::null_mut(), 0) };
|
||||
if result != -1 || Errno::last() != Errno::EINTR {
|
||||
break;
|
||||
}
|
||||
}
|
||||
*reaped = true;
|
||||
}
|
||||
}
|
||||
|
||||
/// Like the spawner after Node reaped its child, escalate by numeric PGID.
|
||||
/// The PGID stays reserved while the original group has members. If it empties
|
||||
/// during the grace, killpg gives ESRCH unless the number has been recycled.
|
||||
fn escalate(pgid: libc::pid_t, pending: WaitGroup) {
|
||||
let deadline = Instant::now() + Duration::from_secs(3);
|
||||
if let Err(error) = std::thread::Builder::new()
|
||||
.name(format!("opencode-pty-escalate-{pgid}"))
|
||||
.spawn(move || {
|
||||
std::thread::sleep(deadline.saturating_duration_since(Instant::now()));
|
||||
unsafe { libc::killpg(pgid, libc::SIGKILL) };
|
||||
drop(pending);
|
||||
})
|
||||
{
|
||||
eprintln!("process group {pgid}: cannot schedule SIGKILL: {error}");
|
||||
unsafe { libc::killpg(pgid, libc::SIGKILL) };
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
@@ -54,14 +54,14 @@ use windows_sys::Win32::System::Threading::{
|
||||
WaitForSingleObject,
|
||||
};
|
||||
|
||||
use super::{DRAIN_AFTER_EXIT, Exit, OutputSink, Waiter, start_pipe};
|
||||
use super::{DRAIN_AFTER_EXIT, Exit, OutputSink, exit_message, start_pipe};
|
||||
use crate::service::{CreatePipe, ProcessSignal, TerminalHandle, TerminalId};
|
||||
use crate::transport::retained::Retained;
|
||||
use crate::transport::windows::{event, owned_handle, security::PrivateSecurity, wide};
|
||||
|
||||
/// Cancel is first so a pipe that is always readable cannot starve it.
|
||||
const CANCEL_READY: u32 = WAIT_OBJECT_0;
|
||||
/// The read event, and the process handle after it.
|
||||
/// The read event, and the exit event after it.
|
||||
const READ_READY: u32 = WAIT_OBJECT_0 + 1;
|
||||
const PROCESS_READY: u32 = WAIT_OBJECT_0 + 2;
|
||||
|
||||
@@ -81,10 +81,11 @@ impl TerminalHandle {
|
||||
// clean up; the reader is the file's only writer.
|
||||
let sink = open_output(&request.output_path)?;
|
||||
let job = Job::new(id);
|
||||
let cancel = CancelOnDrop::new()?;
|
||||
let cancel = SignalOnDrop::new()?;
|
||||
let exited = SignalOnDrop::new()?;
|
||||
let process = Arc::new(spawn(id, &request, job, client)?);
|
||||
let reader_cancel = Arc::clone(&cancel.0);
|
||||
let reader_process = Arc::clone(&process);
|
||||
let reader_exited = Arc::clone(&exited.0);
|
||||
start_pipe(
|
||||
id,
|
||||
order,
|
||||
@@ -96,12 +97,12 @@ impl TerminalHandle {
|
||||
server,
|
||||
OutputSink::new(sink, actor),
|
||||
reader_cancel,
|
||||
reader_process,
|
||||
reader_exited,
|
||||
)
|
||||
},
|
||||
move || Waiter {
|
||||
exit: wait_exit(process),
|
||||
after: Box::new(()),
|
||||
move |actor| {
|
||||
let _ = actor.send(exit_message(wait_exit(&process)));
|
||||
drop(exited);
|
||||
},
|
||||
)
|
||||
}
|
||||
@@ -117,7 +118,7 @@ pub(in crate::service) struct Process {
|
||||
|
||||
#[derive(Debug)]
|
||||
struct State {
|
||||
/// Taken by `reap`, which closes both handles.
|
||||
/// Taken by the waiter at exit, or by `reap` if startup failed.
|
||||
handles: Option<Handles>,
|
||||
/// The signal recorded by `kill`/`signal` before terminating the tree.
|
||||
killed: Option<&'static str>,
|
||||
@@ -126,7 +127,7 @@ struct State {
|
||||
#[derive(Debug)]
|
||||
struct Handles {
|
||||
process: Arc<OwnedHandle>,
|
||||
job: Option<OwnedHandle>,
|
||||
job: Option<Job>,
|
||||
}
|
||||
|
||||
impl Process {
|
||||
@@ -138,7 +139,7 @@ impl Process {
|
||||
self.state.lock().unwrap_or_else(PoisonError::into_inner)
|
||||
}
|
||||
|
||||
/// The process object, kept open until `reap` so its PID cannot be reused.
|
||||
/// Borrows the process object for the wait without holding the state lock.
|
||||
fn process_handle(&self) -> Option<Arc<OwnedHandle>> {
|
||||
self.lock()
|
||||
.handles
|
||||
@@ -156,8 +157,6 @@ impl Process {
|
||||
}
|
||||
|
||||
/// Hard-kills the process tree and records the signal the client will see.
|
||||
/// Allowed after the exit, to reach what is left of the job; refused after
|
||||
/// `reap`.
|
||||
pub(in crate::service) fn signal(&self, signal: ProcessSignal) -> Result<()> {
|
||||
let name = match signal {
|
||||
ProcessSignal::Term => "SIGTERM",
|
||||
@@ -166,33 +165,27 @@ impl Process {
|
||||
};
|
||||
let mut state = self.lock();
|
||||
let Some(handles) = record_kill(&mut state, name) else {
|
||||
bail!("process has been reaped");
|
||||
return Ok(());
|
||||
};
|
||||
terminate(handles).context("failed to signal process")
|
||||
}
|
||||
|
||||
/// Call only after the waiter has returned: closes the process and job
|
||||
/// handles. Closing the job alone kills anything still in it.
|
||||
/// Releases a partially started command whose waiter never started.
|
||||
pub(super) fn reap(&self) {
|
||||
self.lock().handles.take();
|
||||
}
|
||||
|
||||
fn take_signal(&self) -> Option<&'static str> {
|
||||
self.lock().killed.take()
|
||||
}
|
||||
}
|
||||
|
||||
/// Records the signal while the process still runs, so a process that exited on
|
||||
/// its own keeps its exit code, and returns the handles, or `None` after
|
||||
/// `reap`.
|
||||
/// A process that exited on its own keeps its exit code and its waiter's
|
||||
/// cleanup policy, even if a signal races the waiter.
|
||||
fn record_kill<'a>(state: &'a mut State, name: &'static str) -> Option<&'a Handles> {
|
||||
let handles = state.handles.as_ref()?;
|
||||
// SAFETY: the state lock keeps the process handle open.
|
||||
if !is_signalled(&handles.process) {
|
||||
// Termination is asynchronous: the first signal that reached the
|
||||
// running process is the one the client should see.
|
||||
state.killed.get_or_insert(name);
|
||||
if is_signalled(&handles.process) {
|
||||
return None;
|
||||
}
|
||||
// Termination is asynchronous: report the first signal.
|
||||
state.killed.get_or_insert(name);
|
||||
Some(handles)
|
||||
}
|
||||
|
||||
@@ -201,7 +194,7 @@ fn terminate(handles: &Handles) -> io::Result<()> {
|
||||
// SAFETY: the handles stay open while they are borrowed here.
|
||||
let terminated = unsafe {
|
||||
match &handles.job {
|
||||
Some(job) => TerminateJobObject(job.as_raw_handle(), 1),
|
||||
Some(job) => TerminateJobObject(job.handle(), 1),
|
||||
None => TerminateProcess(handles.process.as_raw_handle(), 1),
|
||||
}
|
||||
};
|
||||
@@ -247,7 +240,7 @@ fn spawn(
|
||||
state: Mutex::new(State {
|
||||
handles: Some(Handles {
|
||||
process: Arc::new(created.process),
|
||||
job: job.map(|job| job.0),
|
||||
job,
|
||||
}),
|
||||
killed: None,
|
||||
}),
|
||||
@@ -319,7 +312,7 @@ fn create_process(
|
||||
|
||||
/// Waits for the child to exit, then reports the exit code, or the signal the
|
||||
/// daemon sent when it terminated the tree.
|
||||
fn wait_exit(process: Arc<Process>) -> io::Result<Exit> {
|
||||
fn wait_exit(process: &Process) -> io::Result<Exit> {
|
||||
let Some(handle) = process.process_handle() else {
|
||||
return Err(io::Error::other("process has been reaped"));
|
||||
};
|
||||
@@ -327,27 +320,34 @@ fn wait_exit(process: Arc<Process>) -> io::Result<Exit> {
|
||||
if unsafe { WaitForSingleObject(handle.as_raw_handle(), INFINITE) } != WAIT_OBJECT_0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
let mut state = process.lock();
|
||||
let handles = state.handles.take();
|
||||
let mut code = 0;
|
||||
// SAFETY: a signalled process object has a final exit code.
|
||||
if unsafe { GetExitCodeProcess(handle.as_raw_handle(), &mut code) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Ok(match process.take_signal() {
|
||||
if let Some(job) = handles.and_then(|handles| handles.job)
|
||||
&& let Err(error) = job.finish(code != 0 && state.killed.is_none())
|
||||
{
|
||||
eprintln!("pipe process {}: job cleanup failed: {error}", process.pid);
|
||||
}
|
||||
Ok(match state.killed.take() {
|
||||
Some(name) => Exit::Signal(name.to_string()),
|
||||
None => Exit::Code(code),
|
||||
})
|
||||
}
|
||||
|
||||
/// Sets the reader's cancel event when dropped.
|
||||
struct CancelOnDrop(Arc<OwnedHandle>);
|
||||
/// Wakes the reader on shutdown or once the waiter has published the exit.
|
||||
struct SignalOnDrop(Arc<OwnedHandle>);
|
||||
|
||||
impl CancelOnDrop {
|
||||
impl SignalOnDrop {
|
||||
fn new() -> io::Result<Self> {
|
||||
event().map(|event| Self(Arc::new(event)))
|
||||
}
|
||||
}
|
||||
|
||||
impl Drop for CancelOnDrop {
|
||||
impl Drop for SignalOnDrop {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the shared event stays open through the call.
|
||||
unsafe {
|
||||
@@ -477,12 +477,9 @@ fn read_output(
|
||||
pipe: OwnedHandle,
|
||||
sink: OutputSink,
|
||||
cancel: Arc<OwnedHandle>,
|
||||
process: Arc<Process>,
|
||||
exit_event: Arc<OwnedHandle>,
|
||||
) {
|
||||
let mut sink = sink;
|
||||
let Some(process_object) = process.process_handle() else {
|
||||
return;
|
||||
};
|
||||
let mut read = match Read::new(pipe) {
|
||||
Ok(read) => read,
|
||||
Err(error) => {
|
||||
@@ -491,7 +488,7 @@ fn read_output(
|
||||
}
|
||||
};
|
||||
// The process may have exited before the reader started.
|
||||
let mut exited = is_signalled(&process_object);
|
||||
let mut exited = is_signalled(&exit_event);
|
||||
let mut deadline = exited.then(|| Instant::now() + DRAIN_AFTER_EXIT);
|
||||
loop {
|
||||
// Cancellation and the exit win over output, so a descendant that
|
||||
@@ -500,7 +497,7 @@ fn read_output(
|
||||
// Like Unix, shutdown is not an EOF the actor needs to observe.
|
||||
return;
|
||||
}
|
||||
if !exited && is_signalled(&process_object) {
|
||||
if !exited && is_signalled(&exit_event) {
|
||||
exited = true;
|
||||
deadline = Some(Instant::now() + DRAIN_AFTER_EXIT);
|
||||
}
|
||||
@@ -524,7 +521,7 @@ fn read_output(
|
||||
let handles = [
|
||||
cancel.as_raw_handle(),
|
||||
read.event(),
|
||||
process_object.as_raw_handle(),
|
||||
exit_event.as_raw_handle(),
|
||||
];
|
||||
// Once the exit is seen, stop waiting on its signalled handle.
|
||||
let count = if exited { 2 } else { 3 };
|
||||
@@ -654,21 +651,30 @@ fn output_pipe() -> Result<OutputPipe> {
|
||||
|
||||
/// A kill-on-close job: terminating it kills every descendant, and a crashed
|
||||
/// daemon closes it and kills them too.
|
||||
#[derive(Debug)]
|
||||
struct Job(OwnedHandle);
|
||||
|
||||
impl Job {
|
||||
fn new(id: TerminalId) -> Option<Self> {
|
||||
// SAFETY: an unnamed job with default attributes, adopted on success.
|
||||
let job = match owned_handle(unsafe { CreateJobObjectW(null(), null()) }) {
|
||||
Ok(job) => job,
|
||||
Ok(job) => Self(job),
|
||||
Err(error) => {
|
||||
warn_no_job(id, &error);
|
||||
return None;
|
||||
}
|
||||
};
|
||||
if let Err(error) = job.set_limits(JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE) {
|
||||
warn_no_job(id, &error);
|
||||
return None;
|
||||
}
|
||||
Some(job)
|
||||
}
|
||||
|
||||
fn set_limits(&self, flags: u32) -> io::Result<()> {
|
||||
let limits = JOBOBJECT_EXTENDED_LIMIT_INFORMATION {
|
||||
BasicLimitInformation: JOBOBJECT_BASIC_LIMIT_INFORMATION {
|
||||
LimitFlags: JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE,
|
||||
LimitFlags: flags,
|
||||
..Default::default()
|
||||
},
|
||||
..Default::default()
|
||||
@@ -677,22 +683,31 @@ impl Job {
|
||||
// the extended-information class.
|
||||
if unsafe {
|
||||
SetInformationJobObject(
|
||||
job.as_raw_handle(),
|
||||
self.handle(),
|
||||
JobObjectExtendedLimitInformation,
|
||||
(&raw const limits).cast(),
|
||||
size_of_val(&limits) as u32,
|
||||
)
|
||||
} == 0
|
||||
{
|
||||
warn_no_job(id, &io::Error::last_os_error());
|
||||
return None;
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
Some(Self(job))
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn handle(&self) -> HANDLE {
|
||||
self.0.as_raw_handle()
|
||||
}
|
||||
|
||||
fn finish(self, failed: bool) -> io::Result<()> {
|
||||
// No console and no SIGTERM grace. If termination fails, closing the
|
||||
// still-armed job is the fallback. For a successful command disarm
|
||||
// kill-on-close before releasing the handle.
|
||||
if failed && unsafe { TerminateJobObject(self.handle(), 1) } == 0 {
|
||||
return Err(io::Error::last_os_error());
|
||||
}
|
||||
self.set_limits(0)
|
||||
}
|
||||
}
|
||||
|
||||
fn warn_no_job(id: TerminalId, error: &io::Error) {
|
||||
@@ -1071,10 +1086,10 @@ mod tests {
|
||||
assert!(!is_signalled(&process.process_handle().unwrap()));
|
||||
process.signal(ProcessSignal::Kill).unwrap();
|
||||
assert!(matches!(
|
||||
wait_exit(Arc::clone(&process)).unwrap(),
|
||||
wait_exit(&process).unwrap(),
|
||||
Exit::Signal(name) if name == "SIGKILL"
|
||||
));
|
||||
process.reap();
|
||||
assert!(process.process_handle().is_none());
|
||||
}
|
||||
|
||||
/// A duplicate of `job` with only query access: joining it needs
|
||||
@@ -1110,7 +1125,7 @@ mod tests {
|
||||
let OutputPipe { client, .. } = output_pipe().unwrap();
|
||||
let process = Arc::new(spawn(2, &request, Some(restricted), client).unwrap());
|
||||
let mut in_job = 0;
|
||||
// SAFETY: the process handle stays open until `reap` and the job is live.
|
||||
// SAFETY: the process and job handles stay open through this call.
|
||||
assert_ne!(
|
||||
unsafe {
|
||||
IsProcessInJob(
|
||||
@@ -1122,10 +1137,7 @@ mod tests {
|
||||
0
|
||||
);
|
||||
assert_eq!(in_job, 0, "the restricted job must have been refused");
|
||||
assert!(matches!(
|
||||
wait_exit(Arc::clone(&process)).unwrap(),
|
||||
Exit::Code(5)
|
||||
));
|
||||
process.reap();
|
||||
assert!(matches!(wait_exit(&process).unwrap(), Exit::Code(5)));
|
||||
assert!(process.process_handle().is_none());
|
||||
}
|
||||
}
|
||||
|
||||
@@ -52,7 +52,7 @@ impl Daemon {
|
||||
}
|
||||
thread::sleep(Duration::from_millis(10));
|
||||
};
|
||||
assert_eq!(registration.protocol, 8);
|
||||
assert_eq!(registration.protocol, 9);
|
||||
Self {
|
||||
child,
|
||||
root,
|
||||
@@ -317,7 +317,7 @@ fn rename_is_served() {
|
||||
assert!(daemon.registration.features.is_empty());
|
||||
assert!(matches!(
|
||||
daemon.request(Request::Ping),
|
||||
Response::Pong { protocol: 8, features, .. } if features.is_empty()
|
||||
Response::Pong { protocol: 9, features, .. } if features.is_empty()
|
||||
));
|
||||
let (owner, response) = daemon.own(None);
|
||||
assert!(matches!(response, Response::Owned));
|
||||
|
||||
@@ -82,8 +82,8 @@ fn alive(pid: i32) -> bool {
|
||||
unsafe { libc::kill(pid, 0) == 0 }
|
||||
}
|
||||
|
||||
fn wait_dead(pid: i32) {
|
||||
let deadline = Instant::now() + Duration::from_secs(5);
|
||||
fn wait_dead(pid: i32, timeout: Duration) {
|
||||
let deadline = Instant::now() + timeout;
|
||||
while alive(pid) {
|
||||
assert!(Instant::now() < deadline, "process {pid} is still running");
|
||||
std::thread::sleep(Duration::from_millis(10));
|
||||
@@ -150,11 +150,16 @@ fn sigpipe_is_not_inherited_as_ignored() {
|
||||
#[test]
|
||||
fn reports_the_signal_that_ended_the_process() {
|
||||
let service = TerminalService::default();
|
||||
let (info, file) = start(&service, "kill -TERM $$");
|
||||
let (info, file) = start(
|
||||
&service,
|
||||
"sleep 30 >/dev/null 2>&1 & echo $!; kill -TERM $$",
|
||||
);
|
||||
let finished = run(&service, info.id, &file);
|
||||
let sleeper = KillOnDrop(finished.output.trim().parse().unwrap());
|
||||
assert_eq!(finished.exit.exit_code, None);
|
||||
assert_eq!(finished.exit.signal.as_deref(), Some("SIGTERM"));
|
||||
service.terminate(info.id).unwrap();
|
||||
assert!(alive(sleeper.0));
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -185,11 +190,15 @@ fn a_descendant_holding_the_pipe_delays_the_exit_by_at_most_the_drain() {
|
||||
"{:?}",
|
||||
finished.elapsed
|
||||
);
|
||||
let sleeper: i32 = finished.output.lines().next().unwrap().parse().unwrap();
|
||||
assert!(alive(sleeper));
|
||||
// Terminate kills the rest of the process group.
|
||||
let sleeper = KillOnDrop(finished.output.lines().next().unwrap().parse().unwrap());
|
||||
assert!(alive(sleeper.0));
|
||||
// The leader has already been reaped, but its record can still be read.
|
||||
assert!(!alive(info.pid.unwrap() as i32));
|
||||
assert_eq!(service.list(ProcessMode::Pipe).unwrap()[0].id, info.id);
|
||||
service.signal(info.id, ProcessSignal::Kill).unwrap();
|
||||
service.terminate(info.id).unwrap();
|
||||
wait_dead(sleeper);
|
||||
assert!(service.list(ProcessMode::Pipe).unwrap().is_empty());
|
||||
assert!(alive(sleeper.0));
|
||||
}
|
||||
|
||||
/// Kills a test descendant even when an assertion fails first.
|
||||
@@ -218,17 +227,15 @@ fn terminate_does_not_wait_for_a_descendant_that_left_the_group() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_exited_process_is_kept_until_terminate() {
|
||||
fn a_failed_command_stops_its_background_processes_at_exit() {
|
||||
let service = TerminalService::default();
|
||||
let (info, file) = start(&service, "exit 0");
|
||||
run(&service, info.id, &file);
|
||||
let pid = info.pid.unwrap() as i32;
|
||||
// The zombie keeps the PID and process group reserved.
|
||||
assert!(alive(pid));
|
||||
assert_eq!(service.list(ProcessMode::Pipe).unwrap().len(), 1);
|
||||
service.terminate(info.id).unwrap();
|
||||
assert!(!alive(pid));
|
||||
assert!(service.list(ProcessMode::Pipe).unwrap().is_empty());
|
||||
let (info, file) = start(&service, "sleep 30 & echo $!; exit 3");
|
||||
let finished = run(&service, info.id, &file);
|
||||
assert_eq!(finished.exit.exit_code, Some(3));
|
||||
wait_dead(
|
||||
finished.output.trim().parse().unwrap(),
|
||||
Duration::from_secs(1),
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
@@ -237,7 +244,7 @@ fn terminate_kills_the_process_group() {
|
||||
let (info, file) = start(&service, "sleep 30 & echo $!; wait");
|
||||
let child: i32 = first_line(&file).parse().unwrap();
|
||||
service.terminate(info.id).unwrap();
|
||||
wait_dead(child);
|
||||
wait_dead(child, Duration::from_secs(5));
|
||||
assert!(!alive(info.pid.unwrap() as i32));
|
||||
}
|
||||
|
||||
@@ -537,7 +544,7 @@ fn signal_stops_a_process_and_keeps_its_record() {
|
||||
signal: Some("SIGTERM".into())
|
||||
}
|
||||
);
|
||||
// Nothing is left in the group (macOS reports ESRCH); still fine.
|
||||
// While its record exists, a late signal succeeds.
|
||||
service.signal(info.id, ProcessSignal::Kill).unwrap();
|
||||
service.terminate(info.id).unwrap();
|
||||
assert!(service.signal(info.id, ProcessSignal::Kill).is_err());
|
||||
@@ -574,7 +581,7 @@ fn signal_reaches_a_backgrounded_child_in_the_group() {
|
||||
let child: i32 = first_line(&file).parse().unwrap();
|
||||
// Not SIGINT: a non-interactive shell starts background jobs ignoring it.
|
||||
service.signal(info.id, ProcessSignal::Term).unwrap();
|
||||
wait_dead(child);
|
||||
wait_dead(child, Duration::from_secs(5));
|
||||
let exit = service.wait(info.id).unwrap().recv().unwrap();
|
||||
assert!(exit.signal.is_some() || exit.exit_code.is_some());
|
||||
assert_eq!(service.list(ProcessMode::Pipe).unwrap().len(), 1);
|
||||
@@ -582,15 +589,20 @@ fn signal_reaches_a_backgrounded_child_in_the_group() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signal_after_exit_reaches_leftover_group_members() {
|
||||
fn a_failed_commands_background_process_that_ignores_term_is_killed() {
|
||||
let service = TerminalService::default();
|
||||
let (info, file) = start(&service, "sleep 30 & echo $!");
|
||||
let exit = run(&service, info.id, &file);
|
||||
let sleeper = KillOnDrop(exit.output.trim().parse().unwrap());
|
||||
assert!(alive(sleeper.0));
|
||||
service.signal(info.id, ProcessSignal::Kill).unwrap();
|
||||
wait_dead(sleeper.0);
|
||||
// The sleeper inherits SIG_IGN even if the leader exits before it execs.
|
||||
let (info, file) = start(
|
||||
&service,
|
||||
"trap '' TERM; sleep 30 >/dev/null 2>&1 & echo $!; exit 1",
|
||||
);
|
||||
let finished = run(&service, info.id, &file);
|
||||
let pid = finished.output.trim().parse().unwrap();
|
||||
assert!(!alive(info.pid.unwrap() as i32));
|
||||
service.terminate(info.id).unwrap();
|
||||
// Forgetting the record neither kills the sleeper nor cancels escalation.
|
||||
assert!(alive(pid));
|
||||
wait_dead(pid, Duration::from_secs(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -21,7 +21,7 @@ use opencode_pty::service::{
|
||||
};
|
||||
use windows_sys::Win32::Foundation::{ERROR_PRIVILEGE_NOT_HELD, WAIT_OBJECT_0};
|
||||
use windows_sys::Win32::System::Threading::{
|
||||
OpenProcess, PROCESS_SYNCHRONIZE, WaitForSingleObject,
|
||||
OpenProcess, PROCESS_SYNCHRONIZE, PROCESS_TERMINATE, TerminateProcess, WaitForSingleObject,
|
||||
};
|
||||
|
||||
/// A unique temporary path, removed when dropped even if a test fails.
|
||||
@@ -188,6 +188,23 @@ fn wait_dead(pid: u32) {
|
||||
}
|
||||
}
|
||||
|
||||
/// Kills a test descendant even when an assertion fails first.
|
||||
struct KillOnDrop(u32);
|
||||
|
||||
impl Drop for KillOnDrop {
|
||||
fn drop(&mut self) {
|
||||
// SAFETY: the PID belongs to this test's own descendant.
|
||||
let handle = unsafe { OpenProcess(PROCESS_TERMINATE, 0, self.0) };
|
||||
if handle.is_null() {
|
||||
return;
|
||||
}
|
||||
// SAFETY: OpenProcess returned a new, uniquely owned handle.
|
||||
let handle = unsafe { OwnedHandle::from_raw_handle(handle) };
|
||||
// SAFETY: the owned handle has PROCESS_TERMINATE access and is still valid.
|
||||
unsafe { TerminateProcess(handle.as_raw_handle(), 1) };
|
||||
}
|
||||
}
|
||||
|
||||
fn newlines(bytes: &[u8]) -> u64 {
|
||||
bytes.iter().filter(|&&byte| byte == b'\n').count() as u64
|
||||
}
|
||||
@@ -223,7 +240,7 @@ impl GrandchildTree {
|
||||
}
|
||||
}
|
||||
|
||||
fn grandchild_tree(name: &str, keep_parent_alive: bool) -> GrandchildTree {
|
||||
fn grandchild_tree(name: &str, exit_code: Option<u32>) -> GrandchildTree {
|
||||
let pid_file = TempPath::new(&format!("{name}-pid"));
|
||||
let inner = Script::powershell(
|
||||
&format!("{name}-grandchild"),
|
||||
@@ -242,7 +259,14 @@ fn grandchild_tree(name: &str, keep_parent_alive: bool) -> GrandchildTree {
|
||||
inner.0.0.display()
|
||||
),
|
||||
];
|
||||
if keep_parent_alive {
|
||||
if let Some(code) = exit_code {
|
||||
lines.extend([
|
||||
":wait".to_string(),
|
||||
format!("if exist \"{}\" exit /b {code}", pid_file.0.display()),
|
||||
"ping -n 2 127.0.0.1 >nul".to_string(),
|
||||
"goto wait".to_string(),
|
||||
]);
|
||||
} else {
|
||||
lines.push("ping -n 60 127.0.0.1".to_string());
|
||||
}
|
||||
GrandchildTree {
|
||||
@@ -534,7 +558,7 @@ fn signal_stops_a_process_and_keeps_its_record() {
|
||||
signal: Some("SIGTERM".into())
|
||||
}
|
||||
);
|
||||
// What is left of the job is killed again without an error.
|
||||
// A late signal succeeds while the record is still listed.
|
||||
service.signal(info.id, ProcessSignal::Kill).unwrap();
|
||||
service.terminate(info.id).unwrap();
|
||||
assert!(service.signal(info.id, ProcessSignal::Kill).is_err());
|
||||
@@ -543,7 +567,7 @@ fn signal_stops_a_process_and_keeps_its_record() {
|
||||
#[test]
|
||||
fn signal_reaches_a_grandchild_in_the_job() {
|
||||
let service = TerminalService::default();
|
||||
let tree = grandchild_tree("grandchild", true);
|
||||
let tree = grandchild_tree("grandchild", None);
|
||||
let (info, _file) = tree.start(&service);
|
||||
let grandchild = read_pid(&tree.pid_file.0);
|
||||
assert!(alive(grandchild));
|
||||
@@ -557,7 +581,7 @@ fn signal_reaches_a_grandchild_in_the_job() {
|
||||
#[test]
|
||||
fn terminate_does_not_hang_on_a_grandchild() {
|
||||
let service = TerminalService::default();
|
||||
let tree = grandchild_tree("terminate", true);
|
||||
let tree = grandchild_tree("terminate", None);
|
||||
let (info, _file) = tree.start(&service);
|
||||
let grandchild = read_pid(&tree.pid_file.0);
|
||||
assert!(alive(grandchild));
|
||||
@@ -582,8 +606,9 @@ fn a_noisy_grandchild_still_exits_after_the_drain() {
|
||||
# Prove the pipe is live before the parent exits.
|
||||
[Console]::Out.Write('x')
|
||||
[Console]::Out.Flush()
|
||||
[System.IO.File]::WriteAllText('{}', 'started')
|
||||
while ($true) {{
|
||||
$marker = '{}'
|
||||
[System.IO.File]::WriteAllText($marker, "$PID")
|
||||
while ([System.IO.File]::Exists($marker)) {{
|
||||
[Console]::Out.Write('x')
|
||||
}}
|
||||
"#,
|
||||
@@ -609,6 +634,7 @@ fn a_noisy_grandchild_still_exits_after_the_drain() {
|
||||
],
|
||||
);
|
||||
let (info, file) = start(&service, |file| cmd(&outer.0.display().to_string(), file));
|
||||
let _grandchild = KillOnDrop(read_pid(&marker.0));
|
||||
let finished = run(&service, info.id, &file);
|
||||
assert_eq!(finished.exit.exit_code, Some(0));
|
||||
assert!(
|
||||
@@ -620,11 +646,11 @@ fn a_noisy_grandchild_still_exits_after_the_drain() {
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn signal_after_a_normal_exit_kills_a_leftover_grandchild() {
|
||||
fn signal_and_terminate_after_a_successful_exit_spare_the_grandchild() {
|
||||
let service = TerminalService::default();
|
||||
let tree = grandchild_tree("leftover", false);
|
||||
let tree = grandchild_tree("leftover", Some(0));
|
||||
let (info, _file) = tree.start(&service);
|
||||
let grandchild = read_pid(&tree.pid_file.0);
|
||||
let grandchild = KillOnDrop(read_pid(&tree.pid_file.0));
|
||||
// A descendant holds the pipe, so the exit waits for at most the drain.
|
||||
let started = Instant::now();
|
||||
let exit = service.wait(info.id).unwrap().recv().unwrap();
|
||||
@@ -636,7 +662,7 @@ fn signal_after_a_normal_exit_kills_a_leftover_grandchild() {
|
||||
assert_eq!(exit.exit_code, Some(0));
|
||||
assert_eq!(exit.signal, None);
|
||||
// The process keeps its record after the exit; the grandchild still runs.
|
||||
assert!(alive(grandchild));
|
||||
assert!(alive(grandchild.0));
|
||||
assert_eq!(
|
||||
service.get(info.id).unwrap().lifecycle,
|
||||
TerminalLifecycle::Exited {
|
||||
@@ -646,9 +672,23 @@ fn signal_after_a_normal_exit_kills_a_leftover_grandchild() {
|
||||
);
|
||||
assert_eq!(service.list(ProcessMode::Pipe).unwrap().len(), 1);
|
||||
service.signal(info.id, ProcessSignal::Kill).unwrap();
|
||||
wait_dead(grandchild);
|
||||
service.terminate(info.id).unwrap();
|
||||
assert!(service.list(ProcessMode::Pipe).unwrap().is_empty());
|
||||
let pid = grandchild.0;
|
||||
assert!(alive(pid));
|
||||
drop(grandchild);
|
||||
wait_dead(pid);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_exit_terminates_the_grandchild() {
|
||||
let service = TerminalService::default();
|
||||
let tree = grandchild_tree("failed", Some(3));
|
||||
let (info, _file) = tree.start(&service);
|
||||
let grandchild = read_pid(&tree.pid_file.0);
|
||||
let exit = service.wait(info.id).unwrap().recv().unwrap();
|
||||
assert_eq!(exit.exit_code, Some(3));
|
||||
wait_dead(grandchild);
|
||||
}
|
||||
|
||||
#[test]
|
||||
|
||||
@@ -53,7 +53,7 @@ fn daemon_client_read_rows_roundtrip() {
|
||||
);
|
||||
|
||||
let registration = opencode_pty::daemon::read_registration(&directory).unwrap();
|
||||
assert_eq!(registration.protocol, 8);
|
||||
assert_eq!(registration.protocol, 9);
|
||||
// Exercise omitted rows independently of the Rust client's null encoding.
|
||||
let mut stream = std::os::unix::net::UnixStream::connect(registration.socket).unwrap();
|
||||
write_frame(
|
||||
|
||||
@@ -196,7 +196,7 @@ fn registration(child: &mut Child, directory: &Path) -> Registration {
|
||||
if let Ok(registration) = opencode_pty::daemon::read_registration(directory)
|
||||
&& registration.pid == child.id()
|
||||
{
|
||||
assert_eq!(registration.protocol, 8);
|
||||
assert_eq!(registration.protocol, 9);
|
||||
assert_eq!(
|
||||
registration.socket,
|
||||
PathBuf::from(format!(
|
||||
@@ -658,7 +658,7 @@ fn observer_disconnect_and_control_input_preserve_independent_terminals() {
|
||||
matches!(daemon.request(Request::List { mode: ProcessMode::Pty }), Response::Processes { processes: terminals } if terminals.len() == 2)
|
||||
);
|
||||
assert!(
|
||||
matches!(daemon.request(Request::Ping), Response::Pong { instance_id, pid, protocol: 8, .. }
|
||||
matches!(daemon.request(Request::Ping), Response::Pong { instance_id, pid, protocol: 9, .. }
|
||||
if instance_id == daemon.registration.instance_id && pid == daemon.registration.pid)
|
||||
);
|
||||
assert!(matches!(daemon.own(None).1, Response::Error { .. }));
|
||||
|
||||
Reference in New Issue
Block a user