From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id 0565F1FF0C2 for ; Thu, 03 Dec 2026 16:05:25 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id 5A8F4217F5; Thu, 03 Dec 2026 16:05:12 +0100 (CET) From: Christian Ebner 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 Message-ID: <20261203150448.412515-7-c.ebner@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261203150448.412515-1-c.ebner@proxmox.com> References: <20261203150448.412515-1-c.ebner@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1796310301728 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.331 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: 3YTJJHPOHT5MXEW3YEGOMSGG63RSJOYO X-Message-ID-Hash: 3YTJJHPOHT5MXEW3YEGOMSGG63RSJOYO X-MailFrom: c.ebner@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox Backup Server development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: 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 --- 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 { + 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 { 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 { + 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