blob: 169fdabc2ab51d07c8fdd4bee3096f8bfe8c58f6 [file] [log] [blame]
Andrew Walbran3a5a9212021-05-04 17:09:08 +00001// 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.
16
Andrew Walbranf6bf6862021-05-21 12:41:13 +000017use android_system_virtualizationservice::{
18 aidl::android::system::virtualizationservice::DiskImage::DiskImage as AidlDiskImage,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000019 aidl::android::system::virtualizationservice::Partition::Partition as AidlPartition,
Andrew Walbranf6bf6862021-05-21 12:41:13 +000020 aidl::android::system::virtualizationservice::VirtualMachineConfig::VirtualMachineConfig,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000021 binder::ParcelFileDescriptor,
22};
23use anyhow::{bail, Context, Error};
Andrew Walbran0c4d3df2021-05-27 14:00:42 +000024use compositediskconfig::Partition;
Andrew Walbran3a5a9212021-05-04 17:09:08 +000025use serde::{Deserialize, Serialize};
26use std::fs::{File, OpenOptions};
27use std::io::BufReader;
28use std::path::{Path, PathBuf};
29
30/// Configuration for a particular VM to be started.
31#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
32pub struct VmConfig {
33 /// The filename of the kernel image, if any.
34 pub kernel: Option<PathBuf>,
35 /// The filename of the initial ramdisk for the kernel, if any.
36 pub initrd: Option<PathBuf>,
37 /// Parameters to pass to the kernel. As far as the VMM and boot protocol are concerned this is
38 /// just a string, but typically it will contain multiple parameters separated by spaces.
39 pub params: Option<String>,
40 /// The bootloader to use. If this is supplied then the kernel and initrd must not be supplied;
41 /// the bootloader is instead responsibly for loading the kernel from one of the disks.
42 pub bootloader: Option<PathBuf>,
43 /// Disk images to be made available to the VM.
44 #[serde(default)]
45 pub disks: Vec<DiskImage>,
46}
47
48impl VmConfig {
49 /// Ensure that the configuration has a valid combination of fields set, or return an error if
50 /// not.
51 pub fn validate(&self) -> Result<(), Error> {
52 if self.bootloader.is_none() && self.kernel.is_none() {
53 bail!("VM must have either a bootloader or a kernel image.");
54 }
55 if self.bootloader.is_some() && (self.kernel.is_some() || self.initrd.is_some()) {
56 bail!("Can't have both bootloader and kernel/initrd image.");
57 }
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000058 for disk in &self.disks {
59 if disk.image.is_none() == disk.partitions.is_empty() {
60 bail!("Exactly one of image and partitions must be specified. (Was {:?}.)", disk);
61 }
62 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +000063 Ok(())
64 }
65
66 /// Load the configuration for a VM from the given JSON file, and check that it is valid.
67 pub fn load(file: &File) -> Result<VmConfig, Error> {
68 let buffered = BufReader::new(file);
69 let config: VmConfig = serde_json::from_reader(buffered)?;
70 config.validate()?;
71 Ok(config)
72 }
73
74 /// Convert the `VmConfig` to a [`VirtualMachineConfig`] which can be passed to the Virt
75 /// Manager.
76 pub fn to_parcelable(&self) -> Result<VirtualMachineConfig, Error> {
77 Ok(VirtualMachineConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000078 kernel: maybe_open_parcel_file(&self.kernel, false)?,
79 initrd: maybe_open_parcel_file(&self.initrd, false)?,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000080 params: self.params.clone(),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000081 bootloader: maybe_open_parcel_file(&self.bootloader, false)?,
82 disks: self.disks.iter().map(DiskImage::to_parcelable).collect::<Result<_, Error>>()?,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000083 })
84 }
85}
86
87/// A disk image to be made available to the VM.
88#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
89pub struct DiskImage {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000090 /// The filename of the disk image, if it already exists. Exactly one of this and `partitions`
91 /// must be specified.
92 #[serde(default)]
93 pub image: Option<PathBuf>,
94 /// A set of partitions to be assembled into a composite image.
95 #[serde(default)]
96 pub partitions: Vec<Partition>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000097 /// Whether this disk should be writable by the VM.
98 pub writable: bool,
99}
100
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000101impl DiskImage {
102 fn to_parcelable(&self) -> Result<AidlDiskImage, Error> {
103 let partitions =
Andrew Walbran0c4d3df2021-05-27 14:00:42 +0000104 self.partitions.iter().map(partition_to_parcelable).collect::<Result<_, Error>>()?;
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000105 Ok(AidlDiskImage {
106 image: maybe_open_parcel_file(&self.image, self.writable)?,
107 writable: self.writable,
108 partitions,
109 })
110 }
111}
112
Andrew Walbran0c4d3df2021-05-27 14:00:42 +0000113fn partition_to_parcelable(partition: &Partition) -> Result<AidlPartition, Error> {
114 Ok(AidlPartition {
115 image: Some(open_parcel_file(&partition.path, partition.writable)?),
116 writable: partition.writable,
117 label: partition.label.to_owned(),
118 })
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000119}
120
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000121/// Try to open the given file and wrap it in a [`ParcelFileDescriptor`].
122fn open_parcel_file(filename: &Path, writable: bool) -> Result<ParcelFileDescriptor, Error> {
123 Ok(ParcelFileDescriptor::new(
124 OpenOptions::new()
125 .read(true)
126 .write(writable)
127 .open(filename)
128 .with_context(|| format!("Failed to open {:?}", filename))?,
129 ))
130}
131
132/// If the given filename is `Some`, try to open it and wrap it in a [`ParcelFileDescriptor`].
133fn maybe_open_parcel_file(
134 filename: &Option<PathBuf>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000135 writable: bool,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000136) -> Result<Option<ParcelFileDescriptor>, Error> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000137 filename.as_deref().map(|filename| open_parcel_file(filename, writable)).transpose()
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000138}