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;
38pub(crate) use proxmox::vm_states as proxmox_vm_states;
39
40#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
43#[non_exhaustive]
44pub struct ConsoleOffer {
45 pub protocol: ConsoleProtocol,
47 #[serde(default, skip_serializing_if = "Option::is_none")]
49 pub note: Option<String>,
50 #[serde(default, skip_serializing_if = "Option::is_none")]
55 pub unavailable: Option<String>,
56}
57
58impl ConsoleOffer {
59 #[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#[derive(Debug, Clone, PartialEq, Eq)]
73#[non_exhaustive]
74pub enum Endpoint {
75 Loopback(SocketAddr),
78 ProxmoxVnc(ProxmoxVnc),
80}
81
82#[derive(Debug)]
85#[non_exhaustive]
86pub struct Console {
87 pub machine: String,
89 pub protocol: ConsoleProtocol,
91 pub endpoint: Endpoint,
93 pub user: Option<String>,
95 pub password: Option<SecretValue>,
97 pub note: Option<String>,
99 tunnel: Option<tunnel::Tunnel>,
101}
102
103impl Console {
104 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 #[must_use]
119 pub fn tunnelled(&self) -> bool {
120 self.tunnel.is_some()
121 }
122}
123
124pub(crate) const LOOPBACK: IpAddr = IpAddr::V4(Ipv4Addr::LOCALHOST);
126
127pub(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
135pub(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
147pub(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
160const ANSWER_LIMIT: std::time::Duration = std::time::Duration::from_secs(2);
163
164async 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
175async 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
193pub(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
208pub(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
242fn 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#[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#[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
269fn 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}