From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [IPv6:2a0f:8001:1:32::40]) by lore.proxmox.com (Postfix) with ESMTPS id 85D511FF09F for ; Tue, 01 Dec 2026 15:14:20 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id E5B4021603; Tue, 01 Dec 2026 15:14:16 +0100 (CET) From: Christian Ebner 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 Message-ID: <20261201141401.438577-3-c.ebner@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261201141401.438577-1-c.ebner@proxmox.com> References: <20261201141401.438577-1-c.ebner@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1796134452122 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.338 Adjusted score from AWL reputation of From: address DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment (newer systems) RCVD_IN_DNSWL_MED -2.3 Sender listed at https://www.dnswl.org/, medium trust SPF_HELO_NONE 0.001 SPF: HELO does not publish an SPF Record SPF_PASS -0.001 SPF: sender matches SPF record Message-ID-Hash: 3DVFMS2LC72UZVWNIHFBT53D3NCFNAXE X-Message-ID-Hash: 3DVFMS2LC72UZVWNIHFBT53D3NCFNAXE X-MailFrom: c.ebner@proxmox.com X-Mailman-Rule-Misses: dmarc-mitigation; no-senders; approved; loop; banned-address; emergency; member-moderation; nonmember-moderation; administrivia; implicit-dest; max-recipients; max-size; news-moderation; no-subject; digests; suspicious-header X-Mailman-Version: 3.3.10 Precedence: list List-Id: Proxmox Backup Server development discussion List-Help: List-Owner: List-Post: List-Subscribe: List-Unsubscribe: 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 --- 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>| { + 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, Error>; + /// Asynchronously loads a file from the source into memory. + async fn load_file_bytes( + &self, + archive_name: &BackupArchiveName, + ) -> Result>, 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( + &self, + archive_name: &BackupArchiveName, + output: W, + ) -> Result { + if let Err(err) = self + .backup_reader + .download(archive_name.as_ref(), output) + .await + { + match err.downcast_ref::() { + 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>, 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::() { - 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>, 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, 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