blob: 88d6ed76d81e867ca828f08ff7e2ec76a5b62d6d [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};
23use android_system_virtmanager::binder::{self, add_service, Interface, StatusCode};
24use anyhow::{Context, Error};
25use log::{debug, error, info};
26use serde::{Deserialize, Serialize};
27use std::fs::File;
28use std::io::{self, BufReader};
29use 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 {
45 kernel: String,
46 initrd: Option<String>,
47 params: Option<String>,
48}
49
50fn main() {
51 env_logger::init();
52 let state = Arc::new(Mutex::new(State::new()));
53 let virt_manager = VirtManager::new(state);
54 let virt_manager = BnVirtManager::new_binder(virt_manager);
55 add_service(BINDER_SERVICE_IDENTIFIER, virt_manager.as_binder()).unwrap();
56 info!("Registered Binder service, joining threadpool.");
57 binder::ProcessState::join_thread_pool();
58}
59
60#[derive(Debug)]
61struct VirtManager {
62 state: Arc<Mutex<State>>,
63}
64
65impl VirtManager {
66 fn new(state: Arc<Mutex<State>>) -> Self {
67 VirtManager { state }
68 }
69}
70
71impl Interface for VirtManager {}
72
73impl IVirtManager for VirtManager {
74 /// Create and start a new VM with the given configuration, assigning it the next available CID.
75 ///
76 /// Returns a binder `IVirtualMachine` object referring to it, as a handle for the client.
77 fn startVm(&self, config_path: &str) -> binder::Result<Box<dyn IVirtualMachine>> {
78 let state = &mut *self.state.lock().unwrap();
79 let cid = state.next_cid;
80 let child = start_vm(config_path, cid)?;
81 // TODO(qwandor): keep track of which CIDs are currently in use so that we can reuse them.
82 state.next_cid = state.next_cid.checked_add(1).ok_or(StatusCode::UNKNOWN_ERROR)?;
83 Ok(VirtualMachine::create(Arc::new(VmInstance::new(child, cid))))
84 }
85}
86
87/// Implementation of the AIDL IVirtualMachine interface. Used as a handle to a VM.
88#[derive(Debug)]
89struct VirtualMachine {
90 instance: Arc<VmInstance>,
91}
92
93impl VirtualMachine {
94 fn create(instance: Arc<VmInstance>) -> Box<dyn IVirtualMachine> {
95 let binder = VirtualMachine { instance };
96 Box::new(BnVirtualMachine::new_binder(binder))
97 }
98}
99
100impl Interface for VirtualMachine {}
101
102impl IVirtualMachine for VirtualMachine {
103 fn getCid(&self) -> binder::Result<i32> {
104 Ok(self.instance.cid as i32)
105 }
106}
107
108/// Information about a particular instance of a VM which is running.
109#[derive(Debug)]
110struct VmInstance {
111 /// The crosvm child process.
112 child: Child,
113 /// The CID assigned to the VM for vsock communication.
114 cid: Cid,
115}
116
117impl VmInstance {
118 /// Create a new `VmInstance` with a single reference for the given process.
119 fn new(child: Child, cid: Cid) -> VmInstance {
120 VmInstance { child, cid }
121 }
122}
123
124impl Drop for VmInstance {
125 fn drop(&mut self) {
126 debug!("Dropping {:?}", self);
127 // TODO: Talk to crosvm to shutdown cleanly.
128 if let Err(e) = self.child.kill() {
129 error!("Error killing crosvm instance: {}", e);
130 }
131 // We need to wait on the process after killing it to avoid zombies.
132 match self.child.wait() {
133 Err(e) => error!("Error waiting for crosvm instance to die: {}", e),
134 Ok(status) => info!("Crosvm exited with status {}", status),
135 }
136 }
137}
138
139/// The mutable state of the Virt Manager. There should only be one instance of this struct.
140#[derive(Debug)]
141struct State {
142 next_cid: Cid,
143}
144
145impl State {
146 fn new() -> Self {
147 State { next_cid: FIRST_GUEST_CID }
148 }
149}
150
151/// Start a new VM instance from the given VM config filename. This assumes the VM is not already
152/// running.
153fn start_vm(config_path: &str, cid: Cid) -> binder::Result<Child> {
154 let config = load_vm_config(config_path).map_err(|e| {
155 error!("Failed to load VM config {}: {:?}", config_path, e);
156 StatusCode::BAD_VALUE
157 })?;
158 Ok(run_vm(&config, cid).map_err(|e| {
159 error!("Failed to start VM {}: {:?}", config_path, e);
160 StatusCode::UNKNOWN_ERROR
161 })?)
162}
163
164/// Load the configuration for the VM with the given ID from a JSON file.
165fn load_vm_config(path: &str) -> Result<VmConfig, Error> {
166 let file = File::open(path).with_context(|| format!("Failed to open {}", path))?;
167 let buffered = BufReader::new(file);
168 Ok(serde_json::from_reader(buffered)?)
169}
170
171/// Start an instance of `crosvm` to manage a new VM.
172fn run_vm(config: &VmConfig, cid: Cid) -> Result<Child, io::Error> {
Andrew Walbran3049fdf2020-12-23 12:46:30 +0000173 let mut command = Command::new(CROSVM_PATH);
Andrew Walbranb12a43e2020-11-10 14:22:42 +0000174 // TODO(qwandor): Remove --disable-sandbox.
175 command.arg("run").arg("--disable-sandbox").arg("--cid").arg(cid.to_string());
176 if let Some(initrd) = &config.initrd {
177 command.arg("--initrd").arg(initrd);
178 }
179 if let Some(params) = &config.params {
180 command.arg("--params").arg(params);
181 }
182 command.arg(&config.kernel);
183 info!("Running {:?}", command);
184 // TODO: Monitor child process, and remove from VM map if it dies.
185 command.spawn()
186}