ctb_workspace_ipc/process_manager/
unix.rs1#![cfg(unix)]
35
36#[allow(
37 unused_imports,
38 clippy::wildcard_imports,
39 reason = "Standard workspace module prelude"
40)]
41use crate::utilities::*;
42
43use std::collections::HashMap;
44use std::process::Stdio;
45use std::sync::Arc;
46
47use anyhow::{Context, Result, anyhow};
48use async_trait::async_trait;
49use nix::errno::Errno;
50use nix::libc;
51use nix::sys::signal::{Signal, kill};
52use nix::unistd::Pid;
53use process_wrap::tokio::{CommandWrap, ProcessGroup};
54use tokio::io::AsyncWriteExt;
55use tokio::sync::Mutex;
56use tokio::time::{Duration, sleep};
57
58use crate::error::Error;
59use crate::types::{ConnectionId, ProcessId};
60
61use super::{ChildHandle, ProcessManager, SpawnParams};
62
63pub struct UnixProcessSupervisor;
68
69pub struct UnixSharedMemory;
71
72#[derive(Debug)]
73struct ChildEntry {
74 handle: ChildHandle,
76 pgid: libc::pid_t,
78}
79
80#[derive(Debug)]
81struct Inner {
82 children: HashMap<ProcessId, ChildEntry>,
83}
84
85#[derive(Debug)]
87pub struct TokioProcessManager {
88 inner: Arc<Mutex<Inner>>,
89}
90
91impl TokioProcessManager {
92 pub fn new() -> Arc<Self> {
94 Arc::new(Self {
95 inner: Arc::new(Mutex::new(Inner {
96 children: HashMap::new(),
97 })),
98 })
99 }
100
101 fn to_err(e: anyhow::Error) -> Error {
102 Error::from(e)
104 }
105
106 fn signal_pgid(
108 pgid: libc::pid_t,
109 sig: libc::c_int,
110 ) -> Result<(), anyhow::Error> {
111 let res = kill(Pid::from_raw(pgid), Signal::try_from(sig)?);
114 match res {
115 Ok(()) | Err(Errno::EPERM) => Ok(()),
116 Err(e) => {
117 Err(anyhow::anyhow!("failed to signal process group: {e}"))
118 }
119 }
120 }
121
122 fn pid_exists(pid: libc::pid_t) -> bool {
125 let e = kill(Pid::from_raw(pid), None);
127 match e {
128 Ok(()) | Err(Errno::EPERM) => true,
129 Err(_) => false,
130 }
131 }
132}
133
134#[async_trait]
135impl ProcessManager for TokioProcessManager {
136 async fn spawn_child(
137 &self,
138 params: SpawnParams,
139 ) -> Result<ChildHandle, Error> {
140 let program = if let Some(p) = params.program {
142 p
143 } else {
144 if params.kind == ipc::ChildKind::External {
145 return Err(Error::from(anyhow!(
146 "No program specified for child process"
147 )));
148 }
149 std::env::current_exe()?.into_os_string().into_string()?
150 };
151 let mut cmd = CommandWrap::with_new(&program, |command| {
152 command.args(¶ms.args);
153 command.stdin(Stdio::piped());
154 for (k, v) in ¶ms.env {
155 command.env(k, v);
156 }
157 if let Some(cwd) = ¶ms.cwd {
158 command.current_dir(cwd);
159 }
160 });
161 cmd.wrap(ProcessGroup::leader());
163
164 let mut child = cmd.spawn().context("failed to spawn child")?;
166
167 let token = params.capabilities.token.0.clone();
170 if !token.is_empty() {
171 if let Some(stdin) = child.stdin() {
172 stdin
173 .write_all(token.as_bytes())
174 .await
175 .map_err(|e: std::io::Error| Error::from(e))?;
176 stdin
177 .write_all(b"\n")
178 .await
179 .map_err(|e: std::io::Error| Error::from(e))?;
180 }
181 }
182 let os_pid = child.id().ok_or_else(|| anyhow!("child has no pid"))?;
183 let process_id = ProcessId::new();
184 let handle = ChildHandle {
185 pid: process_id,
186 kind: params.kind,
187 parent: params.parent,
188 connection: None,
189 };
190
191 let pgid = i32::try_from(os_pid)
193 .map_err(|e| Self::to_err(anyhow!("pid conversion error: {e}")))?
194 .checked_neg()
195 .ok_or_else(|| Self::to_err(anyhow!("pid negation overflow")))?;
196
197 let inner_for_reaper = Arc::clone(&self.inner);
199 let pid_for_reaper = process_id;
200 tokio::spawn(async move {
201 let _ = child.wait().await;
203 let mut inner = inner_for_reaper.lock().await;
205 let _ = inner.children.remove(&pid_for_reaper);
206 });
207
208 let entry = ChildEntry {
209 handle: handle.clone(),
210 pgid,
211 };
212 let mut inner = self.inner.lock().await;
213 inner.children.insert(process_id, entry);
214 Ok(handle)
215 }
216
217 async fn attach_connection(
218 &self,
219 pid: ProcessId,
220 conn: ConnectionId,
221 ) -> Result<(), Error> {
222 let mut inner = self.inner.lock().await;
223 let entry = inner.children.get_mut(&pid).ok_or_else(|| {
224 Self::to_err(anyhow!("child with pid {pid:?} not found"))
225 })?;
226 entry.handle.connection = Some(conn);
227 Ok(())
228 }
229
230 async fn list_children(&self) -> Result<Vec<ChildHandle>, Error> {
231 let inner = self.inner.lock().await;
232 Ok(inner.children.values().map(|e| e.handle.clone()).collect())
233 }
234
235 async fn terminate_tree(
236 &self,
237 pid: ProcessId,
238 force: bool,
239 ) -> Result<(), Error> {
240 let targets = {
242 let inner = self.inner.lock().await;
243
244 let mut targets: Vec<(ProcessId, libc::pid_t)> = Vec::new();
245
246 let mut stack = vec![pid];
248 while let Some(cur) = stack.pop() {
249 if let Some(entry) = inner.children.get(&cur) {
250 targets.push((cur, entry.pgid));
251 }
255
256 for (child_pid, entry) in &inner.children {
257 if entry.handle.parent == Some(cur) {
258 stack.push(*child_pid);
259 }
260 }
261 }
262
263 targets
264 };
265
266 if targets.is_empty() {
267 return Ok(());
268 }
269
270 let sig = if force { libc::SIGKILL } else { libc::SIGTERM };
271 for (_pid, pgid) in &targets {
272 let _ = Self::signal_pgid(*pgid, sig);
273 }
274
275 Ok(())
276 }
277
278 async fn wait_for_exit(
279 &self,
280 pid: ProcessId,
281 timeout: Duration,
282 ) -> Result<bool, Error> {
283 let pgids: Vec<libc::pid_t> = {
285 let inner = self.inner.lock().await;
286 let mut pgids = Vec::new();
287 let mut stack = vec![pid];
288 while let Some(cur) = stack.pop() {
289 if let Some(entry) = inner.children.get(&cur) {
290 pgids.push(entry.pgid);
291 }
292 for (child_pid, entry) in &inner.children {
293 if entry.handle.parent == Some(cur) {
294 stack.push(*child_pid);
295 }
296 }
297 }
298 pgids
299 };
300
301 if pgids.is_empty() {
302 return Ok(true);
303 }
304
305 let step = Duration::from_millis(50);
306 let mut waited = Duration::from_millis(0);
307 while waited < timeout {
308 if pgids.iter().all(|pgid| !Self::pid_exists(*pgid)) {
309 return Ok(true);
310 }
311 sleep(step).await;
312 waited = waited.checked_add(step).ok_or_else(|| {
313 Self::to_err(anyhow!("timeout duration overflow"))
314 })?;
315 }
316
317 Ok(pgids.iter().all(|pgid| !Self::pid_exists(*pgid)))
318 }
319}
320
321#[cfg(test)]
322#[allow(
323 clippy::panic,
324 clippy::expect_used,
325 clippy::unwrap_used,
326 clippy::unwrap_in_result,
327 clippy::panic_in_result_fn,
328 clippy::indexing_slicing,
329 clippy::arithmetic_side_effects,
330 reason = "Standard repository test boilerplate"
331)]
332mod tests {
333 use tokio::time::timeout;
334
335 use crate::auth::capability::CapabilityBundle;
336 use ipc::ChildKind;
337
338 use super::*;
339
340 #[crate::ctb_test("tokio")]
341 async fn test_spawn_and_terminate_graceful() {
342 let manager = TokioProcessManager::new();
343 let params = SpawnParams {
344 kind: ChildKind::External,
345 parent: None,
346 program: Some("sleep".to_string()),
347 args: vec!["1".to_string()],
348 env: vec![],
349 cwd: None,
350 capabilities: CapabilityBundle::default(),
351 };
352 let handle = manager.spawn_child(params).await.unwrap();
353 let result = timeout(
355 Duration::from_secs(3),
356 manager.terminate_tree(handle.pid, false),
357 )
358 .await;
359 assert!(
360 result.is_ok(),
361 "graceful termination should complete within timeout"
362 );
363 }
364
365 #[crate::ctb_test("tokio")]
366 async fn test_spawn_and_terminate_force() {
367 let manager = TokioProcessManager::new();
368 let params = SpawnParams {
369 kind: ChildKind::External,
370 parent: None,
371 program: Some("sleep".to_string()),
372 args: vec!["10".to_string()], env: vec![],
374 cwd: None,
375 capabilities: CapabilityBundle::default(),
376 };
377 let handle = manager.spawn_child(params).await.unwrap();
378 let result = manager.terminate_tree(handle.pid, true).await;
380 assert!(result.is_ok(), "force termination should succeed");
381 }
382}
383
384