From: Christian Ebner <c.ebner@proxmox.com>
To: pbs-devel@lists.proxmox.com
Subject: [PATCH v2 proxmox-backup 6/9] pbs-datastore: add BackupDir::lock_with_timeout()
Date: Thu, 3 Dec 2026 16:04:45 +0100 [thread overview]
Message-ID: <20261203150448.412515-7-c.ebner@proxmox.com> (raw)
In-Reply-To: <20261203150448.412515-1-c.ebner@proxmox.com>
Allow callers to wait up to a timeout when acquiring an exclusive
snapshot lock, supporting both file-based and legacy directory locks.
Verify the locked descriptor against the path's (st_dev, st_ino) after
locking in both modes so a concurrent snapshot removal and recreation
while waiting cannot yield a lock on an unlinked inode. This stricter
checks including st_dev now also apply to the pre-existing
lock_helper(), which previously only checked the i-node number.
Add unit tests covering contended waits, timeouts, and stale-inode
rejection.
Signed-off-by: Christian Ebner <c.ebner@proxmox.com>
---
pbs-datastore/src/backup_info.rs | 173 ++++++++++++++++++++++++++++---
1 file changed, 160 insertions(+), 13 deletions(-)
diff --git a/pbs-datastore/src/backup_info.rs b/pbs-datastore/src/backup_info.rs
index cce2b699f..85dea8ecc 100644
--- a/pbs-datastore/src/backup_info.rs
+++ b/pbs-datastore/src/backup_info.rs
@@ -718,18 +718,30 @@ impl BackupDir {
path.join(lock_file_path_helper(&self.ns, rpath))
}
- /// Locks a snapshot exclusively.
+ /// Locks a snapshot exclusively without blocking.
pub fn lock(&self) -> Result<BackupLockGuard, Error> {
+ self.lock_with_timeout(Duration::ZERO)
+ }
+
+ /// Locks a snapshot exclusively, waiting up to `timeout` if currently locked.
+ ///
+ /// Passing `Duration::ZERO` acquires the lock in non-blocking mode.
+ pub fn lock_with_timeout(&self, timeout: Duration) -> Result<BackupLockGuard, Error> {
if *OLD_LOCKING {
- lock_dir_noblock(
- &self.full_path(),
- "snapshot",
- "backup is running or snapshot is in use",
- )
- .map(BackupLockGuard::from)
+ if timeout.is_zero() {
+ lock_dir_noblock(
+ &self.full_path(),
+ "snapshot",
+ "backup is running or snapshot is in use",
+ )
+ .map(BackupLockGuard::from)
+ } else {
+ lock_dir_with_timeout(&self.full_path(), "snapshot", timeout)
+ .map(BackupLockGuard::from)
+ }
} else {
lock_helper(self.store.name(), &self.lock_path(), |p| {
- open_backup_lockfile(p, Some(Duration::from_secs(0)), true)
+ open_backup_lockfile(p, Some(timeout), true)
.with_context(|| format!("unable to acquire snapshot lock {p:?}"))
})
}
@@ -1222,6 +1234,41 @@ fn lock_file_path_helper(ns: &BackupNamespace, path: PathBuf) -> PathBuf {
to_return.join(format!("{first_eigthy}...{last_eighty}-{hash}"))
}
+fn verify_lock_inode(fd: RawFd, path: &Path) -> Result<(), Error> {
+ let fd_stat = nix::sys::stat::fstat(fd)?;
+
+ if nix::sys::stat::stat(path).map_or(true, |st| {
+ fd_stat.st_dev != st.st_dev || fd_stat.st_ino != st.st_ino
+ }) {
+ bail!("could not acquire lock, another thread modified the lock file");
+ }
+
+ Ok(())
+}
+
+fn lock_dir_with_timeout(
+ path: &Path,
+ what: &str,
+ timeout: Duration,
+) -> Result<proxmox_sys::fs::DirLockGuard, Error> {
+ let mut handle = nix::dir::Dir::open(
+ path,
+ nix::fcntl::OFlag::O_RDONLY | nix::fcntl::OFlag::O_CLOEXEC,
+ nix::sys::stat::Mode::empty(),
+ )
+ .map_err(|err| format_err!("unable to open {what} directory {path:?} for locking - {err}"))?;
+
+ proxmox_sys::fs::lock_file(&mut handle, true, Some(timeout)).map_err(|err| {
+ format_err!("unable to acquire lock on {what} directory {path:?} - {err}")
+ })?;
+
+ // If the directory was removed and/or replaced while waiting for the lock, the open fd
+ // points to an unlinked inode and does not provide mutual exclusion for `path`.
+ verify_lock_inode(handle.as_raw_fd(), path)?;
+
+ Ok(handle)
+}
+
/// Helps implement the double stat'ing procedure. It avoids certain race conditions upon lock
/// deletion.
///
@@ -1244,11 +1291,111 @@ where
let lock = lock_fn(path)?;
- let inode = nix::sys::stat::fstat(lock.as_raw_fd())?.st_ino;
-
- if nix::sys::stat::stat(path).map_or(true, |st| inode != st.st_ino) {
- bail!("could not acquire lock, another thread modified the lock file");
- }
+ verify_lock_inode(lock.as_raw_fd(), path)?;
Ok(lock)
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+ use std::sync::{Arc, Barrier};
+ use std::thread;
+
+ use proxmox_sys::fs::{lock_dir_noblock_shared, open_file_locked};
+ use tempfile::TempDir;
+
+ #[test]
+ fn test_lock_dir_with_timeout_waits_for_shared_release() {
+ let temp_dir = TempDir::new().unwrap();
+ let dir_path = temp_dir.path().to_path_buf();
+
+ let shared = lock_dir_noblock_shared(&dir_path, "test", "busy").unwrap();
+
+ // Contended lock with short timeout fails while shared lock is held.
+ assert!(lock_dir_with_timeout(&dir_path, "test", Duration::from_millis(50)).is_err());
+
+ // Releasing shared lock while waiter is blocked allows exclusive lock to succeed.
+ let barrier = Arc::new(Barrier::new(2));
+ let barrier_clone = Arc::clone(&barrier);
+ let holder = thread::spawn(move || {
+ barrier_clone.wait();
+ thread::sleep(Duration::from_millis(50));
+ drop(shared);
+ });
+
+ barrier.wait();
+ let exclusive = lock_dir_with_timeout(&dir_path, "test", Duration::from_secs(2)).unwrap();
+ holder.join().unwrap();
+
+ // Exclusive lock blocks new shared locks.
+ assert!(lock_dir_noblock_shared(&dir_path, "test", "busy").is_err());
+ drop(exclusive);
+ }
+
+ #[test]
+ fn test_lock_dir_with_timeout_rejects_replaced_dir() {
+ let parent = TempDir::new().unwrap();
+ let snap_path = parent.path().join("snap");
+ std::fs::create_dir(&snap_path).unwrap();
+
+ let exclusive = lock_dir_with_timeout(&snap_path, "test", Duration::from_secs(1)).unwrap();
+
+ let barrier = Arc::new(Barrier::new(2));
+ let barrier_clone = Arc::clone(&barrier);
+ let snap_path_clone = snap_path.clone();
+ let waiter = thread::spawn(move || {
+ barrier_clone.wait();
+ lock_dir_with_timeout(&snap_path_clone, "test", Duration::from_secs(2))
+ });
+
+ barrier.wait();
+ // Give waiter time to open the old directory inode and block in flock().
+ thread::sleep(Duration::from_millis(100));
+
+ // Simulate destroy() + concurrent recreate at the same path while holding the old lock.
+ std::fs::remove_dir(&snap_path).unwrap();
+ std::fs::create_dir(&snap_path).unwrap();
+ drop(exclusive);
+
+ // Waiter wakes up on the unlinked directory inode and must reject it via double-stat.
+ assert!(waiter.join().unwrap().is_err());
+ }
+
+ #[test]
+ fn test_verify_lock_inode_rejects_unlinked_and_replaced_file() {
+ let temp_dir = TempDir::new().unwrap();
+ let lock_path = temp_dir.path().join("snap.lck");
+
+ let exclusive =
+ open_file_locked(&lock_path, Duration::ZERO, true, CreateOptions::new()).unwrap();
+
+ let barrier = Arc::new(Barrier::new(2));
+ let barrier_clone = Arc::clone(&barrier);
+ let lock_path_clone = lock_path.clone();
+ let waiter = thread::spawn(move || {
+ barrier_clone.wait();
+ let file = open_file_locked(
+ &lock_path_clone,
+ Duration::from_secs(2),
+ true,
+ CreateOptions::new(),
+ )?;
+ verify_lock_inode(file.as_raw_fd(), &lock_path_clone)?;
+ Ok::<_, Error>(file)
+ });
+
+ barrier.wait();
+ // Give waiter time to open the old lock file inode and block in flock().
+ thread::sleep(Duration::from_millis(100));
+
+ // Simulate destroy() unlinking the lock file, followed by a new lock file creation.
+ std::fs::remove_file(&lock_path).unwrap();
+ let _new_lock =
+ open_file_locked(&lock_path, Duration::ZERO, true, CreateOptions::new()).unwrap();
+ drop(exclusive);
+
+ // Waiter wakes up on the unlinked inode and must fail verify_lock_inode().
+ assert!(waiter.join().unwrap().is_err());
+ }
+}
--
2.47.3
next prev parent reply other threads:[~2026-12-03 15:05 UTC|newest]
Thread overview: 10+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-12-03 15:04 [PATCH v2 proxmox-backup 0/9] pull: avoid lock contention with verify on unchanged snapshots Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 1/9] server: pull: refactor snapshot sync start logging Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 2/9] server: pull: defer sync stats instantiation until needed Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 3/9] server: pull: load source manifest into memory instead of a temp file Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 4/9] server: pull: move target manifest loading logic into reusable helper Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 5/9] server: pull: decouple decryption key gathering from logging Christian Ebner
2026-12-03 15:04 ` Christian Ebner [this message]
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 7/9] pbs-datastore: add create_locked_backup_dir_with_timeout() Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 8/9] server: pull: check for unchanged snapshots under a shared lock Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 9/9] server: pull: skip exclusive lock when source has no client log Christian Ebner
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20261203150448.412515-7-c.ebner@proxmox.com \
--to=c.ebner@proxmox.com \
--cc=pbs-devel@lists.proxmox.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is a public inbox, see mirroring instructions
for how to clone and mirror all data and code used for this inbox