From: Christian Ebner <c.ebner@proxmox.com>
To: pbs-devel@lists.proxmox.com
Subject: [PATCH v2 proxmox-backup 3/9] server: pull: load source manifest into memory instead of a temp file
Date: Thu, 3 Dec 2026 16:04:42 +0100 [thread overview]
Message-ID: <20261203150448.412515-4-c.ebner@proxmox.com> (raw)
In-Reply-To: <20261203150448.412515-1-c.ebner@proxmox.com>
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
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 ` Christian Ebner [this message]
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 ` [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
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-4-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