1 // 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 
15 //! Struct for VM configuration with JSON (de)serialization and AIDL parcelables
16 
17 use android_system_virtualizationservice::{
18     aidl::android::system::virtualizationservice::CpuTopology::CpuTopology,
19     aidl::android::system::virtualizationservice::DiskImage::DiskImage as AidlDiskImage,
20     aidl::android::system::virtualizationservice::Partition::Partition as AidlPartition,
21     aidl::android::system::virtualizationservice::VirtualMachineAppConfig::DebugLevel::DebugLevel,
22     aidl::android::system::virtualizationservice::VirtualMachineConfig::VirtualMachineConfig,
23     aidl::android::system::virtualizationservice::VirtualMachineRawConfig::VirtualMachineRawConfig,
24     binder::ParcelFileDescriptor,
25 };
26 
27 use anyhow::{anyhow, bail, Context, Error, Result};
28 use semver::VersionReq;
29 use serde::{Deserialize, Serialize};
30 use std::convert::TryInto;
31 use std::fs::{File, OpenOptions};
32 use std::io::BufReader;
33 use std::num::NonZeroU32;
34 use std::path::{Path, PathBuf};
35 
36 /// Configuration for a particular VM to be started.
37 #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
38 pub struct VmConfig {
39     /// The name of VM.
40     pub name: Option<String>,
41     /// The filename of the kernel image, if any.
42     pub kernel: Option<PathBuf>,
43     /// The filename of the initial ramdisk for the kernel, if any.
44     pub initrd: Option<PathBuf>,
45     /// Parameters to pass to the kernel. As far as the VMM and boot protocol are concerned this is
46     /// just a string, but typically it will contain multiple parameters separated by spaces.
47     pub params: Option<String>,
48     /// The bootloader to use. If this is supplied then the kernel and initrd must not be supplied;
49     /// the bootloader is instead responsibly for loading the kernel from one of the disks.
50     pub bootloader: Option<PathBuf>,
51     /// Disk images to be made available to the VM.
52     #[serde(default)]
53     pub disks: Vec<DiskImage>,
54     /// Whether the VM should be a protected VM.
55     #[serde(default)]
56     pub protected: bool,
57     /// The amount of RAM to give the VM, in MiB.
58     #[serde(default)]
59     pub memory_mib: Option<NonZeroU32>,
60     /// The CPU topology: either "one_cpu"(default) or "match_host"
61     pub cpu_topology: Option<String>,
62     /// Version or range of versions of the virtual platform that this config is compatible with.
63     /// The format follows SemVer (https://semver.org).
64     pub platform_version: VersionReq,
65     /// SysFS paths of devices assigned to the VM.
66     #[serde(default)]
67     pub devices: Vec<PathBuf>,
68     /// The serial device for VM console input.
69     pub console_input_device: Option<String>,
70 }
71 
72 impl VmConfig {
73     /// Ensure that the configuration has a valid combination of fields set, or return an error if
74     /// not.
validate(&self) -> Result<(), Error>75     pub fn validate(&self) -> Result<(), Error> {
76         if self.bootloader.is_none() && self.kernel.is_none() {
77             bail!("VM must have either a bootloader or a kernel image.");
78         }
79         if self.bootloader.is_some() && (self.kernel.is_some() || self.initrd.is_some()) {
80             bail!("Can't have both bootloader and kernel/initrd image.");
81         }
82         for disk in &self.disks {
83             if disk.image.is_none() == disk.partitions.is_empty() {
84                 bail!("Exactly one of image and partitions must be specified. (Was {:?}.)", disk);
85             }
86         }
87         Ok(())
88     }
89 
90     /// Load the configuration for a VM from the given JSON file, and check that it is valid.
load(file: &File) -> Result<VmConfig, Error>91     pub fn load(file: &File) -> Result<VmConfig, Error> {
92         let buffered = BufReader::new(file);
93         let config: VmConfig = serde_json::from_reader(buffered)?;
94         config.validate()?;
95         Ok(config)
96     }
97 
98     /// Convert the `VmConfig` to a [`VirtualMachineConfig`] which can be passed to the Virt
99     /// Manager.
to_parcelable(&self) -> Result<VirtualMachineRawConfig, Error>100     pub fn to_parcelable(&self) -> Result<VirtualMachineRawConfig, Error> {
101         let memory_mib = if let Some(memory_mib) = self.memory_mib {
102             memory_mib.get().try_into().context("Invalid memory_mib")?
103         } else {
104             0
105         };
106         let cpu_topology = match self.cpu_topology.as_deref() {
107             None => CpuTopology::ONE_CPU,
108             Some("one_cpu") => CpuTopology::ONE_CPU,
109             Some("match_host") => CpuTopology::MATCH_HOST,
110             Some(cpu_topology) => bail!("Invalid cpu topology {}", cpu_topology),
111         };
112         Ok(VirtualMachineRawConfig {
113             kernel: maybe_open_parcel_file(&self.kernel, false)?,
114             initrd: maybe_open_parcel_file(&self.initrd, false)?,
115             params: self.params.clone(),
116             bootloader: maybe_open_parcel_file(&self.bootloader, false)?,
117             disks: self.disks.iter().map(DiskImage::to_parcelable).collect::<Result<_, Error>>()?,
118             protectedVm: self.protected,
119             memoryMib: memory_mib,
120             cpuTopology: cpu_topology,
121             platformVersion: self.platform_version.to_string(),
122             devices: self
123                 .devices
124                 .iter()
125                 .map(|x| {
126                     x.to_str().map(String::from).ok_or(anyhow!("Failed to convert {x:?} to String"))
127                 })
128                 .collect::<Result<_>>()?,
129             consoleInputDevice: self.console_input_device.clone(),
130             ..Default::default()
131         })
132     }
133 }
134 
135 /// Returns the debug level of the VM from its configuration.
get_debug_level(config: &VirtualMachineConfig) -> Option<DebugLevel>136 pub fn get_debug_level(config: &VirtualMachineConfig) -> Option<DebugLevel> {
137     match config {
138         VirtualMachineConfig::AppConfig(config) => Some(config.debugLevel),
139         VirtualMachineConfig::RawConfig(_) => None,
140     }
141 }
142 
143 /// A disk image to be made available to the VM.
144 #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
145 pub struct DiskImage {
146     /// The filename of the disk image, if it already exists. Exactly one of this and `partitions`
147     /// must be specified.
148     #[serde(default)]
149     pub image: Option<PathBuf>,
150     /// A set of partitions to be assembled into a composite image.
151     #[serde(default)]
152     pub partitions: Vec<Partition>,
153     /// Whether this disk should be writable by the VM.
154     pub writable: bool,
155 }
156 
157 impl DiskImage {
to_parcelable(&self) -> Result<AidlDiskImage, Error>158     fn to_parcelable(&self) -> Result<AidlDiskImage, Error> {
159         let partitions =
160             self.partitions.iter().map(Partition::to_parcelable).collect::<Result<_>>()?;
161         Ok(AidlDiskImage {
162             image: maybe_open_parcel_file(&self.image, self.writable)?,
163             writable: self.writable,
164             partitions,
165         })
166     }
167 }
168 
169 /// A partition to be assembled into a composite image.
170 #[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
171 pub struct Partition {
172     /// A label for the partition.
173     pub label: String,
174     /// The filename of the partition image.
175     pub path: PathBuf,
176     /// Whether the partition should be writable.
177     #[serde(default)]
178     pub writable: bool,
179 }
180 
181 impl Partition {
to_parcelable(&self) -> Result<AidlPartition>182     fn to_parcelable(&self) -> Result<AidlPartition> {
183         Ok(AidlPartition {
184             image: Some(open_parcel_file(&self.path, self.writable)?),
185             writable: self.writable,
186             label: self.label.to_owned(),
187         })
188     }
189 }
190 
191 /// Try to open the given file and wrap it in a [`ParcelFileDescriptor`].
open_parcel_file(filename: &Path, writable: bool) -> Result<ParcelFileDescriptor>192 pub fn open_parcel_file(filename: &Path, writable: bool) -> Result<ParcelFileDescriptor> {
193     Ok(ParcelFileDescriptor::new(
194         OpenOptions::new()
195             .read(true)
196             .write(writable)
197             .open(filename)
198             .with_context(|| format!("Failed to open {:?}", filename))?,
199     ))
200 }
201 
202 /// If the given filename is `Some`, try to open it and wrap it in a [`ParcelFileDescriptor`].
maybe_open_parcel_file( filename: &Option<PathBuf>, writable: bool, ) -> Result<Option<ParcelFileDescriptor>>203 fn maybe_open_parcel_file(
204     filename: &Option<PathBuf>,
205     writable: bool,
206 ) -> Result<Option<ParcelFileDescriptor>> {
207     filename.as_deref().map(|filename| open_parcel_file(filename, writable)).transpose()
208 }
209