diff --git a/crates/reims-ctl/src/cli.rs b/crates/reims-ctl/src/cli.rs index 7a724e056..8f44cebb9 100644 --- a/crates/reims-ctl/src/cli.rs +++ b/crates/reims-ctl/src/cli.rs @@ -126,6 +126,7 @@ pub enum Cmd { /// Zip a VM's logs, settings and the host's details into Downloads, for a bug report Report { name: String }, /// Update reims-ctl and its QEMU from the checkout it was installed from + #[command(after_help = UPDATE_HELP)] Update { /// Switch the checkout to this channel first; later updates stay on it #[arg(long, value_enum)] @@ -172,11 +173,23 @@ go to the guest as a US keyboard's and a tablet's. Ctrl-] disconnects; the VM keeps running. Alt+key is Cmd+key. The Cmd, Opt, Ctrl and Shift \ buttons on the top row hold that key for the next key or click."; +const UPDATE_HELP: &str = "\ +After an update, the new reims-ctl's first run (its restart from the interface, or the next \ +command) updates the VMs an older reims-ctl made, once, with a line for each VM. An x86-64 VM \ +whose settings name no graphics, as those an older reims-ctl made on apple-gfx do, moves to \ +reims-vgpu's own GPU device if the macOS on its disk runs its drivers (macOS 26.4 or later), and \ +stays on apple-gfx if not; the choice is saved in its settings. Its OpenCore image is made again \ +for it, presenting the same Mac and without the ported drivers older images held, and the old \ +image is kept beside it as .pre-migration-1. A VM that is running then is updated at its \ +next start. One that can't be updated stays as it was, and its line says why. A VM whose settings \ +name graphics keeps them."; + const UPDATE_OPENCORE_HELP: &str = "\ The new image is made for the VM's graphics. On reims-vgpu it holds the macOS drivers of \ -reims-vgpu's own GPU device that this reims-ctl carries, which an image made for apple-gfx, or by \ -an older reims-ctl, lacks or holds other builds of: make it again after an update of reims-ctl, as \ -reims-ctl start warns. A change of graphics with reims-ctl set or the interface's edit form makes it \ +reims-vgpu's own GPU device that this reims-ctl carries. A start makes the image again where it \ +holds other builds of them, as one an older reims-ctl made does after an update of reims-ctl; an \ +image that lacks them, as one made for apple-gfx does, stays as it is, which reims-ctl start warns \ +of: make it again here. A change of graphics with reims-ctl set or the interface's edit form makes it \ again where the VM is stopped, and a start on other graphics than reims-vgpu makes one without its \ drivers where the image holds them. An image an older reims-util made also lacks what a newer one's \ carries, such as ReimsVgpu.kext, which macOS 26 needs on apple-gfx for a display wider \ @@ -450,6 +463,15 @@ pub fn main(cli: Cli) -> Result { None | Some(Cmd::Tui) => return crate::tui::run().map(|_| 0), Some(c) => c, }; + // The first run after an update brings the VMs an older reims-ctl made up to date, telling + // of it on stderr, so a command's output stays as it is; reims-ctl's own commands, which the + // installer and reims-ctl run, leave it to the user's. + if !matches!( + cmd, + Cmd::VulkanProbe | Cmd::VzInstall { .. } | Cmd::VzLatest | Cmd::RecordInstall { .. } + ) { + crate::migrate::run(&mut |s| eprintln!("{s}")); + } match cmd { Cmd::List { json } => list(json)?, Cmd::Create(a) => create_cmd(*a, host)?, diff --git a/crates/reims-ctl/src/macos.rs b/crates/reims-ctl/src/macos.rs index 4c2269533..9ce76ed0f 100644 --- a/crates/reims-ctl/src/macos.rs +++ b/crates/reims-ctl/src/macos.rs @@ -110,7 +110,7 @@ pub fn graphics_for(found: &[Macos]) -> Option { /// Why reims-vgpu's device has no driver on `m`, a macOS its kexts don't load on: "older than /// macOS 26.4, the first release reims-vgpu's macOS drivers run on". -fn too_old_or_new(m: &Macos) -> String { +pub fn too_old_or_new(m: &Macos) -> String { let (min, max) = prebuilt::bounds().unwrap_or(((0, 0), (u32::MAX, u32::MAX))); match m.darwin() { Some(d) if d > max => format!( diff --git a/crates/reims-ctl/src/main.rs b/crates/reims-ctl/src/main.rs index e3b2bcc60..eb9538be9 100644 --- a/crates/reims-ctl/src/main.rs +++ b/crates/reims-ctl/src/main.rs @@ -10,6 +10,7 @@ mod host; mod install; mod logs; mod macos; +mod migrate; mod opencore; mod paths; mod prebuilt; diff --git a/crates/reims-ctl/src/migrate.rs b/crates/reims-ctl/src/migrate.rs new file mode 100644 index 000000000..aab3ff4e7 --- /dev/null +++ b/crates/reims-ctl/src/migrate.rs @@ -0,0 +1,621 @@ +//! What an update of reims-ctl changes in the VMs an older one made: each migration runs once, at +//! the first run of the new reims-ctl (the restart after `update`, or any later command), on every +//! VM it is for that is stopped then; a VM running then gets it at its next start +//! ([`at_start`]). Each change is told in one line a VM, and a VM it can't change stays as it was, +//! told why and how to change it by hand. +//! +//! The record is `migrations.toml` in the config directory: `done`, the last migration run, and +//! `deferred`, the directories of the VMs that were running then. A lock beside it, +//! `migrations.lock`, keeps two reims-ctl starting at once from migrating a VM twice. +//! +//! Migration 1 is for the x86-64 VMs a reims-ctl from before reims-vgpu's own GPU device made: +//! their settings name no graphics, their OpenCore image has no kexts for that device, and may +//! hold the ported drivers images no longer carry. Each moves to reims-vgpu's own device where +//! the macOS its disk holds runs the device's drivers, as a start would choose +//! ([`crate::macos::graphics_for`]), and stays on apple-gfx otherwise; its image is made again for +//! that, presenting the same Mac ([`crate::opencore::renew`]), the old one kept beside it as +//! `.pre-migration-1`. A VM whose settings name graphics had them set by its user, or by +//! a reims-ctl that knew of the device, and keeps them. + +use crate::macos::{self, Macos}; +use crate::opencore::{self, Config}; +use crate::vm::{Graphics, Registry, Vm}; +use crate::{host::Profile, paths, runtime}; +use anyhow::{Context, Result}; +use serde::{Deserialize, Serialize}; +use std::fs::File; +use std::os::fd::AsRawFd; +use std::path::{Path, PathBuf}; + +/// The migrations this reims-ctl carries: 1 to this. +pub const CURRENT: u32 = 1; + +#[derive(Debug, Default, PartialEq, Serialize, Deserialize)] +struct State { + /// The last migration run. + #[serde(default)] + done: u32, + /// The VMs that were running then, by their directories. + #[serde(default)] + deferred: Vec, +} + +fn state_file() -> PathBuf { + paths::config_dir().join("migrations.toml") +} + +fn load() -> State { + std::fs::read_to_string(state_file()) + .ok() + .and_then(|t| toml::from_str(&t).ok()) + .unwrap_or_default() +} + +fn save(state: &State) -> Result<()> { + let file = state_file(); + std::fs::create_dir_all(file.parent().unwrap())?; + let tmp = file.with_extension("toml.tmp"); + std::fs::write(&tmp, toml::to_string_pretty(state)?)?; + std::fs::rename(&tmp, &file).with_context(|| format!("write {}", file.display())) +} + +/// The migrations' lock, held until it drops; None where it can't be taken, which migrates +/// nothing this run. +fn lock() -> Option { + let file = paths::config_dir().join("migrations.lock"); + std::fs::create_dir_all(file.parent()?).ok()?; + let f = File::create(&file).ok()?; + // SAFETY: flock on a descriptor this File owns. + (unsafe { libc::flock(f.as_raw_fd(), libc::LOCK_EX) } == 0).then_some(f) +} + +/// What migration 1 does to a VM. +#[derive(Debug, PartialEq)] +enum Plan { + /// Nothing: an arm64 VM, or one whose settings name graphics. + Skip, + /// It runs: at its next start. + Defer, + /// Its disk can't be read, so its macOS is not known: it stays as it was. + Unknown(String), + /// Its image made again for its macOS: on the graphics saved in its settings, or, where its + /// disk holds no macOS yet, on the default, with none saved; the macOS that decided. + Image(Option, Option), +} + +/// Migration 1's plan for `vm`, `running` or not, its disk's macOS read by `found`. +fn plan(vm: &Vm, running: bool, found: impl FnOnce() -> Result>) -> Plan { + if vm.config.profile != Profile::Q35X86_64 || vm.config.graphics.is_some() { + return Plan::Skip; + } + if running { + return Plan::Defer; + } + match found() { + Err(e) => Plan::Unknown(format!("{e:#}")), + Ok(found) => { + let graphics = macos::graphics_for(&found); + // The one its graphics follow: on apple-gfx, the first the drivers don't run on. + let decided = found + .iter() + .find(|m| { + graphics == Some(Graphics::AppleGfx) + && m.darwin().and_then(crate::prebuilt::loads_on) == Some(false) + }) + .or(found.first()) + .cloned(); + Plan::Image(graphics, decided) + } + } +} + +/// Runs the migrations this reims-ctl carries that have not run, on every VM in the registry, +/// telling `say` what each did. Where none has run yet and there are VMs, the first line says the +/// update worked. A record that can't be written is told, and the migrations run again next time. +pub fn run(say: &mut dyn FnMut(&str)) { + if load().done >= CURRENT { + return; + } + let Some(_lock) = lock() else { return }; + let mut state = load(); + if state.done >= CURRENT { + return; + } + let registry = match Registry::load() { + Ok(r) => r, + Err(e) => return say(&format!("reims-ctl's update of its VMs waits: {e:#}")), + }; + if !registry.vms.is_empty() { + say("reims-ctl is updated. What the update changes in the VMs an older one made:"); + } + let mut told = false; + for e in ®istry.vms { + let mut vm = match Vm::load(&e.dir) { + Ok(vm) => vm, + Err(err) => { + say(&format!("{}: left as it was: {err:#}", e.name)); + told = true; + continue; + } + }; + let p = plan(&vm, runtime::running(&vm), || { + macos::on_disk(&vm.disk(), vm.config.disk_format) + }); + if p == Plan::Defer { + state.deferred.push(vm.dir.clone()); + } + if let Some(line) = carry_out(&mut vm, p) { + say(&line); + told = true; + } + } + if !registry.vms.is_empty() && !told { + say("nothing: each VM is as this reims-ctl makes them."); + } + state.done = CURRENT; + if let Err(e) = save(&state) { + say(&format!( + "reims-ctl couldn't record its update of the VMs ({e:#}): it runs again next time" + )); + } +} + +/// At a start of a stopped VM, a migration that waited while it ran, now, telling `progress`. +pub fn at_start(vm: &mut Vm, progress: &mut dyn FnMut(&str)) { + if !load().deferred.iter().any(|d| same_dir(d, &vm.dir)) { + return; + } + let Some(_lock) = lock() else { return }; + let mut state = load(); + let before = state.deferred.len(); + state.deferred.retain(|d| !same_dir(d, &vm.dir)); + if state.deferred.len() == before || save(&state).is_err() { + return; + } + let p = plan(vm, false, || { + macos::on_disk(&vm.disk(), vm.config.disk_format) + }); + if let Some(line) = carry_out(vm, p) { + let name = format!("{}: ", vm.name()); + progress(line.strip_prefix(&name).unwrap_or(&line)); + } +} + +fn same_dir(a: &Path, b: &Path) -> bool { + a == b || std::fs::canonicalize(a).ok() == std::fs::canonicalize(b).ok() +} + +/// Carries out `plan` on `vm`: the line telling what happened, or None where nothing did. +fn carry_out(vm: &mut Vm, plan: Plan) -> Option { + let name = vm.name().to_string(); + let manual = format!( + "reims-ctl set {name} --graphics reims-vgpu (for macOS 26.4 or later) or apple-gfx \ + makes its OpenCore image for one" + ); + match plan { + Plan::Skip => None, + Plan::Defer => Some(format!( + "{name} is running: it is updated at its next start, which makes its OpenCore image \ + again" + )), + Plan::Unknown(why) => Some(format!( + "{name}: left as it was: reims-ctl can't tell which macOS its disk holds ({why}); \ + {manual}" + )), + Plan::Image(graphics, decided) => Some(match image(vm, graphics, decided.as_ref()) { + Ok(line) => format!("{name}: {line}"), + Err(e) => format!("{name}: left as it was: {e:#}; {manual}"), + }), + } +} + +/// Saves `graphics` in `vm`'s settings and makes its OpenCore image again for them, keeping the +/// old image beside it; what changed, or an error with the VM as it was. +fn image(vm: &mut Vm, graphics: Option, decided: Option<&Macos>) -> Result { + let q = vm.config.q35.clone().context("it boots no OpenCore")?; + let old = vm.path(&q.opencore); + let before = loaded(&old, q.opencore_format); + // A copy of an image in the VM's directory, which the new one replaces; one elsewhere stays. + let backup = old + .starts_with(&vm.dir) + .then(|| backup_of(&old)) + .flatten() + .filter(|b| !b.exists()); + if let Some(b) = &backup { + std::fs::copy(&old, b).with_context(|| format!("copy its image to {}", b.display()))?; + } + let undo = |vm: &mut Vm, e: anyhow::Error| { + if let Some(b) = &backup { + let _ = std::fs::remove_file(b); + } + if graphics.is_some() + && let Ok(mut now) = Vm::load(&vm.dir) + { + now.config.graphics = None; + if now.save().is_ok() { + *vm = now; + } + } + e + }; + if let Some(g) = graphics { + vm.config.graphics = Some(g); + if let Err(e) = vm.save() { + return Err(undo(vm, e)); + } + } + let made = match opencore::renew(vm, None, &mut |_| {}) { + Ok(s) => s, + Err(e) => return Err(undo(vm, e.context("a new OpenCore image couldn't be made"))), + }; + let q = vm.config.q35.clone().context("it boots no OpenCore")?; + let after = loaded(&vm.path(&q.opencore), q.opencore_format); + let mut line = match (graphics, decided) { + (Some(Graphics::ReimsVgpu), Some(m)) => { + format!( + "now on reims-vgpu's own GPU device, whose drivers {} runs", + m.describe() + ) + } + (Some(Graphics::AppleGfx), Some(m)) => format!( + "stays on apple-gfx: its {} is {}", + m.describe(), + macos::too_old_or_new(m) + ), + _ => "on reims-vgpu's own GPU device, the default, as its disk holds no macOS yet".into(), + }; + line.push_str("; "); + line.push_str( + made.strip_prefix(&format!("{}: ", vm.name())) + .unwrap_or(&made), + ); + let dropped: Vec<&str> = before + .iter() + .filter(|k| !after.contains(k)) + .map(String::as_str) + .collect(); + let added: Vec<&str> = after + .iter() + .filter(|k| !before.contains(k)) + .map(String::as_str) + .collect(); + if !dropped.is_empty() { + line.push_str(&format!(", without {}", some(&dropped))); + } + if !added.is_empty() { + line.push_str(&format!( + "{} with {}", + if dropped.is_empty() { "," } else { " and" }, + some(&added) + )); + } + if let Some(b) = &backup { + line.push_str(&format!( + "; the old image is kept as {}", + b.file_name().unwrap_or_default().to_string_lossy() + )); + } + Ok(line) +} + +/// Up to three kexts by name; more as their count and the first two. +fn some(kexts: &[&str]) -> String { + match kexts { + [_, _, _, _, ..] => format!( + "{} kexts ({}, {} and {} more)", + kexts.len(), + kexts[0], + kexts[1], + kexts.len() - 2 + ), + _ => kexts.join(", "), + } +} + +/// The kexts an image's OpenCore loads; none where it can't be read. +fn loaded(image: &Path, format: crate::vm::ImageFormat) -> Vec { + Config::read(image, format) + .map(|c| c.loaded_kexts().iter().map(|k| k.to_string()).collect()) + .unwrap_or_default() +} + +/// Where migration 1 keeps a VM's old image: beside it, `.pre-migration-1` after its name. +fn backup_of(image: &Path) -> Option { + let name = image.file_name()?.to_str()?; + Some(image.with_file_name(format!("{name}.pre-migration-{CURRENT}"))) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::opencore::tests::{image as oc_image, plist, qcow2}; + use std::os::unix::fs::PermissionsExt; + + fn macos(version: &str, build: &str) -> Macos { + Macos { + version: version.into(), + build: Some(build.into()), + } + } + + fn entry(bundle: &str) -> String { + format!( + "BundlePath{bundle}\ + Enabled" + ) + } + + /// A VM in `dir` of `profile`, with `graphics` where Some, whose image loads `kexts`. + fn vm(dir: &Path, profile: &str, graphics: Option<&str>, kexts: &str) -> Vm { + std::fs::create_dir_all(dir).unwrap(); + std::fs::write(dir.join("opencore.img"), oc_image(plist(kexts).as_bytes())).unwrap(); + let graphics = graphics + .map(|g| format!("graphics = \"{g}\"")) + .unwrap_or_default(); + let config = format!( + r#" + name = "{name}" + profile = "{profile}" + cpus = 2 + memory_mib = 4096 + disk = "disk.img" + disk_format = "raw" + {graphics} + [q35] + opencore = "opencore.img" + opencore_format = "raw" + firmware_code = "OVMF_CODE.fd" + firmware_vars = "OVMF_VARS.fd" + "#, + name = dir.file_name().unwrap().to_string_lossy() + ); + std::fs::write(dir.join(crate::vm::CONFIG_FILE), config).unwrap(); + Vm::load(dir).unwrap() + } + + /// A stand-in reims-util that makes each image it is asked for as `made`, recording its + /// arguments in `args`; one that fails where `fails`. + fn util(env: &crate::testenv::Env, made: &Path, args: &Path, fails: bool) { + let util = env.root.join("reims-util"); + let script = if fails { + "#!/bin/sh\necho 'no room' >&2\nexit 1\n".to_string() + } else { + format!( + "#!/bin/sh\nprintf '%s\\n' \"$@\" > '{args}'\n\ + while [ \"$1\" != -o ]; do shift; done\ncp '{made}' \"$2\"\n\ + echo '{{\"event\":\"done\",\"result\":{{}}}}'\n", + args = args.display(), + made = made.display(), + ) + }; + std::fs::write(&util, script).unwrap(); + std::fs::set_permissions(&util, std::fs::Permissions::from_mode(0o755)).unwrap(); + env.set("REIMS_CTL_UTIL", &util); + } + + /// Migration 1 is for an x86-64 VM whose settings name no graphics, stopped: on the graphics + /// its macOS runs, the test set's kexts loading on Darwin 25.4 and later (macOS 26.4); an + /// arm64 VM, or one whose settings name graphics, as its user chose, is left be. + #[test] + fn migration_1_is_for_x86_64_vms_with_no_graphics_chosen() { + let env = crate::testenv::Env::new("migrate-plan"); + let new = || Ok(vec![macos("26.7.2", "25G332")]); + let old = || Ok(vec![macos("15.7.2", "24G325")]); + let v = vm(&env.root.join("a"), "q35-x86_64", None, ""); + assert_eq!( + plan(&v, false, new), + Plan::Image(Some(Graphics::ReimsVgpu), Some(macos("26.7.2", "25G332"))) + ); + assert_eq!( + plan(&v, false, old), + Plan::Image(Some(Graphics::AppleGfx), Some(macos("15.7.2", "24G325"))) + ); + // A disk with an old and a new macOS: apple-gfx, for the old one. + assert_eq!( + plan(&v, false, || Ok(vec![ + macos("26.7.2", "25G332"), + macos("15.7.2", "24G325") + ])), + Plan::Image(Some(Graphics::AppleGfx), Some(macos("15.7.2", "24G325"))) + ); + assert_eq!(plan(&v, false, || Ok(vec![])), Plan::Image(None, None)); + assert!(matches!( + plan(&v, false, || anyhow::bail!("an encrypted volume")), + Plan::Unknown(why) if why.contains("encrypted") + )); + assert_eq!(plan(&v, true, new), Plan::Defer); + for g in ["apple-gfx", "reims-vgpu", "vmware-svga"] { + let v = vm(&env.root.join(g), "q35-x86_64", Some(g), ""); + assert_eq!(plan(&v, false, new), Plan::Skip, "{g}"); + } + let v = vm(&env.root.join("arm"), "vmapple-arm64", None, ""); + assert_eq!(plan(&v, false, new), Plan::Skip); + } + + /// A migration makes the image again for the graphics it saves, the old image kept beside + /// it, and tells what changed in one line; where the image can't be made, the VM's settings + /// and image stay as they were, and the line says why and what to run. + #[test] + fn migration_1_makes_the_image_again_or_leaves_the_vm_as_it_was() { + let env = crate::testenv::Env::new("migrate-image"); + let made = env.root.join("made.img"); + let args = env.root.join("args"); + // What reims-util makes: Lilu and the set's kexts (by name; the stand-in copies them). + let fresh = entry("Lilu.kext") + &entry("A.kext") + &entry("B.kext"); + std::fs::write(&made, qcow2(&oc_image(plist(&fresh).as_bytes()))).unwrap(); + util(&env, &made, &args, false); + let ported = entry("Lilu.kext") + &entry("AppleParavirtGPU.kext"); + let dir = env.root.join("old26"); + let mut v = vm(&dir, "q35-x86_64", None, &ported); + let old_bytes = std::fs::read(dir.join("opencore.img")).unwrap(); + let line = carry_out( + &mut v, + Plan::Image(Some(Graphics::ReimsVgpu), Some(macos("26.7.2", "25G332"))), + ) + .unwrap(); + assert!( + line.starts_with("old26: now on reims-vgpu's own GPU device"), + "{line}" + ); + assert!(line.contains("macOS 26.7.2 (25G332)"), "{line}"); + assert!( + line.contains("without AppleParavirtGPU.kext and with A.kext, B.kext"), + "{line}" + ); + assert!( + line.contains("kept as opencore.img.pre-migration-1"), + "{line}" + ); + assert!( + std::fs::read_to_string(&args) + .unwrap() + .contains("--add-kext") + ); + let saved = Vm::load(&dir).unwrap(); + assert_eq!(saved.config.graphics, Some(Graphics::ReimsVgpu)); + assert_eq!( + saved.config.q35.as_ref().unwrap().opencore, + Path::new("opencore.qcow2") + ); + assert_eq!( + std::fs::read(dir.join("opencore.img.pre-migration-1")).unwrap(), + old_bytes + ); + + // On apple-gfx, an image without the set's kexts, as reims-util makes for it. + std::fs::write( + &made, + qcow2(&oc_image(plist(&entry("Lilu.kext")).as_bytes())), + ) + .unwrap(); + let dir = env.root.join("old15"); + let mut v = vm(&dir, "q35-x86_64", None, &ported); + let line = carry_out( + &mut v, + Plan::Image(Some(Graphics::AppleGfx), Some(macos("15.7.2", "24G325"))), + ) + .unwrap(); + assert!( + line.starts_with("old15: stays on apple-gfx: its macOS 15.7.2"), + "{line}" + ); + assert!(line.contains("older than macOS 26.4"), "{line}"); + assert!(line.contains("without AppleParavirtGPU.kext"), "{line}"); + assert!( + !std::fs::read_to_string(&args) + .unwrap() + .contains("--add-kext") + ); + assert_eq!( + Vm::load(&dir).unwrap().config.graphics, + Some(Graphics::AppleGfx) + ); + + // reims-util fails: the VM as it was. + util(&env, &made, &args, true); + let dir = env.root.join("stuck"); + let mut v = vm(&dir, "q35-x86_64", None, &ported); + let before = std::fs::read(dir.join("opencore.img")).unwrap(); + let line = carry_out( + &mut v, + Plan::Image(Some(Graphics::ReimsVgpu), Some(macos("26.7.2", "25G332"))), + ) + .unwrap(); + assert!(line.starts_with("stuck: left as it was:"), "{line}"); + assert!(line.contains("reims-ctl set stuck --graphics"), "{line}"); + let saved = Vm::load(&dir).unwrap(); + assert_eq!(saved.config.graphics, None); + assert_eq!( + saved.config.q35.as_ref().unwrap().opencore, + Path::new("opencore.img") + ); + assert_eq!(std::fs::read(dir.join("opencore.img")).unwrap(), before); + assert!(!dir.join("opencore.img.pre-migration-1").exists()); + } + + #[test] + fn a_line_names_up_to_three_kexts() { + assert_eq!(some(&["A.kext"]), "A.kext"); + assert_eq!( + some(&["A.kext", "B.kext", "C.kext"]), + "A.kext, B.kext, C.kext" + ); + assert_eq!( + some(&["A.kext", "B.kext", "C.kext", "D.kext", "E.kext"]), + "5 kexts (A.kext, B.kext and 3 more)" + ); + } + + /// The first run records the migrations, and later ones do nothing; a VM running then waits + /// for its next start, which migrates it once. + #[test] + fn migrations_run_once_and_a_running_vm_waits_for_its_start() { + let env = crate::testenv::Env::new("migrate-run"); + let made = env.root.join("made.img"); + let args = env.root.join("args"); + let fresh = entry("Lilu.kext") + &entry("A.kext") + &entry("B.kext"); + std::fs::write(&made, qcow2(&oc_image(plist(&fresh).as_bytes()))).unwrap(); + util(&env, &made, &args, false); + // No VMs: recorded, nothing said. + let mut said = Vec::new(); + run(&mut |s| said.push(s.to_string())); + assert!(said.is_empty(), "{said:?}"); + assert_eq!(load().done, CURRENT); + let _ = std::fs::remove_file(state_file()); + + // Three VMs: two whose settings name no graphics, one of them running, and one its user + // set to apple-gfx. + let mut reg = Registry::default(); + for (name, graphics) in [ + ("idle", None), + ("busy", None), + ("chosen", Some("apple-gfx")), + ] { + let dir = env.root.join(name); + vm(&dir, "q35-x86_64", graphics, &entry("Lilu.kext")); + reg.add(name, &dir).unwrap(); + } + reg.save().unwrap(); + // A process whose command line names the pidfile, as QEMU's does (runtime::pid_at). + let pidfile = crate::vm::pidfile_in(&env.root.join("busy")); + let mut qemu = std::process::Command::new("sh") + .args(["-c", "sleep 30"]) + .arg(&pidfile) + .spawn() + .unwrap(); + std::fs::write(&pidfile, qemu.id().to_string()).unwrap(); + let mut said = Vec::new(); + run(&mut |s| said.push(s.to_string())); + assert!(said[0].starts_with("reims-ctl is updated"), "{said:?}"); + assert!( + said.iter().any(|s| s.starts_with("busy is running")), + "{said:?}" + ); + // The idle one's disk can't be read here (there is none): left as it was. + assert!( + said.iter().any(|s| s.starts_with("idle: left as it was")), + "{said:?}" + ); + assert!(!said.iter().any(|s| s.starts_with("chosen")), "{said:?}"); + let state = load(); + assert_eq!(state.done, CURRENT); + assert_eq!(state.deferred, vec![env.root.join("busy")]); + let mut said = Vec::new(); + run(&mut |s| said.push(s.to_string())); + assert!(said.is_empty(), "{said:?}"); + + // Stopped, its start migrates it, and only once. + let _ = qemu.kill(); + let _ = qemu.wait(); + std::fs::remove_file(&pidfile).unwrap(); + let mut v = Vm::load(&env.root.join("busy")).unwrap(); + let mut said = Vec::new(); + at_start(&mut v, &mut |s| said.push(s.to_string())); + assert_eq!(said.len(), 1, "{said:?}"); + assert!(said[0].starts_with("left as it was"), "{said:?}"); + assert!(load().deferred.is_empty()); + let mut said = Vec::new(); + at_start(&mut v, &mut |s| said.push(s.to_string())); + assert!(said.is_empty(), "{said:?}"); + } +} diff --git a/crates/reims-ctl/src/opencore.rs b/crates/reims-ctl/src/opencore.rs index 7e47e3762..2cd9e8dd5 100644 --- a/crates/reims-ctl/src/opencore.rs +++ b/crates/reims-ctl/src/opencore.rs @@ -188,6 +188,27 @@ fn guest_kexts( } } +/// How a VM's OpenCore image holds the guest's kexts this reims-ctl carries; None where the +/// image cannot be read, an error where reims-ctl carries no set. +fn image_guest_kexts(vm: &Vm) -> Option> { + let q = vm.config.q35.as_ref()?; + let image = vm.path(&q.opencore); + let config = Config::read(&image, q.opencore_format).ok()?; + let set = match prebuilt::set() { + Ok(s) => s, + Err(e) => return Some(Err(e)), + }; + let mut executable = |k: &Kext| { + let file = format!("EFI/OC/Kexts/{}/{}", k.bundle, k.executable?); + read_file(&image, q.opencore_format, &file).ok()? + }; + Some(Ok(guest_kexts( + set, + &config.loaded_kexts(), + &mut executable, + ))) +} + /// What to tell of a VM on reims-vgpu's own GPU device whose OpenCore image lacks the guest's /// kexts this reims-ctl carries, or holds other builds of them; None where it holds them, the VM /// is on another device, or the image cannot be read. @@ -195,30 +216,20 @@ pub fn missing_guest_kexts(vm: &Vm) -> Option { if vm.config.graphics() != Graphics::ReimsVgpu { return None; } - let q = vm.config.q35.as_ref()?; - let image = vm.path(&q.opencore); - let config = Config::read(&image, q.opencore_format).ok()?; - let set = match prebuilt::set() { - Ok(s) => s, - Err(e) => return Some(format!("{e:#}")), - }; - let mut executable = |k: &Kext| { - let file = format!("EFI/OC/Kexts/{}/{}", k.bundle, k.executable?); - read_file(&image, q.opencore_format, &file).ok()? - }; let fix = format!( "To make it a new image that has this reims-ctl's, presenting the same Mac, press U in \ reims-ctl or run reims-ctl update-opencore {}.", vm.name() ); - match guest_kexts(set, &config.loaded_kexts(), &mut executable) { - GuestKexts::Held => None, - GuestKexts::Lacks(b) => Some(format!( + match image_guest_kexts(vm)? { + Err(e) => Some(format!("{e:#}")), + Ok(GuestKexts::Held) => None, + Ok(GuestKexts::Lacks(b)) => Some(format!( "Its OpenCore image lacks reims-vgpu's macOS drivers ({}), without which macOS has \ no driver for its GPU device. {fix}", b.join(", ") )), - GuestKexts::Other(b) => Some(format!( + Ok(GuestKexts::Other(b)) => Some(format!( "Its OpenCore image holds other builds of reims-vgpu's macOS drivers ({}) than this \ reims-ctl carries, which may not drive its GPU device. {fix}", b.join(", ") @@ -226,6 +237,15 @@ pub fn missing_guest_kexts(vm: &Vm) -> Option { } } +/// Whether a VM on reims-vgpu's own GPU device has an OpenCore image that loads each of the +/// guest's kexts, but other builds of some than this reims-ctl carries, or out of the set's +/// order: an image an older reims-ctl made, which a start makes again ([`crate::runtime::prepare`]) +/// so the guest runs the kexts that came with this reims-ctl. +pub fn holds_other_guest_kexts(vm: &Vm) -> bool { + vm.config.graphics() == Graphics::ReimsVgpu + && matches!(image_guest_kexts(vm), Some(Ok(GuestKexts::Other(_)))) +} + /// Whether a VM's OpenCore image has OpenCore load any of the guest's kexts for reims-vgpu's own /// device; None where the image can't be read, or reims-ctl carries no set. fn loads_guest_kexts(vm: &Vm) -> Option { @@ -680,7 +700,7 @@ fn be64(b: &[u8], o: usize) -> u64 { } #[cfg(test)] -mod tests { +pub(crate) mod tests { use super::*; /// A directory entry of `name`, an 8.3 name, with no long name before it. @@ -741,7 +761,7 @@ mod tests { } /// A config.plist, Kernel > Add holding `kexts`. - fn plist(kexts: &str) -> String { + pub(crate) fn plist(kexts: &str) -> String { format!( r#" @@ -763,7 +783,7 @@ mod tests { /// A raw OpenCore image laid out as reims-util's: a GPT whose one partition, the EFI system /// partition, is FAT32, a sector a cluster, holding EFI/OC/`config_plist`. - fn image(config_plist: &[u8]) -> Vec { + pub(crate) fn image(config_plist: &[u8]) -> Vec { const ESP: usize = 64 * 512; let put = |img: &mut Vec, at: usize, bytes: &[u8]| { img[at..at + bytes.len()].copy_from_slice(bytes) @@ -802,6 +822,43 @@ mod tests { img } + /// `raw` as a qcow2 image, the format reims-util writes: version 2, clusters of 512 bytes, + /// one L1 table, then the L2 tables, then each cluster holding a byte other than zero; a + /// cluster of zeros is left unallocated. + pub(crate) fn qcow2(raw: &[u8]) -> Vec { + const BITS: u32 = 9; + const CLUSTER: usize = 1 << BITS; + const PER_TABLE: usize = CLUSTER / 8; + let clusters = raw.len().div_ceil(CLUSTER); + let tables = clusters.div_ceil(PER_TABLE).max(1); + let l1_clusters = (tables * 8).div_ceil(CLUSTER); + let l2_at = |t: usize| (1 + l1_clusters + t) * CLUSTER; + let mut img = vec![0u8; l2_at(tables)]; + img[..4].copy_from_slice(b"QFI\xfb"); + img[4..8].copy_from_slice(&2u32.to_be_bytes()); + img[20..24].copy_from_slice(&BITS.to_be_bytes()); + img[24..32].copy_from_slice(&(raw.len() as u64).to_be_bytes()); + img[36..40].copy_from_slice(&(tables as u32).to_be_bytes()); + img[40..48].copy_from_slice(&(CLUSTER as u64).to_be_bytes()); + // Bit 63 of an entry: the cluster is used once, as QEMU marks the clusters it writes. + for t in 0..tables { + let e = l2_at(t) as u64 | 1 << 63; + img[CLUSTER + t * 8..CLUSTER + t * 8 + 8].copy_from_slice(&e.to_be_bytes()); + } + for (c, data) in raw.chunks(CLUSTER).enumerate() { + if data.iter().all(|&b| b == 0) { + continue; + } + let at = img.len(); + img.extend_from_slice(data); + img.resize(at + CLUSTER, 0); + let e = (at as u64 | 1 << 63).to_be_bytes(); + let slot = l2_at(c / PER_TABLE) + c % PER_TABLE * 8; + img[slot..slot + 8].copy_from_slice(&e); + } + img + } + #[test] fn an_image_reads_as_reims_util_lays_it_out() { let d = std::env::temp_dir().join(format!("reims-ctl-oc-{}", std::process::id())); @@ -810,6 +867,10 @@ mod tests { std::fs::write(&p, image(plist("").as_bytes())).unwrap(); let c = Config::read(&p, ImageFormat::Raw).unwrap(); assert_eq!(c.identity().unwrap().serial, "C02D40VEPN5T"); + let p = d.join("opencore.qcow2"); + std::fs::write(&p, qcow2(&image(plist("").as_bytes()))).unwrap(); + let c = Config::read(&p, ImageFormat::Qcow2).unwrap(); + assert_eq!(c.identity().unwrap().serial, "C02D40VEPN5T"); std::fs::remove_dir_all(&d).unwrap(); } @@ -1080,7 +1141,7 @@ mod tests { }; let lilu = entry("Lilu.kext"); let made = env.root.join("made.img"); - std::fs::write(&made, image(plist(&lilu).as_bytes())).unwrap(); + std::fs::write(&made, qcow2(&image(plist(&lilu).as_bytes()))).unwrap(); let args = env.root.join("args"); let util = env.root.join("reims-util"); let script = format!( @@ -1148,6 +1209,75 @@ mod tests { ); } + /// A start of a VM on reims-vgpu whose image loads the guest's kexts in other builds than + /// reims-ctl carries, as one an older reims-ctl made does, makes it a new image with these + /// first; one lacking them stays. + #[test] + fn a_start_makes_an_image_with_the_guest_kexts_carried_for_other_builds() { + use std::os::unix::fs::PermissionsExt; + let env = crate::testenv::Env::new("start-builds"); + let dir = env.root.join("vm"); + std::fs::create_dir_all(&dir).unwrap(); + let entry = |bundle: &str| { + format!( + "BundlePath{bundle}\ + Enabled" + ) + }; + let lilu = entry("Lilu.kext"); + let made = env.root.join("made.img"); + std::fs::write(&made, qcow2(&image(plist(&lilu).as_bytes()))).unwrap(); + let args = env.root.join("args"); + let util = env.root.join("reims-util"); + let script = format!( + "#!/bin/sh\nprintf '%s\\n' \"$@\" > '{args}'\n\ + while [ \"$1\" != -o ]; do shift; done\ncp '{made}' \"$2\"\n\ + echo '{{\"event\":\"done\",\"result\":{{}}}}'\n", + args = args.display(), + made = made.display(), + ); + std::fs::write(&util, script).unwrap(); + std::fs::set_permissions(&util, std::fs::Permissions::from_mode(0o755)).unwrap(); + env.set("REIMS_CTL_UTIL", &util); + let config = r#" + name = "t" + profile = "q35-x86_64" + cpus = 2 + memory_mib = 4096 + disk = "disk.img" + disk_format = "raw" + graphics = "reims-vgpu" + [q35] + opencore = "opencore.img" + opencore_format = "raw" + firmware_code = "OVMF_CODE.fd" + firmware_vars = "OVMF_VARS.fd" + "#; + std::fs::write(dir.join(crate::vm::CONFIG_FILE), config).unwrap(); + // Each kext loaded, in order, but none with the executable reims-ctl carries. + let ours = lilu.clone() + &entry("A.kext") + &entry("B.kext"); + std::fs::write(dir.join("opencore.img"), image(plist(&ours).as_bytes())).unwrap(); + let mut v = Vm::load(&dir).unwrap(); + assert!(holds_other_guest_kexts(&v) && !holds_unused_guest_kexts(&v)); + let mut said = Vec::new(); + let warned = crate::runtime::prepare(&mut v, &mut |s| said.push(s.to_string())); + assert!(warned.is_empty(), "{warned:?}"); + assert!(said.iter().any(|s| s.contains("other builds")), "{said:?}"); + assert!( + std::fs::read_to_string(&args) + .unwrap() + .contains("--add-kext") + ); + let q = v.config.q35.as_ref().unwrap(); + assert_eq!(q.opencore, Path::new("opencore.qcow2")); + std::fs::remove_file(&args).unwrap(); + // Lacking them, as the image the stand-in reims-util made does, it stays. + assert!(!holds_other_guest_kexts(&v)); + let mut said = Vec::new(); + crate::runtime::prepare(&mut v, &mut |s| said.push(s.to_string())); + assert!(said.is_empty() && !args.exists(), "{said:?}"); + } + /// An image holds the guest's kexts where OpenCore loads each, in the set's order, with /// the executable reims-ctl carries; one it does not load is lacking, and one out of order /// or of another build is another. diff --git a/crates/reims-ctl/src/runtime.rs b/crates/reims-ctl/src/runtime.rs index f71500dff..3b58b2474 100644 --- a/crates/reims-ctl/src/runtime.rs +++ b/crates/reims-ctl/src/runtime.rs @@ -568,26 +568,31 @@ fn private_dir(d: &Path) -> Result<()> { } /// What a start of a stopped VM does to its settings and OpenCore image first, before [`start`]: -/// for an x86-64 VM on reims-vgpu, its disk's macOS ([`crate::macos::settle`]), which may save -/// the graphics its settings named none of; then, for one on another device whose image loads -/// reims-vgpu's guest kexts, as an image made for reims-vgpu does after a change of graphics, -/// a new image without them ([`crate::opencore::renew`]). An image reims-vgpu's kexts lack is -/// warned of instead (`warnings`): the image may be one the user gave, which a new one would not -/// carry over. Notes go to `progress`, the new image's with what the kexts left in the guest; -/// warnings are returned, for a start that still runs. +/// an update's change that waited while it ran ([`crate::migrate::at_start`]); for an x86-64 VM +/// on reims-vgpu, its disk's macOS ([`crate::macos::settle`]), which may save +/// the graphics its settings named none of; then a new image ([`crate::opencore::renew`]) for +/// one on another device whose image loads reims-vgpu's guest kexts, as an image made for +/// reims-vgpu does after a change of graphics, without them; and for one on reims-vgpu whose +/// image holds other builds of them, as one an older reims-ctl made does after an update, with +/// this reims-ctl's ([`crate::opencore::holds_other_guest_kexts`]). An image reims-vgpu's kexts +/// lack is warned of instead (`warnings`): the image may be one the user gave, which a new one +/// would not carry over. Notes go to `progress`, the new image's with what the kexts left in the +/// guest; warnings are returned, for a start that still runs. pub fn prepare(vm: &mut Vm, progress: &mut dyn FnMut(&str)) -> Vec { let mut w = Vec::new(); if running(vm) { return w; } + // An update's change that waited while the VM ran (crate::migrate). + crate::migrate::at_start(vm, progress); match crate::macos::settle(vm) { Ok(crate::macos::Settled::Kept) => {} Ok(crate::macos::Settled::Saved(note)) => progress(¬e), Ok(crate::macos::Settled::Warn(s)) => w.push(s), Err(e) => w.push(format!("{e:#}")), } + let name = vm.name().to_string(); if crate::opencore::holds_unused_guest_kexts(vm) { - let name = vm.name().to_string(); let graphics = vm.config.graphics().name(); progress(&format!( "its OpenCore image loads reims-vgpu's macOS drivers, which {graphics} has no use \ @@ -601,6 +606,19 @@ pub fn prepare(vm: &mut Vm, progress: &mut dyn FnMut(&str)) -> Vec { update-opencore {name} makes it" )), } + } else if crate::opencore::holds_other_guest_kexts(vm) { + progress( + "its OpenCore image holds other builds of reims-vgpu's macOS drivers than this \ + reims-ctl carries: making it a new one with these, presenting the same Mac", + ); + match crate::opencore::renew(vm, None, progress) { + Ok(s) => progress(s.strip_prefix(&format!("{name}: ")).unwrap_or(&s)), + Err(e) => w.push(format!( + "{name}'s OpenCore image holds other builds of reims-vgpu's macOS drivers than \ + this reims-ctl carries, and a new one with these couldn't be made ({e:#}): \ + reims-ctl update-opencore {name} makes it" + )), + } } w } diff --git a/crates/reims-ctl/src/tui.rs b/crates/reims-ctl/src/tui.rs index 6c14da687..85b20c19d 100644 --- a/crates/reims-ctl/src/tui.rs +++ b/crates/reims-ctl/src/tui.rs @@ -39,7 +39,19 @@ use std::time::{Duration, Instant}; pub fn run() -> Result<()> { let host = Host::current(); + // The first run after an update brings the VMs an older reims-ctl made up to date: what it + // changed shows first. + let mut updated = Vec::new(); + crate::migrate::run(&mut |s| updated.push(s.to_string())); let mut app = App::new(host)?; + if !updated.is_empty() { + app.overlay = Some(Overlay::Text { + title: "reims-ctl is updated (Esc close)".into(), + lines: updated, + scroll: 0, + kind: TextKind::Help, + }); + } let mut terminal = ratatui::init(); app.kitty_keys = ratatui::crossterm::terminal::supports_keyboard_enhancement().unwrap_or(false); let kitty_keys = app.kitty_keys;