-
Notifications
You must be signed in to change notification settings - Fork 25
feat(macOS): add vfkit backend for ephemeral and persistent VMs #259
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Open
tnk4on
wants to merge
2
commits into
bootc-dev:main
Choose a base branch
from
tnk4on:wip/macos-vfkit-pr
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
Open
Changes from all commits
Commits
Show all changes
2 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,223 @@ | ||
| //! Ephemeral VM management commands for macOS (vfkit backend). | ||
|
|
||
| use std::io::Write; | ||
| use std::process::{Command, Stdio}; | ||
|
|
||
| use clap::Subcommand; | ||
| use color_eyre::eyre::bail; | ||
| use color_eyre::Result; | ||
|
|
||
| use crate::run_ephemeral_macos::{self, EphemeralVmMetadata}; | ||
|
|
||
| /// Options for `ephemeral run-ssh`, combining run options with optional SSH arguments. | ||
| #[derive(Debug, clap::Parser)] | ||
| pub struct RunSshOpts { | ||
| #[command(flatten)] | ||
| pub run_opts: run_ephemeral_macos::RunEphemeralOpts, | ||
|
|
||
| /// SSH command to execute (optional, defaults to interactive shell) | ||
| #[arg(trailing_var_arg = true)] | ||
| pub ssh_args: Vec<String>, | ||
| } | ||
|
|
||
| #[derive(Debug, Subcommand)] | ||
| pub enum EphemeralCommands { | ||
| /// Run bootc containers as ephemeral VMs | ||
| #[clap(name = "run")] | ||
| Run(run_ephemeral_macos::RunEphemeralOpts), | ||
|
|
||
| /// Run ephemeral VM and SSH into it | ||
| #[clap(name = "run-ssh")] | ||
| RunSsh(RunSshOpts), | ||
|
|
||
| /// Connect to a running ephemeral VM via SSH | ||
| #[clap(name = "ssh")] | ||
| Ssh { | ||
| /// VM name | ||
| name: String, | ||
|
|
||
| /// Additional SSH arguments (e.g. -v, -L, commands to execute) | ||
| #[clap(allow_hyphen_values = true)] | ||
| args: Vec<String>, | ||
| }, | ||
|
|
||
| /// List ephemeral VM containers | ||
| #[clap(name = "ps")] | ||
| Ps { | ||
| /// Output as JSON | ||
| #[clap(long)] | ||
| json: bool, | ||
| }, | ||
|
|
||
| /// Remove all ephemeral VM containers | ||
| #[clap(name = "rm-all")] | ||
| RmAll { | ||
| /// Force removal without confirmation | ||
| #[clap(short, long)] | ||
| force: bool, | ||
| }, | ||
| } | ||
|
|
||
| impl EphemeralCommands { | ||
| /// Execute the ephemeral subcommand. | ||
| pub fn run(self) -> Result<()> { | ||
| match self { | ||
| EphemeralCommands::Run(opts) => run_ephemeral_macos::run(opts), | ||
| EphemeralCommands::RunSsh(mut opts) => { | ||
| opts.run_opts.ssh_keygen = true; | ||
| if !opts.ssh_args.is_empty() { | ||
| let combined = shlex::try_join(opts.ssh_args.iter().map(|s| s.as_str())) | ||
| .map_err(|e| color_eyre::eyre::eyre!("failed to escape SSH args: {}", e))?; | ||
| opts.run_opts.execute.push(combined); | ||
| } | ||
| run_ephemeral_macos::run(opts.run_opts) | ||
| } | ||
| EphemeralCommands::Ssh { name, args } => cmd_ssh(&name, &args), | ||
| EphemeralCommands::Ps { json } => cmd_ps(json), | ||
| EphemeralCommands::RmAll { force } => cmd_rm_all(force), | ||
| } | ||
| } | ||
| } | ||
|
|
||
| fn cmd_ps(json: bool) -> Result<()> { | ||
| let vms = EphemeralVmMetadata::list_all()?; | ||
| for vm in &vms { | ||
| if !vm.is_alive() { | ||
| EphemeralVmMetadata::remove(&vm.name); | ||
| } | ||
| } | ||
| let live: Vec<_> = vms.into_iter().filter(|vm| vm.is_alive()).collect(); | ||
|
|
||
| if json { | ||
| println!("{}", serde_json::to_string_pretty(&live)?); | ||
| return Ok(()); | ||
| } | ||
|
|
||
| if live.is_empty() { | ||
| println!("No running ephemeral VMs."); | ||
| return Ok(()); | ||
| } | ||
|
|
||
| println!("{:<24} {:<50} SSH", "NAME", "IMAGE"); | ||
| for vm in &live { | ||
| println!( | ||
| "{:<24} {:<50} ssh -p {} -i {} root@localhost", | ||
| vm.name, vm.image, vm.ssh_port, vm.ssh_key | ||
| ); | ||
| } | ||
| Ok(()) | ||
| } | ||
|
|
||
| fn cmd_rm_all(force: bool) -> Result<()> { | ||
| let vms = EphemeralVmMetadata::list_all()?; | ||
| if vms.is_empty() { | ||
| println!("No ephemeral VMs found."); | ||
| return Ok(()); | ||
| } | ||
|
|
||
| if !force { | ||
| println!("Found {} ephemeral VM(s):", vms.len()); | ||
| for vm in &vms { | ||
| println!( | ||
| " {} ({})", | ||
| vm.name, | ||
| if vm.is_alive() { "running" } else { "stopped" } | ||
| ); | ||
| } | ||
| print!("Remove all ephemeral VMs? [y/N]: "); | ||
| std::io::stdout().flush()?; | ||
| let mut input = String::new(); | ||
| std::io::stdin().read_line(&mut input)?; | ||
| let input = input.trim().to_lowercase(); | ||
| if input != "y" && input != "yes" { | ||
| println!("Aborted."); | ||
| return Ok(()); | ||
| } | ||
| } | ||
|
|
||
| for vm in &vms { | ||
| if vm.is_alive() { | ||
| if let Err(e) = rustix::process::kill_process( | ||
| rustix::process::Pid::from_raw(vm.pid as i32).unwrap(), | ||
| rustix::process::Signal::TERM, | ||
| ) { | ||
| tracing::warn!("failed to kill VM process {}: {}", vm.pid, e); | ||
| } | ||
| if vm.gvproxy_pid > 0 { | ||
| if let Err(e) = rustix::process::kill_process( | ||
| rustix::process::Pid::from_raw(vm.gvproxy_pid as i32).unwrap(), | ||
| rustix::process::Signal::TERM, | ||
| ) { | ||
| tracing::warn!("failed to kill gvproxy {}: {}", vm.gvproxy_pid, e); | ||
| } | ||
| } | ||
| } | ||
| if let Some(ref container) = vm.nbd_container { | ||
| crate::nbdkit_macos::stop_nbdkit_container(container); | ||
| } | ||
| EphemeralVmMetadata::remove(&vm.name); | ||
| println!("Removed {}", vm.name); | ||
| } | ||
|
|
||
| // Sweep orphaned resources inside podman machine | ||
| if let Ok(machine) = run_ephemeral_macos::detect_machine_name() { | ||
| // Remove orphaned nbdkit containers | ||
| let _ = Command::new("podman") | ||
| .args([ | ||
| "machine", | ||
| "ssh", | ||
| &machine, | ||
| "--", | ||
| "podman", | ||
| "rm", | ||
| "-f", | ||
| "--filter", | ||
| "name=bcvk-nbd-", | ||
| ]) | ||
| .stdout(Stdio::null()) | ||
| .stderr(Stdio::null()) | ||
| .status(); | ||
| // Unmount any remaining container image overlays | ||
| let _ = Command::new("podman") | ||
| .args([ | ||
| "machine", "ssh", &machine, "--", "podman", "image", "umount", "--all", | ||
| ]) | ||
| .stdout(Stdio::null()) | ||
| .stderr(Stdio::null()) | ||
| .status(); | ||
| } | ||
| Ok(()) | ||
| } | ||
|
|
||
| fn cmd_ssh(name: &str, args: &[String]) -> Result<()> { | ||
| let vm = EphemeralVmMetadata::load(name)?; | ||
| if !vm.is_alive() { | ||
| EphemeralVmMetadata::remove(name); | ||
| bail!("VM '{}' is not running", name); | ||
| } | ||
|
|
||
| // Try to set up SSH port forwarding via VM-specific gvproxy socket | ||
| let base = run_ephemeral_macos::ephemeral_base_dir(); | ||
| let svc_sock = format!("{}/{}-gvproxy-svc.sock", base.display(), name); | ||
| if std::path::Path::new(&svc_sock).exists() { | ||
| if let Err(e) = | ||
| run_ephemeral_macos::expose_ssh_port(&svc_sock, "192.168.127.2", vm.ssh_port) | ||
| { | ||
| tracing::debug!("SSH port forward re-expose: {}", e); | ||
| } | ||
| } | ||
|
|
||
| let key_path = std::path::Path::new(&vm.ssh_key); | ||
| if args.is_empty() { | ||
| run_ephemeral_macos::run_ssh_interactive(vm.ssh_port, key_path, "root")?; | ||
| } else { | ||
| let combined = shlex::try_join(args.iter().map(|s| s.as_str())) | ||
| .map_err(|e| color_eyre::eyre::eyre!("failed to escape SSH command: {}", e))?; | ||
| let status = | ||
| run_ephemeral_macos::run_ssh_command(vm.ssh_port, key_path, "root", &combined)?; | ||
| if !status.success() { | ||
| std::process::exit(status.code().unwrap_or(1)); | ||
| } | ||
| } | ||
| Ok(()) | ||
| } | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Hmm this may not be a new thing but let's try to use say dialoguer or so
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
Agreed. Linux has the same pattern too. How would you like to handle this — separate follow-up?