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