blob: 34031f7a82a73fd82f7e9e0f3b2983028d170809 [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,
45 },
46 /// List running virtual machines
47 List,
48}
49
Andrew Walbranea9fa482021-03-04 16:11:12 +000050fn main() -> Result<(), Error> {
51 env_logger::init();
David Brazdil20412d92021-03-18 10:53:06 +000052 let opt = Opt::from_args();
Andrew Walbranea9fa482021-03-04 16:11:12 +000053
54 // We need to start the thread pool for Binder to work properly, especially link_to_death.
55 ProcessState::start_thread_pool();
56
Andrew Walbran320b5602021-03-04 16:11:12 +000057 let virt_manager = get_interface(VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER)
58 .context("Failed to find Virt Manager service")?;
59
David Brazdil20412d92021-03-18 10:53:06 +000060 match opt {
61 Opt::Run { config } => command_run(virt_manager, &config),
62 Opt::List => command_list(virt_manager),
Andrew Walbranea9fa482021-03-04 16:11:12 +000063 }
64}
65
66/// Run a VM from the given configuration file.
David Brazdil20412d92021-03-18 10:53:06 +000067fn command_run(virt_manager: Strong<dyn IVirtManager>, config_path: &PathBuf) -> Result<(), Error> {
68 let config_filename = config_path.to_str().context("Failed to parse VM config path")?;
Andrew Walbrana89fc132021-03-17 17:08:36 +000069 let stdout_file = ParcelFileDescriptor::new(duplicate_stdout()?);
70 let vm =
71 virt_manager.startVm(config_filename, Some(&stdout_file)).context("Failed to start VM")?;
Andrew Walbran320b5602021-03-04 16:11:12 +000072 let cid = vm.getCid().context("Failed to get CID")?;
Andrew Walbranea9fa482021-03-04 16:11:12 +000073 println!("Started VM from {} with CID {}.", config_filename, cid);
74
75 // Wait until the VM dies. If we just returned immediately then the IVirtualMachine Binder
76 // object would be dropped and the VM would be killed.
77 wait_for_death(&mut vm.as_binder())?;
78 println!("VM died");
79 Ok(())
80}
81
Andrew Walbran320b5602021-03-04 16:11:12 +000082/// List the VMs currently running.
83fn command_list(virt_manager: Strong<dyn IVirtManager>) -> Result<(), Error> {
84 let vms = virt_manager.debugListVms().context("Failed to get list of VMs")?;
85 println!("Running VMs: {:#?}", vms);
86 Ok(())
87}
88
Andrew Walbranea9fa482021-03-04 16:11:12 +000089/// Block until the given Binder object dies.
90fn wait_for_death(binder: &mut impl IBinder) -> Result<(), Error> {
91 let dead = AtomicFlag::default();
92 let mut death_recipient = {
93 let dead = dead.clone();
94 DeathRecipient::new(move || {
95 dead.raise();
96 })
97 };
98 binder.link_to_death(&mut death_recipient)?;
99 dead.wait();
100 Ok(())
101}
Andrew Walbrana89fc132021-03-17 17:08:36 +0000102
103/// Safely duplicate the standard output file descriptor.
104fn duplicate_stdout() -> io::Result<File> {
105 let stdout_fd = io::stdout().as_raw_fd();
106 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
107 // for an error.
108 let dup_fd = unsafe { libc::dup(stdout_fd) };
109 if dup_fd < 0 {
110 Err(io::Error::last_os_error())
111 } else {
112 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
113 // takes ownership of it.
114 Ok(unsafe { File::from_raw_fd(dup_fd) })
115 }
116}