diff --git a/dstack/Cargo.lock b/dstack/Cargo.lock index 6b4dae1d2..dc16ec288 100644 --- a/dstack/Cargo.lock +++ b/dstack/Cargo.lock @@ -2647,6 +2647,7 @@ dependencies = [ "fs-err", "gpt", "hex", + "libc", "serde_json", "sha2 0.10.9", "tempfile", diff --git a/dstack/crates/dstack-volume/Cargo.toml b/dstack/crates/dstack-volume/Cargo.toml index 76262b6fe..aff295957 100644 --- a/dstack/crates/dstack-volume/Cargo.toml +++ b/dstack/crates/dstack-volume/Cargo.toml @@ -20,6 +20,7 @@ sha2 = { workspace = true, features = ["std"] } hex = { workspace = true, features = ["std"] } fs-err.workspace = true gpt = "4.1.0" +libc.workspace = true tempfile.workspace = true tracing.workspace = true tracing-subscriber.workspace = true diff --git a/dstack/crates/dstack-volume/src/volume.rs b/dstack/crates/dstack-volume/src/volume.rs index ba9ee6ac1..2e43708aa 100644 --- a/dstack/crates/dstack-volume/src/volume.rs +++ b/dstack/crates/dstack-volume/src/volume.rs @@ -82,7 +82,7 @@ pub fn build_volume( require_tool("mksquashfs")?; require_tool("veritysetup")?; - let tmp = tempfile::tempdir().context("creating volume scratch dir")?; + let tmp = scratch_dir_for(output).context("creating volume scratch dir")?; let data_path = tmp.path().join("data.fs"); // 1. reproducible squashfs. @@ -112,9 +112,9 @@ pub fn build_fs_image(fs_image: &Path, output: &Path, salt_hex: &str) -> Result< bail!("filesystem image '{}' is empty", fs_image.display()); } - let tmp = tempfile::tempdir().context("creating volume scratch dir")?; + let tmp = scratch_dir_for(output).context("creating volume scratch dir")?; let data_path = tmp.path().join("data.fs"); - fs::copy(fs_image, &data_path) + clone_or_copy_file(fs_image, &data_path) .with_context(|| format!("copying {} into scratch", fs_image.display()))?; seal_data_image(&data_path, len, output, salt_hex) } @@ -125,7 +125,7 @@ fn seal_data_image( output: &Path, salt_hex: &str, ) -> Result { - let hash_tmp = tempfile::tempdir().context("creating verity hash scratch dir")?; + let hash_tmp = scratch_dir_for(output).context("creating verity hash scratch dir")?; let hash_path = hash_tmp.path().join("verity.hash"); let data_size = data_len.div_ceil(BLOCK) * BLOCK; { @@ -368,21 +368,76 @@ fn write_volume_header(out: &mut fs::File, offset: u64, root_hash: &str) -> Resu Ok(()) } +/// Create a scratch directory next to `output` so temporary blobs live on the +/// same filesystem as the final image (required for `FICLONERANGE` and avoids +/// filling a small `/tmp`). +fn scratch_dir_for(output: &Path) -> std::io::Result { + tempfile::tempdir_in(scratch_parent(output)) +} + +fn scratch_parent(output: &Path) -> &Path { + output + .parent() + .filter(|p| !p.as_os_str().is_empty()) + .unwrap_or_else(|| Path::new(".")) +} + +/// Place `src` in `out` at `offset`. On a filesystem with reflinks (XFS, +/// Btrfs) the extents are shared instead of written again (the partitions are +/// 1 MiB aligned and the inputs are padded to whole blocks), so packing a +/// large directory needs no second copy of it on disk. Elsewhere it copies. fn copy_into(src: &Path, out: &mut fs::File, offset: u64) -> Result<()> { - use std::io::{Read, Seek, SeekFrom, Write}; - let mut input = fs::File::open(src)?; + use std::io::{Seek, SeekFrom}; + let input = fs::File::open(src)?; + if clone_range(input.file(), out.file(), offset).is_ok() { + return Ok(()); + } out.seek(SeekFrom::Start(offset))?; - let mut buf = vec![0u8; 1 << 20]; - loop { - let n = input.read(&mut buf)?; - if n == 0 { - break; - } - out.write_all(&buf[..n])?; + // Copy via the underlying `std::fs::File` handles so `std::io::copy` keeps + // its `copy_file_range` specialization instead of an 8 KiB userspace loop. + std::io::copy(&mut input.file(), &mut out.file()) + .with_context(|| format!("copying {} into output", src.display()))?; + Ok(()) +} + +/// Copy `src` to a new file `dst`, sharing extents where the filesystem can. +fn clone_or_copy_file(src: &Path, dst: &Path) -> Result<()> { + let input = fs::File::open(src)?; + let output = fs::File::create(dst)?; + if clone_range(input.file(), output.file(), 0).is_ok() { + return Ok(()); } + drop(output); + fs::copy(src, dst)?; Ok(()) } +/// `FICLONERANGE` of all of `src` (`src_length` 0: to its end) into `dst` at +/// `dest_offset`. `copy_file_range` does not reliably reflink (not on Linux +/// 7.0 with XFS), so this asks for the clone explicitly. +#[cfg(target_os = "linux")] +fn clone_range(src: &std::fs::File, dst: &std::fs::File, dest_offset: u64) -> std::io::Result<()> { + use std::os::fd::AsRawFd; + let arg = libc::file_clone_range { + src_fd: src.as_raw_fd() as i64, + src_offset: 0, + src_length: 0, + dest_offset, + }; + // SAFETY: `FICLONERANGE` reads a `libc::file_clone_range` pointer. + let ret = unsafe { libc::ioctl(dst.as_raw_fd(), libc::FICLONERANGE, &arg) }; + if ret == 0 { + Ok(()) + } else { + Err(std::io::Error::last_os_error()) + } +} + +#[cfg(not(target_os = "linux"))] +fn clone_range(_: &std::fs::File, _: &std::fs::File, _: u64) -> std::io::Result<()> { + Err(std::io::ErrorKind::Unsupported.into()) +} + fn require_tool(name: &str) -> Result<()> { let present = run_cmd!(which $name >/dev/null 2>&1).is_ok(); if !present { @@ -487,4 +542,18 @@ mod tests { Ok(()) } + + #[test] + fn scratch_dir_is_created_next_to_output() -> Result<()> { + assert_eq!(scratch_parent(Path::new("volume.img")), Path::new(".")); + assert_eq!( + scratch_parent(Path::new("/data/volumes/volume.img")), + Path::new("/data/volumes") + ); + let dir = tempfile::tempdir()?; + let output = dir.path().join("volume.img"); + let scratch = scratch_dir_for(&output)?; + assert_eq!(scratch.path().parent(), Some(dir.path())); + Ok(()) + } }