use std::path::PathBuf;
use isoloom_manifest::{ConsoleSource, Driver, HostOs, Machine, Provider};
use serde::{Deserialize, Serialize};
use super::{none, vagrant};
use crate::Result;
use crate::error::Error;
use crate::executor::{Cx, Echo, call};
use crate::process::ProcessSpec;
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[serde(rename_all = "snake_case", tag = "kind", content = "at")]
#[non_exhaustive]
pub enum NativeNeed {
Program(String),
MacApp(PathBuf),
Browser,
}
#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, schemars::JsonSchema)]
#[non_exhaustive]
pub struct NativeApp {
pub name: String,
pub needs: Vec<NativeNeed>,
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub enum NativeOpen {
Program {
program: String,
args: Vec<String>,
},
MacApp {
app: PathBuf,
args: Vec<String>,
},
Url {
url: String,
},
}
impl NativeOpen {
#[must_use]
pub fn need(&self) -> NativeNeed {
match self {
NativeOpen::Program { program, .. } => NativeNeed::Program(program.clone()),
NativeOpen::MacApp { app, .. } => NativeNeed::MacApp(app.clone()),
NativeOpen::Url { .. } => NativeNeed::Browser,
}
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
#[non_exhaustive]
pub struct NativeConsole {
pub machine: String,
pub app: String,
pub ways: Vec<NativeOpen>,
}
const WORKSTATION_WINDOWS: [&str; 2] = [
r"C:\Program Files (x86)\VMware\VMware Workstation\vmware.exe",
r"C:\Program Files\VMware\VMware Workstation\vmware.exe",
];
const FUSION: &str = "/Applications/VMware Fusion.app";
const PARALLELS: &str = "/Applications/Parallels Desktop.app";
const UTM: &str = "/Applications/UTM.app";
pub(crate) fn app(manifest: &isoloom_manifest::Manifest, provider: Option<Provider>, host: HostOs) -> Option<NativeApp> {
let program = |p: &str| NativeNeed::Program(p.to_owned());
let mac = |p: &str| NativeNeed::MacApp(PathBuf::from(p));
let (name, needs) = match (manifest.driver, provider) {
(Driver::Vagrant, Some(Provider::Virtualbox)) => ("VirtualBox", vec![program("VBoxManage")]),
(Driver::Vagrant, Some(Provider::Hyperv)) => ("Hyper-V", vec![program("vmconnect.exe")]),
(Driver::Vagrant, Some(Provider::Libvirt)) => ("virt-viewer", vec![program("virt-viewer"), program("remote-viewer")]),
(Driver::Vagrant, Some(Provider::VmwareDesktop)) => match host {
HostOs::Macos => ("VMware Fusion", vec![mac(FUSION)]),
HostOs::Windows => ("VMware Workstation", WORKSTATION_WINDOWS.iter().map(|p| program(p)).collect()),
HostOs::Linux => ("VMware Workstation", vec![program("vmware")]),
},
(Driver::Vagrant, Some(Provider::Parallels)) => ("Parallels Desktop", vec![mac(PARALLELS)]),
(Driver::Vagrant, Some(Provider::Utm)) => ("UTM", vec![mac(UTM)]),
(Driver::Vagrant, Some(Provider::VmwareEsxi)) => ("ESXi", vec![NativeNeed::Browser]),
(Driver::Terraform, _) if manifest.machines.iter().any(proxmox) => ("Proxmox VE", vec![NativeNeed::Browser]),
_ => return None,
};
Some(NativeApp { name: name.to_owned(), needs })
}
fn proxmox(m: &Machine) -> bool {
m.consoles.iter().any(|c| matches!(c.source, Some(ConsoleSource::ProxmoxApi { .. })))
}
pub(crate) async fn console(cx: &Cx<'_>, machine: &Machine, app: &NativeApp) -> Result<NativeConsole> {
let provider = cx.scope.provider;
let ways = match provider {
_ if cx.run.manifest().driver == Driver::Terraform => vec![proxmox_url(cx, machine)?],
Some(Provider::Virtualbox) => {
let vm = argument(machine, vagrant::vm_name(machine, Provider::Virtualbox)?)?;
vec![program("VBoxManage", ["startvm", vm, "--type", "separate"])]
}
Some(Provider::Hyperv) => vec![program(
"vmconnect.exe",
["localhost", argument(machine, vagrant::vm_name(machine, Provider::Hyperv)?)?],
)],
Some(Provider::Libvirt) => libvirt(cx, machine).await?,
Some(Provider::VmwareDesktop) => {
let vmx = recorded(cx, machine, "vmware_desktop")?;
let vmx = argument(machine, &vmx)?.to_owned();
app.needs
.iter()
.filter_map(|need| match need {
NativeNeed::MacApp(bundle) => Some(NativeOpen::MacApp {
app: bundle.clone(),
args: vec![vmx.clone()],
}),
NativeNeed::Program(p) => Some(program(p, [vmx.as_str()])),
NativeNeed::Browser => None,
})
.collect()
}
Some(Provider::Parallels) => vec![NativeOpen::MacApp {
app: PathBuf::from(PARALLELS),
args: vec![parallels_bundle(cx, machine).await?],
}],
Some(Provider::Utm) => {
let vm = argument(machine, vagrant::vm_name(machine, Provider::Utm)?)?;
vec![NativeOpen::MacApp {
app: PathBuf::from(UTM),
args: vec![format!("utm://start?name={}", percent(vm))],
}]
}
Some(Provider::VmwareEsxi) => vec![esxi_url(cx, machine)?],
Some(Provider::Qemu) | None => return Err(no_app(machine)),
};
Ok(NativeConsole {
machine: machine.name.to_string(),
app: app.name.clone(),
ways,
})
}
fn program<'a>(program: &str, args: impl IntoIterator<Item = &'a str>) -> NativeOpen {
NativeOpen::Program {
program: program.to_owned(),
args: args.into_iter().map(str::to_owned).collect(),
}
}
fn argument<'a>(machine: &Machine, value: &'a str) -> Result<&'a str> {
if value.trim().is_empty() || value.starts_with('-') || value.chars().any(char::is_control) {
return Err(none(
machine,
format!("its VM's name or file `{}` can't be handed to its app", value.escape_debug()),
));
}
Ok(value)
}
fn recorded(cx: &Cx<'_>, machine: &Machine, provider_dir: &str) -> Result<String> {
let path = vagrant::dotfile(cx)?
.join("machines")
.join(vagrant::define(machine)?)
.join(provider_dir)
.join("id");
vagrant::read_if_there(&path)?
.map(|s| s.trim().to_owned())
.filter(|s| !s.is_empty())
.ok_or_else(|| none(machine, "Vagrant records no VM for it: it isn't up"))
}
async fn libvirt(cx: &Cx<'_>, machine: &Machine) -> Result<Vec<NativeOpen>> {
let domain = argument(machine, vagrant::vm_name(machine, Provider::Libvirt)?)?;
let uri = vagrant::libvirt_uri(&cx.run.runner.config.host_env);
let mut ways = vec![program("virt-viewer", ["--connect", argument(machine, &uri)?, domain])];
if let Ok(super::Endpoint::Loopback(at)) = vagrant::libvirt(cx, machine).await {
let display = at.port().saturating_sub(5900);
ways.push(program("remote-viewer", [format!("vnc://{}:{display}", at.ip()).as_str()]));
}
Ok(ways)
}
async fn parallels_bundle(cx: &Cx<'_>, machine: &Machine) -> Result<String> {
let uuid = recorded(cx, machine, "parallels")?;
let uuid = argument(machine, &uuid)?;
let spec = ProcessSpec::new("prlctl", ["list", "--info", "--json", uuid]);
let out = call(cx, "console", &spec, std::time::Duration::from_secs(30), Echo::Quiet).await?;
if !out.success() {
return Err(none(machine, format!("Parallels didn't say where its VM is: {}", out.reason())));
}
let said: serde_json::Value = serde_json::from_str(&out.stdout.join("\n")).unwrap_or_default();
let home = said
.as_array()
.and_then(|vms| vms.first())
.and_then(|vm| vm.get("Home"))
.and_then(serde_json::Value::as_str)
.ok_or_else(|| none(machine, "Parallels didn't say where its VM is"))?;
Ok(argument(machine, home.trim_end_matches('/'))?.to_owned())
}
fn esxi_url(cx: &Cx<'_>, machine: &Machine) -> Result<NativeOpen> {
let host = cx
.vars
.params()
.get(isoloom_manifest::contract::ESXI_HOSTNAME)
.filter(|h| host_name(h))
.ok_or_else(|| none(machine, "the run names no ESXi host"))?;
let id = recorded(cx, machine, "vmware_esxi")?;
if !id.chars().all(|c| c.is_ascii_digit()) {
return Err(none(machine, format!("its ESXi VM id `{}` isn't one", id.escape_debug())));
}
Ok(NativeOpen::Url {
url: format!("https://{host}/ui/#/console/{id}"),
})
}
fn proxmox_url(cx: &Cx<'_>, machine: &Machine) -> Result<NativeOpen> {
let Some(ConsoleSource::ProxmoxApi { endpoint, node, vm_id, .. }) = machine
.consoles
.iter()
.find_map(|c| c.source.as_ref().filter(|s| matches!(s, ConsoleSource::ProxmoxApi { .. })))
else {
return Err(none(machine, "it isn't a Proxmox VE VM"));
};
let at = |field: &str| format!("machines.{}.consoles.source.{field}", machine.name);
let endpoint = cx.vars.render(endpoint, &at("endpoint"))?;
let node = cx.vars.render(node, &at("node"))?;
let vm_id = cx.vars.render(vm_id, &at("vm_id"))?;
let base = endpoint.trim_end_matches('/');
let server = base.strip_prefix("https://").filter(|s| host_name(s.split(':').next().unwrap_or_default()));
let port_ok = base
.split_once("://")
.and_then(|(_, rest)| rest.split_once(':'))
.is_none_or(|(_, p)| p.parse::<u16>().is_ok());
if server.is_none() || !port_ok {
return Err(none(
machine,
format!("its Proxmox VE address `{}` isn't an https server", endpoint.escape_debug()),
));
}
if !vm_id.chars().all(|c| c.is_ascii_digit()) || vm_id.is_empty() || !host_name(&node) {
return Err(none(machine, "its Proxmox VE node or VM id isn't one"));
}
Ok(NativeOpen::Url {
url: format!("{base}/?console=kvm&novnc=1&vmid={vm_id}&node={node}"),
})
}
fn host_name(h: &str) -> bool {
!h.is_empty() && h.len() <= 253 && h.chars().all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '.') && !h.starts_with('-')
}
fn percent(s: &str) -> String {
s.bytes()
.map(|b| match b {
b'A'..=b'Z' | b'a'..=b'z' | b'0'..=b'9' | b'-' | b'.' | b'_' | b'~' => char::from(b).to_string(),
other => format!("%{other:02X}"),
})
.collect()
}
pub(crate) fn no_app(machine: &Machine) -> Error {
none(machine, "its hypervisor has no app of its own to show it in")
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn an_argument_that_could_be_read_as_more_is_refused() {
let m: Machine = serde_json::from_value(serde_json::json!({ "name": "web", "role": "member", "addresses": {} })).unwrap();
assert_eq!(argument(&m, "web-vm - web").unwrap(), "web-vm - web");
for bad in ["", " ", "--type=gui", "a\nb", "a\u{0}b"] {
assert!(argument(&m, bad).is_err(), "{bad:?}");
}
}
#[test]
fn a_host_name_is_only_a_name() {
assert!(host_name("172.16.1.20") && host_name("pve.lab.example"));
for bad in ["", "-x", "a b", "user@host", "host/path", "host?q", "host#x", "h:1"] {
assert!(!host_name(bad), "{bad}");
}
}
#[test]
fn a_name_in_a_link_is_percent_encoded() {
assert_eq!(percent("web-vm - web"), "web-vm%20-%20web");
assert_eq!(percent("a&b=c"), "a%26b%3Dc");
}
}