Skip to main content

isothrum_runner/store/db/
owner.rs

1//! Who holds something: a process, the boot it runs in, and a token per holder.
2
3use serde::{Deserialize, Serialize};
4
5/// A process holding a lease or running an operation.
6#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
7#[non_exhaustive]
8pub struct Owner {
9    /// Its process id.
10    pub pid: u32,
11    /// The boot it runs in (Linux: the kernel's boot id; elsewhere empty, and the pid and the
12    /// lease's expiry decide).
13    pub boot: String,
14    /// A random token telling two holders of one process apart.
15    pub token: String,
16}
17
18impl Owner {
19    /// This process, with a new token.
20    #[must_use]
21    pub fn this_process() -> Owner {
22        let mut bytes = [0u8; 8];
23        // A token that couldn't be drawn is the time's: unique enough within one process.
24        if getrandom::fill(&mut bytes).is_err() {
25            let nanos = std::time::SystemTime::now()
26                .duration_since(std::time::UNIX_EPOCH)
27                .map_or(0, |d| d.subsec_nanos());
28            bytes = u64::from(nanos).to_le_bytes();
29        }
30        Owner {
31            pid: std::process::id(),
32            boot: this_boot(),
33            token: bytes
34                .iter()
35                .flat_map(|b| [b >> 4, b & 0x0f])
36                .map(|nibble| char::from_digit(u32::from(nibble), 16).unwrap_or('0'))
37                .collect(),
38        }
39    }
40
41    /// Whether its process may still run: not when it ran in another boot, nor when no process
42    /// has its pid (Unix: signal 0; Windows: `OpenProcess`). A pid reused since is taken as alive:
43    /// the lease's expiry decides then.
44    #[must_use]
45    pub fn is_alive(&self) -> bool {
46        if self.boot != this_boot() {
47            return false;
48        }
49        if self.pid == std::process::id() {
50            return true;
51        }
52        pid_alive(self.pid)
53    }
54}
55
56/// This boot's id: the kernel's on Linux, else none.
57fn this_boot() -> String {
58    #[cfg(target_os = "linux")]
59    {
60        if let Ok(id) = std::fs::read_to_string("/proc/sys/kernel/random/boot_id") {
61            return id.trim().to_owned();
62        }
63    }
64    String::new()
65}
66
67#[cfg(unix)]
68fn pid_alive(pid: u32) -> bool {
69    use nix::errno::Errno;
70    let Ok(raw) = i32::try_from(pid) else {
71        return false;
72    };
73    // Signal 0 checks the process exists; EPERM means it does, another user's.
74    match nix::sys::signal::kill(nix::unistd::Pid::from_raw(raw), None) {
75        Ok(()) | Err(Errno::EPERM) => true,
76        Err(_) => false,
77    }
78}
79
80/// Windows: whether a process has the pid and hasn't exited, as the system says.
81#[cfg(windows)]
82fn pid_alive(pid: u32) -> bool {
83    crate::process::process_runs(pid)
84}
85
86#[cfg(not(any(unix, windows)))]
87fn pid_alive(_pid: u32) -> bool {
88    true
89}
90
91#[cfg(test)]
92pub(crate) mod tests {
93    use super::*;
94
95    #[test]
96    fn this_process_is_alive_and_a_holder_of_another_boot_or_a_gone_pid_isnt() {
97        let me = Owner::this_process();
98        assert!(me.is_alive());
99        assert_ne!(me.token, Owner::this_process().token, "a token per holder");
100        let mut other_boot = me.clone();
101        other_boot.boot = "another-boot".into();
102        other_boot.pid = 1;
103        assert!(!other_boot.is_alive());
104        let mut gone = me.clone();
105        gone.pid = dead_pid();
106        assert!(!gone.is_alive(), "a pid no process has (Windows: OpenProcess refuses it)");
107    }
108
109    /// Another process of this boot that runs holds what it took: Unix's signal 0 and Windows'
110    /// `OpenProcess` both find it.
111    #[test]
112    fn another_running_process_is_alive() {
113        let mut command = if cfg!(windows) {
114            let mut ping = std::process::Command::new("ping");
115            ping.args(["-n", "300", "127.0.0.1"]);
116            ping
117        } else {
118            let mut sleep = std::process::Command::new("sleep");
119            sleep.arg("300");
120            sleep
121        };
122        let running = isothrum_test_support::ChildGuard::spawn(command.stdout(std::process::Stdio::null())).unwrap();
123        let mut other = Owner::this_process();
124        other.pid = running.id();
125        assert!(other.is_alive());
126    }
127
128    /// The pid of a process that ran and exited.
129    pub(crate) fn dead_pid() -> u32 {
130        let mut command = if cfg!(windows) {
131            let mut cmd = std::process::Command::new("cmd");
132            cmd.args(["/C", "exit 0"]);
133            cmd
134        } else {
135            std::process::Command::new("true")
136        };
137        let mut child = command.spawn().unwrap();
138        let pid = child.id();
139        child.wait().unwrap();
140        pid
141    }
142}