blob: ff115f3fc4ad07336f57dcdd53d9f170150f6ad8 [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,
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +010021 aidl::android::system::virtualizationservice::VirtualMachineAppConfig::DebugLevel::DebugLevel,
22 aidl::android::system::virtualizationservice::VirtualMachineConfig::VirtualMachineConfig,
Jooyung Han21e9b922021-06-26 04:14:16 +090023 aidl::android::system::virtualizationservice::VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000024 binder::ParcelFileDescriptor,
25};
Jooyung Hanfc732f52021-06-26 02:54:20 +090026
Inseob Kim6ef80972023-07-20 17:23:36 +090027use anyhow::{anyhow, bail, Context, Error, Result};
Jiyong Parkdcf17412022-02-08 15:07:23 +090028use semver::VersionReq;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000029use serde::{Deserialize, Serialize};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000030use std::convert::TryInto;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000031use std::fs::{File, OpenOptions};
32use std::io::BufReader;
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000033use std::num::NonZeroU32;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000034use std::path::{Path, PathBuf};
Jiyong Park3f9b5092024-07-10 13:38:29 +090035use uuid::Uuid;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000036
37/// Configuration for a particular VM to be started.
38#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
39pub struct VmConfig {
Seungjae Yoo62085c02022-08-12 04:44:52 +000040 /// The name of VM.
41 pub name: Option<String>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000042 /// The filename of the kernel image, if any.
43 pub kernel: Option<PathBuf>,
44 /// The filename of the initial ramdisk for the kernel, if any.
45 pub initrd: Option<PathBuf>,
46 /// Parameters to pass to the kernel. As far as the VMM and boot protocol are concerned this is
47 /// just a string, but typically it will contain multiple parameters separated by spaces.
48 pub params: Option<String>,
49 /// The bootloader to use. If this is supplied then the kernel and initrd must not be supplied;
50 /// the bootloader is instead responsibly for loading the kernel from one of the disks.
51 pub bootloader: Option<PathBuf>,
52 /// Disk images to be made available to the VM.
53 #[serde(default)]
54 pub disks: Vec<DiskImage>,
Andrew Walbranf8650422021-06-09 15:54:09 +000055 /// Whether the VM should be a protected VM.
56 #[serde(default)]
57 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000058 /// The amount of RAM to give the VM, in MiB.
59 #[serde(default)]
60 pub memory_mib: Option<NonZeroU32>,
Jeongik Cha529bfc22024-03-22 14:05:36 +090061 /// The CPU topology: either "one_cpu"(default) or "match_host"
62 pub cpu_topology: Option<String>,
Jiyong Parkdcf17412022-02-08 15:07:23 +090063 /// Version or range of versions of the virtual platform that this config is compatible with.
64 /// The format follows SemVer (https://semver.org).
65 pub platform_version: VersionReq,
Inseob Kim6ef80972023-07-20 17:23:36 +090066 /// SysFS paths of devices assigned to the VM.
67 #[serde(default)]
68 pub devices: Vec<PathBuf>,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +080069 /// The serial device for VM console input.
70 pub console_input_device: Option<String>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000071}
72
73impl VmConfig {
74 /// Ensure that the configuration has a valid combination of fields set, or return an error if
75 /// not.
76 pub fn validate(&self) -> Result<(), Error> {
77 if self.bootloader.is_none() && self.kernel.is_none() {
78 bail!("VM must have either a bootloader or a kernel image.");
79 }
80 if self.bootloader.is_some() && (self.kernel.is_some() || self.initrd.is_some()) {
81 bail!("Can't have both bootloader and kernel/initrd image.");
82 }
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000083 for disk in &self.disks {
84 if disk.image.is_none() == disk.partitions.is_empty() {
85 bail!("Exactly one of image and partitions must be specified. (Was {:?}.)", disk);
86 }
87 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +000088 Ok(())
89 }
90
91 /// Load the configuration for a VM from the given JSON file, and check that it is valid.
92 pub fn load(file: &File) -> Result<VmConfig, Error> {
93 let buffered = BufReader::new(file);
94 let config: VmConfig = serde_json::from_reader(buffered)?;
95 config.validate()?;
96 Ok(config)
97 }
98
99 /// Convert the `VmConfig` to a [`VirtualMachineConfig`] which can be passed to the Virt
100 /// Manager.
Jooyung Han21e9b922021-06-26 04:14:16 +0900101 pub fn to_parcelable(&self) -> Result<VirtualMachineRawConfig, Error> {
Andrew Walbranb15cd6e2021-07-05 16:38:07 +0000102 let memory_mib = if let Some(memory_mib) = self.memory_mib {
103 memory_mib.get().try_into().context("Invalid memory_mib")?
104 } else {
105 0
106 };
Jeongik Cha529bfc22024-03-22 14:05:36 +0900107 let cpu_topology = match self.cpu_topology.as_deref() {
108 None => CpuTopology::ONE_CPU,
109 Some("one_cpu") => CpuTopology::ONE_CPU,
110 Some("match_host") => CpuTopology::MATCH_HOST,
111 Some(cpu_topology) => bail!("Invalid cpu topology {}", cpu_topology),
112 };
Jooyung Han21e9b922021-06-26 04:14:16 +0900113 Ok(VirtualMachineRawConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000114 kernel: maybe_open_parcel_file(&self.kernel, false)?,
115 initrd: maybe_open_parcel_file(&self.initrd, false)?,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000116 params: self.params.clone(),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000117 bootloader: maybe_open_parcel_file(&self.bootloader, false)?,
118 disks: self.disks.iter().map(DiskImage::to_parcelable).collect::<Result<_, Error>>()?,
Andrew Walbrancc045902021-07-27 16:06:17 +0000119 protectedVm: self.protected,
120 memoryMib: memory_mib,
Jeongik Cha529bfc22024-03-22 14:05:36 +0900121 cpuTopology: cpu_topology,
Jiyong Parkdcf17412022-02-08 15:07:23 +0900122 platformVersion: self.platform_version.to_string(),
Inseob Kim6ef80972023-07-20 17:23:36 +0900123 devices: self
124 .devices
125 .iter()
126 .map(|x| {
127 x.to_str().map(String::from).ok_or(anyhow!("Failed to convert {x:?} to String"))
128 })
129 .collect::<Result<_>>()?,
Yi-Yo Chiang8dd32552024-05-22 19:38:16 +0800130 consoleInputDevice: self.console_input_device.clone(),
Jiyong Park032615f2022-01-10 13:55:34 +0900131 ..Default::default()
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000132 })
133 }
134}
135
Pierre-Clément Tosid3bbe1d2024-04-15 18:03:51 +0100136/// Returns the debug level of the VM from its configuration.
137pub fn get_debug_level(config: &VirtualMachineConfig) -> Option<DebugLevel> {
138 match config {
139 VirtualMachineConfig::AppConfig(config) => Some(config.debugLevel),
140 VirtualMachineConfig::RawConfig(_) => None,
141 }
142}
143
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000144/// A disk image to be made available to the VM.
145#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
146pub struct DiskImage {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000147 /// The filename of the disk image, if it already exists. Exactly one of this and `partitions`
148 /// must be specified.
149 #[serde(default)]
150 pub image: Option<PathBuf>,
151 /// A set of partitions to be assembled into a composite image.
152 #[serde(default)]
153 pub partitions: Vec<Partition>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000154 /// Whether this disk should be writable by the VM.
155 pub writable: bool,
156}
157
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000158impl DiskImage {
159 fn to_parcelable(&self) -> Result<AidlDiskImage, Error> {
160 let partitions =
Jooyung Hanfc732f52021-06-26 02:54:20 +0900161 self.partitions.iter().map(Partition::to_parcelable).collect::<Result<_>>()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000162 Ok(AidlDiskImage {
163 image: maybe_open_parcel_file(&self.image, self.writable)?,
164 writable: self.writable,
165 partitions,
166 })
167 }
168}
169
Jooyung Hanfc732f52021-06-26 02:54:20 +0900170/// A partition to be assembled into a composite image.
171#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
172pub struct Partition {
173 /// A label for the partition.
174 pub label: String,
175 /// The filename of the partition image.
Jooyung Han631d5882021-07-29 06:34:05 +0900176 pub path: PathBuf,
Jooyung Hanfc732f52021-06-26 02:54:20 +0900177 /// Whether the partition should be writable.
178 #[serde(default)]
179 pub writable: bool,
Jiyong Park3f9b5092024-07-10 13:38:29 +0900180 /// GUID of this partition.
181 #[serde(default)]
182 pub guid: Option<Uuid>,
Jooyung Hanfc732f52021-06-26 02:54:20 +0900183}
184
185impl Partition {
186 fn to_parcelable(&self) -> Result<AidlPartition> {
Jooyung Han631d5882021-07-29 06:34:05 +0900187 Ok(AidlPartition {
188 image: Some(open_parcel_file(&self.path, self.writable)?),
189 writable: self.writable,
190 label: self.label.to_owned(),
Jiyong Park3f9b5092024-07-10 13:38:29 +0900191 guid: None,
Jooyung Han631d5882021-07-29 06:34:05 +0900192 })
Jooyung Han9713bd42021-06-26 03:00:18 +0900193 }
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000194}
195
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000196/// Try to open the given file and wrap it in a [`ParcelFileDescriptor`].
Jiyong Park48b354d2021-07-15 15:04:38 +0900197pub fn open_parcel_file(filename: &Path, writable: bool) -> Result<ParcelFileDescriptor> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000198 Ok(ParcelFileDescriptor::new(
199 OpenOptions::new()
200 .read(true)
201 .write(writable)
202 .open(filename)
203 .with_context(|| format!("Failed to open {:?}", filename))?,
204 ))
205}
206
207/// If the given filename is `Some`, try to open it and wrap it in a [`ParcelFileDescriptor`].
208fn maybe_open_parcel_file(
209 filename: &Option<PathBuf>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000210 writable: bool,
Jooyung Hanfc732f52021-06-26 02:54:20 +0900211) -> Result<Option<ParcelFileDescriptor>> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000212 filename.as_deref().map(|filename| open_parcel_file(filename, writable)).transpose()
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000213}