blob: 3bd023ff23d71c87193ef446d781c97cd348df5f [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};
24use serde::{Deserialize, Serialize};
25use std::fs::{File, OpenOptions};
26use std::io::BufReader;
27use std::path::{Path, PathBuf};
28
29/// Configuration for a particular VM to be started.
30#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
31pub struct VmConfig {
32 /// The filename of the kernel image, if any.
33 pub kernel: Option<PathBuf>,
34 /// The filename of the initial ramdisk for the kernel, if any.
35 pub initrd: Option<PathBuf>,
36 /// Parameters to pass to the kernel. As far as the VMM and boot protocol are concerned this is
37 /// just a string, but typically it will contain multiple parameters separated by spaces.
38 pub params: Option<String>,
39 /// The bootloader to use. If this is supplied then the kernel and initrd must not be supplied;
40 /// the bootloader is instead responsibly for loading the kernel from one of the disks.
41 pub bootloader: Option<PathBuf>,
42 /// Disk images to be made available to the VM.
43 #[serde(default)]
44 pub disks: Vec<DiskImage>,
45}
46
47impl VmConfig {
48 /// Ensure that the configuration has a valid combination of fields set, or return an error if
49 /// not.
50 pub fn validate(&self) -> Result<(), Error> {
51 if self.bootloader.is_none() && self.kernel.is_none() {
52 bail!("VM must have either a bootloader or a kernel image.");
53 }
54 if self.bootloader.is_some() && (self.kernel.is_some() || self.initrd.is_some()) {
55 bail!("Can't have both bootloader and kernel/initrd image.");
56 }
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000057 for disk in &self.disks {
58 if disk.image.is_none() == disk.partitions.is_empty() {
59 bail!("Exactly one of image and partitions must be specified. (Was {:?}.)", disk);
60 }
61 }
Andrew Walbran3a5a9212021-05-04 17:09:08 +000062 Ok(())
63 }
64
65 /// Load the configuration for a VM from the given JSON file, and check that it is valid.
66 pub fn load(file: &File) -> Result<VmConfig, Error> {
67 let buffered = BufReader::new(file);
68 let config: VmConfig = serde_json::from_reader(buffered)?;
69 config.validate()?;
70 Ok(config)
71 }
72
73 /// Convert the `VmConfig` to a [`VirtualMachineConfig`] which can be passed to the Virt
74 /// Manager.
75 pub fn to_parcelable(&self) -> Result<VirtualMachineConfig, Error> {
76 Ok(VirtualMachineConfig {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000077 kernel: maybe_open_parcel_file(&self.kernel, false)?,
78 initrd: maybe_open_parcel_file(&self.initrd, false)?,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000079 params: self.params.clone(),
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000080 bootloader: maybe_open_parcel_file(&self.bootloader, false)?,
81 disks: self.disks.iter().map(DiskImage::to_parcelable).collect::<Result<_, Error>>()?,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000082 })
83 }
84}
85
86/// A disk image to be made available to the VM.
87#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
88pub struct DiskImage {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +000089 /// The filename of the disk image, if it already exists. Exactly one of this and `partitions`
90 /// must be specified.
91 #[serde(default)]
92 pub image: Option<PathBuf>,
93 /// A set of partitions to be assembled into a composite image.
94 #[serde(default)]
95 pub partitions: Vec<Partition>,
Andrew Walbran3a5a9212021-05-04 17:09:08 +000096 /// Whether this disk should be writable by the VM.
97 pub writable: bool,
98}
99
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000100impl DiskImage {
101 fn to_parcelable(&self) -> Result<AidlDiskImage, Error> {
102 let partitions =
103 self.partitions.iter().map(Partition::to_parcelable).collect::<Result<_, Error>>()?;
104 Ok(AidlDiskImage {
105 image: maybe_open_parcel_file(&self.image, self.writable)?,
106 writable: self.writable,
107 partitions,
108 })
109 }
110}
111
112// TODO: Share this type with virtualizationservice::composite::config.
113/// A partition for a disk image to be made available to the VM.
114#[derive(Clone, Debug, Deserialize, Eq, PartialEq, Serialize)]
115pub struct Partition {
116 /// A label for the partition.
117 pub label: String,
118 /// The filename of the partition image.
119 pub path: PathBuf,
120 /// Whether the partition should be writable.
121 #[serde(default)]
122 pub writable: bool,
123}
124
125impl Partition {
126 fn to_parcelable(&self) -> Result<AidlPartition, Error> {
127 Ok(AidlPartition {
128 image: Some(open_parcel_file(&self.path, self.writable)?),
129 writable: self.writable,
130 label: self.label.to_owned(),
131 })
132 }
133}
134
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000135/// Try to open the given file and wrap it in a [`ParcelFileDescriptor`].
136fn open_parcel_file(filename: &Path, writable: bool) -> Result<ParcelFileDescriptor, Error> {
137 Ok(ParcelFileDescriptor::new(
138 OpenOptions::new()
139 .read(true)
140 .write(writable)
141 .open(filename)
142 .with_context(|| format!("Failed to open {:?}", filename))?,
143 ))
144}
145
146/// If the given filename is `Some`, try to open it and wrap it in a [`ParcelFileDescriptor`].
147fn maybe_open_parcel_file(
148 filename: &Option<PathBuf>,
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000149 writable: bool,
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000150) -> Result<Option<ParcelFileDescriptor>, Error> {
Andrew Walbranf5fbb7d2021-05-12 17:15:48 +0000151 filename.as_deref().map(|filename| open_parcel_file(filename, writable)).transpose()
Andrew Walbran3a5a9212021-05-04 17:09:08 +0000152}