Skip to main content

isothrum_runner/run/
processes.rs

1//! The tools of a run: an operation's recorded in the run's state folder (and elevated where its
2//! hypervisor needs it), every `docker` call of the run sent to its Docker context, and what the
3//! store keeps of what they did: the resources they made, what their downloads fetched.
4
5use std::sync::Arc;
6
7use super::Running;
8use crate::Result;
9use crate::options::RunOptions;
10use crate::process::ProcessRunner;
11
12impl<'r> Running<'r> {
13    /// The same run, every operation of this handle sharing one elevation where its hypervisor
14    /// needs one (Hyper-V on Windows): one administrator prompt for an `up` and the `exec` after
15    /// it, say, instead of one per operation. The elevated session ends when the handle drops.
16    #[must_use]
17    pub fn sharing_elevation(self) -> Running<'r> {
18        Running {
19            elevation: Some(std::sync::OnceLock::new()),
20            ..self
21        }
22    }
23
24    /// The process runner of an operation: its tools recorded in the run's state folder while they
25    /// run, so a killed operation's are ended by the next ([`crate::process::ledger`]); elevated
26    /// where its hypervisor needs it, in a session of its own or in the one every operation of a
27    /// handle [sharing its elevation](Running::sharing_elevation) shares.
28    pub(super) fn operation_processes(&self, opts: &RunOptions) -> Arc<dyn ProcessRunner> {
29        let tools = self.state_dir().join(crate::process::ledger::DIR);
30        let operation = self.runner.operation_of(&self.name);
31        let base = Arc::clone(&self.runner.config.processes);
32        let windows = self.runner.config.host == crate::project::platform::HostOs::Windows;
33        if !(windows && self.driver.elevates(self.provider(opts))) {
34            return Arc::new(crate::process::Recording::new(base, tools, operation));
35        }
36        let elevated = |inner: Arc<dyn ProcessRunner>| -> Arc<dyn ProcessRunner> {
37            let env = self.runner.config.host_env.for_elevation();
38            Arc::new(crate::process::Elevated::new(inner, self.state_dir().join("elevated"), env))
39        };
40        match &self.elevation {
41            // The shared session under each operation's recording, which only adds its variables.
42            Some(shared) => Arc::new(crate::process::Recording::new(
43                Arc::clone(shared.get_or_init(|| elevated(base))),
44                tools,
45                operation,
46            )),
47            None => elevated(Arc::new(crate::process::Recording::new(base, tools, operation))),
48        }
49    }
50
51    /// The Docker context the run's `docker` calls go to: the one `opts` names, else the one its
52    /// start recorded (a `down` names none, and must reach the engine its start used).
53    pub(super) fn docker_context(&self, opts: &RunOptions) -> Option<String> {
54        opts.docker_context
55            .clone()
56            .or_else(|| self.runner.store.record(&self.name).ok().flatten()?.docker_context)
57    }
58
59    /// Records that the run's tool fetched `item` (an image through Docker context `context`,
60    /// when the run names one). One the store can't record is said in the runner's log only: the
61    /// operation goes on, and the download is never removed as the runner's.
62    pub(super) fn record_fetched(&self, item: crate::DownloadItem, context: Option<&str>) {
63        let item = match item {
64            crate::DownloadItem::Image { reference, image_id, .. } => crate::DownloadItem::Image {
65                reference,
66                image_id,
67                docker_context: context.map(str::to_owned),
68            },
69            other @ crate::DownloadItem::Box { .. } => other,
70        };
71        match self.runner.store.db().write(|tx| tx.record_download(Some(&self.name), &item)) {
72            Ok(_) => tracing::info!(run = %self.name, ?item, "recorded what the run's download fetched"),
73            Err(e) => tracing::warn!(run = %self.name, ?item, error = %e, "what the run's download fetched wasn't recorded"),
74        }
75    }
76
77    /// The keys of the run's resources the store records as made by its tool: the provider's,
78    /// with their id, not gone.
79    pub(super) fn made(&self) -> Result<Vec<String>> {
80        let rows = self.runner.store.db().read(|tx| tx.live_resources(&self.name))?;
81        Ok(rows
82            .into_iter()
83            .filter(|r| r.scope == crate::store::Scope::Provider && r.native_id.is_some())
84            .map(|r| r.key)
85            .collect())
86    }
87}
88
89#[cfg(test)]
90mod tests {
91    use std::sync::Arc;
92
93    use crate::process::ProcessSpec;
94    use crate::process::fake::{FakeProcesses, Reply};
95    use crate::project::platform::{HostOs, Provider};
96    use crate::testing::{no_ports, processes, runner_config};
97    use crate::{RunName, RunOptions, Runner};
98
99    /// How many times an account's rights to manage Hyper-V were asked, after two operations'
100    /// `vagrant status` on a Hyper-V run of a Windows runner, the handle sharing its elevation or
101    /// not: each elevated session asks once.
102    async fn sessions(share: bool) -> usize {
103        let fake = Arc::new(
104            FakeProcesses::script()
105                .allow(
106                    "whoami /groups",
107                    Reply::ok("\"BUILTIN\\Hyper-V Administrators\",\"Alias\",\"S-1-5-32-578\",\"Enabled group\""),
108                )
109                .allow("vagrant status", Reply::ok(""))
110                .build(),
111        );
112        let root = tempfile::tempdir().expect("a folder");
113        let project = root.path().join("stack");
114        std::fs::create_dir(&project).expect("the project");
115        std::fs::write(project.join("Vagrantfile"), "Vagrant.configure(\"2\") do |config| end\n").expect("its file");
116        let config = runner_config(&root.path().join("home"), processes(&fake), no_ports(), HostOs::Windows);
117        let runner = Runner::new(config).expect("a runner");
118        let run = runner.open(&project, Some(RunName::new("vm").expect("a name"))).expect("opened");
119        let run = if share { run.sharing_elevation() } else { run };
120        let opts = RunOptions::new().with_provider(Provider::Hyperv);
121        for _ in 0..2 {
122            let ran = run
123                .operation_processes(&opts)
124                .run(&ProcessSpec::new("vagrant", ["status"]), &mut |_, _| {})
125                .await;
126            assert!(ran.expect("ran").success());
127        }
128        fake.lines().iter().filter(|l| l.starts_with("whoami")).count()
129    }
130
131    #[tokio::test]
132    async fn a_handle_sharing_its_elevation_opens_one_session_for_all_its_operations() {
133        assert_eq!(sessions(false).await, 2, "one session per operation");
134        assert_eq!(sessions(true).await, 1, "one for the handle");
135    }
136}