diff --git a/README.md b/README.md index c076830d5..85add18f6 100644 --- a/README.md +++ b/README.md @@ -77,13 +77,15 @@ pins, and Cargo fetches metal2vulkan from its public repository, at the commit t `~/.local/share/reims-ctl/installers` (delete them there to get the space back, once your VMs' installers are ejected), and an interrupted one picks up where it stopped. - Already have macOS on a disk? `--disk` uses it (copied, reflinked where the file system can, or - in place). Where the OpenCore image it booted with sits beside it as `opencore.qcow2`, as in - a VM's folder, the VM's new image presents that same Mac; `--opencore` copies an image of - yours instead, with OVMF beside it, which keeps its Mac too. With neither, or when you copy the - disk of one of your reims-ctl VMs, which can then run beside it, the VM is a new Mac to that - macOS, so it opens Setup Assistant once at its first boot; finish it in the window, since it - won't shut down until you do. `--installer` takes an installer of your own. + Already have macOS on a disk? `--disk` uses it, copied or in place. The copy is instant where the + disk and the VM's folder are on one file system that makes reflinks, such as btrfs or XFS; + otherwise reims-ctl copies it in full, and says so, with its size, before it starts. Where the + OpenCore image it booted with sits beside it as `opencore.qcow2`, as in a VM's folder, the VM's + new image presents that same Mac; `--opencore` copies an image of yours instead, with OVMF beside + it, which keeps its Mac too. With neither, or when you copy the disk of one of your reims-ctl + VMs, which can then run beside it, the VM is a new Mac to that macOS, so it opens Setup Assistant + once at its first boot; finish it in the window, since it won't shut down until you do. + `--installer` takes an installer of your own. ### Day to day diff --git a/crates/reims-ctl/src/cli.rs b/crates/reims-ctl/src/cli.rs index 23c598e2d..155d667d1 100644 --- a/crates/reims-ctl/src/cli.rs +++ b/crates/reims-ctl/src/cli.rs @@ -278,7 +278,8 @@ pub struct CreateArgs { /// An existing disk image #[arg(long, conflicts_with = "disk_size")] pub disk: Option, - /// How an existing disk is used: copy (a reflink or clone where it can) or in-place + /// How an existing disk is used: copy (instant, a reflink, where the disk and the VM's + /// directory are on one file system that makes them, else a full copy) or in-place #[arg(long, default_value = "copy")] pub disk_mode: String, /// Download this macOS from Apple to install: a name (tahoe), a number (26) or latest; with diff --git a/crates/reims-ctl/src/copy.rs b/crates/reims-ctl/src/copy.rs new file mode 100644 index 000000000..409c97ef0 --- /dev/null +++ b/crates/reims-ctl/src/copy.rs @@ -0,0 +1,476 @@ +//! Copying an image into a VM's directory: a reflink (Linux's btrfs and XFS) or a clone (APFS), +//! which shares the source's blocks and takes no time whatever its size, where the source and the +//! copy are on one file system that makes them; else a full copy, which reads and writes every +//! byte. A long full copy says so before it starts, with how much it copies and why it is no +//! reflink, then how far it is, as reims-util's downloads do (reims_util.rs). Either way the copy +//! is the source's bytes, its holes kept, and a file of its own: a write to one leaves the other +//! as it was. +//! +//! Measured with copies of a 57.9 GB qcow2 between two directories of one btrfs subvolume (Linux +//! 7.3.1, 2026-11-08): a reflink took 119 ms where it had 11,477 extents, and 785 ms where it had +//! 110,874. + +use crate::paths; +use crate::reims_util::size; +use anyhow::{Context, Result}; +use std::fs::{File, OpenOptions}; +use std::io; +use std::os::fd::AsRawFd; +use std::os::unix::fs::{FileExt, MetadataExt, OpenOptionsExt}; +use std::path::Path; +use std::time::{Duration, Instant}; + +/// A full copy of more data than this says so first, and then how far it is: at an NVMe drive's +/// 2 GB/s, a gigabyte takes half a second. An OpenCore image or OVMF, a few megabytes, copies +/// without a word. +const LONG: u64 = 1_000_000_000; + +/// Copies `src` to `dst`, a file that does not exist yet, with `src`'s permissions: a reflink or +/// clone where the file system makes one, else a full copy, which `progress` hears of first where +/// it is long, with its size and why it is no reflink, and then how far it is. +pub fn file(src: &Path, dst: &Path, progress: &mut dyn FnMut(&str)) -> Result<()> { + copy(src, dst, LONG, progress) +} + +/// [`file`], where a full copy of more than `long` bytes of data is told. +fn copy(src: &Path, dst: &Path, long: u64, progress: &mut dyn FnMut(&str)) -> Result<()> { + let fail = || format!("could not copy {} to {}", src.display(), dst.display()); + let refused = match clone(src, dst) { + Ok(()) => return Ok(()), + Err(e) => e, + }; + let from = File::open(src).with_context(fail)?; + let len = from.metadata().with_context(fail)?.len(); + let to = create(&from, dst).with_context(fail)?; + let ranges = data_ranges(&from, len); + let total: u64 = ranges.iter().map(|(a, b)| b - a).sum(); + if total <= long { + return full(&from, &to, &ranges, len, &mut |_| {}).with_context(fail); + } + let why = Why::of(&refused, src, dst); + let name = src + .file_name() + .map(|n| n.to_string_lossy().into_owned()) + .unwrap_or_default(); + progress(&format!( + "copying {name} in full, {}, not as a reflink: {}", + size(total), + why.note(src, dst) + )); + // Each whole percent, at most once a second but for the first and the last. + let short = why.short(); + let mut shown: Option<(u64, Instant)> = None; + full(&from, &to, &ranges, len, &mut |done| { + let pct = done.min(total) * 100 / total; + let due = match shown { + None => true, + Some((p, t)) => p != pct && (pct == 100 || t.elapsed() >= Duration::from_secs(1)), + }; + if due { + shown = Some((pct, Instant::now())); + progress(&format!( + "copying {name} in full ({short}): {pct}% of {}", + size(total) + )); + } + }) + .with_context(fail) +} + +/// `dst`, made empty, with the permissions of `from`, as `cp` makes its copy. +fn create(from: &File, dst: &Path) -> io::Result { + OpenOptions::new() + .write(true) + .create(true) + .truncate(true) + .mode(from.metadata()?.mode() & 0o7777) + .open(dst) +} + +/// Makes `dst` a reflink of `src`, or returns the file system's refusal. +#[cfg(target_os = "linux")] +fn clone(src: &Path, dst: &Path) -> io::Result<()> { + let from = File::open(src)?; + let to = create(&from, dst)?; + // SAFETY: FICLONE takes the source's descriptor; both are open for the call. + if unsafe { libc::ioctl(to.as_raw_fd(), libc::FICLONE, from.as_raw_fd()) } == 0 { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } +} + +/// Makes `dst` a clone of `src`, or returns the file system's refusal. +#[cfg(target_os = "macos")] +fn clone(src: &Path, dst: &Path) -> io::Result<()> { + let (s, d) = (c_path(src)?, c_path(dst)?); + // SAFETY: both are NUL-terminated paths, alive for the call. + if unsafe { libc::clonefile(s.as_ptr(), d.as_ptr(), 0) } == 0 { + Ok(()) + } else { + Err(io::Error::last_os_error()) + } +} + +#[cfg(target_os = "macos")] +fn c_path(p: &Path) -> io::Result { + use std::os::unix::ffi::OsStrExt; + std::ffi::CString::new(p.as_os_str().as_bytes()).map_err(io::Error::other) +} + +/// The parts of `f`, `len` bytes long, that hold data, as `[start, end)`: all of it where the file +/// system tells no holes. +fn data_ranges(f: &File, len: u64) -> Vec<(u64, u64)> { + let seek = |at: u64, whence| { + // SAFETY: lseek on an open descriptor. + let r = unsafe { libc::lseek(f.as_raw_fd(), at as libc::off_t, whence) }; + if r < 0 { + Err(io::Error::last_os_error()) + } else { + Ok(r as u64) + } + }; + let mut ranges = Vec::new(); + let mut at = 0; + while at < len { + let start = match seek(at, libc::SEEK_DATA) { + Ok(s) => s, + // No data after `at`. + Err(e) if e.raw_os_error() == Some(libc::ENXIO) => break, + Err(_) => at, + }; + let end = seek(start, libc::SEEK_HOLE).unwrap_or(len).min(len); + if end <= start { + break; + } + ranges.push((start, end)); + at = end; + } + ranges +} + +/// Copies `ranges` of `from` to `to`, then makes `to` `len` bytes long; `copied` hears how many +/// bytes of the ranges are copied, from 0. Blocks of zeros are left holes, as `cp --sparse=always` +/// leaves them. +fn full( + from: &File, + to: &File, + ranges: &[(u64, u64)], + len: u64, + copied: &mut dyn FnMut(u64), +) -> io::Result<()> { + const BLOCK: usize = 4096; + let mut buf = vec![0u8; 1 << 20]; + let mut done = 0; + copied(0); + for &(start, end) in ranges { + let mut at = start; + while at < end { + let n = ((end - at) as usize).min(buf.len()); + from.read_exact_at(&mut buf[..n], at)?; + // Each run of blocks not all zeros, written at once. + let mut run: Option = None; + for (i, block) in buf[..n].chunks(BLOCK).enumerate() { + match (block.iter().all(|&b| b == 0), run) { + (false, None) => run = Some(i * BLOCK), + (true, Some(r)) => { + to.write_all_at(&buf[r..i * BLOCK], at + r as u64)?; + run = None; + } + _ => {} + } + } + if let Some(r) = run { + to.write_all_at(&buf[r..n], at + r as u64)?; + } + at += n as u64; + done += n as u64; + copied(done); + } + } + to.set_len(len) +} + +/// Why a copy is no reflink, from the file system's refusal of one. +#[derive(Debug, PartialEq, Eq)] +enum Why { + /// The source is on the first file system, and the copy on the second. + Apart(String, String), + /// Their file system makes none. + Unsupported(String), + /// Their file system refused one, with this error. + Refused(String, String), +} + +impl Why { + fn of(e: &io::Error, src: &Path, dst: &Path) -> Why { + let fs = |p: &Path| { + p.parent() + .and_then(file_system) + .unwrap_or_else(|| "its file system".into()) + }; + Why::from_error(e, fs(src), fs(dst)) + } + + /// From `e`, how a reflink of a file on `from` to one on `to` ended. + fn from_error(e: &io::Error, from: String, to: String) -> Why { + match e.raw_os_error() { + Some(libc::EXDEV) => Why::Apart(from, to), + Some(c) + if [libc::EOPNOTSUPP, libc::ENOTSUP, libc::ENOTTY, libc::ENOSYS].contains(&c) => + { + Why::Unsupported(from) + } + _ => Why::Refused(from, e.to_string()), + } + } + + /// Why a full copy of `src` to `dst` is no reflink, as it says before it starts. + fn note(&self, src: &Path, dst: &Path) -> String { + let dir = |p: &Path| paths::tilde(p.parent().unwrap_or(p)); + match self { + Why::Apart(a, b) => format!( + "{} and {} are different file systems ({a} and {b}), and a reflink is made \ + within one", + dir(src), + dir(dst) + ), + Why::Unsupported(fs) => format!("{fs}, which {} is on, makes none", dir(src)), + Why::Refused(fs, e) => format!("{fs} refused one: {e}"), + } + } + + /// Why, in the few words each step of the copy says. + fn short(&self) -> String { + match self { + Why::Apart(..) => "different file systems".into(), + Why::Unsupported(fs) => format!("{fs} makes no reflinks"), + Why::Refused(fs, _) => format!("{fs} refused a reflink"), + } + } +} + +/// The type of the file system `dir` is on: btrfs, ext4, tmpfs. +#[cfg(target_os = "linux")] +fn file_system(dir: &Path) -> Option { + let mounts = std::fs::read_to_string("/proc/self/mountinfo").ok()?; + mount_type(&mounts, &std::fs::canonicalize(dir).ok()?) +} + +/// The type of the file system `dir` is on: apfs, hfs, exfat. +#[cfg(target_os = "macos")] +fn file_system(dir: &Path) -> Option { + let p = c_path(dir).ok()?; + // SAFETY: statfs fills the struct it is given; all zeros is a valid one. + let mut s: libc::statfs = unsafe { std::mem::zeroed() }; + if unsafe { libc::statfs(p.as_ptr(), &mut s) } != 0 { + return None; + } + // SAFETY: f_fstypename is NUL-terminated. + let name = unsafe { std::ffi::CStr::from_ptr(s.f_fstypename.as_ptr()) }; + Some(name.to_string_lossy().into_owned()) +} + +/// The type of the mount `path`, absolute and with no symbolic links, is on, by `mountinfo`, as +/// /proc/self/mountinfo lists the mounts: the last on the longest mount point above it, which is +/// the one over the others there. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn mount_type(mountinfo: &str, path: &Path) -> Option { + let mut best: Option<(usize, &str)> = None; + for line in mountinfo.lines() { + let Some((mount, rest)) = line.split_once(" - ") else { + continue; + }; + let (Some(point), Some(fs)) = (mount.split(' ').nth(4), rest.split(' ').next()) else { + continue; + }; + let point = unescape(point); + if path.starts_with(&point) && best.is_none_or(|(n, _)| point.len() >= n) { + best = Some((point.len(), fs)); + } + } + best.map(|(_, fs)| fs.to_string()) +} + +/// A mount point as mountinfo writes it, where a space, tab, newline or backslash is `\` and its +/// three octal digits. +#[cfg_attr(not(target_os = "linux"), allow(dead_code))] +fn unescape(s: &str) -> String { + let b = s.as_bytes(); + let mut out = Vec::with_capacity(b.len()); + let mut i = 0; + while i < b.len() { + match b.get(i + 1..i + 4) { + Some(d) if b[i] == b'\\' && d.iter().all(|c| (b'0'..=b'7').contains(c)) => { + out.push((d[0] - b'0') * 64 + (d[1] - b'0') * 8 + (d[2] - b'0')); + i += 4; + } + _ => { + out.push(b[i]); + i += 1; + } + } + } + String::from_utf8_lossy(&out).into_owned() +} + +#[cfg(test)] +mod tests { + use super::*; + use std::path::PathBuf; + + fn dir(base: &Path, tag: &str) -> PathBuf { + let d = base.join(format!("reims-ctl-copy-{tag}-{}", std::process::id())); + let _ = std::fs::remove_dir_all(&d); + std::fs::create_dir_all(&d).unwrap(); + d + } + + /// A file of `len` bytes: data at 0, a run of zeros, then a hole to the end. + fn sparse_file(p: &Path, len: u64) -> Vec { + use std::os::unix::fs::PermissionsExt; + let f = File::create(p).unwrap(); + let data: Vec = (0..300_000u32).map(|i| (i * 7 + 1) as u8).collect(); + f.write_all_at(&data, 0).unwrap(); + f.write_all_at(&[0u8; 65536], data.len() as u64).unwrap(); + f.write_all_at(b"tail", len / 2).unwrap(); + f.set_len(len).unwrap(); + std::fs::set_permissions(p, std::fs::Permissions::from_mode(0o640)).unwrap(); + std::fs::read(p).unwrap() + } + + /// A refusal names why: the file systems differ, theirs makes no reflinks, or theirs refused + /// one for a reason of its own, which it gives. + #[test] + fn a_refused_reflink_says_why() { + let why = |code, a: &str, b: &str| { + Why::from_error(&io::Error::from_raw_os_error(code), a.into(), b.into()) + }; + let (src, dst) = ( + paths::home().join("vms/old/disk.qcow2"), + paths::home().join(".local/share/reims-ctl/vms/mac/disk.qcow2"), + ); + let apart = why(libc::EXDEV, "ext4", "btrfs"); + assert_eq!(apart, Why::Apart("ext4".into(), "btrfs".into())); + assert_eq!( + apart.note(&src, &dst), + "~/vms/old and ~/.local/share/reims-ctl/vms/mac are different file systems (ext4 \ + and btrfs), and a reflink is made within one" + ); + assert_eq!(apart.short(), "different file systems"); + for code in [libc::EOPNOTSUPP, libc::ENOTTY] { + let none = why(code, "ext4", "ext4"); + assert_eq!(none, Why::Unsupported("ext4".into())); + assert_eq!( + none.note(&src, &dst), + "ext4, which ~/vms/old is on, makes none" + ); + assert_eq!(none.short(), "ext4 makes no reflinks"); + } + let refused = why(libc::EINVAL, "btrfs", "btrfs"); + let e = io::Error::from_raw_os_error(libc::EINVAL).to_string(); + assert_eq!(refused, Why::Refused("btrfs".into(), e.clone())); + assert_eq!(refused.note(&src, &dst), format!("btrfs refused one: {e}")); + assert_eq!(refused.short(), "btrfs refused a reflink"); + } + + /// A path's file system is the last mount on the longest mount point above it, whose escapes + /// are undone. + #[test] + fn the_mount_table_names_the_file_system_a_path_is_on() { + let mounts = "\ +22 1 0:21 /@ / rw,noatime shared:1 - btrfs /dev/nvme0n1p2 rw,compress=zstd:1 +23 22 0:22 / /tmp rw,noatime shared:5 - tmpfs tmpfs rw,inode64 +24 22 0:21 /@home /home rw,noatime shared:2 - btrfs /dev/nvme0n1p2 rw +25 24 8:1 / /home/u/my\\040vms rw,relatime shared:9 - ext4 /dev/sda1 rw +26 23 0:30 / /tmp rw,relatime shared:6 - ramfs ramfs rw +"; + let fs = |p: &str| mount_type(mounts, Path::new(p)); + assert_eq!(fs("/home/u/vms/disk.qcow2").as_deref(), Some("btrfs")); + assert_eq!(fs("/home/u/my vms/disk.qcow2").as_deref(), Some("ext4")); + assert_eq!(fs("/home/u/my vmsx").as_deref(), Some("btrfs")); + assert_eq!(fs("/tmp/x").as_deref(), Some("ramfs")); + assert_eq!(fs("/usr").as_deref(), Some("btrfs")); + assert_eq!(unescape("a\\134b\\011c\\0"), "a\\b\tc\\0"); + } + + /// A full copy is the source's bytes and length, its holes and zeros left holes, with its + /// permissions, and says how far it is from 0 to all of the data. + #[test] + fn a_full_copy_keeps_the_bytes_and_the_holes() { + let d = dir(&std::env::temp_dir(), "full"); + let len = 64 << 20; + let bytes = sparse_file(&d.join("src"), len); + let from = File::open(d.join("src")).unwrap(); + let to = create(&from, &d.join("dst")).unwrap(); + let ranges = data_ranges(&from, len); + let mut seen = Vec::new(); + full(&from, &to, &ranges, len, &mut |n| seen.push(n)).unwrap(); + assert_eq!(std::fs::read(d.join("dst")).unwrap(), bytes); + let meta = std::fs::metadata(d.join("dst")).unwrap(); + assert_eq!(meta.mode() & 0o777, 0o640); + assert!( + meta.blocks() * 512 < 8 << 20, + "{} bytes", + meta.blocks() * 512 + ); + let total: u64 = ranges.iter().map(|(a, b)| b - a).sum(); + assert_eq!(seen.first(), Some(&0)); + assert_eq!(seen.last(), Some(&total)); + assert!(seen.windows(2).all(|w| w[0] < w[1]), "{seen:?}"); + std::fs::remove_dir_all(&d).unwrap(); + } + + /// A copy within a directory of btrfs or APFS is a reflink or clone, and says nothing; one + /// within tmpfs, which makes none, is a full copy that says so; one between file systems of + /// two types is a full copy that says they differ. Each is the source's bytes. The test + /// copies within and between the temporary directory, the test's own and, on Linux, + /// /dev/shm: one APFS volume on a Mac, and btrfs and tmpfs on the Linux hosts that check + /// it. + #[test] + fn a_copy_is_a_reflink_where_it_can_be_and_says_why_where_not() { + let exe = std::env::current_exe().unwrap(); + let mut dirs = vec![ + dir(&std::env::temp_dir(), "tmp"), + dir(exe.parent().unwrap(), "target"), + ]; + // tmpfs on Linux, wherever the temporary directory is. + if Path::new("/dev/shm").is_dir() { + dirs.push(dir(Path::new("/dev/shm"), "shm")); + } + for (i, from) in dirs.iter().enumerate() { + let bytes = sparse_file(&from.join("src"), 4 << 20); + for (j, to) in dirs.iter().enumerate() { + let dst = to.join(format!("copy-{i}-{j}")); + let mut seen = Vec::new(); + copy(&from.join("src"), &dst, 0, &mut |s| { + seen.push(s.to_string()) + }) + .unwrap(); + assert_eq!(std::fs::read(&dst).unwrap(), bytes); + assert_eq!(std::fs::metadata(&dst).unwrap().mode() & 0o777, 0o640); + let (a, b) = (file_system(from).unwrap(), file_system(to).unwrap()); + let said = seen.first().map(String::as_str).unwrap_or(""); + if a != b { + assert!( + said.contains("are different file systems"), + "{a} {b}: {seen:?}" + ); + } else if i == j && ["btrfs", "apfs"].contains(&a.as_str()) { + assert!(seen.is_empty(), "{a}: {seen:?}"); + } else if i == j && a == "tmpfs" { + assert!(said.ends_with("makes none"), "{seen:?}"); + assert!(said.starts_with("copying src in full, 1 MB, not as a reflink")); + assert_eq!( + seen.last().unwrap(), + "copying src in full (tmpfs makes no reflinks): 100% of 1 MB" + ); + } + std::fs::remove_file(&dst).unwrap(); + } + } + for d in &dirs { + std::fs::remove_dir_all(d).unwrap(); + } + } +} diff --git a/crates/reims-ctl/src/create.rs b/crates/reims-ctl/src/create.rs index 24b8448f0..cb11ccf0c 100644 --- a/crates/reims-ctl/src/create.rs +++ b/crates/reims-ctl/src/create.rs @@ -1,17 +1,18 @@ //! Making a VM: its directory, disks, firmware and `vm.toml`, then its registry entry. //! -//! An x86-64 VM (`q35-x86_64`) boots OpenCore from an OpenCore image of its own, with its own -//! OVMF code and variables: made for it by reims-util, holding the guest's kexts for -//! reims-vgpu's own device where the VM is on it ([`reims_util::kext_args`]), and presenting the -//! Mac an existing disk's macOS ran on where the image it booted from is beside it -//! ([`disks_mac`]), or copies of an image given and the OVMF beside it ([`firmware_beside`]). -//! Its disk is a new one or an existing one (copied, reflinked where the file system can, or used -//! in place). A new disk needs an installer: one reims-util downloads from Apple (reims_util.rs), -//! before the VM's directory is made, so a download stopped part way leaves no VM half made, or -//! one given. An installer is used in place, except a DMG, which qemu-img converts to a raw image -//! in the VM's directory ([`installer_media`]). A VM's settings name its graphics: reims-vgpu's -//! own device unless the create chose another. +//! An x86-64 VM (`q35-x86_64`) boots OpenCore from an OpenCore image of its own, with its own OVMF +//! code and variables: made for it by reims-util, holding the guest's kexts for reims-vgpu's own +//! device where the VM is on it ([`reims_util::kext_args`]), and presenting the Mac an existing +//! disk's macOS ran on where the image it booted from is beside it ([`disks_mac`]), or copies of an +//! image given and the OVMF beside it ([`firmware_beside`]). Its disk is a new one or an existing +//! one, copied (a reflink where the file system can make one, else a full copy, which says so +//! first: copy.rs) or used in place. A new disk needs an installer: one reims-util downloads from +//! Apple (reims_util.rs), before the VM's directory is made, so a download stopped part way leaves +//! no VM half made, or one given. An installer is used in place, except a DMG, which qemu-img +//! converts to a raw image in the VM's directory ([`installer_media`]). A VM's settings name its +//! graphics: reims-vgpu's own device unless the create chose another. +use crate::copy; use crate::host::{Host, Profile}; use crate::install; use crate::opencore::{self, Identity}; @@ -25,7 +26,9 @@ use std::process::Command; #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub enum ImportMode { - /// A copy in the VM's directory: reflinked (btrfs, XFS) or cloned (APFS) where it can be. + /// A copy in the VM's directory: a reflink (btrfs, XFS) or clone (APFS) where the image and + /// the directory are on one file system that makes them, else a full copy, which says so + /// first where it is long ([`copy`]). Copy, /// The image itself. InPlace, @@ -313,38 +316,6 @@ fn file_name(p: &Path) -> String { .unwrap_or_default() } -/// Copies `src` to `dst`: a clone on APFS, a reflink where Linux's file system can, else a -/// sparse copy. -pub fn copy_file(src: &Path, dst: &Path) -> Result<()> { - let ok = if cfg!(target_os = "macos") { - Command::new("cp") - .arg("-c") - .arg(src) - .arg(dst) - .status() - .map(|s| s.success()) - .unwrap_or(false) - || Command::new("cp") - .arg(src) - .arg(dst) - .status() - .map(|s| s.success()) - .unwrap_or(false) - } else { - Command::new("cp") - .args(["--reflink=auto", "--sparse=always"]) - .arg(src) - .arg(dst) - .status() - .map(|s| s.success()) - .unwrap_or(false) - }; - if !ok { - bail!("could not copy {} to {}", src.display(), dst.display()); - } - Ok(()) -} - fn qemu_img(profile: Profile, args: &[&std::ffi::OsStr]) -> Result<()> { let img = install::qemu_img(profile)?; let out = Command::new(&img) @@ -529,7 +500,7 @@ fn make_q35( "img" } ); - copy_file(src, &dir.join(&name))?; + copy::file(src, &dir.join(&name), progress)?; (PathBuf::from(name), format) } }; @@ -537,8 +508,8 @@ fn make_q35( if let Some(src) = &spec.opencore { let (code, vars) = own_firmware(src)?; progress("copying the firmware"); - copy_file(&code, &dir.join("OVMF_CODE.fd"))?; - copy_file(&vars, &dir.join("OVMF_VARS.fd"))?; + copy::file(&code, &dir.join("OVMF_CODE.fd"), progress)?; + copy::file(&vars, &dir.join("OVMF_VARS.fd"), progress)?; } // A read-only source's copy is read-only too; the variables are written. let _ = make_writable(&dir.join("OVMF_VARS.fd")); @@ -589,17 +560,14 @@ fn import_disk( Ok(match mode { ImportMode::InPlace => (src, format), ImportMode::Copy => { - progress(&format!( - "copying {} (a reflink or clone where the file system can)", - file_name(&src) - )); + progress(&format!("copying {}", file_name(&src))); let ext = if format == ImageFormat::Qcow2 { "qcow2" } else { "img" }; let name = format!("{stem}.{ext}"); - copy_file(&src, &dir.join(&name))?; + copy::file(&src, &dir.join(&name), progress)?; let _ = make_writable(&dir.join(&name)); (PathBuf::from(name), format) } diff --git a/crates/reims-ctl/src/main.rs b/crates/reims-ctl/src/main.rs index 542142f33..f821b97f2 100644 --- a/crates/reims-ctl/src/main.rs +++ b/crates/reims-ctl/src/main.rs @@ -3,6 +3,7 @@ //! interface. mod cli; +mod copy; mod create; mod form; mod gpu; diff --git a/crates/reims-ctl/src/reims_util.rs b/crates/reims-ctl/src/reims_util.rs index 4d496ddfc..41456ae16 100644 --- a/crates/reims-ctl/src/reims_util.rs +++ b/crates/reims-ctl/src/reims_util.rs @@ -455,7 +455,7 @@ fn lower_first(s: &str) -> String { } /// "6 MB", "1.1 GB". -fn size(bytes: u64) -> String { +pub(crate) fn size(bytes: u64) -> String { if bytes < 1_000_000_000 { format!("{} MB", bytes.div_ceil(1_000_000)) } else { diff --git a/crates/reims-ctl/src/tui.rs b/crates/reims-ctl/src/tui.rs index 2c1d55d66..5f5c45ef7 100644 --- a/crates/reims-ctl/src/tui.rs +++ b/crates/reims-ctl/src/tui.rs @@ -1473,7 +1473,7 @@ impl App { Field::path("installer", "Installer image", "", "An installer to boot (Tab completes): a raw image, such as a recovery image's BaseSystem.img, or a DMG, converted to a raw image in the VM's directory. Eject it once macOS is installed (e).").show_if("source", &["installer"]), Field::text("disk_size", "Disk size", "128G", "The new disk's size; it takes only what the guest writes.").show_if("source", &["download", "installer"]), Field::path("disk_path", "Disk image", "", "A qcow2 or raw image (Tab completes).").show_if("source", &["disk"]), - Field::choice("disk_mode", "Use the disk by", opts(&[("copy", "Copying it (instant where the file system reflinks)"), ("in-place", "Using it in place")]), "copy", "A copy leaves the image as it was; in place, the VM writes the image itself.") + Field::choice("disk_mode", "Use the disk by", opts(&[("copy", "Copying it (instant where the file system reflinks)"), ("in-place", "Using it in place")]), "copy", "A copy leaves the image as it was; in place, the VM writes the image itself. A copy is instant where the image and the VM's directory are on one file system that makes reflinks, such as btrfs or XFS; else it is a full copy, which says so, with its size, before it starts.") .show_if("source", &["disk"]), Field::path("opencore", "OpenCore image", "", "Empty makes one for this VM, with OVMF, presenting the Mac of the image beside an existing disk (opencore.qcow2, as a VM's directory holds them), unless the disk is copied from a VM reims-ctl has, else a Mac identity of its own. Or an OpenCore image of yours to copy, with OVMF_CODE.fd and OVMF_VARS.fd beside it, such as the one a disk of macOS booted from, which keeps its Mac's identity.") .placeholder("made for this VM"),