blob: 6c1052f8811d1fb64cdf09828b56da47a10df278 [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::{
Andrew Walbran651b0682021-03-19 16:22:07 +000021 get_interface, DeathRecipient, IBinder, ParcelFileDescriptor, ProcessState, Strong,
Andrew Walbrana89fc132021-03-17 17:08:36 +000022};
David Brazdil20412d92021-03-18 10:53:06 +000023use anyhow::{Context, Error};
Andrew Walbrana89fc132021-03-17 17:08:36 +000024use std::fs::File;
25use std::io;
26use std::os::unix::io::{AsRawFd, FromRawFd};
Andrew Walbranc2e5d8b2021-04-08 13:34:45 +000027use std::path::{Path, PathBuf};
David Brazdil20412d92021-03-18 10:53:06 +000028use structopt::clap::AppSettings;
29use structopt::StructOpt;
Andrew Walbranea9fa482021-03-04 16:11:12 +000030use sync::AtomicFlag;
31
32const VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager";
33
David Brazdil20412d92021-03-18 10:53:06 +000034#[derive(StructOpt)]
35#[structopt(no_version, global_settings = &[AppSettings::DisableVersion])]
36enum Opt {
37 /// Run a virtual machine
38 Run {
39 /// Path to VM config JSON
40 #[structopt(parse(from_os_str))]
41 config: PathBuf,
David Brazdil3c2ddef2021-03-18 13:09:57 +000042
43 /// Detach VM from the terminal and run in the background
44 #[structopt(short, long)]
45 daemonize: bool,
46 },
47 /// Stop a virtual machine running in the background
48 Stop {
49 /// CID of the virtual machine
50 cid: u32,
David Brazdil20412d92021-03-18 10:53:06 +000051 },
52 /// List running virtual machines
53 List,
54}
55
Andrew Walbranea9fa482021-03-04 16:11:12 +000056fn main() -> Result<(), Error> {
57 env_logger::init();
David Brazdil20412d92021-03-18 10:53:06 +000058 let opt = Opt::from_args();
Andrew Walbranea9fa482021-03-04 16:11:12 +000059
60 // We need to start the thread pool for Binder to work properly, especially link_to_death.
61 ProcessState::start_thread_pool();
62
Andrew Walbran320b5602021-03-04 16:11:12 +000063 let virt_manager = get_interface(VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER)
64 .context("Failed to find Virt Manager service")?;
65
David Brazdil20412d92021-03-18 10:53:06 +000066 match opt {
David Brazdil3c2ddef2021-03-18 13:09:57 +000067 Opt::Run { config, daemonize } => command_run(virt_manager, &config, daemonize),
68 Opt::Stop { cid } => command_stop(virt_manager, cid),
David Brazdil20412d92021-03-18 10:53:06 +000069 Opt::List => command_list(virt_manager),
Andrew Walbranea9fa482021-03-04 16:11:12 +000070 }
71}
72
73/// Run a VM from the given configuration file.
David Brazdil3c2ddef2021-03-18 13:09:57 +000074fn command_run(
75 virt_manager: Strong<dyn IVirtManager>,
Andrew Walbranc2e5d8b2021-04-08 13:34:45 +000076 config_path: &Path,
David Brazdil3c2ddef2021-03-18 13:09:57 +000077 daemonize: bool,
78) -> Result<(), Error> {
David Brazdil20412d92021-03-18 10:53:06 +000079 let config_filename = config_path.to_str().context("Failed to parse VM config path")?;
Andrew Walbran06b5f5c2021-03-31 12:34:13 +000080 let config_file = ParcelFileDescriptor::new(
81 File::open(config_filename).context("Failed to open config file")?,
82 );
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) };
Andrew Walbran06b5f5c2021-03-31 12:34:13 +000085 let vm = virt_manager.startVm(&config_file, stdout).context("Failed to start VM")?;
David Brazdil3c2ddef2021-03-18 13:09:57 +000086
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}