Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions dstack/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions dstack/crates/dstack-volume/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
95 changes: 82 additions & 13 deletions dstack/crates/dstack-volume/src/volume.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down Expand Up @@ -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)
}
Expand All @@ -125,7 +125,7 @@ fn seal_data_image(
output: &Path,
salt_hex: &str,
) -> Result<BuiltVolume> {
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;
{
Expand Down Expand Up @@ -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> {
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 {
Expand Down Expand Up @@ -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(())
}
}
Loading