1pub(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#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
42#[non_exhaustive]
43pub struct ConsoleOffer {
44 pub protocol: ConsoleProtocol,
46 #[serde(default, skip_serializing_if = "Option::is_none")]
48 pub note: Option<String>,
49 #[serde(default, skip_serializing_if = "Option::is_none")]
54 pub unavailable: Option<String>,
55}
56
57impl ConsoleOffer {
58 #[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#[derive(Debug, Clone, PartialEq, Eq)]
72#[non_exhaustive]
73pub enum Endpoint {
74 Loopback(SocketAddr),
77 ProxmoxVnc(ProxmoxVnc),
79}
80
81#[derive(Debug)]
84#[non_exhaustive]
85pub struct Console {
86 pub machine: String,
88 pub protocol: ConsoleProtocol,
90 pub endpoint: Endpoint,
92 pub user: Option<String>,
94 pub password: Option<SecretValue>,
96 pub note: Option<String>,
98 tunnel: Option<tunnel::Tunnel>,
100}
101
102impl Console {
103 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 #[must_use]
118 pub fn tunnelled(&self) -> bool {
119 self.tunnel.is_some()
120 }
121}
122
123pub(crate) const LOOPBACK: IpAddr = IpAddr::V4(Ipv4Addr::LOCALHOST);
125
126pub(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
134pub(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
146pub(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
159const ANSWER_LIMIT: std::time::Duration = std::time::Duration::from_secs(2);
162
163async 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
174async 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
192pub(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
207pub(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
241fn 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#[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#[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
268fn 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}