use std::net::Ipv4Addr;
use std::path::PathBuf;
use std::process::ExitCode;
use std::time::Duration;
use anyhow::{Context, Result, bail};
use clap::{CommandFactory, Parser, Subcommand};
use std::io::{self, IsTerminal};
use crate::aen_window;
use crate::config::{
Acceleration, AudioMode, Firmware, NetworkMode, NetworkProtocol, PointerDevice, PortForward,
UsbHostDevice,
};
use crate::console;
use crate::manager::{ConfigureOptions, CreateOptions, VmManager, VmStatus};
use crate::qemu::HostCapabilities;
use crate::qga::ShutdownMode;
#[derive(Debug, Parser)]
#[command(name = "aev-vm", version, about)]
struct Cli {
#[command(subcommand)]
command: Option<Command>,
}
#[derive(Debug, Subcommand)]
enum Command {
Doctor,
Init {
name: String,
#[arg(long, default_value = "64G")]
disk_size: String,
#[arg(long)]
iso: Option<PathBuf>,
#[arg(long, default_value_t = 4096)]
memory: u64,
#[arg(long, default_value_t = 4)]
cpus: u16,
#[arg(long, value_enum, default_value_t = FirmwareOption::Uefi)]
firmware: FirmwareOption,
#[arg(long)]
tpm2: bool,
},
Clone {
source: String,
destination: String,
},
Media {
name: String,
#[command(subcommand)]
action: MediaCommand,
},
Disk {
name: String,
#[command(subcommand)]
action: DiskCommand,
},
Port {
name: String,
#[command(subcommand)]
action: PortCommand,
},
Usb {
name: String,
#[command(subcommand)]
action: UsbCommand,
},
Share {
name: String,
#[command(subcommand)]
action: ShareCommand,
},
Backup {
#[command(subcommand)]
action: BackupCommand,
},
Delete {
name: String,
#[arg(long)]
yes: bool,
},
Configure {
name: String,
#[arg(long)]
memory: Option<u64>,
#[arg(long)]
cpus: Option<u16>,
#[arg(long, value_enum)]
acceleration: Option<AccelerationOption>,
#[arg(long, value_enum)]
network: Option<NetworkOption>,
#[arg(long, value_enum)]
audio: Option<AudioOption>,
#[arg(long, value_enum)]
pointer_device: Option<PointerDeviceOption>,
#[arg(long, value_enum)]
firmware: Option<FirmwareOption>,
},
Identity {
name: String,
#[command(subcommand)]
action: IdentityCommand,
},
Balloon {
name: String,
#[command(subcommand)]
action: BalloonCommand,
},
Screenshot { name: String, destination: PathBuf },
Start { name: String },
Run {
name: String,
#[arg(long)]
unsafe_unfenced_host_clipboard_paste: bool,
},
Console {
name: String,
#[arg(long)]
unsafe_unfenced_host_clipboard_paste: bool,
},
Stop {
name: String,
#[arg(long, default_value_t = 30)]
timeout: u64,
},
Kill { name: String },
Pause { name: String },
Resume { name: String },
Reset { name: String },
Agent {
name: String,
#[command(subcommand)]
action: AgentCommand,
},
Snapshot {
name: String,
#[command(subcommand)]
action: SnapshotCommand,
},
Status { name: String },
List,
#[command(name = "command")]
ShowQemu { name: String },
}
#[derive(Debug, Subcommand)]
enum SnapshotCommand {
List,
Create { snapshot: String },
Revert { snapshot: String },
Delete { snapshot: String },
}
#[derive(Debug, Subcommand)]
enum AgentCommand {
Ping,
Info,
Shutdown {
#[arg(value_enum, default_value_t = AgentShutdownMode::Powerdown)]
mode: AgentShutdownMode,
},
}
#[derive(Debug, Subcommand)]
enum MediaCommand {
Show,
Attach { path: PathBuf },
Detach,
}
#[derive(Debug, Subcommand)]
enum DiskCommand {
Info,
Grow { amount: String },
}
#[derive(Debug, Subcommand)]
enum PortCommand {
List,
Add {
#[arg(long, value_enum, default_value_t = PortProtocol::Tcp)]
protocol: PortProtocol,
#[arg(long, default_value_t = Ipv4Addr::LOCALHOST)]
host_address: Ipv4Addr,
#[arg(long)]
host_port: u16,
#[arg(long)]
guest_port: u16,
},
Remove {
#[arg(long, value_enum, default_value_t = PortProtocol::Tcp)]
protocol: PortProtocol,
#[arg(long, default_value_t = Ipv4Addr::LOCALHOST)]
host_address: Ipv4Addr,
#[arg(long)]
host_port: u16,
},
}
#[derive(Debug, Subcommand)]
enum UsbCommand {
List,
Add {
#[arg(long)]
bus: u16,
#[arg(long)]
address: u16,
},
Remove {
#[arg(long)]
bus: u16,
#[arg(long)]
address: u16,
},
}
#[derive(Debug, Subcommand)]
enum ShareCommand {
List,
Add {
tag: String,
path: PathBuf,
#[arg(long)]
writable: bool,
},
Remove { tag: String },
}
#[derive(Debug, Subcommand)]
enum BackupCommand {
Create { name: String, destination: PathBuf },
Verify { path: PathBuf },
Restore { path: PathBuf, name: String },
}
#[derive(Debug, Subcommand)]
enum IdentityCommand {
Show,
Regenerate,
}
#[derive(Debug, Subcommand)]
enum BalloonCommand {
Show,
Set { memory_mib: u64 },
Restore,
}
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum PortProtocol {
Tcp,
Udp,
}
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum AccelerationOption {
Auto,
Kvm,
Tcg,
}
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum FirmwareOption {
Uefi,
UefiSecure,
Bios,
}
impl From<FirmwareOption> for Firmware {
fn from(value: FirmwareOption) -> Self {
match value {
FirmwareOption::Uefi => Self::Uefi,
FirmwareOption::UefiSecure => Self::UefiSecure,
FirmwareOption::Bios => Self::Bios,
}
}
}
impl From<AccelerationOption> for Acceleration {
fn from(value: AccelerationOption) -> Self {
match value {
AccelerationOption::Auto => Self::Auto,
AccelerationOption::Kvm => Self::Kvm,
AccelerationOption::Tcg => Self::Tcg,
}
}
}
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum NetworkOption {
User,
None,
}
impl From<NetworkOption> for NetworkMode {
fn from(value: NetworkOption) -> Self {
match value {
NetworkOption::User => Self::User,
NetworkOption::None => Self::None,
}
}
}
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum AudioOption {
None,
Pipewire,
}
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum PointerDeviceOption {
Tablet,
Mouse,
}
impl From<PointerDeviceOption> for PointerDevice {
fn from(value: PointerDeviceOption) -> Self {
match value {
PointerDeviceOption::Tablet => Self::Tablet,
PointerDeviceOption::Mouse => Self::Mouse,
}
}
}
impl From<AudioOption> for AudioMode {
fn from(value: AudioOption) -> Self {
match value {
AudioOption::None => Self::None,
AudioOption::Pipewire => Self::Pipewire,
}
}
}
impl From<PortProtocol> for NetworkProtocol {
fn from(protocol: PortProtocol) -> Self {
match protocol {
PortProtocol::Tcp => Self::Tcp,
PortProtocol::Udp => Self::Udp,
}
}
}
#[derive(Debug, Clone, Copy, clap::ValueEnum)]
enum AgentShutdownMode {
Powerdown,
Halt,
Reboot,
}
impl From<AgentShutdownMode> for ShutdownMode {
fn from(mode: AgentShutdownMode) -> Self {
match mode {
AgentShutdownMode::Powerdown => Self::Powerdown,
AgentShutdownMode::Halt => Self::Halt,
AgentShutdownMode::Reboot => Self::Reboot,
}
}
}
#[must_use]
pub fn main() -> ExitCode {
match run() {
Ok(()) => ExitCode::SUCCESS,
Err(error) => {
eprintln!("aev-vm: {error:#}");
ExitCode::FAILURE
}
}
}
fn run() -> Result<()> {
let cli = Cli::parse();
let Some(command) = cli.command else {
if io::stdin().is_terminal() && io::stdout().is_terminal() {
return crate::vm_menu::run(&VmManager::discover()?);
}
Cli::command().print_help()?;
println!();
return Ok(());
};
if matches!(command, Command::Doctor) {
return doctor();
}
let manager = VmManager::discover()?;
match command {
Command::Doctor => unreachable!(),
Command::Init {
name,
disk_size,
iso,
memory,
cpus,
firmware,
tpm2,
} => {
let path = manager.create(&CreateOptions {
name,
disk_size,
install_media: iso,
memory_mib: memory,
vcpus: cpus,
firmware: firmware.into(),
software_tpm2: tpm2,
})?;
println!("created {}", path.display());
}
Command::Clone {
source,
destination,
} => {
let path = manager.clone_vm(&source, &destination)?;
println!("cloned {source} to {destination} at {}", path.display());
}
Command::Media { name, action } => match action {
MediaCommand::Show => match manager.config(&name)?.install_media {
Some(media) => println!("{}", media.display()),
None => println!("none"),
},
MediaCommand::Attach { path } => {
let media = manager.media_attach(&name, &path)?;
println!("attached {} to {name}", media.display());
}
MediaCommand::Detach => match manager.media_detach(&name)? {
Some(media) => println!("detached {} from {name}", media.display()),
None => println!("{name} had no installation media attached"),
},
},
Command::Disk { name, action } => match action {
DiskCommand::Info => {
println!(
"{}",
serde_json::to_string_pretty(&manager.disk_info(&name)?)?
);
}
DiskCommand::Grow { amount } => {
manager.disk_grow(&name, &amount)?;
println!("grew {name} system disk by {amount}");
}
},
Command::Port { name, action } => match action {
PortCommand::List => {
for forward in manager.config(&name)?.network.forwards {
println!(
"{} {}:{} -> guest:{}",
forward.protocol.qemu_name(),
forward.host_address,
forward.host_port,
forward.guest_port
);
}
}
PortCommand::Add {
protocol,
host_address,
host_port,
guest_port,
} => {
manager.port_add(
&name,
PortForward {
protocol: protocol.into(),
host_address,
host_port,
guest_port,
},
)?;
println!("added {host_address}:{host_port} -> guest:{guest_port} for {name}");
}
PortCommand::Remove {
protocol,
host_address,
host_port,
} => {
let removed =
manager.port_remove(&name, protocol.into(), host_address, host_port)?;
println!(
"removed {} {}:{} -> guest:{} from {name}",
removed.protocol.qemu_name(),
removed.host_address,
removed.host_port,
removed.guest_port
);
}
},
Command::Usb { name, action } => match action {
UsbCommand::List => {
let mut devices = manager.config(&name)?.usb_devices;
devices.sort_unstable_by_key(|device| (device.bus, device.address));
for device in devices {
println!("bus {:03} address {:03}", device.bus, device.address);
}
}
UsbCommand::Add { bus, address } => {
manager.usb_add(&name, UsbHostDevice { bus, address })?;
println!("assigned USB bus {bus:03} address {address:03} to {name}");
}
UsbCommand::Remove { bus, address } => {
manager.usb_remove(&name, UsbHostDevice { bus, address })?;
println!("removed USB bus {bus:03} address {address:03} from {name}");
}
},
Command::Share { name, action } => match action {
ShareCommand::List => {
let mut shares = manager.config(&name)?.shares;
shares.sort_unstable_by(|left, right| left.tag.cmp(&right.tag));
for share in shares {
println!(
"{}\t{}\t{}",
share.tag,
if share.read_only {
"read-only"
} else {
"writable"
},
share.path.display()
);
}
}
ShareCommand::Add {
tag,
path,
writable,
} => {
let share = manager.share_add(&name, tag, &path, !writable)?;
println!(
"shared {} as {} ({}) for {name}",
share.path.display(),
share.tag,
if share.read_only {
"read-only"
} else {
"writable"
}
);
}
ShareCommand::Remove { tag } => {
let share = manager.share_remove(&name, &tag)?;
println!("removed share {} from {name}", share.tag);
}
},
Command::Backup { action } => match action {
BackupCommand::Create { name, destination } => {
let manifest = manager.backup_create(&name, &destination)?;
println!(
"created verified backup of {} at {} ({})",
manifest.source_name,
destination.display(),
manifest.disk.sha256
);
}
BackupCommand::Verify { path } => {
let manifest = manager.backup_verify(&path)?;
println!(
"verified backup of {} from Unix time {}",
manifest.source_name, manifest.created_at_unix
);
}
BackupCommand::Restore { path, name } => {
let definition = manager.backup_restore(&path, &name)?;
println!("restored {name} at {}", definition.display());
}
},
Command::Delete { name, yes } => {
if !yes {
bail!("refusing to delete {name} without --yes");
}
let report = manager.delete_vm(&name)?;
println!("deleted {}", report.definition.display());
if let Some(disk) = report.preserved_disk {
println!("preserved external disk {}", disk.display());
}
}
Command::Configure {
name,
memory,
cpus,
acceleration,
network,
audio,
pointer_device,
firmware,
} => {
let config = manager.configure(
&name,
&ConfigureOptions {
memory_mib: memory,
vcpus: cpus,
acceleration: acceleration.map(Into::into),
network_mode: network.map(Into::into),
audio: audio.map(Into::into),
pointer_device: pointer_device.map(Into::into),
firmware: firmware.map(Into::into),
},
)?;
println!(
"configured {name}: {} MiB, {} vCPUs, {:?}, firmware {:?}, network {:?}, audio {:?}, pointer {:?}",
config.memory_mib,
config.vcpus,
config.acceleration,
config.firmware,
config.network.mode,
config.audio,
config.pointer_device
);
}
Command::Identity { name, action } => match action {
IdentityCommand::Show => match manager.generation_id(&name)? {
Some(generation_id) => println!("{generation_id}"),
None => println!("auto"),
},
IdentityCommand::Regenerate => {
println!("{}", manager.regenerate_generation_id(&name)?);
}
},
Command::Balloon { name, action } => match action {
BalloonCommand::Show => {
let status = manager.balloon_status(&name)?;
println!(
"actual {} bytes, configured maximum {} MiB",
status.actual_bytes, status.configured_mib
);
}
BalloonCommand::Set { memory_mib } => {
manager.balloon_set(&name, memory_mib)?;
println!("requested {memory_mib} MiB for {name}");
}
BalloonCommand::Restore => {
let configured_mib = manager.balloon_restore(&name)?;
println!("restored {name} target to {configured_mib} MiB");
}
},
Command::Screenshot { name, destination } => {
let bytes = manager.screenshot(&name, &destination)?;
println!(
"captured {name} to {} ({bytes} bytes)",
destination.display()
);
}
Command::Start { name } => {
let state = manager.start(&name)?;
println!("started {} as PID {}", state.name, state.pid);
}
Command::Run {
name,
unsafe_unfenced_host_clipboard_paste,
} => open_vm(&manager, &name, unsafe_unfenced_host_clipboard_paste)?,
Command::Console {
name,
unsafe_unfenced_host_clipboard_paste,
} => {
let state = manager.running_state(&name)?;
if unsafe_unfenced_host_clipboard_paste {
console::run_with_unfenced_host_clipboard_paste(&name, &state.display_socket)?;
} else {
console::run(&name, &state.display_socket)?;
}
}
Command::Stop { name, timeout } => {
manager.stop(&name, Duration::from_secs(timeout))?;
println!("stopped {name}");
}
Command::Kill { name } => {
manager.kill(&name)?;
println!("stopped {name}");
}
Command::Pause { name } => {
manager.pause(&name)?;
println!("paused {name}");
}
Command::Resume { name } => {
manager.resume(&name)?;
println!("resumed {name}");
}
Command::Reset { name } => {
manager.reset(&name)?;
println!("reset {name}");
}
Command::Agent { name, action } => match action {
AgentCommand::Ping => {
manager.agent_ping(&name)?;
println!("guest agent is ready for {name}");
}
AgentCommand::Info => {
println!(
"{}",
serde_json::to_string_pretty(&manager.agent_info(&name)?)?
);
}
AgentCommand::Shutdown { mode } => {
manager.agent_shutdown(&name, mode.into())?;
println!("sent guest-agent {mode:?} request to {name}");
}
},
Command::Snapshot { name, action } => match action {
SnapshotCommand::List => print!("{}", manager.snapshot_list(&name)?),
SnapshotCommand::Create { snapshot } => {
manager.snapshot_create(&name, &snapshot)?;
println!("created snapshot {snapshot} for {name}");
}
SnapshotCommand::Revert { snapshot } => {
manager.snapshot_revert(&name, &snapshot)?;
println!("reverted {name} to snapshot {snapshot}");
}
SnapshotCommand::Delete { snapshot } => {
manager.snapshot_delete(&name, &snapshot)?;
println!("deleted snapshot {snapshot} from {name}");
}
},
Command::Status { name } => match manager.status(&name)? {
VmStatus::Stopped => println!("{name}: stopped"),
VmStatus::Running { pid, qemu_status } => {
println!("{name}: {qemu_status} (PID {pid})");
}
VmStatus::Stale { pid } => println!("{name}: stale state (PID {pid})"),
},
Command::List => {
for name in manager.list()? {
let status = match manager.status(&name)? {
VmStatus::Stopped => "stopped".to_owned(),
VmStatus::Running { qemu_status, .. } => qemu_status,
VmStatus::Stale { .. } => "stale".to_owned(),
};
println!("{name}\t{status}");
}
}
Command::ShowQemu { name } => println!("{}", manager.command(&name)?.display()),
}
Ok(())
}
pub(crate) fn open_vm(
manager: &VmManager,
name: &str,
unsafe_unfenced_host_clipboard_paste: bool,
) -> Result<()> {
let native_socket = console::preflight_native_endpoint()?;
if !matches!(manager.status(name)?, VmStatus::Running { .. }) {
let state = manager.start(name)?;
println!("started {} as PID {}", state.name, state.pid);
}
let state = manager.running_state(name)?;
if unsafe_unfenced_host_clipboard_paste {
console::run_with_unfenced_endpoint(name, &state.display_socket, &native_socket)
} else {
console::run_with_endpoint(name, &state.display_socket, &native_socket)
}
}
fn doctor() -> Result<()> {
let host = HostCapabilities::probe()?;
println!("qemu: {}", host.qemu.display());
println!("qemu-img: {}", host.qemu_img.display());
println!(
"kvm: {}",
if host.kvm_available {
"available"
} else {
"unavailable; auto mode will use TCG"
}
);
println!(
"uefi-code: {}",
host.uefi_code
.as_deref()
.map_or_else(|| "not found".to_owned(), |path| path.display().to_string())
);
println!(
"uefi-secure-code: {}",
host.uefi_secure_code
.as_deref()
.map_or_else(|| "not found".to_owned(), |path| path.display().to_string())
);
println!(
"uefi-secure-vars: {}",
host.uefi_secure_vars
.as_deref()
.map_or_else(|| "not found".to_owned(), |path| path.display().to_string())
);
println!(
"uefi-vars: {}",
host.uefi_vars
.as_deref()
.map_or_else(|| "not found".to_owned(), |path| path.display().to_string())
);
let socket = aen_window::socket_from_env()
.context("start an Aen session or set AEN_WINDOW_SOCKET before opening a console")?;
console::probe(&socket)?;
println!("aen-window-socket: {}", socket.display());
println!("aen-window-connection: ready (native configure verified)");
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
fn paste_opt_in(command: &Command) -> bool {
match command {
Command::Run {
unsafe_unfenced_host_clipboard_paste,
..
}
| Command::Console {
unsafe_unfenced_host_clipboard_paste,
..
} => *unsafe_unfenced_host_clipboard_paste,
_ => panic!("expected run or console command"),
}
}
#[test]
fn unsafe_unfenced_clipboard_flag_is_explicit_for_run_and_console() {
for subcommand in ["run", "console"] {
let safe = Cli::try_parse_from(["knottvm", subcommand, "guest"]).unwrap();
assert!(!paste_opt_in(safe.command.as_ref().unwrap()));
let unsafe_opt_in = Cli::try_parse_from([
"knottvm",
subcommand,
"guest",
"--unsafe-unfenced-host-clipboard-paste",
])
.unwrap();
assert!(paste_opt_in(unsafe_opt_in.command.as_ref().unwrap()));
let help = Cli::try_parse_from(["knottvm", subcommand, "guest", "--help"]).unwrap_err();
assert_eq!(help.kind(), clap::error::ErrorKind::DisplayHelp);
assert!(help.to_string().contains("UNSAFE"));
assert!(help.to_string().contains("final guest delivery"));
}
}
}