Skip to main content

gosh_runner/
process.rs

1// [[file:../runners.note::312de6f2][312de6f2]]
2//! For manage processes
3//!
4//! # Example
5//!
6//! ```rust, no_run
7//! use gosh_runner::prelude::*;
8//! 
9//! let mut command = std::process::Command::new("vasp-program");
10//! let mut session = command.spawn_session()?;
11//! let session_handler = session.handler().clone();
12//! session_handler.pause()?;
13//! session_handler.resume()?;
14//! session_handler.terminate()?;
15//! session.child.wait()?;
16//! # Ok::<(), anyhow::Error>(())
17//! ```
18
19use super::*;
20// 312de6f2 ends here
21
22// [[file:../runners.note::*process group][process group:1]]
23mod process_group {
24    use super::*;
25
26    macro_rules! setsid {
27        () => {{
28            // Don't check the error of setsid because it fails if we're the
29            // process leader already. We just forked so it shouldn't return
30            // error, but ignore it anyway.
31            nix::unistd::setsid().ok();
32            Ok(())
33        }};
34    }
35
36    /// Create child process in new session
37    pub trait ProcessGroupExt<T> {
38        fn new_process_group(&mut self) -> &mut T;
39    }
40
41    impl ProcessGroupExt<std::process::Command> for std::process::Command {
42        fn new_process_group(&mut self) -> &mut std::process::Command {
43            use std::os::unix::process::CommandExt;
44
45            unsafe {
46                self.pre_exec(|| setsid!());
47            }
48            self
49        }
50    }
51
52    impl ProcessGroupExt<tokio::process::Command> for tokio::process::Command {
53        fn new_process_group(&mut self) -> &mut tokio::process::Command {
54            unsafe {
55                self.pre_exec(|| setsid!());
56            }
57            self
58        }
59    }
60}
61// process group:1 ends here
62
63// [[file:../runners.note::*timestamp][timestamp:1]]
64use chrono::*;
65
66/// Convert unix timestamp in floating point seconds to `DateTime`
67fn float_unix_timestamp_to_date_time(t: f64) -> DateTime<Utc> {
68    let nano = t.fract() * 1_000_000_000f64;
69    Utc.timestamp(t.trunc() as i64, nano.round() as u32)
70}
71// timestamp:1 ends here
72
73// [[file:../runners.note::*process][process:1]]
74mod impl_process_procfs {
75    use super::*;
76    use procfs::process;
77
78    /// Represents a process
79    #[derive(Debug, Clone)]
80    pub struct Process {
81        inner: process::Process,
82        create_time: u64,
83    }
84
85    impl Process {
86        /// Construct from process ID
87        pub fn from_pid(pid: u32) -> Result<Self> {
88            let p = process::Process::new(pid as i32)?;
89            let create_time = p.stat.starttime;
90            let p = Self { inner: p, create_time };
91            Ok(p)
92        }
93
94        /// Return the system assigned process ID
95        pub fn id(&self) -> u32 {
96            self.inner.pid as u32
97        }
98
99        /// Test if process is alive
100        pub fn is_alive(&self) -> bool {
101            self.inner.is_alive()
102        }
103
104        /// Returns the session Id of the process.
105        pub fn session_id(&self) -> u32 {
106            self.inner.stat.session as u32
107        }
108
109        /// Get the working directory of the process.
110        pub fn get_cwd(&self) -> Result<PathBuf> {
111            let d = self.inner.cwd()?;
112            Ok(d)
113        }
114
115        /// Return actual path of the executed command for the process.
116        pub fn get_exe(&self) -> Result<PathBuf> {
117            let exe = self.inner.exe()?;
118            Ok(exe)
119        }
120
121        /// Returns the complete command line for the process.
122        pub fn get_cmdline(&self) -> Result<Vec<String>> {
123            let cmdline = self.inner.cmdline()?;
124            Ok(cmdline)
125        }
126
127        /// Test if process is paused
128        pub fn is_paused(&self) -> bool {
129            if let Ok(stat) = self.inner.stat() {
130                if let Ok(state) = stat.state() {
131                    state == procfs::process::ProcState::Stopped
132                } else {
133                    false
134                }
135            } else {
136                false
137            }
138        }
139
140        /// Send signal to the process.
141        pub fn send_signal(&self, signal: &str) -> Result<()> {
142            use nix::sys::signal::Signal;
143
144            let signal: Signal = signal
145                .parse()
146                .with_context(|| format!("invalid signal name: {}", signal))?;
147            nix::sys::signal::kill(nix::unistd::Pid::from_raw(self.inner.pid), signal)?;
148            Ok(())
149        }
150
151        /// Test if is the same process, useful for avoiding re-used process ID
152        pub fn is_same(&self, p: &Process) -> bool {
153            self.create_time == p.create_time && self.inner.pid == p.inner.pid
154        }
155    }
156
157    /// Return processes with the same session ID
158    pub fn get_processes_in_session(id: u32) -> Result<Vec<Process>> {
159        let all = process::all_processes()?
160            .into_iter()
161            .filter_map(|p| {
162                if p.stat.session == id as i32 {
163                    Process {
164                        create_time: p.stat.starttime,
165                        inner: p,
166                    }
167                    .into()
168                } else {
169                    None
170                }
171            })
172            .collect();
173        Ok(all)
174    }
175}
176// process:1 ends here
177
178// [[file:../runners.note::49b16e9d][49b16e9d]]
179mod session {
180    use super::*;
181    use std::process::Child;
182    use std::process::ExitStatus;
183
184    /// Manange a group of processes in the same session. The child processes
185    /// will be terminated, if `Session` dropped.
186    /// 
187    /// # Example
188    ///
189    /// ```rust, no_run
190    /// use gosh_runner::prelude::*;
191    /// 
192    /// let mut command = std::process::Command::new("vasp-program");
193    /// let mut session = command.spawn_session()?;
194    /// let session_handler = session.handler().clone();
195    /// session_handler.pause()?;
196    /// session_handler.resume()?;
197    /// session_handler.terminate()?;
198    /// session.child.wait()?;
199    /// # Ok::<(), anyhow::Error>(())
200    /// ```
201    pub struct Session<T> {
202        pub child: T,
203        session_handler: SessionHandler,
204    }
205
206    impl<T> Session<T> {
207        /// Returns a reference to `SessionHandler`.
208        pub fn handler(&self) -> &SessionHandler {
209            &self.session_handler
210        }
211    }
212
213    // Send SIGTERM to processes in the session on drop
214    impl<T> Drop for Session<T> {
215        fn drop(&mut self) {
216            let _ = self.session_handler.terminate();
217        }
218    }
219
220    /// Handle a group of processes in the same session, possible operations:
221    /// `pause`, `resume`, `terminate`
222    #[derive(Debug, Clone)]
223    pub struct SessionHandler {
224        process: Option<Process>,
225    }
226
227    /// Create child process in new session
228    pub trait SpawnSessionExt<T> {
229        /// Spawn child process in new session.
230        fn spawn_session(&mut self) -> Result<Session<T>>;
231    }
232
233    impl SessionHandler {
234        fn from(id: u32) -> Self {
235            let process = Process::from_pid(id).ok();
236            Self { process }
237        }
238
239        /// Return process ID of the session leader.
240        pub fn id(&self) -> Option<u32> {
241            self.process.as_ref().map(|p| p.id())
242        }
243
244        /// Send signal to all processes in the session
245        fn send_signal(&self, signal: &str) -> Result<()> {
246            if let Some(p_old) = &self.process {
247                let id = p_old.id();
248                let p_now = Process::from_pid(id)?;
249                // send signal only when the session leader still exists and
250                // look like the same as created before (PID could be reused)
251                if p_now.is_same(p_old) {
252                    signal_processes_by_session_id(id, signal)?;
253                } else {
254                    warn!("Send signal {} to a resued process {}", signal, id);
255                }
256            } else {
257                bail!("no session leader!");
258            }
259            Ok(())
260        }
261
262        /// Return the processes in the session.
263        pub fn get_processes(&self) -> Result<Vec<Process>> {
264            if let Some(id) = self.id() {
265                let p = get_processes_in_session(id)?;
266                Ok(p)
267            } else {
268                bail!("session is not alive");
269            }
270        }
271
272        /// Pause all processes in the session.
273        pub fn pause(&self) -> Result<()> {
274            debug!("pause session {:?}", self.id());
275            self.send_signal("SIGSTOP")?;
276            Ok(())
277        }
278
279        /// Resume processes in the session.
280        pub fn resume(&self) -> Result<()> {
281            debug!("resume session {:?}", self.id());
282            self.send_signal("SIGCONT")?;
283            Ok(())
284        }
285
286        /// Terminate processes in the session.
287        pub fn terminate(&self) -> Result<()> {
288            debug!("terminate session {:?}", self.id());
289            // If process was paused, terminate it directly could result a deadlock or zombie.
290            self.send_signal("SIGCONT")?;
291            gut::utils::sleep(0.2);
292            self.send_signal("SIGTERM")?;
293            Ok(())
294        }
295    }
296
297    impl SpawnSessionExt<std::process::Child> for std::process::Command {
298        fn spawn_session(&mut self) -> Result<Session<std::process::Child>> {
299            let child = self.new_process_group().spawn()?;
300            let id = child.id();
301            let session_handler = SessionHandler::from(id);
302            let s = Session { child, session_handler };
303            Ok(s)
304        }
305    }
306    impl SpawnSessionExt<tokio::process::Child> for tokio::process::Command {
307        fn spawn_session(&mut self) -> Result<Session<tokio::process::Child>> {
308            let child = self.new_process_group().spawn()?;
309            let id = child.id().ok_or(format_err!("no id: child process already exited"))?;
310            let session_handler = SessionHandler::from(id);
311            let s = Session { child, session_handler };
312            Ok(s)
313        }
314    }
315}
316// 49b16e9d ends here
317
318// [[file:../runners.note::*pub][pub:1]]
319/// Signal all child processes in session `sid`
320pub(crate) fn signal_processes_by_session_id(sid: u32, signal: &str) -> Result<()> {
321    debug!("Send signal {} to processes in session {}", signal, sid);
322
323    let pp = get_processes_in_session(sid)?;
324    debug!("found {} processes in session {}", pp.len(), sid);
325    for p in pp {
326        p.send_signal(signal)?;
327    }
328
329    Ok(())
330}
331
332pub use impl_process_procfs::{get_processes_in_session, Process};
333pub use process_group::ProcessGroupExt;
334pub use session::{Session, SessionHandler, SpawnSessionExt};
335// pub:1 ends here
336
337// [[file:../runners.note::3ceaa6e9][3ceaa6e9]]
338#[test]
339fn test_spawn_session_std() -> Result<()> {
340    use std::process::Command;
341    gut::cli::setup_logger_for_test();
342
343    let mut command = Command::new("scripts/test_runner.sh");
344    let mut session = command.spawn_session()?;
345    let session_handler = session.handler();
346
347    gut::utils::sleep(0.2);
348    session_handler.pause()?;
349    for p in session_handler.get_processes()? {
350        assert!(p.is_paused());
351    }
352    gut::utils::sleep(0.2);
353    session_handler.resume()?;
354    for p in session_handler.get_processes()? {
355        assert!(!p.is_paused());
356    }
357    gut::utils::sleep(0.2);
358    session_handler.terminate()?;
359    gut::utils::sleep(0.2);
360    assert!(session.child.wait().is_ok());
361
362    Ok(())
363}
364
365#[tokio::test]
366async fn test_spawn_session_tokio() -> Result<()> {
367    use tokio::process::Command;
368
369    let mut command = Command::new("scripts/test_runner.sh");
370    let mut session = command.spawn_session()?;
371    let session_handler = session.handler();
372
373    gut::utils::sleep(0.2);
374    session_handler.pause()?;
375    for p in session_handler.get_processes()? {
376        assert!(p.is_paused());
377    }
378    gut::utils::sleep(0.2);
379    session_handler.resume()?;
380    for p in session_handler.get_processes()? {
381        assert!(!p.is_paused());
382    }
383    gut::utils::sleep(0.2);
384    session_handler.terminate()?;
385    gut::utils::sleep(0.2);
386    assert!(session.child.wait().await.is_ok());
387
388    Ok(())
389}
390// 3ceaa6e9 ends here