Skip to main content

rigspark_runtime/
process_control.rs

1use crate::identity::{Listener, NativeProcessProbe, ProcessIdentity, ProcessProbe};
2use std::{
3    collections::BTreeMap,
4    future::Future,
5    path::{Path, PathBuf},
6    process::Stdio,
7    time::Duration,
8};
9use tokio_util::sync::CancellationToken;
10
11pub struct SpawnSpec {
12    pub binary: PathBuf,
13    pub args: Vec<String>,
14    pub env: BTreeMap<String, String>,
15}
16#[async_trait::async_trait]
17pub trait ChildProcess: Send {
18    fn pid(&self) -> u32;
19    fn exited(&mut self) -> Result<bool, String>;
20    async fn terminate(&mut self) -> Result<(), String>;
21    fn detach(&mut self);
22}
23#[async_trait::async_trait]
24pub trait ProcessControl: Send + Sync {
25    async fn occupied(&self, endpoint: &str) -> Result<bool, String>;
26    async fn spawn(&self, spec: &SpawnSpec) -> Result<Box<dyn ChildProcess>, String>;
27    async fn signal(&self, process: &ProcessIdentity, force: bool) -> Result<(), String>;
28    async fn alive(&self, pid: u32) -> Result<bool, String>;
29}
30struct NativeChild {
31    child: tokio::process::Child,
32    detached: bool,
33    pid: u32,
34}
35#[async_trait::async_trait]
36impl ChildProcess for NativeChild {
37    fn pid(&self) -> u32 {
38        self.pid
39    }
40    fn exited(&mut self) -> Result<bool, String> {
41        self.child
42            .try_wait()
43            .map(|value| value.is_some())
44            .map_err(|_| "cannot observe child exit".into())
45    }
46    async fn terminate(&mut self) -> Result<(), String> {
47        if self.exited()? {
48            return Ok(());
49        }
50        self.child
51            .start_kill()
52            .map_err(|_| "child termination failed")?;
53        tokio::time::timeout(Duration::from_secs(5), self.child.wait())
54            .await
55            .map_err(|_| "child termination timed out")?
56            .map_err(|_| "child wait failed")?;
57        Ok(())
58    }
59    fn detach(&mut self) {
60        self.detached = true;
61    }
62}
63impl Drop for NativeChild {
64    fn drop(&mut self) {
65        if !self.detached {
66            let _ = self.child.start_kill();
67        }
68    }
69}
70pub struct NativeProcessControl;
71#[async_trait::async_trait]
72impl ProcessControl for NativeProcessControl {
73    async fn occupied(&self, endpoint: &str) -> Result<bool, String> {
74        let url = crate::state::loopback(endpoint).map_err(|error| error.to_string())?;
75        let host = url
76            .host_str()
77            .ok_or("missing host")?
78            .trim_matches(['[', ']']);
79        let port = url.port_or_known_default().ok_or("missing port")?;
80        let addresses = if host == "localhost" {
81            vec![format!("127.0.0.1:{port}"), format!("[::1]:{port}")]
82        } else {
83            vec![format!(
84                "{}:{port}",
85                if host.contains(':') {
86                    format!("[{host}]")
87                } else {
88                    host.into()
89                }
90            )]
91        };
92        for address in addresses {
93            match tokio::time::timeout(
94                Duration::from_secs(2),
95                tokio::net::TcpStream::connect(address),
96            )
97            .await
98            {
99                Ok(Ok(_)) => return Ok(true),
100                Ok(Err(error)) if error.kind() == std::io::ErrorKind::ConnectionRefused => (),
101                _ => return Err("cannot establish port availability".into()),
102            }
103        }
104        Ok(false)
105    }
106    async fn spawn(&self, spec: &SpawnSpec) -> Result<Box<dyn ChildProcess>, String> {
107        if !spec.binary.is_absolute() || spec.args.iter().any(|arg| arg.contains('\0')) {
108            return Err("invalid spawn specification".into());
109        }
110        let mut command = tokio::process::Command::new(&spec.binary);
111        command
112            .args(&spec.args)
113            .env_clear()
114            .envs(&spec.env)
115            .stdin(Stdio::null())
116            .stdout(Stdio::null())
117            .stderr(Stdio::null());
118        let mut child = command.spawn().map_err(|_| "runtime spawn failed")?;
119        let Some(pid) = child.id().filter(|pid| *pid > 0) else {
120            let _ = child.kill().await;
121            return Err("runtime reported invalid PID".into());
122        };
123        Ok(Box::new(NativeChild {
124            child,
125            detached: false,
126            pid,
127        }))
128    }
129    async fn signal(&self, expected: &ProcessIdentity, force: bool) -> Result<(), String> {
130        let observed = NativeProcessProbe
131            .process(expected.pid)
132            .await
133            .map_err(|_| "cannot verify process before signal")?;
134        if !same_process(&observed, expected) {
135            return Err("process changed before signal".into());
136        }
137        #[cfg(unix)]
138        {
139            let pid = i32::try_from(expected.pid)
140                .ok()
141                .and_then(rustix::process::Pid::from_raw)
142                .ok_or("invalid process PID")?;
143            rustix::process::kill_process(
144                pid,
145                if force {
146                    rustix::process::Signal::KILL
147                } else {
148                    rustix::process::Signal::TERM
149                },
150            )
151            .map_err(|_| "signal failed".to_owned())
152        }
153        #[cfg(windows)]
154        {
155            let _ = force;
156            let system = sysinfo::System::new_all();
157            let process = system
158                .process(sysinfo::Pid::from_u32(expected.pid))
159                .ok_or("process unavailable")?;
160            if process.kill() {
161                Ok(())
162            } else {
163                Err("process termination failed".into())
164            }
165        }
166        #[cfg(not(any(unix, windows)))]
167        {
168            let _ = force;
169            Err("unsupported platform".into())
170        }
171    }
172    async fn alive(&self, pid: u32) -> Result<bool, String> {
173        #[cfg(unix)]
174        {
175            let pid = i32::try_from(pid)
176                .ok()
177                .and_then(rustix::process::Pid::from_raw)
178                .ok_or("invalid process PID")?;
179            match rustix::process::test_kill_process(pid) {
180                Ok(()) => Ok(true),
181                Err(rustix::io::Errno::SRCH) => Ok(false),
182                Err(rustix::io::Errno::PERM) => Ok(true),
183                Err(_) => Err("process existence unavailable".into()),
184            }
185        }
186        #[cfg(not(unix))]
187        {
188            let system = sysinfo::System::new_all();
189            Ok(system.process(sysinfo::Pid::from_u32(pid)).is_some())
190        }
191    }
192}
193pub fn same_process(actual: &ProcessIdentity, expected: &ProcessIdentity) -> bool {
194    actual.pid == expected.pid
195        && actual.executable == expected.executable
196        && actual.started == expected.started
197}
198pub fn resolve_binary(binary: &str) -> Result<PathBuf, String> {
199    let path = Path::new(binary);
200    if path.is_absolute() {
201        return path
202            .canonicalize()
203            .map_err(|_| "runtime executable unavailable".into());
204    }
205    for directory in std::env::split_paths(&std::env::var_os("PATH").unwrap_or_default()) {
206        if directory.as_os_str().is_empty() {
207            continue;
208        }
209        for name in [binary.to_owned(), format!("{binary}.exe")] {
210            let candidate = directory.join(name);
211            if candidate.is_file() {
212                return candidate
213                    .canonicalize()
214                    .map_err(|_| "runtime executable cannot be resolved".into());
215            }
216        }
217    }
218    Err("runtime executable not found on PATH".into())
219}
220pub fn minimal_env() -> BTreeMap<String, String> {
221    [
222        "PATH",
223        "HOME",
224        "USER",
225        "LOGNAME",
226        "LANG",
227        "LC_ALL",
228        "LC_CTYPE",
229        "TMPDIR",
230        "TMP",
231        "TEMP",
232        "SYSTEMROOT",
233        "WINDIR",
234        "COMSPEC",
235        "PATHEXT",
236    ]
237    .into_iter()
238    .filter_map(|key| std::env::var(key).ok().map(|value| (key.into(), value)))
239    .collect()
240}
241pub async fn listener(
242    probe: &dyn ProcessProbe,
243    endpoint: &str,
244    cancel: &CancellationToken,
245) -> Result<Listener, String> {
246    let url = crate::state::loopback(endpoint).map_err(|error| error.to_string())?;
247    let host = url.host_str().ok_or("missing host")?;
248    let port = url.port_or_known_default().ok_or("missing port")?;
249    tokio::select! {biased;_=cancel.cancelled()=>Err("cancelled".into()),result=tokio::time::timeout(Duration::from_secs(5),probe.listener(port,host))=>{
250        let observed=result.map_err(|_|"listener probe timed out")?.map_err(|_|"listener identity unavailable")?;
251        crate::identity::choose_listener(std::slice::from_ref(&observed),port,host).map_err(|_|"listener address mismatch".into())
252    }}
253}
254pub async fn wait_owned<F, Fut>(
255    child: Box<dyn ChildProcess>,
256    endpoint: &str,
257    executable: &str,
258    probe: &dyn ProcessProbe,
259    cancel: &CancellationToken,
260    ready: F,
261) -> Result<Listener, String>
262where
263    F: FnOnce() -> Fut,
264    Fut: Future<Output = Result<(), String>>,
265{
266    wait_owned_with_timeout(
267        child,
268        endpoint,
269        executable,
270        probe,
271        cancel,
272        Duration::from_secs(30),
273        ready,
274    )
275    .await
276}
277pub async fn wait_owned_with_timeout<F, Fut>(
278    mut child: Box<dyn ChildProcess>,
279    endpoint: &str,
280    executable: &str,
281    probe: &dyn ProcessProbe,
282    cancel: &CancellationToken,
283    timeout: Duration,
284    ready: F,
285) -> Result<Listener, String>
286where
287    F: FnOnce() -> Fut,
288    Fut: Future<Output = Result<(), String>>,
289{
290    if timeout.is_zero() || timeout > Duration::from_secs(300) {
291        child.terminate().await?;
292        return Err("invalid readiness deadline".into());
293    }
294    let operation = async {
295        if child.pid() == 0 {
296            return Err("invalid child PID".into());
297        }
298        let readiness = ready();
299        tokio::pin!(readiness);
300        loop {
301            if child.exited()? {
302                return Err("runtime exited before readiness".into());
303            }
304            tokio::select! {result=&mut readiness=>{result?;break;},_=tokio::time::sleep(Duration::from_millis(50))=>()}
305        }
306        let observed = listener(probe, endpoint, cancel).await?;
307        if observed.identity.pid != child.pid() || observed.identity.executable != executable {
308            return Err("readiness belongs to another process".into());
309        }
310        Ok(observed)
311    };
312    let result = tokio::select! {biased;_=cancel.cancelled()=>Err("cancelled".into()),result=tokio::time::timeout(timeout,operation)=>result.map_err(|_|"runtime readiness timed out".to_owned()).and_then(|result|result)};
313    match result {
314        Ok(observed) => {
315            child.detach();
316            Ok(observed)
317        }
318        Err(error) => {
319            child
320                .terminate()
321                .await
322                .map_err(|cleanup| format!("{error}; {cleanup}"))?;
323            Err(error)
324        }
325    }
326}
327pub async fn stop_owned(
328    endpoint: &str,
329    expected: &ProcessIdentity,
330    probe: &dyn ProcessProbe,
331    control: &dyn ProcessControl,
332    cancel: &CancellationToken,
333) -> Result<(), String> {
334    let observed = listener(probe, endpoint, cancel).await?;
335    if !same_process(&observed.identity, expected) {
336        return Err("listener changed; refusing to stop".into());
337    }
338    for force in [false, true] {
339        let current = tokio::select! {biased;_=cancel.cancelled()=>return Err("cancelled".into()),result=tokio::time::timeout(Duration::from_secs(5),probe.process(expected.pid))=>result.map_err(|_|"process probe timed out")?.map_err(|_|"process identity unavailable")?};
340        if !same_process(&current, expected) {
341            if force {
342                return Ok(());
343            }
344            return Err("process changed; refusing to stop".into());
345        }
346        control.signal(expected, force).await?;
347        for _ in 0..10 {
348            if !control.alive(expected.pid).await? {
349                return Ok(());
350            }
351            let current = match probe.process(expected.pid).await {
352                Ok(current) => current,
353                Err(_) => {
354                    if !control.alive(expected.pid).await? {
355                        return Ok(());
356                    }
357                    return Err("process identity unavailable after signal".into());
358                }
359            };
360            if !same_process(&current, expected) {
361                return Ok(());
362            }
363            tokio::select! {biased;_=cancel.cancelled()=>return Err("cancelled".into()),_=tokio::time::sleep(Duration::from_millis(50))=>()}
364        }
365    }
366    Err("runtime remains alive after termination".into())
367}