[pbs-devel] [PATCH proxmox v2] tools: Add tempfile() helper function
Mira Limbeck
m.limbeck at proxmox.com
Wed Aug 12 16:34:20 CEST 2020
The tempfile() helper function tries to create a temporary file in /tmp
with the O_TMPFILE option. If that fails it falls back to using
mkstemp().
As O_TMPFILE was introduced in kernel 3.11 this fallback can help with
CentOS 7 and its 3.10 kernel as well as with WSL (Windows Subsystem for
Linux).
Signed-off-by: Mira Limbeck <m.limbeck at proxmox.com>
---
proxmox/src/tools/fs.rs | 25 ++++++++++++++++++++++++-
1 file changed, 24 insertions(+), 1 deletion(-)
diff --git a/proxmox/src/tools/fs.rs b/proxmox/src/tools/fs.rs
index b1a95b5..b3072db 100644
--- a/proxmox/src/tools/fs.rs
+++ b/proxmox/src/tools/fs.rs
@@ -3,6 +3,7 @@
use std::ffi::CStr;
use std::fs::{File, OpenOptions};
use std::io::{self, BufRead, BufReader, Write};
+use std::os::unix::fs::OpenOptionsExt;
use std::os::unix::io::{AsRawFd, FromRawFd, RawFd};
use std::path::Path;
use std::time::Duration;
@@ -11,7 +12,7 @@ use anyhow::{bail, format_err, Error};
use nix::errno::Errno;
use nix::fcntl::OFlag;
use nix::sys::stat;
-use nix::unistd::{self, Gid, Uid};
+use nix::unistd::{self, mkstemp, unlink, Gid, Uid};
use serde_json::Value;
use crate::sys::error::SysResult;
@@ -518,3 +519,25 @@ pub fn open_file_locked<P: AsRef<Path>>(path: P, timeout: Duration) -> Result<Fi
Err(err) => bail!("Unable to acquire lock {:?} - {}", path, err),
}
}
+
+/// Create a new tempfile by using O_TMPFILE with a fallback to mkstemp() if it fails (e.g. not supported).
+pub fn tempfile() -> Result<File, Error> {
+ match std::fs::OpenOptions::new()
+ .write(true)
+ .read(true)
+ .custom_flags(libc::O_TMPFILE)
+ .open("/tmp")
+ {
+ Ok(file) => return Ok(file),
+ Err(err) => {
+ eprintln!(
+ "Error creating tempfile: '{}', trying mkstemp() instead",
+ err
+ );
+ let (fd, path) = mkstemp("/tmp/proxmox-tmpfile_XXXXXX")?;
+ unlink(path.as_path())?;
+ let file = unsafe { File::from_raw_fd(fd) };
+ Ok(file)
+ }
+ }
+}
--
2.20.1
More information about the pbs-devel
mailing list