blob: 859ca773ab775cc9220bb62a37c1e46e6da1631b [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::{
Elie Kheirallahb4b2f242025-01-23 03:38:07 +000018 aidl::android::system::virtualizationservice::{
19 AssignedDevices::AssignedDevices, CpuOptions::CpuOptions,
20 CpuOptions::CpuTopology::CpuTopology, DiskImage::DiskImage as AidlDiskImage,
21 Partition::Partition as AidlPartition, UsbConfig::UsbConfig as AidlUsbConfig,
22 VirtualMachineAppConfig::DebugLevel::DebugLevel,
23 VirtualMachineConfig::VirtualMachineConfig,
24 VirtualMachineRawConfig::VirtualMachineRawConfig,
25 },
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() {
Elie Kheirallahb4b2f242025-01-23 03:38:07 +0000112 None => CpuTopology::CpuCount(1),
113 Some("one_cpu") => CpuTopology::CpuCount(1),
114 Some("match_host") => CpuTopology::MatchHost(true),
Jeongik Cha529bfc22024-03-22 14:05:36 +0900115 Some(cpu_topology) => bail!("Invalid cpu topology {}", cpu_topology),
116 };
Elie Kheirallahb4b2f242025-01-23 03:38:07 +0000117 let cpu_options = CpuOptions { cpuTopology: cpu_topology };
Elie Kheirallah29d72912024-08-07 20:17:26 +0000118 let usb_config = self.usb_config.clone().map(|x| x.to_parcelable()).transpose()?;
Jooyung Han21e9b922021-06-26 04:14:16 +0900119 Ok(VirtualMachineRawConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000120 kernel: maybe_open_parcel_file(&self.kernel, false)?,
121 initrd: maybe_open_parcel_file(&self.initrd, false)?,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000122 params: self.params.clone(),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000123 bootloader: maybe_open_parcel_file(&self.bootloader, false)?,
124 disks: self.disks.iter().map(DiskImage::to_parcelable).collect::<Result<_, Error>>()?,
Andrew Walbrancc045902021-07-27 16:06:17 +0000125 protectedVm: self.protected,
126 memoryMib: memory_mib,
Elie Kheirallahb4b2f242025-01-23 03:38:07 +0000127 cpuOptions: cpu_options,
Jiyong Parkdcf17412022-02-08 15:07:23 +0900128 platformVersion: self.platform_version.to_string(),
Jaewan Kimf43372b2024-12-13 18:33:58 +0900129 devices: AssignedDevices::Devices(
130 self.devices
131 .iter()
132 .map(|x| {
133 x.to_str()
134 .map(String::from)
135 .ok_or(anyhow!("Failed to convert {x:?} to String"))
136 })
137 .collect::<Result<_>>()?,
138 ),
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800139 consoleInputDevice: self.console_input_device.clone(),
Elie Kheirallah29d72912024-08-07 20:17:26 +0000140 usbConfig: usb_config,
Frederick Maylecc4e2d72024-12-06 16:54:40 -0800141 balloon: true,
Jiyong Park032615f2022-01-10 13:55:34 +0900142 ..Default::default()
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000143 })
144 }
145}
146
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +0100147/// Returns the debug level of the VM from its configuration.
148pub fn get_debug_level(config: &VirtualMachineConfig) -> Option<DebugLevel> {
149 match config {
150 VirtualMachineConfig::AppConfig(config) => Some(config.debugLevel),
151 VirtualMachineConfig::RawConfig(_) => None,
152 }
153}
154
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000155/// A disk image to be made available to the VM.
156#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
157pub struct DiskImage {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000158 /// The filename of the disk image, if it already exists. Exactly one of this and `partitions`
159 /// must be specified.
160 #[serde(default)]
161 pub image: Option<PathBuf>,
162 /// A set of partitions to be assembled into a composite image.
163 #[serde(default)]
164 pub partitions: Vec<Partition>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000165 /// Whether this disk should be writable by the VM.
166 pub writable: bool,
167}
168
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000169impl DiskImage {
170 fn to_parcelable(&self) -> Result<AidlDiskImage, Error> {
171 let partitions =
Jooyung Hanfc732f52021-06-26 02:54:20 +0900172 self.partitions.iter().map(Partition::to_parcelable).collect::<Result<_>>()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000173 Ok(AidlDiskImage {
174 image: maybe_open_parcel_file(&self.image, self.writable)?,
175 writable: self.writable,
176 partitions,
177 })
178 }
179}
180
Jooyung Hanfc732f52021-06-26 02:54:20 +0900181/// A partition to be assembled into a composite image.
182#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
183pub struct Partition {
184 /// A label for the partition.
185 pub label: String,
186 /// The filename of the partition image.
Jooyung Han631d5882021-07-29 06:34:05 +0900187 pub path: PathBuf,
Jooyung Hanfc732f52021-06-26 02:54:20 +0900188 /// Whether the partition should be writable.
189 #[serde(default)]
190 pub writable: bool,
Jiyong Park3f9b5092024-07-10 13:38:29 +0900191 /// GUID of this partition.
192 #[serde(default)]
193 pub guid: Option<Uuid>,
Jooyung Hanfc732f52021-06-26 02:54:20 +0900194}
195
196impl Partition {
197 fn to_parcelable(&self) -> Result<AidlPartition> {
Jooyung Han631d5882021-07-29 06:34:05 +0900198 Ok(AidlPartition {
199 image: Some(open_parcel_file(&self.path, self.writable)?),
200 writable: self.writable,
201 label: self.label.to_owned(),
Jiyong Park3f9b5092024-07-10 13:38:29 +0900202 guid: None,
Jooyung Han631d5882021-07-29 06:34:05 +0900203 })
Jooyung Han9713bd42021-06-26 03:00:18 +0900204 }
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000205}
206
Elie Kheirallah29d72912024-08-07 20:17:26 +0000207/// USB controller and available USB devices
208#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
209pub struct UsbConfig {
210 /// Enable USB controller
211 pub controller: bool,
212}
213
214impl UsbConfig {
215 fn to_parcelable(&self) -> Result<AidlUsbConfig> {
216 Ok(AidlUsbConfig { controller: self.controller })
217 }
218}
219
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000220/// Try to open the given file and wrap it in a [`ParcelFileDescriptor`].
Jiyong Park48b354d2021-07-15 15:04:38 +0900221pub fn open_parcel_file(filename: &Path, writable: bool) -> Result<ParcelFileDescriptor> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000222 Ok(ParcelFileDescriptor::new(
223 OpenOptions::new()
224 .read(true)
225 .write(writable)
226 .open(filename)
227 .with_context(|| format!("Failed to open {:?}", filename))?,
228 ))
229}
230
231/// If the given filename is `Some`, try to open it and wrap it in a [`ParcelFileDescriptor`].
232fn maybe_open_parcel_file(
233 filename: &Option<PathBuf>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000234 writable: bool,
Jooyung Hanfc732f52021-06-26 02:54:20 +0900235) -> Result<Option<ParcelFileDescriptor>> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000236 filename.as_deref().map(|filename| open_parcel_file(filename, writable)).transpose()
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000237}