link_cli/store_lock/
owner.rs1use std::time::{SystemTime, UNIX_EPOCH};
20
21#[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#[derive(Debug, Clone, PartialEq, Eq)]
35pub enum Liveness {
36 Alive,
37 Gone(String),
39 Unknown(String),
41}
42
43impl LockOwner {
44 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 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 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 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 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
147pub fn host_name() -> String {
149 #[cfg(unix)]
150 {
151 let mut buffer = [0u8; 256];
152 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
165pub 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
175pub 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 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
194pub 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 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 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 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}