blob: d215d7cf116b48dd90696a6297fc2d870552132c [file] [log] [blame]
Andrew Walbranea9fa482021-03-04 16:11:12 +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 VM control tool.
16
Jooyung Hanc221c052022-02-22 05:20:15 +090017mod create_idsig;
Jiyong Park48b354d2021-07-15 15:04:38 +090018mod create_partition;
Andrew Walbranf395b822021-05-05 10:38:59 +000019mod run;
Andrew Walbranea9fa482021-03-04 16:11:12 +000020mod sync;
21
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090022use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
23 IVirtualizationService::IVirtualizationService, PartitionType::PartitionType,
24 VirtualMachineAppConfig::DebugLevel::DebugLevel,
25};
Jiyong Park48b354d2021-07-15 15:04:38 +090026use android_system_virtualizationservice::binder::{wait_for_interface, ProcessState, Strong};
David Brazdil20412d92021-03-18 10:53:06 +000027use anyhow::{Context, Error};
Jooyung Hanc221c052022-02-22 05:20:15 +090028use create_idsig::command_create_idsig;
Jiyong Park48b354d2021-07-15 15:04:38 +090029use create_partition::command_create_partition;
Jooyung Han21e9b922021-06-26 04:14:16 +090030use run::{command_run, command_run_app};
Andrew Walbranc4b1bde2022-02-03 15:26:02 +000031use rustutils::system_properties;
32use std::path::{Path, PathBuf};
David Brazdil20412d92021-03-18 10:53:06 +000033use structopt::clap::AppSettings;
34use structopt::StructOpt;
Andrew Walbranea9fa482021-03-04 16:11:12 +000035
Andrew Walbran17de24f2021-05-27 13:27:30 +000036const VIRTUALIZATION_SERVICE_BINDER_SERVICE_IDENTIFIER: &str =
37 "android.system.virtualizationservice";
Andrew Walbranea9fa482021-03-04 16:11:12 +000038
Inseob Kima5a262f2021-11-17 19:41:03 +090039#[derive(Debug)]
40struct Idsigs(Vec<PathBuf>);
41
David Brazdil20412d92021-03-18 10:53:06 +000042#[derive(StructOpt)]
43#[structopt(no_version, global_settings = &[AppSettings::DisableVersion])]
44enum Opt {
Jooyung Han21e9b922021-06-26 04:14:16 +090045 /// Run a virtual machine with a config in APK
46 RunApp {
47 /// Path to VM Payload APK
48 #[structopt(parse(from_os_str))]
49 apk: PathBuf,
50
51 /// Path to idsig of the APK
52 #[structopt(parse(from_os_str))]
53 idsig: PathBuf,
54
Jiyong Park48b354d2021-07-15 15:04:38 +090055 /// Path to the instance image. Created if not exists.
56 #[structopt(parse(from_os_str))]
57 instance: PathBuf,
58
Jooyung Han21e9b922021-06-26 04:14:16 +090059 /// Path to VM config JSON within APK (e.g. assets/vm_config.json)
60 config_path: String,
61
62 /// Detach VM from the terminal and run in the background
63 #[structopt(short, long)]
64 daemonize: bool,
65
Jiyong Parkb8182bb2021-10-26 22:53:08 +090066 /// Path to file for VM console output.
67 #[structopt(long)]
68 console: Option<PathBuf>,
69
Jooyung Han21e9b922021-06-26 04:14:16 +090070 /// Path to file for VM log output.
Jiyong Parkb8182bb2021-10-26 22:53:08 +090071 #[structopt(long)]
Jooyung Han21e9b922021-06-26 04:14:16 +090072 log: Option<PathBuf>,
Jiyong Park23601142021-07-05 13:15:32 +090073
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090074 /// Debug level of the VM. Supported values: "none" (default), "app_only", and "full".
Jiyong Parkb8182bb2021-10-26 22:53:08 +090075 #[structopt(long, default_value = "none", parse(try_from_str=parse_debug_level))]
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090076 debug: DebugLevel,
Jiyong Parkd63cfff2021-09-27 20:10:17 +090077
Andrew Walbran3994f002022-01-27 17:33:45 +000078 /// Run VM in protected mode.
79 #[structopt(short, long)]
80 protected: bool,
81
Jiyong Parkd63cfff2021-09-27 20:10:17 +090082 /// Memory size (in MiB) of the VM. If unspecified, defaults to the value of `memory_mib`
83 /// in the VM config file.
84 #[structopt(short, long)]
85 mem: Option<u32>,
Inseob Kima5a262f2021-11-17 19:41:03 +090086
Jiyong Park032615f2022-01-10 13:55:34 +090087 /// Number of vCPUs in the VM. If unspecified, defaults to 1.
88 #[structopt(long)]
89 cpus: Option<u32>,
90
91 /// Host CPUs where vCPUs are run on. If unspecified, vCPU runs on any host CPU.
92 #[structopt(long)]
93 cpu_affinity: Option<String>,
94
Inseob Kima5a262f2021-11-17 19:41:03 +090095 /// Paths to extra idsig files.
Victor Hsieh99782572022-01-05 15:38:33 -080096 #[structopt(long = "extra-idsig")]
Inseob Kima5a262f2021-11-17 19:41:03 +090097 extra_idsigs: Vec<PathBuf>,
Jooyung Han21e9b922021-06-26 04:14:16 +090098 },
David Brazdil20412d92021-03-18 10:53:06 +000099 /// Run a virtual machine
100 Run {
101 /// Path to VM config JSON
102 #[structopt(parse(from_os_str))]
103 config: PathBuf,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000104
105 /// Detach VM from the terminal and run in the background
106 #[structopt(short, long)]
107 daemonize: bool,
Andrew Walbranbe429242021-06-28 12:22:54 +0000108
Jiyong Park032615f2022-01-10 13:55:34 +0900109 /// Number of vCPUs in the VM. If unspecified, defaults to 1.
110 #[structopt(long)]
111 cpus: Option<u32>,
112
113 /// Host CPUs where vCPUs are run on. If unspecified, vCPU runs on any host CPU. The format
114 /// can be either a comma-separated list of CPUs or CPU ranges to run vCPUs on (e.g.
115 /// "0,1-3,5" to choose host CPUs 0, 1, 2, 3, and 5, or a colon-separated list of
116 /// assignments of vCPU-to-host-CPU assignments e.g. "0=0:1=1:2=2" to map vCPU 0 to host
117 /// CPU 0 and so on.
118 #[structopt(long)]
119 cpu_affinity: Option<String>,
120
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900121 /// Path to file for VM console output.
122 #[structopt(long)]
123 console: Option<PathBuf>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000124 },
125 /// Stop a virtual machine running in the background
126 Stop {
127 /// CID of the virtual machine
128 cid: u32,
David Brazdil20412d92021-03-18 10:53:06 +0000129 },
130 /// List running virtual machines
131 List,
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000132 /// Print information about virtual machine support
133 Info,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000134 /// Create a new empty partition to be used as a writable partition for a VM
135 CreatePartition {
136 /// Path at which to create the image file
137 #[structopt(parse(from_os_str))]
138 path: PathBuf,
139
140 /// The desired size of the partition, in bytes.
141 size: u64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900142
143 /// Type of the partition
144 #[structopt(short="t", long="type", default_value="raw", parse(try_from_str=parse_partition_type))]
145 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000146 },
Jooyung Hanc221c052022-02-22 05:20:15 +0900147 /// Creates or update the idsig file by digesting the input APK file.
148 CreateIdsig {
149 /// Path to VM Payload APK
150 #[structopt(parse(from_os_str))]
151 apk: PathBuf,
152 /// Path to idsig of the APK
153 #[structopt(parse(from_os_str))]
154 path: PathBuf,
155 },
David Brazdil20412d92021-03-18 10:53:06 +0000156}
157
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900158fn parse_debug_level(s: &str) -> Result<DebugLevel, String> {
159 match s {
160 "none" => Ok(DebugLevel::NONE),
161 "app_only" => Ok(DebugLevel::APP_ONLY),
162 "full" => Ok(DebugLevel::FULL),
163 _ => Err(format!("Invalid debug level {}", s)),
164 }
165}
166
Jiyong Park9dd389e2021-08-23 20:42:59 +0900167fn parse_partition_type(s: &str) -> Result<PartitionType, String> {
168 match s {
169 "raw" => Ok(PartitionType::RAW),
170 "instance" => Ok(PartitionType::ANDROID_VM_INSTANCE),
171 _ => Err(format!("Invalid partition type {}", s)),
172 }
173}
174
Andrew Walbranea9fa482021-03-04 16:11:12 +0000175fn main() -> Result<(), Error> {
176 env_logger::init();
David Brazdil20412d92021-03-18 10:53:06 +0000177 let opt = Opt::from_args();
Andrew Walbranea9fa482021-03-04 16:11:12 +0000178
179 // We need to start the thread pool for Binder to work properly, especially link_to_death.
180 ProcessState::start_thread_pool();
181
Andrew Walbranf1453802021-03-29 17:12:54 +0000182 let service = wait_for_interface(VIRTUALIZATION_SERVICE_BINDER_SERVICE_IDENTIFIER)
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000183 .context("Failed to find VirtualizationService")?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000184
David Brazdil20412d92021-03-18 10:53:06 +0000185 match opt {
Inseob Kima5a262f2021-11-17 19:41:03 +0900186 Opt::RunApp {
187 apk,
188 idsig,
189 instance,
190 config_path,
191 daemonize,
192 console,
193 log,
194 debug,
Andrew Walbran3994f002022-01-27 17:33:45 +0000195 protected,
Inseob Kima5a262f2021-11-17 19:41:03 +0900196 mem,
Jiyong Park032615f2022-01-10 13:55:34 +0900197 cpus,
198 cpu_affinity,
Inseob Kima5a262f2021-11-17 19:41:03 +0900199 extra_idsigs,
200 } => command_run_app(
201 service,
202 &apk,
203 &idsig,
204 &instance,
205 &config_path,
206 daemonize,
207 console.as_deref(),
208 log.as_deref(),
209 debug,
Andrew Walbran3994f002022-01-27 17:33:45 +0000210 protected,
Inseob Kima5a262f2021-11-17 19:41:03 +0900211 mem,
Jiyong Park032615f2022-01-10 13:55:34 +0900212 cpus,
213 cpu_affinity,
Inseob Kima5a262f2021-11-17 19:41:03 +0900214 &extra_idsigs,
215 ),
Jiyong Park032615f2022-01-10 13:55:34 +0900216 Opt::Run { config, daemonize, cpus, cpu_affinity, console } => {
217 command_run(
218 service,
219 &config,
220 daemonize,
221 console.as_deref(),
222 /* mem */ None,
223 cpus,
224 cpu_affinity,
225 )
Andrew Walbranbe429242021-06-28 12:22:54 +0000226 }
Andrew Walbran17de24f2021-05-27 13:27:30 +0000227 Opt::Stop { cid } => command_stop(service, cid),
228 Opt::List => command_list(service),
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000229 Opt::Info => command_info(),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900230 Opt::CreatePartition { path, size, partition_type } => {
231 command_create_partition(service, &path, size, partition_type)
232 }
Jooyung Hanc221c052022-02-22 05:20:15 +0900233 Opt::CreateIdsig { apk, path } => command_create_idsig(service, &apk, &path),
Andrew Walbranea9fa482021-03-04 16:11:12 +0000234 }
235}
236
David Brazdil3c2ddef2021-03-18 13:09:57 +0000237/// Retrieve reference to a previously daemonized VM and stop it.
Andrew Walbran17de24f2021-05-27 13:27:30 +0000238fn command_stop(service: Strong<dyn IVirtualizationService>, cid: u32) -> Result<(), Error> {
239 service
David Brazdil3c2ddef2021-03-18 13:09:57 +0000240 .debugDropVmRef(cid as i32)
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000241 .context("Failed to get VM from VirtualizationService")?
David Brazdil3c2ddef2021-03-18 13:09:57 +0000242 .context("CID does not correspond to a running background VM")?;
Andrew Walbranea9fa482021-03-04 16:11:12 +0000243 Ok(())
244}
245
Andrew Walbran320b5602021-03-04 16:11:12 +0000246/// List the VMs currently running.
Andrew Walbran17de24f2021-05-27 13:27:30 +0000247fn command_list(service: Strong<dyn IVirtualizationService>) -> Result<(), Error> {
248 let vms = service.debugListVms().context("Failed to get list of VMs")?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000249 println!("Running VMs: {:#?}", vms);
250 Ok(())
251}
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000252
253/// Print information about supported VM types.
254fn command_info() -> Result<(), Error> {
255 let unprotected_vm_supported =
256 system_properties::read_bool("ro.boot.hypervisor.vm.supported", false)?;
257 let protected_vm_supported =
258 system_properties::read_bool("ro.boot.hypervisor.protected_vm.supported", false)?;
259 match (unprotected_vm_supported, protected_vm_supported) {
260 (false, false) => println!("VMs are not supported."),
261 (false, true) => println!("Only protected VMs are supported."),
262 (true, false) => println!("Only unprotected VMs are supported."),
263 (true, true) => println!("Both protected and unprotected VMs are supported."),
264 }
265
Andrew Walbran014efb52022-02-03 17:43:11 +0000266 if let Some(version) = system_properties::read("ro.boot.hypervisor.version")? {
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000267 println!("Hypervisor version: {}", version);
268 } else {
269 println!("Hypervisor version not set.");
270 }
271
272 if Path::new("/dev/kvm").exists() {
273 println!("/dev/kvm exists.");
274 } else {
275 println!("/dev/kvm does not exist.");
276 }
277
278 Ok(())
279}