Skip to main content

isothrum_runner/
graphical.rs

1//! A machine's graphical console (its screen, keyboard and mouse), found where its manifest says
2//! (`machines[].consoles`): [`Console`], what [`crate::Running::graphical_console`] gives, and
3//! [`ConsoleOffer`], what a status says of each machine's.
4//!
5//! The runner guarantees where a console answers: a TCP port of this computer's loopback
6//! ([`Endpoint::Loopback`]), refusing one the hypervisor says listens anywhere else, opening an
7//! SSH tunnel to it when the manifest says so ([`tunnel`], held by the [`Console`]), or, for
8//! Proxmox VE, its API's own VNC websocket with a ticket for this session
9//! ([`Endpoint::ProxmoxVnc`]).
10//!
11//! - **libvirt**: `virsh domdisplay <domain>` ([`vagrant::libvirt`]).
12//! - **QEMU** (vagrant-qemu): `info vnc` on the VM's monitor socket ([`vagrant::qemu`]).
13//! - **VirtualBox**: `VBoxManage showvminfo --machinereadable` ([`vagrant::vrde`]).
14//! - **The runner's own** (VMware): the port and password it chose for the run, kept in the
15//!   run's `consoles.json` ([`chosen`]).
16//! - **Proxmox**: `vncproxy` over its API with `curl`, its credentials from a config file the
17//!   runner writes owner-only and removes ([`proxmox`]).
18//! - **An SSH tunnel**: `ssh -N -L 127.0.0.1:<port>:<host>:<port>` ([`tunnel`]).
19
20pub(crate) mod chosen;
21pub(crate) mod native;
22mod proxmox;
23mod tunnel;
24mod vagrant;
25
26use std::net::{IpAddr, Ipv4Addr, SocketAddr};
27
28use isoloom_manifest::{ConsoleProtocol, ConsoleSource, Machine, Provider};
29use serde::{Deserialize, Serialize};
30
31use crate::Result;
32use crate::error::Error;
33use crate::executor::Cx;
34use crate::secrets::SecretValue;
35
36pub use native::{NativeApp, NativeConsole, NativeNeed, NativeOpen};
37pub use proxmox::ProxmoxVnc;
38
39/// What a status says of a machine's graphical console under the run's provider: its protocol,
40/// or `none` and why ([`isoloom_manifest::Console`]'s, as the manifest says it).
41#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
42#[non_exhaustive]
43pub struct ConsoleOffer {
44    /// `vnc`, `rdp`, or `none`.
45    pub protocol: ConsoleProtocol,
46    /// Why there is none, or what it needs (an extension pack).
47    #[serde(default, skip_serializing_if = "Option::is_none")]
48    pub note: Option<String>,
49    /// Why it can't be shown now, as the status found it on a running machine: its hypervisor
50    /// gives it no display (a VM started without one), or it doesn't answer where the hypervisor
51    /// says. None when it answers, or wasn't looked at: the machine doesn't run, it has none, or
52    /// it is reached through an SSH tunnel or Proxmox's API, which a status doesn't open.
53    #[serde(default, skip_serializing_if = "Option::is_none")]
54    pub unavailable: Option<String>,
55}
56
57impl ConsoleOffer {
58    /// What `machine`'s manifest offers under `provider`: `None` when it says nothing (a
59    /// container, a manifest written before consoles were).
60    #[must_use]
61    pub(crate) fn of(machine: &Machine, provider: Option<Provider>) -> Option<ConsoleOffer> {
62        machine.console(provider).map(|c| ConsoleOffer {
63            protocol: c.protocol,
64            note: c.note.clone(),
65            unavailable: None,
66        })
67    }
68}
69
70/// Where a graphical console answers.
71#[derive(Debug, Clone, PartialEq, Eq)]
72#[non_exhaustive]
73pub enum Endpoint {
74    /// A TCP port of this computer's loopback speaking the console's protocol (VNC, RDP): the
75    /// hypervisor's own, or a tunnel's the [`Console`] holds.
76    Loopback(SocketAddr),
77    /// Proxmox VE's VNC websocket, through its API.
78    ProxmoxVnc(ProxmoxVnc),
79}
80
81/// A machine's graphical console the runner reached: where it answers, and how to sign in. A
82/// tunnel it opened lives as long as the console: drop it once the viewer is done.
83#[derive(Debug)]
84#[non_exhaustive]
85pub struct Console {
86    /// The machine.
87    pub machine: String,
88    /// The protocol it speaks: VNC or RDP.
89    pub protocol: ConsoleProtocol,
90    /// Where it answers.
91    pub endpoint: Endpoint,
92    /// The account to sign in as, when it signs in to the machine's own OS (RDP to Windows).
93    pub user: Option<String>,
94    /// Its password: the VNC password, or the account's. Never print or log it.
95    pub password: Option<SecretValue>,
96    /// What to know of it, as the manifest says (the extension pack VirtualBox's takes).
97    pub note: Option<String>,
98    /// The SSH tunnel it is reached through, while the console lives.
99    tunnel: Option<tunnel::Tunnel>,
100}
101
102impl Console {
103    /// A console of `machine` at `endpoint`, as `console` says.
104    fn new(machine: &Machine, console: &isoloom_manifest::Console, endpoint: Endpoint) -> Console {
105        Console {
106            machine: machine.name.to_string(),
107            protocol: console.protocol,
108            endpoint,
109            user: None,
110            password: None,
111            note: console.note.clone(),
112            tunnel: None,
113        }
114    }
115
116    /// Whether it is reached through an SSH tunnel the runner holds open.
117    #[must_use]
118    pub fn tunnelled(&self) -> bool {
119        self.tunnel.is_some()
120    }
121}
122
123/// The loopback address the runner's own listeners and tunnels take.
124pub(crate) const LOOPBACK: IpAddr = IpAddr::V4(Ipv4Addr::LOCALHOST);
125
126/// [`Error::NoConsole`] for `machine`, saying `why`.
127pub(crate) fn none(machine: &Machine, why: impl Into<String>) -> Error {
128    Error::NoConsole {
129        machine: machine.name.to_string(),
130        why: why.into(),
131    }
132}
133
134/// `machine`'s console under `provider`, as the manifest gives it; refused when it lists none or
135/// says it has none (why, its note).
136pub(crate) fn offered(machine: &Machine, provider: Option<Provider>) -> Result<&isoloom_manifest::Console> {
137    let Some(console) = machine.console(provider) else {
138        return Err(none(machine, "the run's manifest lists no graphical console for it"));
139    };
140    if console.protocol == ConsoleProtocol::None || console.source.is_none() {
141        return Err(none(machine, console.note.clone().unwrap_or_else(|| "it has none".to_owned())));
142    }
143    Ok(console)
144}
145
146/// `at`, when it is on this computer's loopback; refused otherwise, whatever the hypervisor says:
147/// the runner never hands out a console on the network.
148pub(crate) fn on_loopback(machine: &Machine, at: SocketAddr) -> Result<Endpoint> {
149    if at.ip().is_loopback() {
150        Ok(Endpoint::Loopback(at))
151    } else {
152        Err(none(
153            machine,
154            format!("its console listens on {at}, not on this computer's loopback: the runner refuses it"),
155        ))
156    }
157}
158
159/// How long a console on the loopback gets to accept a connection before it is said not to
160/// answer.
161const ANSWER_LIMIT: std::time::Duration = std::time::Duration::from_secs(2);
162
163/// `at`, once a connection to it is accepted within [`ANSWER_LIMIT`]; refused otherwise, saying
164/// where it didn't answer.
165async fn answering(cx: &Cx<'_>, machine: &Machine, at: SocketAddr) -> Result<Endpoint> {
166    let ports = &cx.run.runner.config.ports;
167    if ports.reachable(&at.ip().to_string(), at.port(), ANSWER_LIMIT).await {
168        Ok(Endpoint::Loopback(at))
169    } else {
170        Err(none(machine, format!("its screen didn't answer at {at}")))
171    }
172}
173
174/// Where the hypervisor of this computer says `machine`'s console `console` answers, with the
175/// password the runner chose for it, when the hypervisor keeps it (libvirt, QEMU, VirtualBox,
176/// the runner's own); `None` for one reached through Proxmox's API or an SSH tunnel.
177async fn local(cx: &Cx<'_>, machine: &Machine, console: &isoloom_manifest::Console) -> Option<Result<(SocketAddr, Option<SecretValue>)>> {
178    let at = |endpoint: Result<Endpoint>| match endpoint {
179        Ok(Endpoint::Loopback(at)) => Ok((at, None)),
180        Ok(Endpoint::ProxmoxVnc(_)) => Err(none(machine, "its hypervisor gives no port of this computer")),
181        Err(e) => Err(e),
182    };
183    Some(match console.source.as_ref()? {
184        ConsoleSource::Libvirt {} => at(vagrant::libvirt(cx, machine).await),
185        ConsoleSource::QemuMonitor {} => at(vagrant::qemu(cx, machine).await),
186        ConsoleSource::Vrde {} => at(vagrant::vrde(cx, machine).await),
187        ConsoleSource::Runner {} => chosen::of(cx, machine).map(|(port, password)| (SocketAddr::new(LOOPBACK, port), Some(password))),
188        ConsoleSource::ProxmoxApi { .. } | ConsoleSource::SshTunnel { .. } => return None,
189    })
190}
191
192/// Why `machine`'s console `console` (one [`offered`] gave) can't be shown now, the machine
193/// running: its hypervisor gives it no display, or it doesn't answer there. None when it answers,
194/// or is reached through Proxmox's API or an SSH tunnel, which this doesn't open.
195pub(crate) async fn unavailable(cx: &Cx<'_>, machine: &Machine, console: &isoloom_manifest::Console) -> Option<String> {
196    let found = match local(cx, machine, console).await? {
197        Ok((at, _)) => answering(cx, machine, at).await.map(drop),
198        Err(e) => Err(e),
199    };
200    match found {
201        Ok(()) => None,
202        Err(Error::NoConsole { why, .. }) => Some(why),
203        Err(e) => Some(e.to_string()),
204    }
205}
206
207/// Reaches `machine`'s console `console` (one [`offered`] gave), the machine running and the
208/// run's outputs bound in `cx`: one on the loopback only once it answers there.
209pub(crate) async fn reach(cx: &Cx<'_>, machine: &Machine, console: &isoloom_manifest::Console, outputs: &[crate::OutputValue]) -> Result<Console> {
210    let at = |field: &str| format!("machines.{}.consoles.source.{field}", machine.name);
211    if let Some(found) = local(cx, machine, console).await {
212        let (address, password) = found?;
213        let mut c = Console::new(machine, console, answering(cx, machine, address).await?);
214        c.password = password;
215        return with_account(cx, machine, console, outputs, c);
216    }
217    let reached = match console.source.as_ref() {
218        None => return Err(none(machine, "it has none")),
219        Some(ConsoleSource::Libvirt {} | ConsoleSource::QemuMonitor {} | ConsoleSource::Vrde {} | ConsoleSource::Runner {}) => {
220            return Err(none(machine, "its hypervisor didn't say where it is"));
221        }
222        Some(ConsoleSource::ProxmoxApi { .. }) => {
223            let vnc = proxmox::vnc(cx, machine, console).await?;
224            let mut c = Console::new(machine, console, Endpoint::ProxmoxVnc(vnc.clone()));
225            c.password = Some(vnc.ticket.clone());
226            c
227        }
228        Some(ConsoleSource::SshTunnel { via, user, host, port }) => {
229            let via = cx.vars.render(via, &at("via"))?;
230            let user = cx.vars.render(user, &at("user"))?;
231            let host = cx.vars.render(host, &at("host"))?;
232            let open = tunnel::open(cx, machine, &tunnel::To { via, user, host, port: *port }).await?;
233            let mut c = Console::new(machine, console, Endpoint::Loopback(open.local));
234            c.tunnel = Some(open);
235            c
236        }
237    };
238    with_account(cx, machine, console, outputs, reached)
239}
240
241/// `reached` with the account `console` signs in as, when it names one.
242fn with_account(cx: &Cx<'_>, machine: &Machine, console: &isoloom_manifest::Console, outputs: &[crate::OutputValue], mut reached: Console) -> Result<Console> {
243    let at = |field: &str| format!("machines.{}.consoles.source.{field}", machine.name);
244    if let Some(account) = &console.account {
245        reached.user = Some(cx.vars.render(&account.user, &at("account.user"))?);
246        reached.password = Some(SecretValue::new(revealed(cx, &account.password, outputs, &at("account.password"))?));
247    }
248    Ok(reached)
249}
250
251/// Where a tunnel goes, for the run's tests.
252#[cfg(test)]
253pub(crate) fn tunnel_to_for_tests(via: &str, user: &str, host: &str, port: u16) -> tunnel::To {
254    tunnel::To {
255        via: via.into(),
256        user: user.into(),
257        host: host.into(),
258        port,
259    }
260}
261
262/// A tunnel's `ssh`, for the run's tests.
263#[cfg(test)]
264pub(crate) fn tunnel_spec_for_tests(cx: &Cx<'_>, to: &tunnel::To, local: u16) -> Result<crate::process::ProcessSpec> {
265    tunnel::spec(cx, to, local)
266}
267
268/// `template` filled, a sensitive output it is alone made of revealed (one a template is never
269/// otherwise given: a password the viewer signs in with).
270fn revealed(cx: &Cx<'_>, template: &isoloom_manifest::Template, outputs: &[crate::OutputValue], at: &str) -> Result<String> {
271    if let [isoloom_manifest::Part::Placeholder(isoloom_manifest::Placeholder::Output(name))] = template.parts()
272        && let Some(value) = outputs.iter().find(|o| o.name == name.as_str()).and_then(crate::OutputValue::revealed)
273    {
274        return Ok(value.to_owned());
275    }
276    cx.vars.render(template, at)
277}
278
279#[cfg(test)]
280mod tests {
281    use super::*;
282
283    fn machine(consoles: &serde_json::Value) -> Machine {
284        serde_json::from_value(serde_json::json!({ "name": "web", "role": "member", "addresses": {}, "consoles": consoles })).unwrap()
285    }
286
287    #[test]
288    fn a_machine_offers_its_providers_console_or_says_why_not() {
289        let m = machine(&serde_json::json!([
290            { "providers": ["libvirt"], "protocol": "vnc", "source": { "from": "libvirt" } },
291            { "providers": ["parallels"], "protocol": "none", "note": "no console set up" },
292        ]));
293        assert_eq!(offered(&m, Some(Provider::Libvirt)).unwrap().protocol, ConsoleProtocol::Vnc);
294        let parallels = offered(&m, Some(Provider::Parallels)).unwrap_err();
295        assert_eq!(
296            (parallels.code(), parallels.to_string()),
297            (
298                crate::ErrorCode::NoConsole,
299                "machine `web` has no graphical console: no console set up".to_owned()
300            )
301        );
302        let other = offered(&m, Some(Provider::Hyperv)).unwrap_err();
303        assert!(other.to_string().ends_with("the run's manifest lists no graphical console for it"), "{other}");
304        assert_eq!(
305            ConsoleOffer::of(&m, Some(Provider::Parallels)),
306            Some(ConsoleOffer {
307                protocol: ConsoleProtocol::None,
308                note: Some("no console set up".into()),
309                unavailable: None,
310            })
311        );
312        assert_eq!(ConsoleOffer::of(&machine(&serde_json::json!([])), None), None, "a container says nothing");
313    }
314
315    #[test]
316    fn a_console_off_the_loopback_is_refused() {
317        let m = machine(&serde_json::json!([]));
318        assert!(matches!(on_loopback(&m, "127.0.0.1:5900".parse().unwrap()), Ok(Endpoint::Loopback(_))));
319        assert!(matches!(on_loopback(&m, "[::1]:5900".parse().unwrap()), Ok(Endpoint::Loopback(_))));
320        for lan in ["0.0.0.0:5900", "192.168.1.20:5900", "[::]:5900"] {
321            let err = on_loopback(&m, lan.parse().unwrap()).unwrap_err();
322            assert_eq!(err.code(), crate::ErrorCode::NoConsole, "{lan}");
323            assert!(err.to_string().contains("not on this computer's loopback"), "{err}");
324        }
325    }
326}