isothrum_machine/install/steps.rs
1//! Running install and removal steps: one program each, through the [`Context`]'s runner, every
2//! line it prints handed on as it comes, and what its output says beyond its exit code read on the
3//! way: pkexec's own refusals told apart from the script's failures, `sudo -n` refusing to run
4//! without a password, a broken Homebrew.
5
6use std::sync::Mutex;
7
8use isothrum_runner::{ProcessError, ProcessSpec, Stream};
9
10use crate::context::Context;
11use crate::host::tool_path::{self, Env};
12
13/// One command of an install or removal.
14#[derive(Debug)]
15#[non_exhaustive]
16pub struct Step {
17 /// The program to run.
18 pub program: String,
19 /// Its arguments.
20 pub args: Vec<String>,
21 /// What a UI shows before it instead of its command line, when it says one.
22 pub note: Option<Note>,
23 /// What it asks of the person at the computer while it runs or after it (a password prompt, a
24 /// vendor's agreement they accept in its app, a restart after it), in order: a UI says them
25 /// before the install and again as the step starts ([`super::interaction`]). Empty when it
26 /// asks nothing.
27 pub interactions: Vec<super::Interaction>,
28 /// A private folder of files the step reads (a root step's proxy settings), removed with
29 /// the step.
30 pub(crate) private: Option<tempfile::TempDir>,
31 /// What the step's script finds this system isn't, when it exits with [`NOT_SERVED`] before
32 /// changing anything.
33 pub(crate) not_served: Option<NotServed>,
34}
35
36/// The exit code of a step's script that stops before changing anything because this system isn't
37/// one it serves ([`Step`]'s `not_served` says which).
38pub(crate) const NOT_SERVED: i32 = 69;
39
40/// What a step found this system isn't, before it changed anything. A UI says each in its own
41/// words.
42#[derive(Debug, Clone, Copy, PartialEq, Eq)]
43#[non_exhaustive]
44pub enum NotServed {
45 /// Docker's install serves Debian, Ubuntu and the distributions built on them; elsewhere its
46 /// user installs Docker Engine from their distribution or Docker's documentation.
47 DockerDistribution,
48 /// This edition of Windows (Home) has no Hyper-V to turn on.
49 HypervEdition,
50}
51
52impl Step {
53 /// This step, its script exiting with [`NOT_SERVED`] when this system isn't one it serves.
54 pub(crate) fn not_served(mut self, why: NotServed) -> Step {
55 self.not_served = Some(why);
56 self
57 }
58}
59
60/// A step that runs `program` with `args`.
61#[must_use]
62pub fn step(program: impl Into<String>, args: &[&str]) -> Step {
63 Step {
64 program: program.into(),
65 args: args.iter().map(ToString::to_string).collect(),
66 note: None,
67 interactions: Vec::new(),
68 private: None,
69 not_served: None,
70 }
71}
72
73/// What a step is, said before it instead of its command line (a UI words it): an install that
74/// opens its vendor's own installer, a step that raises an administrator's prompt.
75#[derive(Debug, Clone, Copy, PartialEq, Eq)]
76#[non_exhaustive]
77pub enum Note {
78 /// The tool installed from its vendor's disk image or package, which Homebrew (or the vendor's
79 /// own address) downloads, as
80 /// an administrator (macOS asks for the user's password): its app copied into Applications or
81 /// its package installed, each checked as signed by its vendor. No window is left to finish.
82 InstallingFromVendor {
83 /// The tool.
84 dependency: super::Dependency,
85 /// The agreement the tool's app shows its user at its first start, for them to accept
86 /// there, when it has one (Docker Desktop's): no install accepts it for them.
87 agreement: Option<Agreement>,
88 },
89 /// QEMU's install, Homebrew updated first if it is out of date for this macOS.
90 QemuUpdatingHomebrewFirst,
91 /// The tool's Homebrew formula built from source, which takes long (QEMU: its dependencies
92 /// too, a quarter of an hour or more): Homebrew has no bottles for this Mac's CPU (Intel).
93 BuildsFromSource(super::Dependency),
94 /// The Azure CLI's Homebrew tap trusted (Homebrew 7 asks for it; older ones don't).
95 TrustingAzureTap,
96 /// The prebuilt Azure CLI cask installed (no long source build).
97 AzureCliCask,
98 /// HashiCorp's Vagrant VMware Utility downloaded, at this version.
99 DownloadingVmwareUtility {
100 /// Its version.
101 version: &'static str,
102 },
103 /// The tool removed by its vendor's own uninstaller or by a script, macOS asking for the
104 /// user's password when the step is an administrator's.
105 Removing(super::Dependency),
106}
107
108/// A vendor's agreement its app shows its user, who accepts it there themselves
109/// ([`Note::InstallingFromVendor`]): nothing here ever accepts it for them.
110#[derive(Debug, Clone, Copy, PartialEq, Eq)]
111#[non_exhaustive]
112pub struct Agreement {
113 /// Its name, as its vendor writes it.
114 pub name: &'static str,
115 /// Where its vendor publishes it.
116 pub url: &'static str,
117}
118
119/// How a step shows in a log: `$ program args`, as typed. A root step's proxy is never on it
120/// (it is read from a private file); a caller that shows the line to someone may still redact it.
121#[must_use]
122pub fn command_line(step: &Step) -> String {
123 format!("$ {} {}", step.program, step.args.join(" "))
124}
125
126/// Why a step failed. A UI says each in its own words.
127#[derive(Debug, Clone, PartialEq, Eq)]
128#[non_exhaustive]
129pub enum StepFailed {
130 /// pkexec isn't installed, so no password prompt can be shown (Debian ships it apart from
131 /// polkit).
132 NoPkexec,
133 /// The step's program isn't installed.
134 Missing {
135 /// The program.
136 program: String,
137 },
138 /// The program couldn't be started for another reason: what the OS said.
139 NotStarted(String),
140 /// pkexec's password prompt was dismissed, or the password refused: nothing was changed.
141 PromptRefused,
142 /// pkexec could show no password prompt: no polkit agent runs.
143 NoPolkitAgent,
144 /// `sudo -n` (an unattended root step) needed a password: nothing was changed.
145 SudoRefused,
146 /// The step's script stopped before changing anything: this system isn't one it serves.
147 NotServed(NotServed),
148 /// Homebrew itself is broken (a root-owned lock, too old for this macOS, an Xcode too old): the
149 /// user's to repair, which an install can't mend.
150 Homebrew(super::brew::Trouble),
151 /// The program ran and failed: its exit code, `None` when a signal ended it, and what its codes
152 /// say happened when that is known (winget's, an installer's run through PowerShell).
153 Exited {
154 /// The program.
155 program: String,
156 /// Its exit code.
157 code: Option<i32>,
158 /// What its codes say happened, when known.
159 known: Option<super::exit_codes::Known>,
160 },
161}
162
163impl std::fmt::Display for StepFailed {
164 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
165 match self {
166 StepFailed::NoPkexec => f.write_str("pkexec isn't installed: no password prompt can be shown"),
167 StepFailed::Missing { program } => write!(f, "{program} isn't installed"),
168 StepFailed::NotStarted(why) => write!(f, "the step couldn't be started: {why}"),
169 StepFailed::PromptRefused => f.write_str("the password prompt was dismissed or the password refused"),
170 StepFailed::NoPolkitAgent => f.write_str("no password prompt could be shown: no polkit agent runs"),
171 StepFailed::SudoRefused => f.write_str("sudo needs a password, and none can be asked for unattended"),
172 StepFailed::NotServed(why) => write!(f, "this system isn't one the step serves: {why:?}"),
173 StepFailed::Homebrew(trouble) => write!(f, "Homebrew is broken: {trouble:?}"),
174 StepFailed::Exited { program, code: Some(code), .. } => write!(f, "`{program}` exited with code {code}"),
175 StepFailed::Exited { program, code: None, .. } => write!(f, "`{program}` was ended by a signal"),
176 }
177 }
178}
179
180impl std::error::Error for StepFailed {}
181
182/// Runs `steps` in order, each without a [`Note`] announced as [`command_line`] first (a caller
183/// that shows notes says them itself); the first that fails stops them.
184///
185/// # Errors
186///
187/// The first step's failure.
188pub async fn run_steps(cx: &Context, steps: &[Step], on_line: &mut (dyn FnMut(&str) + Send)) -> Result<(), StepFailed> {
189 for step in steps {
190 if step.note.is_none() {
191 on_line(&command_line(step));
192 }
193 run_step(cx, step, on_line).await?;
194 }
195 Ok(())
196}
197
198/// Runs one step, each line it prints (standard output and error) handed to `on_line`. It runs
199/// in a process group of its own, like every tool of the runner: a step dropped mid-way is ended
200/// with what it started, not left installing unattended.
201///
202/// Done, it says how when its codes say more than "done" ([`super::exit_codes::Done`]: winget's
203/// "already installed", "restart to finish").
204///
205/// # Errors
206///
207/// [`StepFailed`]: why it failed.
208pub async fn run_step(cx: &Context, step: &Step, on_line: &mut (dyn FnMut(&str) + Send)) -> Result<Option<super::exit_codes::Done>, StepFailed> {
209 run_step_on(cx, step, &Env::here(), on_line).await
210}
211
212/// [`run_step`], this process's variables read from `env`. On Windows the step runs with the
213/// `PATH` installers have written to the registry since this process started merged in
214/// ([`tool_path::refreshed_value`]): a running process never reads it again, so a step after
215/// an install (Vagrant's plugin after Vagrant, in one setup or a process started before it)
216/// would not find the tool just installed.
217pub(crate) async fn run_step_on(
218 cx: &Context,
219 step: &Step,
220 env: &Env,
221 on_line: &mut (dyn FnMut(&str) + Send),
222) -> Result<Option<super::exit_codes::Done>, StepFailed> {
223 let mut spec = ProcessSpec::new(&step.program, step.args.iter().map(String::as_str));
224 if let Some(path) = tool_path::refreshed_value(cx, env).await {
225 spec.env.push(("PATH".to_owned(), path));
226 }
227 let watch = Mutex::new(Watch::new(step));
228 let exit = {
229 let mut each = |stream: Stream, line: &str| {
230 let mut watched = watch.lock().unwrap_or_else(std::sync::PoisonError::into_inner);
231 watched.line(line);
232 if stream == Stream::Stderr {
233 watched.error_line(line);
234 }
235 drop(watched);
236 on_line(line);
237 };
238 cx.runner.run(&spec, &mut each).await
239 };
240 let exit = match exit {
241 Ok(exit) => exit,
242 Err(ProcessError::Missing { .. }) if step.program == "pkexec" => return Err(StepFailed::NoPkexec),
243 Err(ProcessError::Missing { program }) => return Err(StepFailed::Missing { program }),
244 Err(e) => return Err(StepFailed::NotStarted(e.to_string())),
245 };
246 watch.into_inner().unwrap_or_else(std::sync::PoisonError::into_inner).end(step, exit.code)
247}
248
249/// The programs whose output a step's watch reads.
250#[derive(Clone, Copy, PartialEq, Eq, Debug)]
251enum Program {
252 /// winget: the installer it ran exits with a code of its own.
253 Winget,
254 /// PowerShell running an installer (WSL's, Hyper-V's DISM, an MSI): exits with its code.
255 Powershell,
256 /// pkexec: its own refusals, told apart from the script's.
257 Pkexec,
258 /// `sudo -n` (an unattended root step): its refusal to run without a password.
259 UnattendedSudo,
260 /// Any other.
261 Other,
262}
263
264/// Whether `step` drives Homebrew (directly, or through a shell line that calls it), so its output
265/// is worth reading for a broken-Homebrew cause. apt, winget and pkexec never are.
266fn is_brew_step(step: &Step) -> bool {
267 step.program.contains("brew") || step.args.iter().any(|a| a.contains("brew"))
268}
269
270impl Program {
271 /// The program `step` runs.
272 fn of(step: &Step) -> Program {
273 match step.program.as_str() {
274 "winget" => Program::Winget,
275 "powershell" => Program::Powershell,
276 "pkexec" => Program::Pkexec,
277 "sudo" if step.args.first().is_some_and(|a| a == "-n") => Program::UnattendedSudo,
278 _ => Program::Other,
279 }
280 }
281}
282
283/// What a step's error output says beyond its exit code: pkexec's own refusal (told apart from
284/// the script's exit code), sudo's refusal to run without a password.
285#[derive(Debug)]
286struct Watch {
287 program: Program,
288 pkexec_refusal: Option<super::pkexec::Refusal>,
289 sudo_refused: bool,
290 /// Whether the step drives Homebrew, and the first broken-Homebrew cause it said (an
291 /// update's lock error comes before the install error it leads to, so it wins).
292 brew: bool,
293 brew_trouble: Option<super::brew::Trouble>,
294 /// The exit code of the installer winget ran, from its output.
295 installer_code: Option<u32>,
296}
297
298impl Watch {
299 fn new(step: &Step) -> Watch {
300 Watch {
301 program: Program::of(step),
302 pkexec_refusal: None,
303 sudo_refused: false,
304 brew: is_brew_step(step),
305 brew_trouble: None,
306 installer_code: None,
307 }
308 }
309
310 /// A line of the step's output, either stream.
311 fn line(&mut self, line: &str) {
312 if self.program == Program::Winget {
313 self.installer_code = super::exit_codes::installer_exit_code(line).or(self.installer_code);
314 }
315 }
316
317 /// A line of the step's error output.
318 fn error_line(&mut self, line: &str) {
319 if self.program == Program::Pkexec
320 && let Some(refusal) = super::pkexec::Refusal::of_line(line)
321 {
322 self.pkexec_refusal = Some(refusal);
323 }
324 if self.program == Program::UnattendedSudo && line.starts_with("sudo: ") && line.contains("password") {
325 self.sudo_refused = true;
326 }
327 if self.brew && self.brew_trouble.is_none() {
328 self.brew_trouble = super::brew::Trouble::of_line(line);
329 }
330 }
331
332 /// How the step ended, once it exited with `code`.
333 fn end(self, step: &Step, code: Option<i32>) -> Result<Option<super::exit_codes::Done>, StepFailed> {
334 // pkexec exits 126 when the password prompt was dismissed or refused and 127 when no
335 // polkit agent could show one, but the script's own 126/127 (a command missing or not
336 // executable) come through as is: only pkexec's own message says which it was.
337 if let Some(refusal) = self.pkexec_refusal.filter(|_| matches!(code, Some(126 | 127))) {
338 return Err(match refusal {
339 super::pkexec::Refusal::NoAgent => StepFailed::NoPolkitAgent,
340 super::pkexec::Refusal::Refused => StepFailed::PromptRefused,
341 });
342 }
343 if code == Some(0) {
344 return Ok(None);
345 }
346 if self.program == Program::Winget
347 && let Some(done) = super::exit_codes::winget_done(code)
348 {
349 return Ok(Some(done));
350 }
351 if self.sudo_refused {
352 return Err(StepFailed::SudoRefused);
353 }
354 if let Some(why) = step.not_served.filter(|_| code == Some(NOT_SERVED)) {
355 return Err(StepFailed::NotServed(why));
356 }
357 if let Some(trouble) = self.brew_trouble {
358 return Err(StepFailed::Homebrew(trouble));
359 }
360 let known = match self.program {
361 Program::Winget => super::exit_codes::winget_failure(code, self.installer_code),
362 Program::Powershell => super::exit_codes::installer_failure(code),
363 Program::Pkexec | Program::UnattendedSudo | Program::Other => None,
364 };
365 Err(StepFailed::Exited {
366 program: step.program.clone(),
367 code,
368 known,
369 })
370 }
371}
372
373#[cfg(test)]
374mod tests;