Andrew Walbran | b12a43e | 2020-11-10 14:22:42 +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 Virt Manager |
| 16 | |
| 17 | use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::{ |
| 18 | BnVirtManager, IVirtManager, |
| 19 | }; |
| 20 | use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachine::{ |
| 21 | BnVirtualMachine, IVirtualMachine, |
| 22 | }; |
Stephen Crane | c607b47 | 2021-02-09 22:24:37 -0800 | [diff] [blame] | 23 | use android_system_virtmanager::binder::{self, add_service, Interface, StatusCode, Strong}; |
Andrew Walbran | c852ee0 | 2021-02-23 17:20:22 +0000 | [diff] [blame] | 24 | use anyhow::{bail, Context, Error}; |
Andrew Walbran | b12a43e | 2020-11-10 14:22:42 +0000 | [diff] [blame] | 25 | use log::{debug, error, info}; |
| 26 | use serde::{Deserialize, Serialize}; |
| 27 | use std::fs::File; |
Andrew Walbran | c852ee0 | 2021-02-23 17:20:22 +0000 | [diff] [blame] | 28 | use std::io::BufReader; |
Andrew Walbran | b12a43e | 2020-11-10 14:22:42 +0000 | [diff] [blame] | 29 | use std::process::{Child, Command}; |
| 30 | use std::sync::{Arc, Mutex}; |
| 31 | |
| 32 | /// The first CID to assign to a guest VM managed by the Virt Manager. CIDs lower than this are |
| 33 | /// reserved for the host or other usage. |
| 34 | const FIRST_GUEST_CID: Cid = 10; |
| 35 | |
| 36 | const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager"; |
Andrew Walbran | 3049fdf | 2020-12-23 12:46:30 +0000 | [diff] [blame] | 37 | const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm"; |
Andrew Walbran | b12a43e | 2020-11-10 14:22:42 +0000 | [diff] [blame] | 38 | |
| 39 | /// The unique ID of a VM used (together with a port number) for vsock communication. |
| 40 | type Cid = u32; |
| 41 | |
| 42 | /// Configuration for a particular VM to be started. |
| 43 | #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] |
| 44 | struct VmConfig { |
Andrew Walbran | c852ee0 | 2021-02-23 17:20:22 +0000 | [diff] [blame] | 45 | kernel: Option<String>, |
Andrew Walbran | b12a43e | 2020-11-10 14:22:42 +0000 | [diff] [blame] | 46 | initrd: Option<String>, |
| 47 | params: Option<String>, |
Andrew Walbran | c852ee0 | 2021-02-23 17:20:22 +0000 | [diff] [blame] | 48 | bootloader: Option<String>, |
| 49 | #[serde(default)] |
| 50 | disks: Vec<DiskImage>, |
| 51 | } |
| 52 | |
| 53 | /// A disk image to be made available to the VM. |
| 54 | #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)] |
| 55 | struct DiskImage { |
| 56 | image: String, |
| 57 | writable: bool, |
Andrew Walbran | b12a43e | 2020-11-10 14:22:42 +0000 | [diff] [blame] | 58 | } |
| 59 | |
| 60 | fn main() { |
| 61 | env_logger::init(); |
| 62 | let state = Arc::new(Mutex::new(State::new())); |
| 63 | let virt_manager = VirtManager::new(state); |
| 64 | let virt_manager = BnVirtManager::new_binder(virt_manager); |
| 65 | add_service(BINDER_SERVICE_IDENTIFIER, virt_manager.as_binder()).unwrap(); |
| 66 | info!("Registered Binder service, joining threadpool."); |
| 67 | binder::ProcessState::join_thread_pool(); |
| 68 | } |
| 69 | |
| 70 | #[derive(Debug)] |
| 71 | struct VirtManager { |
| 72 | state: Arc<Mutex<State>>, |
| 73 | } |
| 74 | |
| 75 | impl VirtManager { |
| 76 | fn new(state: Arc<Mutex<State>>) -> Self { |
| 77 | VirtManager { state } |
| 78 | } |
| 79 | } |
| 80 | |
| 81 | impl Interface for VirtManager {} |
| 82 | |
| 83 | impl IVirtManager for VirtManager { |
| 84 | /// Create and start a new VM with the given configuration, assigning it the next available CID. |
| 85 | /// |
| 86 | /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client. |
Stephen Crane | c607b47 | 2021-02-09 22:24:37 -0800 | [diff] [blame] | 87 | fn startVm(&self, config_path: &str) -> binder::Result<Strong<dyn IVirtualMachine>> { |
Andrew Walbran | b12a43e | 2020-11-10 14:22:42 +0000 | [diff] [blame] | 88 | let state = &mut *self.state.lock().unwrap(); |
| 89 | let cid = state.next_cid; |
| 90 | let child = start_vm(config_path, cid)?; |
| 91 | // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them. |
| 92 | state.next_cid = state.next_cid.checked_add(1).ok_or(StatusCode::UNKNOWN_ERROR)?; |
| 93 | Ok(VirtualMachine::create(Arc::new(VmInstance::new(child, cid)))) |
| 94 | } |
| 95 | } |
| 96 | |
| 97 | /// Implementation of the AIDL IVirtualMachine interface. Used as a handle to a VM. |
| 98 | #[derive(Debug)] |
| 99 | struct VirtualMachine { |
| 100 | instance: Arc<VmInstance>, |
| 101 | } |
| 102 | |
| 103 | impl VirtualMachine { |
Stephen Crane | c607b47 | 2021-02-09 22:24:37 -0800 | [diff] [blame] | 104 | fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> { |
Andrew Walbran | b12a43e | 2020-11-10 14:22:42 +0000 | [diff] [blame] | 105 | let binder = VirtualMachine { instance }; |
Stephen Crane | c607b47 | 2021-02-09 22:24:37 -0800 | [diff] [blame] | 106 | BnVirtualMachine::new_binder(binder) |
Andrew Walbran | b12a43e | 2020-11-10 14:22:42 +0000 | [diff] [blame] | 107 | } |
| 108 | } |
| 109 | |
| 110 | impl Interface for VirtualMachine {} |
| 111 | |
| 112 | impl IVirtualMachine for VirtualMachine { |
| 113 | fn getCid(&self) -> binder::Result<i32> { |
| 114 | Ok(self.instance.cid as i32) |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | /// Information about a particular instance of a VM which is running. |
| 119 | #[derive(Debug)] |
| 120 | struct VmInstance { |
| 121 | /// The crosvm child process. |
| 122 | child: Child, |
| 123 | /// The CID assigned to the VM for vsock communication. |
| 124 | cid: Cid, |
| 125 | } |
| 126 | |
| 127 | impl VmInstance { |
| 128 | /// Create a new `VmInstance` with a single reference for the given process. |
| 129 | fn new(child: Child, cid: Cid) -> VmInstance { |
| 130 | VmInstance { child, cid } |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | impl Drop for VmInstance { |
| 135 | fn drop(&mut self) { |
| 136 | debug!("Dropping {:?}", self); |
| 137 | // TODO: Talk to crosvm to shutdown cleanly. |
| 138 | if let Err(e) = self.child.kill() { |
| 139 | error!("Error killing crosvm instance: {}", e); |
| 140 | } |
| 141 | // We need to wait on the process after killing it to avoid zombies. |
| 142 | match self.child.wait() { |
| 143 | Err(e) => error!("Error waiting for crosvm instance to die: {}", e), |
| 144 | Ok(status) => info!("Crosvm exited with status {}", status), |
| 145 | } |
| 146 | } |
| 147 | } |
| 148 | |
| 149 | /// The mutable state of the Virt Manager. There should only be one instance of this struct. |
| 150 | #[derive(Debug)] |
| 151 | struct State { |
| 152 | next_cid: Cid, |
| 153 | } |
| 154 | |
| 155 | impl State { |
| 156 | fn new() -> Self { |
| 157 | State { next_cid: FIRST_GUEST_CID } |
| 158 | } |
| 159 | } |
| 160 | |
| 161 | /// Start a new VM instance from the given VM config filename. This assumes the VM is not already |
| 162 | /// running. |
| 163 | fn start_vm(config_path: &str, cid: Cid) -> binder::Result<Child> { |
| 164 | let config = load_vm_config(config_path).map_err(|e| { |
| 165 | error!("Failed to load VM config {}: {:?}", config_path, e); |
| 166 | StatusCode::BAD_VALUE |
| 167 | })?; |
| 168 | Ok(run_vm(&config, cid).map_err(|e| { |
| 169 | error!("Failed to start VM {}: {:?}", config_path, e); |
| 170 | StatusCode::UNKNOWN_ERROR |
| 171 | })?) |
| 172 | } |
| 173 | |
| 174 | /// Load the configuration for the VM with the given ID from a JSON file. |
| 175 | fn load_vm_config(path: &str) -> Result<VmConfig, Error> { |
| 176 | let file = File::open(path).with_context(|| format!("Failed to open {}", path))?; |
| 177 | let buffered = BufReader::new(file); |
| 178 | Ok(serde_json::from_reader(buffered)?) |
| 179 | } |
| 180 | |
| 181 | /// Start an instance of `crosvm` to manage a new VM. |
Andrew Walbran | c852ee0 | 2021-02-23 17:20:22 +0000 | [diff] [blame] | 182 | fn run_vm(config: &VmConfig, cid: Cid) -> Result<Child, Error> { |
| 183 | if config.bootloader.is_none() && config.kernel.is_none() { |
| 184 | bail!("VM must have either a bootloader or a kernel image."); |
| 185 | } |
| 186 | if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) { |
| 187 | bail!("Can't have both bootloader and kernel/initrd image."); |
| 188 | } |
| 189 | |
Andrew Walbran | 3049fdf | 2020-12-23 12:46:30 +0000 | [diff] [blame] | 190 | let mut command = Command::new(CROSVM_PATH); |
Andrew Walbran | b12a43e | 2020-11-10 14:22:42 +0000 | [diff] [blame] | 191 | // TODO(qwandor): Remove --disable-sandbox. |
| 192 | command.arg("run").arg("--disable-sandbox").arg("--cid").arg(cid.to_string()); |
Andrew Walbran | c852ee0 | 2021-02-23 17:20:22 +0000 | [diff] [blame] | 193 | // TODO(jiyong): Don't redirect console to the host syslog |
| 194 | command.arg("--serial=type=syslog"); |
| 195 | if let Some(bootloader) = &config.bootloader { |
| 196 | command.arg("--bios").arg(bootloader); |
| 197 | } |
Andrew Walbran | b12a43e | 2020-11-10 14:22:42 +0000 | [diff] [blame] | 198 | if let Some(initrd) = &config.initrd { |
| 199 | command.arg("--initrd").arg(initrd); |
| 200 | } |
| 201 | if let Some(params) = &config.params { |
| 202 | command.arg("--params").arg(params); |
| 203 | } |
Andrew Walbran | c852ee0 | 2021-02-23 17:20:22 +0000 | [diff] [blame] | 204 | for disk in &config.disks { |
| 205 | command.arg(if disk.writable { "--rwdisk" } else { "--disk" }).arg(&disk.image); |
| 206 | } |
| 207 | if let Some(kernel) = &config.kernel { |
| 208 | command.arg(kernel); |
| 209 | } |
Andrew Walbran | b12a43e | 2020-11-10 14:22:42 +0000 | [diff] [blame] | 210 | info!("Running {:?}", command); |
| 211 | // TODO: Monitor child process, and remove from VM map if it dies. |
Andrew Walbran | c852ee0 | 2021-02-23 17:20:22 +0000 | [diff] [blame] | 212 | Ok(command.spawn()?) |
Andrew Walbran | b12a43e | 2020-11-10 14:22:42 +0000 | [diff] [blame] | 213 | } |