Skip to main content

link_cli/store_lock/
owner.rs

1//! The owner record of a store lock and the process probes that decide
2//! whether its owner still runs.
3//!
4//! A record is a few `key=value` lines, the same in every implementation:
5//!
6//! ```text
7//! pid=4242
8//! host=build-7
9//! pid_namespace=pid:[4026531836]
10//! start_time=1234567
11//! acquired_at_ms=1764028800000
12//! token=5f0c2a9d1e3b4c6a
13//! program=clink (rust) 3.1.2
14//! ```
15//!
16//! `pid_namespace` and `start_time` are only known on Linux; elsewhere they
17//! are empty and the owner is judged by host and process id alone.
18
19use std::time::{SystemTime, UNIX_EPOCH};
20
21/// Who holds a store lock.
22#[derive(Debug, Clone, Default, PartialEq, Eq)]
23pub struct LockOwner {
24    pub pid: u32,
25    pub host: String,
26    pub pid_namespace: String,
27    pub start_time: String,
28    pub acquired_at_ms: u64,
29    pub token: String,
30    pub program: String,
31}
32
33/// Whether the owner of a lock still runs, as far as this host can tell.
34#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum Liveness {
36    Alive,
37    /// The owner is gone; the reason says how that is known.
38    Gone(String),
39    /// Another host or PID namespace: nothing here can tell.
40    Unknown(String),
41}
42
43impl LockOwner {
44    /// The record this process writes when it takes a lock.
45    pub fn current(token: &str) -> Self {
46        let pid = std::process::id();
47        Self {
48            pid,
49            host: host_name(),
50            pid_namespace: pid_namespace(),
51            start_time: process_start_time(pid).unwrap_or_default(),
52            acquired_at_ms: SystemTime::now()
53                .duration_since(UNIX_EPOCH)
54                .map_or(0, |elapsed| elapsed.as_millis() as u64),
55            token: token.to_string(),
56            program: format!("clink (rust) {}", env!("CARGO_PKG_VERSION")),
57        }
58    }
59
60    /// The `key=value` lines of the record.
61    pub fn to_record(&self) -> String {
62        format!(
63            "pid={}\nhost={}\npid_namespace={}\nstart_time={}\nacquired_at_ms={}\ntoken={}\nprogram={}\n",
64            self.pid,
65            self.host,
66            self.pid_namespace,
67            self.start_time,
68            self.acquired_at_ms,
69            self.token,
70            self.program
71        )
72    }
73
74    /// Reads a record; `None` unless it names a process id. Unknown keys are
75    /// ignored so that later versions can add fields.
76    pub fn parse(text: &str) -> Option<Self> {
77        let mut owner = Self::default();
78        for line in text.lines() {
79            let Some((key, value)) = line.split_once('=') else {
80                continue;
81            };
82            let value = value.trim().to_string();
83            match key.trim() {
84                "pid" => owner.pid = value.parse().ok()?,
85                "host" => owner.host = value,
86                "pid_namespace" => owner.pid_namespace = value,
87                "start_time" => owner.start_time = value,
88                "acquired_at_ms" => owner.acquired_at_ms = value.parse().unwrap_or(0),
89                "token" => owner.token = value,
90                "program" => owner.program = value,
91                _ => {}
92            }
93        }
94        (owner.pid != 0).then_some(owner)
95    }
96
97    /// One line for messages: every known field, then whether it still runs.
98    pub fn describe(&self) -> String {
99        let mut text = format!("pid={} host={}", self.pid, self.host);
100        for (key, value) in [
101            ("pid_namespace", &self.pid_namespace),
102            ("start_time", &self.start_time),
103            ("program", &self.program),
104        ] {
105            if !value.is_empty() {
106                text.push_str(&format!(" {key}={value}"));
107            }
108        }
109        if self.acquired_at_ms != 0 {
110            text.push_str(&format!(" acquired_at_ms={}", self.acquired_at_ms));
111        }
112        match self.liveness() {
113            Liveness::Alive => text.push_str(" (running)"),
114            Liveness::Gone(reason) | Liveness::Unknown(reason) => {
115                text.push_str(&format!(" ({reason})"))
116            }
117        }
118        text
119    }
120
121    /// Whether the owner still runs. Only an owner on this host and in this
122    /// PID namespace can be judged; a reused process id is told apart by its
123    /// start time where the system reports one.
124    pub fn liveness(&self) -> Liveness {
125        if self.host != host_name() {
126            return Liveness::Unknown(format!("held on another host, {}", self.host));
127        }
128        if self.pid_namespace != pid_namespace() {
129            return Liveness::Unknown("held in another PID namespace".into());
130        }
131        match process_alive(self.pid) {
132            Some(false) => Liveness::Gone(format!("owner process {} is gone", self.pid)),
133            Some(true) => match process_start_time(self.pid) {
134                Some(started) if !self.start_time.is_empty() && started != self.start_time => {
135                    Liveness::Gone(format!(
136                        "owner process {} is gone; its id now belongs to another process",
137                        self.pid
138                    ))
139                }
140                _ => Liveness::Alive,
141            },
142            None => Liveness::Unknown("cannot tell whether the owner runs".into()),
143        }
144    }
145}
146
147/// The name of this host, or an empty string when it cannot be read.
148pub fn host_name() -> String {
149    #[cfg(unix)]
150    {
151        let mut buffer = [0u8; 256];
152        // SAFETY: the buffer is writable for its whole length.
153        if unsafe { libc::gethostname(buffer.as_mut_ptr().cast(), buffer.len()) } == 0 {
154            let end = buffer.iter().position(|&byte| byte == 0).unwrap_or(0);
155            return String::from_utf8_lossy(&buffer[..end]).into_owned();
156        }
157        String::new()
158    }
159    #[cfg(not(unix))]
160    {
161        std::env::var("COMPUTERNAME").unwrap_or_default()
162    }
163}
164
165/// The PID namespace of this process (Linux), so that a container does not
166/// judge the process ids of another; empty elsewhere.
167pub fn pid_namespace() -> String {
168    #[cfg(target_os = "linux")]
169    if let Ok(target) = std::fs::read_link("/proc/self/ns/pid") {
170        return target.to_string_lossy().into_owned();
171    }
172    String::new()
173}
174
175/// When `pid` started, in clock ticks since boot (Linux); `None` elsewhere
176/// or when the process does not exist.
177pub fn process_start_time(pid: u32) -> Option<String> {
178    #[cfg(target_os = "linux")]
179    {
180        let stat = std::fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
181        // The command name in parentheses may hold spaces; the fields after
182        // it start with the state (field 3), so `starttime` (field 22) is
183        // the 20th.
184        let rest = &stat[stat.rfind(')')? + 1..];
185        rest.split_whitespace().nth(19).map(str::to_string)
186    }
187    #[cfg(not(target_os = "linux"))]
188    {
189        let _ = pid;
190        None
191    }
192}
193
194/// Whether process `pid` exists; `None` when the system cannot tell.
195pub fn process_alive(pid: u32) -> Option<bool> {
196    if pid == 0 {
197        return Some(false);
198    }
199    #[cfg(unix)]
200    {
201        let Ok(pid) = libc::pid_t::try_from(pid) else {
202            return Some(false);
203        };
204        // SAFETY: signal 0 only checks that the process exists.
205        if unsafe { libc::kill(pid, 0) } == 0 {
206            return Some(true);
207        }
208        match errno::errno().0 {
209            libc::ESRCH => Some(false),
210            libc::EPERM => Some(true),
211            _ => None,
212        }
213    }
214    #[cfg(windows)]
215    {
216        use windows_sys::Win32::Foundation::{CloseHandle, GetLastError, ERROR_INVALID_PARAMETER};
217        use windows_sys::Win32::System::Threading::{
218            GetExitCodeProcess, OpenProcess, PROCESS_QUERY_LIMITED_INFORMATION,
219        };
220        const STILL_ACTIVE: u32 = 259;
221        // SAFETY: the handle is checked and closed before returning.
222        unsafe {
223            let handle = OpenProcess(PROCESS_QUERY_LIMITED_INFORMATION, 0, pid);
224            if handle.is_null() {
225                return if GetLastError() == ERROR_INVALID_PARAMETER {
226                    Some(false)
227                } else {
228                    // Access denied and the like: the process exists.
229                    Some(true)
230                };
231            }
232            let mut code = 0u32;
233            let known = GetExitCodeProcess(handle, &mut code) != 0;
234            CloseHandle(handle);
235            known.then_some(code == STILL_ACTIVE)
236        }
237    }
238    #[cfg(not(any(unix, windows)))]
239    {
240        None
241    }
242}