Skip to main content

isothrum_machine/providers/
ready.rs

1//! Whether a provider is ready for a start right now, beyond what detection reads: UTM open and
2//! answering Apple events, and QEMU's system emulator for each CPU a project's machines are built
3//! for. Detection ([`super::detect`]) says a hypervisor is installed; these are asked right before
4//! a start, since they change while the computer runs (UTM quit, an Automation permission turned
5//! off).
6//!
7//! UTM is opened hidden and in the background (`open -g -j`), never with its window in front,
8//! and asked for its machines through `osascript`, as Vagrant's UTM plugin asks it. Every tool
9//! runs through the [`Context`]'s runner.
10
11use std::time::Duration;
12
13use isothrum_runner::{ErrorCode, ProcessSpec, ProviderNeed};
14
15use crate::context::Context;
16use crate::exec;
17use crate::host::{Arch, HostOs, qemu_system};
18
19/// How long UTM may take to open and answer Apple events, by default.
20pub const UTM_WAIT: Duration = Duration::from_secs(60);
21
22/// How long one Apple event to UTM may take.
23const UTM_ASK: Duration = Duration::from_secs(15);
24
25/// The pause between two asks while UTM opens.
26const UTM_RETRY: Duration = Duration::from_secs(1);
27
28/// What UTM is asked, once it runs: its machines. Not its name: UTM answers that while it is
29/// still loading, then refuses a machine's import a moment later with "UTM is not ready to accept
30/// commands. (-2700)"; it lists its machines only once it takes commands.
31const UTM_PROBE: &str = "tell application \"UTM\" to get id of every virtual machine";
32
33/// The Apple event error macOS answers when the sender may not drive the app (its Automation
34/// permission): no wait fixes it.
35const NOT_AUTHORIZED: i32 = -1743;
36
37/// Why a provider isn't ready for a start.
38#[derive(Debug, Clone, PartialEq, Eq)]
39#[non_exhaustive]
40pub enum NotReady {
41    /// The system refuses what driving the hypervisor needs: UTM's Apple events
42    /// ([`ProviderNeed::Automation`], `-1743`). Waiting doesn't fix it; the user's settings do.
43    Needs(ProviderNeed),
44    /// The hypervisor's app couldn't be opened (not installed where it was looked for).
45    NotOpened {
46        /// Why, as the system said it.
47        said: String,
48    },
49    /// The hypervisor's app didn't answer within `waited`.
50    NoAnswer {
51        /// How long it was waited for.
52        waited: Duration,
53        /// Its last answer.
54        said: String,
55    },
56    /// QEMU's system emulator for `arch` isn't installed.
57    Emulator {
58        /// The CPU it emulates.
59        arch: Arch,
60        /// Its program (`qemu-system-x86_64`).
61        program: &'static str,
62    },
63}
64
65impl NotReady {
66    /// The runner's code for it: a refusal of the system's is [`ErrorCode::ProviderRefused`], a
67    /// missing app or emulator [`ErrorCode::ToolMissing`], no answer [`ErrorCode::Timeout`].
68    #[must_use]
69    pub fn code(&self) -> ErrorCode {
70        match self {
71            NotReady::Needs(_) => ErrorCode::ProviderRefused,
72            NotReady::NotOpened { .. } | NotReady::Emulator { .. } => ErrorCode::ToolMissing,
73            NotReady::NoAnswer { .. } => ErrorCode::Timeout,
74        }
75    }
76}
77
78impl std::fmt::Display for NotReady {
79    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
80        match self {
81            NotReady::Needs(ProviderNeed::Automation) => f.write_str("macOS doesn't allow this app to control UTM (Automation permission)"),
82            NotReady::Needs(need) => write!(f, "the system refuses what the hypervisor needs ({need:?})"),
83            NotReady::NotOpened { said } => write!(f, "UTM couldn't be opened: {said}"),
84            NotReady::NoAnswer { waited, said } => write!(f, "UTM didn't answer within {} s: {said}", waited.as_secs()),
85            NotReady::Emulator { program, .. } => write!(f, "QEMU's emulator {program} isn't installed"),
86        }
87    }
88}
89
90impl std::error::Error for NotReady {}
91
92/// Opens UTM hidden and in the background (`open -g -j -a <UTM's bundle>`: `-g` alone still
93/// shows its window over the caller's), then asks it for its machines until it answers, for at
94/// most `wait` ([`UTM_WAIT`] is a start's). A UTM already open is left as it is. `waiting` is
95/// called once, when it doesn't answer at first (UTM opening), so the caller can say so. Nothing
96/// to do on any OS but macOS.
97///
98/// # Errors
99///
100/// [`NotReady::NotOpened`] when UTM can't be opened, [`NotReady::Needs`] with
101/// [`ProviderNeed::Automation`] when macOS refuses this app Apple events to it (`-1743`), and
102/// [`NotReady::NoAnswer`] when it doesn't answer within `wait`.
103pub async fn utm(cx: &Context, wait: Duration, waiting: &mut (dyn FnMut() + Send)) -> Result<(), NotReady> {
104    if cx.host.os != HostOs::Macos {
105        return Ok(());
106    }
107    let app = cx.host.devices.utm_app.to_string_lossy().into_owned();
108    let open = ProcessSpec::new("open", ["-g", "-j", "-a", app.as_str()]);
109    match cx.probe_within(cx.probe_timeout, &open).await {
110        Ok(opened) if opened.success() => {}
111        Ok(failed) => return Err(NotReady::NotOpened { said: failed.reason() }),
112        Err(e) => return Err(NotReady::NotOpened { said: e.to_string() }),
113    }
114    let ask = ProcessSpec::new("osascript", ["-e", UTM_PROBE]);
115    let started = tokio::time::Instant::now();
116    let mut said_waiting = false;
117    loop {
118        let said = match cx.probe_within(UTM_ASK, &ask).await {
119            Ok(answer) if answer.success() => return Ok(()),
120            Ok(refused) if apple_event(&exec::all_lines(&refused)) == Some(NOT_AUTHORIZED) => {
121                return Err(NotReady::Needs(ProviderNeed::Automation));
122            }
123            Ok(refused) => refused.reason(),
124            Err(e) => e.to_string(),
125        };
126        if started.elapsed() >= wait {
127            return Err(NotReady::NoAnswer { waited: wait, said });
128        }
129        if !said_waiting {
130            waiting();
131            said_waiting = true;
132        }
133        tokio::time::sleep(UTM_RETRY).await;
134    }
135}
136
137/// The CPUs of `machines` (a project's machines' CPUs) this computer emulates, each once, in
138/// order: those other than its own. QEMU's system emulator for each must be installed
139/// (`qemu-system-x86_64 --version` answers): an x86 machine on an Apple silicon Mac needs it.
140///
141/// # Errors
142///
143/// [`NotReady::Emulator`] naming the first CPU whose emulator isn't installed.
144pub async fn emulators(cx: &Context, machines: impl IntoIterator<Item = Arch>) -> Result<Vec<Arch>, NotReady> {
145    let mut emulated = Vec::new();
146    for arch in machines {
147        if arch == cx.host.arch || emulated.contains(&arch) {
148            continue;
149        }
150        let program = qemu_system(arch);
151        if cx.read_ok(program, &["--version"]).await.is_err() {
152            return Err(NotReady::Emulator { arch, program });
153        }
154        emulated.push(arch);
155    }
156    Ok(emulated)
157}
158
159/// The last Apple event error number `said` names (`(-1743)`, ending `osascript`'s message in
160/// every language); none when it names none.
161fn apple_event(said: &str) -> Option<i32> {
162    said.match_indices("(-")
163        .filter_map(|(at, _)| {
164            let rest = said.get(at + 1..)?;
165            rest.get(..rest.find(')')?)?.parse::<i32>().ok()
166        })
167        .last()
168}
169
170#[cfg(test)]
171mod tests;