Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 1 | // Copyright 2023, 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 | |
Alice Wang | 734801c | 2023-09-05 11:46:50 +0000 | [diff] [blame] | 15 | //! This module contains the functions to start, stop and communicate with the |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 16 | //! Service VM. |
| 17 | |
| 18 | use android_system_virtualizationservice::{ |
| 19 | aidl::android::system::virtualizationservice::{ |
| 20 | CpuTopology::CpuTopology, DiskImage::DiskImage, |
| 21 | IVirtualizationService::IVirtualizationService, Partition::Partition, |
| 22 | PartitionType::PartitionType, VirtualMachineConfig::VirtualMachineConfig, |
| 23 | VirtualMachineRawConfig::VirtualMachineRawConfig, |
| 24 | }, |
| 25 | binder::ParcelFileDescriptor, |
| 26 | }; |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 27 | use anyhow::{ensure, Context, Result}; |
| 28 | use log::{info, warn}; |
| 29 | use service_vm_comm::{Request, Response, VmType}; |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 30 | use std::fs::{File, OpenOptions}; |
Alice Wang | 977b64b | 2023-09-07 14:04:26 +0000 | [diff] [blame^] | 31 | use std::io::{self, BufRead, BufReader, BufWriter, Write}; |
| 32 | use std::os::unix::io::FromRawFd; |
Alice Wang | 17dc76e | 2023-09-06 09:43:52 +0000 | [diff] [blame] | 33 | use std::path::{Path, PathBuf}; |
Alice Wang | 977b64b | 2023-09-07 14:04:26 +0000 | [diff] [blame^] | 34 | use std::thread; |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 35 | use std::time::Duration; |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 36 | use vmclient::VmInstance; |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 37 | use vsock::{VsockListener, VsockStream, VMADDR_CID_HOST}; |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 38 | |
| 39 | const VIRT_DATA_DIR: &str = "/data/misc/apexdata/com.android.virt"; |
| 40 | const RIALTO_PATH: &str = "/apex/com.android.virt/etc/rialto.bin"; |
| 41 | const INSTANCE_IMG_NAME: &str = "service_vm_instance.img"; |
| 42 | const INSTANCE_IMG_SIZE_BYTES: i64 = 1 << 20; // 1MB |
| 43 | const MEMORY_MB: i32 = 300; |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 44 | const WRITE_BUFFER_CAPACITY: usize = 512; |
| 45 | const READ_TIMEOUT: Duration = Duration::from_secs(10); |
| 46 | const WRITE_TIMEOUT: Duration = Duration::from_secs(10); |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 47 | |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 48 | /// Service VM. |
| 49 | pub struct ServiceVm { |
| 50 | vsock_stream: VsockStream, |
| 51 | /// VmInstance will be dropped when ServiceVm goes out of scope, which will kill the VM. |
| 52 | vm: VmInstance, |
| 53 | } |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 54 | |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 55 | impl ServiceVm { |
| 56 | /// Starts the service VM and returns its instance. |
| 57 | /// The same instance image is used for different VMs. |
| 58 | /// TODO(b/278858244): Allow only one service VM running at each time. |
| 59 | pub fn start() -> Result<Self> { |
Alice Wang | 17dc76e | 2023-09-06 09:43:52 +0000 | [diff] [blame] | 60 | let vm = vm_instance()?; |
| 61 | Self::start_vm(vm, VmType::ProtectedVm) |
| 62 | } |
| 63 | |
| 64 | /// Starts the given VM instance and sets up the vsock connection with it. |
| 65 | /// Returns a `ServiceVm` instance. |
| 66 | /// This function is exposed for testing. |
| 67 | pub fn start_vm(vm: VmInstance, vm_type: VmType) -> Result<Self> { |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 68 | // Sets up the vsock server on the host. |
Alice Wang | 17dc76e | 2023-09-06 09:43:52 +0000 | [diff] [blame] | 69 | let vsock_listener = VsockListener::bind_with_cid_port(VMADDR_CID_HOST, vm_type.port())?; |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 70 | |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 71 | // Starts the service VM. |
Alice Wang | a448659 | 2023-09-05 08:25:59 +0000 | [diff] [blame] | 72 | vm.start().context("Failed to start service VM")?; |
| 73 | info!("Service VM started"); |
| 74 | |
| 75 | // Accepts the connection from the service VM. |
| 76 | // TODO(b/299427101): Introduce a timeout for the accept. |
| 77 | let (vsock_stream, peer_addr) = vsock_listener.accept().context("Failed to accept")?; |
| 78 | info!("Accepted connection {:?}", vsock_stream); |
| 79 | ensure!( |
| 80 | peer_addr.cid() == u32::try_from(vm.cid()).unwrap(), |
| 81 | "The CID of the peer address {} doesn't match the service VM CID {}", |
| 82 | peer_addr, |
| 83 | vm.cid() |
| 84 | ); |
| 85 | vsock_stream.set_read_timeout(Some(READ_TIMEOUT))?; |
| 86 | vsock_stream.set_write_timeout(Some(WRITE_TIMEOUT))?; |
| 87 | |
| 88 | Ok(Self { vsock_stream, vm }) |
| 89 | } |
| 90 | |
| 91 | /// Processes the request in the service VM. |
| 92 | pub fn process_request(&mut self, request: &Request) -> Result<Response> { |
| 93 | self.write_request(request)?; |
| 94 | self.read_response() |
| 95 | } |
| 96 | |
| 97 | /// Sends the request to the service VM. |
| 98 | fn write_request(&mut self, request: &Request) -> Result<()> { |
| 99 | let mut buffer = BufWriter::with_capacity(WRITE_BUFFER_CAPACITY, &mut self.vsock_stream); |
| 100 | ciborium::into_writer(request, &mut buffer)?; |
| 101 | buffer.flush().context("Failed to flush the buffer")?; |
| 102 | info!("Sent request to the service VM."); |
| 103 | Ok(()) |
| 104 | } |
| 105 | |
| 106 | /// Reads the response from the service VM. |
| 107 | fn read_response(&mut self) -> Result<Response> { |
| 108 | let response: Response = ciborium::from_reader(&mut self.vsock_stream) |
| 109 | .context("Failed to read the response from the service VM")?; |
| 110 | info!("Received response from the service VM."); |
| 111 | Ok(response) |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | impl Drop for ServiceVm { |
| 116 | fn drop(&mut self) { |
| 117 | // Wait till the service VM finishes releasing all the resources. |
| 118 | match self.vm.wait_for_death_with_timeout(Duration::from_secs(10)) { |
| 119 | Some(e) => info!("Exit the service VM: {e:?}"), |
| 120 | None => warn!("Timed out waiting for service VM exit"), |
| 121 | } |
| 122 | } |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 123 | } |
| 124 | |
Alice Wang | 17dc76e | 2023-09-06 09:43:52 +0000 | [diff] [blame] | 125 | fn vm_instance() -> Result<VmInstance> { |
| 126 | let virtmgr = vmclient::VirtualizationService::new().context("Failed to spawn VirtMgr")?; |
| 127 | let service = virtmgr.connect().context("Failed to connect to VirtMgr")?; |
| 128 | info!("Connected to VirtMgr for service VM"); |
| 129 | |
| 130 | let instance_img_path = Path::new(VIRT_DATA_DIR).join(INSTANCE_IMG_NAME); |
| 131 | let instance_img = instance_img(service.as_ref(), instance_img_path)?; |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 132 | let writable_partitions = vec![Partition { |
| 133 | label: "vm-instance".to_owned(), |
| 134 | image: Some(instance_img), |
| 135 | writable: true, |
| 136 | }]; |
| 137 | let rialto = File::open(RIALTO_PATH).context("Failed to open Rialto kernel binary")?; |
| 138 | let config = VirtualMachineConfig::RawConfig(VirtualMachineRawConfig { |
| 139 | name: String::from("Service VM"), |
| 140 | bootloader: Some(ParcelFileDescriptor::new(rialto)), |
| 141 | disks: vec![DiskImage { image: None, partitions: writable_partitions, writable: true }], |
| 142 | protectedVm: true, |
| 143 | memoryMib: MEMORY_MB, |
| 144 | cpuTopology: CpuTopology::ONE_CPU, |
| 145 | platformVersion: "~1.0".to_string(), |
| 146 | gdbPort: 0, // No gdb |
| 147 | ..Default::default() |
| 148 | }); |
Alice Wang | 977b64b | 2023-09-07 14:04:26 +0000 | [diff] [blame^] | 149 | let console_out = Some(android_log_fd()?); |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 150 | let console_in = None; |
Alice Wang | 977b64b | 2023-09-07 14:04:26 +0000 | [diff] [blame^] | 151 | let log = Some(android_log_fd()?); |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 152 | let callback = None; |
Alice Wang | 17dc76e | 2023-09-06 09:43:52 +0000 | [diff] [blame] | 153 | VmInstance::create(service.as_ref(), &config, console_out, console_in, log, callback) |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 154 | .context("Failed to create service VM") |
| 155 | } |
| 156 | |
Alice Wang | 17dc76e | 2023-09-06 09:43:52 +0000 | [diff] [blame] | 157 | /// Returns the file descriptor of the instance image at the given path. |
| 158 | /// This function is only exposed for testing. |
| 159 | pub fn instance_img( |
| 160 | service: &dyn IVirtualizationService, |
| 161 | instance_img_path: PathBuf, |
| 162 | ) -> Result<ParcelFileDescriptor> { |
Alice Wang | c206b9b | 2023-08-28 14:13:51 +0000 | [diff] [blame] | 163 | if instance_img_path.exists() { |
| 164 | // TODO(b/298174584): Try to recover if the service VM is triggered by rkpd. |
| 165 | return Ok(OpenOptions::new() |
| 166 | .read(true) |
| 167 | .write(true) |
| 168 | .open(instance_img_path) |
| 169 | .map(ParcelFileDescriptor::new)?); |
| 170 | } |
| 171 | let instance_img = OpenOptions::new() |
| 172 | .create(true) |
| 173 | .read(true) |
| 174 | .write(true) |
| 175 | .open(instance_img_path) |
| 176 | .map(ParcelFileDescriptor::new)?; |
| 177 | service.initializeWritablePartition( |
| 178 | &instance_img, |
| 179 | INSTANCE_IMG_SIZE_BYTES, |
| 180 | PartitionType::ANDROID_VM_INSTANCE, |
| 181 | )?; |
| 182 | Ok(instance_img) |
| 183 | } |
Alice Wang | 977b64b | 2023-09-07 14:04:26 +0000 | [diff] [blame^] | 184 | |
| 185 | /// This function is only exposed for testing. |
| 186 | pub fn android_log_fd() -> io::Result<File> { |
| 187 | let (reader_fd, writer_fd) = nix::unistd::pipe()?; |
| 188 | |
| 189 | // SAFETY: These are new FDs with no previous owner. |
| 190 | let reader = unsafe { File::from_raw_fd(reader_fd) }; |
| 191 | // SAFETY: These are new FDs with no previous owner. |
| 192 | let writer = unsafe { File::from_raw_fd(writer_fd) }; |
| 193 | |
| 194 | thread::spawn(|| { |
| 195 | for line in BufReader::new(reader).lines() { |
| 196 | match line { |
| 197 | Ok(l) => info!("{}", l), |
| 198 | Err(e) => { |
| 199 | warn!("Failed to read line: {e:?}"); |
| 200 | break; |
| 201 | } |
| 202 | } |
| 203 | } |
| 204 | }); |
| 205 | Ok(writer) |
| 206 | } |