Skip to main content

isothrum_machine/
boxes.rs

1//! Vagrant's boxes on this computer: which are held for a provider and this CPU (`vagrant box
2//! list`), and a box added (`vagrant box add`), its download handed back for a caller that keeps
3//! a record of its downloads, or a box file saved here added under a name ([`add_file`]: a run's
4//! machine saved by `Running::package`). What uses a box (a self-test's, a project's) picks it.
5
6use std::time::Duration;
7
8use isothrum_runner::{Arch, DownloadToAdopt, ProcessSpec, Provider};
9
10use crate::Context;
11
12/// A box is hundreds of MB: past this the download is stalled, not just on a slow link.
13const ADD_LIMIT: Duration = Duration::from_secs(1800);
14
15/// The most error lines of a failed `vagrant box add` its failure says: Vagrant's error is a
16/// paragraph, ending with what failed (curl's error, the lock another download holds).
17const SAID_LINES: usize = 10;
18
19/// The Vagrant box provider a box is added and listed under for `p`. QEMU is the exception: the
20/// vagrant-qemu plugin boots a libvirt-format box's qcow2 directly, so its box is stored as
21/// `libvirt`, never `qemu`. `generic/alpine319`'s own "qemu" box is a libvirt image mislabeled
22/// (`box add --provider qemu` fetches it and then rejects it), while its `libvirt` box bakes in
23/// the vagrant user and key, so the test VM gets SSH without cloud-init (which vagrant-qemu does
24/// not seed).
25#[must_use]
26pub fn box_provider(p: Provider) -> &'static str {
27    match p {
28        Provider::Qemu => "libvirt",
29        _ => p.id(),
30    }
31}
32
33/// One box of `vagrant box list`: `name (provider, version[, (arch)])`.
34#[derive(Debug, Clone, PartialEq, Eq)]
35struct Listed {
36    name: String,
37    provider: String,
38    version: String,
39    arch: Option<String>,
40}
41
42/// The boxes `vagrant box list` printed.
43fn listed(out: &str) -> Vec<Listed> {
44    out.lines()
45        .filter_map(|line| {
46            let (name, rest) = line.trim().split_once(char::is_whitespace)?;
47            let inner = rest.trim().strip_prefix('(')?;
48            let mut fields = inner.split(',').map(|f| f.trim().trim_end_matches(')'));
49            let provider = fields.next().filter(|p| !p.is_empty())?;
50            let version = fields.next().filter(|v| !v.is_empty())?;
51            let arch = fields.next().map(|a| a.trim_start_matches('(')).filter(|a| !a.is_empty()).map(str::to_owned);
52            Some(Listed {
53                name: name.to_owned(),
54                provider: provider.to_owned(),
55                version: version.to_owned(),
56                arch,
57            })
58        })
59        .collect()
60}
61
62/// The CPU's name in a box listing.
63pub(crate) fn arch_name(arch: Arch) -> &'static str {
64    match arch {
65        Arch::Amd64 => "amd64",
66        Arch::Arm64 => "arm64",
67    }
68}
69
70/// The version of box `name` for `p` that `list` (`vagrant box list`) holds for `arch`; a box
71/// with no architecture in the listing counts for any.
72pub(crate) fn held(list: &str, name: &str, p: Provider, arch: Arch) -> Option<String> {
73    listed(list).into_iter().find_map(|b| {
74        let other_cpu = matches!(b.arch.as_deref(), Some(a @ ("amd64" | "arm64")) if a != arch_name(arch));
75        (b.name == name && b.provider == box_provider(p) && !other_cpu).then_some(b.version)
76    })
77}
78
79/// Adds box `name` for `p` (`vagrant box add --force`), each line Vagrant prints said to `line`;
80/// past half an hour it is given up on. The box as added, for a caller that keeps a record of its
81/// downloads (none when its version can't be read back).
82///
83/// # Errors
84///
85/// What Vagrant said (its last error lines), or that it stalled.
86pub async fn add_box(cx: &Context, p: Provider, name: &str, line: &mut (dyn FnMut(&str) + Send)) -> Result<Option<DownloadToAdopt>, String> {
87    let args = ["box", "add", name, "--provider", box_provider(p), "--force"];
88    vagrant_add(cx, &args, &format!("vagrant box add {name}"), line).await?;
89    Ok(listed_as_added(cx, p, name).await)
90}
91
92/// Adds the box file `file` as box `name` for `p` (`vagrant box add --name <name> <file> --force`),
93/// each line Vagrant prints said to `line`: a run's machine saved by `Running::package`, which a
94/// later run boots by that name. The box as added, for a caller that keeps a record of what it
95/// added (none when its version can't be read back).
96///
97/// # Errors
98///
99/// What Vagrant said (its last error lines), or that it stalled.
100pub async fn add_file(
101    cx: &Context,
102    p: Provider,
103    name: &str,
104    file: &std::path::Path,
105    line: &mut (dyn FnMut(&str) + Send),
106) -> Result<Option<DownloadToAdopt>, String> {
107    let file = file.display().to_string();
108    let args = ["box", "add", "--name", name, file.as_str(), "--force"];
109    vagrant_add(cx, &args, &format!("vagrant box add --name {name}"), line).await?;
110    Ok(listed_as_added(cx, p, name).await)
111}
112
113/// Runs `vagrant <args>` (a `box add`), each line said to `line`; past [`ADD_LIMIT`] it is given
114/// up on. A failure says `what` failed, with Vagrant's last error lines.
115async fn vagrant_add(cx: &Context, args: &[&str], what: &str, line: &mut (dyn FnMut(&str) + Send)) -> Result<(), String> {
116    let spec = ProcessSpec::new("vagrant", args.iter().copied());
117    let mut said: Vec<String> = Vec::new();
118    let mut on_line = |stream: isothrum_runner::Stream, l: &str| {
119        if stream == isothrum_runner::Stream::Stderr && !l.trim().is_empty() {
120            if said.len() == SAID_LINES {
121                said.remove(0);
122            }
123            said.push(l.trim().to_owned());
124        }
125        line(l);
126    };
127    let added = tokio::time::timeout(ADD_LIMIT, cx.runner.run(&spec, &mut on_line)).await;
128    let exit = added.map_err(|_| format!("vagrant box add stalled: nothing for {} minutes", ADD_LIMIT.as_secs() / 60))?;
129    let exit = exit.map_err(|e| e.to_string())?;
130    if exit.success() {
131        return Ok(());
132    }
133    Err(if said.is_empty() {
134        format!("{what} failed ({exit})")
135    } else {
136        format!("{what} failed: {} ({exit})", said.join("\n"))
137    })
138}
139
140/// The version of box `name` Vagrant holds here for `p` and this computer's CPU (`vagrant box
141/// list`); none when it holds none, or Vagrant can't be read.
142pub async fn held_here(cx: &Context, p: Provider, name: &str) -> Option<String> {
143    let list = cx.read_ok("vagrant", &["box", "list"]).await.unwrap_or_default();
144    held(&list, name, p, cx.host.arch)
145}
146
147/// Box `name` for `p` as `vagrant box list` now holds it, for a caller's record.
148async fn listed_as_added(cx: &Context, p: Provider, name: &str) -> Option<DownloadToAdopt> {
149    held_here(cx, p, name).await.map(|version| adopted(name, p, version))
150}
151
152/// The box `name` added for `provider` by this process: for a caller that keeps a record of its
153/// downloads.
154fn adopted(name: &str, provider: Provider, version: String) -> DownloadToAdopt {
155    DownloadToAdopt::Box {
156        name: name.to_owned(),
157        provider: box_provider(provider).to_owned(),
158        version,
159    }
160}
161
162#[cfg(test)]
163mod tests {
164    use super::*;
165
166    #[test]
167    fn a_box_is_held_for_its_provider_and_this_cpu() {
168        let list = "generic/debian12   (virtualbox, 202510.26.0, (amd64))\r\ngeneric/alpine319\t(libvirt, 4.3.12)\nThere are no installed boxes!\nodd (\n";
169        assert_eq!(
170            held(list, "generic/debian12", Provider::Virtualbox, Arch::Amd64).as_deref(),
171            Some("202510.26.0")
172        );
173        assert_eq!(held(list, "generic/debian12", Provider::Virtualbox, Arch::Arm64), None, "another CPU's");
174        assert_eq!(
175            held(list, "generic/alpine319", Provider::Qemu, Arch::Arm64).as_deref(),
176            Some("4.3.12"),
177            "QEMU boots libvirt boxes, any CPU listed"
178        );
179        assert_eq!(held(list, "generic/alpine319", Provider::Virtualbox, Arch::Amd64), None);
180    }
181
182    /// Regression: a failed `vagrant box add` said only its exit code, so a download another
183    /// process held (two self-tests at once) read as a network failure.
184    #[tokio::test]
185    async fn a_failed_add_says_what_vagrant_said() {
186        use isothrum_runner::fake::{FakeProcesses, Reply};
187        let lock = "Download to global Vagrant location already in progress. This\nmay be caused by other Vagrant processes attempting to download\na file to the same location.\n\nDownload path: /home/u/.vagrant.d/tmp/boxd9\nLock file path: /home/u/.vagrant.d/tmp/boxd9.lock";
188        for (reply, expected) in [
189            (
190                Reply::fail(1, lock),
191                "vagrant box add bento/debian-12 failed: Download to global Vagrant location already in progress. This\nmay be caused by other Vagrant processes attempting to download\na file to the same location.\nDownload path: /home/u/.vagrant.d/tmp/boxd9\nLock file path: /home/u/.vagrant.d/tmp/boxd9.lock (exited with code 1)",
192            ),
193            (Reply::fail(1, ""), "vagrant box add bento/debian-12 failed (exited with code 1)"),
194        ] {
195            let fake = FakeProcesses::script().expect("vagrant box add bento/debian-12", reply).build();
196            let cx = crate::testing::answered_by(fake);
197            let mut lines = Vec::new();
198            let failed = add_box(&cx, Provider::Virtualbox, "bento/debian-12", &mut |l| lines.push(l.to_owned())).await;
199            assert_eq!(failed.err().as_deref(), Some(expected), "{expected}");
200        }
201    }
202
203    #[tokio::test]
204    async fn a_box_is_held_here_as_vagrant_lists_it() {
205        use isothrum_runner::fake::{FakeProcesses, Reply};
206        let fake = FakeProcesses::script().expect("vagrant box list", Reply::ok("local/tools (utm, 0)\n")).build();
207        let cx = crate::testing::answered_by(fake);
208        assert_eq!(held_here(&cx, Provider::Utm, "local/tools").await.as_deref(), Some("0"));
209        assert_eq!(held_here(&cx, Provider::Utm, "other/box").await, None);
210    }
211
212    #[tokio::test]
213    async fn a_saved_box_file_is_added_under_its_name() {
214        use isothrum_runner::fake::{FakeProcesses, Reply};
215        let fake = FakeProcesses::script()
216            .expect("vagrant box add --name local/tools /tmp/saved.box --force", Reply::ok(""))
217            .expect("vagrant box list", Reply::ok("local/tools (virtualbox, 0)\n"))
218            .build();
219        let cx = crate::testing::answered_by(fake);
220        let added = add_file(&cx, Provider::Virtualbox, "local/tools", std::path::Path::new("/tmp/saved.box"), &mut |_| {}).await;
221        assert_eq!(added, Ok(Some(adopted("local/tools", Provider::Virtualbox, "0".to_owned()))));
222        let refused = FakeProcesses::script()
223            .expect("vagrant box add --name local/tools", Reply::fail(1, "not a box"))
224            .build();
225        let failed = add_file(
226            &crate::testing::answered_by(refused),
227            Provider::Virtualbox,
228            "local/tools",
229            std::path::Path::new("/tmp/saved.box"),
230            &mut |_| {},
231        )
232        .await;
233        assert_eq!(
234            failed.err().as_deref(),
235            Some("vagrant box add --name local/tools failed: not a box (exited with code 1)")
236        );
237    }
238}