Skip to main content

isothrum_runner/run/
graphical.rs

1//! A machine's graphical console, found where its hypervisor keeps it through the run's driver,
2//! reached on this computer's loopback (or Proxmox's API), for the embedder's viewer; and what
3//! opens it in the hypervisor's own app.
4
5use std::time::Duration;
6
7use super::Running;
8use crate::Result;
9use crate::events::Emitter;
10use crate::formats::{Seen, ToolCx};
11use crate::graphical::{Console, ConsoleOffer, Endpoint, NativeConsole, no_console, on_loopback};
12use crate::options::RunOptions;
13use crate::status::MachineState;
14
15/// How long a console on the loopback gets to accept a connection before it is said not to
16/// answer.
17const ANSWER_LIMIT: Duration = Duration::from_secs(2);
18
19impl Running<'_> {
20    /// What a status says of each machine `seen` has, in its order: a console its driver can't
21    /// say anything of is none, traced.
22    pub(super) async fn screens(&self, cx: &ToolCx<'_>, seen: &Seen) -> Vec<Option<ConsoleOffer>> {
23        let mut out = Vec::with_capacity(seen.machines.len());
24        for m in &seen.machines {
25            out.push(self.driver.graphical(cx, seen, m).await.unwrap_or_else(|e| {
26                tracing::debug!(machine = %m.name, error = %e, "the machine's console couldn't be said");
27                None
28            }));
29        }
30        out
31    }
32
33    /// `machine`'s graphical console (its screen), where its hypervisor keeps it: its protocol
34    /// (VNC or RDP), where it answers ([`crate::Endpoint`]: a port of this computer's loopback, or
35    /// Proxmox's VNC websocket) and the account and password that sign in. A console that
36    /// answers only on the run's own networks (a module's Windows VM's Remote Desktop) is reached
37    /// through an SSH tunnel to the machine beside it the driver names: `ssh -N -L
38    /// 127.0.0.1:<free port>:<its address>:<its port>`, signed in with the run's key (its
39    /// `ssh_private_key_file`, else the runner's) and checked against the host key the run
40    /// pinned the first time it met that machine. The returned [`Console`] owns the tunnel
41    /// ([`Console::tunnel`]): keep it while the viewer shows the screen; dropping it ends the
42    /// tunnel, and so does a `down` of the run. A console the hypervisor says
43    /// listens anywhere but the loopback is refused, and so is one on the loopback that doesn't
44    /// answer. `opts` gives what the tools get (a Proxmox server's address and credentials, as
45    /// its provider reads them). Emits nothing and never locks the run; while an operation holds
46    /// it, the hypervisor is asked all the same.
47    ///
48    /// # Errors
49    ///
50    /// `machine_unknown` for a machine the run doesn't have; `no_console` when it has none (the
51    /// error says why: a hypervisor whose screen opens only in its own app, VirtualBox without
52    /// its extension pack…), isn't running, its hypervisor doesn't say where its console is or
53    /// started it without one, or it doesn't answer there; `server_auth_failed` when Proxmox
54    /// refuses the run's credentials; a tool's own failure (`tool_missing` for a missing `virsh`,
55    /// `VBoxManage`, `curl`, `ssh` or `ssh-keyscan`); `tool_failed` when the machine a tunnel goes
56    /// through gives no SSH host key to pin.
57    pub async fn graphical_console(&self, machine: &str, opts: &RunOptions) -> Result<Console> {
58        let mut console = self
59            .query(opts, async |cx: &ToolCx<'_>| {
60                self.running_now(cx, machine).await?;
61                self.driver.reach_graphical(cx, machine).await
62            })
63            .await?;
64        if let Some(to) = console.through.take() {
65            let tunnel = crate::graphical::tunnel::open(
66                self.runner,
67                &self.name,
68                &self.state_dir(),
69                crate::graphical::tunnel::Purpose::Console(machine),
70                &to,
71            )
72            .await?;
73            console.endpoint = Endpoint::Loopback(tunnel.local());
74            console.tunnel = Some(tunnel);
75        }
76        if let Endpoint::Loopback(at) = &console.endpoint {
77            let at = on_loopback(machine, *at)?;
78            if !self.runner.config.ports.reachable(&at.ip().to_string(), at.port(), ANSWER_LIMIT).await {
79                return Err(no_console(machine, format!("its screen didn't answer at {at}")));
80            }
81        }
82        Ok(console)
83    }
84
85    /// What opens running VM `machine` in its hypervisor's own app, beside the embedder's viewer
86    /// ([`crate::Status::native`] names the app): a program and its arguments, a macOS app and
87    /// what it opens, or an `https` URL, best first, each argument checked; the embedder runs the
88    /// first this computer has, never through a shell. Reads as [`Running::graphical_console`]
89    /// does, and runs nothing but a read (Parallels' `prlctl`, UTM's `utmctl`, libvirt's `virsh`).
90    ///
91    /// # Errors
92    ///
93    /// `machine_unknown` for a machine the run doesn't have; `no_console` when its hypervisor has
94    /// no app (QEMU, ESXi, a container), it isn't running, or what names it can't be handed to
95    /// the app as it is.
96    pub async fn native_console(&self, machine: &str, opts: &RunOptions) -> Result<NativeConsole> {
97        self.query(opts, async |cx: &ToolCx<'_>| {
98            self.running_now(cx, machine).await?;
99            self.driver.native_console(cx, machine).await
100        })
101        .await
102    }
103
104    /// Runs `work` with a silent tool context of this run (nothing emitted, nothing locked).
105    async fn query<T>(&self, opts: &RunOptions, work: impl AsyncFnOnce(&ToolCx<'_>) -> Result<T>) -> Result<T> {
106        let emitter = Emitter::silent(self.name.as_str(), self.runner.config.clock.as_ref());
107        self.with_cx(opts, &emitter, self.runner.config.processes.as_ref(), work).await
108    }
109
110    /// Refuses `machine` unless the run has it running, as its tool says now; while an operation
111    /// holds the run its tool isn't asked (it would contend with it), and the hypervisor answers
112    /// for itself.
113    async fn running_now(&self, cx: &ToolCx<'_>, machine: &str) -> Result<()> {
114        let recorded = self.runner.store.record(&self.name)?.map_or(crate::state::RunState::Absent, |r| r.state);
115        if self.held(recorded)? {
116            return Ok(());
117        }
118        let (seen, _) = self.driver.observe(cx).await?;
119        let Some(found) = seen.machines.iter().find(|m| m.name == machine) else {
120            return Err(crate::error::Error::MachineUnknown {
121                run: self.name.to_string(),
122                machine: machine.to_owned(),
123            });
124        };
125        match &found.state {
126            MachineState::Busy => Err(no_console(
127                machine,
128                "another process is acting on it (starting or provisioning it): its screen can be shown once that is done",
129            )),
130            s if s.runs() => Ok(()),
131            s => Err(no_console(machine, format!("it isn't running ({s})"))),
132        }
133    }
134}