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