blob: 2cbae3ef3ab3d83ff0975d97ec438efe2ec6cd58 [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
Jiyong Park48b354d2021-07-15 15:04:38 +090017mod create_partition;
Andrew Walbranf395b822021-05-05 10:38:59 +000018mod run;
Andrew Walbranea9fa482021-03-04 16:11:12 +000019mod sync;
20
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090021use android_system_virtualizationservice::aidl::android::system::virtualizationservice::{
22 IVirtualizationService::IVirtualizationService, PartitionType::PartitionType,
23 VirtualMachineAppConfig::DebugLevel::DebugLevel,
24};
Jiyong Park48b354d2021-07-15 15:04:38 +090025use android_system_virtualizationservice::binder::{wait_for_interface, ProcessState, Strong};
David Brazdil20412d92021-03-18 10:53:06 +000026use anyhow::{Context, Error};
Jiyong Park48b354d2021-07-15 15:04:38 +090027use create_partition::command_create_partition;
Jooyung Han21e9b922021-06-26 04:14:16 +090028use run::{command_run, command_run_app};
Andrew Walbranc4b1bde2022-02-03 15:26:02 +000029use rustutils::system_properties;
30use std::path::{Path, PathBuf};
David Brazdil20412d92021-03-18 10:53:06 +000031use structopt::clap::AppSettings;
32use structopt::StructOpt;
Andrew Walbranea9fa482021-03-04 16:11:12 +000033
Andrew Walbran17de24f2021-05-27 13:27:30 +000034const VIRTUALIZATION_SERVICE_BINDER_SERVICE_IDENTIFIER: &str =
35 "android.system.virtualizationservice";
Andrew Walbranea9fa482021-03-04 16:11:12 +000036
Inseob Kima5a262f2021-11-17 19:41:03 +090037#[derive(Debug)]
38struct Idsigs(Vec<PathBuf>);
39
David Brazdil20412d92021-03-18 10:53:06 +000040#[derive(StructOpt)]
41#[structopt(no_version, global_settings = &[AppSettings::DisableVersion])]
42enum Opt {
Jooyung Han21e9b922021-06-26 04:14:16 +090043 /// Run a virtual machine with a config in APK
44 RunApp {
45 /// Path to VM Payload APK
46 #[structopt(parse(from_os_str))]
47 apk: PathBuf,
48
49 /// Path to idsig of the APK
50 #[structopt(parse(from_os_str))]
51 idsig: PathBuf,
52
Jiyong Park48b354d2021-07-15 15:04:38 +090053 /// Path to the instance image. Created if not exists.
54 #[structopt(parse(from_os_str))]
55 instance: PathBuf,
56
Jooyung Han21e9b922021-06-26 04:14:16 +090057 /// Path to VM config JSON within APK (e.g. assets/vm_config.json)
58 config_path: String,
59
60 /// Detach VM from the terminal and run in the background
61 #[structopt(short, long)]
62 daemonize: bool,
63
Jiyong Parkb8182bb2021-10-26 22:53:08 +090064 /// Path to file for VM console output.
65 #[structopt(long)]
66 console: Option<PathBuf>,
67
Jooyung Han21e9b922021-06-26 04:14:16 +090068 /// Path to file for VM log output.
Jiyong Parkb8182bb2021-10-26 22:53:08 +090069 #[structopt(long)]
Jooyung Han21e9b922021-06-26 04:14:16 +090070 log: Option<PathBuf>,
Jiyong Park23601142021-07-05 13:15:32 +090071
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090072 /// Debug level of the VM. Supported values: "none" (default), "app_only", and "full".
Jiyong Parkb8182bb2021-10-26 22:53:08 +090073 #[structopt(long, default_value = "none", parse(try_from_str=parse_debug_level))]
Jiyong Parkc2a49cc2021-10-15 00:02:12 +090074 debug: DebugLevel,
Jiyong Parkd63cfff2021-09-27 20:10:17 +090075
Andrew Walbran3994f002022-01-27 17:33:45 +000076 /// Run VM in protected mode.
77 #[structopt(short, long)]
78 protected: bool,
79
Jiyong Parkd63cfff2021-09-27 20:10:17 +090080 /// Memory size (in MiB) of the VM. If unspecified, defaults to the value of `memory_mib`
81 /// in the VM config file.
82 #[structopt(short, long)]
83 mem: Option<u32>,
Inseob Kima5a262f2021-11-17 19:41:03 +090084
Jiyong Park032615f2022-01-10 13:55:34 +090085 /// Number of vCPUs in the VM. If unspecified, defaults to 1.
86 #[structopt(long)]
87 cpus: Option<u32>,
88
89 /// Host CPUs where vCPUs are run on. If unspecified, vCPU runs on any host CPU.
90 #[structopt(long)]
91 cpu_affinity: Option<String>,
92
Inseob Kima5a262f2021-11-17 19:41:03 +090093 /// Paths to extra idsig files.
Victor Hsieh99782572022-01-05 15:38:33 -080094 #[structopt(long = "extra-idsig")]
Inseob Kima5a262f2021-11-17 19:41:03 +090095 extra_idsigs: Vec<PathBuf>,
Jooyung Han21e9b922021-06-26 04:14:16 +090096 },
David Brazdil20412d92021-03-18 10:53:06 +000097 /// Run a virtual machine
98 Run {
99 /// Path to VM config JSON
100 #[structopt(parse(from_os_str))]
101 config: PathBuf,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000102
103 /// Detach VM from the terminal and run in the background
104 #[structopt(short, long)]
105 daemonize: bool,
Andrew Walbranbe429242021-06-28 12:22:54 +0000106
Jiyong Park032615f2022-01-10 13:55:34 +0900107 /// Number of vCPUs in the VM. If unspecified, defaults to 1.
108 #[structopt(long)]
109 cpus: Option<u32>,
110
111 /// Host CPUs where vCPUs are run on. If unspecified, vCPU runs on any host CPU. The format
112 /// can be either a comma-separated list of CPUs or CPU ranges to run vCPUs on (e.g.
113 /// "0,1-3,5" to choose host CPUs 0, 1, 2, 3, and 5, or a colon-separated list of
114 /// assignments of vCPU-to-host-CPU assignments e.g. "0=0:1=1:2=2" to map vCPU 0 to host
115 /// CPU 0 and so on.
116 #[structopt(long)]
117 cpu_affinity: Option<String>,
118
Jiyong Parkb8182bb2021-10-26 22:53:08 +0900119 /// Path to file for VM console output.
120 #[structopt(long)]
121 console: Option<PathBuf>,
David Brazdil3c2ddef2021-03-18 13:09:57 +0000122 },
123 /// Stop a virtual machine running in the background
124 Stop {
125 /// CID of the virtual machine
126 cid: u32,
David Brazdil20412d92021-03-18 10:53:06 +0000127 },
128 /// List running virtual machines
129 List,
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000130 /// Print information about virtual machine support
131 Info,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000132 /// Create a new empty partition to be used as a writable partition for a VM
133 CreatePartition {
134 /// Path at which to create the image file
135 #[structopt(parse(from_os_str))]
136 path: PathBuf,
137
138 /// The desired size of the partition, in bytes.
139 size: u64,
Jiyong Park9dd389e2021-08-23 20:42:59 +0900140
141 /// Type of the partition
142 #[structopt(short="t", long="type", default_value="raw", parse(try_from_str=parse_partition_type))]
143 partition_type: PartitionType,
Andrew Walbrandff3b942021-06-09 15:20:36 +0000144 },
David Brazdil20412d92021-03-18 10:53:06 +0000145}
146
Jiyong Parkc2a49cc2021-10-15 00:02:12 +0900147fn parse_debug_level(s: &str) -> Result<DebugLevel, String> {
148 match s {
149 "none" => Ok(DebugLevel::NONE),
150 "app_only" => Ok(DebugLevel::APP_ONLY),
151 "full" => Ok(DebugLevel::FULL),
152 _ => Err(format!("Invalid debug level {}", s)),
153 }
154}
155
Jiyong Park9dd389e2021-08-23 20:42:59 +0900156fn parse_partition_type(s: &str) -> Result<PartitionType, String> {
157 match s {
158 "raw" => Ok(PartitionType::RAW),
159 "instance" => Ok(PartitionType::ANDROID_VM_INSTANCE),
160 _ => Err(format!("Invalid partition type {}", s)),
161 }
162}
163
Andrew Walbranea9fa482021-03-04 16:11:12 +0000164fn main() -> Result<(), Error> {
165 env_logger::init();
David Brazdil20412d92021-03-18 10:53:06 +0000166 let opt = Opt::from_args();
Andrew Walbranea9fa482021-03-04 16:11:12 +0000167
168 // We need to start the thread pool for Binder to work properly, especially link_to_death.
169 ProcessState::start_thread_pool();
170
Andrew Walbranf1453802021-03-29 17:12:54 +0000171 let service = wait_for_interface(VIRTUALIZATION_SERVICE_BINDER_SERVICE_IDENTIFIER)
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000172 .context("Failed to find VirtualizationService")?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000173
David Brazdil20412d92021-03-18 10:53:06 +0000174 match opt {
Inseob Kima5a262f2021-11-17 19:41:03 +0900175 Opt::RunApp {
176 apk,
177 idsig,
178 instance,
179 config_path,
180 daemonize,
181 console,
182 log,
183 debug,
Andrew Walbran3994f002022-01-27 17:33:45 +0000184 protected,
Inseob Kima5a262f2021-11-17 19:41:03 +0900185 mem,
Jiyong Park032615f2022-01-10 13:55:34 +0900186 cpus,
187 cpu_affinity,
Inseob Kima5a262f2021-11-17 19:41:03 +0900188 extra_idsigs,
189 } => command_run_app(
190 service,
191 &apk,
192 &idsig,
193 &instance,
194 &config_path,
195 daemonize,
196 console.as_deref(),
197 log.as_deref(),
198 debug,
Andrew Walbran3994f002022-01-27 17:33:45 +0000199 protected,
Inseob Kima5a262f2021-11-17 19:41:03 +0900200 mem,
Jiyong Park032615f2022-01-10 13:55:34 +0900201 cpus,
202 cpu_affinity,
Inseob Kima5a262f2021-11-17 19:41:03 +0900203 &extra_idsigs,
204 ),
Jiyong Park032615f2022-01-10 13:55:34 +0900205 Opt::Run { config, daemonize, cpus, cpu_affinity, console } => {
206 command_run(
207 service,
208 &config,
209 daemonize,
210 console.as_deref(),
211 /* mem */ None,
212 cpus,
213 cpu_affinity,
214 )
Andrew Walbranbe429242021-06-28 12:22:54 +0000215 }
Andrew Walbran17de24f2021-05-27 13:27:30 +0000216 Opt::Stop { cid } => command_stop(service, cid),
217 Opt::List => command_list(service),
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000218 Opt::Info => command_info(),
Jiyong Park9dd389e2021-08-23 20:42:59 +0900219 Opt::CreatePartition { path, size, partition_type } => {
220 command_create_partition(service, &path, size, partition_type)
221 }
Andrew Walbranea9fa482021-03-04 16:11:12 +0000222 }
223}
224
David Brazdil3c2ddef2021-03-18 13:09:57 +0000225/// Retrieve reference to a previously daemonized VM and stop it.
Andrew Walbran17de24f2021-05-27 13:27:30 +0000226fn command_stop(service: Strong<dyn IVirtualizationService>, cid: u32) -> Result<(), Error> {
227 service
David Brazdil3c2ddef2021-03-18 13:09:57 +0000228 .debugDropVmRef(cid as i32)
Andrew Walbranf6bf6862021-05-21 12:41:13 +0000229 .context("Failed to get VM from VirtualizationService")?
David Brazdil3c2ddef2021-03-18 13:09:57 +0000230 .context("CID does not correspond to a running background VM")?;
Andrew Walbranea9fa482021-03-04 16:11:12 +0000231 Ok(())
232}
233
Andrew Walbran320b5602021-03-04 16:11:12 +0000234/// List the VMs currently running.
Andrew Walbran17de24f2021-05-27 13:27:30 +0000235fn command_list(service: Strong<dyn IVirtualizationService>) -> Result<(), Error> {
236 let vms = service.debugListVms().context("Failed to get list of VMs")?;
Andrew Walbran320b5602021-03-04 16:11:12 +0000237 println!("Running VMs: {:#?}", vms);
238 Ok(())
239}
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000240
241/// Print information about supported VM types.
242fn command_info() -> Result<(), Error> {
243 let unprotected_vm_supported =
244 system_properties::read_bool("ro.boot.hypervisor.vm.supported", false)?;
245 let protected_vm_supported =
246 system_properties::read_bool("ro.boot.hypervisor.protected_vm.supported", false)?;
247 match (unprotected_vm_supported, protected_vm_supported) {
248 (false, false) => println!("VMs are not supported."),
249 (false, true) => println!("Only protected VMs are supported."),
250 (true, false) => println!("Only unprotected VMs are supported."),
251 (true, true) => println!("Both protected and unprotected VMs are supported."),
252 }
253
Andrew Walbran014efb52022-02-03 17:43:11 +0000254 if let Some(version) = system_properties::read("ro.boot.hypervisor.version")? {
Andrew Walbranc4b1bde2022-02-03 15:26:02 +0000255 println!("Hypervisor version: {}", version);
256 } else {
257 println!("Hypervisor version not set.");
258 }
259
260 if Path::new("/dev/kvm").exists() {
261 println!("/dev/kvm exists.");
262 } else {
263 println!("/dev/kvm does not exist.");
264 }
265
266 Ok(())
267}