blob: bdb89d2ed4ca19a6202cb0406275e29fbcfdbe15 [file] [log] [blame]
Andrew Walbranb12a43e2020-11-10 14:22:42 +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 Virt Manager
16
17use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::{
18 BnVirtManager, IVirtManager,
19};
20use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachine::{
21 BnVirtualMachine, IVirtualMachine,
22};
Stephen Cranec607b472021-02-09 22:24:37 -080023use android_system_virtmanager::binder::{self, add_service, Interface, StatusCode, Strong};
Andrew Walbranc852ee02021-02-23 17:20:22 +000024use anyhow::{bail, Context, Error};
Andrew Walbranb12a43e2020-11-10 14:22:42 +000025use log::{debug, error, info};
26use serde::{Deserialize, Serialize};
27use std::fs::File;
Andrew Walbranc852ee02021-02-23 17:20:22 +000028use std::io::BufReader;
Andrew Walbranb12a43e2020-11-10 14:22:42 +000029use std::process::{Child, Command};
30use 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.
34const FIRST_GUEST_CID: Cid = 10;
35
36const BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager";
Andrew Walbran3049fdf2020-12-23 12:46:30 +000037const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
Andrew Walbranb12a43e2020-11-10 14:22:42 +000038
39/// The unique ID of a VM used (together with a port number) for vsock communication.
40type Cid = u32;
41
42/// Configuration for a particular VM to be started.
43#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
44struct VmConfig {
Andrew Walbranc852ee02021-02-23 17:20:22 +000045 kernel: Option<String>,
Andrew Walbranb12a43e2020-11-10 14:22:42 +000046 initrd: Option<String>,
47 params: Option<String>,
Andrew Walbranc852ee02021-02-23 17:20:22 +000048 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)]
55struct DiskImage {
56 image: String,
57 writable: bool,
Andrew Walbranb12a43e2020-11-10 14:22:42 +000058}
59
60fn 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)]
71struct VirtManager {
72 state: Arc<Mutex<State>>,
73}
74
75impl VirtManager {
76 fn new(state: Arc<Mutex<State>>) -> Self {
77 VirtManager { state }
78 }
79}
80
81impl Interface for VirtManager {}
82
83impl 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 Cranec607b472021-02-09 22:24:37 -080087 fn startVm(&self, config_path: &str) -> binder::Result<Strong<dyn IVirtualMachine>> {
Andrew Walbranb12a43e2020-11-10 14:22:42 +000088 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)]
99struct VirtualMachine {
100 instance: Arc<VmInstance>,
101}
102
103impl VirtualMachine {
Stephen Cranec607b472021-02-09 22:24:37 -0800104 fn create(instance: Arc<VmInstance>) -> Strong<dyn IVirtualMachine> {
Andrew Walbranb12a43e2020-11-10 14:22:42 +0000105 let binder = VirtualMachine { instance };
Stephen Cranec607b472021-02-09 22:24:37 -0800106 BnVirtualMachine::new_binder(binder)
Andrew Walbranb12a43e2020-11-10 14:22:42 +0000107 }
108}
109
110impl Interface for VirtualMachine {}
111
112impl 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)]
120struct VmInstance {
121 /// The crosvm child process.
122 child: Child,
123 /// The CID assigned to the VM for vsock communication.
124 cid: Cid,
125}
126
127impl 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
134impl 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)]
151struct State {
152 next_cid: Cid,
153}
154
155impl 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.
163fn 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.
175fn 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 Walbranc852ee02021-02-23 17:20:22 +0000182fn 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 Walbran3049fdf2020-12-23 12:46:30 +0000190 let mut command = Command::new(CROSVM_PATH);
Andrew Walbranb12a43e2020-11-10 14:22:42 +0000191 // TODO(qwandor): Remove --disable-sandbox.
192 command.arg("run").arg("--disable-sandbox").arg("--cid").arg(cid.to_string());
Andrew Walbranc852ee02021-02-23 17:20:22 +0000193 // 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 Walbranb12a43e2020-11-10 14:22:42 +0000198 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 Walbranc852ee02021-02-23 17:20:22 +0000204 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 Walbranb12a43e2020-11-10 14:22:42 +0000210 info!("Running {:?}", command);
211 // TODO: Monitor child process, and remove from VM map if it dies.
Andrew Walbranc852ee02021-02-23 17:20:22 +0000212 Ok(command.spawn()?)
Andrew Walbranb12a43e2020-11-10 14:22:42 +0000213}