blob: 867c3a7251375202e65c7a3de4ff063bedc09f0b [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 }
Jiyong Parke558ab12022-07-07 20:18:55 +0900146
147 /// Get ramdump
148 pub fn get_ramdump(&self) -> Option<File> {
149 self.state.get_ramdump()
150 }
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000151}
152
153impl Debug for VmInstance {
154 fn fmt(&self, f: &mut Formatter) -> fmt::Result {
155 f.debug_struct("VmInstance").field("cid", &self.cid).field("state", &self.state).finish()
156 }
157}
158
159/// Notify the VmState when the given Binder object dies.
160///
161/// If the returned DeathRecipient is dropped then this will no longer do anything.
162fn wait_for_binder_death(
163 binder: &mut impl IBinder,
164 state: Arc<Monitor<VmState>>,
165) -> BinderResult<DeathRecipient> {
166 let mut death_recipient = DeathRecipient::new(move || {
167 warn!("VirtualizationService unexpectedly died");
168 state.notify_death(DeathReason::VirtualizationServiceDied);
169 });
170 binder.link_to_death(&mut death_recipient)?;
171 Ok(death_recipient)
172}
173
174#[derive(Debug, Default)]
175struct VmState {
176 death_reason: Option<DeathReason>,
177 reported_state: VirtualMachineState,
Jiyong Parke558ab12022-07-07 20:18:55 +0900178 ramdump: Option<File>,
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000179}
180
181impl Monitor<VmState> {
182 fn notify_death(&self, reason: DeathReason) {
183 let state = &mut *self.state.lock().unwrap();
184 // In case this method is called more than once, ignore subsequent calls.
185 if state.death_reason.is_none() {
186 state.death_reason.replace(reason);
187 self.cv.notify_all();
188 }
189 }
190
191 fn notify_state(&self, state: VirtualMachineState) {
192 self.state.lock().unwrap().reported_state = state;
193 self.cv.notify_all();
194 }
Jiyong Parke558ab12022-07-07 20:18:55 +0900195
196 fn set_ramdump(&self, ramdump: File) {
197 self.state.lock().unwrap().ramdump = Some(ramdump);
198 }
199
200 fn get_ramdump(&self) -> Option<File> {
201 self.state.lock().unwrap().ramdump.as_ref().and_then(|f| f.try_clone().ok())
202 }
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000203}
204
205#[derive(Debug)]
206struct VirtualMachineCallback {
207 state: Arc<Monitor<VmState>>,
208}
209
210impl Interface for VirtualMachineCallback {}
211
212impl IVirtualMachineCallback for VirtualMachineCallback {
213 fn onPayloadStarted(
214 &self,
215 _cid: i32,
216 _stream: Option<&ParcelFileDescriptor>,
217 ) -> BinderResult<()> {
218 self.state.notify_state(VirtualMachineState::STARTED);
219 Ok(())
220 }
221
222 fn onPayloadReady(&self, _cid: i32) -> BinderResult<()> {
223 self.state.notify_state(VirtualMachineState::READY);
224 Ok(())
225 }
226
227 fn onPayloadFinished(&self, _cid: i32, _exit_code: i32) -> BinderResult<()> {
228 self.state.notify_state(VirtualMachineState::FINISHED);
229 Ok(())
230 }
231
232 fn onError(&self, _cid: i32, _error_code: i32, _message: &str) -> BinderResult<()> {
233 self.state.notify_state(VirtualMachineState::FINISHED);
234 Ok(())
235 }
236
Jiyong Parke558ab12022-07-07 20:18:55 +0900237 fn onRamdump(&self, _cid: i32, ramdump: &ParcelFileDescriptor) -> BinderResult<()> {
238 let ramdump: File = ramdump.as_ref().try_clone().unwrap();
239 self.state.set_ramdump(ramdump);
240 Ok(())
241 }
242
Andrew Walbrand0ef4002022-05-16 16:14:10 +0000243 fn onDied(&self, _cid: i32, reason: AidlDeathReason) -> BinderResult<()> {
244 self.state.notify_death(reason.into());
245 Ok(())
246 }
247}