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