Andrew Walbran | ea9fa48 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 1 | // 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 | |
| 17 | mod sync; |
| 18 | |
| 19 | use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::IVirtManager; |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 20 | use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachine::IVirtualMachine; |
| 21 | use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachineCallback::{ |
| 22 | BnVirtualMachineCallback, IVirtualMachineCallback, |
| 23 | }; |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 24 | use android_system_virtmanager::binder::{ |
Andrew Walbran | 651b068 | 2021-03-19 16:22:07 +0000 | [diff] [blame] | 25 | get_interface, DeathRecipient, IBinder, ParcelFileDescriptor, ProcessState, Strong, |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 26 | }; |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 27 | use android_system_virtmanager::binder::{Interface, Result as BinderResult}; |
David Brazdil | 20412d9 | 2021-03-18 10:53:06 +0000 | [diff] [blame] | 28 | use anyhow::{Context, Error}; |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 29 | use std::fs::File; |
| 30 | use std::io; |
| 31 | use std::os::unix::io::{AsRawFd, FromRawFd}; |
Andrew Walbran | c2e5d8b | 2021-04-08 13:34:45 +0000 | [diff] [blame] | 32 | use std::path::{Path, PathBuf}; |
David Brazdil | 20412d9 | 2021-03-18 10:53:06 +0000 | [diff] [blame] | 33 | use structopt::clap::AppSettings; |
| 34 | use structopt::StructOpt; |
Andrew Walbran | ea9fa48 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 35 | use sync::AtomicFlag; |
| 36 | |
| 37 | const VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager"; |
| 38 | |
David Brazdil | 20412d9 | 2021-03-18 10:53:06 +0000 | [diff] [blame] | 39 | #[derive(StructOpt)] |
| 40 | #[structopt(no_version, global_settings = &[AppSettings::DisableVersion])] |
| 41 | enum Opt { |
| 42 | /// Run a virtual machine |
| 43 | Run { |
| 44 | /// Path to VM config JSON |
| 45 | #[structopt(parse(from_os_str))] |
| 46 | config: PathBuf, |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 47 | |
| 48 | /// Detach VM from the terminal and run in the background |
| 49 | #[structopt(short, long)] |
| 50 | daemonize: bool, |
| 51 | }, |
| 52 | /// Stop a virtual machine running in the background |
| 53 | Stop { |
| 54 | /// CID of the virtual machine |
| 55 | cid: u32, |
David Brazdil | 20412d9 | 2021-03-18 10:53:06 +0000 | [diff] [blame] | 56 | }, |
| 57 | /// List running virtual machines |
| 58 | List, |
| 59 | } |
| 60 | |
Andrew Walbran | ea9fa48 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 61 | fn main() -> Result<(), Error> { |
| 62 | env_logger::init(); |
David Brazdil | 20412d9 | 2021-03-18 10:53:06 +0000 | [diff] [blame] | 63 | let opt = Opt::from_args(); |
Andrew Walbran | ea9fa48 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 64 | |
| 65 | // We need to start the thread pool for Binder to work properly, especially link_to_death. |
| 66 | ProcessState::start_thread_pool(); |
| 67 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 68 | let virt_manager = get_interface(VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER) |
| 69 | .context("Failed to find Virt Manager service")?; |
| 70 | |
David Brazdil | 20412d9 | 2021-03-18 10:53:06 +0000 | [diff] [blame] | 71 | match opt { |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 72 | Opt::Run { config, daemonize } => command_run(virt_manager, &config, daemonize), |
| 73 | Opt::Stop { cid } => command_stop(virt_manager, cid), |
David Brazdil | 20412d9 | 2021-03-18 10:53:06 +0000 | [diff] [blame] | 74 | Opt::List => command_list(virt_manager), |
Andrew Walbran | ea9fa48 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 75 | } |
| 76 | } |
| 77 | |
| 78 | /// Run a VM from the given configuration file. |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 79 | fn command_run( |
| 80 | virt_manager: Strong<dyn IVirtManager>, |
Andrew Walbran | c2e5d8b | 2021-04-08 13:34:45 +0000 | [diff] [blame] | 81 | config_path: &Path, |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 82 | daemonize: bool, |
| 83 | ) -> Result<(), Error> { |
David Brazdil | 20412d9 | 2021-03-18 10:53:06 +0000 | [diff] [blame] | 84 | let config_filename = config_path.to_str().context("Failed to parse VM config path")?; |
Andrew Walbran | 06b5f5c | 2021-03-31 12:34:13 +0000 | [diff] [blame] | 85 | let config_file = ParcelFileDescriptor::new( |
| 86 | File::open(config_filename).context("Failed to open config file")?, |
| 87 | ); |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 88 | let stdout_file = ParcelFileDescriptor::new(duplicate_stdout()?); |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 89 | let stdout = if daemonize { None } else { Some(&stdout_file) }; |
Andrew Walbran | 06b5f5c | 2021-03-31 12:34:13 +0000 | [diff] [blame] | 90 | let vm = virt_manager.startVm(&config_file, stdout).context("Failed to start VM")?; |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 91 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 92 | let cid = vm.getCid().context("Failed to get CID")?; |
Andrew Walbran | ea9fa48 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 93 | println!("Started VM from {} with CID {}.", config_filename, cid); |
| 94 | |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 95 | if daemonize { |
| 96 | // Pass the VM reference back to Virt Manager and have it hold it in the background. |
Andrei Homescu | 1415c13 | 2021-03-24 02:39:55 +0000 | [diff] [blame] | 97 | virt_manager.debugHoldVmRef(&vm).context("Failed to pass VM to Virt Manager") |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 98 | } else { |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 99 | // Wait until the VM or VirtManager dies. If we just returned immediately then the |
| 100 | // IVirtualMachine Binder object would be dropped and the VM would be killed. |
| 101 | wait_for_vm(vm) |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 102 | } |
| 103 | } |
| 104 | |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 105 | /// Wait until the given VM or the VirtManager itself dies. |
| 106 | fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> { |
| 107 | let dead = AtomicFlag::default(); |
| 108 | let callback = |
| 109 | BnVirtualMachineCallback::new_binder(VirtualMachineCallback { dead: dead.clone() }); |
| 110 | vm.registerCallback(&callback)?; |
| 111 | let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?; |
| 112 | dead.wait(); |
| 113 | // Ensure that death_recipient isn't dropped before we wait on the flag, as it is removed |
| 114 | // from the Binder when it's dropped. |
| 115 | drop(death_recipient); |
| 116 | Ok(()) |
| 117 | } |
| 118 | |
David Brazdil | 3c2ddef | 2021-03-18 13:09:57 +0000 | [diff] [blame] | 119 | /// Retrieve reference to a previously daemonized VM and stop it. |
| 120 | fn command_stop(virt_manager: Strong<dyn IVirtManager>, cid: u32) -> Result<(), Error> { |
| 121 | virt_manager |
| 122 | .debugDropVmRef(cid as i32) |
| 123 | .context("Failed to get VM from Virt Manager")? |
| 124 | .context("CID does not correspond to a running background VM")?; |
Andrew Walbran | ea9fa48 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 125 | Ok(()) |
| 126 | } |
| 127 | |
Andrew Walbran | 320b560 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 128 | /// List the VMs currently running. |
| 129 | fn command_list(virt_manager: Strong<dyn IVirtManager>) -> Result<(), Error> { |
| 130 | let vms = virt_manager.debugListVms().context("Failed to get list of VMs")?; |
| 131 | println!("Running VMs: {:#?}", vms); |
| 132 | Ok(()) |
| 133 | } |
| 134 | |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 135 | /// Raise the given flag when the given Binder object dies. |
| 136 | /// |
| 137 | /// If the returned DeathRecipient is dropped then this will no longer do anything. |
| 138 | fn wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error> { |
| 139 | let mut death_recipient = DeathRecipient::new(move || { |
| 140 | println!("VirtManager died"); |
| 141 | dead.raise(); |
| 142 | }); |
Andrew Walbran | ea9fa48 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 143 | binder.link_to_death(&mut death_recipient)?; |
Andrew Walbran | dae0716 | 2021-03-12 17:05:20 +0000 | [diff] [blame] | 144 | Ok(death_recipient) |
| 145 | } |
| 146 | |
| 147 | #[derive(Debug)] |
| 148 | struct VirtualMachineCallback { |
| 149 | dead: AtomicFlag, |
| 150 | } |
| 151 | |
| 152 | impl Interface for VirtualMachineCallback {} |
| 153 | |
| 154 | impl IVirtualMachineCallback for VirtualMachineCallback { |
| 155 | fn onDied(&self, _cid: i32) -> BinderResult<()> { |
| 156 | println!("VM died"); |
| 157 | self.dead.raise(); |
| 158 | Ok(()) |
| 159 | } |
Andrew Walbran | ea9fa48 | 2021-03-04 16:11:12 +0000 | [diff] [blame] | 160 | } |
Andrew Walbran | a89fc13 | 2021-03-17 17:08:36 +0000 | [diff] [blame] | 161 | |
| 162 | /// Safely duplicate the standard output file descriptor. |
| 163 | fn duplicate_stdout() -> io::Result<File> { |
| 164 | let stdout_fd = io::stdout().as_raw_fd(); |
| 165 | // Safe because this just duplicates a file descriptor which we know to be valid, and we check |
| 166 | // for an error. |
| 167 | let dup_fd = unsafe { libc::dup(stdout_fd) }; |
| 168 | if dup_fd < 0 { |
| 169 | Err(io::Error::last_os_error()) |
| 170 | } else { |
| 171 | // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd` |
| 172 | // takes ownership of it. |
| 173 | Ok(unsafe { File::from_raw_fd(dup_fd) }) |
| 174 | } |
| 175 | } |