Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 1 | // Copyright 2022, 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 | //! Client library for VirtualizationService. |
| 16 | |
| 17 | mod death_reason; |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 18 | mod error_code; |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 19 | mod errors; |
| 20 | mod sync; |
| 21 | |
| 22 | pub use crate::death_reason::DeathReason; |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 23 | pub use crate::error_code::ErrorCode; |
Andrew Walbran | c944fae | 2022-08-02 16:16:28 +0000 | [diff] [blame] | 24 | pub use crate::errors::VmWaitError; |
| 25 | use crate::sync::Monitor; |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 26 | use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::ErrorCode::ErrorCode as AidlErrorCode; |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 27 | use android_system_virtualizationservice::{ |
| 28 | aidl::android::system::virtualizationservice::{ |
| 29 | DeathReason::DeathReason as AidlDeathReason, |
| 30 | IVirtualMachine::IVirtualMachine, |
| 31 | IVirtualMachineCallback::{BnVirtualMachineCallback, IVirtualMachineCallback}, |
| 32 | IVirtualizationService::IVirtualizationService, |
| 33 | VirtualMachineConfig::VirtualMachineConfig, |
| 34 | VirtualMachineState::VirtualMachineState, |
| 35 | }, |
| 36 | binder::{ |
Andrew Walbran | 1072cc0 | 2022-05-23 14:47:58 +0000 | [diff] [blame] | 37 | wait_for_interface, BinderFeatures, DeathRecipient, FromIBinder, IBinder, Interface, |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 38 | ParcelFileDescriptor, Result as BinderResult, StatusCode, Strong, |
| 39 | }, |
| 40 | }; |
| 41 | use log::warn; |
Andrew Walbran | 7eb5ca4 | 2022-08-08 15:33:34 +0000 | [diff] [blame] | 42 | use rpcbinder::get_preconnected_rpc_interface; |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 43 | use std::{ |
| 44 | fmt::{self, Debug, Formatter}, |
| 45 | fs::File, |
Andrew Walbran | c944fae | 2022-08-02 16:16:28 +0000 | [diff] [blame] | 46 | os::unix::io::IntoRawFd, |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 47 | sync::Arc, |
| 48 | time::Duration, |
| 49 | }; |
| 50 | |
| 51 | const VIRTUALIZATION_SERVICE_BINDER_SERVICE_IDENTIFIER: &str = |
| 52 | "android.system.virtualizationservice"; |
| 53 | |
| 54 | /// Connects to the VirtualizationService AIDL service. |
| 55 | pub fn connect() -> Result<Strong<dyn IVirtualizationService>, StatusCode> { |
| 56 | wait_for_interface(VIRTUALIZATION_SERVICE_BINDER_SERVICE_IDENTIFIER) |
| 57 | } |
| 58 | |
| 59 | /// A virtual machine which has been started by the VirtualizationService. |
| 60 | pub struct VmInstance { |
| 61 | /// The `IVirtualMachine` Binder object representing the VM. |
| 62 | pub vm: Strong<dyn IVirtualMachine>, |
| 63 | cid: i32, |
| 64 | state: Arc<Monitor<VmState>>, |
| 65 | // Ensure that the DeathRecipient isn't dropped while someone might call wait_for_death, as it |
| 66 | // is removed from the Binder when it's dropped. |
| 67 | _death_recipient: DeathRecipient, |
| 68 | } |
| 69 | |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 70 | /// A trait to be implemented by clients to handle notification of significant changes to the VM |
| 71 | /// state. Default implementations of all functions are provided so clients only need to handle the |
| 72 | /// notifications they are interested in. |
| 73 | #[allow(unused_variables)] |
| 74 | pub trait VmCallback { |
| 75 | /// Called when the payload has been started within the VM. If present, `stream` is connected |
| 76 | /// to the stdin/stdout of the payload. |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame^] | 77 | fn on_payload_started(&self, cid: i32) {} |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 78 | |
| 79 | /// Callend when the payload has notified Virtualization Service that it is ready to serve |
| 80 | /// clients. |
| 81 | fn on_payload_ready(&self, cid: i32) {} |
| 82 | |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame^] | 83 | /// Called by the payload to forward its standard I/O streams to the host. |
| 84 | fn on_payload_stdio(&self, cid: i32, fd: &File); |
| 85 | |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 86 | /// Called when the payload has exited in the VM. `exit_code` is the exit code of the payload |
| 87 | /// process. |
| 88 | fn on_payload_finished(&self, cid: i32, exit_code: i32) {} |
| 89 | |
| 90 | /// Called when an error has occurred in the VM. The `error_code` and `message` may give |
| 91 | /// further details. |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 92 | fn on_error(&self, cid: i32, error_code: ErrorCode, message: &str) {} |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 93 | |
| 94 | /// Called when the VM has exited, all resources have been freed, and any logs have been |
| 95 | /// written. `death_reason` gives an indication why the VM exited. |
| 96 | fn on_died(&self, cid: i32, death_reason: DeathReason) {} |
| 97 | } |
| 98 | |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 99 | impl VmInstance { |
| 100 | /// Creates (but doesn't start) a new VM with the given configuration. |
| 101 | pub fn create( |
| 102 | service: &dyn IVirtualizationService, |
| 103 | config: &VirtualMachineConfig, |
| 104 | console: Option<File>, |
| 105 | log: Option<File>, |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 106 | callback: Option<Box<dyn VmCallback + Send + Sync>>, |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 107 | ) -> BinderResult<Self> { |
| 108 | let console = console.map(ParcelFileDescriptor::new); |
| 109 | let log = log.map(ParcelFileDescriptor::new); |
| 110 | |
| 111 | let vm = service.createVm(config, console.as_ref(), log.as_ref())?; |
| 112 | |
| 113 | let cid = vm.getCid()?; |
| 114 | |
| 115 | // Register callback before starting VM, in case it dies immediately. |
| 116 | let state = Arc::new(Monitor::new(VmState::default())); |
| 117 | let callback = BnVirtualMachineCallback::new_binder( |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 118 | VirtualMachineCallback { state: state.clone(), client_callback: callback }, |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 119 | BinderFeatures::default(), |
| 120 | ); |
| 121 | vm.registerCallback(&callback)?; |
| 122 | let death_recipient = wait_for_binder_death(&mut vm.as_binder(), state.clone())?; |
| 123 | |
| 124 | Ok(Self { vm, cid, state, _death_recipient: death_recipient }) |
| 125 | } |
| 126 | |
| 127 | /// Starts the VM. |
| 128 | pub fn start(&self) -> BinderResult<()> { |
| 129 | self.vm.start() |
| 130 | } |
| 131 | |
| 132 | /// Returns the CID used for vsock connections to the VM. |
| 133 | pub fn cid(&self) -> i32 { |
| 134 | self.cid |
| 135 | } |
| 136 | |
| 137 | /// Returns the current lifecycle state of the VM. |
| 138 | pub fn state(&self) -> BinderResult<VirtualMachineState> { |
| 139 | self.vm.getState() |
| 140 | } |
| 141 | |
| 142 | /// Blocks until the VM or the VirtualizationService itself dies, and then returns the reason |
| 143 | /// why it died. |
| 144 | pub fn wait_for_death(&self) -> DeathReason { |
| 145 | self.state.wait_while(|state| state.death_reason.is_none()).unwrap().death_reason.unwrap() |
| 146 | } |
| 147 | |
Alan Stokes | 7140377 | 2022-06-21 14:56:28 +0100 | [diff] [blame] | 148 | /// Blocks until the VM or the VirtualizationService itself dies, or the given timeout expires. |
| 149 | /// Returns the reason why it died if it did so. |
| 150 | pub fn wait_for_death_with_timeout(&self, timeout: Duration) -> Option<DeathReason> { |
| 151 | let (state, _timeout_result) = |
| 152 | self.state.wait_timeout_while(timeout, |state| state.death_reason.is_none()).unwrap(); |
| 153 | // We don't care if it timed out - we just return the reason if there now is one |
| 154 | state.death_reason |
| 155 | } |
| 156 | |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 157 | /// Waits until the VM reports that it is ready. |
| 158 | /// |
| 159 | /// Returns an error if the VM dies first, or the `timeout` elapses before the VM is ready. |
| 160 | pub fn wait_until_ready(&self, timeout: Duration) -> Result<(), VmWaitError> { |
| 161 | let (state, timeout_result) = self |
| 162 | .state |
| 163 | .wait_timeout_while(timeout, |state| { |
| 164 | state.reported_state < VirtualMachineState::READY && state.death_reason.is_none() |
| 165 | }) |
| 166 | .unwrap(); |
| 167 | if timeout_result.timed_out() { |
| 168 | Err(VmWaitError::TimedOut) |
| 169 | } else if let Some(reason) = state.death_reason { |
| 170 | Err(VmWaitError::Died { reason }) |
| 171 | } else if state.reported_state != VirtualMachineState::READY { |
| 172 | Err(VmWaitError::Finished) |
| 173 | } else { |
| 174 | Ok(()) |
| 175 | } |
| 176 | } |
Andrew Walbran | 1072cc0 | 2022-05-23 14:47:58 +0000 | [diff] [blame] | 177 | |
| 178 | /// Tries to connect to an RPC Binder service provided by the VM on the given vsock port. |
Alan Stokes | 7140377 | 2022-06-21 14:56:28 +0100 | [diff] [blame] | 179 | pub fn connect_service<T: FromIBinder + ?Sized>( |
Andrew Walbran | 1072cc0 | 2022-05-23 14:47:58 +0000 | [diff] [blame] | 180 | &self, |
| 181 | port: u32, |
Andrew Walbran | c944fae | 2022-08-02 16:16:28 +0000 | [diff] [blame] | 182 | ) -> Result<Strong<T>, StatusCode> { |
Andrew Walbran | 7eb5ca4 | 2022-08-08 15:33:34 +0000 | [diff] [blame] | 183 | get_preconnected_rpc_interface(|| { |
Andrew Walbran | c944fae | 2022-08-02 16:16:28 +0000 | [diff] [blame] | 184 | match self.vm.connectVsock(port as i32) { |
| 185 | Ok(vsock) => { |
| 186 | // Ownership of the fd is transferred to binder |
| 187 | Some(vsock.into_raw_fd()) |
| 188 | } |
| 189 | Err(e) => { |
| 190 | warn!("Vsock connection failed: {}", e); |
| 191 | None |
| 192 | } |
| 193 | } |
| 194 | }) |
Andrew Walbran | 1072cc0 | 2022-05-23 14:47:58 +0000 | [diff] [blame] | 195 | } |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 196 | |
| 197 | /// Get ramdump |
| 198 | pub fn get_ramdump(&self) -> Option<File> { |
| 199 | self.state.get_ramdump() |
| 200 | } |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 201 | } |
| 202 | |
| 203 | impl Debug for VmInstance { |
| 204 | fn fmt(&self, f: &mut Formatter) -> fmt::Result { |
| 205 | f.debug_struct("VmInstance").field("cid", &self.cid).field("state", &self.state).finish() |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | /// Notify the VmState when the given Binder object dies. |
| 210 | /// |
| 211 | /// If the returned DeathRecipient is dropped then this will no longer do anything. |
| 212 | fn wait_for_binder_death( |
| 213 | binder: &mut impl IBinder, |
| 214 | state: Arc<Monitor<VmState>>, |
| 215 | ) -> BinderResult<DeathRecipient> { |
| 216 | let mut death_recipient = DeathRecipient::new(move || { |
| 217 | warn!("VirtualizationService unexpectedly died"); |
| 218 | state.notify_death(DeathReason::VirtualizationServiceDied); |
| 219 | }); |
| 220 | binder.link_to_death(&mut death_recipient)?; |
| 221 | Ok(death_recipient) |
| 222 | } |
| 223 | |
| 224 | #[derive(Debug, Default)] |
| 225 | struct VmState { |
| 226 | death_reason: Option<DeathReason>, |
| 227 | reported_state: VirtualMachineState, |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 228 | ramdump: Option<File>, |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 229 | } |
| 230 | |
| 231 | impl Monitor<VmState> { |
| 232 | fn notify_death(&self, reason: DeathReason) { |
| 233 | let state = &mut *self.state.lock().unwrap(); |
| 234 | // In case this method is called more than once, ignore subsequent calls. |
| 235 | if state.death_reason.is_none() { |
| 236 | state.death_reason.replace(reason); |
| 237 | self.cv.notify_all(); |
| 238 | } |
| 239 | } |
| 240 | |
| 241 | fn notify_state(&self, state: VirtualMachineState) { |
| 242 | self.state.lock().unwrap().reported_state = state; |
| 243 | self.cv.notify_all(); |
| 244 | } |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 245 | |
| 246 | fn set_ramdump(&self, ramdump: File) { |
| 247 | self.state.lock().unwrap().ramdump = Some(ramdump); |
| 248 | } |
| 249 | |
| 250 | fn get_ramdump(&self) -> Option<File> { |
| 251 | self.state.lock().unwrap().ramdump.as_ref().and_then(|f| f.try_clone().ok()) |
| 252 | } |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 253 | } |
| 254 | |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 255 | struct VirtualMachineCallback { |
| 256 | state: Arc<Monitor<VmState>>, |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 257 | client_callback: Option<Box<dyn VmCallback + Send + Sync>>, |
| 258 | } |
| 259 | |
| 260 | impl Debug for VirtualMachineCallback { |
| 261 | fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result { |
| 262 | fmt.debug_struct("VirtualMachineCallback") |
| 263 | .field("state", &self.state) |
| 264 | .field( |
| 265 | "client_callback", |
| 266 | &if self.client_callback.is_some() { "Some(...)" } else { "None" }, |
| 267 | ) |
| 268 | .finish() |
| 269 | } |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 270 | } |
| 271 | |
| 272 | impl Interface for VirtualMachineCallback {} |
| 273 | |
| 274 | impl IVirtualMachineCallback for VirtualMachineCallback { |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame^] | 275 | fn onPayloadStarted(&self, cid: i32) -> BinderResult<()> { |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 276 | self.state.notify_state(VirtualMachineState::STARTED); |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 277 | if let Some(ref callback) = self.client_callback { |
David Brazdil | 451cc96 | 2022-10-14 14:08:12 +0100 | [diff] [blame^] | 278 | callback.on_payload_started(cid); |
| 279 | } |
| 280 | Ok(()) |
| 281 | } |
| 282 | |
| 283 | fn onPayloadStdio(&self, cid: i32, stream: &ParcelFileDescriptor) -> BinderResult<()> { |
| 284 | if let Some(ref callback) = self.client_callback { |
| 285 | callback.on_payload_stdio(cid, stream.as_ref()); |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 286 | } |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 287 | Ok(()) |
| 288 | } |
| 289 | |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 290 | fn onPayloadReady(&self, cid: i32) -> BinderResult<()> { |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 291 | self.state.notify_state(VirtualMachineState::READY); |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 292 | if let Some(ref callback) = self.client_callback { |
| 293 | callback.on_payload_ready(cid); |
| 294 | } |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 295 | Ok(()) |
| 296 | } |
| 297 | |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 298 | fn onPayloadFinished(&self, cid: i32, exit_code: i32) -> BinderResult<()> { |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 299 | self.state.notify_state(VirtualMachineState::FINISHED); |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 300 | if let Some(ref callback) = self.client_callback { |
| 301 | callback.on_payload_finished(cid, exit_code); |
| 302 | } |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 303 | Ok(()) |
| 304 | } |
| 305 | |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 306 | fn onError(&self, cid: i32, error_code: AidlErrorCode, message: &str) -> BinderResult<()> { |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 307 | self.state.notify_state(VirtualMachineState::FINISHED); |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 308 | if let Some(ref callback) = self.client_callback { |
Alan Stokes | 2bead0d | 2022-09-05 16:58:34 +0100 | [diff] [blame] | 309 | let error_code = error_code.into(); |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 310 | callback.on_error(cid, error_code, message); |
| 311 | } |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 312 | Ok(()) |
| 313 | } |
| 314 | |
Jiyong Park | e558ab1 | 2022-07-07 20:18:55 +0900 | [diff] [blame] | 315 | fn onRamdump(&self, _cid: i32, ramdump: &ParcelFileDescriptor) -> BinderResult<()> { |
| 316 | let ramdump: File = ramdump.as_ref().try_clone().unwrap(); |
| 317 | self.state.set_ramdump(ramdump); |
| 318 | Ok(()) |
| 319 | } |
| 320 | |
Alan Stokes | 0e82b50 | 2022-08-08 14:44:48 +0100 | [diff] [blame] | 321 | fn onDied(&self, cid: i32, reason: AidlDeathReason) -> BinderResult<()> { |
| 322 | let reason = reason.into(); |
| 323 | self.state.notify_death(reason); |
| 324 | if let Some(ref callback) = self.client_callback { |
| 325 | callback.on_died(cid, reason); |
| 326 | } |
Andrew Walbran | d0ef400 | 2022-05-16 16:14:10 +0000 | [diff] [blame] | 327 | Ok(()) |
| 328 | } |
| 329 | } |