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