Skip to content

Commit d11fc8d

Browse files
committed
refactor(sandbox): manage boundary exec child ownership
Route RFC 0012 boundary exec children through ManagedChild so spawn registration, waiting, cleanup, and lost-child diagnostics remain structurally coupled. Closes #3154 Signed-off-by: Evan Lezar <[email protected]>
1 parent f23a6d5 commit d11fc8d

2 files changed

Lines changed: 53 additions & 70 deletions

File tree

‎crates/openshell-sandbox/src/boundary_exec.rs‎

Lines changed: 31 additions & 42 deletions
Original file line numberDiff line numberDiff line change
@@ -5,7 +5,7 @@
55
66
use std::collections::HashMap;
77
use std::os::fd::{AsRawFd, OwnedFd};
8-
use std::process::{Child, Command, Stdio};
8+
use std::process::{Command, Stdio};
99
use std::sync::Arc;
1010

1111
use async_trait::async_trait;
@@ -142,16 +142,20 @@ impl LocalBoundaryExec {
142142
)
143143
.map_err(|error| BackendError::Process(error.to_string()))?;
144144
#[cfg(target_os = "linux")]
145-
let mut child_registry = crate::managed_children::lock();
146-
#[cfg(target_os = "linux")]
147-
let mut child =
148-
crate::process::spawn_std_command_with_workload_launcher(&self.launcher, command)
149-
.map_err(|error| BackendError::Process(error.to_string()))?;
145+
let mut child = crate::managed_children::ManagedChild::spawn(
146+
|| crate::process::spawn_std_command_with_workload_launcher(&self.launcher, command),
147+
|child| Some(child.id()),
148+
)
149+
.map_err(|error| BackendError::Process(error.to_string()))?;
150150
#[cfg(not(target_os = "linux"))]
151-
let mut child = command
152-
.spawn()
153-
.map_err(|error| BackendError::Process(error.to_string()))?;
154-
let pid = child.id();
151+
let mut child = crate::managed_children::ManagedChild::spawn(
152+
|| command.spawn(),
153+
|child| Some(child.id()),
154+
)
155+
.map_err(|error| BackendError::Process(error.to_string()))?;
156+
let pid = child
157+
.id()
158+
.expect("a spawned standard child always has a valid PID");
155159
let process_terminal = Arc::new(std::sync::atomic::AtomicBool::new(false));
156160
let signal_lock = Arc::new(std::sync::Mutex::new(()));
157161
if let Err(error) =
@@ -165,23 +169,18 @@ impl LocalBoundaryExec {
165169
let _ = child.wait();
166170
return Err(error);
167171
}
168-
#[cfg(target_os = "linux")]
169-
let managed_child = child_registry.register(pid);
170-
#[cfg(target_os = "linux")]
171-
drop(child_registry);
172-
let stdin = child.stdin.take().map(|file| -> BoundaryInput {
172+
let stdin = child.take_stdin().map(|file| -> BoundaryInput {
173173
let fd: OwnedFd = file.into();
174174
Box::new(tokio::fs::File::from_std(std::fs::File::from(fd)))
175175
});
176176
let stdout = child
177-
.stdout
178-
.take()
177+
.take_stdout()
179178
.map(|file| -> BoundaryOutput {
180179
let fd: OwnedFd = file.into();
181180
Box::new(tokio::fs::File::from_std(std::fs::File::from(fd)))
182181
})
183182
.ok_or_else(|| BackendError::Process("exec stdout pipe missing".to_string()))?;
184-
let stderr = child.stderr.take().map(|file| -> BoundaryOutput {
183+
let stderr = child.take_stderr().map(|file| -> BoundaryOutput {
185184
let fd: OwnedFd = file.into();
186185
Box::new(tokio::fs::File::from_std(std::fs::File::from(fd)))
187186
});
@@ -191,8 +190,6 @@ impl LocalBoundaryExec {
191190
self.runtime.clone(),
192191
process_terminal,
193192
signal_lock,
194-
#[cfg(target_os = "linux")]
195-
managed_child,
196193
));
197194
Ok(SpawnedExec {
198195
session: Some(ExecSession {
@@ -253,16 +250,20 @@ impl LocalBoundaryExec {
253250
)
254251
.map_err(|error| BackendError::Process(error.to_string()))?;
255252
#[cfg(target_os = "linux")]
256-
let mut child_registry = crate::managed_children::lock();
257-
#[cfg(target_os = "linux")]
258-
let mut child =
259-
crate::process::spawn_std_command_with_workload_launcher(&self.launcher, command)
260-
.map_err(|error| BackendError::Process(error.to_string()))?;
253+
let mut child = crate::managed_children::ManagedChild::spawn(
254+
|| crate::process::spawn_std_command_with_workload_launcher(&self.launcher, command),
255+
|child| Some(child.id()),
256+
)
257+
.map_err(|error| BackendError::Process(error.to_string()))?;
261258
#[cfg(not(target_os = "linux"))]
262-
let mut child = command
263-
.spawn()
264-
.map_err(|error| BackendError::Process(error.to_string()))?;
265-
let pid = child.id();
259+
let mut child = crate::managed_children::ManagedChild::spawn(
260+
|| command.spawn(),
261+
|child| Some(child.id()),
262+
)
263+
.map_err(|error| BackendError::Process(error.to_string()))?;
264+
let pid = child
265+
.id()
266+
.expect("a spawned standard child always has a valid PID");
266267
let process_terminal = Arc::new(std::sync::atomic::AtomicBool::new(false));
267268
let signal_lock = Arc::new(std::sync::Mutex::new(()));
268269
if let Err(error) =
@@ -276,19 +277,13 @@ impl LocalBoundaryExec {
276277
let _ = child.wait();
277278
return Err(error);
278279
}
279-
#[cfg(target_os = "linux")]
280-
let managed_child = child_registry.register(pid);
281-
#[cfg(target_os = "linux")]
282-
drop(child_registry);
283280
let terminal: Arc<dyn BoundaryTerminal> = Arc::new(LocalTerminal { master });
284281
let process = Arc::new(LocalExecProcess::new(
285282
child,
286283
pid,
287284
self.runtime.clone(),
288285
process_terminal,
289286
signal_lock,
290-
#[cfg(target_os = "linux")]
291-
managed_child,
292287
));
293288
Ok(SpawnedExec {
294289
session: Some(ExecSession {
@@ -379,14 +374,11 @@ struct LocalExecProcess {
379374

380375
impl LocalExecProcess {
381376
fn new(
382-
child: Child,
377+
child: crate::managed_children::ManagedChild<std::process::Child>,
383378
pid: u32,
384379
runtime: Arc<crate::boundary_io::BoundaryRuntimeState>,
385380
terminal: Arc<std::sync::atomic::AtomicBool>,
386381
signal_lock: Arc<std::sync::Mutex<()>>,
387-
#[cfg(target_os = "linux")] managed_child: Option<
388-
crate::managed_children::ManagedChildRegistration,
389-
>,
390382
) -> Self {
391383
let result = Arc::new(std::sync::Mutex::new(None));
392384
let exited = Arc::new(tokio::sync::Notify::new());
@@ -408,9 +400,6 @@ impl LocalExecProcess {
408400
.unwrap_or_else(std::sync::PoisonError::into_inner);
409401
let result = child.wait();
410402
terminal_for_wait.store(true, std::sync::atomic::Ordering::Release);
411-
if let Some(managed_child) = managed_child {
412-
crate::managed_children::unregister(managed_child);
413-
}
414403
match (terminal_observed, result) {
415404
(_, Ok(status)) => Ok(status),
416405
(Err(observe_error), Err(wait_error)) => Err(std::io::Error::other(

‎crates/openshell-sandbox/src/managed_children.rs‎

Lines changed: 22 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -29,7 +29,7 @@ static NEXT_GENERATION: AtomicU64 = AtomicU64::new(1);
2929
/// removing a newer child that reused the same numeric PID after reap.
3030
#[cfg(target_os = "linux")]
3131
#[derive(Clone, Copy)]
32-
pub struct ManagedChildRegistration {
32+
struct ManagedChildRegistration {
3333
pid: i32,
3434
generation: u64,
3535
}
@@ -42,12 +42,12 @@ pub struct ManagedChildRegistration {
4242
/// otherwise unavoidable window in which a fast-exiting managed child exists
4343
/// but its PID has not yet been published.
4444
#[cfg(target_os = "linux")]
45-
pub struct RegistryGuard(MutexGuard<'static, HashMap<i32, u64>>);
45+
struct RegistryGuard(MutexGuard<'static, HashMap<i32, u64>>);
4646

4747
#[cfg(target_os = "linux")]
4848
impl RegistryGuard {
4949
/// Add a newly spawned managed child.
50-
pub fn register(&mut self, pid: u32) -> Option<ManagedChildRegistration> {
50+
fn register(&mut self, pid: u32) -> Option<ManagedChildRegistration> {
5151
let Ok(pid) = i32::try_from(pid) else {
5252
return None;
5353
};
@@ -61,32 +61,26 @@ impl RegistryGuard {
6161

6262
/// Return whether the PID belongs to an explicit waiter.
6363
#[must_use]
64-
pub fn contains(&self, pid: i32) -> bool {
64+
fn contains(&self, pid: i32) -> bool {
6565
self.0.contains_key(&pid)
6666
}
6767
}
6868

6969
/// Lock the registry for an atomic spawn-and-register or inspect-and-reap
7070
/// operation.
7171
#[cfg(target_os = "linux")]
72-
pub fn lock() -> RegistryGuard {
72+
fn lock() -> RegistryGuard {
7373
RegistryGuard(
7474
MANAGED_CHILDREN
7575
.lock()
7676
.unwrap_or_else(std::sync::PoisonError::into_inner),
7777
)
7878
}
7979

80-
/// Register a child and return the generation-bearing removal token.
81-
#[cfg(target_os = "linux")]
82-
pub fn register(pid: u32) -> Option<ManagedChildRegistration> {
83-
lock().register(pid)
84-
}
85-
8680
/// Remove exactly this supervised-child registration. A newer registration
8781
/// for a reused PID is preserved.
8882
#[cfg(target_os = "linux")]
89-
pub fn unregister(child: ManagedChildRegistration) {
83+
fn unregister(child: ManagedChildRegistration) {
9084
if let Ok(mut children) = MANAGED_CHILDREN.lock()
9185
&& children.get(&child.pid) == Some(&child.generation)
9286
{
@@ -95,9 +89,9 @@ pub fn unregister(child: ManagedChildRegistration) {
9589
}
9690

9791
/// Return `true` if `pid` is currently in the supervised-child set.
98-
#[cfg(target_os = "linux")]
92+
#[cfg(all(test, target_os = "linux"))]
9993
#[must_use]
100-
pub fn is_managed(pid: i32) -> bool {
94+
fn is_managed(pid: i32) -> bool {
10195
lock().contains(pid)
10296
}
10397

@@ -112,7 +106,7 @@ fn valid_pid(pid: Option<u32>) -> Option<u32> {
112106
/// insertion, so the orphan reaper cannot consume a fast child's status
113107
/// between those operations. Other platforms retain the same ownership API
114108
/// without enabling Linux-only reaper bookkeeping.
115-
pub struct ManagedChild<C> {
109+
pub(crate) struct ManagedChild<C> {
116110
child: C,
117111
pid: Option<u32>,
118112
#[cfg(target_os = "linux")]
@@ -121,7 +115,7 @@ pub struct ManagedChild<C> {
121115

122116
impl<C> ManagedChild<C> {
123117
/// Spawn a child and register its PID before returning it.
124-
pub fn spawn<E>(
118+
pub(crate) fn spawn<E>(
125119
spawn: impl FnOnce() -> Result<C, E>,
126120
pid: impl FnOnce(&C) -> Option<u32>,
127121
) -> Result<Self, E> {
@@ -148,7 +142,7 @@ impl<C> ManagedChild<C> {
148142

149143
/// Return the child's PID when it was available at spawn time.
150144
#[must_use]
151-
pub const fn id(&self) -> Option<u32> {
145+
pub(crate) const fn id(&self) -> Option<u32> {
152146
self.pid
153147
}
154148

@@ -179,7 +173,7 @@ fn log_wait_error(pid: Option<u32>, error: &std::io::Error) {
179173

180174
impl ManagedChild<tokio::process::Child> {
181175
/// Wait for a Tokio child and release its managed PID.
182-
pub async fn wait(&mut self) -> std::io::Result<std::process::ExitStatus> {
176+
pub(crate) async fn wait(&mut self) -> std::io::Result<std::process::ExitStatus> {
183177
let status = self.child.wait().await;
184178
if let Err(error) = &status {
185179
log_wait_error(self.pid, error);
@@ -189,7 +183,7 @@ impl ManagedChild<tokio::process::Child> {
189183
}
190184

191185
/// Observe a Tokio child without blocking.
192-
pub fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>> {
186+
pub(crate) fn try_wait(&mut self) -> std::io::Result<Option<std::process::ExitStatus>> {
193187
match self.child.try_wait() {
194188
Ok(status) => {
195189
if status.is_some() {
@@ -206,24 +200,24 @@ impl ManagedChild<tokio::process::Child> {
206200
}
207201

208202
/// Take the child's stdin handle without exposing the child itself.
209-
pub fn take_stdin(&mut self) -> Option<tokio::process::ChildStdin> {
203+
pub(crate) fn take_stdin(&mut self) -> Option<tokio::process::ChildStdin> {
210204
self.child.stdin.take()
211205
}
212206

213207
/// Take the child's stdout handle without exposing the child itself.
214-
pub fn take_stdout(&mut self) -> Option<tokio::process::ChildStdout> {
208+
pub(crate) fn take_stdout(&mut self) -> Option<tokio::process::ChildStdout> {
215209
self.child.stdout.take()
216210
}
217211

218212
/// Take the child's stderr handle without exposing the child itself.
219-
pub fn take_stderr(&mut self) -> Option<tokio::process::ChildStderr> {
213+
pub(crate) fn take_stderr(&mut self) -> Option<tokio::process::ChildStderr> {
220214
self.child.stderr.take()
221215
}
222216
}
223217

224218
impl ManagedChild<std::process::Child> {
225219
/// Wait for a standard-library child and release its managed PID.
226-
pub fn wait(&mut self) -> std::io::Result<std::process::ExitStatus> {
220+
pub(crate) fn wait(&mut self) -> std::io::Result<std::process::ExitStatus> {
227221
let status = self.child.wait();
228222
if let Err(error) = &status {
229223
log_wait_error(self.pid, error);
@@ -233,17 +227,17 @@ impl ManagedChild<std::process::Child> {
233227
}
234228

235229
/// Take the child's stdin handle without exposing the child itself.
236-
pub fn take_stdin(&mut self) -> Option<std::process::ChildStdin> {
230+
pub(crate) fn take_stdin(&mut self) -> Option<std::process::ChildStdin> {
237231
self.child.stdin.take()
238232
}
239233

240234
/// Take the child's stdout handle without exposing the child itself.
241-
pub fn take_stdout(&mut self) -> Option<std::process::ChildStdout> {
235+
pub(crate) fn take_stdout(&mut self) -> Option<std::process::ChildStdout> {
242236
self.child.stdout.take()
243237
}
244238

245239
/// Take the child's stderr handle without exposing the child itself.
246-
pub fn take_stderr(&mut self) -> Option<std::process::ChildStderr> {
240+
pub(crate) fn take_stderr(&mut self) -> Option<std::process::ChildStderr> {
247241
self.child.stderr.take()
248242
}
249243
}
@@ -253,7 +247,7 @@ impl ManagedChild<std::process::Child> {
253247
/// Keeping the child as a zombie prevents PID/process-group reuse until the
254248
/// owner publishes terminal state and performs the final wait.
255249
#[cfg(target_os = "linux")]
256-
pub fn wait_until_terminal(pid: u32) -> io::Result<()> {
250+
pub(crate) fn wait_until_terminal(pid: u32) -> io::Result<()> {
257251
use nix::sys::wait::{Id, WaitPidFlag, waitid};
258252
let pid = i32::try_from(pid)
259253
.map_err(|_| io::Error::new(io::ErrorKind::InvalidInput, "PID out of range"))?;
@@ -270,7 +264,7 @@ pub fn wait_until_terminal(pid: u32) -> io::Result<()> {
270264
/// Explicitly managed children remain owned by their normal waiters. Only
271265
/// unregistered children adopted from the workload process tree are reaped.
272266
#[cfg(target_os = "linux")]
273-
pub fn start_orphan_reaper() -> io::Result<()> {
267+
pub(crate) fn start_orphan_reaper() -> io::Result<()> {
274268
std::thread::Builder::new()
275269
.name("openshell-orphan-reaper".to_string())
276270
.spawn(|| {

0 commit comments

Comments
 (0)