blob: 552941d06f9ddcdcbd5e11228c8d5b237cb79d9c [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 Walbranf6bf6862021-05-21 12:41:13 +000019use android_system_virtualizationservice::aidl::android::system::virtualizationservice::VirtualMachineConfig::VirtualMachineConfig;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000020use anyhow::{bail, Context, Error};
21use command_fds::{CommandFdExt, FdMapping};
22use log::{debug, error, info};
Andrew Walbrandae07162021-03-12 17:05:20 +000023use shared_child::SharedChild;
Andrew Walbrana89fc132021-03-17 17:08:36 +000024use std::fs::File;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000025use std::os::unix::io::AsRawFd;
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
33/// Information about a particular instance of a VM which is running.
34#[derive(Debug)]
35pub struct VmInstance {
36 /// The crosvm child process.
Andrew Walbrandae07162021-03-12 17:05:20 +000037 child: SharedChild,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000038 /// The CID assigned to the VM for vsock communication.
39 pub cid: Cid,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000040 /// The UID of the process which requested the VM.
41 pub requester_uid: u32,
42 /// The SID of the process which requested the VM.
Andrew Walbran02034492021-04-13 15:05:07 +000043 pub requester_sid: String,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000044 /// The PID of the process which requested the VM. Note that this process may no longer exist
45 /// and the PID may have been reused for a different process, so this should not be trusted.
Andrew Walbran02034492021-04-13 15:05:07 +000046 pub requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +000047 /// Whether the VM is still running.
48 running: AtomicBool,
49 /// Callbacks to clients of the VM.
50 pub callbacks: VirtualMachineCallbacks,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000051}
52
53impl VmInstance {
54 /// Create a new `VmInstance` for the given process.
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000055 fn new(
Andrew Walbrandae07162021-03-12 17:05:20 +000056 child: SharedChild,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000057 cid: Cid,
58 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +000059 requester_sid: String,
60 requester_debug_pid: i32,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000061 ) -> VmInstance {
Andrew Walbrandae07162021-03-12 17:05:20 +000062 VmInstance {
63 child,
64 cid,
65 requester_uid,
66 requester_sid,
Andrew Walbran02034492021-04-13 15:05:07 +000067 requester_debug_pid,
Andrew Walbrandae07162021-03-12 17:05:20 +000068 running: AtomicBool::new(true),
69 callbacks: Default::default(),
70 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000071 }
72
73 /// Start an instance of `crosvm` to manage a new VM. The `crosvm` instance will be killed when
74 /// the `VmInstance` is dropped.
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000075 pub fn start(
Andrew Walbran3a5a9212021-05-04 17:09:08 +000076 config: &VirtualMachineConfig,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000077 cid: Cid,
78 log_fd: Option<File>,
79 requester_uid: u32,
Andrew Walbran02034492021-04-13 15:05:07 +000080 requester_sid: String,
81 requester_debug_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +000082 ) -> Result<Arc<VmInstance>, Error> {
Andrew Walbrana89fc132021-03-17 17:08:36 +000083 let child = run_vm(config, cid, log_fd)?;
Andrew Walbran02034492021-04-13 15:05:07 +000084 let instance = Arc::new(VmInstance::new(
85 child,
86 cid,
87 requester_uid,
88 requester_sid,
89 requester_debug_pid,
90 ));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000091
Andrew Walbrandae07162021-03-12 17:05:20 +000092 let instance_clone = instance.clone();
93 thread::spawn(move || {
94 instance_clone.monitor();
95 });
96
97 Ok(instance)
98 }
99
100 /// Wait for the crosvm child process to finish, then mark the VM as no longer running and call
101 /// any callbacks.
102 fn monitor(&self) {
103 match self.child.wait() {
104 Err(e) => error!("Error waiting for crosvm instance to die: {}", e),
105 Ok(status) => info!("crosvm exited with status {}", status),
106 }
107 self.running.store(false, Ordering::Release);
108 self.callbacks.callback_on_died(self.cid);
109 }
110
111 /// Return whether `crosvm` is still running the VM.
112 pub fn running(&self) -> bool {
113 self.running.load(Ordering::Acquire)
114 }
115
116 /// Kill the crosvm instance.
117 pub fn kill(&self) {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000118 // TODO: Talk to crosvm to shutdown cleanly.
119 if let Err(e) = self.child.kill() {
120 error!("Error killing crosvm instance: {}", e);
121 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000122 }
123}
124
125/// Start an instance of `crosvm` to manage a new VM.
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000126fn run_vm(
127 config: &VirtualMachineConfig,
128 cid: Cid,
129 log_fd: Option<File>,
130) -> Result<SharedChild, Error> {
131 validate_config(config)?;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000132
133 let mut command = Command::new(CROSVM_PATH);
134 // TODO(qwandor): Remove --disable-sandbox.
135 command.arg("run").arg("--disable-sandbox").arg("--cid").arg(cid.to_string());
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000136
Andrew Walbrana89fc132021-03-17 17:08:36 +0000137 if let Some(log_fd) = log_fd {
138 command.stdout(log_fd);
139 } else {
140 // Ignore console output.
141 command.arg("--serial=type=sink");
142 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000143
144 // Keep track of what file descriptors should be mapped to the crosvm process.
145 let mut fd_mappings = vec![];
146
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000147 if let Some(bootloader) = &config.bootloader {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000148 command.arg("--bios").arg(add_fd_mapping(&mut fd_mappings, bootloader.as_ref()));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000149 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000150
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000151 if let Some(initrd) = &config.initrd {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000152 command.arg("--initrd").arg(add_fd_mapping(&mut fd_mappings, initrd.as_ref()));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000153 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000154
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000155 if let Some(params) = &config.params {
156 command.arg("--params").arg(params);
157 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000158
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000159 for disk in &config.disks {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000160 command.arg(if disk.writable { "--rwdisk" } else { "--disk" }).arg(add_fd_mapping(
161 &mut fd_mappings,
162 // TODO(b/187187765): This shouldn't be an Option.
163 disk.image.as_ref().context("Invalid disk image file descriptor")?.as_ref(),
164 ));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000165 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000166
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000167 if let Some(kernel) = &config.kernel {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000168 command.arg(add_fd_mapping(&mut fd_mappings, kernel.as_ref()));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000169 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000170
171 debug!("Setting mappings {:?}", fd_mappings);
172 command.fd_mappings(fd_mappings)?;
173
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000174 info!("Running {:?}", command);
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000175 let result = SharedChild::spawn(&mut command)?;
176 Ok(result)
177}
178
179/// Ensure that the configuration has a valid combination of fields set, or return an error if not.
180fn validate_config(config: &VirtualMachineConfig) -> Result<(), Error> {
181 if config.bootloader.is_none() && config.kernel.is_none() {
182 bail!("VM must have either a bootloader or a kernel image.");
183 }
184 if config.bootloader.is_some() && (config.kernel.is_some() || config.initrd.is_some()) {
185 bail!("Can't have both bootloader and kernel/initrd image.");
186 }
187 Ok(())
188}
189
190/// Adds a mapping for `file` to `fd_mappings`, and returns a string of the form "/proc/self/fd/N"
191/// where N is the file descriptor for the child process.
192fn add_fd_mapping(fd_mappings: &mut Vec<FdMapping>, file: &File) -> String {
193 let fd = file.as_raw_fd();
194 fd_mappings.push(FdMapping { parent_fd: fd, child_fd: fd });
195 format!("/proc/self/fd/{}", fd)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000196}