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