blob: 329c859d834d9c059439e47a9e8f0d2117663813 [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
17mod sync;
18
19use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::IVirtManager;
Andrew Walbrana89fc132021-03-17 17:08:36 +000020use android_system_virtmanager::binder::{
21 get_interface, ParcelFileDescriptor, ProcessState, Strong,
22};
David Brazdil20412d92021-03-18 10:53:06 +000023use anyhow::{Context, Error};
Andrew Walbranea9fa482021-03-04 16:11:12 +000024// TODO: Import these via android_system_virtmanager::binder once https://r.android.com/1619403 is
25// submitted.
26use binder::{DeathRecipient, IBinder};
Andrew Walbrana89fc132021-03-17 17:08:36 +000027use std::fs::File;
28use std::io;
29use std::os::unix::io::{AsRawFd, FromRawFd};
David Brazdil20412d92021-03-18 10:53:06 +000030use std::path::PathBuf;
31use structopt::clap::AppSettings;
32use structopt::StructOpt;
Andrew Walbranea9fa482021-03-04 16:11:12 +000033use sync::AtomicFlag;
34
35const VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager";
36
David Brazdil20412d92021-03-18 10:53:06 +000037#[derive(StructOpt)]
38#[structopt(no_version, global_settings = &[AppSettings::DisableVersion])]
39enum Opt {
40 /// Run a virtual machine
41 Run {
42 /// Path to VM config JSON
43 #[structopt(parse(from_os_str))]
44 config: PathBuf,
David Brazdil3c2ddef2021-03-18 13:09:57 +000045
46 /// Detach VM from the terminal and run in the background
47 #[structopt(short, long)]
48 daemonize: bool,
49 },
50 /// Stop a virtual machine running in the background
51 Stop {
52 /// CID of the virtual machine
53 cid: u32,
David Brazdil20412d92021-03-18 10:53:06 +000054 },
55 /// List running virtual machines
56 List,
57}
58
Andrew Walbranea9fa482021-03-04 16:11:12 +000059fn main() -> Result<(), Error> {
60 env_logger::init();
David Brazdil20412d92021-03-18 10:53:06 +000061 let opt = Opt::from_args();
Andrew Walbranea9fa482021-03-04 16:11:12 +000062
63 // We need to start the thread pool for Binder to work properly, especially link_to_death.
64 ProcessState::start_thread_pool();
65
Andrew Walbran320b5602021-03-04 16:11:12 +000066 let virt_manager = get_interface(VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER)
67 .context("Failed to find Virt Manager service")?;
68
David Brazdil20412d92021-03-18 10:53:06 +000069 match opt {
David Brazdil3c2ddef2021-03-18 13:09:57 +000070 Opt::Run { config, daemonize } => command_run(virt_manager, &config, daemonize),
71 Opt::Stop { cid } => command_stop(virt_manager, cid),
David Brazdil20412d92021-03-18 10:53:06 +000072 Opt::List => command_list(virt_manager),
Andrew Walbranea9fa482021-03-04 16:11:12 +000073 }
74}
75
76/// Run a VM from the given configuration file.
David Brazdil3c2ddef2021-03-18 13:09:57 +000077fn command_run(
78 virt_manager: Strong<dyn IVirtManager>,
79 config_path: &PathBuf,
80 daemonize: bool,
81) -> Result<(), Error> {
David Brazdil20412d92021-03-18 10:53:06 +000082 let config_filename = config_path.to_str().context("Failed to parse VM config path")?;
Andrew Walbrana89fc132021-03-17 17:08:36 +000083 let stdout_file = ParcelFileDescriptor::new(duplicate_stdout()?);
David Brazdil3c2ddef2021-03-18 13:09:57 +000084 let stdout = if daemonize { None } else { Some(&stdout_file) };
85 let vm = virt_manager.startVm(config_filename, stdout).context("Failed to start VM")?;
86
Andrew Walbran320b5602021-03-04 16:11:12 +000087 let cid = vm.getCid().context("Failed to get CID")?;
Andrew Walbranea9fa482021-03-04 16:11:12 +000088 println!("Started VM from {} with CID {}.", config_filename, cid);
89
David Brazdil3c2ddef2021-03-18 13:09:57 +000090 if daemonize {
91 // Pass the VM reference back to Virt Manager and have it hold it in the background.
92 virt_manager.debugHoldVmRef(&*vm).context("Failed to pass VM to Virt Manager")
93 } else {
94 // Wait until the VM dies. If we just returned immediately then the IVirtualMachine Binder
95 // object would be dropped and the VM would be killed.
96 wait_for_death(&mut vm.as_binder())?;
97 println!("VM died");
98 Ok(())
99 }
100}
101
102/// Retrieve reference to a previously daemonized VM and stop it.
103fn command_stop(virt_manager: Strong<dyn IVirtManager>, cid: u32) -> Result<(), Error> {
104 virt_manager
105 .debugDropVmRef(cid as i32)
106 .context("Failed to get VM from Virt Manager")?
107 .context("CID does not correspond to a running background VM")?;
Andrew Walbranea9fa482021-03-04 16:11:12 +0000108 Ok(())
109}
110
Andrew Walbran320b5602021-03-04 16:11:12 +0000111/// List the VMs currently running.
112fn command_list(virt_manager: Strong<dyn IVirtManager>) -> Result<(), Error> {
113 let vms = virt_manager.debugListVms().context("Failed to get list of VMs")?;
114 println!("Running VMs: {:#?}", vms);
115 Ok(())
116}
117
Andrew Walbranea9fa482021-03-04 16:11:12 +0000118/// Block until the given Binder object dies.
119fn wait_for_death(binder: &mut impl IBinder) -> Result<(), Error> {
120 let dead = AtomicFlag::default();
121 let mut death_recipient = {
122 let dead = dead.clone();
123 DeathRecipient::new(move || {
124 dead.raise();
125 })
126 };
127 binder.link_to_death(&mut death_recipient)?;
128 dead.wait();
129 Ok(())
130}
Andrew Walbrana89fc132021-03-17 17:08:36 +0000131
132/// Safely duplicate the standard output file descriptor.
133fn duplicate_stdout() -> io::Result<File> {
134 let stdout_fd = io::stdout().as_raw_fd();
135 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
136 // for an error.
137 let dup_fd = unsafe { libc::dup(stdout_fd) };
138 if dup_fd < 0 {
139 Err(io::Error::last_os_error())
140 } else {
141 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
142 // takes ownership of it.
143 Ok(unsafe { File::from_raw_fd(dup_fd) })
144 }
145}