Skip to main content

link_cli/store_lock/
pid_lock.rs

1//! `--lock pid`: a lock directory, `<db>.lock.d`, holding an `owner` record.
2//!
3//! The directory is built under a private name with its record inside, then
4//! renamed to `<db>.lock.d`. A rename onto an existing directory fails, so
5//! exactly one process publishes the lock, and a published lock always has
6//! its record. The operating system does not release it when the owner
7//! exits, so a waiter breaks the lock when the record names a process on
8//! this host, in this PID namespace, that is gone. Works where `flock` does
9//! not, such as on some network file systems.
10
11use std::fs;
12use std::io::Write;
13use std::path::{Path, PathBuf};
14use std::time::{Duration, SystemTime};
15
16use super::owner::{Liveness, LockOwner};
17use crate::diagnostics;
18use crate::storage::lock::unique_token;
19
20/// A directory without a readable record is treated as abandoned after this
21/// long (an owner crashed between creating and renaming it, or another tool
22/// made it).
23const UNOWNED_GRACE: Duration = Duration::from_secs(10);
24const OWNER_FILE: &str = "owner";
25
26/// `<db>.lock.d`.
27pub fn lock_dir_path(store: &Path) -> PathBuf {
28    sibling(store, ".lock.d")
29}
30
31/// A held `--lock pid` lock; dropping it removes the directory.
32#[derive(Debug)]
33pub struct PidLock {
34    dir: PathBuf,
35    token: String,
36}
37
38/// The outcome of one attempt.
39pub enum Attempt {
40    Acquired(PidLock),
41    /// Held by the owner of this record, or by a directory without one.
42    Held(Option<LockOwner>),
43}
44
45/// The owner record of `dir`, if it has a readable one.
46pub fn read_owner(dir: &Path) -> Option<LockOwner> {
47    LockOwner::parse(&fs::read_to_string(dir.join(OWNER_FILE)).ok()?)
48}
49
50/// Why the lock in `dir` may be broken, if it may.
51pub fn stale_reason(dir: &Path, owner: Option<&LockOwner>) -> Option<String> {
52    match owner {
53        Some(owner) => match owner.liveness() {
54            Liveness::Gone(reason) => Some(reason),
55            Liveness::Alive | Liveness::Unknown(_) => None,
56        },
57        None => {
58            let age = fs::metadata(dir)
59                .and_then(|metadata| metadata.modified())
60                .ok()
61                .and_then(|modified| SystemTime::now().duration_since(modified).ok())?;
62            (age >= UNOWNED_GRACE)
63                .then(|| format!("no owner record for {} s", UNOWNED_GRACE.as_secs()))
64        }
65    }
66}
67
68/// Publishes the lock once, breaking a stale one first.
69pub fn try_acquire(dir: &Path, trace: bool) -> std::io::Result<Attempt> {
70    if let Some(parent) = dir.parent().filter(|parent| !parent.as_os_str().is_empty()) {
71        fs::create_dir_all(parent)?;
72    }
73    let token = unique_token();
74    let owner = LockOwner::current(&token);
75    let mut last_error = None;
76    for _ in 0..4 {
77        let staging = sibling(dir, &format!(".{}.{}.tmp", owner.pid, unique_token()));
78        fs::create_dir(&staging)?;
79        let published = write_owner(&staging, &owner).and_then(|()| fs::rename(&staging, dir));
80        let error = match published {
81            Ok(()) => {
82                return Ok(Attempt::Acquired(PidLock {
83                    dir: dir.to_path_buf(),
84                    token,
85                }))
86            }
87            Err(error) => error,
88        };
89        let _ = fs::remove_dir_all(&staging);
90        if fs::symlink_metadata(dir).is_err() {
91            // Released between the rename and this check, or a real error.
92            last_error = Some(error);
93            continue;
94        }
95        let holder = read_owner(dir);
96        match stale_reason(dir, holder.as_ref()) {
97            Some(reason) => {
98                if trace {
99                    diagnostics::stderr!("[TRACE] Breaking stale lock {}: {reason}", dir.display());
100                }
101                break_stale(dir, holder.as_ref());
102            }
103            None => return Ok(Attempt::Held(holder)),
104        }
105    }
106    match last_error {
107        Some(error) => Err(error),
108        None => Ok(Attempt::Held(read_owner(dir))),
109    }
110}
111
112/// Moves a stale lock aside and removes it. Should a live owner have
113/// published a new lock in between, its directory is moved back. A lock
114/// that cannot be moved (another waiter moved it first, or the directory is
115/// not writable) is left alone: the next attempt sees what became of it.
116fn break_stale(dir: &Path, expected: Option<&LockOwner>) {
117    let tombstone = sibling(
118        dir,
119        &format!(".{}.{}.stale", std::process::id(), unique_token()),
120    );
121    if fs::rename(dir, &tombstone).is_err() {
122        return;
123    }
124    let moved = read_owner(&tombstone);
125    if moved.as_ref().map(|owner| &owner.token) == expected.map(|owner| &owner.token) {
126        let _ = fs::remove_dir_all(&tombstone);
127    } else if fs::rename(&tombstone, dir).is_err() {
128        // A third process published meanwhile; the moved owner has lost its
129        // lock. Keep its directory for inspection.
130    }
131}
132
133fn write_owner(dir: &Path, owner: &LockOwner) -> std::io::Result<()> {
134    let mut file = fs::File::create(dir.join(OWNER_FILE))?;
135    file.write_all(owner.to_record().as_bytes())?;
136    file.sync_all()
137}
138
139impl PidLock {
140    pub fn path(&self) -> &Path {
141        &self.dir
142    }
143}
144
145impl Drop for PidLock {
146    fn drop(&mut self) {
147        // Only remove the lock while it is still ours.
148        if read_owner(&self.dir).is_some_and(|owner| owner.token == self.token) {
149            let tombstone = sibling(&self.dir, &format!(".{}.released", self.token));
150            if fs::rename(&self.dir, &tombstone).is_ok() {
151                let _ = fs::remove_dir_all(&tombstone);
152            }
153        }
154    }
155}
156
157fn sibling(path: &Path, suffix: &str) -> PathBuf {
158    let mut name = path.as_os_str().to_owned();
159    name.push(suffix);
160    PathBuf::from(name)
161}