From: Christian Ebner <c.ebner@proxmox.com>
To: pbs-devel@lists.proxmox.com
Subject: [PATCH v2 proxmox-backup 8/9] server: pull: check for unchanged snapshots under a shared lock
Date: Thu, 3 Dec 2026 16:04:47 +0100 [thread overview]
Message-ID: <20261203150448.412515-9-c.ebner@proxmox.com> (raw)
In-Reply-To: <20261203150448.412515-1-c.ebner@proxmox.com>
Since commit 7241811f7 ("fix #6990: server: drop verify state on
non-decrypt pull job") synced snapshots no longer inherit the source's
verify state, so a verify job on the target checks every newly synced
snapshot while holding a shared lock. A concurrent pull then fails to
acquire the exclusive lock and aborts the whole group, delaying newer
snapshots until the next run.
To reduce lock contention, check existing, non-corrupt snapshots
under a shared lock first.
When target modifications are needed, drop the shared lock and acquire
a validated exclusive lock via create_locked_backup_dir_with_timeout()
before re-evaluating the state. The shared lock is only ever acquired
for pre-existing snapshots and is the fast path for these, as it is
most likely that a snapshot did not change except for its verify
state. If only the client log is missing on the target, and present on
the source the snapshot is exclusively locked as well.
For not pre-existing snapshots, the shared lock is never acquired,
the exclusive lock is considered the fast path. Here no timeout is
used since any concurrent operation (e.g. backup) is in conflict
anyway.
Link: https://forum.proxmox.com/threads/187896/
Signed-off-by: Christian Ebner <c.ebner@proxmox.com>
---
src/server/pull.rs | 191 +++++++++++++++++++++++++++++++++++++++------
1 file changed, 167 insertions(+), 24 deletions(-)
diff --git a/src/server/pull.rs b/src/server/pull.rs
index 52be2edda..ae780d0db 100644
--- a/src/server/pull.rs
+++ b/src/server/pull.rs
@@ -24,7 +24,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};
@@ -43,6 +43,10 @@ use proxmox_parallel_handler::ParallelHandler;
use proxmox_sys::fs::{CreateOptions, replace_file};
use tracing::{Level, info};
+/// Maximum time to wait when transitioning to an exclusive snapshot lock after checking for
+/// snapshot modifications under a shared lock.
+const SNAPSHOT_EXCLUSIVE_LOCK_TIMEOUT: Duration = Duration::from_secs(15);
+
pub(crate) struct PullTarget {
store: Arc<DataStore>,
ns: BackupNamespace,
@@ -784,7 +788,89 @@ fn load_target_manifest(manifest_name: &Path, prefix: &str) -> Result<BackupMani
BackupManifest::try_from(manifest_blob).with_context(|| prefix.to_owned())
}
-/// Actual implementation of pulling a snapshot.
+/// Checks whether an existing, non-corrupt target snapshot is already up to date under a shared
+/// snapshot lock.
+///
+/// Never mutates the target snapshot directory. Takes ownership of the shared lock so it is
+/// released before any subsequent exclusive lock acquisition.
+/// Returns `None` if no data changes are required, otherwise the raw manifest bytes as read from
+/// the pull source.
+async fn check_snapshot_under_shared_lock<'a>(
+ params: Arc<PullParameters>,
+ reader: Arc<dyn SyncSourceReader + 'a>,
+ snapshot: &'a pbs_datastore::BackupDir,
+ _shared_lock: BackupLockGuard,
+ log_sender: Arc<LogLineSender>,
+) -> Result<Option<Vec<u8>>, Error> {
+ let prefix = snapshot.backup_time_string().to_owned();
+ let manifest_name = snapshot.full_archive_path(&MANIFEST_BLOB_NAME);
+ let client_log_name = snapshot.full_archive_path(&CLIENT_LOG_BLOB_NAME);
+
+ let Some(manifest_data) = reader
+ .load_file_bytes(&MANIFEST_BLOB_NAME)
+ .await
+ .with_context(|| prefix.clone())?
+ else {
+ log_sender
+ .log(
+ Level::INFO,
+ format!("{prefix}: skipped because vanished since start of sync"),
+ )
+ .await?;
+ return Ok(None);
+ };
+
+ if !manifest_name.exists() {
+ return Ok(Some(manifest_data));
+ }
+
+ let manifest_blob = DataBlob::load_from_reader(&mut manifest_data.as_slice())
+ .with_context(|| prefix.clone())?;
+ let manifest = BackupManifest::try_from(manifest_blob).with_context(|| prefix.clone())?;
+
+ let existing_manifest = load_target_manifest(&manifest_name, &prefix)?;
+
+ let unchanged = if existing_manifest
+ .eq_ignoring_verify_state(&manifest)
+ .with_context(|| prefix.clone())?
+ {
+ true
+ } else if ignore_not_verified_or_encrypted(
+ &manifest,
+ snapshot.dir(),
+ params.verified_only,
+ params.encrypted_only,
+ ) {
+ log_sender
+ .log(
+ Level::INFO,
+ format!("{prefix}: skipped, did not match verified-only/encrypted-only filter"),
+ )
+ .await?;
+ return Ok(None);
+ } else {
+ let pull_variant =
+ params.optionally_use_decryption_key(&manifest, Some(&existing_manifest), &prefix)?;
+ matches!(
+ pull_variant,
+ PullVariant::Decrypt {
+ skip_resync: true,
+ ..
+ }
+ )
+ };
+
+ if unchanged && client_log_name.exists() {
+ log_sender
+ .log(Level::INFO, format!("{prefix}: no data changes"))
+ .await?;
+ return Ok(None);
+ }
+
+ Ok(Some(manifest_data))
+}
+
+/// Pull snapshot under an exclusive snapshot lock.
///
/// Pulling a snapshot consists of the following steps:
/// - (Re)download the manifest
@@ -799,6 +885,7 @@ async fn pull_snapshot<'a>(
snapshot: &'a pbs_datastore::BackupDir,
encountered_chunks: Arc<Mutex<EncounteredChunks>>,
corrupt: bool,
+ prefetched_manifest: Option<Vec<u8>>,
log_sender: Arc<LogLineSender>,
) -> Result<Option<SyncStats>, Error> {
let prefix = snapshot.backup_time_string().to_owned();
@@ -806,18 +893,24 @@ async fn pull_snapshot<'a>(
let manifest_name = snapshot.full_archive_path(&MANIFEST_BLOB_NAME);
let client_log_name = snapshot.full_archive_path(&CLIENT_LOG_BLOB_NAME);
- let Some(mut manifest_data) = reader
- .load_file_bytes(&MANIFEST_BLOB_NAME)
- .await
- .with_context(|| prefix.clone())?
- else {
- log_sender
- .log(
- Level::INFO,
- format!("{prefix}: skipped because vanished since start of sync"),
- )
- .await?;
- return Ok(None);
+ let mut manifest_data = match prefetched_manifest {
+ Some(data) => data,
+ None => {
+ let Some(data) = reader
+ .load_file_bytes(&MANIFEST_BLOB_NAME)
+ .await
+ .with_context(|| prefix.clone())?
+ else {
+ log_sender
+ .log(
+ Level::INFO,
+ format!("{prefix}: skipped because vanished since start of sync"),
+ )
+ .await?;
+ return Ok(None);
+ };
+ data
+ }
};
let manifest_blob = DataBlob::load_from_reader(&mut manifest_data.as_slice())
@@ -1130,19 +1223,68 @@ async fn pull_snapshot_from<'a>(
) -> 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, non-corrupt snapshot is usually unchanged and can be checked under a
+ // shared lock so concurrent readers (such as verify jobs) do not conflict with the sync.
+ // If target changes are required, release the shared lock and acquire an exclusive lock.
+ let mut prefetched_manifest = None;
+ let mut start_logged_under_shared_lock = false;
+ if !corrupt && snapshot.full_path().exists() {
+ match snapshot.lock_shared() {
+ Ok(shared_lock) if snapshot.full_path().exists() => {
+ log_sender
+ .log(Level::INFO, format!("re-sync snapshot {prefix}"))
+ .await?;
+ start_logged_under_shared_lock = true;
+
+ match check_snapshot_under_shared_lock(
+ Arc::clone(¶ms),
+ Arc::clone(&reader),
+ snapshot,
+ shared_lock,
+ Arc::clone(&log_sender),
+ )
+ .await?
+ {
+ None => return Ok(SyncStats::default()),
+ Some(manifest_data) => {
+ prefetched_manifest = Some(manifest_data);
+ }
+ }
+ }
+ Ok(shared_lock) => drop(shared_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 log_message = if is_new {
- format!("{prefix}: start sync")
- } else if corrupt {
- format!("re-sync snapshot {prefix} due to corruption")
+ let (_path, is_new, _snapshot_exclusive_lock) = if prefetched_manifest.is_some() {
+ let store = Arc::clone(snapshot.datastore());
+ let ns = snapshot.backup_ns().clone();
+ let dir = snapshot.dir().clone();
+ tokio::task::spawn_blocking(move || {
+ store.create_locked_backup_dir_with_timeout(&ns, &dir, SNAPSHOT_EXCLUSIVE_LOCK_TIMEOUT)
+ })
+ .await?
+ .context(prefix.clone())?
} else {
- format!("re-sync snapshot {prefix}")
+ snapshot
+ .datastore()
+ .create_locked_backup_dir(snapshot.backup_ns(), snapshot.as_ref())
+ .context(prefix.clone())?
};
- log_sender.log(Level::INFO, log_message).await?;
+
+ if !start_logged_under_shared_lock {
+ let log_message = if is_new {
+ format!("{prefix}: start sync")
+ } else if corrupt {
+ format!("re-sync snapshot {prefix} due to corruption")
+ } else {
+ format!("re-sync snapshot {prefix}")
+ };
+ log_sender.log(Level::INFO, log_message).await?;
+ }
let result = pull_snapshot(
params,
@@ -1150,6 +1292,7 @@ async fn pull_snapshot_from<'a>(
snapshot,
encountered_chunks,
corrupt,
+ prefetched_manifest,
Arc::clone(&log_sender),
)
.await;
--
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 ` [PATCH v2 proxmox-backup 6/9] pbs-datastore: add BackupDir::lock_with_timeout() Christian Ebner
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 ` Christian Ebner [this message]
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-9-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