blob: 8357f9989defef0c62abaf071a6ec6d5ab6de8eb [file] [log] [blame]
Andrew Walbran3a5a9212021-05-04 17:09:08 +00001// Copyright 2021, 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
Jooyung Hanfc732f52021-06-26 02:54:20 +090015//! Struct for VM configuration with JSON (de)serialization and AIDL parcelables
Andrew Walbran3a5a9212021-05-04 17:09:08 +000016
Andrew Walbranf6bf6862021-05-21 12:41:13 +000017use android_system_virtualizationservice::{
Jaewan Kimf43372b2024-12-13 18:33:58 +090018 aidl::android::system::virtualizationservice::AssignedDevices::AssignedDevices,
Jeongik Cha529bfc22024-03-22 14:05:36 +090019 aidl::android::system::virtualizationservice::CpuTopology::CpuTopology,
Andrew Walbranf6bf6862021-05-21 12:41:13 +000020 aidl::android::system::virtualizationservice::DiskImage::DiskImage as AidlDiskImage,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000021 aidl::android::system::virtualizationservice::Partition::Partition as AidlPartition,
Elie Kheirallah29d72912024-08-07 20:17:26 +000022 aidl::android::system::virtualizationservice::UsbConfig::UsbConfig as AidlUsbConfig,
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010023 aidl::android::system::virtualizationservice::VirtualMachineAppConfig::DebugLevel::DebugLevel,
24 aidl::android::system::virtualizationservice::VirtualMachineConfig::VirtualMachineConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090025 aidl::android::system::virtualizationservice::VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000026 binder::ParcelFileDescriptor,
27};
Jooyung Hanfc732f52021-06-26 02:54:20 +090028
Inseob Kim6ef80972023-07-20 17:23:36 +090029use anyhow::{anyhow, bail, Context, Error, Result};
Jiyong Parkdcf17412022-02-08 15:07:23 +090030use semver::VersionReq;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000031use serde::{Deserialize, Serialize};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000032use std::convert::TryInto;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000033use std::fs::{File, OpenOptions};
34use std::io::BufReader;
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000035use std::num::NonZeroU32;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000036use std::path::{Path, PathBuf};
Jiyong Park3f9b5092024-07-10 13:38:29 +090037use uuid::Uuid;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000038
39/// Configuration for a particular VM to be started.
40#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
41pub struct VmConfig {
Seungjae Yoo62085c02022-08-12 04:44:52 +000042 /// The name of VM.
43 pub name: Option<String>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000044 /// The filename of the kernel image, if any.
45 pub kernel: Option<PathBuf>,
46 /// The filename of the initial ramdisk for the kernel, if any.
47 pub initrd: Option<PathBuf>,
48 /// Parameters to pass to the kernel. As far as the VMM and boot protocol are concerned this is
49 /// just a string, but typically it will contain multiple parameters separated by spaces.
50 pub params: Option<String>,
51 /// The bootloader to use. If this is supplied then the kernel and initrd must not be supplied;
52 /// the bootloader is instead responsibly for loading the kernel from one of the disks.
53 pub bootloader: Option<PathBuf>,
54 /// Disk images to be made available to the VM.
55 #[serde(default)]
56 pub disks: Vec<DiskImage>,
Andrew Walbranf8650422021-06-09 15:54:09 +000057 /// Whether the VM should be a protected VM.
58 #[serde(default)]
59 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000060 /// The amount of RAM to give the VM, in MiB.
61 #[serde(default)]
62 pub memory_mib: Option<NonZeroU32>,
Jeongik Cha529bfc22024-03-22 14:05:36 +090063 /// The CPU topology: either "one_cpu"(default) or "match_host"
64 pub cpu_topology: Option<String>,
Jiyong Parkdcf17412022-02-08 15:07:23 +090065 /// Version or range of versions of the virtual platform that this config is compatible with.
66 /// The format follows SemVer (https://semver.org).
67 pub platform_version: VersionReq,
Inseob Kim6ef80972023-07-20 17:23:36 +090068 /// SysFS paths of devices assigned to the VM.
69 #[serde(default)]
70 pub devices: Vec<PathBuf>,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +080071 /// The serial device for VM console input.
72 pub console_input_device: Option<String>,
Elie Kheirallah29d72912024-08-07 20:17:26 +000073 /// The USB config of the VM.
74 pub usb_config: Option<UsbConfig>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000075}
76
77impl VmConfig {
78 /// Ensure that the configuration has a valid combination of fields set, or return an error if
79 /// not.
80 pub fn validate(&self) -> Result<(), Error> {
81 if self.bootloader.is_none() && self.kernel.is_none() {
82 bail!("VM must have either a bootloader or a kernel image.");
83 }
84 if self.bootloader.is_some() && (self.kernel.is_some() || self.initrd.is_some()) {
85 bail!("Can't have both bootloader and kernel/initrd image.");
86 }
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000087 for disk in &self.disks {
88 if disk.image.is_none() == disk.partitions.is_empty() {
89 bail!("Exactly one of image and partitions must be specified. (Was {:?}.)", disk);
90 }
91 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +000092 Ok(())
93 }
94
95 /// Load the configuration for a VM from the given JSON file, and check that it is valid.
96 pub fn load(file: &File) -> Result<VmConfig, Error> {
97 let buffered = BufReader::new(file);
98 let config: VmConfig = serde_json::from_reader(buffered)?;
99 config.validate()?;
100 Ok(config)
101 }
102
103 /// Convert the `VmConfig` to a [`VirtualMachineConfig`] which can be passed to the Virt
104 /// Manager.
Jooyung Han21e9b922021-06-26 04:14:16 +0900105 pub fn to_parcelable(&self) -> Result<VirtualMachineRawConfig, Error> {
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000106 let memory_mib = if let Some(memory_mib) = self.memory_mib {
107 memory_mib.get().try_into().context("Invalid memory_mib")?
108 } else {
109 0
110 };
Jeongik Cha529bfc22024-03-22 14:05:36 +0900111 let cpu_topology = match self.cpu_topology.as_deref() {
112 None => CpuTopology::ONE_CPU,
113 Some("one_cpu") => CpuTopology::ONE_CPU,
114 Some("match_host") => CpuTopology::MATCH_HOST,
115 Some(cpu_topology) => bail!("Invalid cpu topology {}", cpu_topology),
116 };
Elie Kheirallah29d72912024-08-07 20:17:26 +0000117 let usb_config = self.usb_config.clone().map(|x| x.to_parcelable()).transpose()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900118 Ok(VirtualMachineRawConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000119 kernel: maybe_open_parcel_file(&self.kernel, false)?,
120 initrd: maybe_open_parcel_file(&self.initrd, false)?,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000121 params: self.params.clone(),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000122 bootloader: maybe_open_parcel_file(&self.bootloader, false)?,
123 disks: self.disks.iter().map(DiskImage::to_parcelable).collect::<Result<_, Error>>()?,
Andrew Walbrancc045902021-07-27 16:06:17 +0000124 protectedVm: self.protected,
125 memoryMib: memory_mib,
Jeongik Cha529bfc22024-03-22 14:05:36 +0900126 cpuTopology: cpu_topology,
Jiyong Parkdcf17412022-02-08 15:07:23 +0900127 platformVersion: self.platform_version.to_string(),
Jaewan Kimf43372b2024-12-13 18:33:58 +0900128 devices: AssignedDevices::Devices(
129 self.devices
130 .iter()
131 .map(|x| {
132 x.to_str()
133 .map(String::from)
134 .ok_or(anyhow!("Failed to convert {x:?} to String"))
135 })
136 .collect::<Result<_>>()?,
137 ),
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800138 consoleInputDevice: self.console_input_device.clone(),
Elie Kheirallah29d72912024-08-07 20:17:26 +0000139 usbConfig: usb_config,
Frederick Maylecc4e2d72024-12-06 16:54:40 -0800140 balloon: true,
Jiyong Park032615f2022-01-10 13:55:34 +0900141 ..Default::default()
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000142 })
143 }
144}
145
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +0100146/// Returns the debug level of the VM from its configuration.
147pub fn get_debug_level(config: &VirtualMachineConfig) -> Option<DebugLevel> {
148 match config {
149 VirtualMachineConfig::AppConfig(config) => Some(config.debugLevel),
150 VirtualMachineConfig::RawConfig(_) => None,
151 }
152}
153
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000154/// A disk image to be made available to the VM.
155#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
156pub struct DiskImage {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000157 /// The filename of the disk image, if it already exists. Exactly one of this and `partitions`
158 /// must be specified.
159 #[serde(default)]
160 pub image: Option<PathBuf>,
161 /// A set of partitions to be assembled into a composite image.
162 #[serde(default)]
163 pub partitions: Vec<Partition>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000164 /// Whether this disk should be writable by the VM.
165 pub writable: bool,
166}
167
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000168impl DiskImage {
169 fn to_parcelable(&self) -> Result<AidlDiskImage, Error> {
170 let partitions =
Jooyung Hanfc732f52021-06-26 02:54:20 +0900171 self.partitions.iter().map(Partition::to_parcelable).collect::<Result<_>>()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000172 Ok(AidlDiskImage {
173 image: maybe_open_parcel_file(&self.image, self.writable)?,
174 writable: self.writable,
175 partitions,
176 })
177 }
178}
179
Jooyung Hanfc732f52021-06-26 02:54:20 +0900180/// A partition to be assembled into a composite image.
181#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
182pub struct Partition {
183 /// A label for the partition.
184 pub label: String,
185 /// The filename of the partition image.
Jooyung Han631d5882021-07-29 06:34:05 +0900186 pub path: PathBuf,
Jooyung Hanfc732f52021-06-26 02:54:20 +0900187 /// Whether the partition should be writable.
188 #[serde(default)]
189 pub writable: bool,
Jiyong Park3f9b5092024-07-10 13:38:29 +0900190 /// GUID of this partition.
191 #[serde(default)]
192 pub guid: Option<Uuid>,
Jooyung Hanfc732f52021-06-26 02:54:20 +0900193}
194
195impl Partition {
196 fn to_parcelable(&self) -> Result<AidlPartition> {
Jooyung Han631d5882021-07-29 06:34:05 +0900197 Ok(AidlPartition {
198 image: Some(open_parcel_file(&self.path, self.writable)?),
199 writable: self.writable,
200 label: self.label.to_owned(),
Jiyong Park3f9b5092024-07-10 13:38:29 +0900201 guid: None,
Jooyung Han631d5882021-07-29 06:34:05 +0900202 })
Jooyung Han9713bd42021-06-26 03:00:18 +0900203 }
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000204}
205
Elie Kheirallah29d72912024-08-07 20:17:26 +0000206/// USB controller and available USB devices
207#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
208pub struct UsbConfig {
209 /// Enable USB controller
210 pub controller: bool,
211}
212
213impl UsbConfig {
214 fn to_parcelable(&self) -> Result<AidlUsbConfig> {
215 Ok(AidlUsbConfig { controller: self.controller })
216 }
217}
218
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000219/// Try to open the given file and wrap it in a [`ParcelFileDescriptor`].
Jiyong Park48b354d2021-07-15 15:04:38 +0900220pub fn open_parcel_file(filename: &Path, writable: bool) -> Result<ParcelFileDescriptor> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000221 Ok(ParcelFileDescriptor::new(
222 OpenOptions::new()
223 .read(true)
224 .write(writable)
225 .open(filename)
226 .with_context(|| format!("Failed to open {:?}", filename))?,
227 ))
228}
229
230/// If the given filename is `Some`, try to open it and wrap it in a [`ParcelFileDescriptor`].
231fn maybe_open_parcel_file(
232 filename: &Option<PathBuf>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000233 writable: bool,
Jooyung Hanfc732f52021-06-26 02:54:20 +0900234) -> Result<Option<ParcelFileDescriptor>> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000235 filename.as_deref().map(|filename| open_parcel_file(filename, writable)).transpose()
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000236}