Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions Cargo.lock
Original file line number Diff line number Diff line change
Expand Up @@ -5176,6 +5176,7 @@ dependencies = [
"fs-err",
"futures",
"futures-concurrency",
"guid",
"inspect",
"kmsg",
"mesh",
Expand Down
50 changes: 29 additions & 21 deletions openhcl/diag_client/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -50,6 +50,8 @@ pub mod hyperv {
pub enum ComPortAccessInfo<'a> {
/// Access by number
NameAndPortNumber(&'a str, u32),
/// Access by VM ID and port number
IdAndPortNumber(Guid, u32),
/// Access through a named pipe
PortPipePath(&'a str),
}
Expand Down Expand Up @@ -109,6 +111,32 @@ pub mod hyperv {
Ok(socket.convert().into_inner())
}

fn query_vm_com_port(port: ComPortAccessInfo<'_>) -> anyhow::Result<String> {
let script = match port {
ComPortAccessInfo::NameAndPortNumber(vm, num) => {
format!(r#"$x = Get-VMComPort "{vm}" -Number {num} -ErrorAction Stop; $x.Path"#)
}
ComPortAccessInfo::IdAndPortNumber(id, num) => {
format!(
r#"$x = Get-VMComPort -VMId "{id}" -Number {num} -ErrorAction Stop; $x.Path"#
)
}
ComPortAccessInfo::PortPipePath(path) => return Ok(path.to_owned()),
};

let output = Command::new("powershell.exe")
.arg("-NoProfile")
.arg(&script)
.output()
.context("failed to query VM com port")?;
Comment on lines +115 to +131

if !output.status.success() {
let _ = std::io::stderr().write_all(&output.stderr);
anyhow::bail!("failed to query VM com port: exit status {}", output.status);
}
Ok(String::from_utf8(output.stdout)?)
}

/// Opens a serial port on a Hyper-V VM.
///
/// If the VM is not running, it will periodically try to connect to the
Expand All @@ -121,27 +149,7 @@ pub mod hyperv {
driver: &(impl Driver + ?Sized),
port: ComPortAccessInfo<'_>,
) -> anyhow::Result<File> {
let path = match port {
ComPortAccessInfo::NameAndPortNumber(vm, num) => {
let output = Command::new("powershell.exe")
.arg("-NoProfile")
.arg(format!(
r#"$x = Get-VMComPort "{vm}" -Number {num} -ErrorAction Stop; $x.Path"#,
))
.output()
.context("failed to query VM com port")?;

if !output.status.success() {
let _ = std::io::stderr().write_all(&output.stderr);
anyhow::bail!(
"failed to query VM com port: exit status {}",
output.status.code().unwrap()
);
}
&String::from_utf8(output.stdout)?
}
ComPortAccessInfo::PortPipePath(path) => path,
};
let path = query_vm_com_port(port)?;

let path = path.trim();
if path.is_empty() {
Expand Down
1 change: 1 addition & 0 deletions openhcl/ohcldiag-dev/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -27,6 +27,7 @@ tracing-subscriber = { workspace = true, features = ["env-filter"] }
unicycle.workspace = true

[target.'cfg(windows)'.dependencies]
guid.workspace = true
pal.workspace = true
socket2.workspace = true

Expand Down
56 changes: 45 additions & 11 deletions openhcl/ohcldiag-dev/src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -331,7 +331,13 @@ pub struct VmArg {
)]
#[cfg_attr(
windows,
doc = "* NAME_OR_PATH - Either a Hyper-V VM name, or a path as in vsock:PATH>"
doc = "* hyperv:GUID - A Hyper-V VM ID (with or without braces)

"
)]
#[cfg_attr(
windows,
doc = "* NAME_OR_GUID_OR_PATH - Either a Hyper-V VM name or GUID, or a path as in vsock:PATH"
)]
#[cfg_attr(not(windows), doc = "* PATH - A path as in vsock:PATH")]
#[clap(name = "VM")]
Expand All @@ -342,6 +348,8 @@ pub struct VmArg {
enum VmId {
#[cfg(windows)]
HyperV(String),
#[cfg(windows)]
HyperVId(guid::Guid),
Comment thread
moor-coding marked this conversation as resolved.
HybridVsock(PathBuf),
}

Expand All @@ -353,10 +361,21 @@ impl FromStr for VmId {
Ok(Self::HybridVsock(Path::new(s).to_owned()))
} else {
#[cfg(windows)]
if let Some(s) = s.strip_prefix("hyperv:") {
return Ok(Self::HyperV(s.to_owned()));
} else if !pal::windows::fs::is_unix_socket(s.as_ref()).unwrap_or(false) {
return Ok(Self::HyperV(s.to_owned()));
{
let (value, had_prefix) = match s.strip_prefix("hyperv:") {
Some(rest) => (rest, true),
None => (s, false),
};

// Try parsing as a GUID first (with or without braces).
if let Ok(guid) = value.parse::<guid::Guid>() {
return Ok(Self::HyperVId(guid));
}

if had_prefix || !pal::windows::fs::is_unix_socket(value.as_ref()).unwrap_or(false)
{
return Ok(Self::HyperV(value.to_owned()));
}
}
// Default to hybrid vsock since this is what OpenVMM supports for
// Underhill.
Expand Down Expand Up @@ -475,6 +494,8 @@ fn new_client(driver: impl Driver + Spawn + Clone, input: &VmArg) -> anyhow::Res
let client = match &input.id {
#[cfg(windows)]
VmId::HyperV(name) => DiagClient::from_hyperv_name(driver, name)?,
#[cfg(windows)]
VmId::HyperVId(guid) => DiagClient::from_hyperv_id(driver, *guid),
VmId::HybridVsock(path) => DiagClient::from_hybrid_vsock(driver, path),
};
Ok(client)
Expand Down Expand Up @@ -655,15 +676,15 @@ pub fn main() -> anyhow::Result<()> {
use diag_client::hyperv::ComPortAccessInfo;
use futures::AsyncBufReadExt;

let vm_name = match &vm.id {
VmId::HyperV(name) => name,
_ => anyhow::bail!("--serial is only supported for Hyper-V VMs"),
};

let port_access_info = if let Some(pipe_path) = pipe_path.as_ref() {
ComPortAccessInfo::PortPipePath(pipe_path)
} else {
ComPortAccessInfo::NameAndPortNumber(vm_name, 3)
match &vm.id {
VmId::HyperV(name) => ComPortAccessInfo::NameAndPortNumber(name, 3),
#[cfg(windows)]
VmId::HyperVId(guid) => ComPortAccessInfo::IdAndPortNumber(*guid, 3),
_ => anyhow::bail!("--serial is only supported for Hyper-V VMs"),
}
};

let pipe =
Expand Down Expand Up @@ -762,6 +783,12 @@ pub fn main() -> anyhow::Result<()> {
diag_client::hyperv::connect_vsock(&driver, vm_id, port).await?;
PolledSocket::new(&driver, socket2::Socket::from(stream))?
}
#[cfg(windows)]
VmId::HyperVId(vm_id) => {
let stream =
diag_client::hyperv::connect_vsock(&driver, vm_id, port).await?;
PolledSocket::new(&driver, socket2::Socket::from(stream))?
}
};

let vsock = Arc::new(vsock.into_inner());
Expand Down Expand Up @@ -906,6 +933,13 @@ pub fn main() -> anyhow::Result<()> {
.await?;
PolledSocket::new(&driver, socket2::Socket::from(stream))?
}
#[cfg(windows)]
VmId::HyperVId(ref vm_id) => {
let stream =
diag_client::hyperv::connect_vsock(&driver, *vm_id, vsock_port)
.await?;
PolledSocket::new(&driver, socket2::Socket::from(stream))?
}
};
println!("VSOCK connect to port {:?}", vsock_port);

Expand Down
Loading