1use std::time::Duration;
7
8use isothrum_runner::{Arch, DownloadToAdopt, ProcessSpec, Provider};
9
10use crate::Context;
11
12const ADD_LIMIT: Duration = Duration::from_secs(1800);
14
15const SAID_LINES: usize = 10;
18
19#[must_use]
26pub fn box_provider(p: Provider) -> &'static str {
27 match p {
28 Provider::Qemu => "libvirt",
29 _ => p.id(),
30 }
31}
32
33#[derive(Debug, Clone, PartialEq, Eq)]
35struct Listed {
36 name: String,
37 provider: String,
38 version: String,
39 arch: Option<String>,
40}
41
42fn 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
62pub(crate) fn arch_name(arch: Arch) -> &'static str {
64 match arch {
65 Arch::Amd64 => "amd64",
66 Arch::Arm64 => "arm64",
67 }
68}
69
70pub(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
79pub 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
92pub 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
113async 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
140pub 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
147async 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
152fn 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 #[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}