From mboxrd@z Thu Jan 1 00:00:00 1970 Return-Path: Received: from firstgate.proxmox.com (firstgate.proxmox.com [212.224.123.68]) by lore.proxmox.com (Postfix) with ESMTPS id 0B26F1FF139 for ; Tue, 10 Feb 2026 16:06:27 +0100 (CET) Received: from firstgate.proxmox.com (localhost [127.0.0.1]) by firstgate.proxmox.com (Proxmox) with ESMTP id 09C1162CB; Tue, 10 Feb 2026 16:07:11 +0100 (CET) From: Robert Obkircher To: pbs-devel@lists.proxmox.com Subject: [PATCH v6 proxmox-backup 03/18] datastore: add TempDir that is automatically deleted on drop Date: Tue, 10 Feb 2026 16:06:19 +0100 Message-ID: <20260210150642.469670-4-r.obkircher@proxmox.com> X-Mailer: git-send-email 2.47.3 In-Reply-To: <20260210150642.469670-1-r.obkircher@proxmox.com> References: <20260210150642.469670-1-r.obkircher@proxmox.com> MIME-Version: 1.0 Content-Transfer-Encoding: 8bit X-Bm-Milter-Handled: 55990f41-d878-4baa-be0a-ee34c49e34d2 X-Bm-Transport-Timestamp: 1770735940139 X-SPAM-LEVEL: Spam detection results: 0 AWL 0.061 Adjusted score from AWL reputation of From: address BAYES_00 -1.9 Bayes spam probability is 0 to 1% DMARC_MISSING 0.1 Missing DMARC policy KAM_DMARC_STATUS 0.01 Test Rule for DKIM or SPF Failure with Strict Alignment 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: PVG7MDWM47473CEYUZNZMUGSDWZGK7D3 X-Message-ID-Hash: PVG7MDWM47473CEYUZNZMUGSDWZGK7D3 X-MailFrom: r.obkircher@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: This will be used to test the FixedIndexWriter and chunk store creation. PDM has a similar type called NamedTempDir, so it would make sense to move this to a shared crate in the future. Signed-off-by: Robert Obkircher --- pbs-datastore/src/lib.rs | 3 + pbs-datastore/src/temp_dir.rs | 142 ++++++++++++++++++++++++++++++++++ 2 files changed, 145 insertions(+) create mode 100644 pbs-datastore/src/temp_dir.rs diff --git a/pbs-datastore/src/lib.rs b/pbs-datastore/src/lib.rs index 1f7c54ae..f6c73bcb 100644 --- a/pbs-datastore/src/lib.rs +++ b/pbs-datastore/src/lib.rs @@ -233,3 +233,6 @@ pub use local_chunk_reader::LocalChunkReader; mod local_datastore_lru_cache; pub use local_datastore_lru_cache::LocalDatastoreLruCache; + +#[cfg(test)] +mod temp_dir; diff --git a/pbs-datastore/src/temp_dir.rs b/pbs-datastore/src/temp_dir.rs new file mode 100644 index 00000000..bea97792 --- /dev/null +++ b/pbs-datastore/src/temp_dir.rs @@ -0,0 +1,142 @@ +use core::convert::AsRef; +use std::convert::From; +use std::env; +use std::mem; +use std::path::{Path, PathBuf}; + +use anyhow::{Context, Error}; + +/// A temporary directory that is automatically removed on drop. +/// Deletion is best-effort and errors are silently ignored, unless +/// the explicit `delete` method is used. +#[derive(Debug)] +pub struct TempDir { + directory: PathBuf, + delete_on_drop: bool, +} + +impl TempDir { + /// Create an empty directory in `env::temp_dir()`. + pub fn new() -> Result { + TempDir::new_in(env::temp_dir()) + } + + /// Create an empty child directory in the specified one. + pub fn new_in(parent: impl AsRef) -> Result { + let parent = parent.as_ref(); + let directory = proxmox_sys::fs::make_tmp_dir(parent, None) + .with_context(|| format!("Failed to create temporary directory in {parent:?}"))?; + Ok(Self { + directory, + delete_on_drop: true, + }) + } + + /// The path to this directory. + pub fn path(&self) -> &Path { + &self.directory + } + + /// Disable automatic deletion. + /// May be useful when debugging tests. + pub fn disable_deletion(&mut self) { + self.delete_on_drop = false; + } + + /// Disable atomatic deletion and turn into a normal `PathBuf`. + pub fn to_persistent(mut self) -> PathBuf { + self.disable_deletion(); + mem::take(&mut self.directory) + } + + /// Delete the directory with the possibility of handling the error. + pub fn delete(mut self) -> Result<(), Error> { + self.disable_deletion(); + std::fs::remove_dir_all(&self.directory) + .with_context(|| format!("Failed to delete temporary directory {:?}", self.directory)) + } +} + +impl Drop for TempDir { + fn drop(&mut self) { + if self.delete_on_drop { + let _ = std::fs::remove_dir_all(&self.directory); + } + } +} + +impl AsRef for TempDir { + fn as_ref(&self) -> &Path { + self.path() + } +} + +#[cfg(test)] +mod tests { + use super::*; + use std::fs; + + #[test] + fn test_empty() { + let temp_dir = TempDir::new().unwrap(); + + let copy = PathBuf::from(temp_dir.path()); + assert!(fs::exists(©).unwrap()); + assert!(copy.is_dir()); + + drop(temp_dir); + + assert!(!fs::exists(copy).unwrap()); + } + + #[test] + fn test_delete_with_content() { + let temp_dir = TempDir::new().unwrap(); + + let copy = PathBuf::from(temp_dir.path()); + assert!(fs::exists(©).unwrap()); + assert!(copy.is_dir()); + + fs::write(temp_dir.path().join("test.txt"), "hello").unwrap(); + + let subdir = temp_dir.path().join("foo").join("bar"); + fs::create_dir_all(&subdir).unwrap(); + fs::write(subdir.join("baz.txt"), "world").unwrap(); + + temp_dir.delete().unwrap(); + + assert!(!fs::exists(copy).unwrap()); + } + + #[test] + fn test_disable_deletion() { + let mut temp_dir = TempDir::new().unwrap(); + + let copy = PathBuf::from(temp_dir.path()); + temp_dir.disable_deletion(); + drop(temp_dir); + + assert!( + fs::exists(©).unwrap(), + "Drop must not delte the directory" + ); + + fs::remove_dir_all(copy).unwrap(); // cleanup + } + + #[test] + fn test_to_persistent() { + let temp_dir = TempDir::new().unwrap(); + + let copy = PathBuf::from(temp_dir.path()); + + let persistent = temp_dir.to_persistent(); + assert_eq!(copy, persistent, "Path must be correct"); + assert!( + fs::exists(&persistent).unwrap(), + "Directory must still exist." + ); + + fs::remove_dir_all(persistent).unwrap(); // cleanup + } +} -- 2.47.3