blob: 96ec6499a2e3a65becfcf365b84e3765a08ada18 [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};
Andrew Walbranea9fa482021-03-04 16:11:12 +000023use anyhow::{bail, Context, Error};
24// TODO: Import these via android_system_virtmanager::binder once https://r.android.com/1619403 is
25// submitted.
26use binder::{DeathRecipient, IBinder};
27use std::env;
Andrew Walbrana89fc132021-03-17 17:08:36 +000028use std::fs::File;
29use std::io;
30use std::os::unix::io::{AsRawFd, FromRawFd};
Andrew Walbranea9fa482021-03-04 16:11:12 +000031use std::process::exit;
32use sync::AtomicFlag;
33
34const VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER: &str = "android.system.virtmanager";
35
36fn main() -> Result<(), Error> {
37 env_logger::init();
38
39 let args: Vec<_> = env::args().collect();
40 if args.len() < 2 {
41 eprintln!("Usage:");
42 eprintln!(" {} run <vm_config.json>", args[0]);
Andrew Walbran320b5602021-03-04 16:11:12 +000043 eprintln!(" {} list", args[0]);
Andrew Walbranea9fa482021-03-04 16:11:12 +000044 exit(1);
45 }
46
47 // We need to start the thread pool for Binder to work properly, especially link_to_death.
48 ProcessState::start_thread_pool();
49
Andrew Walbran320b5602021-03-04 16:11:12 +000050 let virt_manager = get_interface(VIRT_MANAGER_BINDER_SERVICE_IDENTIFIER)
51 .context("Failed to find Virt Manager service")?;
52
Andrew Walbranea9fa482021-03-04 16:11:12 +000053 match args[1].as_ref() {
Andrew Walbran320b5602021-03-04 16:11:12 +000054 "run" if args.len() == 3 => command_run(virt_manager, &args[2]),
55 "list" if args.len() == 2 => command_list(virt_manager),
Andrew Walbranea9fa482021-03-04 16:11:12 +000056 command => bail!("Invalid command '{}' or wrong number of arguments", command),
57 }
58}
59
60/// Run a VM from the given configuration file.
Andrew Walbran320b5602021-03-04 16:11:12 +000061fn command_run(virt_manager: Strong<dyn IVirtManager>, config_filename: &str) -> Result<(), Error> {
Andrew Walbrana89fc132021-03-17 17:08:36 +000062 let stdout_file = ParcelFileDescriptor::new(duplicate_stdout()?);
63 let vm =
64 virt_manager.startVm(config_filename, Some(&stdout_file)).context("Failed to start VM")?;
Andrew Walbran320b5602021-03-04 16:11:12 +000065 let cid = vm.getCid().context("Failed to get CID")?;
Andrew Walbranea9fa482021-03-04 16:11:12 +000066 println!("Started VM from {} with CID {}.", config_filename, cid);
67
68 // Wait until the VM dies. If we just returned immediately then the IVirtualMachine Binder
69 // object would be dropped and the VM would be killed.
70 wait_for_death(&mut vm.as_binder())?;
71 println!("VM died");
72 Ok(())
73}
74
Andrew Walbran320b5602021-03-04 16:11:12 +000075/// List the VMs currently running.
76fn command_list(virt_manager: Strong<dyn IVirtManager>) -> Result<(), Error> {
77 let vms = virt_manager.debugListVms().context("Failed to get list of VMs")?;
78 println!("Running VMs: {:#?}", vms);
79 Ok(())
80}
81
Andrew Walbranea9fa482021-03-04 16:11:12 +000082/// Block until the given Binder object dies.
83fn wait_for_death(binder: &mut impl IBinder) -> Result<(), Error> {
84 let dead = AtomicFlag::default();
85 let mut death_recipient = {
86 let dead = dead.clone();
87 DeathRecipient::new(move || {
88 dead.raise();
89 })
90 };
91 binder.link_to_death(&mut death_recipient)?;
92 dead.wait();
93 Ok(())
94}
Andrew Walbrana89fc132021-03-17 17:08:36 +000095
96/// Safely duplicate the standard output file descriptor.
97fn duplicate_stdout() -> io::Result<File> {
98 let stdout_fd = io::stdout().as_raw_fd();
99 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
100 // for an error.
101 let dup_fd = unsafe { libc::dup(stdout_fd) };
102 if dup_fd < 0 {
103 Err(io::Error::last_os_error())
104 } else {
105 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
106 // takes ownership of it.
107 Ok(unsafe { File::from_raw_fd(dup_fd) })
108 }
109}