From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [45.144.208.40]) by lore.proxmox.com (Postfix) with ESMTPS id 2A45D1FF09F for ; Tue, 01 Dec 2026 15:14:28 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id E7654216C8; Tue, 01 Dec 2026 15:14:17 +0100 (CET) From: Christian Ebner To: pbs-devel@lists.proxmox.com Subject: [PATCH proxmox-backup 4/4] server: pull: check unchanged snapshots under a shared lock Date: Tue, 1 Dec 2026 15:14:01 +0100 Message-ID: <20261201141401.438577-5-c.ebner@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261201141401.438577-1-c.ebner@proxmox.com> References: <20261201141401.438577-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: 1796134452613 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.337 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: JS55AZ3CJ3XMHH4DXB7HUJDJZ36YSM7W X-Message-ID-Hash: JS55AZ3CJ3XMHH4DXB7HUJDJZ36YSM7W 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: Each pull re-syncs the newest snapshot of a group already present on the target, to pick up a client log that was not yet available during the previous run. This took an exclusive snapshot lock up front, even though the snapshot is usually unchanged. Since commit 7241811f7 ("fix #6990: server: drop verify state on non-decrypt pull job") sync no longer passes the source's verify state on to the target and therefore a verify job on the target checks every newly synced snapshot, making lock contention more likely. Verification holds a shared lock on the snapshot, so the exclusive lock attempt of a concurrent sync fails and aborts the whole group, delaying newer snapshots syncs until the next run. To reduce lock contention, acquire a shared lock first for existing, non-corrupt snapshots and upgrade it in place to an exclusive lock via BackupLockGuard::try_upgrade() only if the target actually needs changes. This avoids performing operations which can be under a shared lock to be under an exclusive lock. Whether the source has a client log or not is checked via the snapshot listing, so also snapshots without one can be checked under the shared lock alone. Link: https://forum.proxmox.com/threads/187896/ Signed-off-by: Christian Ebner --- src/server/pull.rs | 129 ++++++++++++++++++++++++++++++++++++++------- 1 file changed, 109 insertions(+), 20 deletions(-) diff --git a/src/server/pull.rs b/src/server/pull.rs index 55f8773a8..2f861762b 100644 --- a/src/server/pull.rs +++ b/src/server/pull.rs @@ -23,7 +23,7 @@ use pbs_api_types::{ VerifyState, print_store_and_ns, }; use pbs_client::BackupRepository; -use pbs_config::CachedUserInfo; +use pbs_config::{BackupLockGuard, CachedUserInfo}; use pbs_datastore::data_blob::{DataBlob, DataChunkBuilder}; use pbs_datastore::dynamic_index::{DynamicIndexReader, DynamicIndexWriter}; use pbs_datastore::fixed_index::{FixedIndexReader, FixedIndexWriter}; @@ -613,21 +613,71 @@ async fn pull_single_archive<'a>( Ok(sync_stats) } +enum SnapshotLockState { + Shared(BackupLockGuard), + Exclusive(BackupLockGuard), + Released, +} + +/// Snapshot lock held while pulling a snapshot. +/// +/// Existing, non-corrupt snapshots start under a shared lock so unchanged snapshots can be checked +/// concurrently with readers such as verify jobs, and upgrade in place to an exclusive lock only +/// when target modifications are actually needed. +struct SnapshotLock(SnapshotLockState); + +impl SnapshotLock { + fn shared(guard: BackupLockGuard) -> Self { + Self(SnapshotLockState::Shared(guard)) + } + + fn exclusive(guard: BackupLockGuard) -> Self { + Self(SnapshotLockState::Exclusive(guard)) + } + + fn is_exclusive(&self) -> bool { + matches!(self.0, SnapshotLockState::Exclusive(_)) + } + + fn upgrade_to_exclusive(&mut self) -> Result<(), Error> { + match std::mem::replace(&mut self.0, SnapshotLockState::Released) { + SnapshotLockState::Exclusive(guard) => { + self.0 = SnapshotLockState::Exclusive(guard); + Ok(()) + } + SnapshotLockState::Shared(guard) => { + // Avoid immediate failure if a concurrent operation is not that long running + let guard = guard.try_upgrade(Some(Duration::from_secs(15)))?; + self.0 = SnapshotLockState::Exclusive(guard); + Ok(()) + } + SnapshotLockState::Released => { + bail!("internal error: snapshot lock was already released"); + } + } + } +} + /// Actual implementation of pulling a snapshot. /// /// Pulling a snapshot consists of the following steps: /// - (Re)download the manifest into memory -/// -- if it matches and is not corrupt, only download log and treat snapshot as already synced +/// -- if it matches and is not corrupt, only download log (if present on source) and treat +/// snapshot as already synced +/// - Upgrade a shared lock to an exclusive lock before touching the target snapshot /// - Iterate over referenced files /// -- if file already exists, verify contents /// -- if not, pull it from the remote /// - Download log if not already existing +#[allow(clippy::too_many_arguments)] async fn pull_snapshot<'a>( params: Arc, reader: Arc, snapshot: &'a pbs_datastore::BackupDir, + snap_lock: &mut SnapshotLock, encountered_chunks: Arc>, corrupt: bool, + source_has_client_log: bool, log_sender: Arc, ) -> Result, Error> { let prefix = snapshot.backup_time_string().to_owned(); @@ -686,8 +736,13 @@ async fn pull_snapshot<'a>( Ok::<(), Error>(()) }; - let unchanged = async |crypt_config: Option>| { - fetch_log(crypt_config).await?; + let unchanged = async |snap_lock: &mut SnapshotLock, crypt_config: Option>| { + if !client_log_name.exists() && (snap_lock.is_exclusive() || source_has_client_log) { + snap_lock + .upgrade_to_exclusive() + .with_context(|| prefix.clone())?; + fetch_log(crypt_config).await?; + } log_sender .log(Level::INFO, format!("{prefix}: no data changes")) .await?; @@ -720,7 +775,7 @@ async fn pull_snapshot<'a>( .with_context(|| prefix.clone())? { // requires no decryption since either none or both, source and target are encrypted - return unchanged(None).await; + return unchanged(snap_lock, None).await; } Some(existing_manifest) @@ -760,10 +815,14 @@ async fn pull_snapshot<'a>( } (crypt_config, true) => { // nothing changed - return unchanged(crypt_config).await; + return unchanged(snap_lock, crypt_config).await; } }; + snap_lock + .upgrade_to_exclusive() + .with_context(|| prefix.clone())?; + let mut archives_pulled = false; let mut sync_stats = SyncStats::default(); for item in manifest.files() { @@ -1089,14 +1148,36 @@ async fn pull_snapshot_from<'a>( snapshot: &'a pbs_datastore::BackupDir, encountered_chunks: Arc>, corrupt: bool, + source_has_client_log: bool, log_sender: Arc, ) -> Result { let prefix = snapshot.backup_time_string().to_string(); - let (_path, is_new, _snap_lock) = snapshot - .datastore() - .create_locked_backup_dir(snapshot.backup_ns(), snapshot.as_ref()) - .context(prefix.clone())?; + // An already synced snapshot is usually unchanged, which can be checked under a shared lock. + // An exclusive lock would fail while, for example, a verify job reads the snapshot. + let mut shared_lock = None; + if !corrupt && snapshot.full_path().exists() { + match snapshot.lock_shared() { + Ok(lock) if snapshot.full_path().exists() => { + shared_lock = Some(lock); + } + Ok(lock) => drop(lock), + // Under legacy directory locking, a concurrent removal before lock_shared() fails + // with ENOENT; fall through to create_locked_backup_dir() in that case. + Err(_) if !snapshot.full_path().exists() => {} + Err(err) => return Err(err).context(prefix.clone()), + } + } + + let (is_new, mut snap_lock) = if let Some(lock) = shared_lock { + (false, SnapshotLock::shared(lock)) + } else { + let (_path, is_new, lock) = snapshot + .datastore() + .create_locked_backup_dir(snapshot.backup_ns(), snapshot.as_ref()) + .context(prefix.clone())?; + (is_new, SnapshotLock::exclusive(lock)) + }; if is_new { log_sender @@ -1119,8 +1200,10 @@ async fn pull_snapshot_from<'a>( params, reader, snapshot, + &mut snap_lock, encountered_chunks, corrupt, + source_has_client_log, Arc::clone(&log_sender), ) .await; @@ -1196,8 +1279,9 @@ async fn pull_group( .unwrap_or(i64::MIN); // Filter remote BackupDirs to include in pull - // Also stores if the snapshot is corrupt (verification job failed) - let list: Vec<(BackupDir, bool)> = raw_list + // Also stores if the snapshot is corrupt (verification job failed) and if the source has a + // client log + let list: Vec<(BackupDir, bool, bool)> = raw_list .into_iter() .filter_map(|item| { if exclude_not_verified_or_encrypted(&item, params.verified_only, params.encrypted_only) @@ -1205,6 +1289,10 @@ async fn pull_group( return None; } + let has_client_log = item + .files + .iter() + .any(|file| file.filename == CLIENT_LOG_BLOB_NAME.as_ref()); let dir = item.backup; source_snapshots.insert(dir.time); // If resync_corrupt is set, check if the corresponding local snapshot failed to @@ -1219,7 +1307,7 @@ async fn pull_group( match local_dir.verify_state() { Ok(Some(state)) => { if state == VerifyState::Failed { - return Some((dir, true)); + return Some((dir, true, has_client_log)); } } Ok(None) => { @@ -1229,13 +1317,13 @@ async fn pull_group( Err(_) => { // There was an error loading the manifest, probably better if we // resync. - return Some((dir, true)); + return Some((dir, true, has_client_log)); } } } } } - Some((dir, false)) + Some((dir, false, has_client_log)) }) .collect(); @@ -1245,12 +1333,12 @@ async fn pull_group( .map(|count| total_amount.saturating_sub(count)) .unwrap_or_default(); - let list: Vec<(BackupDir, bool)> = list + let list: Vec<(BackupDir, bool, bool)> = list .into_iter() .enumerate() - .filter_map(|(pos, (dir, needs_resync))| { + .filter_map(|(pos, (dir, needs_resync, has_client_log))| { if params.resync_corrupt && needs_resync { - return Some((dir, needs_resync)); + return Some((dir, needs_resync, has_client_log)); } // Note: the snapshot represented by `last_sync_time` might be missing its backup log // or post-backup verification state if those were not yet available during the last @@ -1263,7 +1351,7 @@ async fn pull_group( transfer_last_skip_info.update(dir.time); return None; } - Some((dir, needs_resync)) + Some((dir, needs_resync, has_client_log)) }) .collect(); @@ -1358,7 +1446,7 @@ async fn pull_group( let mut sync_stats = SyncStats::default(); - for (pos, (from_snapshot, corrupt)) in list.into_iter().enumerate() { + for (pos, (from_snapshot, corrupt, source_has_client_log)) in list.into_iter().enumerate() { let to_snapshot = params .target .store @@ -1374,6 +1462,7 @@ async fn pull_group( &to_snapshot, encountered_chunks.clone(), corrupt, + source_has_client_log, Arc::clone(&log_sender), ) .await; -- 2.47.3