runner_manager_platform/lock.rs
1// owner: d1-platform-core
2
3//! The host locks: one keeps a second agent from reconciling the same policies,
4//! one serialises runtime creation, and one serialises rotating credentials
5//! across a background service and foreground tools.
6//!
7//! `03-control-flows.md`, flow 3.1: *"A single-instance lock prevents two
8//! agents on one host from reconciling the same policy."* Flow 2.4: the agent
9//! *"takes the host-wide allocation lock before creating each local runtime"*.
10//! `07-security.md`'s threat table names the single-instance lock as one of the
11//! four controls on *"API replay or a duplicate agent creates too many
12//! runners"*.
13//!
14//! # Why an operating-system file lock, and not a PID file
15//!
16//! The requirement that decides the mechanism is *"released on crash rather
17//! than leaking"*. A PID file cannot do that: a process that is `SIGKILL`ed, or
18//! whose machine loses power, leaves the file behind, and every recovery
19//! strategy built on top — is that PID still alive? was it reused? — is
20//! guesswork that fails exactly when it matters. An operating-system file lock
21//! is released by the kernel when the holding process ends, for *any* reason,
22//! with no cooperation from the process and nothing left to clean up.
23//!
24//! Two mechanisms, one behaviour:
25//!
26//! - **Windows** opens the file for read and write while sharing only read
27//! access. A second acquirer asks for write access as well, which the
28//! holder's share mode denies, and gets `ERROR_SHARING_VIOLATION`. A
29//! *reader* asks only for read access, which the share mode permits — which
30//! is what lets the loser find out who beat it.
31//! - **Unix** takes `flock(LOCK_EX | LOCK_NB)`. `flock` is advisory and does
32//! not stand in the way of an ordinary `open` for reading, so the loser can
33//! read the holder record there too. Locks are held per open file
34//! description, so a second acquisition from the *same* process is refused as
35//! firmly as one from another process.
36//!
37//! # The lock file is never deleted
38//!
39//! Not on release, not on a clean shutdown, not by `Drop`. On Unix a lock is a
40//! property of the inode, so a holder that unlinks the file lets the next
41//! acquirer create and lock a *different* inode — after which two processes
42//! each hold "the lock" and neither can see the other. Leaving a zero-cost
43//! empty file behind is the whole price of not having that bug.
44//!
45//! # What "host-wide" means, precisely
46//!
47//! The lock is a file under [`crate::paths::AppPaths::state_dir`], as
48//! `05-infrastructure.md` specifies (*"state/ agent lock"*). Two agents
49//! contend if and only if they resolve the same state directory — which is what
50//! makes the lock host-wide for every configuration this product supports, and
51//! is worth stating rather than assuming: the platform-standard state directory
52//! is per-account on all three operating systems, so a daemon running as a
53//! service account and an interactive `daemon run` by a logged-in operator
54//! resolve *different* paths and would not contend. That is why
55//! `05-infrastructure.md` requires `service install` to record its resolved
56//! configuration and why `service status` reports it. A future host-wide
57//! machine lock (`%ProgramData%`, `/var/lock`) would need the installer to
58//! create it with the right ownership, which is `d3`'s territory, not this
59//! module's.
60
61use std::fmt;
62use std::fs::{File, OpenOptions};
63use std::io::{Read, Seek, SeekFrom, Write};
64use std::path::{Path, PathBuf};
65use std::time::{Duration, Instant};
66
67use chrono::{DateTime, Utc};
68use serde::{Deserialize, Serialize};
69
70use crate::paths::AppPaths;
71use crate::process::{Adoption, ProcessIdentity};
72
73/// Which host-wide operation is being excluded.
74#[derive(Debug, Clone, Copy, PartialEq, Eq, Serialize, Deserialize)]
75#[serde(rename_all = "snake_case")]
76pub enum LockKind {
77 /// Held for the whole life of the agent process. One holder per host means
78 /// one reconciler per host.
79 SingleInstance,
80 /// Held only while one runtime is being created, so that two concurrent
81 /// allocations cannot both read the same headroom and both use it.
82 Allocation,
83 /// Held while one process rotates the credential shared by a service and
84 /// foreground tools.
85 CredentialRenewal,
86}
87
88impl LockKind {
89 /// The file this lock lives in, inside `state/`.
90 #[must_use]
91 pub const fn file_name(self) -> &'static str {
92 match self {
93 Self::SingleInstance => "agent.lock",
94 Self::Allocation => "allocation.lock",
95 Self::CredentialRenewal => "credential-renewal.lock",
96 }
97 }
98
99 /// How to name this lock to an operator.
100 #[must_use]
101 pub const fn description(self) -> &'static str {
102 match self {
103 Self::SingleInstance => "the single-instance agent lock",
104 Self::Allocation => "the runtime allocation lock",
105 Self::CredentialRenewal => "the credential-renewal lock",
106 }
107 }
108
109 /// What an operator who lost the race should do about it. Present because
110 /// "the lock is held" is a statement and not yet an instruction.
111 #[must_use]
112 pub const fn advice(self) -> &'static str {
113 match self {
114 Self::SingleInstance => {
115 "Only one agent may reconcile policies on a host. Stop the other agent, or wait \
116 for it to exit; the operating system releases this lock when that process ends, \
117 including after a crash, so there is never anything to clean up by hand."
118 }
119 Self::Allocation => {
120 "This lock is held only for as long as it takes to create one runtime. Retry \
121 shortly."
122 }
123 Self::CredentialRenewal => {
124 "This lock is held only while one process rotates the shared credential. Retry \
125 shortly."
126 }
127 }
128 }
129}
130
131impl fmt::Display for LockKind {
132 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
133 f.write_str(self.description())
134 }
135}
136
137/// Who holds a lock, as recorded by the holder itself.
138///
139/// Written into the lock file after the lock is taken, so that the process
140/// that loses the race can say something useful instead of "somebody else".
141#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
142pub struct LockHolder {
143 /// The holder's process identity — a PID alone would not survive being
144 /// read back by a process that started after a reboot.
145 pub identity: ProcessIdentity,
146 /// The holder's executable, when it could be resolved. `05-infrastructure.md`
147 /// requires `service status` to report a stale or moved binary path, and
148 /// an operator looking at a contended lock has the same question.
149 pub executable: Option<PathBuf>,
150 /// When the lock was taken.
151 pub acquired_at: DateTime<Utc>,
152 /// Which lock the record belongs to. Recorded so that a file opened by
153 /// mistake is recognised rather than misreported.
154 pub lock: LockKind,
155}
156
157impl fmt::Display for LockHolder {
158 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
159 write!(f, "process {}", self.identity.pid())?;
160 if let Some(executable) = &self.executable {
161 write!(f, " ({})", executable.display())?;
162 }
163 write!(f, ", holding since {}", self.acquired_at.to_rfc3339())
164 }
165}
166
167/// Something went wrong taking or inspecting a lock.
168#[derive(Debug, thiserror::Error)]
169pub enum LockError {
170 /// Somebody else has it.
171 #[error(
172 "{kind} ({}) is already held on this host by {}. {} [refused with {}]",
173 path.display(),
174 describe(holder.as_deref()),
175 kind.advice(),
176 describe_refusal(*refused_with)
177 )]
178 Held {
179 /// Which lock.
180 kind: LockKind,
181 /// Where the lock file is, so the message is actionable on a host with
182 /// a non-default layout.
183 path: PathBuf,
184 /// Who holds it, when the record could be read. `None` is not the same
185 /// as "nobody": it means the holder had not finished identifying
186 /// itself, which is a race of microseconds and not a reason to proceed.
187 ///
188 /// Boxed because this variant travels inside a `Result` that `e1`
189 /// carries across a `spawn_blocking` boundary, and an inline
190 /// `LockHolder` makes that `Err` large enough for clippy's
191 /// `result_large_err` to refuse the build. The indirection costs one
192 /// allocation on a path that has already lost a lock race.
193 holder: Option<Box<LockHolder>>,
194 /// The operating system code the refusal actually carried.
195 ///
196 /// # Why an errno is in a user-facing message
197 ///
198 /// This variant has two causes that look identical once it is
199 /// constructed: the lock is genuinely somebody else's, or the operating
200 /// system said "would block" for a reason this code does not model. The
201 /// second is not hypothetical — a refusal that no reading of this
202 /// module explains has been seen in CI on both Unix platforms, for a
203 /// lock the same process had just released, and there was nothing in
204 /// the message to tell the two apart.
205 ///
206 /// Carrying the raw code costs a few characters and turns the next
207 /// occurrence from a mystery into a report. `None` where the platform
208 /// excluded at the open rather than at the lock call.
209 refused_with: Option<i32>,
210 },
211
212 /// The lock file could not be opened, read, or written.
213 #[error("cannot use the lock file {}: {source}", path.display())]
214 Io {
215 /// The lock file.
216 path: PathBuf,
217 /// The underlying error.
218 #[source]
219 source: std::io::Error,
220 },
221
222 /// The holder's own identity could not be read, so it could not record who
223 /// it is.
224 #[error("cannot record this process as the holder of {kind}: {source}")]
225 Identity {
226 /// Which lock.
227 kind: LockKind,
228 /// The underlying error.
229 #[source]
230 source: crate::process::ProcessError,
231 },
232}
233
234/// Renders the holder half of a [`LockError::Held`] message.
235fn describe(holder: Option<&LockHolder>) -> String {
236 match holder {
237 Some(holder) => holder.to_string(),
238 None => "a process that has not finished identifying itself".to_string(),
239 }
240}
241
242/// A held lock. Releasing it is dropping it.
243///
244/// There is no `release()` returning a `Result`, deliberately: releasing is
245/// closing a file descriptor, the kernel does it whether this program asks or
246/// not, and an API that suggested release could fail would invite a caller to
247/// handle a failure that does not exist.
248#[derive(Debug)]
249pub struct HostLock {
250 /// Held open for the lock's whole life. Closing it *is* the release, which
251 /// is why this field exists even though nothing reads it after
252 /// acquisition.
253 file: File,
254 path: PathBuf,
255 kind: LockKind,
256}
257
258impl HostLock {
259 /// Takes the lock, or reports who has it, without waiting.
260 ///
261 /// # Errors
262 ///
263 /// [`LockError::Held`] when another process has it, [`LockError::Io`] when
264 /// the lock file cannot be opened, and [`LockError::Identity`] when this
265 /// process cannot describe itself.
266 pub fn try_acquire(paths: &AppPaths, kind: LockKind) -> Result<Self, LockError> {
267 Self::try_acquire_at(&paths.state_dir().join(kind.file_name()), kind)
268 }
269
270 /// Takes the lock, retrying until `wait` elapses.
271 ///
272 /// `e1` takes the allocation lock before each runtime it creates, and brief
273 /// contention there is expected rather than exceptional, so waiting a
274 /// little is the right default for that caller. The single-instance lock
275 /// should normally use [`HostLock::try_acquire`]: a second agent is a
276 /// configuration problem, and waiting for it makes the problem quieter
277 /// rather than fixing it.
278 ///
279 /// # This blocks the calling thread
280 ///
281 /// The retry loop is `std::thread::sleep`, not a timer an executor can
282 /// park. `e1` takes the allocation lock from inside async reconciliation,
283 /// and calling this directly from a `tokio` task blocks a worker thread for
284 /// up to `wait` — starving every other task scheduled on it, and with a
285 /// current-thread runtime deadlocking against the very task that would
286 /// release the lock. **Async callers must wrap it in
287 /// [`tokio::task::spawn_blocking`]**, which is also where the returned
288 /// [`HostLock`] should then live, since dropping it is the release.
289 ///
290 /// [`HostLock::try_acquire`] does not block and is safe to call inline.
291 ///
292 /// # Errors
293 ///
294 /// As [`HostLock::try_acquire`], reporting the last holder seen.
295 pub fn acquire(paths: &AppPaths, kind: LockKind, wait: Duration) -> Result<Self, LockError> {
296 Self::acquire_at(&paths.state_dir().join(kind.file_name()), kind, wait)
297 }
298
299 /// [`HostLock::try_acquire`] against an explicit path.
300 ///
301 /// # Errors
302 ///
303 /// As [`HostLock::try_acquire`].
304 pub fn try_acquire_at(path: &Path, kind: LockKind) -> Result<Self, LockError> {
305 if let Some(parent) = path.parent() {
306 std::fs::create_dir_all(parent).map_err(|source| LockError::Io {
307 path: path.to_path_buf(),
308 source,
309 })?;
310 }
311
312 // Best effort in both contention branches below: an unreadable or
313 // half-written record makes the message vaguer, and is never a reason
314 // to behave as if the lock were free.
315 let held = |path: &Path, refused_with: Option<i32>| LockError::Held {
316 kind,
317 path: path.to_path_buf(),
318 holder: read_holder(path).ok().flatten().map(Box::new),
319 refused_with,
320 };
321
322 let file = match open_for_locking(path) {
323 Ok(file) => file,
324 // Windows excludes at the open itself, through the share mode, so
325 // this is where contention surfaces there. On Unix nothing fails
326 // the open for contention and this arm never fires.
327 Err(source) if sys::is_contention(&source) => {
328 return Err(held(path, source.raw_os_error()));
329 }
330 Err(source) => return Err(io_error(path, source)),
331 };
332
333 match sys::try_lock(&file).map_err(|source| io_error(path, source))? {
334 Acquired::Yes => {}
335 Acquired::No { refused_with } => return Err(held(path, refused_with)),
336 }
337
338 let lock = Self {
339 file,
340 path: path.to_path_buf(),
341 kind,
342 };
343 lock.record_holder()?;
344 Ok(lock)
345 }
346
347 /// [`HostLock::acquire`] against an explicit path.
348 ///
349 /// # Errors
350 ///
351 /// As [`HostLock::try_acquire`].
352 pub fn acquire_at(path: &Path, kind: LockKind, wait: Duration) -> Result<Self, LockError> {
353 let deadline = Instant::now() + wait;
354 loop {
355 match Self::try_acquire_at(path, kind) {
356 Ok(lock) => return Ok(lock),
357 Err(error @ LockError::Held { .. }) => {
358 if Instant::now() >= deadline {
359 return Err(error);
360 }
361 std::thread::sleep(RETRY_INTERVAL);
362 }
363 Err(other) => return Err(other),
364 }
365 }
366 }
367
368 /// Reads the holder record of a lock without trying to take it.
369 ///
370 /// Answers `Ok(None)` when the file does not exist or carries no readable
371 /// record. It deliberately says nothing about whether the lock is *held*:
372 /// the record outlives its writer by design, and the only authority on
373 /// whether a lock is free is trying to take it.
374 ///
375 /// # Errors
376 ///
377 /// [`LockError::Io`] when the file exists but cannot be read.
378 pub fn holder_of(path: &Path) -> Result<Option<LockHolder>, LockError> {
379 read_holder(path)
380 }
381
382 /// Where the lock file is.
383 #[must_use]
384 pub fn path(&self) -> &Path {
385 &self.path
386 }
387
388 /// Which lock this is.
389 #[must_use]
390 pub const fn kind(&self) -> LockKind {
391 self.kind
392 }
393
394 /// Whether the recorded holder of `path` is still running.
395 ///
396 /// For diagnostics — `host show` reporting a lock whose record names a
397 /// process that no longer exists tells an operator something a bare
398 /// "locked/unlocked" does not.
399 ///
400 /// # Errors
401 ///
402 /// [`LockError::Io`] when the record cannot be read.
403 pub fn recorded_holder_is_live(path: &Path) -> Result<bool, LockError> {
404 let Some(holder) = read_holder(path)? else {
405 return Ok(false);
406 };
407 Ok(matches!(holder.identity.recheck(), Ok(Adoption::Live)))
408 }
409
410 /// Writes this process's identity into the lock file.
411 ///
412 /// Runs *after* the lock is taken, which leaves a window of a few
413 /// microseconds in which a loser sees the previous holder's record or none
414 /// at all. That is why [`LockError::Held`] carries an `Option` and why the
415 /// message for `None` says the holder has not identified itself yet, rather
416 /// than implying the lock might be free.
417 fn record_holder(&self) -> Result<(), LockError> {
418 let holder = LockHolder {
419 identity: ProcessIdentity::of_current_process().map_err(|source| {
420 LockError::Identity {
421 kind: self.kind,
422 source,
423 }
424 })?,
425 executable: std::env::current_exe().ok(),
426 acquired_at: Utc::now(),
427 lock: self.kind,
428 };
429
430 let encoded = serde_json::to_vec_pretty(&holder).map_err(|source| {
431 io_error(
432 &self.path,
433 std::io::Error::new(std::io::ErrorKind::InvalidData, source),
434 )
435 })?;
436
437 let mut file = &self.file;
438 file.seek(SeekFrom::Start(0))
439 .map_err(|source| io_error(&self.path, source))?;
440 // The previous holder's record is longer or shorter than this one; a
441 // write without a truncate would leave its tail behind and produce
442 // unparseable JSON for the next reader.
443 file.set_len(0)
444 .map_err(|source| io_error(&self.path, source))?;
445 file.write_all(&encoded)
446 .map_err(|source| io_error(&self.path, source))?;
447 file.flush()
448 .map_err(|source| io_error(&self.path, source))?;
449 // Durable before the caller does anything with the lock: a record that
450 // is only in the page cache is not there for the operator diagnosing
451 // the machine that just stopped responding.
452 file.sync_all()
453 .map_err(|source| io_error(&self.path, source))
454 }
455}
456
457fn io_error(path: &Path, source: std::io::Error) -> LockError {
458 LockError::Io {
459 path: path.to_path_buf(),
460 source,
461 }
462}
463
464/// How often [`HostLock::acquire_at`] retries. Short enough that an allocation
465/// waiting on the lock is not noticeably delayed.
466const RETRY_INTERVAL: Duration = Duration::from_millis(25);
467
468/// What a non-blocking lock attempt answered, and — when it refused — why.
469///
470/// A bare `bool` threw away the one fact that would explain a refusal nobody
471/// can account for. See [`LockError::Held::refused_with`].
472#[derive(Debug, Clone, Copy, PartialEq, Eq)]
473// Windows excludes at the open, so its `try_lock` can only ever answer `Yes`
474// and the refusal arm is genuinely unreachable there. It is not dead code — it
475// is the whole answer on the two platforms that lock after opening.
476#[cfg_attr(windows, allow(dead_code))]
477pub(crate) enum Acquired {
478 Yes,
479 No { refused_with: Option<i32> },
480}
481
482/// Renders the refusal code for an operator, without pretending to interpret it.
483fn describe_refusal(code: Option<i32>) -> String {
484 match code {
485 Some(code) => format!("os error {code}"),
486 None => "the open itself, which is how this platform excludes".to_string(),
487 }
488}
489
490fn open_for_locking(path: &Path) -> std::io::Result<File> {
491 let mut options = OpenOptions::new();
492 // `truncate(false)` is explicit rather than implied: the previous holder's
493 // record must survive the open, because it is what a *loser* reads, and the
494 // loser's open is this same call.
495 options.read(true).write(true).create(true).truncate(false);
496 sys::prepare_for_locking(&mut options);
497 options.open(path)
498}
499
500fn read_holder(path: &Path) -> Result<Option<LockHolder>, LockError> {
501 let mut options = OpenOptions::new();
502 options.read(true);
503 sys::prepare_for_reading(&mut options);
504
505 let mut file = match options.open(path) {
506 Ok(file) => file,
507 Err(source) if source.kind() == std::io::ErrorKind::NotFound => return Ok(None),
508 Err(source) => return Err(io_error(path, source)),
509 };
510
511 let mut contents = String::new();
512 file.read_to_string(&mut contents)
513 .map_err(|source| io_error(path, source))?;
514
515 // An empty or half-written file is the acquisition race described on
516 // `HostLock::record_holder`, not a corrupt installation. Say "no record"
517 // and let the caller's message be vaguer.
518 Ok(serde_json::from_str(&contents).ok())
519}
520
521// ---------------------------------------------------------------------------
522// Platform implementations
523// ---------------------------------------------------------------------------
524
525#[cfg(windows)]
526mod sys {
527 use std::fs::{File, OpenOptions};
528 use std::io;
529 use std::os::windows::fs::OpenOptionsExt;
530
531 use windows::Win32::Storage::FileSystem::{
532 FILE_SHARE_DELETE, FILE_SHARE_READ, FILE_SHARE_WRITE,
533 };
534
535 /// The acquisition open. Sharing *read* only: a second acquirer also asks
536 /// for write access, which this share mode denies, so `CreateFile` fails
537 /// with `ERROR_SHARING_VIOLATION` before any lock call is needed. The
538 /// exclusion is the open itself, which is why `try_lock` below has nothing
539 /// left to do.
540 pub(super) fn prepare_for_locking(options: &mut OpenOptions) {
541 options.share_mode(FILE_SHARE_READ.0);
542 }
543
544 /// The diagnostic open. Read access only, and permissive sharing, so that
545 /// it is compatible with the holder's open in both directions: the holder
546 /// permits readers, and this permits the holder's read/write access.
547 pub(super) fn prepare_for_reading(options: &mut OpenOptions) {
548 options.share_mode(FILE_SHARE_READ.0 | FILE_SHARE_WRITE.0 | FILE_SHARE_DELETE.0);
549 }
550
551 /// Always `true` on Windows: if the open in `open_for_locking` succeeded,
552 /// this process is the exclusive writer, and when the process ends — for
553 /// any reason, including a crash — the kernel closes the handle and the
554 /// next acquirer's open succeeds.
555 pub(super) fn try_lock(_file: &File) -> io::Result<super::Acquired> {
556 Ok(super::Acquired::Yes)
557 }
558
559 /// Windows reports a share-mode conflict as `ERROR_SHARING_VIOLATION`, and
560 /// `std` maps it to a generic error, so the raw code is what identifies it.
561 pub(super) const SHARING_VIOLATION: i32 =
562 windows::Win32::Foundation::ERROR_SHARING_VIOLATION.0 as i32;
563
564 /// Whether an open failure means "somebody else holds it" rather than
565 /// something an operator should investigate.
566 pub(super) fn is_contention(error: &io::Error) -> bool {
567 error.raw_os_error() == Some(SHARING_VIOLATION)
568 }
569}
570
571#[cfg(unix)]
572mod sys {
573 use std::fs::{File, OpenOptions};
574 use std::io;
575 use std::os::unix::io::AsRawFd;
576
577 /// Nothing to prepare: on Unix the open is ordinary and the exclusion comes
578 /// from `flock` below.
579 pub(super) fn prepare_for_locking(_options: &mut OpenOptions) {}
580
581 pub(super) fn prepare_for_reading(_options: &mut OpenOptions) {}
582
583 /// `flock(LOCK_EX | LOCK_NB)`.
584 ///
585 /// Chosen over `fcntl` record locks for one reason that matters here:
586 /// `fcntl` locks are dropped when *any* file descriptor for the file is
587 /// closed by the process, so an unrelated `read_holder` in the same process
588 /// would silently release the agent's lock. `flock` locks belong to the
589 /// open file description and are immune to that.
590 pub(super) fn try_lock(file: &File) -> io::Result<super::Acquired> {
591 // SAFETY: `flock` takes a file descriptor and a flag word and touches
592 // no memory this program owns. The descriptor is valid for the life of
593 // `file`, which outlives the call.
594 let result = unsafe { libc::flock(file.as_raw_fd(), libc::LOCK_EX | libc::LOCK_NB) };
595 if result == 0 {
596 return Ok(super::Acquired::Yes);
597 }
598 let error = io::Error::last_os_error();
599 if is_contention(&error) {
600 return Ok(super::Acquired::No {
601 refused_with: error.raw_os_error(),
602 });
603 }
604 Err(error)
605 }
606
607 /// `EWOULDBLOCK` — and `EAGAIN`, which is the same number on Linux and
608 /// macOS but is written both ways in the documentation.
609 pub(super) fn is_contention(error: &io::Error) -> bool {
610 matches!(
611 error.raw_os_error(),
612 Some(code) if code == libc::EWOULDBLOCK || code == libc::EAGAIN
613 )
614 }
615}
616
617#[cfg(test)]
618mod tests {
619 use super::*;
620
621 use crate::process::{OutputMode, SpawnSpec};
622
623 /// The environment variable that turns `lock_holder_helper` below from a
624 /// no-op into a process that takes a lock and holds it until it is killed.
625 const HELPER_PATH: &str = "RUNNER_MANAGER_LOCK_HELPER_PATH";
626 /// What the helper prints once it holds the lock.
627 ///
628 /// Searched for *within* a line rather than at the start of one, because
629 /// libtest writes `test <name> ... ` with no trailing newline before the
630 /// test body runs — so the helper's first line of output is that prefix
631 /// followed by this marker, not the marker alone.
632 const HELPER_READY: &str = "@@LOCK-HELD@@";
633
634 fn lock_path(directory: &tempfile::TempDir, kind: LockKind) -> PathBuf {
635 directory.path().join(kind.file_name())
636 }
637
638 /// Takes the lock twice with `acquire` and reports whether exactly one
639 /// acquisition won.
640 ///
641 /// A helper returning `Result` rather than inline assertions, so that
642 /// `the_contention_check_catches_a_lock_that_never_excludes` can point it
643 /// at a lock that excludes nothing. A mutual-exclusion test that has only
644 /// ever been run against a working lock cannot distinguish "the lock works"
645 /// from "the test asserts nothing".
646 fn check_mutual_exclusion<G>(acquire: impl Fn() -> Result<G, LockError>) -> Result<(), String> {
647 let first = acquire().map_err(|error| format!("the first acquisition failed: {error}"))?;
648
649 let outcome = match acquire() {
650 Ok(_) => Err("both acquisitions succeeded; nothing is being excluded".to_string()),
651 Err(LockError::Held { .. }) => Ok(()),
652 Err(other) => Err(format!(
653 "the second acquisition failed, but not because the lock was held: {other}"
654 )),
655 };
656
657 drop(first);
658 outcome
659 }
660
661 #[test]
662 fn two_contenders_produce_exactly_one_holder() {
663 let directory = tempfile::tempdir().expect("a temporary directory");
664 let path = lock_path(&directory, LockKind::SingleInstance);
665
666 check_mutual_exclusion(|| HostLock::try_acquire_at(&path, LockKind::SingleInstance))
667 .expect("the single-instance lock must admit exactly one holder");
668 }
669
670 #[test]
671 fn the_contention_check_catches_a_lock_that_never_excludes() {
672 let complaint = check_mutual_exclusion(|| Ok::<(), LockError>(()))
673 .expect_err("a lock that excludes nothing must be caught");
674 assert!(
675 complaint.contains("nothing is being excluded"),
676 "the complaint must name the failure mode, got: {complaint}"
677 );
678 }
679
680 #[test]
681 fn releasing_the_lock_lets_the_next_contender_take_it() {
682 let directory = tempfile::tempdir().expect("a temporary directory");
683 let path = lock_path(&directory, LockKind::SingleInstance);
684
685 let first = HostLock::try_acquire_at(&path, LockKind::SingleInstance).expect("acquired");
686 assert!(HostLock::try_acquire_at(&path, LockKind::SingleInstance).is_err());
687 drop(first);
688
689 let second = HostLock::try_acquire_at(&path, LockKind::SingleInstance)
690 .expect("the lock must be free once the holder drops it");
691 assert_eq!(second.path(), path);
692 assert_eq!(second.kind(), LockKind::SingleInstance);
693 }
694
695 #[test]
696 fn independent_host_locks_do_not_contend_with_each_other() {
697 // `e1` takes the allocation lock while the agent already holds the
698 // single-instance lock. If those two shared a file, the agent would
699 // deadlock against itself on the first runtime it tried to create.
700 let directory = tempfile::tempdir().expect("a temporary directory");
701
702 let instance = HostLock::try_acquire_at(
703 &lock_path(&directory, LockKind::SingleInstance),
704 LockKind::SingleInstance,
705 )
706 .expect("the instance lock is free");
707
708 let allocation = HostLock::try_acquire_at(
709 &lock_path(&directory, LockKind::Allocation),
710 LockKind::Allocation,
711 )
712 .expect("the allocation lock is a different lock and must be free");
713
714 let renewal = HostLock::try_acquire_at(
715 &lock_path(&directory, LockKind::CredentialRenewal),
716 LockKind::CredentialRenewal,
717 )
718 .expect("the credential-renewal lock is a different lock and must be free");
719
720 assert_ne!(instance.path(), allocation.path());
721 assert_ne!(instance.path(), renewal.path());
722 assert_ne!(allocation.path(), renewal.path());
723 assert_ne!(
724 LockKind::SingleInstance.file_name(),
725 LockKind::Allocation.file_name()
726 );
727 assert_ne!(
728 LockKind::Allocation.file_name(),
729 LockKind::CredentialRenewal.file_name()
730 );
731 }
732
733 #[test]
734 fn the_loser_gets_a_message_naming_the_holder_and_saying_what_to_do() {
735 let directory = tempfile::tempdir().expect("a temporary directory");
736 let path = lock_path(&directory, LockKind::SingleInstance);
737
738 let _held = HostLock::try_acquire_at(&path, LockKind::SingleInstance).expect("acquired");
739 let error = HostLock::try_acquire_at(&path, LockKind::SingleInstance)
740 .expect_err("the second acquisition must fail");
741
742 let LockError::Held { holder, kind, .. } = &error else {
743 panic!("expected a contention error, got {error}");
744 };
745 assert_eq!(*kind, LockKind::SingleInstance);
746
747 let holder = holder.as_ref().expect("the holder recorded itself");
748 assert_eq!(holder.identity.pid(), std::process::id());
749 assert_eq!(holder.lock, LockKind::SingleInstance);
750 assert_eq!(
751 holder.executable.as_deref(),
752 std::env::current_exe().ok().as_deref()
753 );
754
755 let message = error.to_string();
756 assert!(
757 message.contains(&std::process::id().to_string()),
758 "the message must name the holding process: {message}"
759 );
760 assert!(
761 message.contains("Stop the other agent"),
762 "the message must say what to do, not only what happened: {message}"
763 );
764 }
765
766 #[test]
767 fn the_recorded_holder_survives_a_read_by_a_second_process_shape() {
768 // Reading the record must work while the lock is held — on Windows that
769 // is a share-mode question and it is easy to get wrong in a way that
770 // only shows up when it matters, because the only caller is the loser.
771 let directory = tempfile::tempdir().expect("a temporary directory");
772 let path = lock_path(&directory, LockKind::SingleInstance);
773
774 let _held = HostLock::try_acquire_at(&path, LockKind::SingleInstance).expect("acquired");
775
776 let holder = HostLock::holder_of(&path)
777 .expect("the record must be readable while the lock is held")
778 .expect("a record must be there");
779 assert_eq!(holder.identity.pid(), std::process::id());
780 assert!(HostLock::recorded_holder_is_live(&path).expect("readable"));
781 }
782
783 #[test]
784 fn a_stale_record_is_reported_as_not_live() {
785 let directory = tempfile::tempdir().expect("a temporary directory");
786 let path = lock_path(&directory, LockKind::SingleInstance);
787
788 // A record naming a process that has come and gone: exactly what a
789 // crashed holder leaves behind.
790 //
791 // THE CHILD HAS TO OUTLIVE ITS OWN IDENTITY LOOKUP.
792 //
793 // `SpawnSpec::spawn` reads `ProcessIdentity::of_child` immediately after
794 // starting the process, because the start token is what stops a reused
795 // pid from being mistaken for the original. A child that exits INSTANTLY
796 // -- `true` did -- can be gone before that read, and the spawn then
797 // fails with `NoSuchProcess` rather than yielding the identity this test
798 // needs. It blocked release 0.1.5 on the macOS leg, where a loaded
799 // runner made the race easy to lose.
800 //
801 // So the child sleeps briefly: long enough to be observed, short enough
802 // that waiting for it costs nothing. What is being tested is unchanged
803 // -- the record is stale by the time it is read, because `wait` below
804 // returns only after the process is gone.
805 let mut child = SpawnSpec::new(if cfg!(windows) { "cmd" } else { "sh" })
806 .args(if cfg!(windows) {
807 vec!["/C", "exit", "0"]
808 } else {
809 vec!["-c", "sleep 0.3"]
810 })
811 .spawn()
812 .expect("the child starts");
813 let identity = child.identity().clone();
814 child.wait().expect("the child exits");
815
816 let stale = LockHolder {
817 identity,
818 executable: None,
819 acquired_at: Utc::now(),
820 lock: LockKind::SingleInstance,
821 };
822 std::fs::write(&path, serde_json::to_vec(&stale).expect("serialisable")).expect("writable");
823
824 assert!(
825 !HostLock::recorded_holder_is_live(&path).expect("readable"),
826 "a record naming a dead process must not be reported as live"
827 );
828 // And the lock itself is free, because nothing holds the file.
829 HostLock::try_acquire_at(&path, LockKind::SingleInstance)
830 .expect("a stale record must not keep the lock held");
831 }
832
833 #[test]
834 fn an_unidentified_holder_still_reads_as_a_holder() {
835 // The microsecond between taking the lock and writing the record. The
836 // message gets vaguer; the exclusion does not, and the wording must not
837 // leave a reader thinking the lock might be free.
838 let no_record = describe(None);
839 assert!(
840 no_record.contains("not finished identifying itself"),
841 "an unidentified holder must still read as a holder: {no_record}"
842 );
843
844 let error = LockError::Held {
845 kind: LockKind::SingleInstance,
846 path: PathBuf::from("/var/lib/runner-manager/state/agent.lock"),
847 holder: None,
848 refused_with: Some(35),
849 };
850 let message = error.to_string();
851 assert!(message.contains("already held"), "{message}");
852 assert!(message.contains("agent.lock"), "{message}");
853 assert!(message.contains("Stop the other agent"), "{message}");
854 // The refusal code is in the message because this variant has two
855 // causes that are otherwise indistinguishable once constructed: a lock
856 // that really is somebody else's, and a refusal this module does not
857 // model. Without it, the second reads exactly like the first.
858 assert!(message.contains("os error 35"), "{message}");
859
860 let at_open = LockError::Held {
861 kind: LockKind::SingleInstance,
862 path: PathBuf::from("/var/lib/runner-manager/state/agent.lock"),
863 holder: None,
864 refused_with: None,
865 };
866 assert!(
867 at_open.to_string().contains("the open itself"),
868 "a platform that excludes at the open says so rather than showing a bare `None`: {at_open}"
869 );
870 }
871
872 #[test]
873 fn acquire_waits_and_then_reports_the_holder() {
874 let directory = tempfile::tempdir().expect("a temporary directory");
875 let path = lock_path(&directory, LockKind::Allocation);
876
877 let _held = HostLock::try_acquire_at(&path, LockKind::Allocation).expect("acquired");
878
879 let wait = Duration::from_millis(200);
880 let started = Instant::now();
881 let error = HostLock::acquire_at(&path, LockKind::Allocation, wait)
882 .expect_err("the lock is held for the whole window");
883 let elapsed = started.elapsed();
884
885 assert!(matches!(error, LockError::Held { .. }), "{error}");
886 assert!(
887 elapsed >= wait,
888 "acquire must actually wait; it returned after {elapsed:?} of a {wait:?} window"
889 );
890 }
891
892 #[test]
893 fn acquire_returns_immediately_when_the_lock_is_free() {
894 let directory = tempfile::tempdir().expect("a temporary directory");
895 let path = lock_path(&directory, LockKind::Allocation);
896
897 let started = Instant::now();
898 let lock = HostLock::acquire_at(&path, LockKind::Allocation, Duration::from_secs(30))
899 .expect("the lock is free");
900 assert!(
901 started.elapsed() < Duration::from_secs(5),
902 "a free lock must not be waited for"
903 );
904 drop(lock);
905 }
906
907 #[test]
908 fn try_acquire_uses_the_state_directory() {
909 let root = tempfile::tempdir().expect("a temporary directory");
910 let paths = AppPaths::rooted_at(root.path());
911
912 let lock = HostLock::try_acquire(&paths, LockKind::SingleInstance).expect("acquired");
913 assert_eq!(lock.path(), paths.state_dir().join("agent.lock"));
914 assert!(
915 lock.path().exists(),
916 "the lock file must have been created under state/, as 05-infrastructure.md says"
917 );
918 }
919
920 // -----------------------------------------------------------------------
921 // The cross-process half of the Definition of Done
922 // -----------------------------------------------------------------------
923
924 /// Runs as an ordinary no-op test, unless `RUNNER_MANAGER_LOCK_HELPER_PATH`
925 /// is set — in which case this process *is* the second contender: it takes
926 /// the lock named by that variable, announces that it has it, and then
927 /// waits to be killed.
928 ///
929 /// Re-executing the test binary is what makes a genuinely separate process
930 /// available without shipping a second binary. The two tests below drive
931 /// it.
932 #[test]
933 fn lock_holder_helper() {
934 let Some(path) = std::env::var_os(HELPER_PATH) else {
935 return;
936 };
937
938 let _lock = HostLock::try_acquire_at(Path::new(&path), LockKind::SingleInstance)
939 .expect("the helper must be able to take the lock");
940
941 println!("{HELPER_READY} {}", std::process::id());
942 let _ = std::io::stdout().flush();
943
944 // Long enough that the parent always kills it first, short enough that
945 // a parent which somehow died leaves nothing behind for long.
946 std::thread::sleep(Duration::from_secs(120));
947 }
948
949 /// Starts the helper and waits until it reports that it holds the lock.
950 fn start_helper(path: &Path) -> (crate::process::ChildProcess, u32) {
951 let executable = std::env::current_exe().expect("the test binary's own path");
952
953 let mut child = SpawnSpec::new(executable)
954 .args([
955 "--exact",
956 "lock::tests::lock_holder_helper",
957 // Without this, libtest swallows the helper's announcement and
958 // the parent waits forever for a line that was captured.
959 "--nocapture",
960 "--test-threads=1",
961 ])
962 .env(HELPER_PATH, path)
963 .output(OutputMode::Capture)
964 .spawn()
965 .expect("the helper process starts");
966
967 let stdout = child.take_stdout().expect("captured");
968 let (sender, receiver) = std::sync::mpsc::channel();
969 std::thread::spawn(move || {
970 use std::io::BufRead as _;
971 for line in std::io::BufReader::new(stdout).lines() {
972 let Ok(line) = line else { break };
973 if let Some((_, rest)) = line.split_once(HELPER_READY) {
974 let _ = sender.send(rest.trim().to_string());
975 return;
976 }
977 }
978 let _ = sender.send(String::new());
979 });
980
981 let announced = receiver
982 .recv_timeout(Duration::from_secs(60))
983 .expect("the helper must announce that it holds the lock");
984 let pid: u32 = announced
985 .parse()
986 .unwrap_or_else(|_| panic!("the helper announced {announced:?} instead of a PID"));
987
988 (child, pid)
989 }
990
991 #[test]
992 fn two_processes_contending_produce_exactly_one_holder() {
993 let directory = tempfile::tempdir().expect("a temporary directory");
994 let path = lock_path(&directory, LockKind::SingleInstance);
995
996 let (mut helper, helper_pid) = start_helper(&path);
997 assert_ne!(helper_pid, std::process::id());
998
999 let error = HostLock::try_acquire_at(&path, LockKind::SingleInstance)
1000 .expect_err("a second agent must not get the lock");
1001
1002 let LockError::Held { holder, .. } = &error else {
1003 panic!("expected a contention error, got {error}");
1004 };
1005 let holder = holder.as_ref().expect("the helper recorded itself");
1006 assert_eq!(
1007 holder.identity.pid(),
1008 helper_pid,
1009 "the record must name the process that actually holds it"
1010 );
1011 assert!(
1012 error.to_string().contains(&helper_pid.to_string()),
1013 "the loser's message must name the holder: {error}"
1014 );
1015
1016 helper.stop(Duration::ZERO).expect("cleanup");
1017 }
1018
1019 #[test]
1020 fn killing_the_holder_releases_the_lock_with_no_manual_cleanup() {
1021 let directory = tempfile::tempdir().expect("a temporary directory");
1022 let path = lock_path(&directory, LockKind::SingleInstance);
1023
1024 let (mut helper, helper_pid) = start_helper(&path);
1025 assert!(
1026 HostLock::try_acquire_at(&path, LockKind::SingleInstance).is_err(),
1027 "the helper holds it"
1028 );
1029
1030 // `Duration::ZERO` leaves the helper no grace period. On Windows that
1031 // is literally straight to `TerminateProcess`, because there is no
1032 // signal to send; on Unix a SIGTERM is still sent first, but the grace
1033 // period it is given is zero, so SIGKILL follows before the helper can
1034 // act on it. Either way no destructor and no cleanup code runs, which
1035 // is the point: this is a crash, not a shutdown.
1036 helper.stop(Duration::ZERO).expect("the helper is killed");
1037 assert!(!helper.is_running().expect("observable"));
1038
1039 // Nothing is deleted, nothing is reset, no PID file is reaped: the next
1040 // acquisition simply succeeds.
1041 let recovered = HostLock::try_acquire_at(&path, LockKind::SingleInstance)
1042 .unwrap_or_else(|error| panic!("the lock leaked after its holder was killed: {error}"));
1043
1044 assert!(
1045 path.exists(),
1046 "the lock file itself must survive; deleting it is how two processes end up \
1047 locking different inodes"
1048 );
1049
1050 let holder = HostLock::holder_of(&path)
1051 .expect("readable")
1052 .expect("the new holder recorded itself");
1053 assert_eq!(holder.identity.pid(), std::process::id());
1054 assert_ne!(
1055 holder.identity.pid(),
1056 helper_pid,
1057 "the record must have been replaced, not inherited"
1058 );
1059 drop(recovered);
1060 }
1061}