blob: 5e6f65840bca4015a9babbf32e649845a1eedc66 [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::config::VmConfig;
19use crate::Cid;
20use anyhow::Error;
Andrew Walbrandae07162021-03-12 17:05:20 +000021use log::{error, info};
22use shared_child::SharedChild;
Andrew Walbrana89fc132021-03-17 17:08:36 +000023use std::fs::File;
Andrew Walbrandae07162021-03-12 17:05:20 +000024use std::process::Command;
25use std::sync::atomic::{AtomicBool, Ordering};
26use std::sync::Arc;
27use std::thread;
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000028
29const CROSVM_PATH: &str = "/apex/com.android.virt/bin/crosvm";
30
31/// Information about a particular instance of a VM which is running.
32#[derive(Debug)]
33pub struct VmInstance {
34 /// The crosvm child process.
Andrew Walbrandae07162021-03-12 17:05:20 +000035 child: SharedChild,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000036 /// The CID assigned to the VM for vsock communication.
37 pub cid: Cid,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000038 /// The UID of the process which requested the VM.
39 pub requester_uid: u32,
40 /// The SID of the process which requested the VM.
41 pub requester_sid: Option<String>,
42 /// The PID of the process which requested the VM. Note that this process may no longer exist
43 /// and the PID may have been reused for a different process, so this should not be trusted.
44 pub requester_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +000045 /// Whether the VM is still running.
46 running: AtomicBool,
47 /// Callbacks to clients of the VM.
48 pub callbacks: VirtualMachineCallbacks,
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000049}
50
51impl VmInstance {
52 /// Create a new `VmInstance` for the given process.
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000053 fn new(
Andrew Walbrandae07162021-03-12 17:05:20 +000054 child: SharedChild,
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000055 cid: Cid,
56 requester_uid: u32,
57 requester_sid: Option<String>,
58 requester_pid: i32,
59 ) -> VmInstance {
Andrew Walbrandae07162021-03-12 17:05:20 +000060 VmInstance {
61 child,
62 cid,
63 requester_uid,
64 requester_sid,
65 requester_pid,
66 running: AtomicBool::new(true),
67 callbacks: Default::default(),
68 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000069 }
70
71 /// Start an instance of `crosvm` to manage a new VM. The `crosvm` instance will be killed when
72 /// the `VmInstance` is dropped.
Andrew Walbranf6a1eb92021-04-01 11:16:02 +000073 pub fn start(
74 config: &VmConfig,
75 cid: Cid,
76 log_fd: Option<File>,
77 requester_uid: u32,
78 requester_sid: Option<String>,
79 requester_pid: i32,
Andrew Walbrandae07162021-03-12 17:05:20 +000080 ) -> Result<Arc<VmInstance>, Error> {
Andrew Walbrana89fc132021-03-17 17:08:36 +000081 let child = run_vm(config, cid, log_fd)?;
Andrew Walbrandae07162021-03-12 17:05:20 +000082 let instance =
83 Arc::new(VmInstance::new(child, cid, requester_uid, requester_sid, requester_pid));
Andrew Walbrand6dce6f2021-03-05 16:39:08 +000084
Andrew Walbrandae07162021-03-12 17:05:20 +000085 let instance_clone = instance.clone();
86 thread::spawn(move || {
87 instance_clone.monitor();
88 });
89
90 Ok(instance)
91 }
92
93 /// Wait for the crosvm child process to finish, then mark the VM as no longer running and call
94 /// any callbacks.
95 fn monitor(&self) {
96 match self.child.wait() {
97 Err(e) => error!("Error waiting for crosvm instance to die: {}", e),
98 Ok(status) => info!("crosvm exited with status {}", status),
99 }
100 self.running.store(false, Ordering::Release);
101 self.callbacks.callback_on_died(self.cid);
102 }
103
104 /// Return whether `crosvm` is still running the VM.
105 pub fn running(&self) -> bool {
106 self.running.load(Ordering::Acquire)
107 }
108
109 /// Kill the crosvm instance.
110 pub fn kill(&self) {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000111 // TODO: Talk to crosvm to shutdown cleanly.
112 if let Err(e) = self.child.kill() {
113 error!("Error killing crosvm instance: {}", e);
114 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000115 }
116}
117
118/// Start an instance of `crosvm` to manage a new VM.
Andrew Walbrandae07162021-03-12 17:05:20 +0000119fn run_vm(config: &VmConfig, cid: Cid, log_fd: Option<File>) -> Result<SharedChild, Error> {
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000120 config.validate()?;
121
122 let mut command = Command::new(CROSVM_PATH);
123 // TODO(qwandor): Remove --disable-sandbox.
124 command.arg("run").arg("--disable-sandbox").arg("--cid").arg(cid.to_string());
Andrew Walbrana89fc132021-03-17 17:08:36 +0000125 if let Some(log_fd) = log_fd {
126 command.stdout(log_fd);
127 } else {
128 // Ignore console output.
129 command.arg("--serial=type=sink");
130 }
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000131 if let Some(bootloader) = &config.bootloader {
132 command.arg("--bios").arg(bootloader);
133 }
134 if let Some(initrd) = &config.initrd {
135 command.arg("--initrd").arg(initrd);
136 }
137 if let Some(params) = &config.params {
138 command.arg("--params").arg(params);
139 }
140 for disk in &config.disks {
141 command.arg(if disk.writable { "--rwdisk" } else { "--disk" }).arg(&disk.image);
142 }
143 if let Some(kernel) = &config.kernel {
144 command.arg(kernel);
145 }
146 info!("Running {:?}", command);
Andrew Walbrandae07162021-03-12 17:05:20 +0000147 Ok(SharedChild::spawn(&mut command)?)
Andrew Walbrand6dce6f2021-03-05 16:39:08 +0000148}