public inbox for pbs-devel@lists.proxmox.com
 help / color / mirror / Atom feed
From: Robert Obkircher <r.obkircher@proxmox.com>
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	[thread overview]
Message-ID: <20260210150642.469670-4-r.obkircher@proxmox.com> (raw)
In-Reply-To: <20260210150642.469670-1-r.obkircher@proxmox.com>

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 <r.obkircher@proxmox.com>
---
 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<Self, Error> {
+        TempDir::new_in(env::temp_dir())
+    }
+
+    /// Create an empty child directory in the specified one.
+    pub fn new_in(parent: impl AsRef<Path>) -> Result<Self, Error> {
+        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<Path> 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(&copy).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(&copy).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(&copy).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





  parent reply	other threads:[~2026-02-10 15:06 UTC|newest]

Thread overview: 24+ messages / expand[flat|nested]  mbox.gz  Atom feed  top
2026-02-10 15:06 [PATCH v6 proxmox-backup 00/18] fix: #3847 pipe from STDIN to proxmox-backup-client Robert Obkircher
2026-02-10 15:06 ` [PATCH v6 proxmox-backup 01/18] datastore: remove Arc<ChunkStore> from FixedIndexWriter Robert Obkircher
2026-02-10 15:06 ` [PATCH v6 proxmox-backup 02/18] datastore: remove Arc<ChunkStore> from DynamicIndexWriter Robert Obkircher
2026-02-10 15:06 ` Robert Obkircher [this message]
2026-02-10 15:06 ` [PATCH v6 proxmox-backup 04/18] datastore: use temporary directory for chunk store test Robert Obkircher
2026-02-10 15:06 ` [PATCH v6 proxmox-backup 05/18] datastore: combine public FixedIndexWriter methods into add_chunk Robert Obkircher
2026-02-10 15:06 ` [PATCH v6 proxmox-backup 06/18] datastore: use fixed size types for FixedIndexWriter Robert Obkircher
2026-02-10 15:06 ` [PATCH v6 proxmox-backup 07/18] datastore: verify that chunk_size is a power of two Robert Obkircher
2026-02-17  9:13   ` Robert Obkircher
2026-02-17  9:40     ` Christian Ebner
2026-02-10 15:06 ` [PATCH v6 proxmox-backup 08/18] datastore: support writing fidx files of unknown size Robert Obkircher
2026-02-10 15:06 ` [PATCH v6 proxmox-backup 09/18] datastore: test FixedIndexWriter Robert Obkircher
2026-02-10 15:06 ` [PATCH v6 proxmox-backup 10/18] api: backup: make fixed index file size optional Robert Obkircher
2026-02-10 15:06 ` [PATCH v6 proxmox-backup 11/18] api: verify fixed index writer size on close Robert Obkircher
2026-02-10 15:06 ` [PATCH v6 proxmox-backup 12/18] client: don't poll terminated source in FixedChunkStream Robert Obkircher
2026-02-17 10:01   ` Christian Ebner
2026-02-17 10:06     ` Christian Ebner
2026-02-10 15:06 ` [PATCH v6 proxmox-backup 13/18] client: don't poll terminated source in ChunkStream Robert Obkircher
2026-02-10 15:06 ` [PATCH v6 proxmox-backup 14/18] fix #3847: client: support fifo pipe inputs for image backups Robert Obkircher
2026-02-10 15:06 ` [PATCH v6 proxmox-backup 15/18] client: Fail early if the same pipe is specified for multiple inputs Robert Obkircher
2026-02-10 15:06 ` [PATCH v6 proxmox-backup 16/18] datastore: compute fidx file size with overflow checks Robert Obkircher
2026-02-10 15:06 ` [PATCH v6 proxmox-backup 17/18] datastore: support writing fidx files on systems with larger page size Robert Obkircher
2026-02-10 15:06 ` [PATCH v6 proxmox-backup 18/18] datastore: support incremental fidx uploads with different size Robert Obkircher
2026-02-17 12:42 ` [PATCH v6 proxmox-backup 00/18] fix: #3847 pipe from STDIN to proxmox-backup-client 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=20260210150642.469670-4-r.obkircher@proxmox.com \
    --to=r.obkircher@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
Service provided by Proxmox Server Solutions GmbH | Privacy | Legal