Skip to main content

isothrum_runner/
downloads.rs

1//! What the runs' own downloads fetched, and their removal: the images a Compose start's pull
2//! pulled and the boxes a Vagrant `up` added, recorded in the home's store as they are fetched
3//! ([`Runner::downloads`], [`Runner::remove_downloads`]). An image counts as fetched when, after
4//! the pull, its reference stands for an id the engine didn't hold before it; a box when `box
5//! list` lists it after the `up` and didn't before. What was there before, or what anything else
6//! fetched, is never recorded, so never removed.
7
8use std::path::{Path, PathBuf};
9use std::time::Duration;
10
11use serde::{Deserialize, Serialize};
12
13use crate::Result;
14use crate::cli::{Call, docker, vagrant};
15use crate::name::RunName;
16use crate::process::{DockerContext, ProcessRunner};
17use crate::runner::Runner;
18use crate::tool_output::vagrant::InstalledBox;
19
20mod adopt;
21
22pub use adopt::DownloadToAdopt;
23
24/// How long one call of a listing or a removal may take.
25const CALL_LIMIT: Duration = Duration::from_secs(300);
26
27/// A recorded download's id in the home's store.
28#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord, Hash, Serialize, Deserialize, schemars::JsonSchema)]
29#[serde(transparent)]
30pub struct DownloadId(pub i64);
31
32/// What a run's tool fetched.
33#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
34#[serde(tag = "kind", rename_all = "snake_case")]
35#[non_exhaustive]
36pub enum DownloadItem {
37    /// A container image a Compose start's pull pulled.
38    Image {
39        /// The reference it was pulled as (`nginx:1.27`), as the project names it.
40        reference: String,
41        /// The id the reference stood for once pulled (`sha256:…`).
42        image_id: String,
43        /// The Docker context it was pulled through, when the run names one.
44        #[serde(default, skip_serializing_if = "Option::is_none")]
45        docker_context: Option<String>,
46    },
47    /// A Vagrant box an `up` added.
48    Box {
49        /// Its name (`bento/debian-12`).
50        name: String,
51        /// The provider it is for (`virtualbox`).
52        provider: String,
53        /// Its version.
54        version: String,
55        /// Its architecture (`amd64`), when it has one.
56        #[serde(default, skip_serializing_if = "Option::is_none")]
57        architecture: Option<String>,
58    },
59}
60
61impl DownloadItem {
62    /// The box `held` names, as fetched.
63    pub(crate) fn of_box(held: InstalledBox) -> DownloadItem {
64        DownloadItem::Box {
65            name: held.name,
66            provider: held.provider,
67            version: held.version,
68            architecture: held.architecture,
69        }
70    }
71}
72
73/// One recorded download.
74#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
75#[non_exhaustive]
76pub struct Download {
77    /// Its id: what a removal names it by.
78    pub id: DownloadId,
79    /// What was fetched.
80    #[serde(flatten)]
81    pub item: DownloadItem,
82    /// The run whose operation fetched it; none for one adopted ([`Runner::adopt_downloads`]).
83    #[serde(default, skip_serializing_if = "Option::is_none")]
84    pub run: Option<RunName>,
85    /// When (RFC 3339, UTC).
86    pub fetched_at: String,
87    /// Its size on disk in bytes, when it could be read (an image's as its engine says, a box's
88    /// folder's); none in what the store keeps.
89    #[serde(default, skip_serializing_if = "Option::is_none")]
90    pub size_bytes: Option<u64>,
91}
92
93/// Which recorded downloads a removal takes: all, or those of the given ids.
94#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
95#[serde(rename_all = "snake_case")]
96pub enum DownloadsToRemove {
97    /// Every recorded download.
98    All,
99    /// Only these.
100    Only(Vec<DownloadId>),
101}
102
103/// How the removal of one recorded download went.
104#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
105#[serde(tag = "outcome", rename_all = "snake_case")]
106#[non_exhaustive]
107pub enum RemovalOutcome {
108    /// Removed, and its record forgotten.
109    Removed,
110    /// Gone already (removed outside the runner): its record forgotten.
111    Gone,
112    /// The image's reference now stands for another image (pulled again, retagged): nothing
113    /// removed, the record forgotten, the reference no longer the runner's.
114    Moved {
115        /// The id the reference stands for now.
116        now: String,
117    },
118    /// Its tool refused (an image a container uses, a box a machine uses) or failed: kept, and
119    /// its record too.
120    Failed {
121        /// What the tool said.
122        reason: String,
123    },
124    /// No download of that id is recorded.
125    NotRecorded,
126}
127
128/// The removal of one recorded download.
129#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]
130#[non_exhaustive]
131pub struct DownloadRemoval {
132    /// The download asked for.
133    pub id: DownloadId,
134    /// How it went.
135    #[serde(flatten)]
136    pub outcome: RemovalOutcome,
137    /// What it was, when it was recorded.
138    #[serde(default, skip_serializing_if = "Option::is_none")]
139    pub download: Option<Download>,
140}
141
142impl Runner {
143    /// Every download the home's runs fetched and the store records, oldest first, each with its
144    /// size when it can be read.
145    ///
146    /// # Errors
147    ///
148    /// The store can't be read.
149    pub async fn downloads(&self) -> Result<Vec<Download>> {
150        let mut listed = self.store.db().read(recorded)?;
151        for download in &mut listed {
152            download.size_bytes = self.size_of(&download.item).await;
153        }
154        Ok(listed)
155    }
156
157    /// Removes the recorded downloads `which` names, each on its own: an image by its reference
158    /// (`docker image rm`, never forced) while the reference still stands for the recorded id, a
159    /// box by its name, provider, version and architecture (`vagrant box remove`, never forced).
160    /// One its tool refuses (in use) or fails to remove is said in its outcome and kept with its
161    /// record; the others go on. The record of one removed, gone already, or whose reference now
162    /// stands for another image is forgotten. Nothing the store doesn't record is removed.
163    ///
164    /// # Errors
165    ///
166    /// The store can't be read or written.
167    pub async fn remove_downloads(&self, which: &DownloadsToRemove) -> Result<Vec<DownloadRemoval>> {
168        let recorded = self.store.db().read(recorded)?;
169        let asked: Vec<(DownloadId, Option<Download>)> = match which {
170            DownloadsToRemove::All => recorded.into_iter().map(|d| (d.id, Some(d))).collect(),
171            DownloadsToRemove::Only(ids) => ids.iter().map(|id| (*id, recorded.iter().find(|d| d.id == *id).cloned())).collect(),
172        };
173        let mut removals = Vec::with_capacity(asked.len());
174        for (id, download) in asked {
175            let outcome = match &download {
176                Some(d) => self.remove(&d.item).await,
177                None => RemovalOutcome::NotRecorded,
178            };
179            if matches!(outcome, RemovalOutcome::Removed | RemovalOutcome::Gone | RemovalOutcome::Moved { .. }) {
180                self.store.db().write(|tx| tx.forget_download(id))?;
181            }
182            removals.push(DownloadRemoval { id, outcome, download });
183        }
184        Ok(removals)
185    }
186
187    /// Removes `item`, as [`Runner::remove_downloads`] says.
188    async fn remove(&self, item: &DownloadItem) -> RemovalOutcome {
189        let failed = |e: &dyn std::fmt::Display| RemovalOutcome::Failed { reason: e.to_string() };
190        match item {
191            DownloadItem::Image {
192                reference,
193                image_id,
194                docker_context,
195            } => {
196                let processes = self.docker(docker_context.as_deref());
197                let call = self.call(&processes);
198                match docker::image_id(&call, reference).await {
199                    Ok(None) => RemovalOutcome::Gone,
200                    Ok(Some(now)) if now != *image_id => RemovalOutcome::Moved { now },
201                    Ok(Some(_)) => match docker::remove_image(&call, reference).await {
202                        Ok(()) => RemovalOutcome::Removed,
203                        Err(e) => failed(&e),
204                    },
205                    Err(e) => failed(&e),
206                }
207            }
208            DownloadItem::Box {
209                name,
210                provider,
211                version,
212                architecture,
213            } => {
214                let held = InstalledBox {
215                    name: name.clone(),
216                    provider: provider.clone(),
217                    version: version.clone(),
218                    architecture: architecture.clone(),
219                };
220                let call = self.call(self.config.processes.as_ref());
221                match vagrant::boxes(&call).await {
222                    Ok(boxes) if !boxes.contains(&held) => RemovalOutcome::Gone,
223                    Ok(_) => match vagrant::remove_box(&call, &held).await {
224                        Ok(()) => RemovalOutcome::Removed,
225                        Err(e) => failed(&e),
226                    },
227                    Err(e) => failed(&e),
228                }
229            }
230        }
231    }
232
233    /// `item`'s size on disk, when it can be read.
234    async fn size_of(&self, item: &DownloadItem) -> Option<u64> {
235        match item {
236            DownloadItem::Image { image_id, docker_context, .. } => {
237                let processes = self.docker(docker_context.as_deref());
238                docker::image_size(&self.call(&processes), image_id).await.ok().flatten()
239            }
240            DownloadItem::Box {
241                name,
242                provider,
243                version,
244                architecture,
245            } => {
246                let home = vagrant_home(&self.config.host_env)?;
247                let mut dir = home.join("boxes").join(name.replace('/', "-VAGRANTSLASH-")).join(version);
248                if let Some(arch) = architecture {
249                    dir.push(arch);
250                }
251                folder_size(&dir.join(provider))
252            }
253        }
254    }
255
256    /// The runner's processes, their `docker` calls sent to `context` when there is one.
257    pub(super) fn docker<'a>(&'a self, context: Option<&'a str>) -> DockerContext<'a> {
258        DockerContext {
259            inner: self.config.processes.as_ref(),
260            context,
261        }
262    }
263
264    /// A call of a tool through `processes`, in the home (no project's folder: Vagrant reads the
265    /// Vagrantfile of the folder it runs in), saying nothing.
266    pub(super) fn call<'a>(&'a self, processes: &'a dyn ProcessRunner) -> Call<'a> {
267        Call {
268            runner: processes,
269            cwd: Some(self.config.home.clone()),
270            env: Vec::new(),
271            limit: CALL_LIMIT,
272            sink: &crate::formats::discard,
273            host_env: &self.config.host_env,
274        }
275    }
276}
277
278/// Every recorded download ([`crate::store::Tx::downloads`]).
279fn recorded(tx: &crate::store::Tx<'_>) -> Result<Vec<Download>> {
280    tx.downloads()
281}
282
283/// Vagrant's own folder: `VAGRANT_HOME`, else `.vagrant.d` in the user's home (`HOME`, on Windows
284/// `USERPROFILE`).
285fn vagrant_home(env: &crate::host_env::HostEnv) -> Option<PathBuf> {
286    if let Some(home) = env.get("VAGRANT_HOME").filter(|h| !h.is_empty()) {
287        return Some(PathBuf::from(home));
288    }
289    ["HOME", "USERPROFILE"]
290        .into_iter()
291        .find_map(|name| env.get(name).filter(|h| !h.is_empty()))
292        .map(|home| Path::new(home).join(".vagrant.d"))
293}
294
295/// The size of every file under `dir`, links not followed; none when `dir` can't be read.
296fn folder_size(dir: &Path) -> Option<u64> {
297    let mut total = 0_u64;
298    for entry in std::fs::read_dir(dir).ok()? {
299        let entry = entry.ok()?;
300        let kind = entry.file_type().ok()?;
301        total = total.saturating_add(if kind.is_dir() {
302            folder_size(&entry.path())?
303        } else if kind.is_file() {
304            entry.metadata().ok()?.len()
305        } else {
306            0
307        });
308    }
309    Some(total)
310}
311
312#[cfg(test)]
313mod tests;