From: Christian Ebner <c.ebner@proxmox.com>
To: pbs-devel@lists.proxmox.com
Subject: [PATCH proxmox-backup 2/4] server: pull: load source manifest into memory instead of a temp file
Date: Tue, 1 Dec 2026 15:13:59 +0100 [thread overview]
Message-ID: <20261201141401.438577-3-c.ebner@proxmox.com> (raw)
In-Reply-To: <20261201141401.438577-1-c.ebner@proxmox.com>
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
next prev parent reply other threads:[~2026-12-01 14:14 UTC|newest]
Thread overview: 5+ messages / expand[flat|nested] mbox.gz Atom feed top
2026-12-01 14:13 [PATCH proxmox-backup 0/4] server: pull: reduce lock contention on unchanged snapshots Christian Ebner
2026-12-01 14:13 ` [PATCH proxmox-backup 1/4] pbs-config: add helper to try upgrade shared lock to exclusive lock Christian Ebner
2026-12-01 14:13 ` Christian Ebner [this message]
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
Reply instructions:
You may reply publicly to this message via plain-text email
using any one of the following methods:
* Save the following mbox file, import it into your mail client,
and reply-to-all from there: mbox
Avoid top-posting and favor interleaved quoting:
https://en.wikipedia.org/wiki/Posting_style#Interleaved_style
* Reply using the --to, --cc, and --in-reply-to
switches of git-send-email(1):
git send-email \
--in-reply-to=20261201141401.438577-3-c.ebner@proxmox.com \
--to=c.ebner@proxmox.com \
--cc=pbs-devel@lists.proxmox.com \
/path/to/YOUR_REPLY
https://kernel.org/pub/software/scm/git/docs/git-send-email.html
* If your mail client supports setting the In-Reply-To header
via mailto: links, try the mailto: link
Be sure your reply has a Subject: header at the top and a blank line
before the message body.
This is an external index of several public inboxes,
see mirroring instructions on how to clone and mirror
all data and code used by this external index.