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