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