* [PATCH proxmox-backup 0/4] server: pull: reduce lock contention on unchanged snapshots
@ 2026-12-01 14:13 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
` (3 more replies)
0 siblings, 4 replies; 5+ messages in thread
From: Christian Ebner @ 2026-12-01 14:13 UTC (permalink / raw)
To: pbs-devel
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. Currently this acquires 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"), pull jobs no longer inherit the source's
verify state, so verify jobs on the target check every newly synced
snapshot while holding a shared lock. Concurrent pull jobs then fail
to acquire the exclusive lock and abort the whole group, delaying
newer snapshots until the next run.
This series checks existing, non-corrupt snapshots under a shared
lock first and upgrades the lock in place to exclusive only when
target changes are actually required:
- Patch 1 adds a BackupLockGuard::try_upgrade() helper for upgrading
a shared lock to exclusive in place.
- Patch 2 implements SyncSourceReader::load_file_bytes() and loads
the source manifest into memory only during pull instead of writing
the temporary index.json.tmp into the target snapshot directory.
- Patch 3 refactors the initial sync/re-sync logging
- Patch 4 finally adapts snapshot checks to start under a shared lock
and only upgrade to an exclusive lock when modifications to the
snapshot are needed.
Based on a report in the community forum:
https://forum.proxmox.com/threads/187896/
Christian Ebner (4):
pbs-config: add helper to try upgrade shared lock to exclusive lock
server: pull: load source manifest into memory instead of a temp file
server: pull: log snapshot sync start in pull_snapshot_from
server: pull: check unchanged snapshots under a shared lock
pbs-config/Cargo.toml | 3 +
pbs-config/src/lib.rs | 80 +++++++++++++++++
src/server/pull.rs | 201 +++++++++++++++++++++++++++++-------------
src/server/sync.rs | 89 +++++++++++++------
4 files changed, 286 insertions(+), 87 deletions(-)
--
2.47.3
^ permalink raw reply [flat|nested] 5+ messages in thread
* [PATCH proxmox-backup 1/4] pbs-config: add helper to try upgrade shared lock to exclusive lock
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 ` 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
` (2 subsequent siblings)
3 siblings, 0 replies; 5+ messages in thread
From: Christian Ebner @ 2026-12-01 14:13 UTC (permalink / raw)
To: pbs-devel
Allow callers holding a shared BackupLockGuard to upgrade it in place
to an exclusive lock with a specified timeou, supporting both
file-based and legacy directory locks. On failure (for example, if
another holder still holds a shared lock), the guard is dropped and
any held lock is released.
Add unit tests covering contended and uncontended upgrades for both
file-based and legacy directory locks.
Signed-off-by: Christian Ebner <c.ebner@proxmox.com>
---
pbs-config/Cargo.toml | 3 ++
pbs-config/src/lib.rs | 80 +++++++++++++++++++++++++++++++++++++++++++
2 files changed, 83 insertions(+)
diff --git a/pbs-config/Cargo.toml b/pbs-config/Cargo.toml
index 81d9c1650..808079416 100644
--- a/pbs-config/Cargo.toml
+++ b/pbs-config/Cargo.toml
@@ -36,3 +36,6 @@ proxmox-uuid.workspace = true
pbs-api-types.workspace = true
pbs-buildcfg.workspace = true
pbs-key-config.workspace = true
+
+[dev-dependencies]
+tempfile.workspace = true
diff --git a/pbs-config/src/lib.rs b/pbs-config/src/lib.rs
index b50062866..2bab9f018 100644
--- a/pbs-config/src/lib.rs
+++ b/pbs-config/src/lib.rs
@@ -1,4 +1,5 @@
use std::os::unix::prelude::AsRawFd;
+use std::time::Duration;
use anyhow::{Error, bail, format_err};
use hex::FromHex;
@@ -59,6 +60,24 @@ pub struct BackupLockGuard {
_legacy_dir: Option<DirLockGuard>,
}
+impl BackupLockGuard {
+ /// Upgrade of a shared lock to an exclusive lock on the same underlying lock descriptor.
+ ///
+ /// Blocking if timeout is `None`, otherwise blocks for duration if lock cannot be upgraded.
+ /// Non-blocking if timeout is set to 0. Not guaranteed to be atomic. On failure (for example,
+ /// if another holder still holds a shared lock), the guard is dropped, releasing any held lock.
+ pub fn try_upgrade(mut self, timeout: Option<Duration>) -> Result<Self, Error> {
+ if let Some(ref mut file) = self.file {
+ proxmox_sys::fs::lock_file(file, true, timeout)
+ .map_err(|err| format_err!("unable to upgrade lock to exclusive - {err}"))?;
+ } else if let Some(ref mut dir) = self._legacy_dir {
+ proxmox_sys::fs::lock_file(dir, true, timeout)
+ .map_err(|err| format_err!("unable to upgrade lock to exclusive - {err}"))?;
+ }
+ Ok(self)
+ }
+}
+
impl AsRawFd for BackupLockGuard {
fn as_raw_fd(&self) -> i32 {
self.file.as_ref().map_or(-1, |f| f.as_raw_fd())
@@ -124,3 +143,64 @@ pub fn detect_modified_configuration_file<T: AsRef<str>>(
}
Ok(())
}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ use proxmox_sys::fs::{CreateOptions, lock_dir_noblock_shared, open_file_locked};
+ use tempfile::TempDir;
+
+ #[test]
+ fn test_backup_lock_guard_try_upgrade_file() {
+ let temp_dir = TempDir::new().unwrap();
+ let lock_path = temp_dir.path().join("test.lck");
+ let timeout = Some(Duration::ZERO);
+
+ let lock_shared = || -> Result<BackupLockGuard, Error> {
+ let file = open_file_locked(&lock_path, Duration::ZERO, false, CreateOptions::new())?;
+ Ok(BackupLockGuard {
+ file: Some(file),
+ _legacy_dir: None,
+ })
+ };
+
+ let guard1 = lock_shared().unwrap();
+ let guard2 = lock_shared().unwrap();
+
+ // Contended upgrade must fail and drop guard1.
+ assert!(guard1.try_upgrade(timeout).is_err());
+
+ // With guard1 dropped, guard2 is the sole holder and can upgrade.
+ let exclusive = guard2.try_upgrade(timeout).unwrap();
+
+ // Exclusive lock must block new shared locks.
+ assert!(lock_shared().is_err());
+
+ drop(exclusive);
+
+ // Once released, shared locks succeed again.
+ let _guard3 = lock_shared().unwrap();
+ }
+
+ #[test]
+ fn test_backup_lock_guard_try_upgrade_legacy_dir() {
+ let temp_dir = TempDir::new().unwrap();
+ let timeout = Some(Duration::ZERO);
+
+ let lock_shared = || -> Result<BackupLockGuard, Error> {
+ lock_dir_noblock_shared(&temp_dir.path(), "test", "busy").map(BackupLockGuard::from)
+ };
+
+ let guard1 = lock_shared().unwrap();
+ let guard2 = lock_shared().unwrap();
+
+ assert!(guard1.try_upgrade(timeout).is_err());
+
+ let exclusive = guard2.try_upgrade(timeout).unwrap();
+ assert!(lock_shared().is_err());
+
+ drop(exclusive);
+ let _guard3 = lock_shared().unwrap();
+ }
+}
--
2.47.3
^ permalink raw reply related [flat|nested] 5+ messages in thread
* [PATCH proxmox-backup 2/4] server: pull: load source manifest into memory instead of a temp file
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 ` 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 ` [PATCH proxmox-backup 4/4] server: pull: check unchanged snapshots under a shared lock Christian Ebner
3 siblings, 0 replies; 5+ messages in thread
From: Christian Ebner @ 2026-12-01 14:13 UTC (permalink / raw)
To: pbs-devel
Add a SyncSourceReader::load_file_bytes() helper which shares the
missing data blob handling in RemoteSourceReader::download_optional()
and reusing it in LocalSourceReader::load_file_into() and loads the
source manifest into memory in pull_snapshot() instead of writing it
to index.json.tmp in the target snapshot directory.
When writing an unmodified manifest, use replace_file() for atomic
replacement instead of renaming the temporary file. Since the
manifest is now in-memory and no temporary file left for cleanup,
refactor the cleanup closure into an unchanged helper.
These changes ensure that it is possible to inspect the source
snapshot state without mutating the target snapshot directory. This
is required so checking for unchanged snapshots can be performed
under a shared lock instead of an exclusive lock, which will be
introduced in subsequent changes.
Signed-off-by: Christian Ebner <c.ebner@proxmox.com>
---
src/server/pull.rs | 45 +++++++++++------------
src/server/sync.rs | 89 +++++++++++++++++++++++++++++++---------------
2 files changed, 81 insertions(+), 53 deletions(-)
diff --git a/src/server/pull.rs b/src/server/pull.rs
index 763fdb5d3..e5bc853da 100644
--- a/src/server/pull.rs
+++ b/src/server/pull.rs
@@ -39,6 +39,7 @@ use pbs_tools::crypt_config::CryptConfig;
use pbs_tools::sha::sha256;
use proxmox_human_byte::HumanByte;
use proxmox_parallel_handler::ParallelHandler;
+use proxmox_sys::fs::{CreateOptions, replace_file};
use tracing::{Level, info};
pub(crate) struct PullTarget {
@@ -615,7 +616,7 @@ async fn pull_single_archive<'a>(
/// Actual implementation of pulling a snapshot.
///
/// Pulling a snapshot consists of the following steps:
-/// - (Re)download the manifest
+/// - (Re)download the manifest into memory
/// -- if it matches and is not corrupt, only download log and treat snapshot as already synced
/// - Iterate over referenced files
/// -- if file already exists, verify contents
@@ -648,18 +649,14 @@ async fn pull_snapshot<'a>(
.await?;
}
- let mut sync_stats = SyncStats::default();
let manifest_name = snapshot.full_archive_path(&MANIFEST_BLOB_NAME);
let client_log_name = snapshot.full_archive_path(&CLIENT_LOG_BLOB_NAME);
- let mut tmp_manifest_name = manifest_name.clone();
- tmp_manifest_name.set_extension("tmp");
- let Some(mut tmp_manifest_file) = reader
- .load_file_into(&MANIFEST_BLOB_NAME, &tmp_manifest_name)
+ let Some(mut manifest_data) = reader
+ .load_file_bytes(&MANIFEST_BLOB_NAME)
.await
.with_context(|| prefix.clone())?
else {
- let _ = tokio::fs::remove_file(&tmp_manifest_name).await;
log_sender
.log(
Level::INFO,
@@ -669,8 +666,8 @@ async fn pull_snapshot<'a>(
return Ok(None);
};
- let tmp_manifest_blob =
- DataBlob::load_from_reader(&mut tmp_manifest_file).with_context(|| prefix.clone())?;
+ let manifest_blob = DataBlob::load_from_reader(&mut manifest_data.as_slice())
+ .with_context(|| prefix.clone())?;
let backend = ¶ms.target.backend;
@@ -706,17 +703,15 @@ async fn pull_snapshot<'a>(
Ok::<(), Error>(())
};
- let cleanup = async || {
+ let unchanged = async |crypt_config: Option<Arc<CryptConfig>>| {
+ fetch_log(crypt_config).await?;
log_sender
.log(Level::INFO, format!("{prefix}: no data changes"))
.await?;
- let _ = tokio::fs::remove_file(&tmp_manifest_name).await;
- Ok::<(), Error>(())
+ Ok::<_, Error>(Some(SyncStats::default()))
};
- let mut manifest_data = tmp_manifest_blob.raw_data().to_vec();
- let mut manifest =
- BackupManifest::try_from(tmp_manifest_blob).with_context(|| prefix.clone())?;
+ let mut manifest = BackupManifest::try_from(manifest_blob).with_context(|| prefix.clone())?;
let existing_target_manifest = if manifest_name.exists() && !corrupt {
let manifest_blob = proxmox_lang::try_block!({
@@ -742,9 +737,7 @@ async fn pull_snapshot<'a>(
.with_context(|| prefix.clone())?
{
// requires no decryption since either none or both, source and target are encrypted
- fetch_log(None).await?;
- cleanup().await?;
- return Ok(Some(sync_stats)); // nothing changed
+ return unchanged(None).await;
}
Some(existing_manifest)
@@ -758,7 +751,6 @@ async fn pull_snapshot<'a>(
params.verified_only,
params.encrypted_only,
) {
- let _ = tokio::fs::remove_file(&tmp_manifest_name).await;
log_sender
.log(
Level::INFO,
@@ -785,13 +777,12 @@ async fn pull_snapshot<'a>(
}
(crypt_config, true) => {
// nothing changed
- fetch_log(crypt_config).await?;
- cleanup().await?;
- return Ok(Some(sync_stats));
+ return unchanged(crypt_config).await;
}
};
let mut archives_pulled = false;
+ let mut sync_stats = SyncStats::default();
for item in manifest.files() {
let path = snapshot.full_archive_path(&item.filename);
if !corrupt && path.exists() {
@@ -920,9 +911,13 @@ async fn pull_snapshot<'a>(
if let Some(manifest) = manifest_to_write {
manifest_data =
tokio::task::spawn_blocking(move || manifest.write_to_path(&manifest_name)).await??;
- let _ = tokio::fs::remove_file(&tmp_manifest_name).await;
- } else if let Err(err) = tokio::fs::rename(&tmp_manifest_name, &manifest_name).await {
- bail!("{prefix}: Atomic rename file {manifest_name:?} failed - {err}");
+ } else {
+ manifest_data = tokio::task::spawn_blocking(move || {
+ replace_file(&manifest_name, &manifest_data, CreateOptions::new(), true)
+ .with_context(|| format!("failed to write manifest {manifest_name:?}"))?;
+ Ok::<_, Error>(manifest_data)
+ })
+ .await??;
}
if let DatastoreBackend::S3(s3_client) = backend {
diff --git a/src/server/sync.rs b/src/server/sync.rs
index 67d02a6a1..04df10857 100644
--- a/src/server/sync.rs
+++ b/src/server/sync.rs
@@ -104,6 +104,12 @@ pub(crate) trait SyncSourceReader: Send + Sync {
crypt_mode: CryptMode,
) -> Result<Arc<dyn AsyncReadChunk>, Error>;
+ /// Asynchronously loads a file from the source into memory.
+ async fn load_file_bytes(
+ &self,
+ archive_name: &BackupArchiveName,
+ ) -> Result<Option<Vec<u8>>, Error>;
+
/// Asynchronously loads a file from the source into a local file.
/// `filename` is the name of the file to load from the source.
/// `into` is the path of the local file to load the source file into.
@@ -135,6 +141,29 @@ pub(crate) struct LocalSourceReader {
pub(crate) dir: pbs_datastore::BackupDir,
}
+impl RemoteSourceReader {
+ async fn download_optional<W: Write + Send>(
+ &self,
+ archive_name: &BackupArchiveName,
+ output: W,
+ ) -> Result<bool, Error> {
+ if let Err(err) = self
+ .backup_reader
+ .download(archive_name.as_ref(), output)
+ .await
+ {
+ match err.downcast_ref::<HttpError>() {
+ Some(HttpError { code, message }) => match *code {
+ StatusCode::NOT_FOUND => return Ok(false),
+ _ => bail!("Snapshot {}: HTTP error {code} - {message}", &self.dir),
+ },
+ None => return Err(err),
+ }
+ }
+ Ok(true)
+ }
+}
+
#[async_trait::async_trait]
impl SyncSourceReader for RemoteSourceReader {
fn chunk_reader(
@@ -151,6 +180,17 @@ impl SyncSourceReader for RemoteSourceReader {
Ok(Arc::new(chunk_reader))
}
+ async fn load_file_bytes(
+ &self,
+ archive_name: &BackupArchiveName,
+ ) -> Result<Option<Vec<u8>>, Error> {
+ let mut data = Vec::new();
+ if !self.download_optional(archive_name, &mut data).await? {
+ return Ok(None);
+ }
+ Ok(Some(data))
+ }
+
async fn load_file_into(
&self,
archive_name: &BackupArchiveName,
@@ -162,25 +202,9 @@ impl SyncSourceReader for RemoteSourceReader {
.truncate(true)
.read(true)
.open(into)?;
- let download_result = self
- .backup_reader
- .download(archive_name.as_ref(), &mut tmp_file)
- .await;
- if let Err(err) = download_result {
- match err.downcast_ref::<HttpError>() {
- Some(HttpError { code, message }) => match *code {
- StatusCode::NOT_FOUND => {
- return Ok(None);
- }
- _ => {
- bail!("Snapshot {}: HTTP error {code} - {message}", &self.dir);
- }
- },
- None => {
- return Err(err);
- }
- };
- };
+ if !self.download_optional(archive_name, &mut tmp_file).await? {
+ return Ok(None);
+ }
tmp_file.rewind()?;
Ok(Some(tmp_file))
}
@@ -253,26 +277,35 @@ impl SyncSourceReader for LocalSourceReader {
Ok(Arc::new(chunk_reader))
}
+ async fn load_file_bytes(
+ &self,
+ archive_name: &BackupArchiveName,
+ ) -> Result<Option<Vec<u8>>, Error> {
+ let from_path = self.dir.full_archive_path(archive_name);
+ match tokio::fs::read(&from_path).await {
+ Ok(data) => Ok(Some(data)),
+ // mirror the RemoteSourceReader's HTTP 404 path: a file vanishing between
+ // snapshot listing and load is not fatal for the group, the caller logs
+ // and skips the snapshot
+ Err(err) if err.kind() == std::io::ErrorKind::NotFound => Ok(None),
+ Err(err) => Err(err.into()),
+ }
+ }
+
async fn load_file_into(
&self,
archive_name: &BackupArchiveName,
into: &Path,
) -> Result<Option<File>, Error> {
+ let Some(data) = self.load_file_bytes(archive_name).await? else {
+ return Ok(None);
+ };
let mut tmp_file = std::fs::OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.read(true)
.open(into)?;
- let from_path = self.dir.full_archive_path(archive_name);
- let data = match std::fs::read(&from_path) {
- Ok(data) => data,
- // mirror the RemoteSourceReader's HTTP 404 path: a file vanishing between
- // snapshot listing and load is not fatal for the group, the caller logs
- // and skips the snapshot
- Err(err) if err.kind() == std::io::ErrorKind::NotFound => return Ok(None),
- Err(err) => return Err(err.into()),
- };
tmp_file.write_all(&data)?;
tmp_file.rewind()?;
Ok(Some(tmp_file))
--
2.47.3
^ permalink raw reply related [flat|nested] 5+ messages in thread
* [PATCH proxmox-backup 3/4] server: pull: log snapshot sync start in pull_snapshot_from
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 ` Christian Ebner
2026-12-01 14:14 ` [PATCH proxmox-backup 4/4] server: pull: check unchanged snapshots under a shared lock Christian Ebner
3 siblings, 0 replies; 5+ messages in thread
From: Christian Ebner @ 2026-12-01 14:14 UTC (permalink / raw)
To: pbs-devel
Move the initial start-sync and re-sync log messages from
pull_snapshot() up to pull_snapshot_from(), where is_new is determined,
and drop the is_new parameter from pull_snapshot().
No functional changes.
Signed-off-by: Christian Ebner <c.ebner@proxmox.com>
---
src/server/pull.rs | 35 +++++++++++++++++------------------
1 file changed, 17 insertions(+), 18 deletions(-)
diff --git a/src/server/pull.rs b/src/server/pull.rs
index e5bc853da..55f8773a8 100644
--- a/src/server/pull.rs
+++ b/src/server/pull.rs
@@ -628,26 +628,9 @@ async fn pull_snapshot<'a>(
snapshot: &'a pbs_datastore::BackupDir,
encountered_chunks: Arc<Mutex<EncounteredChunks>>,
corrupt: bool,
- is_new: bool,
log_sender: Arc<LogLineSender>,
) -> Result<Option<SyncStats>, Error> {
let prefix = snapshot.backup_time_string().to_owned();
- if is_new {
- log_sender
- .log(Level::INFO, format!("{prefix}: start sync"))
- .await?;
- } else if corrupt {
- log_sender
- .log(
- Level::INFO,
- format!("re-sync snapshot {prefix} due to corruption"),
- )
- .await?;
- } else {
- log_sender
- .log(Level::INFO, format!("re-sync snapshot {prefix}"))
- .await?;
- }
let manifest_name = snapshot.full_archive_path(&MANIFEST_BLOB_NAME);
let client_log_name = snapshot.full_archive_path(&CLIENT_LOG_BLOB_NAME);
@@ -1115,13 +1098,29 @@ async fn pull_snapshot_from<'a>(
.create_locked_backup_dir(snapshot.backup_ns(), snapshot.as_ref())
.context(prefix.clone())?;
+ if is_new {
+ log_sender
+ .log(Level::INFO, format!("{prefix}: start sync"))
+ .await?;
+ } else if corrupt {
+ log_sender
+ .log(
+ Level::INFO,
+ format!("re-sync snapshot {prefix} due to corruption"),
+ )
+ .await?;
+ } else {
+ log_sender
+ .log(Level::INFO, format!("re-sync snapshot {prefix}"))
+ .await?;
+ }
+
let result = pull_snapshot(
params,
reader,
snapshot,
encountered_chunks,
corrupt,
- is_new,
Arc::clone(&log_sender),
)
.await;
--
2.47.3
^ permalink raw reply related [flat|nested] 5+ messages in thread
* [PATCH proxmox-backup 4/4] server: pull: check unchanged snapshots under a shared lock
2026-12-01 14:13 [PATCH proxmox-backup 0/4] server: pull: reduce lock contention on unchanged snapshots Christian Ebner
` (2 preceding siblings ...)
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
3 siblings, 0 replies; 5+ messages in thread
From: Christian Ebner @ 2026-12-01 14:14 UTC (permalink / raw)
To: pbs-devel
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
^ permalink raw reply related [flat|nested] 5+ messages in thread
end of thread, other threads:[~2026-12-01 14:14 UTC | newest]
Thread overview: 5+ messages (download: mbox.gz follow: Atom feed
-- links below jump to the message on this page --
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 ` [PATCH proxmox-backup 4/4] server: pull: check unchanged snapshots under a shared lock Christian Ebner
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.