blob: 8c2a084a17171c6a50ed5b9c9ae8cf909e16f49f [file] [log] [blame]
Andrew Walbranea9fa482021-03-04 16:11:12 +00001// Copyright 2021, The Android Open Source Project
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Android VM control tool.
16
17mod sync;
18
19use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::IVirtManager;
Andrew Walbrana89fc132021-03-17 17:08:36 +000020use android_system_virtmanager::binder::{
Andrew Walbran651b0682021-03-19 16:22:07 +000021 get_interface, DeathRecipient, IBinder, ParcelFileDescriptor, ProcessState, Strong,
Andrew Walbrana89fc132021-03-17 17:08:36 +000022};
David Brazdil20412d92021-03-18 10:53:06 +000023use anyhow::{Context, Error};
Andrew Walbrana89fc132021-03-17 17:08:36 +000024use std::fs::File;
25use std::io;
26use std::os::unix::io::{AsRawFd, FromRawFd};
David Brazdil20412d92021-03-18 10:53:06 +000027use std::path::PathBuf;
28use structopt::clap::AppSettings;
29use structopt::StructOpt;
Andrew Walbranea9fa482021-03-04 16:11:12 +000030use sync::AtomicFlag;
31
32const VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager";
33
David Brazdil20412d92021-03-18 10:53:06 +000034#[derive(StructOpt)]
35#[structopt(no_version, global_settings = &[AppSettings::DisableVersion])]
36enum Opt {
37 /// Run a virtual machine
38 Run {
39 /// Path to VM config JSON
40 #[structopt(parse(from_os_str))]
41 config: PathBuf,
David Brazdil3c2ddef2021-03-18 13:09:57 +000042
43 /// Detach VM from the terminal and run in the background
44 #[structopt(short, long)]
45 daemonize: bool,
46 },
47 /// Stop a virtual machine running in the background
48 Stop {
49 /// CID of the virtual machine
50 cid: u32,
David Brazdil20412d92021-03-18 10:53:06 +000051 },
52 /// List running virtual machines
53 List,
54}
55
Andrew Walbranea9fa482021-03-04 16:11:12 +000056fn main() -> Result<(), Error> {
57 env_logger::init();
David Brazdil20412d92021-03-18 10:53:06 +000058 let opt = Opt::from_args();
Andrew Walbranea9fa482021-03-04 16:11:12 +000059
60 // We need to start the thread pool for Binder to work properly, especially link_to_death.
61 ProcessState::start_thread_pool();
62
Andrew Walbran320b5602021-03-04 16:11:12 +000063 let virt_manager = get_interface(VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER)
64 .context("Failed to find Virt Manager service")?;
65
David Brazdil20412d92021-03-18 10:53:06 +000066 match opt {
David Brazdil3c2ddef2021-03-18 13:09:57 +000067 Opt::Run { config, daemonize } => command_run(virt_manager, &config, daemonize),
68 Opt::Stop { cid } => command_stop(virt_manager, cid),
David Brazdil20412d92021-03-18 10:53:06 +000069 Opt::List => command_list(virt_manager),
Andrew Walbranea9fa482021-03-04 16:11:12 +000070 }
71}
72
73/// Run a VM from the given configuration file.
David Brazdil3c2ddef2021-03-18 13:09:57 +000074fn command_run(
75 virt_manager: Strong<dyn IVirtManager>,
76 config_path: &PathBuf,
77 daemonize: bool,
78) -> Result<(), Error> {
David Brazdil20412d92021-03-18 10:53:06 +000079 let config_filename = config_path.to_str().context("Failed to parse VM config path")?;
Andrew Walbrana89fc132021-03-17 17:08:36 +000080 let stdout_file = ParcelFileDescriptor::new(duplicate_stdout()?);
David Brazdil3c2ddef2021-03-18 13:09:57 +000081 let stdout = if daemonize { None } else { Some(&stdout_file) };
82 let vm = virt_manager.startVm(config_filename, stdout).context("Failed to start VM")?;
83
Andrew Walbran320b5602021-03-04 16:11:12 +000084 let cid = vm.getCid().context("Failed to get CID")?;
Andrew Walbranea9fa482021-03-04 16:11:12 +000085 println!("Started VM from {} with CID {}.", config_filename, cid);
86
David Brazdil3c2ddef2021-03-18 13:09:57 +000087 if daemonize {
88 // Pass the VM reference back to Virt Manager and have it hold it in the background.
89 virt_manager.debugHoldVmRef(&*vm).context("Failed to pass VM to Virt Manager")
90 } else {
91 // Wait until the VM dies. If we just returned immediately then the IVirtualMachine Binder
92 // object would be dropped and the VM would be killed.
93 wait_for_death(&mut vm.as_binder())?;
94 println!("VM died");
95 Ok(())
96 }
97}
98
99/// Retrieve reference to a previously daemonized VM and stop it.
100fn command_stop(virt_manager: Strong<dyn IVirtManager>, cid: u32) -> Result<(), Error> {
101 virt_manager
102 .debugDropVmRef(cid as i32)
103 .context("Failed to get VM from Virt Manager")?
104 .context("CID does not correspond to a running background VM")?;
Andrew Walbranea9fa482021-03-04 16:11:12 +0000105 Ok(())
106}
107
Andrew Walbran320b5602021-03-04 16:11:12 +0000108/// List the VMs currently running.
109fn command_list(virt_manager: Strong<dyn IVirtManager>) -> Result<(), Error> {
110 let vms = virt_manager.debugListVms().context("Failed to get list of VMs")?;
111 println!("Running VMs: {:#?}", vms);
112 Ok(())
113}
114
Andrew Walbranea9fa482021-03-04 16:11:12 +0000115/// Block until the given Binder object dies.
116fn wait_for_death(binder: &mut impl IBinder) -> Result<(), Error> {
117 let dead = AtomicFlag::default();
118 let mut death_recipient = {
119 let dead = dead.clone();
120 DeathRecipient::new(move || {
121 dead.raise();
122 })
123 };
124 binder.link_to_death(&mut death_recipient)?;
125 dead.wait();
126 Ok(())
127}
Andrew Walbrana89fc132021-03-17 17:08:36 +0000128
129/// Safely duplicate the standard output file descriptor.
130fn duplicate_stdout() -> io::Result<File> {
131 let stdout_fd = io::stdout().as_raw_fd();
132 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
133 // for an error.
134 let dup_fd = unsafe { libc::dup(stdout_fd) };
135 if dup_fd < 0 {
136 Err(io::Error::last_os_error())
137 } else {
138 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
139 // takes ownership of it.
140 Ok(unsafe { File::from_raw_fd(dup_fd) })
141 }
142}