blob: 138236c45b6335ba7d64037953bae1700f6884b3 [file] [log] [blame]
Andrew Walbrand6dce6f2021-03-05 16:39:08 +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//! Functions for running instances of `crosvm`.
16
Andrew Walbrandae07162021-03-12 17:05:20 +000017use crate::aidl::VirtualMachineCallbacks;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000018use crate::Cid;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000019use anyhow::{bail, Error};
Andrew Walbran3a5a9212021-05-04 17:09:08 +000020use command_fds::{CommandFdExt, FdMapping};
21use log::{debug, error, info};
Andrew Walbrandae07162021-03-12 17:05:20 +000022use shared_child::SharedChild;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000023use std::fs::{remove_dir_all, File};
Andrew Walbran3a5a9212021-05-04 17:09:08 +000024use std::os::unix::io::AsRawFd;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000025use std::path::PathBuf;
Andrew Walbrandae07162021-03-12 17:05:20 +000026use std::process::Command;
27use std::sync::atomic::{AtomicBool, Ordering};
28use std::sync::Arc;
29use std::thread;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000030
31const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
32
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000033/// Configuration for a VM to run with crosvm.
34#[derive(Debug)]
35pub struct CrosvmConfig<'a> {
36 pub cid: Cid,
37 pub bootloader: Option<&'a File>,
38 pub kernel: Option<&'a File>,
39 pub initrd: Option<&'a File>,
40 pub disks: Vec<DiskFile>,
41 pub params: Option<String>,
42}
43
44/// A disk image to pass to crosvm for a VM.
45#[derive(Debug)]
46pub struct DiskFile {
47 pub image: File,
48 pub writable: bool,
49}
50
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000051/// Information about a particular instance of a VM which is running.
52#[derive(Debug)]
53pub struct VmInstance {
54 /// The crosvm child process.
Andrew Walbrandae07162021-03-12 17:05:20 +000055 child: SharedChild,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000056 /// The CID assigned to the VM for vsock communication.
57 pub cid: Cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000058 /// Directory of temporary files used by the VM while it is running.
59 pub temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000060 /// The UID of the process which requested the VM.
61 pub requester_uid: u32,
62 /// The SID of the process which requested the VM.
Andrew Walbran02034492021-04-13 15:05:07 +000063 pub requester_sid: String,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000064 /// The PID of the process which requested the VM. Note that this process may no longer exist
65 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +000066 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +000067 /// Whether the VM is still running.
68 running: AtomicBool,
69 /// Callbacks to clients of the VM.
70 pub callbacks: VirtualMachineCallbacks,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000071}
72
73impl VmInstance {
74 /// Create a new `VmInstance` for the given process.
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000075 fn new(
Andrew Walbrandae07162021-03-12 17:05:20 +000076 child: SharedChild,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000077 cid: Cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000078 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000079 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +000080 requester_sid: String,
81 requester_debug_pid: i32,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000082 ) -> VmInstance {
Andrew Walbrandae07162021-03-12 17:05:20 +000083 VmInstance {
84 child,
85 cid,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000086 temporary_directory,
Andrew Walbrandae07162021-03-12 17:05:20 +000087 requester_uid,
88 requester_sid,
Andrew Walbran02034492021-04-13 15:05:07 +000089 requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +000090 running: AtomicBool::new(true),
91 callbacks: Default::default(),
92 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000093 }
94
95 /// Start an instance of `crosvm` to manage a new VM. The `crosvm` instance will be killed when
96 /// the `VmInstance` is dropped.
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000097 pub fn start(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000098 config: &CrosvmConfig,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000099 log_fd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000100 composite_disk_mappings: &[FdMapping],
101 temporary_directory: PathBuf,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +0000102 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +0000103 requester_sid: String,
104 requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +0000105 ) -> Result<Arc<VmInstance>, Error> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000106 let child = run_vm(config, log_fd, composite_disk_mappings)?;
Andrew Walbran02034492021-04-13 15:05:07 +0000107 let instance = Arc::new(VmInstance::new(
108 child,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000109 config.cid,
110 temporary_directory,
Andrew Walbran02034492021-04-13 15:05:07 +0000111 requester_uid,
112 requester_sid,
113 requester_debug_pid,
114 ));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000115
Andrew Walbrandae07162021-03-12 17:05:20 +0000116 let instance_clone = instance.clone();
117 thread::spawn(move || {
118 instance_clone.monitor();
119 });
120
121 Ok(instance)
122 }
123
124 /// Wait for the crosvm child process to finish, then mark the VM as no longer running and call
125 /// any callbacks.
126 fn monitor(&self) {
127 match self.child.wait() {
128 Err(e) => error!("Error waiting for crosvm instance to die: {}", e),
129 Ok(status) => info!("crosvm exited with status {}", status),
130 }
131 self.running.store(false, Ordering::Release);
132 self.callbacks.callback_on_died(self.cid);
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000133
134 // Delete temporary files.
135 if let Err(e) = remove_dir_all(&self.temporary_directory) {
136 error!("Error removing temporary directory {:?}: {:?}", self.temporary_directory, e);
137 }
Andrew Walbrandae07162021-03-12 17:05:20 +0000138 }
139
140 /// Return whether `crosvm` is still running the VM.
141 pub fn running(&self) -> bool {
142 self.running.load(Ordering::Acquire)
143 }
144
145 /// Kill the crosvm instance.
146 pub fn kill(&self) {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000147 // TODO: Talk to crosvm to shutdown cleanly.
148 if let Err(e) = self.child.kill() {
149 error!("Error killing crosvm instance: {}", e);
150 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000151 }
152}
153
154/// Start an instance of `crosvm` to manage a new VM.
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000155fn run_vm(
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000156 config: &CrosvmConfig,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000157 log_fd: Option<File>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000158 composite_disk_mappings: &[FdMapping],
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000159) -> Result<SharedChild, Error> {
160 validate_config(config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000161
162 let mut command = Command::new(CROSVM_PATH);
163 // TODO(qwandor): Remove --disable-sandbox.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000164 command.arg("run").arg("--disable-sandbox").arg("--cid").arg(config.cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000165
Andrew Walbrana89fc132021-03-17 17:08:36 +0000166 if let Some(log_fd) = log_fd {
167 command.stdout(log_fd);
168 } else {
169 // Ignore console output.
170 command.arg("--serial=type=sink");
171 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000172
173 // Keep track of what file descriptors should be mapped to the crosvm process.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000174 let mut fd_mappings = composite_disk_mappings.to_vec();
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000175
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000176 if let Some(bootloader) = &config.bootloader {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000177 command.arg("--bios").arg(add_fd_mapping(&mut fd_mappings, bootloader));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000178 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000179
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000180 if let Some(initrd) = &config.initrd {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000181 command.arg("--initrd").arg(add_fd_mapping(&mut fd_mappings, initrd));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000182 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000183
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000184 if let Some(params) = &config.params {
185 command.arg("--params").arg(params);
186 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000187
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000188 for disk in &config.disks {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000189 command
190 .arg(if disk.writable { "--rwdisk" } else { "--disk" })
191 .arg(add_fd_mapping(&mut fd_mappings, &disk.image));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000192 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000193
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000194 if let Some(kernel) = &config.kernel {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000195 command.arg(add_fd_mapping(&mut fd_mappings, kernel));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000196 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000197
198 debug!("Setting mappings {:?}", fd_mappings);
199 command.fd_mappings(fd_mappings)?;
200
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000201 info!("Running {:?}", command);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000202 let result = SharedChild::spawn(&mut command)?;
203 Ok(result)
204}
205
206/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000207fn validate_config(config: &CrosvmConfig) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000208 if config.bootloader.is_none() && config.kernel.is_none() {
209 bail!("VM must have either a bootloader or a kernel image.");
210 }
211 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
212 bail!("Can't have both bootloader and kernel/initrd image.");
213 }
214 Ok(())
215}
216
217/// Adds a mapping for `file` to `fd_mappings`, and returns a string of the form "/proc/self/fd/N"
218/// where N is the file descriptor for the child process.
219fn add_fd_mapping(fd_mappings: &mut Vec<FdMapping>, file: &File) -> String {
220 let fd = file.as_raw_fd();
221 fd_mappings.push(FdMapping { parent_fd: fd, child_fd: fd });
222 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000223}