From: Christian Ebner <c.ebner@proxmox.com>
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 [thread overview]
Message-ID: <20261201141401.438577-5-c.ebner@proxmox.com> (raw)
In-Reply-To: <20261201141401.438577-1-c.ebner@proxmox.com>
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 <c.ebner@proxmox.com>
---
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<PullParameters>,
reader: Arc<dyn SyncSourceReader + 'a>,
snapshot: &'a pbs_datastore::BackupDir,
+ snap_lock: &mut SnapshotLock,
encountered_chunks: Arc<Mutex<EncounteredChunks>>,
corrupt: bool,
+ source_has_client_log: bool,
log_sender: Arc<LogLineSender>,
) -> Result<Option<SyncStats>, 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<Arc<CryptConfig>>| {
- fetch_log(crypt_config).await?;
+ let unchanged = async |snap_lock: &mut SnapshotLock, crypt_config: Option<Arc<CryptConfig>>| {
+ 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<Mutex<EncounteredChunks>>,
corrupt: bool,
+ source_has_client_log: bool,
log_sender: Arc<LogLineSender>,
) -> Result<SyncStats, Error> {
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
prev parent reply other threads:[~2026-12-01 14:14 UTC|newest]
Thread overview: 5+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-12-01 14:13 [PATCH proxmox-backup 0/4] server: pull: reduce lock contention on unchanged snapshots Christian Ebner
2026-12-01 14:13 ` [PATCH proxmox-backup 1/4] pbs-config: add helper to try upgrade shared lock to exclusive lock Christian Ebner
2026-12-01 14:13 ` [PATCH proxmox-backup 2/4] server: pull: load source manifest into memory instead of a temp file Christian Ebner
2026-12-01 14:14 ` [PATCH proxmox-backup 3/4] server: pull: log snapshot sync start in pull_snapshot_from Christian Ebner
2026-12-01 14:14 ` Christian Ebner [this message]
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=20261201141401.438577-5-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 an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.