blob: 9c3e671ec17fc05897a4e99fc7d10f5600d99096 [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
24use anyhow::{bail, Context, Error, Result};
Andrew Walbran3a5a9212021-05-04 17:09:08 +000025use serde::{Deserialize, Serialize};
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000026use std::convert::TryInto;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000027use std::fs::{File, OpenOptions};
28use std::io::BufReader;
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000029use std::num::NonZeroU32;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000030use std::path::{Path, PathBuf};
31
32/// Configuration for a particular VM to be started.
33#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
34pub struct VmConfig {
35 /// The filename of the kernel image, if any.
36 pub kernel: Option<PathBuf>,
37 /// The filename of the initial ramdisk for the kernel, if any.
38 pub initrd: Option<PathBuf>,
39 /// Parameters to pass to the kernel. As far as the VMM and boot protocol are concerned this is
40 /// just a string, but typically it will contain multiple parameters separated by spaces.
41 pub params: Option<String>,
42 /// The bootloader to use. If this is supplied then the kernel and initrd must not be supplied;
43 /// the bootloader is instead responsibly for loading the kernel from one of the disks.
44 pub bootloader: Option<PathBuf>,
45 /// Disk images to be made available to the VM.
46 #[serde(default)]
47 pub disks: Vec<DiskImage>,
Andrew Walbranf8650422021-06-09 15:54:09 +000048 /// Whether the VM should be a protected VM.
49 #[serde(default)]
50 pub protected: bool,
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000051 /// The amount of RAM to give the VM, in MiB.
52 #[serde(default)]
53 pub memory_mib: Option<NonZeroU32>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000054}
55
56impl VmConfig {
57 /// Ensure that the configuration has a valid combination of fields set, or return an error if
58 /// not.
59 pub fn validate(&self) -> Result<(), Error> {
60 if self.bootloader.is_none() && self.kernel.is_none() {
61 bail!("VM must have either a bootloader or a kernel image.");
62 }
63 if self.bootloader.is_some() && (self.kernel.is_some() || self.initrd.is_some()) {
64 bail!("Can't have both bootloader and kernel/initrd image.");
65 }
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000066 for disk in &self.disks {
67 if disk.image.is_none() == disk.partitions.is_empty() {
68 bail!("Exactly one of image and partitions must be specified. (Was {:?}.)", disk);
69 }
70 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +000071 Ok(())
72 }
73
74 /// Load the configuration for a VM from the given JSON file, and check that it is valid.
75 pub fn load(file: &File) -> Result<VmConfig, Error> {
76 let buffered = BufReader::new(file);
77 let config: VmConfig = serde_json::from_reader(buffered)?;
78 config.validate()?;
79 Ok(config)
80 }
81
82 /// Convert the `VmConfig` to a [`VirtualMachineConfig`] which can be passed to the Virt
83 /// Manager.
Jooyung Han21e9b922021-06-26 04:14:16 +090084 pub fn to_parcelable(&self) -> Result<VirtualMachineRawConfig, Error> {
Andrew Walbranb15cd6e2021-07-05 16:38:07 +000085 let memory_mib = if let Some(memory_mib) = self.memory_mib {
86 memory_mib.get().try_into().context("Invalid memory_mib")?
87 } else {
88 0
89 };
Jooyung Han21e9b922021-06-26 04:14:16 +090090 Ok(VirtualMachineRawConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000091 kernel: maybe_open_parcel_file(&self.kernel, false)?,
92 initrd: maybe_open_parcel_file(&self.initrd, false)?,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000093 params: self.params.clone(),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000094 bootloader: maybe_open_parcel_file(&self.bootloader, false)?,
95 disks: self.disks.iter().map(DiskImage::to_parcelable).collect::<Result<_, Error>>()?,
Andrew Walbrancc045902021-07-27 16:06:17 +000096 protectedVm: self.protected,
97 memoryMib: memory_mib,
Jiyong Park032615f2022-01-10 13:55:34 +090098 ..Default::default()
Andrew Walbran3a5a9212021-05-04 17:09:08 +000099 })
100 }
101}
102
103/// A disk image to be made available to the VM.
104#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
105pub struct DiskImage {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000106 /// The filename of the disk image, if it already exists. Exactly one of this and `partitions`
107 /// must be specified.
108 #[serde(default)]
109 pub image: Option<PathBuf>,
110 /// A set of partitions to be assembled into a composite image.
111 #[serde(default)]
112 pub partitions: Vec<Partition>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000113 /// Whether this disk should be writable by the VM.
114 pub writable: bool,
115}
116
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000117impl DiskImage {
118 fn to_parcelable(&self) -> Result<AidlDiskImage, Error> {
119 let partitions =
Jooyung Hanfc732f52021-06-26 02:54:20 +0900120 self.partitions.iter().map(Partition::to_parcelable).collect::<Result<_>>()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000121 Ok(AidlDiskImage {
122 image: maybe_open_parcel_file(&self.image, self.writable)?,
123 writable: self.writable,
124 partitions,
125 })
126 }
127}
128
Jooyung Hanfc732f52021-06-26 02:54:20 +0900129/// A partition to be assembled into a composite image.
130#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
131pub struct Partition {
132 /// A label for the partition.
133 pub label: String,
134 /// The filename of the partition image.
Jooyung Han631d5882021-07-29 06:34:05 +0900135 pub path: PathBuf,
Jooyung Hanfc732f52021-06-26 02:54:20 +0900136 /// Whether the partition should be writable.
137 #[serde(default)]
138 pub writable: bool,
139}
140
141impl Partition {
142 fn to_parcelable(&self) -> Result<AidlPartition> {
Jooyung Han631d5882021-07-29 06:34:05 +0900143 Ok(AidlPartition {
144 image: Some(open_parcel_file(&self.path, self.writable)?),
145 writable: self.writable,
146 label: self.label.to_owned(),
147 })
Jooyung Han9713bd42021-06-26 03:00:18 +0900148 }
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000149}
150
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000151/// Try to open the given file and wrap it in a [`ParcelFileDescriptor`].
Jiyong Park48b354d2021-07-15 15:04:38 +0900152pub fn open_parcel_file(filename: &Path, writable: bool) -> Result<ParcelFileDescriptor> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000153 Ok(ParcelFileDescriptor::new(
154 OpenOptions::new()
155 .read(true)
156 .write(writable)
157 .open(filename)
158 .with_context(|| format!("Failed to open {:?}", filename))?,
159 ))
160}
161
162/// If the given filename is `Some`, try to open it and wrap it in a [`ParcelFileDescriptor`].
163fn maybe_open_parcel_file(
164 filename: &Option<PathBuf>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000165 writable: bool,
Jooyung Hanfc732f52021-06-26 02:54:20 +0900166) -> Result<Option<ParcelFileDescriptor>> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000167 filename.as_deref().map(|filename| open_parcel_file(filename, writable)).transpose()
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000168}