blob: 6ac66f1c0fe0ebb902306daf27a361edf6dd3cd7 [file] [log] [blame]
Andrew Walbranf395b822021-05-05 10:38:59 +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//! Command to run a VM.
16
Andrew Walbran3a5a9212021-05-04 17:09:08 +000017use crate::config::VmConfig;
Andrew Walbranf395b822021-05-05 10:38:59 +000018use crate::sync::AtomicFlag;
Andrew Walbranf6bf6862021-05-21 12:41:13 +000019use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualizationService::IVirtualizationService;
20use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachine::IVirtualMachine;
21use android_system_virtualizationservice::aidl::android::system::virtualizationservice::IVirtualMachineCallback::{
Andrew Walbranf395b822021-05-05 10:38:59 +000022 BnVirtualMachineCallback, IVirtualMachineCallback,
23};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000024use android_system_virtualizationservice::binder::{
Andrew Walbranf395b822021-05-05 10:38:59 +000025 BinderFeatures, DeathRecipient, IBinder, ParcelFileDescriptor, Strong,
26};
Andrew Walbranf6bf6862021-05-21 12:41:13 +000027use android_system_virtualizationservice::binder::{Interface, Result as BinderResult};
Andrew Walbranf395b822021-05-05 10:38:59 +000028use anyhow::{Context, Error};
29use std::fs::File;
30use std::io;
31use std::os::unix::io::{AsRawFd, FromRawFd};
32use std::path::Path;
33
34/// Run a VM from the given configuration file.
35pub fn command_run(
Andrew Walbranf6bf6862021-05-21 12:41:13 +000036 virt_manager: Strong<dyn IVirtualizationService>,
Andrew Walbranf395b822021-05-05 10:38:59 +000037 config_path: &Path,
38 daemonize: bool,
39) -> Result<(), Error> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +000040 let config_file = File::open(config_path).context("Failed to open config file")?;
41 let config =
42 VmConfig::load(&config_file).context("Failed to parse config file")?.to_parcelable()?;
43 let stdout =
44 if daemonize { None } else { Some(ParcelFileDescriptor::new(duplicate_stdout()?)) };
45 let vm = virt_manager.startVm(&config, stdout.as_ref()).context("Failed to start VM")?;
Andrew Walbranf395b822021-05-05 10:38:59 +000046
47 let cid = vm.getCid().context("Failed to get CID")?;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000048 println!("Started VM from {:?} with CID {}.", config_path, cid);
Andrew Walbranf395b822021-05-05 10:38:59 +000049
50 if daemonize {
Andrew Walbranf6bf6862021-05-21 12:41:13 +000051 // Pass the VM reference back to VirtualizationService and have it hold it in the
52 // background.
53 virt_manager.debugHoldVmRef(&vm).context("Failed to pass VM to VirtualizationService")
Andrew Walbranf395b822021-05-05 10:38:59 +000054 } else {
Andrew Walbranf6bf6862021-05-21 12:41:13 +000055 // Wait until the VM or VirtualizationService dies. If we just returned immediately then the
Andrew Walbranf395b822021-05-05 10:38:59 +000056 // IVirtualMachine Binder object would be dropped and the VM would be killed.
57 wait_for_vm(vm)
58 }
59}
60
Andrew Walbranf6bf6862021-05-21 12:41:13 +000061/// Wait until the given VM or the VirtualizationService itself dies.
Andrew Walbranf395b822021-05-05 10:38:59 +000062fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> {
63 let dead = AtomicFlag::default();
64 let callback = BnVirtualMachineCallback::new_binder(
65 VirtualMachineCallback { dead: dead.clone() },
66 BinderFeatures::default(),
67 );
68 vm.registerCallback(&callback)?;
69 let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?;
70 dead.wait();
71 // Ensure that death_recipient isn't dropped before we wait on the flag, as it is removed
72 // from the Binder when it's dropped.
73 drop(death_recipient);
74 Ok(())
75}
76
77/// Raise the given flag when the given Binder object dies.
78///
79/// If the returned DeathRecipient is dropped then this will no longer do anything.
80fn wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error> {
81 let mut death_recipient = DeathRecipient::new(move || {
Andrew Walbranf6bf6862021-05-21 12:41:13 +000082 println!("VirtualizationService died");
Andrew Walbranf395b822021-05-05 10:38:59 +000083 dead.raise();
84 });
85 binder.link_to_death(&mut death_recipient)?;
86 Ok(death_recipient)
87}
88
89#[derive(Debug)]
90struct VirtualMachineCallback {
91 dead: AtomicFlag,
92}
93
94impl Interface for VirtualMachineCallback {}
95
96impl IVirtualMachineCallback for VirtualMachineCallback {
97 fn onDied(&self, _cid: i32) -> BinderResult<()> {
98 println!("VM died");
99 self.dead.raise();
100 Ok(())
101 }
102}
103
104/// Safely duplicate the standard output file descriptor.
105fn duplicate_stdout() -> io::Result<File> {
106 let stdout_fd = io::stdout().as_raw_fd();
107 // Safe because this just duplicates a file descriptor which we know to be valid, and we check
108 // for an error.
109 let dup_fd = unsafe { libc::dup(stdout_fd) };
110 if dup_fd < 0 {
111 Err(io::Error::last_os_error())
112 } else {
113 // Safe because we have just duplicated the file descriptor so we own it, and `from_raw_fd`
114 // takes ownership of it.
115 Ok(unsafe { File::from_raw_fd(dup_fd) })
116 }
117}