1use anyhow::Context;
7use fatfs::FormatVolumeOptions;
8use fatfs::FsOptions;
9use guid::Guid;
10use petri_artifacts_common::artifacts as common_artifacts;
11use petri_artifacts_common::tags::MachineArch;
12use petri_artifacts_common::tags::OsFlavor;
13use petri_artifacts_core::ArtifactResolver;
14use petri_artifacts_core::ResolvedArtifact;
15use std::io::Read;
16use std::io::Seek;
17use std::io::Write;
18use std::ops::Range;
19use std::path::Path;
20
21#[derive(Debug)]
23pub struct AgentImage {
24 os_flavor: OsFlavor,
25 pipette: Option<ResolvedArtifact>,
26 extras: Vec<(String, ResolvedArtifact)>,
27}
28
29pub enum ImageType {
31 Raw,
33 Vhd,
35}
36
37impl AgentImage {
38 pub fn new(os_flavor: OsFlavor) -> Self {
40 Self {
41 os_flavor,
42 pipette: None,
43 extras: Vec::new(),
44 }
45 }
46
47 pub fn with_pipette(mut self, resolver: &ArtifactResolver<'_>, arch: MachineArch) -> Self {
49 self.pipette = match (self.os_flavor, arch) {
50 (OsFlavor::Windows, MachineArch::X86_64) => Some(
51 resolver
52 .require(common_artifacts::PIPETTE_WINDOWS_X64)
53 .erase(),
54 ),
55 (OsFlavor::Linux, MachineArch::X86_64) => Some(
56 resolver
57 .require(common_artifacts::PIPETTE_LINUX_X64)
58 .erase(),
59 ),
60 (OsFlavor::Windows, MachineArch::Aarch64) => Some(
61 resolver
62 .require(common_artifacts::PIPETTE_WINDOWS_AARCH64)
63 .erase(),
64 ),
65 (OsFlavor::Linux, MachineArch::Aarch64) => Some(
66 resolver
67 .require(common_artifacts::PIPETTE_LINUX_AARCH64)
68 .erase(),
69 ),
70 (OsFlavor::FreeBsd | OsFlavor::Uefi, _) => {
71 todo!("No pipette binary yet for os");
72 }
73 };
74 self
75 }
76
77 pub fn contains_pipette(&self) -> bool {
79 self.pipette.is_some()
80 }
81
82 pub fn add_file(&mut self, name: &str, artifact: ResolvedArtifact) {
84 self.extras.push((name.to_string(), artifact));
85 }
86
87 pub fn build(&self, image_type: ImageType) -> anyhow::Result<Option<tempfile::NamedTempFile>> {
90 let mut files = self
91 .extras
92 .iter()
93 .map(|(name, artifact)| (name.as_str(), PathOrBinary::Path(artifact.as_ref())))
94 .collect::<Vec<_>>();
95 let volume_label = match self.os_flavor {
96 OsFlavor::Windows => {
97 if let Some(pipette) = self.pipette.as_ref() {
100 files.push(("pipette.exe", PathOrBinary::Path(pipette.as_ref())));
101 }
102 b"pipette "
103 }
104 OsFlavor::Linux => {
105 if let Some(pipette) = self.pipette.as_ref() {
106 files.push(("pipette", PathOrBinary::Path(pipette.as_ref())));
107 }
108 files.extend([
111 (
112 "meta-data",
113 PathOrBinary::Binary(include_bytes!("../guest-bootstrap/meta-data")),
114 ),
115 (
116 "user-data",
117 if self.pipette.is_some() {
118 PathOrBinary::Binary(include_bytes!("../guest-bootstrap/user-data"))
119 } else {
120 PathOrBinary::Binary(include_bytes!(
121 "../guest-bootstrap/user-data-no-agent"
122 ))
123 },
124 ),
125 (
128 "network-config",
129 PathOrBinary::Binary(include_bytes!("../guest-bootstrap/network-config")),
130 ),
131 ]);
132 b"cidata " }
134 _ => b"cidata ",
136 };
137
138 if files.is_empty() {
139 Ok(None)
140 } else {
141 let mut image_file = match image_type {
142 ImageType::Raw => tempfile::NamedTempFile::new()?,
143 ImageType::Vhd => tempfile::Builder::new().suffix(".vhd").tempfile()?,
144 };
145
146 image_file
147 .as_file()
148 .set_len(64 * 1024 * 1024)
149 .context("failed to set file size")?;
150
151 build_fat32_disk_image(&mut image_file, "CIDATA", volume_label, &files)?;
152
153 if matches!(image_type, ImageType::Vhd) {
154 disk_vhd1::Vhd1Disk::make_fixed(image_file.as_file())
155 .context("failed to make vhd for agent image")?;
156 }
157
158 Ok(Some(image_file))
159 }
160 }
161}
162
163pub(crate) const SECTOR_SIZE: u64 = 512;
164
165pub(crate) enum PathOrBinary<'a> {
166 Path(&'a Path),
167 Binary(&'a [u8]),
168}
169
170pub(crate) fn build_fat32_disk_image(
171 file: &mut (impl Read + Write + Seek),
172 gpt_name: &str,
173 volume_label: &[u8; 11],
174 files: &[(&str, PathOrBinary<'_>)],
175) -> anyhow::Result<()> {
176 let partition_range =
177 build_gpt(file, gpt_name).context("failed to construct partition table")?;
178 build_fat32(
179 &mut fscommon::StreamSlice::new(file, partition_range.start, partition_range.end)?,
180 volume_label,
181 files,
182 )
183 .context("failed to format volume")?;
184 Ok(())
185}
186
187fn build_gpt(file: &mut (impl Read + Write + Seek), name: &str) -> anyhow::Result<Range<u64>> {
188 let mut gpt = gptman::GPT::new_from(file, SECTOR_SIZE, Guid::new_random().into())?;
189
190 gptman::GPT::write_protective_mbr_into(file, SECTOR_SIZE)?;
192
193 gpt[1] = gptman::GPTPartitionEntry {
195 partition_type_guid: guid::guid!("EBD0A0A2-B9E5-4433-87C0-68B6B72699C7").into(),
197 unique_partition_guid: Guid::new_random().into(),
198 starting_lba: gpt.header.first_usable_lba,
199 ending_lba: gpt.header.last_usable_lba,
200 attribute_bits: 0,
201 partition_name: name.into(),
202 };
203 gpt.write_into(file)?;
204
205 let partition_start_byte = gpt[1].starting_lba * SECTOR_SIZE;
207 let partition_num_bytes = (gpt[1].ending_lba - gpt[1].starting_lba) * SECTOR_SIZE;
208 Ok(partition_start_byte..partition_start_byte + partition_num_bytes)
209}
210
211fn build_fat32(
212 file: &mut (impl Read + Write + Seek),
213 volume_label: &[u8; 11],
214 files: &[(&str, PathOrBinary<'_>)],
215) -> anyhow::Result<()> {
216 fatfs::format_volume(
217 &mut *file,
218 FormatVolumeOptions::new()
219 .volume_label(*volume_label)
220 .fat_type(fatfs::FatType::Fat32),
221 )
222 .context("failed to format volume")?;
223 let fs = fatfs::FileSystem::new(file, FsOptions::new()).context("failed to open fs")?;
224 for (path, src) in files {
225 let mut dest = fs
226 .root_dir()
227 .create_file(path)
228 .context("failed to create file")?;
229 match *src {
230 PathOrBinary::Path(src_path) => {
231 let mut src = fs_err::File::open(src_path)?;
232 std::io::copy(&mut src, &mut dest).context("failed to copy file")?;
233 }
234 PathOrBinary::Binary(src_data) => {
235 dest.write_all(src_data).context("failed to write file")?;
236 }
237 }
238 dest.flush().context("failed to flush file")?;
239 }
240 fs.unmount().context("failed to unmount fs")?;
241 Ok(())
242}