-
Notifications
You must be signed in to change notification settings - Fork 103
Expand file tree
/
Copy pathrootmap.rs
More file actions
284 lines (249 loc) · 10.4 KB
/
Copy pathrootmap.rs
File metadata and controls
284 lines (249 loc) · 10.4 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
// Copyright 2020 CoreOS, Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
use anyhow::{bail, Context, Result};
use nix::mount;
use std::collections::HashMap;
use std::path::{Path, PathBuf};
use std::process::Command;
use libcoreinst::blockdev::*;
use libcoreinst::io::*;
use libcoreinst::util::*;
use libcoreinst::runcmd_output;
use crate::cmdline::*;
pub fn rootmap(config: RootmapConfig) -> Result<()> {
// get the backing device for the root mount
let mount = Mount::from_existing(&config.root_mount)?;
let device = PathBuf::from(mount.device());
// and from that we can collect all the parent backing devices too
let mut backing_devices = get_blkdev_deps_recursing(&device)?;
backing_devices.push(device);
// for each of those, convert them to kargs
let mut kargs = Vec::new();
for backing_device in backing_devices {
if let Some(dev_kargs) = device_to_kargs(&mount, backing_device)? {
kargs.extend(dev_kargs);
}
}
// we push the root kargs last, this has the nice property that the final order of kargs goes
// from lowest level to highest; see also
// https://github.com/coreos/fedora-coreos-tracker/issues/465
kargs.push(format!("root=UUID={}", mount.get_filesystem_uuid()?));
// we need this because with root= it's systemd that takes care of mounting via
// systemd-fstab-generator, and it defaults to read-only otherwise
kargs.push("rw".into());
let rootflags = runcmd_output!("coreos-rootflags", &config.root_mount)?;
let rootflags = rootflags.trim();
if !rootflags.is_empty() {
kargs.push(format!("rootflags={}", rootflags));
}
let boot_mount = get_boot_mount_from_cmdline_args(&config.boot_mount, &config.boot_device)?;
if let Some(mount) = boot_mount {
visit_bls_entry_options(mount.mountpoint(), |orig_options: &str| {
KargsEditor::new()
.append(&kargs)
.maybe_apply_to(orig_options)
})
.context("appending rootmap kargs")?;
eprintln!("Injected kernel arguments into BLS: {}", kargs.join(" "));
// Note here we're not calling `zipl` on s390x; it will be called anyway on firstboot by
// `coreos-ignition-firstboot-complete.service`, so might as well batch them.
} else {
// without /boot options, we just print the kargs; note we output to stdout here
println!("{}", kargs.join(" "));
}
Ok(())
}
// This is shared with the kargs code -- might move this to a helper file eventually
pub fn get_boot_mount_from_cmdline_args(
boot_mount: &Option<String>,
boot_device: &Option<String>,
) -> Result<Option<Mount>> {
if let Some(path) = boot_mount {
Ok(Some(Mount::from_existing(path)?))
} else if let Some(devpath) = boot_device {
let devinfo = blkid_single(Path::new(devpath))?;
let fs = devinfo
.get("TYPE")
.with_context(|| format!("failed to query filesystem for {}", devpath))?;
Ok(Some(Mount::try_mount(
devpath,
fs,
mount::MsFlags::empty(),
)?))
} else {
Ok(None)
}
}
fn device_to_kargs(root: &Mount, device: PathBuf) -> Result<Option<Vec<String>>> {
let blktype = get_block_device_type(&device)?;
// a `match {}` construct would be nice here, but for RAID it's a prefix match
if blktype.starts_with("raid") || blktype == "linear" {
Ok(Some(get_raid_kargs(&device)?))
} else if blktype == "crypt" {
Ok(Some(get_luks_kargs(root, &device)?))
} else if blktype == "part" || blktype == "disk" || blktype == "mpath" {
Ok(None)
} else {
bail!("unknown block device type {}", blktype)
}
}
fn get_raid_kargs(device: &Path) -> Result<Vec<String>> {
let details = mdadm_detail(device)?;
let uuid = details
.get("MD_UUID")
.with_context(|| format!("missing MD_UUID for {}", device.display()))?;
Ok(vec![format!("rd.md.uuid={}", uuid)])
}
fn mdadm_detail(device: &Path) -> Result<HashMap<String, String>> {
let output = runcmd_output!("mdadm", "--detail", "--export", device)?;
output.lines().map(split_mdadm_line).collect()
}
fn split_mdadm_line(line: &str) -> Result<(String, String)> {
line.split_once('=')
.ok_or_else(|| anyhow::anyhow!("invalid mdadm line: {}", line))
.map(|(k, v)| (k.to_string(), v.to_string()))
}
fn get_luks_kargs(root: &Mount, device: &Path) -> Result<Vec<String>> {
// The LUKS UUID is a property of the backing block device of *this* block device, so we have
// to get its parent. This is a bit awkward because we're already iterating through parents, so
// theoretically we could re-use the same state here. But meh... this is easier to understand.
let deps = get_blkdev_deps(device)?;
match deps.len() {
0 => bail!("missing parent device for {}", device.display()),
1 => {
let uuid = get_luks_uuid(&deps[0])?;
let name = get_luks_name(device)?;
let mut kargs = vec![format!("rd.luks.name={}={}", uuid, name)];
if crypttab_device_has_netdev(root, &name)? {
kargs.push("rd.neednet=1".into());
kargs.push("rd.luks.options=_netdev".into());
}
Ok(kargs)
}
_ => bail!(
"found multiple parent devices for crypt device {}",
device.display()
),
}
}
// crypttab is the source of truth for whether an encrypted block device requires networking.
fn crypttab_device_has_netdev(root: &Mount, dmname: &str) -> Result<bool> {
let crypttab_path = root.mountpoint().join("etc/crypttab");
let crypttab = std::fs::read_to_string(&crypttab_path)
.with_context(|| format!("opening {}", crypttab_path.display()))?;
for line in crypttab.lines() {
let line = line.trim();
if line.is_empty() || line.starts_with('#') {
continue;
}
let fields: Vec<&str> = line.split_whitespace().collect();
// from crypttab(5), format is:
// name encrypted-device password options
// first two fields are mandatory, remaining are optional
if fields.len() < 2 {
bail!("crypttab line missing name or device: {}", line);
}
if fields[0] != dmname {
continue;
}
if fields.len() < 4 {
return Ok(false);
}
return Ok(fields[3].split(',').any(|opt| opt == "_netdev"));
}
bail!("couldn't find {} in {}", dmname, crypttab_path.display());
}
fn get_luks_name(device: &Path) -> Result<String> {
Ok(runcmd_output!(
"dmsetup",
"info",
"--columns",
"--noheadings",
"-o",
"name",
device
)?
.trim()
.into())
}
fn get_luks_uuid(device: &Path) -> Result<String> {
Ok(runcmd_output!("cryptsetup", "luksUUID", device)?
.trim()
.into())
}
pub fn bind_boot(config: BindBootConfig) -> Result<()> {
let boot_mount = Mount::from_existing(&config.boot_mount)?;
let root_mount = Mount::from_existing(&config.root_mount)?;
let boot_uuid = boot_mount.get_filesystem_uuid()?;
let root_uuid = root_mount.get_filesystem_uuid()?;
let kargs = vec![format!("boot=UUID={}", boot_uuid)];
let changed = visit_bls_entry_options(boot_mount.mountpoint(), |orig_options: &str| {
if !orig_options.starts_with("boot=") && !orig_options.contains(" boot=") {
KargsEditor::new()
.append(&kargs)
.maybe_apply_to(orig_options)
} else {
// boot= karg already exists; let's not add anything
Ok(None)
}
})
.context("appending boot kargs")?;
// put it in /run also for the first boot real root mount
// https://github.com/coreos/fedora-coreos-config/blob/8661649009/overlay.d/05core/usr/lib/systemd/system-generators/coreos-boot-mount-generator#L105-L108
if changed {
let boot_uuid_run = Path::new("/run/coreos/bootfs_uuid");
let parent = boot_uuid_run.parent().unwrap();
std::fs::create_dir_all(parent)
.with_context(|| format!("creating {}", parent.display()))?;
std::fs::write(boot_uuid_run, format!("{}\n", &boot_uuid))
.with_context(|| format!("writing {}", boot_uuid_run.display()))?;
}
// bind rootfs to bootfs
let root_uuid_stamp = boot_mount.mountpoint().join(".root_uuid");
if root_uuid_stamp.exists() {
let bound_root_uuid = std::fs::read_to_string(&root_uuid_stamp)
.with_context(|| format!("reading {}", root_uuid_stamp.display()))?;
let bound_root_uuid = bound_root_uuid.trim();
// Let it slide if it already matches the rootfs... that shouldn't happen unless the user
// is trying to force a rerun of Ignition. In that case, we'll have nicer errors and
// warnings elsewhere.
if bound_root_uuid != root_uuid {
bail!(
"boot filesystem already bound to a root filesystem (UUID: {})",
bound_root_uuid
);
}
} else {
std::fs::write(&root_uuid_stamp, format!("{}\n", root_uuid))
.with_context(|| format!("writing {}", root_uuid_stamp.display()))?;
}
// now bind GRUB to bootfs
#[cfg(not(target_arch = "s390x"))]
{
let grub_bios_path = boot_mount.mountpoint().join("grub2/bootuuid.cfg");
write_boot_uuid_grub2_dropin(&boot_uuid, grub_bios_path)?;
}
for esp in find_colocated_esps(boot_mount.device())? {
let mount = Mount::try_mount(&esp, "vfat", mount::MsFlags::empty())?;
let vendor_dir = find_efi_vendor_dir(&mount)?;
let grub_efi_path = vendor_dir.join("bootuuid.cfg");
write_boot_uuid_grub2_dropin(&boot_uuid, grub_efi_path)?;
}
Ok(())
}
fn write_boot_uuid_grub2_dropin<P: AsRef<Path>>(uuid: &str, p: P) -> Result<()> {
let p = p.as_ref();
std::fs::write(p, format!("set BOOT_UUID=\"{}\"\n", uuid))
.with_context(|| format!("writing {}", p.display()))
}