From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from gate001.proxmox.com (gate001.proxmox.com [45.144.208.40]) by lore.proxmox.com (Postfix) with ESMTPS id 0B1761FF0C2 for ; Thu, 03 Dec 2026 16:05:21 +0100 (CET) Received: from gate001.proxmox.com (localhost.localdomain [127.0.0.1]) by gate001.proxmox.com (Proxmox) with ESMTP id F2D7B217E7; Thu, 03 Dec 2026 16:05:11 +0100 (CET) From: Christian Ebner 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 Message-ID: <20261203150448.412515-4-c.ebner@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20261203150448.412515-1-c.ebner@proxmox.com> References: <20261203150448.412515-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: 1796310300973 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.331 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: YVGN5SILN6BBB54B4MTRTAVLKLX3VQ4W X-Message-ID-Hash: YVGN5SILN6BBB54B4MTRTAVLKLX3VQ4W 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 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 --- 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, 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