* [PATCH v2 proxmox-backup 1/9] server: pull: refactor snapshot sync start logging
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 ` Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 2/9] server: pull: defer sync stats instantiation until needed Christian Ebner
` (7 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Christian Ebner @ 2026-12-03 15:04 UTC (permalink / raw)
To: pbs-devel
Move the initial start/re-sync log lines from pull_snapshot() up to
pull_snapshot_from() which allows to drop `is_new` as function
parameter and simplify the code by only doing the log line formatting
in the respective branches.
No functional changes.
Signed-off-by: Christian Ebner <c.ebner@proxmox.com>
---
src/server/pull.rs | 27 +++++++++------------------
1 file changed, 9 insertions(+), 18 deletions(-)
diff --git a/src/server/pull.rs b/src/server/pull.rs
index 763fdb5d3..6d282ad21 100644
--- a/src/server/pull.rs
+++ b/src/server/pull.rs
@@ -627,26 +627,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 mut sync_stats = SyncStats::default();
let manifest_name = snapshot.full_archive_path(&MANIFEST_BLOB_NAME);
@@ -1120,13 +1103,21 @@ async fn pull_snapshot_from<'a>(
.create_locked_backup_dir(snapshot.backup_ns(), snapshot.as_ref())
.context(prefix.clone())?;
+ 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,
reader,
snapshot,
encountered_chunks,
corrupt,
- is_new,
Arc::clone(&log_sender),
)
.await;
--
2.47.3
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH v2 proxmox-backup 2/9] server: pull: defer sync stats instantiation until needed
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 ` 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
` (6 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Christian Ebner @ 2026-12-03 15:04 UTC (permalink / raw)
To: pbs-devel
Instead of creating the instance of SyncStats right away during
snapshot pull, defer it until it is actually required. This will
reduce changes required to decouple the manifest loading and change
checks from the rest of the snapshot sync in subsequent changes.
Signed-off-by: Christian Ebner <c.ebner@proxmox.com>
---
src/server/pull.rs | 6 +++---
1 file changed, 3 insertions(+), 3 deletions(-)
diff --git a/src/server/pull.rs b/src/server/pull.rs
index 6d282ad21..c97ed9cc6 100644
--- a/src/server/pull.rs
+++ b/src/server/pull.rs
@@ -631,7 +631,6 @@ async fn pull_snapshot<'a>(
) -> Result<Option<SyncStats>, Error> {
let prefix = snapshot.backup_time_string().to_owned();
- 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);
@@ -727,7 +726,7 @@ async fn pull_snapshot<'a>(
// 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 Ok(Some(SyncStats::default())); // nothing changed
}
Some(existing_manifest)
@@ -770,10 +769,11 @@ async fn pull_snapshot<'a>(
// nothing changed
fetch_log(crypt_config).await?;
cleanup().await?;
- return Ok(Some(sync_stats));
+ return Ok(Some(SyncStats::default()));
}
};
+ let mut sync_stats = SyncStats::default();
let mut archives_pulled = false;
for item in manifest.files() {
let path = snapshot.full_archive_path(&item.filename);
--
2.47.3
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH v2 proxmox-backup 3/9] server: pull: load source manifest into memory instead of a temp file
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 ` 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
` (5 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Christian Ebner @ 2026-12-03 15:04 UTC (permalink / raw)
To: pbs-devel
Add SyncSourceReader::load_file_bytes() and load the source manifest
into memory during pull instead of writing index.json.tmp into the
target snapshot directory and use replace_file() to then atomically
persist the manifest. Since there is no temp file to cleanup, inline
the logging part and drop the cleanup closure.
SyncSourceReader::load_file_into() implementations are refactored to
reuse logic shared with SyncSourceReader::load_file_bytes() to keep
the same error handling behaviour for source reading.
This allows to inspect the source manifest without mutating the
target snapshot directory and simplifies manifest loading in general,
avoiding additional filesystem I/O.
This is in preparation for being able to check for unchanged
snapshots while holding a shared lock instead of an exclusive one.
Signed-off-by: Christian Ebner <c.ebner@proxmox.com>
---
src/server/pull.rs | 42 ++++++++++------------
src/server/sync.rs | 89 +++++++++++++++++++++++++++++++---------------
2 files changed, 80 insertions(+), 51 deletions(-)
diff --git a/src/server/pull.rs b/src/server/pull.rs
index c97ed9cc6..5ab47ac3f 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 {
@@ -634,14 +635,11 @@ 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 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,
@@ -651,8 +649,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;
@@ -688,17 +686,8 @@ async fn pull_snapshot<'a>(
Ok::<(), Error>(())
};
- let cleanup = async || {
- log_sender
- .log(Level::INFO, format!("{prefix}: no data changes"))
- .await?;
- let _ = tokio::fs::remove_file(&tmp_manifest_name).await;
- Ok::<(), Error>(())
- };
- 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!({
@@ -725,7 +714,9 @@ async fn pull_snapshot<'a>(
{
// requires no decryption since either none or both, source and target are encrypted
fetch_log(None).await?;
- cleanup().await?;
+ log_sender
+ .log(Level::INFO, format!("{prefix}: no data changes"))
+ .await?;
return Ok(Some(SyncStats::default())); // nothing changed
}
@@ -740,7 +731,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,
@@ -768,7 +758,9 @@ async fn pull_snapshot<'a>(
(crypt_config, true) => {
// nothing changed
fetch_log(crypt_config).await?;
- cleanup().await?;
+ log_sender
+ .log(Level::INFO, format!("{prefix}: no data changes"))
+ .await?;
return Ok(Some(SyncStats::default()));
}
};
@@ -903,9 +895,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] 10+ messages in thread* [PATCH v2 proxmox-backup 4/9] server: pull: move target manifest loading logic into reusable helper
2026-12-03 15:04 [PATCH v2 proxmox-backup 0/9] pull: avoid lock contention with verify on unchanged snapshots Christian Ebner
` (2 preceding siblings ...)
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 ` Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 5/9] server: pull: decouple decryption key gathering from logging Christian Ebner
` (4 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Christian Ebner @ 2026-12-03 15:04 UTC (permalink / raw)
To: pbs-devel
Extract the local manifest reading and parsing from pull_snapshot()
into a dedicated load_target_manifest() helper.
In preparation for checking snapshots being unchanged since the last
sync under a shared instead of exclusive lock.
No functional changes.
Signed-off-by: Christian Ebner <c.ebner@proxmox.com>
---
src/server/pull.rs | 34 +++++++++++++++++++---------------
1 file changed, 19 insertions(+), 15 deletions(-)
diff --git a/src/server/pull.rs b/src/server/pull.rs
index 5ab47ac3f..308ac752b 100644
--- a/src/server/pull.rs
+++ b/src/server/pull.rs
@@ -3,6 +3,7 @@
use std::collections::hash_map::Entry;
use std::collections::{HashMap, HashSet};
use std::io::Seek;
+use std::path::Path;
use std::sync::atomic::{AtomicU64, AtomicUsize, Ordering};
use std::sync::{Arc, Mutex};
use std::time::{Duration, SystemTime};
@@ -613,6 +614,23 @@ async fn pull_single_archive<'a>(
Ok(sync_stats)
}
+fn load_target_manifest(manifest_name: &Path, prefix: &str) -> Result<BackupManifest, Error> {
+ let manifest_blob = proxmox_lang::try_block!({
+ let mut manifest_file = std::fs::File::open(manifest_name).map_err(|err| {
+ format_err!("{prefix}: unable to open local manifest {manifest_name:?} - {err}")
+ })?;
+
+ let manifest_blob =
+ DataBlob::load_from_reader(&mut manifest_file).with_context(|| prefix.to_owned())?;
+ Ok(manifest_blob)
+ })
+ .map_err(|err: Error| {
+ format_err!("{prefix}: unable to read local manifest {manifest_name:?} - {err}")
+ })?;
+
+ BackupManifest::try_from(manifest_blob).with_context(|| prefix.to_owned())
+}
+
/// Actual implementation of pulling a snapshot.
///
/// Pulling a snapshot consists of the following steps:
@@ -690,21 +708,7 @@ async fn pull_snapshot<'a>(
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!({
- let mut manifest_file = std::fs::File::open(&manifest_name).map_err(|err| {
- format_err!("{prefix}: unable to open local manifest {manifest_name:?} - {err}")
- })?;
-
- let manifest_blob =
- DataBlob::load_from_reader(&mut manifest_file).with_context(|| prefix.clone())?;
- Ok(manifest_blob)
- })
- .map_err(|err: Error| {
- format_err!("{prefix}: unable to read local manifest {manifest_name:?} - {err}")
- })?;
-
- let existing_manifest =
- BackupManifest::try_from(manifest_blob).with_context(|| prefix.clone())?;
+ let existing_manifest = load_target_manifest(&manifest_name, &prefix)?;
// the target never inherits the source's verify state (see below), so a manifest that
// only differs in it means the snapshot did not change since it was last synced
--
2.47.3
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH v2 proxmox-backup 5/9] server: pull: decouple decryption key gathering from logging
2026-12-03 15:04 [PATCH v2 proxmox-backup 0/9] pull: avoid lock contention with verify on unchanged snapshots Christian Ebner
` (3 preceding siblings ...)
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 ` Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 6/9] pbs-datastore: add BackupDir::lock_with_timeout() Christian Ebner
` (3 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Christian Ebner @ 2026-12-03 15:04 UTC (permalink / raw)
To: pbs-devel
optionally_use_decryption_key() decides which decryption key to use
(if any), checking for matching fingerprint and signature and checks
if the snapshot can be resynced or not if already existing on the
target.
In an effort to make the key gathering and chosen pull variant more
transparent/readable and decouple it from the logging, make the
helper a method of PullParameters so decryption key configs need not
be passed as parameter, introduce intrinsically more descriptive enum
variants as return values instead of plain types, and pull the logging
completely out of the helper.
No functional changes apart from not logging decryption key match
in case of no resync since no data changes, which is in preparation
for state checking under shared lock.
Signed-off-by: Christian Ebner <c.ebner@proxmox.com>
---
src/server/pull.rs | 360 ++++++++++++++++++++++++---------------------
1 file changed, 196 insertions(+), 164 deletions(-)
diff --git a/src/server/pull.rs b/src/server/pull.rs
index 308ac752b..52be2edda 100644
--- a/src/server/pull.rs
+++ b/src/server/pull.rs
@@ -168,6 +168,159 @@ impl PullParameters {
crypt_configs,
})
}
+
+ /// Decide whether a configured decryption key should be used to decrypt the snapshot during
+ /// pull based on the source manifest and an optional pre-existing target manifest.
+ fn optionally_use_decryption_key(
+ &self,
+ manifest: &BackupManifest,
+ existing_target_manifest: Option<&BackupManifest>,
+ prefix: &str,
+ ) -> Result<PullVariant, Error> {
+ let Some(key_fp) = manifest.fingerprint().with_context(|| prefix.to_owned())? else {
+ if let Some(existing_manifest) = existing_target_manifest {
+ if existing_manifest.fingerprint()?.is_some() {
+ bail!("refusing to overwrite local encrypted snapshot from unencrypted source");
+ } else {
+ // Use a zero key to produce a deterministic content hash over the canonical,
+ // signature- and unprotected-stripped manifest. Equal output means equal
+ // protected content (files, csums, backup-time, ...).
+ let dummy = CryptConfig::new([0u8; 32])?;
+ if existing_manifest.signature(&dummy)? != manifest.signature(&dummy)? {
+ // neither source nor target encrypted, but manifests differ
+ bail!("refusing to overwrite local snapshot: content differs from source");
+ }
+ }
+ }
+
+ return Ok(PullVariant::Plain);
+ };
+
+ // check if source is encrypted or contents signed
+ let encrypted = manifest
+ .files()
+ .iter()
+ .all(|f| f.chunk_crypt_mode() == CryptMode::Encrypt);
+
+ if let Some(existing_manifest) = existing_target_manifest {
+ if let Some(existing_fingerprint) = existing_manifest.fingerprint()? {
+ if existing_fingerprint == key_fp {
+ let target_encrypted = existing_manifest
+ .files()
+ .iter()
+ .all(|f| f.chunk_crypt_mode() == CryptMode::Encrypt);
+ if encrypted == target_encrypted {
+ // both sides are signed or encrypted with the same key, just resync
+ return Ok(PullVariant::Plain);
+ }
+ } else {
+ // pre-existing local manifest for encrypted snapshot with key mismatch
+ bail!(
+ "Local encrypted or signed snapshot with different key detected, \
+ refuse to sync"
+ );
+ }
+ }
+ };
+
+ // source got key fingerprint, expect contents to be signed or encrypted
+ let Some((key_id, config)) = self
+ .crypt_configs
+ .iter()
+ .find(|(_id, crypt_conf)| crypt_conf.fingerprint() == *key_fp.bytes())
+ else {
+ // all the other cases are handled above
+ if encrypted && existing_target_manifest.is_some() {
+ bail!("No matching key found, refusing sync");
+ }
+
+ return Ok(if !self.crypt_configs.is_empty() {
+ PullVariant::NoMatchingKey
+ } else {
+ PullVariant::Plain
+ });
+ };
+
+ // check if source is encrypted or contents signed
+ if !encrypted {
+ return Ok(PullVariant::NotFullyEncrypted {
+ key_id: key_id.clone(),
+ key_fp,
+ });
+ }
+
+ manifest
+ .check_signature(config, false)
+ .context("failed to check source manifest signature")
+ .with_context(|| prefix.to_owned())?;
+
+ let mut skip_resync = false;
+
+ // avoid overwriting pre-existing target manifest
+ if let Some(existing_manifest) = existing_target_manifest {
+ let source_fp = manifest
+ .get_sync_source_signature()
+ .context("failed to parse sync-source-signature of source manifest")
+ .with_context(|| prefix.to_owned())?;
+ let stored_source_fp = existing_manifest
+ .get_sync_source_signature()
+ .context("failed to parse sync-source-signature of existing target manifest")
+ .with_context(|| prefix.to_owned())?;
+
+ if source_fp.is_none() && stored_source_fp.is_none() {
+ bail!("No sync-source-signature found, refuse to continue!");
+ }
+
+ if let Some(source_fp) = source_fp {
+ // Stored fp is HMAC over the unencrypted source's protected fields; recompute
+ // over the locally decrypted manifest, not the fresh encrypted remote one.
+ let target_fp = existing_manifest
+ .signature(config)
+ .with_context(|| prefix.to_owned())?;
+ skip_resync = skip_resync || target_fp == *source_fp.bytes();
+ }
+
+ if let Some(stored_source_fp) = stored_source_fp {
+ // Stored sync-source-signature is the source's prior signature on decrypt-pull
+ // (the flow this fallback handles); values set by encrypt-push hold a different
+ // HMAC input and fall through to the mismatch bail.
+ let Some(current) = &manifest.signature else {
+ bail!("No signature on source manifest.");
+ };
+ let current: Fingerprint = current.parse().with_context(|| prefix.to_owned())?;
+ skip_resync = skip_resync || current == stored_source_fp;
+ }
+
+ if !skip_resync {
+ bail!("sync-source-signature mismatch, refuse to continue!");
+ }
+ }
+
+ Ok(PullVariant::Decrypt {
+ key_id: key_id.clone(),
+ key_fp,
+ crypt_config: Arc::clone(config),
+ skip_resync,
+ })
+ }
+}
+
+/// Variant of pull sync specifying whether and how to decrypt a snapshot during pull.
+enum PullVariant {
+ /// Pull without decryption
+ Plain,
+ /// Pull as-is, since configured decryption keys did not match the source snapshot's key
+ /// fingerprint.
+ NoMatchingKey,
+ /// Pull as-is, a matching key exists, but the snapshot is not fully encrypted.
+ NotFullyEncrypted { key_id: String, key_fp: Fingerprint },
+ /// Decrypt archives on pull with the matching key or skip resync if target is already synced.
+ Decrypt {
+ key_id: String,
+ key_fp: Fingerprint,
+ crypt_config: Arc<CryptConfig>,
+ skip_resync: bool,
+ },
}
async fn pull_index_chunks<I: IndexFile>(
@@ -744,24 +897,54 @@ async fn pull_snapshot<'a>(
return Ok(None);
}
- let (crypt_config, new_manifest) = match optionally_use_decryption_key(
- Arc::clone(¶ms),
+ let (crypt_config, new_manifest) = match params.optionally_use_decryption_key(
&manifest,
existing_target_manifest.as_ref(),
- prefix.clone(),
- Arc::clone(&log_sender),
- )
- .await?
- {
- (None, false) => (None, None), // regular pull without decryption
- (Some(crypt_config), false) => {
- // decrypt while pull
+ &prefix,
+ )? {
+ PullVariant::Plain => (None, None),
+ PullVariant::NoMatchingKey => {
+ log_sender
+ .log(
+ Level::INFO,
+ format!("{prefix}: No matching key found, sync without decryption"),
+ )
+ .await?;
+ (None, None)
+ }
+ PullVariant::NotFullyEncrypted { key_id, key_fp } => {
+ log_sender.log(
+ Level::WARN,
+ format!(
+ "Snapshot not fully encrypted, sync as is despite matching key '{key_id}' with \
+ fingerprint {key_fp}"
+ ),
+ ).await?;
+ (None, None)
+ }
+ PullVariant::Decrypt {
+ crypt_config,
+ key_id,
+ key_fp,
+ skip_resync: false,
+ } => {
+ log_sender
+ .log(
+ Level::INFO,
+ format!(
+ "Found matching key '{key_id}' with fingerprint {key_fp}, decrypt on pull"
+ ),
+ )
+ .await?;
let new_manifest = Arc::new(Mutex::new(BackupManifest::new(snapshot.into())));
(Some(crypt_config), Some(new_manifest))
}
- (crypt_config, true) => {
- // nothing changed
- fetch_log(crypt_config).await?;
+ PullVariant::Decrypt {
+ crypt_config,
+ skip_resync: true,
+ ..
+ } => {
+ fetch_log(Some(crypt_config)).await?;
log_sender
.log(Level::INFO, format!("{prefix}: no data changes"))
.await?;
@@ -933,157 +1116,6 @@ async fn pull_snapshot<'a>(
Ok(Some(sync_stats))
}
-/// Check if the decryption key should be used to decrypt the snapshot during
-/// pull based on given pull parameter, source and optionally already present
-/// target manifest.
-///
-/// The boolean flag in the returned tuple indicates whether the pull can be
-/// skipped altogether, since the already existing target is unchanged.
-/// If decryption should happen, the matching decryption key is returned.
-async fn optionally_use_decryption_key(
- params: Arc<PullParameters>,
- manifest: &BackupManifest,
- existing_target_manifest: Option<&BackupManifest>,
- prefix: String,
- log_sender: Arc<LogLineSender>,
-) -> Result<(Option<Arc<CryptConfig>>, bool), Error> {
- let Some(key_fp) = manifest.fingerprint().with_context(|| prefix.clone())? else {
- if let Some(existing_manifest) = existing_target_manifest {
- if existing_manifest.fingerprint()?.is_some() {
- bail!("refusing to overwrite local encrypted snapshot from unencrypted source");
- } else {
- // Use a zero key to produce a deterministic content hash over the canonical,
- // signature- and unprotected-stripped manifest. Equal output means equal
- // protected content (files, csums, backup-time, ...).
- let dummy = CryptConfig::new([0u8; 32])?;
- if existing_manifest.signature(&dummy)? != manifest.signature(&dummy)? {
- // neither source nor target encrypted, but manifests differ
- bail!("refusing to overwrite local snapshot: content differs from source");
- }
- }
- }
-
- return Ok((None, false)); // no fingerprint on source, regular pull
- };
-
- // check if source is encrypted or contents signed
- let encrypted = manifest
- .files()
- .iter()
- .all(|f| f.chunk_crypt_mode() == CryptMode::Encrypt);
-
- if let Some(existing_manifest) = existing_target_manifest {
- if let Some(existing_fingerprint) = existing_manifest.fingerprint()? {
- if existing_fingerprint == key_fp {
- let target_encrypted = existing_manifest
- .files()
- .iter()
- .all(|f| f.chunk_crypt_mode() == CryptMode::Encrypt);
- if encrypted == target_encrypted {
- // both sides are signed or encrypted with the same key, just resync
- return Ok((None, false));
- }
- } else {
- // pre-existing local manifest for encrypted snapshot with key mismatch
- bail!(
- "Local encrypted or signed snapshot with different key detected, refuse to sync"
- );
- }
- }
- };
-
- // source got key fingerprint, expect contents to be signed or encrypted
- let Some((key_id, config)) = params
- .crypt_configs
- .iter()
- .find(|(_id, crypt_conf)| crypt_conf.fingerprint() == *key_fp.bytes())
- else {
- // all the other cases are handled above
- if encrypted && existing_target_manifest.is_some() {
- bail!("No matching key found, refusing sync");
- }
-
- // regular sync
- if !params.crypt_configs.is_empty() {
- log_sender
- .log(
- Level::INFO,
- format!("{prefix}: No matching key found, sync without decryption"),
- )
- .await?;
- }
-
- return Ok((None, false));
- };
-
- // check if source is encrypted or contents signed
- if !encrypted {
- log_sender
- .log(
- Level::WARN,
- format!("Snapshot not fully encrypted, sync as is despite matching key '{key_id}' with fingerprint {key_fp}"),
- )
- .await?;
- return Ok((None, false));
- }
-
- manifest
- .check_signature(config, false)
- .context("failed to check source manifest signature")
- .with_context(|| prefix.clone())?;
-
- let mut skip_resync = false;
-
- // avoid overwriting pre-existing target manifest
- if let Some(existing_manifest) = existing_target_manifest {
- let source_fp = manifest
- .get_sync_source_signature()
- .context("failed to parse sync-source-signature of source manifest")
- .with_context(|| prefix.clone())?;
- let stored_source_fp = existing_manifest
- .get_sync_source_signature()
- .context("failed to parse sync-source-signature of existing target manifest")
- .with_context(|| prefix.clone())?;
-
- if source_fp.is_none() && stored_source_fp.is_none() {
- bail!("No sync-source-signature found, refuse to continue!");
- }
-
- if let Some(source_fp) = source_fp {
- // Stored fp is HMAC over the unencrypted source's protected fields; recompute
- // over the locally decrypted manifest, not the fresh encrypted remote one.
- let target_fp = existing_manifest
- .signature(config)
- .with_context(|| prefix.clone())?;
- skip_resync = skip_resync || target_fp == *source_fp.bytes();
- }
-
- if let Some(stored_source_fp) = stored_source_fp {
- // Stored sync-source-signature is the source's prior signature on decrypt-pull
- // (the flow this fallback handles); values set by encrypt-push hold a different
- // HMAC input and fall through to the mismatch bail.
- let Some(current) = &manifest.signature else {
- bail!("No signature on source manifest.");
- };
- let current: Fingerprint = current.parse().with_context(|| prefix.clone())?;
- skip_resync = skip_resync || current == stored_source_fp;
- }
-
- if !skip_resync {
- bail!("sync-source-signature mismatch, refuse to continue!");
- }
- }
-
- log_sender
- .log(
- Level::INFO,
- format!("Found matching key '{key_id}' with fingerprint {key_fp}, decrypt on pull"),
- )
- .await?;
-
- Ok((Some(Arc::clone(config)), skip_resync))
-}
-
/// Pulls a `snapshot`, removing newly created ones on error, but keeping existing ones in any case.
///
/// The `reader` is configured to read from the source backup directory, while the
--
2.47.3
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH v2 proxmox-backup 6/9] pbs-datastore: add BackupDir::lock_with_timeout()
2026-12-03 15:04 [PATCH v2 proxmox-backup 0/9] pull: avoid lock contention with verify on unchanged snapshots Christian Ebner
` (4 preceding siblings ...)
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 ` Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 7/9] pbs-datastore: add create_locked_backup_dir_with_timeout() Christian Ebner
` (2 subsequent siblings)
8 siblings, 0 replies; 10+ messages in thread
From: Christian Ebner @ 2026-12-03 15:04 UTC (permalink / raw)
To: pbs-devel
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 <c.ebner@proxmox.com>
---
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<BackupLockGuard, Error> {
+ 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<BackupLockGuard, Error> {
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<proxmox_sys::fs::DirLockGuard, Error> {
+ 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
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH v2 proxmox-backup 7/9] pbs-datastore: add create_locked_backup_dir_with_timeout()
2026-12-03 15:04 [PATCH v2 proxmox-backup 0/9] pull: avoid lock contention with verify on unchanged snapshots Christian Ebner
` (5 preceding siblings ...)
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 ` Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 8/9] server: pull: check for unchanged snapshots under a shared lock Christian Ebner
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 9/9] server: pull: skip exclusive lock when source has no client log Christian Ebner
8 siblings, 0 replies; 10+ messages in thread
From: Christian Ebner @ 2026-12-03 15:04 UTC (permalink / raw)
To: pbs-devel
Add a timeout-aware variant of create_locked_backup_dir() using
BackupDir::lock_with_timeout().
Verify the snapshot directory still exists once the exclusive lock is
held and bail if it vanished concurrently. This is now also checked
for the case without timeout.
Signed-off-by: Christian Ebner <c.ebner@proxmox.com>
---
pbs-datastore/src/datastore.rs | 37 ++++++++++++++++++++++++++++------
1 file changed, 31 insertions(+), 6 deletions(-)
diff --git a/pbs-datastore/src/datastore.rs b/pbs-datastore/src/datastore.rs
index e6766a3b9..c8e4bc598 100644
--- a/pbs-datastore/src/datastore.rs
+++ b/pbs-datastore/src/datastore.rs
@@ -1873,6 +1873,19 @@ impl DataStore {
self: &Arc<Self>,
ns: &BackupNamespace,
backup_dir: &pbs_api_types::BackupDir,
+ ) -> Result<(PathBuf, bool, BackupLockGuard), Error> {
+ self.create_locked_backup_dir_with_timeout(ns, backup_dir, Duration::ZERO)
+ }
+
+ /// Creates a new backup snapshot inside a BackupGroup, or locks an existing one, waiting up
+ /// to `timeout` for the exclusive snapshot lock.
+ ///
+ /// The BackupGroup directory needs to exist.
+ pub fn create_locked_backup_dir_with_timeout(
+ self: &Arc<Self>,
+ ns: &BackupNamespace,
+ backup_dir: &pbs_api_types::BackupDir,
+ timeout: Duration,
) -> Result<(PathBuf, bool, BackupLockGuard), Error> {
if backup_dir.time
> proxmox_time::epoch_i64().saturating_add(self.inner.max_snapshot_time_skew)
@@ -1885,22 +1898,34 @@ impl DataStore {
let backup_dir = self.backup_dir(ns.clone(), backup_dir.clone())?;
let relative_path = backup_dir.relative_path();
+ let full_path = backup_dir.full_path();
- match std::fs::create_dir(backup_dir.full_path()) {
+ let (is_new, guard) = match std::fs::create_dir(&full_path) {
Ok(_) => {
- let guard = backup_dir.lock().with_context(|| {
+ let guard = backup_dir.lock_with_timeout(timeout).with_context(|| {
format!("while creating new locked snapshot {relative_path:?}")
})?;
- Ok((relative_path, true, guard))
+ (true, guard)
}
Err(ref e) if e.kind() == io::ErrorKind::AlreadyExists => {
let guard = backup_dir
- .lock()
+ .lock_with_timeout(timeout)
.with_context(|| format!("while creating locked snapshot {relative_path:?}"))?;
- Ok((relative_path, false, guard))
+ (false, guard)
}
- Err(e) => Err(e.into()),
+ Err(e) => return Err(e.into()),
+ };
+
+ // Ensure the snapshot directory was not removed between create_dir() and acquiring the
+ // lock (under file-based locking, open_backup_lockfile() can create a fresh lock file
+ // after a concurrent destroy() unlinked the old one).
+ if !full_path.exists() {
+ bail!(
+ "while creating locked snapshot {relative_path:?}: snapshot vanished concurrently"
+ );
}
+
+ Ok((relative_path, is_new, guard))
}
/// Get a streaming iter over single-level backup namespaces of a datatstore
--
2.47.3
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH v2 proxmox-backup 8/9] server: pull: check for unchanged snapshots under a shared lock
2026-12-03 15:04 [PATCH v2 proxmox-backup 0/9] pull: avoid lock contention with verify on unchanged snapshots Christian Ebner
` (6 preceding siblings ...)
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
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 9/9] server: pull: skip exclusive lock when source has no client log Christian Ebner
8 siblings, 0 replies; 10+ messages in thread
From: Christian Ebner @ 2026-12-03 15:04 UTC (permalink / raw)
To: pbs-devel
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
^ permalink raw reply related [flat|nested] 10+ messages in thread* [PATCH v2 proxmox-backup 9/9] server: pull: skip exclusive lock when source has no client log
2026-12-03 15:04 [PATCH v2 proxmox-backup 0/9] pull: avoid lock contention with verify on unchanged snapshots Christian Ebner
` (7 preceding siblings ...)
2026-12-03 15:04 ` [PATCH v2 proxmox-backup 8/9] server: pull: check for unchanged snapshots under a shared lock Christian Ebner
@ 2026-12-03 15:04 ` Christian Ebner
8 siblings, 0 replies; 10+ messages in thread
From: Christian Ebner @ 2026-12-03 15:04 UTC (permalink / raw)
To: pbs-devel
Check from the source snapshot listing whether a client log exists on
the source and pass that into pull_snapshot_from().
Unchanged snapshots without a client log on the source no longer need
to acquire an exclusive lock just to find out there is actually no
client log available on the source.
Signed-off-by: Christian Ebner <c.ebner@proxmox.com>
---
src/server/pull.rs | 31 ++++++++++++++++++++-----------
1 file changed, 20 insertions(+), 11 deletions(-)
diff --git a/src/server/pull.rs b/src/server/pull.rs
index ae780d0db..f36ae305b 100644
--- a/src/server/pull.rs
+++ b/src/server/pull.rs
@@ -800,6 +800,7 @@ async fn check_snapshot_under_shared_lock<'a>(
reader: Arc<dyn SyncSourceReader + 'a>,
snapshot: &'a pbs_datastore::BackupDir,
_shared_lock: BackupLockGuard,
+ source_has_client_log: bool,
log_sender: Arc<LogLineSender>,
) -> Result<Option<Vec<u8>>, Error> {
let prefix = snapshot.backup_time_string().to_owned();
@@ -860,7 +861,7 @@ async fn check_snapshot_under_shared_lock<'a>(
)
};
- if unchanged && client_log_name.exists() {
+ if unchanged && (client_log_name.exists() || !source_has_client_log) {
log_sender
.log(Level::INFO, format!("{prefix}: no data changes"))
.await?;
@@ -1219,6 +1220,7 @@ 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();
@@ -1241,6 +1243,7 @@ async fn pull_snapshot_from<'a>(
Arc::clone(&reader),
snapshot,
shared_lock,
+ source_has_client_log,
Arc::clone(&log_sender),
)
.await?
@@ -1368,8 +1371,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)
@@ -1377,6 +1381,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
@@ -1391,7 +1399,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) => {
@@ -1401,13 +1409,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();
@@ -1417,12 +1425,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
@@ -1435,7 +1443,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();
@@ -1530,7 +1538,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
@@ -1546,6 +1554,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] 10+ messages in thread