blob: 8045817911e7227ec3cea3b813b6879855644b0f [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 Walbran4de28782021-04-13 14:51:43 +000025 get_interface, BinderFeatures, DeathRecipient, IBinder, ParcelFileDescriptor, ProcessState,
26 Strong,
Andrew Walbrana89fc132021-03-17 17:08:36 +000027};
Andrew Walbrandae07162021-03-12 17:05:20 +000028use android_system_virtmanager::binder::{Interface, Result as BinderResult};
David Brazdil20412d92021-03-18 10:53:06 +000029use anyhow::{Context, Error};
Andrew Walbrana89fc132021-03-17 17:08:36 +000030use std::fs::File;
31use std::io;
32use std::os::unix::io::{AsRawFd, FromRawFd};
Andrew Walbranc2e5d8b2021-04-08 13:34:45 +000033use std::path::{Path, PathBuf};
David Brazdil20412d92021-03-18 10:53:06 +000034use structopt::clap::AppSettings;
35use structopt::StructOpt;
Andrew Walbranea9fa482021-03-04 16:11:12 +000036use sync::AtomicFlag;
37
38const VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager";
39
David Brazdil20412d92021-03-18 10:53:06 +000040#[derive(StructOpt)]
41#[structopt(no_version, global_settings = &[AppSettings::DisableVersion])]
42enum Opt {
43 /// Run a virtual machine
44 Run {
45 /// Path to VM config JSON
46 #[structopt(parse(from_os_str))]
47 config: PathBuf,
David Brazdil3c2ddef2021-03-18 13:09:57 +000048
49 /// Detach VM from the terminal and run in the background
50 #[structopt(short, long)]
51 daemonize: bool,
52 },
53 /// Stop a virtual machine running in the background
54 Stop {
55 /// CID of the virtual machine
56 cid: u32,
David Brazdil20412d92021-03-18 10:53:06 +000057 },
58 /// List running virtual machines
59 List,
60}
61
Andrew Walbranea9fa482021-03-04 16:11:12 +000062fn main() -> Result<(), Error> {
63 env_logger::init();
David Brazdil20412d92021-03-18 10:53:06 +000064 let opt = Opt::from_args();
Andrew Walbranea9fa482021-03-04 16:11:12 +000065
66 // We need to start the thread pool for Binder to work properly, especially link_to_death.
67 ProcessState::start_thread_pool();
68
Andrew Walbran320b5602021-03-04 16:11:12 +000069 let virt_manager = get_interface(VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER)
70 .context("Failed to find Virt Manager service")?;
71
David Brazdil20412d92021-03-18 10:53:06 +000072 match opt {
David Brazdil3c2ddef2021-03-18 13:09:57 +000073 Opt::Run { config, daemonize } => command_run(virt_manager, &config, daemonize),
74 Opt::Stop { cid } => command_stop(virt_manager, cid),
David Brazdil20412d92021-03-18 10:53:06 +000075 Opt::List => command_list(virt_manager),
Andrew Walbranea9fa482021-03-04 16:11:12 +000076 }
77}
78
79/// Run a VM from the given configuration file.
David Brazdil3c2ddef2021-03-18 13:09:57 +000080fn command_run(
81 virt_manager: Strong<dyn IVirtManager>,
Andrew Walbranc2e5d8b2021-04-08 13:34:45 +000082 config_path: &Path,
David Brazdil3c2ddef2021-03-18 13:09:57 +000083 daemonize: bool,
84) -> Result<(), Error> {
David Brazdil20412d92021-03-18 10:53:06 +000085 let config_filename = config_path.to_str().context("Failed to parse VM config path")?;
Andrew Walbran06b5f5c2021-03-31 12:34:13 +000086 let config_file = ParcelFileDescriptor::new(
87 File::open(config_filename).context("Failed to open config file")?,
88 );
Andrew Walbrana89fc132021-03-17 17:08:36 +000089 let stdout_file = ParcelFileDescriptor::new(duplicate_stdout()?);
David Brazdil3c2ddef2021-03-18 13:09:57 +000090 let stdout = if daemonize { None } else { Some(&stdout_file) };
Andrew Walbran06b5f5c2021-03-31 12:34:13 +000091 let vm = virt_manager.startVm(&config_file, stdout).context("Failed to start VM")?;
David Brazdil3c2ddef2021-03-18 13:09:57 +000092
Andrew Walbran320b5602021-03-04 16:11:12 +000093 let cid = vm.getCid().context("Failed to get CID")?;
Andrew Walbranea9fa482021-03-04 16:11:12 +000094 println!("Started VM from {} with CID {}.", config_filename, cid);
95
David Brazdil3c2ddef2021-03-18 13:09:57 +000096 if daemonize {
97 // Pass the VM reference back to Virt Manager and have it hold it in the background.
Andrei Homescu1415c132021-03-24 02:39:55 +000098 virt_manager.debugHoldVmRef(&vm).context("Failed to pass VM to Virt Manager")
David Brazdil3c2ddef2021-03-18 13:09:57 +000099 } else {
Andrew Walbrandae07162021-03-12 17:05:20 +0000100 // Wait until the VM or VirtManager dies. If we just returned immediately then the
101 // IVirtualMachine Binder object would be dropped and the VM would be killed.
102 wait_for_vm(vm)
David Brazdil3c2ddef2021-03-18 13:09:57 +0000103 }
104}
105
Andrew Walbrandae07162021-03-12 17:05:20 +0000106/// Wait until the given VM or the VirtManager itself dies.
107fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> {
108 let dead = AtomicFlag::default();
Andrew Walbran4de28782021-04-13 14:51:43 +0000109 let callback = BnVirtualMachineCallback::new_binder(
110 VirtualMachineCallback { dead: dead.clone() },
111 BinderFeatures::default(),
112 );
Andrew Walbrandae07162021-03-12 17:05:20 +0000113 vm.registerCallback(&callback)?;
114 let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?;
115 dead.wait();
116 // Ensure that death_recipient isn't dropped before we wait on the flag, as it is removed
117 // from the Binder when it's dropped.
118 drop(death_recipient);
119 Ok(())
120}
121
David Brazdil3c2ddef2021-03-18 13:09:57 +0000122/// Retrieve reference to a previously daemonized VM and stop it.
123fn command_stop(virt_manager: Strong<dyn IVirtManager>, cid: u32) -> Result<(), Error> {
124 virt_manager
125 .debugDropVmRef(cid as i32)
126 .context("Failed to get VM from Virt Manager")?
127 .context("CID does not correspond to a running background VM")?;
Andrew Walbranea9fa482021-03-04 16:11:12 +0000128 Ok(())
129}
130
Andrew Walbran320b5602021-03-04 16:11:12 +0000131/// List the VMs currently running.
132fn command_list(virt_manager: Strong<dyn IVirtManager>) -> Result<(), Error> {
133 let vms = virt_manager.debugListVms().context("Failed to get list of VMs")?;
134 println!("Running VMs: {:#?}", vms);
135 Ok(())
136}
137
Andrew Walbrandae07162021-03-12 17:05:20 +0000138/// Raise the given flag when the given Binder object dies.
139///
140/// If the returned DeathRecipient is dropped then this will no longer do anything.
141fn wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error> {
142 let mut death_recipient = DeathRecipient::new(move || {
143 println!("VirtManager died");
144 dead.raise();
145 });
Andrew Walbranea9fa482021-03-04 16:11:12 +0000146 binder.link_to_death(&mut death_recipient)?;
Andrew Walbrandae07162021-03-12 17:05:20 +0000147 Ok(death_recipient)
148}
149
150#[derive(Debug)]
151struct VirtualMachineCallback {
152 dead: AtomicFlag,
153}
154
155impl Interface for VirtualMachineCallback {}
156
157impl IVirtualMachineCallback for VirtualMachineCallback {
158 fn onDied(&self, _cid: i32) -> BinderResult<()> {
159 println!("VM died");
160 self.dead.raise();
161 Ok(())
162 }
Andrew Walbranea9fa482021-03-04 16:11:12 +0000163}
Andrew Walbrana89fc132021-03-17 17:08:36 +0000164
165/// Safely duplicate the standard output file descriptor.
166fn duplicate_stdout() -> io::Result<File> {
167 let stdout_fd = io::stdout().as_raw_fd();
168 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
169 // for an error.
170 let dup_fd = unsafe { libc::dup(stdout_fd) };
171 if dup_fd < 0 {
172 Err(io::Error::last_os_error())
173 } else {
174 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
175 // takes ownership of it.
176 Ok(unsafe { File::from_raw_fd(dup_fd) })
177 }
178}