blob: 907e0d31fa93d4c2a45e00dc8df2d22ea5ea3409 [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::{
Jeongik Cha529bfc22024-03-22 14:05:36 +090018 aidl::android::system::virtualizationservice::CpuTopology::CpuTopology,
Andrew Walbranf6bf6862021-05-21 12:41:13 +000019 aidl::android::system::virtualizationservice::DiskImage::DiskImage as AidlDiskImage,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000020 aidl::android::system::virtualizationservice::Partition::Partition as AidlPartition,
Jooyung Han21e9b922021-06-26 04:14:16 +090021 aidl::android::system::virtualizationservice::VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000022 binder::ParcelFileDescriptor,
23};
Jooyung Hanfc732f52021-06-26 02:54:20 +090024
Inseob Kim6ef80972023-07-20 17:23:36 +090025use anyhow::{anyhow, bail, Context, Error, Result};
Jiyong Parkdcf17412022-02-08 15:07:23 +090026use semver::VersionReq;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000027use serde::{Deserialize, Serialize};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000028use std::convert::TryInto;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000029use std::fs::{File, OpenOptions};
30use std::io::BufReader;
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000031use std::num::NonZeroU32;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000032use std::path::{Path, PathBuf};
33
34/// Configuration for a particular VM to be started.
35#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
36pub struct VmConfig {
Seungjae Yoo62085c02022-08-12 04:44:52 +000037 /// The name of VM.
38 pub name: Option<String>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000039 /// The filename of the kernel image, if any.
40 pub kernel: Option<PathBuf>,
41 /// The filename of the initial ramdisk for the kernel, if any.
42 pub initrd: Option<PathBuf>,
43 /// Parameters to pass to the kernel. As far as the VMM and boot protocol are concerned this is
44 /// just a string, but typically it will contain multiple parameters separated by spaces.
45 pub params: Option<String>,
46 /// The bootloader to use. If this is supplied then the kernel and initrd must not be supplied;
47 /// the bootloader is instead responsibly for loading the kernel from one of the disks.
48 pub bootloader: Option<PathBuf>,
49 /// Disk images to be made available to the VM.
50 #[serde(default)]
51 pub disks: Vec<DiskImage>,
Andrew Walbranf8650422021-06-09 15:54:09 +000052 /// Whether the VM should be a protected VM.
53 #[serde(default)]
54 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000055 /// The amount of RAM to give the VM, in MiB.
56 #[serde(default)]
57 pub memory_mib: Option<NonZeroU32>,
Jeongik Cha529bfc22024-03-22 14:05:36 +090058 /// The CPU topology: either "one_cpu"(default) or "match_host"
59 pub cpu_topology: Option<String>,
Jiyong Parkdcf17412022-02-08 15:07:23 +090060 /// Version or range of versions of the virtual platform that this config is compatible with.
61 /// The format follows SemVer (https://semver.org).
62 pub platform_version: VersionReq,
Inseob Kim6ef80972023-07-20 17:23:36 +090063 /// SysFS paths of devices assigned to the VM.
64 #[serde(default)]
65 pub devices: Vec<PathBuf>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000066}
67
68impl VmConfig {
69 /// Ensure that the configuration has a valid combination of fields set, or return an error if
70 /// not.
71 pub fn validate(&self) -> Result<(), Error> {
72 if self.bootloader.is_none() && self.kernel.is_none() {
73 bail!("VM must have either a bootloader or a kernel image.");
74 }
75 if self.bootloader.is_some() && (self.kernel.is_some() || self.initrd.is_some()) {
76 bail!("Can't have both bootloader and kernel/initrd image.");
77 }
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000078 for disk in &self.disks {
79 if disk.image.is_none() == disk.partitions.is_empty() {
80 bail!("Exactly one of image and partitions must be specified. (Was {:?}.)", disk);
81 }
82 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +000083 Ok(())
84 }
85
86 /// Load the configuration for a VM from the given JSON file, and check that it is valid.
87 pub fn load(file: &File) -> Result<VmConfig, Error> {
88 let buffered = BufReader::new(file);
89 let config: VmConfig = serde_json::from_reader(buffered)?;
90 config.validate()?;
91 Ok(config)
92 }
93
94 /// Convert the `VmConfig` to a [`VirtualMachineConfig`] which can be passed to the Virt
95 /// Manager.
Jooyung Han21e9b922021-06-26 04:14:16 +090096 pub fn to_parcelable(&self) -> Result<VirtualMachineRawConfig, Error> {
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000097 let memory_mib = if let Some(memory_mib) = self.memory_mib {
98 memory_mib.get().try_into().context("Invalid memory_mib")?
99 } else {
100 0
101 };
Jeongik Cha529bfc22024-03-22 14:05:36 +0900102 let cpu_topology = match self.cpu_topology.as_deref() {
103 None => CpuTopology::ONE_CPU,
104 Some("one_cpu") => CpuTopology::ONE_CPU,
105 Some("match_host") => CpuTopology::MATCH_HOST,
106 Some(cpu_topology) => bail!("Invalid cpu topology {}", cpu_topology),
107 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900108 Ok(VirtualMachineRawConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000109 kernel: maybe_open_parcel_file(&self.kernel, false)?,
110 initrd: maybe_open_parcel_file(&self.initrd, false)?,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000111 params: self.params.clone(),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000112 bootloader: maybe_open_parcel_file(&self.bootloader, false)?,
113 disks: self.disks.iter().map(DiskImage::to_parcelable).collect::<Result<_, Error>>()?,
Andrew Walbrancc045902021-07-27 16:06:17 +0000114 protectedVm: self.protected,
115 memoryMib: memory_mib,
Jeongik Cha529bfc22024-03-22 14:05:36 +0900116 cpuTopology: cpu_topology,
Jiyong Parkdcf17412022-02-08 15:07:23 +0900117 platformVersion: self.platform_version.to_string(),
Inseob Kim6ef80972023-07-20 17:23:36 +0900118 devices: self
119 .devices
120 .iter()
121 .map(|x| {
122 x.to_str().map(String::from).ok_or(anyhow!("Failed to convert {x:?} to String"))
123 })
124 .collect::<Result<_>>()?,
Jiyong Park032615f2022-01-10 13:55:34 +0900125 ..Default::default()
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000126 })
127 }
128}
129
130/// A disk image to be made available to the VM.
131#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
132pub struct DiskImage {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000133 /// The filename of the disk image, if it already exists. Exactly one of this and `partitions`
134 /// must be specified.
135 #[serde(default)]
136 pub image: Option<PathBuf>,
137 /// A set of partitions to be assembled into a composite image.
138 #[serde(default)]
139 pub partitions: Vec<Partition>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000140 /// Whether this disk should be writable by the VM.
141 pub writable: bool,
142}
143
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000144impl DiskImage {
145 fn to_parcelable(&self) -> Result<AidlDiskImage, Error> {
146 let partitions =
Jooyung Hanfc732f52021-06-26 02:54:20 +0900147 self.partitions.iter().map(Partition::to_parcelable).collect::<Result<_>>()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000148 Ok(AidlDiskImage {
149 image: maybe_open_parcel_file(&self.image, self.writable)?,
150 writable: self.writable,
151 partitions,
152 })
153 }
154}
155
Jooyung Hanfc732f52021-06-26 02:54:20 +0900156/// A partition to be assembled into a composite image.
157#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
158pub struct Partition {
159 /// A label for the partition.
160 pub label: String,
161 /// The filename of the partition image.
Jooyung Han631d5882021-07-29 06:34:05 +0900162 pub path: PathBuf,
Jooyung Hanfc732f52021-06-26 02:54:20 +0900163 /// Whether the partition should be writable.
164 #[serde(default)]
165 pub writable: bool,
166}
167
168impl Partition {
169 fn to_parcelable(&self) -> Result<AidlPartition> {
Jooyung Han631d5882021-07-29 06:34:05 +0900170 Ok(AidlPartition {
171 image: Some(open_parcel_file(&self.path, self.writable)?),
172 writable: self.writable,
173 label: self.label.to_owned(),
174 })
Jooyung Han9713bd42021-06-26 03:00:18 +0900175 }
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000176}
177
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000178/// Try to open the given file and wrap it in a [`ParcelFileDescriptor`].
Jiyong Park48b354d2021-07-15 15:04:38 +0900179pub fn open_parcel_file(filename: &Path, writable: bool) -> Result<ParcelFileDescriptor> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000180 Ok(ParcelFileDescriptor::new(
181 OpenOptions::new()
182 .read(true)
183 .write(writable)
184 .open(filename)
185 .with_context(|| format!("Failed to open {:?}", filename))?,
186 ))
187}
188
189/// If the given filename is `Some`, try to open it and wrap it in a [`ParcelFileDescriptor`].
190fn maybe_open_parcel_file(
191 filename: &Option<PathBuf>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000192 writable: bool,
Jooyung Hanfc732f52021-06-26 02:54:20 +0900193) -> Result<Option<ParcelFileDescriptor>> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000194 filename.as_deref().map(|filename| open_parcel_file(filename, writable)).transpose()
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000195}