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