blob: aaa3988c50d2b244c704f14b4f2f50b7896362e7 [file] [log] [blame]
Andrew Walbranf395b822021-05-05 10:38:59 +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//! Command to run a VM.
16
Jiyong Park48b354d2021-07-15 15:04:38 +090017use crate::create_partition::command_create_partition;
Jooyung Han21e9b922021-06-26 04:14:16 +090018use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
Alan Stokes0e82b502022-08-08 14:44:48 +010019 IVirtualizationService::IVirtualizationService, PartitionType::PartitionType,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090020 VirtualMachineAppConfig::DebugLevel::DebugLevel,
Alan Stokes0e82b502022-08-08 14:44:48 +010021 VirtualMachineAppConfig::VirtualMachineAppConfig, VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbranf8d94112021-09-07 11:45:36 +000022 VirtualMachineState::VirtualMachineState,
Jooyung Han21e9b922021-06-26 04:14:16 +090023};
Inseob Kima5a262f2021-11-17 19:41:03 +090024use anyhow::{bail, Context, Error};
Alan Stokes0e82b502022-08-08 14:44:48 +010025use binder::ParcelFileDescriptor;
Inseob Kima5a262f2021-11-17 19:41:03 +090026use microdroid_payload_config::VmPayloadConfig;
Andrew Walbranf395b822021-05-05 10:38:59 +000027use std::fs::File;
Jiyong Park8611a6c2021-07-09 18:17:44 +090028use std::io::{self, BufRead, BufReader};
Andrew Walbranf395b822021-05-05 10:38:59 +000029use std::os::unix::io::{AsRawFd, FromRawFd};
Inseob Kima5a262f2021-11-17 19:41:03 +090030use std::path::{Path, PathBuf};
Alan Stokes2bead0d2022-09-05 16:58:34 +010031use vmclient::{ErrorCode, VmInstance};
Jiyong Park48b354d2021-07-15 15:04:38 +090032use vmconfig::{open_parcel_file, VmConfig};
Inseob Kima5a262f2021-11-17 19:41:03 +090033use zip::ZipArchive;
Andrew Walbranf395b822021-05-05 10:38:59 +000034
Jooyung Han21e9b922021-06-26 04:14:16 +090035/// Run a VM from the given APK, idsig, and config.
Jiyong Park48b354d2021-07-15 15:04:38 +090036#[allow(clippy::too_many_arguments)]
Jooyung Han21e9b922021-06-26 04:14:16 +090037pub fn command_run_app(
Seungjae Yoo62085c02022-08-12 04:44:52 +000038 name: Option<String>,
Andrew Walbran616d13f2022-05-12 18:35:55 +000039 service: &dyn IVirtualizationService,
Jooyung Han21e9b922021-06-26 04:14:16 +090040 apk: &Path,
41 idsig: &Path,
Jiyong Park48b354d2021-07-15 15:04:38 +090042 instance: &Path,
Jooyung Han21e9b922021-06-26 04:14:16 +090043 config_path: &str,
44 daemonize: bool,
Jiyong Parkb8182bb2021-10-26 22:53:08 +090045 console_path: Option<&Path>,
Jooyung Han21e9b922021-06-26 04:14:16 +090046 log_path: Option<&Path>,
Jiyong Parke558ab12022-07-07 20:18:55 +090047 ramdump_path: Option<&Path>,
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090048 debug_level: DebugLevel,
Andrew Walbran3994f002022-01-27 17:33:45 +000049 protected: bool,
Jiyong Parkd63cfff2021-09-27 20:10:17 +090050 mem: Option<u32>,
Jiyong Park032615f2022-01-10 13:55:34 +090051 cpus: Option<u32>,
52 cpu_affinity: Option<String>,
Jiyong Parkdfe16d62022-04-20 17:32:12 +090053 task_profiles: Vec<String>,
Inseob Kima5a262f2021-11-17 19:41:03 +090054 extra_idsigs: &[PathBuf],
Jooyung Han21e9b922021-06-26 04:14:16 +090055) -> Result<(), Error> {
Inseob Kima5a262f2021-11-17 19:41:03 +090056 let extra_apks = parse_extra_apk_list(apk, config_path)?;
57 if extra_apks.len() != extra_idsigs.len() {
58 bail!(
59 "Found {} extra apks, but there are {} extra idsigs",
60 extra_apks.len(),
61 extra_idsigs.len()
62 )
63 }
64
65 for i in 0..extra_apks.len() {
66 let extra_apk_fd = ParcelFileDescriptor::new(File::open(&extra_apks[i])?);
67 let extra_idsig_fd = ParcelFileDescriptor::new(File::create(&extra_idsigs[i])?);
68 service.createOrUpdateIdsigFile(&extra_apk_fd, &extra_idsig_fd)?;
69 }
70
Jooyung Han21e9b922021-06-26 04:14:16 +090071 let apk_file = File::open(apk).context("Failed to open APK file")?;
Jiyong Park0a248432021-08-20 23:32:39 +090072 let idsig_file = File::create(idsig).context("Failed to create idsig file")?;
73
74 let apk_fd = ParcelFileDescriptor::new(apk_file);
75 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
76 service.createOrUpdateIdsigFile(&apk_fd, &idsig_fd)?;
77
Jooyung Han21e9b922021-06-26 04:14:16 +090078 let idsig_file = File::open(idsig).context("Failed to open idsig file")?;
Jiyong Park0a248432021-08-20 23:32:39 +090079 let idsig_fd = ParcelFileDescriptor::new(idsig_file);
Jiyong Park48b354d2021-07-15 15:04:38 +090080
81 if !instance.exists() {
82 const INSTANCE_FILE_SIZE: u64 = 10 * 1024 * 1024;
Jiyong Park9dd389e2021-08-23 20:42:59 +090083 command_create_partition(
Andrew Walbran616d13f2022-05-12 18:35:55 +000084 service,
Jiyong Park9dd389e2021-08-23 20:42:59 +090085 instance,
86 INSTANCE_FILE_SIZE,
87 PartitionType::ANDROID_VM_INSTANCE,
88 )?;
Jiyong Park48b354d2021-07-15 15:04:38 +090089 }
90
Inseob Kima5a262f2021-11-17 19:41:03 +090091 let extra_idsig_files: Result<Vec<File>, _> = extra_idsigs.iter().map(File::open).collect();
92 let extra_idsig_fds = extra_idsig_files?.into_iter().map(ParcelFileDescriptor::new).collect();
93
Jooyung Han21e9b922021-06-26 04:14:16 +090094 let config = VirtualMachineConfig::AppConfig(VirtualMachineAppConfig {
Seungjae Yoo62085c02022-08-12 04:44:52 +000095 name: name.unwrap_or_else(|| String::from("VmRunApp")),
Jiyong Park0a248432021-08-20 23:32:39 +090096 apk: apk_fd.into(),
97 idsig: idsig_fd.into(),
Inseob Kima5a262f2021-11-17 19:41:03 +090098 extraIdsigs: extra_idsig_fds,
Jiyong Park48b354d2021-07-15 15:04:38 +090099 instanceImage: open_parcel_file(instance, true /* writable */)?.into(),
Jooyung Han21e9b922021-06-26 04:14:16 +0900100 configPath: config_path.to_owned(),
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900101 debugLevel: debug_level,
Andrew Walbran3994f002022-01-27 17:33:45 +0000102 protectedVm: protected,
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900103 memoryMib: mem.unwrap_or(0) as i32, // 0 means use the VM default
Jiyong Park032615f2022-01-10 13:55:34 +0900104 numCpus: cpus.unwrap_or(1) as i32,
105 cpuAffinity: cpu_affinity,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900106 taskProfiles: task_profiles,
Jooyung Han21e9b922021-06-26 04:14:16 +0900107 });
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900108 run(
109 service,
110 &config,
111 &format!("{:?}!{:?}", apk, config_path),
112 daemonize,
113 console_path,
114 log_path,
Jiyong Parke558ab12022-07-07 20:18:55 +0900115 ramdump_path,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900116 )
Jooyung Han21e9b922021-06-26 04:14:16 +0900117}
118
Andrew Walbranf395b822021-05-05 10:38:59 +0000119/// Run a VM from the given configuration file.
Jooyung Hanb7983a22022-02-22 05:21:27 +0900120#[allow(clippy::too_many_arguments)]
Andrew Walbranf395b822021-05-05 10:38:59 +0000121pub fn command_run(
Seungjae Yoo62085c02022-08-12 04:44:52 +0000122 name: Option<String>,
Andrew Walbran616d13f2022-05-12 18:35:55 +0000123 service: &dyn IVirtualizationService,
Andrew Walbranf395b822021-05-05 10:38:59 +0000124 config_path: &Path,
125 daemonize: bool,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900126 console_path: Option<&Path>,
Jooyung Hanb7983a22022-02-22 05:21:27 +0900127 log_path: Option<&Path>,
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900128 mem: Option<u32>,
Jiyong Park032615f2022-01-10 13:55:34 +0900129 cpus: Option<u32>,
130 cpu_affinity: Option<String>,
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900131 task_profiles: Vec<String>,
Andrew Walbranf395b822021-05-05 10:38:59 +0000132) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000133 let config_file = File::open(config_path).context("Failed to open config file")?;
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900134 let mut config =
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000135 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
Jiyong Parkd63cfff2021-09-27 20:10:17 +0900136 if let Some(mem) = mem {
137 config.memoryMib = mem as i32;
138 }
Jiyong Park032615f2022-01-10 13:55:34 +0900139 if let Some(cpus) = cpus {
140 config.numCpus = cpus as i32;
141 }
Seungjae Yoo62085c02022-08-12 04:44:52 +0000142 if let Some(name) = name {
143 config.name = name;
144 } else {
145 config.name = String::from("VmRun");
146 }
Jiyong Park032615f2022-01-10 13:55:34 +0900147 config.cpuAffinity = cpu_affinity;
Jiyong Parkdfe16d62022-04-20 17:32:12 +0900148 config.taskProfiles = task_profiles;
Jooyung Han21e9b922021-06-26 04:14:16 +0900149 run(
150 service,
151 &VirtualMachineConfig::RawConfig(config),
152 &format!("{:?}", config_path),
153 daemonize,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900154 console_path,
Jooyung Hanb7983a22022-02-22 05:21:27 +0900155 log_path,
Jiyong Parke558ab12022-07-07 20:18:55 +0900156 /* ramdump_path */ None,
Jooyung Han21e9b922021-06-26 04:14:16 +0900157 )
158}
159
Andrew Walbranf8d94112021-09-07 11:45:36 +0000160fn state_to_str(vm_state: VirtualMachineState) -> &'static str {
161 match vm_state {
162 VirtualMachineState::NOT_STARTED => "NOT_STARTED",
163 VirtualMachineState::STARTING => "STARTING",
164 VirtualMachineState::STARTED => "STARTED",
165 VirtualMachineState::READY => "READY",
166 VirtualMachineState::FINISHED => "FINISHED",
167 VirtualMachineState::DEAD => "DEAD",
168 _ => "(invalid state)",
169 }
170}
171
Jooyung Han21e9b922021-06-26 04:14:16 +0900172fn run(
Andrew Walbran616d13f2022-05-12 18:35:55 +0000173 service: &dyn IVirtualizationService,
Jooyung Han21e9b922021-06-26 04:14:16 +0900174 config: &VirtualMachineConfig,
175 config_path: &str,
176 daemonize: bool,
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900177 console_path: Option<&Path>,
Jooyung Han21e9b922021-06-26 04:14:16 +0900178 log_path: Option<&Path>,
Jiyong Parke558ab12022-07-07 20:18:55 +0900179 ramdump_path: Option<&Path>,
Jooyung Han21e9b922021-06-26 04:14:16 +0900180) -> Result<(), Error> {
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900181 let console = if let Some(console_path) = console_path {
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000182 Some(
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900183 File::create(console_path)
184 .with_context(|| format!("Failed to open console file {:?}", console_path))?,
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000185 )
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900186 } else if daemonize {
187 None
188 } else {
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000189 Some(duplicate_stdout()?)
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900190 };
191 let log = if let Some(log_path) = log_path {
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000192 Some(
Andrew Walbranbe429242021-06-28 12:22:54 +0000193 File::create(log_path)
194 .with_context(|| format!("Failed to open log file {:?}", log_path))?,
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000195 )
Andrew Walbranbe429242021-06-28 12:22:54 +0000196 } else if daemonize {
197 None
198 } else {
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000199 Some(duplicate_stdout()?)
Andrew Walbranbe429242021-06-28 12:22:54 +0000200 };
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900201
Alan Stokes0e82b502022-08-08 14:44:48 +0100202 let callback = Box::new(Callback {});
203 let vm = VmInstance::create(service, config, console, log, Some(callback))
204 .context("Failed to create VM")?;
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000205 vm.start().context("Failed to start VM")?;
Andrew Walbranf395b822021-05-05 10:38:59 +0000206
Andrew Walbranf8d94112021-09-07 11:45:36 +0000207 println!(
208 "Created VM from {} with CID {}, state is {}.",
209 config_path,
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000210 vm.cid(),
211 state_to_str(vm.state()?)
Andrew Walbranf8d94112021-09-07 11:45:36 +0000212 );
Andrew Walbranf395b822021-05-05 10:38:59 +0000213
214 if daemonize {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000215 // Pass the VM reference back to VirtualizationService and have it hold it in the
216 // background.
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000217 service.debugHoldVmRef(&vm.vm).context("Failed to pass VM to VirtualizationService")?;
Andrew Walbranf395b822021-05-05 10:38:59 +0000218 } else {
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000219 // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
Andrew Walbranf395b822021-05-05 10:38:59 +0000220 // IVirtualMachine Binder object would be dropped and the VM would be killed.
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000221 let death_reason = vm.wait_for_death();
Jiyong Parke558ab12022-07-07 20:18:55 +0900222
223 if let Some(path) = ramdump_path {
224 save_ramdump_if_available(path, &vm)?;
225 }
Alan Stokes2bead0d2022-09-05 16:58:34 +0100226 println!("VM ended: {:?}", death_reason);
Andrew Walbranf395b822021-05-05 10:38:59 +0000227 }
Andrew Walbranf395b822021-05-05 10:38:59 +0000228
Andrew Walbranf395b822021-05-05 10:38:59 +0000229 Ok(())
230}
231
Jiyong Parke558ab12022-07-07 20:18:55 +0900232fn save_ramdump_if_available(path: &Path, vm: &VmInstance) -> Result<(), Error> {
233 if let Some(mut ramdump) = vm.get_ramdump() {
234 let mut file =
235 File::create(path).context(format!("Failed to create ramdump file {:?}", path))?;
236 let size = std::io::copy(&mut ramdump, &mut file)
237 .context(format!("Failed to save ramdump to file {:?}", path))?;
238 eprintln!("Ramdump ({} bytes) saved to {:?}", size, path);
239 }
240 Ok(())
241}
242
Inseob Kima5a262f2021-11-17 19:41:03 +0900243fn parse_extra_apk_list(apk: &Path, config_path: &str) -> Result<Vec<String>, Error> {
244 let mut archive = ZipArchive::new(File::open(apk)?)?;
245 let config_file = archive.by_name(config_path)?;
246 let config: VmPayloadConfig = serde_json::from_reader(config_file)?;
247 Ok(config.extra_apks.into_iter().map(|x| x.path).collect())
248}
249
Alan Stokes0e82b502022-08-08 14:44:48 +0100250struct Callback {}
Andrew Walbranf395b822021-05-05 10:38:59 +0000251
Alan Stokes0e82b502022-08-08 14:44:48 +0100252impl vmclient::VmCallback for Callback {
253 fn on_payload_started(&self, _cid: i32, stream: Option<&File>) {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900254 // Show the output of the payload
255 if let Some(stream) = stream {
Jiyong Parke39c7652022-09-02 16:45:57 +0900256 let mut reader = BufReader::new(stream.try_clone().unwrap());
257 std::thread::spawn(move || loop {
Inseob Kim7f61fe72021-08-20 20:50:47 +0900258 let mut s = String::new();
259 match reader.read_line(&mut s) {
260 Ok(0) => break,
261 Ok(_) => print!("{}", s),
262 Err(e) => eprintln!("error reading from virtual machine: {}", e),
263 };
Jiyong Parke39c7652022-09-02 16:45:57 +0900264 });
Jiyong Park8611a6c2021-07-09 18:17:44 +0900265 }
Jiyong Park8611a6c2021-07-09 18:17:44 +0900266 }
267
Alan Stokes0e82b502022-08-08 14:44:48 +0100268 fn on_payload_ready(&self, _cid: i32) {
Inseob Kim8dbc3222021-09-01 21:50:23 +0900269 eprintln!("payload is ready");
Inseob Kim14cb8692021-08-31 21:50:39 +0900270 }
271
Alan Stokes0e82b502022-08-08 14:44:48 +0100272 fn on_payload_finished(&self, _cid: i32, exit_code: i32) {
Inseob Kim8dbc3222021-09-01 21:50:23 +0900273 eprintln!("payload finished with exit code {}", exit_code);
Inseob Kim2444af92021-08-31 01:22:50 +0900274 }
275
Alan Stokes2bead0d2022-09-05 16:58:34 +0100276 fn on_error(&self, _cid: i32, error_code: ErrorCode, message: &str) {
277 eprintln!("VM encountered an error: code={:?}, message={}", error_code, message);
Andrew Walbranf395b822021-05-05 10:38:59 +0000278 }
279}
280
281/// Safely duplicate the standard output file descriptor.
282fn duplicate_stdout() -> io::Result<File> {
283 let stdout_fd = io::stdout().as_raw_fd();
284 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
285 // for an error.
286 let dup_fd = unsafe { libc::dup(stdout_fd) };
287 if dup_fd < 0 {
288 Err(io::Error::last_os_error())
289 } else {
290 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
291 // takes ownership of it.
292 Ok(unsafe { File::from_raw_fd(dup_fd) })
293 }
294}