blob: 0e3d140b6c2c07be615bdd492ffc6fbad750f141 [file] [log] [blame]
Andrew Walbrand0ef4002022-05-16 16:14:10 +00001// 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
17mod death_reason;
Alan Stokes2bead0d2022-09-05 16:58:34 +010018mod error_code;
Andrew Walbrand0ef4002022-05-16 16:14:10 +000019mod errors;
20mod sync;
21
22pub use crate::death_reason::DeathReason;
Alan Stokes2bead0d2022-09-05 16:58:34 +010023pub use crate::error_code::ErrorCode;
Andrew Walbranc944fae2022-08-02 16:16:28 +000024pub use crate::errors::VmWaitError;
25use crate::sync::Monitor;
David Brazdil49f96f52022-12-16 21:29:13 +000026use android_system_virtualizationcommon::aidl::android::system::virtualizationcommon::{
27 DeathReason::DeathReason as AidlDeathReason, ErrorCode::ErrorCode as AidlErrorCode,
28};
Andrew Walbrand0ef4002022-05-16 16:14:10 +000029use android_system_virtualizationservice::{
30 aidl::android::system::virtualizationservice::{
Andrew Walbrand0ef4002022-05-16 16:14:10 +000031 IVirtualMachine::IVirtualMachine,
32 IVirtualMachineCallback::{BnVirtualMachineCallback, IVirtualMachineCallback},
33 IVirtualizationService::IVirtualizationService,
34 VirtualMachineConfig::VirtualMachineConfig,
35 VirtualMachineState::VirtualMachineState,
36 },
37 binder::{
Andrew Walbran1072cc02022-05-23 14:47:58 +000038 wait_for_interface, BinderFeatures, DeathRecipient, FromIBinder, IBinder, Interface,
Andrew Walbrand0ef4002022-05-16 16:14:10 +000039 ParcelFileDescriptor, Result as BinderResult, StatusCode, Strong,
40 },
41};
David Brazdil46446062022-10-25 13:18:18 +010042use command_fds::CommandFdExt;
Andrew Walbrand0ef4002022-05-16 16:14:10 +000043use log::warn;
David Brazdil46446062022-10-25 13:18:18 +010044use rpcbinder::{FileDescriptorTransportMode, RpcSession};
45use shared_child::SharedChild;
46use std::io::{self, Read};
47use std::process::Command;
Andrew Walbrand0ef4002022-05-16 16:14:10 +000048use std::{
49 fmt::{self, Debug, Formatter},
50 fs::File,
David Brazdil46446062022-10-25 13:18:18 +010051 os::unix::io::{AsFd, AsRawFd, FromRawFd, IntoRawFd, OwnedFd},
Andrew Walbrand0ef4002022-05-16 16:14:10 +000052 sync::Arc,
53 time::Duration,
54};
55
56const VIRTUALIZATION_SERVICE_BINDER_SERVICE_IDENTIFIER: &str =
57 "android.system.virtualizationservice";
58
David Brazdil46446062022-10-25 13:18:18 +010059const VIRTMGR_PATH: &str = "/apex/com.android.virt/bin/virtmgr";
60const VIRTMGR_THREADS: usize = 16;
61
62fn posix_pipe() -> Result<(OwnedFd, OwnedFd), io::Error> {
63 use nix::fcntl::OFlag;
64 use nix::unistd::pipe2;
65
66 // Create new POSIX pipe. Make it O_CLOEXEC to align with how Rust creates
67 // file descriptors (expected by SharedChild).
68 let (raw1, raw2) = pipe2(OFlag::O_CLOEXEC)?;
69
70 // SAFETY - Taking ownership of brand new FDs.
71 unsafe { Ok((OwnedFd::from_raw_fd(raw1), OwnedFd::from_raw_fd(raw2))) }
72}
73
74fn posix_socketpair() -> Result<(OwnedFd, OwnedFd), io::Error> {
75 use nix::sys::socket::{socketpair, AddressFamily, SockFlag, SockType};
76
77 // Create new POSIX socketpair, suitable for use with RpcBinder UDS bootstrap
78 // transport. Make it O_CLOEXEC to align with how Rust creates file
79 // descriptors (expected by SharedChild).
80 let (raw1, raw2) =
81 socketpair(AddressFamily::Unix, SockType::Stream, None, SockFlag::SOCK_CLOEXEC)?;
82
83 // SAFETY - Taking ownership of brand new FDs.
84 unsafe { Ok((OwnedFd::from_raw_fd(raw1), OwnedFd::from_raw_fd(raw2))) }
85}
86
87/// A running instance of virtmgr which is hosting a VirtualizationService
88/// RpcBinder server.
89pub struct VirtualizationService {
90 /// Client FD for UDS connection to virtmgr's RpcBinder server. Closing it
91 /// will make virtmgr shut down.
92 client_fd: OwnedFd,
93}
94
95impl VirtualizationService {
96 /// Spawns a new instance of virtmgr, a child process that will host
97 /// the VirtualizationService AIDL service.
98 pub fn new() -> Result<VirtualizationService, io::Error> {
99 let (wait_fd, ready_fd) = posix_pipe()?;
100 let (client_fd, server_fd) = posix_socketpair()?;
101
102 let mut command = Command::new(VIRTMGR_PATH);
103 command.arg("--rpc-server-fd").arg(format!("{}", server_fd.as_raw_fd()));
104 command.arg("--ready-fd").arg(format!("{}", ready_fd.as_raw_fd()));
105 command.preserved_fds(vec![server_fd.as_raw_fd(), ready_fd.as_raw_fd()]);
106
107 SharedChild::spawn(&mut command)?;
108
109 // Drop FDs that belong to virtmgr.
110 drop(server_fd);
111 drop(ready_fd);
112
113 // Wait for the child to signal that the RpcBinder server is ready
114 // by closing its end of the pipe.
115 let _ = File::from(wait_fd).read(&mut [0]);
116
117 Ok(VirtualizationService { client_fd })
118 }
119
120 /// Connects to the VirtualizationService AIDL service.
121 pub fn connect(&self) -> Result<Strong<dyn IVirtualizationService>, io::Error> {
122 let session = RpcSession::new();
123 session.set_file_descriptor_transport_mode(FileDescriptorTransportMode::Unix);
124 session.set_max_incoming_threads(VIRTMGR_THREADS);
125 session.set_max_outgoing_threads(VIRTMGR_THREADS);
126 session
127 .setup_unix_domain_bootstrap_client(self.client_fd.as_fd())
128 .map_err(|_| io::Error::from(io::ErrorKind::ConnectionRefused))
129 }
130}
131
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000132/// Connects to the VirtualizationService AIDL service.
133pub fn connect() -> Result<Strong<dyn IVirtualizationService>, StatusCode> {
134 wait_for_interface(VIRTUALIZATION_SERVICE_BINDER_SERVICE_IDENTIFIER)
135}
136
137/// A virtual machine which has been started by the VirtualizationService.
138pub struct VmInstance {
139 /// The `IVirtualMachine` Binder object representing the VM.
140 pub vm: Strong<dyn IVirtualMachine>,
141 cid: i32,
142 state: Arc<Monitor<VmState>>,
143 // Ensure that the DeathRecipient isn't dropped while someone might call wait_for_death, as it
144 // is removed from the Binder when it's dropped.
145 _death_recipient: DeathRecipient,
146}
147
Alan Stokes0e82b502022-08-08 14:44:48 +0100148/// A trait to be implemented by clients to handle notification of significant changes to the VM
149/// state. Default implementations of all functions are provided so clients only need to handle the
150/// notifications they are interested in.
151#[allow(unused_variables)]
152pub trait VmCallback {
153 /// Called when the payload has been started within the VM. If present, `stream` is connected
154 /// to the stdin/stdout of the payload.
David Brazdil451cc962022-10-14 14:08:12 +0100155 fn on_payload_started(&self, cid: i32) {}
Alan Stokes0e82b502022-08-08 14:44:48 +0100156
157 /// Callend when the payload has notified Virtualization Service that it is ready to serve
158 /// clients.
159 fn on_payload_ready(&self, cid: i32) {}
160
161 /// Called when the payload has exited in the VM. `exit_code` is the exit code of the payload
162 /// process.
163 fn on_payload_finished(&self, cid: i32, exit_code: i32) {}
164
165 /// Called when an error has occurred in the VM. The `error_code` and `message` may give
166 /// further details.
Alan Stokes2bead0d2022-09-05 16:58:34 +0100167 fn on_error(&self, cid: i32, error_code: ErrorCode, message: &str) {}
Alan Stokes0e82b502022-08-08 14:44:48 +0100168
169 /// Called when the VM has exited, all resources have been freed, and any logs have been
170 /// written. `death_reason` gives an indication why the VM exited.
171 fn on_died(&self, cid: i32, death_reason: DeathReason) {}
172}
173
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000174impl VmInstance {
175 /// Creates (but doesn't start) a new VM with the given configuration.
176 pub fn create(
177 service: &dyn IVirtualizationService,
178 config: &VirtualMachineConfig,
179 console: Option<File>,
180 log: Option<File>,
Alan Stokes0e82b502022-08-08 14:44:48 +0100181 callback: Option<Box<dyn VmCallback + Send + Sync>>,
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000182 ) -> BinderResult<Self> {
183 let console = console.map(ParcelFileDescriptor::new);
184 let log = log.map(ParcelFileDescriptor::new);
185
186 let vm = service.createVm(config, console.as_ref(), log.as_ref())?;
187
188 let cid = vm.getCid()?;
189
190 // Register callback before starting VM, in case it dies immediately.
191 let state = Arc::new(Monitor::new(VmState::default()));
192 let callback = BnVirtualMachineCallback::new_binder(
Alan Stokes0e82b502022-08-08 14:44:48 +0100193 VirtualMachineCallback { state: state.clone(), client_callback: callback },
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000194 BinderFeatures::default(),
195 );
196 vm.registerCallback(&callback)?;
197 let death_recipient = wait_for_binder_death(&mut vm.as_binder(), state.clone())?;
198
199 Ok(Self { vm, cid, state, _death_recipient: death_recipient })
200 }
201
202 /// Starts the VM.
203 pub fn start(&self) -> BinderResult<()> {
204 self.vm.start()
205 }
206
207 /// Returns the CID used for vsock connections to the VM.
208 pub fn cid(&self) -> i32 {
209 self.cid
210 }
211
212 /// Returns the current lifecycle state of the VM.
213 pub fn state(&self) -> BinderResult<VirtualMachineState> {
214 self.vm.getState()
215 }
216
217 /// Blocks until the VM or the VirtualizationService itself dies, and then returns the reason
218 /// why it died.
219 pub fn wait_for_death(&self) -> DeathReason {
220 self.state.wait_while(|state| state.death_reason.is_none()).unwrap().death_reason.unwrap()
221 }
222
Alan Stokes71403772022-06-21 14:56:28 +0100223 /// Blocks until the VM or the VirtualizationService itself dies, or the given timeout expires.
224 /// Returns the reason why it died if it did so.
225 pub fn wait_for_death_with_timeout(&self, timeout: Duration) -> Option<DeathReason> {
226 let (state, _timeout_result) =
227 self.state.wait_timeout_while(timeout, |state| state.death_reason.is_none()).unwrap();
228 // We don't care if it timed out - we just return the reason if there now is one
229 state.death_reason
230 }
231
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000232 /// Waits until the VM reports that it is ready.
233 ///
234 /// Returns an error if the VM dies first, or the `timeout` elapses before the VM is ready.
235 pub fn wait_until_ready(&self, timeout: Duration) -> Result<(), VmWaitError> {
236 let (state, timeout_result) = self
237 .state
238 .wait_timeout_while(timeout, |state| {
239 state.reported_state < VirtualMachineState::READY && state.death_reason.is_none()
240 })
241 .unwrap();
242 if timeout_result.timed_out() {
243 Err(VmWaitError::TimedOut)
244 } else if let Some(reason) = state.death_reason {
245 Err(VmWaitError::Died { reason })
246 } else if state.reported_state != VirtualMachineState::READY {
247 Err(VmWaitError::Finished)
248 } else {
249 Ok(())
250 }
251 }
Andrew Walbran1072cc02022-05-23 14:47:58 +0000252
253 /// Tries to connect to an RPC Binder service provided by the VM on the given vsock port.
Alan Stokes71403772022-06-21 14:56:28 +0100254 pub fn connect_service<T: FromIBinder + ?Sized>(
Andrew Walbran1072cc02022-05-23 14:47:58 +0000255 &self,
256 port: u32,
Andrew Walbranc944fae2022-08-02 16:16:28 +0000257 ) -> Result<Strong<T>, StatusCode> {
David Brazdila2125dd2022-12-14 16:37:44 +0000258 RpcSession::new().setup_preconnected_client(|| {
Andrew Walbranc944fae2022-08-02 16:16:28 +0000259 match self.vm.connectVsock(port as i32) {
260 Ok(vsock) => {
261 // Ownership of the fd is transferred to binder
262 Some(vsock.into_raw_fd())
263 }
264 Err(e) => {
265 warn!("Vsock connection failed: {}", e);
266 None
267 }
268 }
269 })
Andrew Walbran1072cc02022-05-23 14:47:58 +0000270 }
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000271}
272
273impl Debug for VmInstance {
274 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
275 f.debug_struct("VmInstance").field("cid", &self.cid).field("state", &self.state).finish()
276 }
277}
278
279/// Notify the VmState when the given Binder object dies.
280///
281/// If the returned DeathRecipient is dropped then this will no longer do anything.
282fn wait_for_binder_death(
283 binder: &mut impl IBinder,
284 state: Arc<Monitor<VmState>>,
285) -> BinderResult<DeathRecipient> {
286 let mut death_recipient = DeathRecipient::new(move || {
287 warn!("VirtualizationService unexpectedly died");
288 state.notify_death(DeathReason::VirtualizationServiceDied);
289 });
290 binder.link_to_death(&mut death_recipient)?;
291 Ok(death_recipient)
292}
293
294#[derive(Debug, Default)]
295struct VmState {
296 death_reason: Option<DeathReason>,
297 reported_state: VirtualMachineState,
298}
299
300impl Monitor<VmState> {
301 fn notify_death(&self, reason: DeathReason) {
302 let state = &mut *self.state.lock().unwrap();
303 // In case this method is called more than once, ignore subsequent calls.
304 if state.death_reason.is_none() {
305 state.death_reason.replace(reason);
306 self.cv.notify_all();
307 }
308 }
309
310 fn notify_state(&self, state: VirtualMachineState) {
311 self.state.lock().unwrap().reported_state = state;
312 self.cv.notify_all();
313 }
314}
315
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000316struct VirtualMachineCallback {
317 state: Arc<Monitor<VmState>>,
Alan Stokes0e82b502022-08-08 14:44:48 +0100318 client_callback: Option<Box<dyn VmCallback + Send + Sync>>,
319}
320
321impl Debug for VirtualMachineCallback {
322 fn fmt(&self, fmt: &mut fmt::Formatter) -> fmt::Result {
323 fmt.debug_struct("VirtualMachineCallback")
324 .field("state", &self.state)
325 .field(
326 "client_callback",
327 &if self.client_callback.is_some() { "Some(...)" } else { "None" },
328 )
329 .finish()
330 }
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000331}
332
333impl Interface for VirtualMachineCallback {}
334
335impl IVirtualMachineCallback for VirtualMachineCallback {
David Brazdil451cc962022-10-14 14:08:12 +0100336 fn onPayloadStarted(&self, cid: i32) -> BinderResult<()> {
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000337 self.state.notify_state(VirtualMachineState::STARTED);
Alan Stokes0e82b502022-08-08 14:44:48 +0100338 if let Some(ref callback) = self.client_callback {
David Brazdil451cc962022-10-14 14:08:12 +0100339 callback.on_payload_started(cid);
340 }
341 Ok(())
342 }
343
Alan Stokes0e82b502022-08-08 14:44:48 +0100344 fn onPayloadReady(&self, cid: i32) -> BinderResult<()> {
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000345 self.state.notify_state(VirtualMachineState::READY);
Alan Stokes0e82b502022-08-08 14:44:48 +0100346 if let Some(ref callback) = self.client_callback {
347 callback.on_payload_ready(cid);
348 }
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000349 Ok(())
350 }
351
Alan Stokes0e82b502022-08-08 14:44:48 +0100352 fn onPayloadFinished(&self, cid: i32, exit_code: i32) -> BinderResult<()> {
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000353 self.state.notify_state(VirtualMachineState::FINISHED);
Alan Stokes0e82b502022-08-08 14:44:48 +0100354 if let Some(ref callback) = self.client_callback {
355 callback.on_payload_finished(cid, exit_code);
356 }
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000357 Ok(())
358 }
359
Alan Stokes2bead0d2022-09-05 16:58:34 +0100360 fn onError(&self, cid: i32, error_code: AidlErrorCode, message: &str) -> BinderResult<()> {
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000361 self.state.notify_state(VirtualMachineState::FINISHED);
Alan Stokes0e82b502022-08-08 14:44:48 +0100362 if let Some(ref callback) = self.client_callback {
Alan Stokes2bead0d2022-09-05 16:58:34 +0100363 let error_code = error_code.into();
Alan Stokes0e82b502022-08-08 14:44:48 +0100364 callback.on_error(cid, error_code, message);
365 }
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000366 Ok(())
367 }
368
Alan Stokes0e82b502022-08-08 14:44:48 +0100369 fn onDied(&self, cid: i32, reason: AidlDeathReason) -> BinderResult<()> {
370 let reason = reason.into();
371 self.state.notify_death(reason);
372 if let Some(ref callback) = self.client_callback {
373 callback.on_died(cid, reason);
374 }
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000375 Ok(())
376 }
377}