1 // 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
17 use crate::sync::AtomicFlag;
18 use android_system_virtmanager::aidl::android::system::virtmanager::IVirtManager::IVirtManager;
19 use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachine::IVirtualMachine;
20 use android_system_virtmanager::aidl::android::system::virtmanager::IVirtualMachineCallback::{
21 BnVirtualMachineCallback, IVirtualMachineCallback,
22 };
23 use android_system_virtmanager::binder::{
24 BinderFeatures, DeathRecipient, IBinder, ParcelFileDescriptor, Strong,
25 };
26 use android_system_virtmanager::binder::{Interface, Result as BinderResult};
27 use anyhow::{Context, Error};
28 use std::fs::File;
29 use std::io;
30 use std::os::unix::io::{AsRawFd, FromRawFd};
31 use std::path::Path;
32
33 /// Run a VM from the given configuration file.
command_run( virt_manager: Strong<dyn IVirtManager>, config_path: &Path, daemonize: bool, ) -> Result<(), Error>34 pub fn command_run(
35 virt_manager: Strong<dyn IVirtManager>,
36 config_path: &Path,
37 daemonize: bool,
38 ) -> Result<(), Error> {
39 let config_filename = config_path.to_str().context("Failed to parse VM config path")?;
40 let config_file = ParcelFileDescriptor::new(
41 File::open(config_filename).context("Failed to open config file")?,
42 );
43 let stdout_file = ParcelFileDescriptor::new(duplicate_stdout()?);
44 let stdout = if daemonize { None } else { Some(&stdout_file) };
45 let vm = virt_manager.startVm(&config_file, stdout).context("Failed to start VM")?;
46
47 let cid = vm.getCid().context("Failed to get CID")?;
48 println!("Started VM from {} with CID {}.", config_filename, cid);
49
50 if daemonize {
51 // Pass the VM reference back to Virt Manager and have it hold it in the background.
52 virt_manager.debugHoldVmRef(&vm).context("Failed to pass VM to Virt Manager")
53 } else {
54 // Wait until the VM or VirtManager dies. If we just returned immediately then the
55 // IVirtualMachine Binder object would be dropped and the VM would be killed.
56 wait_for_vm(vm)
57 }
58 }
59
60 /// Wait until the given VM or the VirtManager itself dies.
wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error>61 fn wait_for_vm(vm: Strong<dyn IVirtualMachine>) -> Result<(), Error> {
62 let dead = AtomicFlag::default();
63 let callback = BnVirtualMachineCallback::new_binder(
64 VirtualMachineCallback { dead: dead.clone() },
65 BinderFeatures::default(),
66 );
67 vm.registerCallback(&callback)?;
68 let death_recipient = wait_for_death(&mut vm.as_binder(), dead.clone())?;
69 dead.wait();
70 // Ensure that death_recipient isn't dropped before we wait on the flag, as it is removed
71 // from the Binder when it's dropped.
72 drop(death_recipient);
73 Ok(())
74 }
75
76 /// Raise the given flag when the given Binder object dies.
77 ///
78 /// If the returned DeathRecipient is dropped then this will no longer do anything.
wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error>79 fn wait_for_death(binder: &mut impl IBinder, dead: AtomicFlag) -> Result<DeathRecipient, Error> {
80 let mut death_recipient = DeathRecipient::new(move || {
81 println!("VirtManager died");
82 dead.raise();
83 });
84 binder.link_to_death(&mut death_recipient)?;
85 Ok(death_recipient)
86 }
87
88 #[derive(Debug)]
89 struct VirtualMachineCallback {
90 dead: AtomicFlag,
91 }
92
93 impl Interface for VirtualMachineCallback {}
94
95 impl IVirtualMachineCallback for VirtualMachineCallback {
onDied(&self, _cid: i32) -> BinderResult<()>96 fn onDied(&self, _cid: i32) -> BinderResult<()> {
97 println!("VM died");
98 self.dead.raise();
99 Ok(())
100 }
101 }
102
103 /// Safely duplicate the standard output file descriptor.
duplicate_stdout() -> io::Result<File>104 fn 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 }
117