blob: e5c8e1b6a6d36d685bf30fcf54f6dcfb74f1df37 [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};
26use std::fs::{File, OpenOptions};
27use std::io::BufReader;
28use std::path::{Path, PathBuf};
29
30/// Configuration for a particular VM to be started.
31#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
32pub struct VmConfig {
33 /// The filename of the kernel image, if any.
34 pub kernel: Option<PathBuf>,
35 /// The filename of the initial ramdisk for the kernel, if any.
36 pub initrd: Option<PathBuf>,
37 /// Parameters to pass to the kernel. As far as the VMM and boot protocol are concerned this is
38 /// just a string, but typically it will contain multiple parameters separated by spaces.
39 pub params: Option<String>,
40 /// The bootloader to use. If this is supplied then the kernel and initrd must not be supplied;
41 /// the bootloader is instead responsibly for loading the kernel from one of the disks.
42 pub bootloader: Option<PathBuf>,
43 /// Disk images to be made available to the VM.
44 #[serde(default)]
45 pub disks: Vec<DiskImage>,
Andrew Walbranf8650422021-06-09 15:54:09 +000046 /// Whether the VM should be a protected VM.
47 #[serde(default)]
48 pub protected: bool,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000049}
50
51impl VmConfig {
52 /// Ensure that the configuration has a valid combination of fields set, or return an error if
53 /// not.
54 pub fn validate(&self) -> Result<(), Error> {
55 if self.bootloader.is_none() && self.kernel.is_none() {
56 bail!("VM must have either a bootloader or a kernel image.");
57 }
58 if self.bootloader.is_some() && (self.kernel.is_some() || self.initrd.is_some()) {
59 bail!("Can't have both bootloader and kernel/initrd image.");
60 }
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000061 for disk in &self.disks {
62 if disk.image.is_none() == disk.partitions.is_empty() {
63 bail!("Exactly one of image and partitions must be specified. (Was {:?}.)", disk);
64 }
65 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +000066 Ok(())
67 }
68
69 /// Load the configuration for a VM from the given JSON file, and check that it is valid.
70 pub fn load(file: &File) -> Result<VmConfig, Error> {
71 let buffered = BufReader::new(file);
72 let config: VmConfig = serde_json::from_reader(buffered)?;
73 config.validate()?;
74 Ok(config)
75 }
76
77 /// Convert the `VmConfig` to a [`VirtualMachineConfig`] which can be passed to the Virt
78 /// Manager.
Jooyung Han21e9b922021-06-26 04:14:16 +090079 pub fn to_parcelable(&self) -> Result<VirtualMachineRawConfig, Error> {
80 Ok(VirtualMachineRawConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000081 kernel: maybe_open_parcel_file(&self.kernel, false)?,
82 initrd: maybe_open_parcel_file(&self.initrd, false)?,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000083 params: self.params.clone(),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000084 bootloader: maybe_open_parcel_file(&self.bootloader, false)?,
85 disks: self.disks.iter().map(DiskImage::to_parcelable).collect::<Result<_, Error>>()?,
Andrew Walbranf8650422021-06-09 15:54:09 +000086 protected_vm: self.protected,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000087 })
88 }
89}
90
91/// A disk image to be made available to the VM.
92#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
93pub struct DiskImage {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000094 /// The filename of the disk image, if it already exists. Exactly one of this and `partitions`
95 /// must be specified.
96 #[serde(default)]
97 pub image: Option<PathBuf>,
98 /// A set of partitions to be assembled into a composite image.
99 #[serde(default)]
100 pub partitions: Vec<Partition>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000101 /// Whether this disk should be writable by the VM.
102 pub writable: bool,
103}
104
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000105impl DiskImage {
106 fn to_parcelable(&self) -> Result<AidlDiskImage, Error> {
107 let partitions =
Jooyung Hanfc732f52021-06-26 02:54:20 +0900108 self.partitions.iter().map(Partition::to_parcelable).collect::<Result<_>>()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000109 Ok(AidlDiskImage {
110 image: maybe_open_parcel_file(&self.image, self.writable)?,
111 writable: self.writable,
112 partitions,
113 })
114 }
115}
116
Jooyung Hanfc732f52021-06-26 02:54:20 +0900117/// A partition to be assembled into a composite image.
118#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
119pub struct Partition {
120 /// A label for the partition.
121 pub label: String,
122 /// The filename of the partition image.
123 #[serde(default)]
124 pub path: Option<PathBuf>,
125 /// The filename of the partition image.
126 #[serde(default)]
127 pub paths: Vec<PathBuf>,
128 /// Whether the partition should be writable.
129 #[serde(default)]
130 pub writable: bool,
131}
132
133impl Partition {
134 fn to_parcelable(&self) -> Result<AidlPartition> {
135 if !self.paths.is_empty() {
136 if self.path.is_some() {
137 bail!("Partition {} contains both path/paths", &self.label);
138 }
139 let images = self
140 .paths
141 .iter()
142 .map(|path| open_parcel_file(&path, self.writable))
143 .collect::<Result<Vec<_>, _>>()?;
144 Ok(AidlPartition { images, writable: self.writable, label: self.label.to_owned() })
145 } else {
146 let path = self.path.as_ref().ok_or_else(|| {
147 Error::msg(format!("Partition {} doesn't set path/paths", &self.label))
148 })?;
149 Ok(AidlPartition {
150 images: vec![open_parcel_file(&path, self.writable)?],
151 writable: self.writable,
152 label: self.label.to_owned(),
153 })
Jooyung Han9713bd42021-06-26 03:00:18 +0900154 }
Jooyung Han9713bd42021-06-26 03:00:18 +0900155 }
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000156}
157
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000158/// Try to open the given file and wrap it in a [`ParcelFileDescriptor`].
Jooyung Hanfc732f52021-06-26 02:54:20 +0900159fn open_parcel_file(filename: &Path, writable: bool) -> Result<ParcelFileDescriptor> {
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000160 Ok(ParcelFileDescriptor::new(
161 OpenOptions::new()
162 .read(true)
163 .write(writable)
164 .open(filename)
165 .with_context(|| format!("Failed to open {:?}", filename))?,
166 ))
167}
168
169/// If the given filename is `Some`, try to open it and wrap it in a [`ParcelFileDescriptor`].
170fn maybe_open_parcel_file(
171 filename: &Option<PathBuf>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000172 writable: bool,
Jooyung Hanfc732f52021-06-26 02:54:20 +0900173) -> Result<Option<ParcelFileDescriptor>> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000174 filename.as_deref().map(|filename| open_parcel_file(filename, writable)).transpose()
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000175}