blob: 061cfd71ed75abf9a1139fdd625d1723a2d408b3 [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 Walbrandae07162021-03-12 17:05:20 +000020use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachine::IVirtualMachine;
21use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachineCallback::{
22 BnVirtualMachineCallback, IVirtualMachineCallback,
23};
Andrew Walbrana89fc132021-03-17 17:08:36 +000024use android_system_virtmanager::binder::{
Andrew Walbran651b0682021-03-19 16:22:07 +000025 get_interface, DeathRecipient, IBinder, ParcelFileDescriptor, ProcessState, Strong,
Andrew Walbrana89fc132021-03-17 17:08:36 +000026};
Andrew Walbrandae07162021-03-12 17:05:20 +000027use android_system_virtmanager::binder::{Interface, Result as BinderResult};
David Brazdil20412d92021-03-18 10:53:06 +000028use anyhow::{Context, Error};
Andrew Walbrana89fc132021-03-17 17:08:36 +000029use std::fs::File;
30use std::io;
31use std::os::unix::io::{AsRawFd, FromRawFd};
Andrew Walbranc2e5d8b2021-04-08 13:34:45 +000032use 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 +000035use sync::AtomicFlag;
36
37const VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager";
38
David Brazdil20412d92021-03-18 10:53:06 +000039#[derive(StructOpt)]
40#[structopt(no_version, global_settings = &[AppSettings::DisableVersion])]
41enum Opt {
42 /// Run a virtual machine
43 Run {
44 /// Path to VM config JSON
45 #[structopt(parse(from_os_str))]
46 config: PathBuf,
David Brazdil3c2ddef2021-03-18 13:09:57 +000047
48 /// Detach VM from the terminal and run in the background
49 #[structopt(short, long)]
50 daemonize: bool,
51 },
52 /// Stop a virtual machine running in the background
53 Stop {
54 /// CID of the virtual machine
55 cid: u32,
David Brazdil20412d92021-03-18 10:53:06 +000056 },
57 /// List running virtual machines
58 List,
59}
60
Andrew Walbranea9fa482021-03-04 16:11:12 +000061fn main() -> Result<(), Error> {
62 env_logger::init();
David Brazdil20412d92021-03-18 10:53:06 +000063 let opt = Opt::from_args();
Andrew Walbranea9fa482021-03-04 16:11:12 +000064
65 // We need to start the thread pool for Binder to work properly, especially link_to_death.
66 ProcessState::start_thread_pool();
67
Andrew Walbran320b5602021-03-04 16:11:12 +000068 let virt_manager = get_interface(VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER)
69 .context("Failed to find Virt Manager service")?;
70
David Brazdil20412d92021-03-18 10:53:06 +000071 match opt {
David Brazdil3c2ddef2021-03-18 13:09:57 +000072 Opt::Run { config, daemonize } => command_run(virt_manager, &config, daemonize),
73 Opt::Stop { cid } => command_stop(virt_manager, cid),
David Brazdil20412d92021-03-18 10:53:06 +000074 Opt::List => command_list(virt_manager),
Andrew Walbranea9fa482021-03-04 16:11:12 +000075 }
76}
77
78/// Run a VM from the given configuration file.
David Brazdil3c2ddef2021-03-18 13:09:57 +000079fn command_run(
80 virt_manager: Strong<dyn IVirtManager>,
Andrew Walbranc2e5d8b2021-04-08 13:34:45 +000081 config_path: &Path,
David Brazdil3c2ddef2021-03-18 13:09:57 +000082 daemonize: bool,
83) -> Result<(), Error> {
David Brazdil20412d92021-03-18 10:53:06 +000084 let config_filename = config_path.to_str().context("Failed to parse VM config path")?;
Andrew Walbran06b5f5c2021-03-31 12:34:13 +000085 let config_file = ParcelFileDescriptor::new(
86 File::open(config_filename).context("Failed to open config file")?,
87 );
Andrew Walbrana89fc132021-03-17 17:08:36 +000088 let stdout_file = ParcelFileDescriptor::new(duplicate_stdout()?);
David Brazdil3c2ddef2021-03-18 13:09:57 +000089 let stdout = if daemonize { None } else { Some(&stdout_file) };
Andrew Walbran06b5f5c2021-03-31 12:34:13 +000090 let vm = virt_manager.startVm(&config_file, stdout).context("Failed to start VM")?;
David Brazdil3c2ddef2021-03-18 13:09:57 +000091
Andrew Walbran320b5602021-03-04 16:11:12 +000092 let cid = vm.getCid().context("Failed to get CID")?;
Andrew Walbranea9fa482021-03-04 16:11:12 +000093 println!("Started VM from {} with CID {}.", config_filename, cid);
94
David Brazdil3c2ddef2021-03-18 13:09:57 +000095 if daemonize {
96 // Pass the VM reference back to Virt Manager and have it hold it in the background.
Andrei Homescu1415c132021-03-24 02:39:55 +000097 virt_manager.debugHoldVmRef(&vm).context("Failed to pass VM to Virt Manager")
David Brazdil3c2ddef2021-03-18 13:09:57 +000098 } else {
Andrew Walbrandae07162021-03-12 17:05:20 +000099 // Wait until the VM or VirtManager dies. If we just returned immediately then the
100 // IVirtualMachine Binder object would be dropped and the VM would be killed.
101 wait_for_vm(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000102 }
103}
104
Andrew Walbrandae07162021-03-12 17:05:20 +0000105/// Wait until the given VM or the VirtManager itself dies.
106fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> {
107 let dead = AtomicFlag::default();
108 let callback =
109 BnVirtualMachineCallback::new_binder(VirtualMachineCallback { dead: dead.clone() });
110 vm.registerCallback(&callback)?;
111 let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?;
112 dead.wait();
113 // Ensure that death_recipient isn't dropped before we wait on the flag, as it is removed
114 // from the Binder when it's dropped.
115 drop(death_recipient);
116 Ok(())
117}
118
David Brazdil3c2ddef2021-03-18 13:09:57 +0000119/// Retrieve reference to a previously daemonized VM and stop it.
120fn command_stop(virt_manager: Strong<dyn IVirtManager>, cid: u32) -> Result<(), Error> {
121 virt_manager
122 .debugDropVmRef(cid as i32)
123 .context("Failed to get VM from Virt Manager")?
124 .context("CID does not correspond to a running background VM")?;
Andrew Walbranea9fa482021-03-04 16:11:12 +0000125 Ok(())
126}
127
Andrew Walbran320b5602021-03-04 16:11:12 +0000128/// List the VMs currently running.
129fn command_list(virt_manager: Strong<dyn IVirtManager>) -> Result<(), Error> {
130 let vms = virt_manager.debugListVms().context("Failed to get list of VMs")?;
131 println!("Running VMs: {:#?}", vms);
132 Ok(())
133}
134
Andrew Walbrandae07162021-03-12 17:05:20 +0000135/// Raise the given flag when the given Binder object dies.
136///
137/// If the returned DeathRecipient is dropped then this will no longer do anything.
138fn wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error> {
139 let mut death_recipient = DeathRecipient::new(move || {
140 println!("VirtManager died");
141 dead.raise();
142 });
Andrew Walbranea9fa482021-03-04 16:11:12 +0000143 binder.link_to_death(&mut death_recipient)?;
Andrew Walbrandae07162021-03-12 17:05:20 +0000144 Ok(death_recipient)
145}
146
147#[derive(Debug)]
148struct VirtualMachineCallback {
149 dead: AtomicFlag,
150}
151
152impl Interface for VirtualMachineCallback {}
153
154impl IVirtualMachineCallback for VirtualMachineCallback {
155 fn onDied(&self, _cid: i32) -> BinderResult<()> {
156 println!("VM died");
157 self.dead.raise();
158 Ok(())
159 }
Andrew Walbranea9fa482021-03-04 16:11:12 +0000160}
Andrew Walbrana89fc132021-03-17 17:08:36 +0000161
162/// Safely duplicate the standard output file descriptor.
163fn duplicate_stdout() -> io::Result<File> {
164 let stdout_fd = io::stdout().as_raw_fd();
165 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
166 // for an error.
167 let dup_fd = unsafe { libc::dup(stdout_fd) };
168 if dup_fd < 0 {
169 Err(io::Error::last_os_error())
170 } else {
171 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
172 // takes ownership of it.
173 Ok(unsafe { File::from_raw_fd(dup_fd) })
174 }
175}