blob: d182b6070670421fbf438d075571a365083cde11 [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;
18mod errors;
Andrew Walbran1072cc02022-05-23 14:47:58 +000019mod rpc_binder;
Andrew Walbrand0ef4002022-05-16 16:14:10 +000020mod sync;
21
22pub use crate::death_reason::DeathReason;
Andrew Walbran1072cc02022-05-23 14:47:58 +000023pub use crate::errors::{GetServiceError, VmWaitError};
24use crate::{rpc_binder::VsockFactory, sync::Monitor};
Andrew Walbrand0ef4002022-05-16 16:14:10 +000025use android_system_virtualizationservice::{
26 aidl::android::system::virtualizationservice::{
27 DeathReason::DeathReason as AidlDeathReason,
28 IVirtualMachine::IVirtualMachine,
29 IVirtualMachineCallback::{BnVirtualMachineCallback, IVirtualMachineCallback},
30 IVirtualizationService::IVirtualizationService,
31 VirtualMachineConfig::VirtualMachineConfig,
32 VirtualMachineState::VirtualMachineState,
33 },
34 binder::{
Andrew Walbran1072cc02022-05-23 14:47:58 +000035 wait_for_interface, BinderFeatures, DeathRecipient, FromIBinder, IBinder, Interface,
Andrew Walbrand0ef4002022-05-16 16:14:10 +000036 ParcelFileDescriptor, Result as BinderResult, StatusCode, Strong,
37 },
38};
39use log::warn;
40use std::{
41 fmt::{self, Debug, Formatter},
42 fs::File,
43 sync::Arc,
44 time::Duration,
45};
46
47const VIRTUALIZATION_SERVICE_BINDER_SERVICE_IDENTIFIER: &str =
48 "android.system.virtualizationservice";
49
50/// Connects to the VirtualizationService AIDL service.
51pub fn connect() -> Result<Strong<dyn IVirtualizationService>, StatusCode> {
52 wait_for_interface(VIRTUALIZATION_SERVICE_BINDER_SERVICE_IDENTIFIER)
53}
54
55/// A virtual machine which has been started by the VirtualizationService.
56pub struct VmInstance {
57 /// The `IVirtualMachine` Binder object representing the VM.
58 pub vm: Strong<dyn IVirtualMachine>,
59 cid: i32,
60 state: Arc<Monitor<VmState>>,
61 // Ensure that the DeathRecipient isn't dropped while someone might call wait_for_death, as it
62 // is removed from the Binder when it's dropped.
63 _death_recipient: DeathRecipient,
64}
65
66impl VmInstance {
67 /// Creates (but doesn't start) a new VM with the given configuration.
68 pub fn create(
69 service: &dyn IVirtualizationService,
70 config: &VirtualMachineConfig,
71 console: Option<File>,
72 log: Option<File>,
73 ) -> BinderResult<Self> {
74 let console = console.map(ParcelFileDescriptor::new);
75 let log = log.map(ParcelFileDescriptor::new);
76
77 let vm = service.createVm(config, console.as_ref(), log.as_ref())?;
78
79 let cid = vm.getCid()?;
80
81 // Register callback before starting VM, in case it dies immediately.
82 let state = Arc::new(Monitor::new(VmState::default()));
83 let callback = BnVirtualMachineCallback::new_binder(
84 VirtualMachineCallback { state: state.clone() },
85 BinderFeatures::default(),
86 );
87 vm.registerCallback(&callback)?;
88 let death_recipient = wait_for_binder_death(&mut vm.as_binder(), state.clone())?;
89
90 Ok(Self { vm, cid, state, _death_recipient: death_recipient })
91 }
92
93 /// Starts the VM.
94 pub fn start(&self) -> BinderResult<()> {
95 self.vm.start()
96 }
97
98 /// Returns the CID used for vsock connections to the VM.
99 pub fn cid(&self) -> i32 {
100 self.cid
101 }
102
103 /// Returns the current lifecycle state of the VM.
104 pub fn state(&self) -> BinderResult<VirtualMachineState> {
105 self.vm.getState()
106 }
107
108 /// Blocks until the VM or the VirtualizationService itself dies, and then returns the reason
109 /// why it died.
110 pub fn wait_for_death(&self) -> DeathReason {
111 self.state.wait_while(|state| state.death_reason.is_none()).unwrap().death_reason.unwrap()
112 }
113
114 /// Waits until the VM reports that it is ready.
115 ///
116 /// Returns an error if the VM dies first, or the `timeout` elapses before the VM is ready.
117 pub fn wait_until_ready(&self, timeout: Duration) -> Result<(), VmWaitError> {
118 let (state, timeout_result) = self
119 .state
120 .wait_timeout_while(timeout, |state| {
121 state.reported_state < VirtualMachineState::READY && state.death_reason.is_none()
122 })
123 .unwrap();
124 if timeout_result.timed_out() {
125 Err(VmWaitError::TimedOut)
126 } else if let Some(reason) = state.death_reason {
127 Err(VmWaitError::Died { reason })
128 } else if state.reported_state != VirtualMachineState::READY {
129 Err(VmWaitError::Finished)
130 } else {
131 Ok(())
132 }
133 }
Andrew Walbran1072cc02022-05-23 14:47:58 +0000134
135 /// Tries to connect to an RPC Binder service provided by the VM on the given vsock port.
136 pub fn get_service<T: FromIBinder + ?Sized>(
137 &self,
138 port: u32,
139 ) -> Result<Strong<T>, GetServiceError> {
140 let mut vsock_factory = VsockFactory::new(&*self.vm, port);
141
142 let ibinder = vsock_factory.connect_rpc_client()?;
143
144 FromIBinder::try_from(ibinder).map_err(GetServiceError::WrongServiceType)
145 }
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000146}
147
148impl Debug for VmInstance {
149 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
150 f.debug_struct("VmInstance").field("cid", &self.cid).field("state", &self.state).finish()
151 }
152}
153
154/// Notify the VmState when the given Binder object dies.
155///
156/// If the returned DeathRecipient is dropped then this will no longer do anything.
157fn wait_for_binder_death(
158 binder: &mut impl IBinder,
159 state: Arc<Monitor<VmState>>,
160) -> BinderResult<DeathRecipient> {
161 let mut death_recipient = DeathRecipient::new(move || {
162 warn!("VirtualizationService unexpectedly died");
163 state.notify_death(DeathReason::VirtualizationServiceDied);
164 });
165 binder.link_to_death(&mut death_recipient)?;
166 Ok(death_recipient)
167}
168
169#[derive(Debug, Default)]
170struct VmState {
171 death_reason: Option<DeathReason>,
172 reported_state: VirtualMachineState,
173}
174
175impl Monitor<VmState> {
176 fn notify_death(&self, reason: DeathReason) {
177 let state = &mut *self.state.lock().unwrap();
178 // In case this method is called more than once, ignore subsequent calls.
179 if state.death_reason.is_none() {
180 state.death_reason.replace(reason);
181 self.cv.notify_all();
182 }
183 }
184
185 fn notify_state(&self, state: VirtualMachineState) {
186 self.state.lock().unwrap().reported_state = state;
187 self.cv.notify_all();
188 }
189}
190
191#[derive(Debug)]
192struct VirtualMachineCallback {
193 state: Arc<Monitor<VmState>>,
194}
195
196impl Interface for VirtualMachineCallback {}
197
198impl IVirtualMachineCallback for VirtualMachineCallback {
199 fn onPayloadStarted(
200 &self,
201 _cid: i32,
202 _stream: Option<&ParcelFileDescriptor>,
203 ) -> BinderResult<()> {
204 self.state.notify_state(VirtualMachineState::STARTED);
205 Ok(())
206 }
207
208 fn onPayloadReady(&self, _cid: i32) -> BinderResult<()> {
209 self.state.notify_state(VirtualMachineState::READY);
210 Ok(())
211 }
212
213 fn onPayloadFinished(&self, _cid: i32, _exit_code: i32) -> BinderResult<()> {
214 self.state.notify_state(VirtualMachineState::FINISHED);
215 Ok(())
216 }
217
218 fn onError(&self, _cid: i32, _error_code: i32, _message: &str) -> BinderResult<()> {
219 self.state.notify_state(VirtualMachineState::FINISHED);
220 Ok(())
221 }
222
223 fn onDied(&self, _cid: i32, reason: AidlDeathReason) -> BinderResult<()> {
224 self.state.notify_death(reason.into());
225 Ok(())
226 }
227}