-
Notifications
You must be signed in to change notification settings - Fork 192
Expand file tree
/
Copy pathdelete.rs
More file actions
370 lines (293 loc) · 12.2 KB
/
delete.rs
File metadata and controls
370 lines (293 loc) · 12.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
use std::{collections::HashSet, io::Write, path::Path};
use anyhow::{Context, Result};
use cap_std_ext::{cap_std::fs::Dir, dirext::CapStdExtDirExt};
use composefs::fsverity::Sha512HashValue;
use composefs_boot::bootloader::{EFI_ADDON_DIR_EXT, EFI_EXT};
use crate::{
bootc_composefs::{
boot::{
find_vmlinuz_initrd_duplicates, get_efi_uuid_source, get_esp_partition,
get_sysroot_parent_dev, mount_esp, BootType, BOOTC_UKI_DIR,
},
gc::composefs_gc,
repo::open_composefs_repo,
rollback::{composefs_rollback, rename_exchange_user_cfg},
status::{get_composefs_status, get_sorted_grub_uki_boot_entries},
},
composefs_consts::{
COMPOSEFS_STAGED_DEPLOYMENT_FNAME, COMPOSEFS_TRANSIENT_STATE_DIR, STATE_DIR_RELATIVE,
TYPE1_ENT_PATH, TYPE1_ENT_PATH_STAGED, USER_CFG_STAGED,
},
parsers::bls_config::{parse_bls_config, BLSConfigType},
spec::{BootEntry, Bootloader, DeploymentEntry},
status::Slot,
store::{BootedComposefs, Storage},
};
#[fn_error_context::context("Deleting Type1 Entry {}", depl.deployment.verity)]
fn delete_type1_entry(depl: &DeploymentEntry, boot_dir: &Dir, deleting_staged: bool) -> Result<()> {
let entries_dir_path = if deleting_staged {
TYPE1_ENT_PATH_STAGED
} else {
TYPE1_ENT_PATH
};
let entries_dir = boot_dir
.open_dir(entries_dir_path)
.context("Opening entries dir")?;
// We reuse kernel + initrd if they're the same for two deployments
// We don't want to delete the (being deleted) deployment's kernel + initrd
// if it's in use by any other deployment
let should_del_kernel = match depl.deployment.boot_digest.as_ref() {
Some(digest) => find_vmlinuz_initrd_duplicates(digest)?
.is_some_and(|vec| vec.iter().any(|digest| *digest != depl.deployment.verity)),
None => false,
};
for entry in entries_dir.entries_utf8()? {
let entry = entry?;
let file_name = entry.file_name()?;
if !file_name.ends_with(".conf") {
// We don't put any non .conf file in the entries dir
// This is here just for sanity
tracing::debug!("Found non .conf file '{file_name}' in entires dir");
continue;
}
let cfg = entries_dir
.read_to_string(&file_name)
.with_context(|| format!("Reading {file_name}"))?;
let bls_config = parse_bls_config(&cfg)?;
match &bls_config.cfg_type {
BLSConfigType::UKI { uki } => {
if !uki.as_str().contains(&depl.deployment.verity) {
continue;
}
// Boot dir in case of EFI will be the ESP
tracing::debug!("Deleting UKI .conf file: {}", file_name);
entry.remove_file().context("Removing .conf file")?;
delete_uki(&depl.deployment.verity, boot_dir)?;
break;
}
BLSConfigType::NonUKI { options, .. } => {
let options = options
.as_ref()
.ok_or(anyhow::anyhow!("options not found in BLS config file"))?;
if !options.contains(&depl.deployment.verity) {
continue;
}
tracing::debug!("Deleting non-UKI .conf file: {}", file_name);
entry.remove_file().context("Removing .conf file")?;
if should_del_kernel {
delete_kernel_initrd(&bls_config.cfg_type, boot_dir)?;
}
break;
}
BLSConfigType::Unknown => anyhow::bail!("Unknown BLS Config Type"),
}
}
if deleting_staged {
tracing::debug!(
"Deleting staged entries directory: {}",
TYPE1_ENT_PATH_STAGED
);
boot_dir
.remove_dir_all(TYPE1_ENT_PATH_STAGED)
.context("Removing staged entries dir")?;
}
Ok(())
}
#[fn_error_context::context("Deleting kernel and initrd")]
fn delete_kernel_initrd(bls_config: &BLSConfigType, boot_dir: &Dir) -> Result<()> {
let BLSConfigType::NonUKI { linux, initrd, .. } = bls_config else {
anyhow::bail!("Found UKI config")
};
// "linux" and "initrd" are relative to the boot_dir in our config files
tracing::debug!("Deleting kernel: {:?}", linux);
boot_dir
.remove_file(linux)
.with_context(|| format!("Removing {linux:?}"))?;
for ird in initrd {
tracing::debug!("Deleting initrd: {:?}", ird);
boot_dir
.remove_file(ird)
.with_context(|| format!("Removing {ird:?}"))?;
}
// Remove the directory if it's empty
//
// This shouldn't ever error as we'll never have these in root
let dir = linux
.parent()
.ok_or_else(|| anyhow::anyhow!("Bad path for vmlinuz {linux}"))?;
let kernel_parent_dir = boot_dir.open_dir(&dir)?;
if kernel_parent_dir.entries().iter().len() == 0 {
// We don't have anything other than kernel and initrd in this directory for now
// So this directory should *always* be empty, for now at least
tracing::debug!("Deleting empty kernel directory: {:?}", dir);
kernel_parent_dir.remove_open_dir()?;
};
Ok(())
}
/// Deletes the UKI `uki_id` and any addons specific to it
#[fn_error_context::context("Deleting UKI and UKI addons {uki_id}")]
fn delete_uki(uki_id: &str, esp_mnt: &Dir) -> Result<()> {
// TODO: We don't delete global addons here
let ukis = esp_mnt.open_dir(BOOTC_UKI_DIR)?;
for entry in ukis.entries_utf8()? {
let entry = entry?;
let entry_name = entry.file_name()?;
// The actual UKI PE binary
if entry_name == format!("{}{}", uki_id, EFI_EXT) {
tracing::debug!("Deleting UKI: {}", entry_name);
entry.remove_file().context("Deleting UKI")?;
} else if entry_name == format!("{}{}", uki_id, EFI_ADDON_DIR_EXT) {
// Addons dir
tracing::debug!("Deleting UKI addons directory: {}", entry_name);
ukis.remove_dir_all(entry_name)
.context("Deleting UKI addons dir")?;
}
}
Ok(())
}
#[fn_error_context::context("Removing Grub Menuentry")]
fn remove_grub_menucfg_entry(id: &str, boot_dir: &Dir, deleting_staged: bool) -> Result<()> {
let grub_dir = boot_dir.open_dir("grub2").context("Opening grub2")?;
if deleting_staged {
tracing::debug!("Deleting staged grub menuentry file: {}", USER_CFG_STAGED);
return grub_dir
.remove_file(USER_CFG_STAGED)
.context("Deleting staged Menuentry");
}
let mut string = String::new();
let menuentries = get_sorted_grub_uki_boot_entries(boot_dir, &mut string)?;
grub_dir
.atomic_replace_with(USER_CFG_STAGED, move |f| -> std::io::Result<_> {
f.write_all(get_efi_uuid_source().as_bytes())?;
for entry in menuentries {
if entry.body.chainloader.contains(id) {
continue;
}
f.write_all(entry.to_string().as_bytes())?;
}
Ok(())
})
.with_context(|| format!("Writing to {USER_CFG_STAGED}"))?;
rustix::fs::fsync(grub_dir.reopen_as_ownedfd().context("Reopening")?).context("fsync")?;
rename_exchange_user_cfg(&grub_dir)
}
#[fn_error_context::context("Deleting boot entries for deployment {}", deployment.deployment.verity)]
fn delete_depl_boot_entries(
deployment: &DeploymentEntry,
physical_root: &Dir,
deleting_staged: bool,
) -> Result<()> {
match deployment.deployment.bootloader {
Bootloader::Grub => {
let boot_dir = physical_root.open_dir("boot").context("Opening boot dir")?;
match deployment.deployment.boot_type {
BootType::Bls => delete_type1_entry(deployment, &boot_dir, deleting_staged),
BootType::Uki => {
let device = get_sysroot_parent_dev(physical_root)?;
let (esp_part, ..) = get_esp_partition(&device)?;
let esp_mount = mount_esp(&esp_part)?;
remove_grub_menucfg_entry(
&deployment.deployment.verity,
&boot_dir,
deleting_staged,
)?;
delete_uki(&deployment.deployment.verity, &esp_mount.fd)
}
}
}
Bootloader::Systemd => {
let device = get_sysroot_parent_dev(physical_root)?;
let (esp_part, ..) = get_esp_partition(&device)?;
let esp_mount = mount_esp(&esp_part)?;
// For Systemd UKI as well, we use .conf files
delete_type1_entry(deployment, &esp_mount.fd, deleting_staged)
}
}
}
#[fn_error_context::context("Getting image objects")]
pub(crate) fn get_image_objects(sysroot: &Dir) -> Result<HashSet<Sha512HashValue>> {
let repo = open_composefs_repo(&sysroot)?;
let images_dir = sysroot
.open_dir("composefs/images")
.context("Opening images dir")?;
let image_entries = images_dir
.entries_utf8()
.context("Reading entries in images dir")?;
let mut object_refs = HashSet::new();
for image in image_entries {
let image = image?;
let img_name = image.file_name().context("Getting image name")?;
let objects = repo
.objects_for_image(&img_name)
.with_context(|| format!("Getting objects for image {img_name}"))?;
object_refs.extend(objects);
}
Ok(object_refs)
}
#[fn_error_context::context("Deleting image for deployment {}", deployment_id)]
pub(crate) fn delete_image(sysroot: &Dir, deployment_id: &str) -> Result<()> {
let img_path = Path::new("composefs").join("images").join(deployment_id);
tracing::debug!("Deleting EROFS image: {:?}", img_path);
sysroot
.remove_file(&img_path)
.context("Deleting EROFS image")
}
#[fn_error_context::context("Deleting state directory for deployment {}", deployment_id)]
pub(crate) fn delete_state_dir(sysroot: &Dir, deployment_id: &str) -> Result<()> {
let state_dir = Path::new(STATE_DIR_RELATIVE).join(deployment_id);
tracing::debug!("Deleting state directory: {:?}", state_dir);
sysroot
.remove_dir_all(&state_dir)
.with_context(|| format!("Removing dir {state_dir:?}"))
}
#[fn_error_context::context("Deleting staged deployment")]
pub(crate) fn delete_staged(staged: &Option<BootEntry>) -> Result<()> {
if staged.is_none() {
tracing::debug!("No staged deployment");
return Ok(());
};
let file = Path::new(COMPOSEFS_TRANSIENT_STATE_DIR).join(COMPOSEFS_STAGED_DEPLOYMENT_FNAME);
tracing::debug!("Deleting staged deployment file: {file:?}");
std::fs::remove_file(file).context("Removing staged file")?;
Ok(())
}
#[fn_error_context::context("Deleting composefs deployment {}", deployment_id)]
pub(crate) async fn delete_composefs_deployment(
deployment_id: &str,
storage: &Storage,
booted_cfs: &BootedComposefs,
) -> Result<()> {
let host = get_composefs_status(storage, booted_cfs).await?;
let booted = host.require_composefs_booted()?;
if deployment_id == &booted.verity {
anyhow::bail!("Cannot delete currently booted deployment");
}
let all_depls = host.all_composefs_deployments()?;
let depl_to_del = all_depls
.iter()
.find(|d| d.deployment.verity == deployment_id);
let Some(depl_to_del) = depl_to_del else {
anyhow::bail!("Deployment {deployment_id} not found");
};
let deleting_staged = host
.status
.staged
.as_ref()
.and_then(|s| s.composefs.as_ref())
.map_or(false, |cfs| cfs.verity == deployment_id);
// Unqueue rollback. This makes it easier to delete boot entries later on
if matches!(depl_to_del.ty, Some(Slot::Rollback)) && host.status.rollback_queued {
composefs_rollback(storage, booted_cfs).await?;
}
let kind = if depl_to_del.pinned {
"pinned "
} else if deleting_staged {
"staged "
} else {
""
};
tracing::info!("Deleting {kind}deployment '{deployment_id}'");
delete_depl_boot_entries(&depl_to_del, &storage.physical_root, deleting_staged)?;
composefs_gc(storage, booted_cfs).await?;
Ok(())
}