blob: 50f3c8ec5e3400b4c3f5a8df5aaabd055ef4a9b6 [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::{
18 aidl::android::system::virtualizationservice::DiskImage::DiskImage as AidlDiskImage,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000019 aidl::android::system::virtualizationservice::Partition::Partition as AidlPartition,
Jooyung Han21e9b922021-06-26 04:14:16 +090020 aidl::android::system::virtualizationservice::VirtualMachineRawConfig::VirtualMachineRawConfig,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000021 binder::ParcelFileDescriptor,
22};
Jooyung Hanfc732f52021-06-26 02:54:20 +090023
Inseob Kim6ef80972023-07-20 17:23:36 +090024use anyhow::{anyhow, bail, Context, Error, Result};
Jiyong Parkdcf17412022-02-08 15:07:23 +090025use semver::VersionReq;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000026use serde::{Deserialize, Serialize};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000027use std::convert::TryInto;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000028use std::fs::{File, OpenOptions};
29use std::io::BufReader;
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000030use std::num::NonZeroU32;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000031use std::path::{Path, PathBuf};
32
33/// Configuration for a particular VM to be started.
34#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
35pub struct VmConfig {
Seungjae Yoo62085c02022-08-12 04:44:52 +000036 /// The name of VM.
37 pub name: Option<String>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000038 /// The filename of the kernel image, if any.
39 pub kernel: Option<PathBuf>,
40 /// The filename of the initial ramdisk for the kernel, if any.
41 pub initrd: Option<PathBuf>,
42 /// Parameters to pass to the kernel. As far as the VMM and boot protocol are concerned this is
43 /// just a string, but typically it will contain multiple parameters separated by spaces.
44 pub params: Option<String>,
45 /// The bootloader to use. If this is supplied then the kernel and initrd must not be supplied;
46 /// the bootloader is instead responsibly for loading the kernel from one of the disks.
47 pub bootloader: Option<PathBuf>,
48 /// Disk images to be made available to the VM.
49 #[serde(default)]
50 pub disks: Vec<DiskImage>,
Andrew Walbranf8650422021-06-09 15:54:09 +000051 /// Whether the VM should be a protected VM.
52 #[serde(default)]
53 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000054 /// The amount of RAM to give the VM, in MiB.
55 #[serde(default)]
56 pub memory_mib: Option<NonZeroU32>,
Jiyong Parkdcf17412022-02-08 15:07:23 +090057 /// Version or range of versions of the virtual platform that this config is compatible with.
58 /// The format follows SemVer (https://semver.org).
59 pub platform_version: VersionReq,
Inseob Kim6ef80972023-07-20 17:23:36 +090060 /// SysFS paths of devices assigned to the VM.
61 #[serde(default)]
62 pub devices: Vec<PathBuf>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000063}
64
65impl VmConfig {
66 /// Ensure that the configuration has a valid combination of fields set, or return an error if
67 /// not.
68 pub fn validate(&self) -> Result<(), Error> {
69 if self.bootloader.is_none() && self.kernel.is_none() {
70 bail!("VM must have either a bootloader or a kernel image.");
71 }
72 if self.bootloader.is_some() && (self.kernel.is_some() || self.initrd.is_some()) {
73 bail!("Can't have both bootloader and kernel/initrd image.");
74 }
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000075 for disk in &self.disks {
76 if disk.image.is_none() == disk.partitions.is_empty() {
77 bail!("Exactly one of image and partitions must be specified. (Was {:?}.)", disk);
78 }
79 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +000080 Ok(())
81 }
82
83 /// Load the configuration for a VM from the given JSON file, and check that it is valid.
84 pub fn load(file: &File) -> Result<VmConfig, Error> {
85 let buffered = BufReader::new(file);
86 let config: VmConfig = serde_json::from_reader(buffered)?;
87 config.validate()?;
88 Ok(config)
89 }
90
91 /// Convert the `VmConfig` to a [`VirtualMachineConfig`] which can be passed to the Virt
92 /// Manager.
Jooyung Han21e9b922021-06-26 04:14:16 +090093 pub fn to_parcelable(&self) -> Result<VirtualMachineRawConfig, Error> {
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000094 let memory_mib = if let Some(memory_mib) = self.memory_mib {
95 memory_mib.get().try_into().context("Invalid memory_mib")?
96 } else {
97 0
98 };
Seungjae Yoo62085c02022-08-12 04:44:52 +000099
Jooyung Han21e9b922021-06-26 04:14:16 +0900100 Ok(VirtualMachineRawConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000101 kernel: maybe_open_parcel_file(&self.kernel, false)?,
102 initrd: maybe_open_parcel_file(&self.initrd, false)?,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000103 params: self.params.clone(),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000104 bootloader: maybe_open_parcel_file(&self.bootloader, false)?,
105 disks: self.disks.iter().map(DiskImage::to_parcelable).collect::<Result<_, Error>>()?,
Andrew Walbrancc045902021-07-27 16:06:17 +0000106 protectedVm: self.protected,
107 memoryMib: memory_mib,
Jiyong Parkdcf17412022-02-08 15:07:23 +0900108 platformVersion: self.platform_version.to_string(),
Inseob Kim6ef80972023-07-20 17:23:36 +0900109 devices: self
110 .devices
111 .iter()
112 .map(|x| {
113 x.to_str().map(String::from).ok_or(anyhow!("Failed to convert {x:?} to String"))
114 })
115 .collect::<Result<_>>()?,
Jiyong Park032615f2022-01-10 13:55:34 +0900116 ..Default::default()
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000117 })
118 }
119}
120
121/// A disk image to be made available to the VM.
122#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
123pub struct DiskImage {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000124 /// The filename of the disk image, if it already exists. Exactly one of this and `partitions`
125 /// must be specified.
126 #[serde(default)]
127 pub image: Option<PathBuf>,
128 /// A set of partitions to be assembled into a composite image.
129 #[serde(default)]
130 pub partitions: Vec<Partition>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000131 /// Whether this disk should be writable by the VM.
132 pub writable: bool,
133}
134
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000135impl DiskImage {
136 fn to_parcelable(&self) -> Result<AidlDiskImage, Error> {
137 let partitions =
Jooyung Hanfc732f52021-06-26 02:54:20 +0900138 self.partitions.iter().map(Partition::to_parcelable).collect::<Result<_>>()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000139 Ok(AidlDiskImage {
140 image: maybe_open_parcel_file(&self.image, self.writable)?,
141 writable: self.writable,
142 partitions,
143 })
144 }
145}
146
Jooyung Hanfc732f52021-06-26 02:54:20 +0900147/// A partition to be assembled into a composite image.
148#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
149pub struct Partition {
150 /// A label for the partition.
151 pub label: String,
152 /// The filename of the partition image.
Jooyung Han631d5882021-07-29 06:34:05 +0900153 pub path: PathBuf,
Jooyung Hanfc732f52021-06-26 02:54:20 +0900154 /// Whether the partition should be writable.
155 #[serde(default)]
156 pub writable: bool,
157}
158
159impl Partition {
160 fn to_parcelable(&self) -> Result<AidlPartition> {
Jooyung Han631d5882021-07-29 06:34:05 +0900161 Ok(AidlPartition {
162 image: Some(open_parcel_file(&self.path, self.writable)?),
163 writable: self.writable,
164 label: self.label.to_owned(),
165 })
Jooyung Han9713bd42021-06-26 03:00:18 +0900166 }
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000167}
168
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000169/// Try to open the given file and wrap it in a [`ParcelFileDescriptor`].
Jiyong Park48b354d2021-07-15 15:04:38 +0900170pub fn open_parcel_file(filename: &Path, writable: bool) -> Result<ParcelFileDescriptor> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000171 Ok(ParcelFileDescriptor::new(
172 OpenOptions::new()
173 .read(true)
174 .write(writable)
175 .open(filename)
176 .with_context(|| format!("Failed to open {:?}", filename))?,
177 ))
178}
179
180/// If the given filename is `Some`, try to open it and wrap it in a [`ParcelFileDescriptor`].
181fn maybe_open_parcel_file(
182 filename: &Option<PathBuf>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000183 writable: bool,
Jooyung Hanfc732f52021-06-26 02:54:20 +0900184) -> Result<Option<ParcelFileDescriptor>> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000185 filename.as_deref().map(|filename| open_parcel_file(filename, writable)).transpose()
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000186}