Skip to content

Commit 84b7f03

Browse files
drewnatedemoss
authored andcommitted
fix(vm): resolve e2fsprogs through augmented path
Signed-off-by: Drew Newberry <anewberry@nvidia.com>
1 parent 49b5453 commit 84b7f03

1 file changed

Lines changed: 153 additions & 165 deletions

File tree

‎crates/openshell-driver-vm/src/rootfs.rs‎

Lines changed: 153 additions & 165 deletions
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33

44
use flate2::read::MultiGzDecoder;
55
use sha2::{Digest, Sha256};
6+
use std::ffi::{OsStr, OsString};
67
use std::fs;
78
use std::fs::File;
89
#[cfg(test)]
@@ -370,36 +371,24 @@ pub fn set_rootfs_image_file_mode(
370371
/// Replay the ext4 journal and repair automatically correctable filesystem
371372
/// state before the driver mutates a preserved guest disk offline.
372373
pub fn recover_rootfs_image(image_path: &Path) -> Result<(), String> {
373-
let mut failures = Vec::new();
374-
let mut unavailable = Vec::new();
375-
376-
for candidate in e2fs_tool_candidates("e2fsck") {
377-
let label = candidate.display().to_string();
378-
match Command::new(&candidate)
379-
.arg("-p")
380-
.arg("-f")
381-
.arg(image_path)
382-
.output()
383-
{
384-
Ok(output) if matches!(output.status.code(), Some(0..=2)) => return Ok(()),
385-
Ok(output) => failures.push(format!(
386-
"{label} failed with status {}\nstdout: {}\nstderr: {}",
387-
output.status,
388-
String::from_utf8_lossy(&output.stdout),
389-
String::from_utf8_lossy(&output.stderr)
390-
)),
391-
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
392-
unavailable.push(format!("{label} not found"));
393-
}
394-
Err(error) => failures.push(format!("run {label}: {error}")),
374+
let output = e2fs_command("e2fsck")?
375+
.arg("-p")
376+
.arg("-f")
377+
.arg(image_path)
378+
.output();
379+
match output {
380+
Ok(output) if matches!(output.status.code(), Some(0..=2)) => Ok(()),
381+
Ok(output) => Err(format!(
382+
"e2fsck failed with status {}\nstdout: {}\nstderr: {}",
383+
output.status,
384+
String::from_utf8_lossy(&output.stdout),
385+
String::from_utf8_lossy(&output.stderr)
386+
)),
387+
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
388+
Err("e2fsck not found".to_string())
395389
}
390+
Err(error) => Err(format!("run e2fsck: {error}")),
396391
}
397-
398-
Err(if failures.is_empty() {
399-
unavailable.join("\n")
400-
} else {
401-
failures.join("\n")
402-
})
403392
}
404393

405394
#[cfg(target_os = "macos")]
@@ -675,12 +664,14 @@ enum FormatterAttempt {
675664
}
676665

677666
fn format_ext4_image_from_dir(source: &Path, image_path: &Path) -> Result<(), String> {
678-
let candidates = ["mke2fs", "mkfs.ext4"]
679-
.into_iter()
680-
.flat_map(e2fs_tool_candidates);
667+
let candidates = ["mke2fs", "mkfs.ext4"].map(PathBuf::from);
681668
run_ext4_formatter_candidates(candidates, |candidate| {
682669
let label = candidate.display().to_string();
683-
let output = Command::new(candidate)
670+
let mut command = match e2fs_command(candidate.as_os_str()) {
671+
Ok(command) => command,
672+
Err(error) => return FormatterAttempt::Failed(error),
673+
};
674+
let output = command
684675
.arg("-q")
685676
.arg("-F")
686677
.arg("-t")
@@ -699,10 +690,10 @@ fn format_ext4_image_from_dir(source: &Path, image_path: &Path) -> Result<(), St
699690
String::from_utf8_lossy(&output.stdout),
700691
String::from_utf8_lossy(&output.stderr)
701692
)),
702-
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
693+
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
703694
FormatterAttempt::Unavailable(format!("{label} not found"))
704695
}
705-
Err(err) => FormatterAttempt::Failed(format!("run {label}: {err}")),
696+
Err(error) => FormatterAttempt::Failed(format!("run {label}: {error}")),
706697
}
707698
})
708699
.map_err(|details| {
@@ -949,45 +940,33 @@ fn sandbox_guest_user_ids_from_image_path(
949940
let quoted_path = debugfs_quote_absolute_path(guest_path)
950941
.expect("the static passwd path is a valid debugfs path");
951942
let command = format!("cat {quoted_path}");
952-
let mut last_error = None;
953-
954-
for candidate in e2fs_tool_candidates("debugfs") {
955-
let label = candidate.display().to_string();
956-
match Command::new(&candidate)
957-
.arg("-R")
958-
.arg(&command)
959-
.arg(image_path)
960-
.output()
961-
{
962-
Ok(output) if output.status.success() => {
963-
let passwd = String::from_utf8(output.stdout).map_err(|error| {
964-
format!(
965-
"read {guest_path} from {} as UTF-8: {error}",
966-
image_path.display()
967-
)
968-
})?;
969-
return parse_sandbox_guest_user_ids(&passwd, &image_path.display().to_string());
970-
}
971-
Ok(output) => {
972-
last_error = Some(format!(
973-
"{label} failed with status {}\nstdout: {}\nstderr: {}",
974-
output.status,
975-
String::from_utf8_lossy(&output.stdout),
976-
String::from_utf8_lossy(&output.stderr)
977-
));
978-
}
979-
Err(error) if error.kind() == std::io::ErrorKind::NotFound => {
980-
last_error = Some(format!("{label} not found"));
981-
}
982-
Err(error) => last_error = Some(format!("run {label}: {error}")),
943+
let output = e2fs_command("debugfs")?
944+
.arg("-R")
945+
.arg(&command)
946+
.arg(image_path)
947+
.output();
948+
match output {
949+
Ok(output) if output.status.success() => {
950+
let passwd = String::from_utf8(output.stdout).map_err(|error| {
951+
format!(
952+
"read {guest_path} from {} as UTF-8: {error}",
953+
image_path.display()
954+
)
955+
})?;
956+
parse_sandbox_guest_user_ids(&passwd, &image_path.display().to_string())
983957
}
958+
Ok(output) => Err(format!(
959+
"debugfs command '{command}' failed for {}: debugfs failed with status {}\nstdout: {}\nstderr: {}. Install e2fsprogs (debugfs) and retry",
960+
image_path.display(),
961+
output.status,
962+
String::from_utf8_lossy(&output.stdout),
963+
String::from_utf8_lossy(&output.stderr)
964+
)),
965+
Err(error) => Err(format!(
966+
"debugfs command '{command}' failed for {}: {error}. Install e2fsprogs (debugfs) and retry",
967+
image_path.display()
968+
)),
984969
}
985-
986-
Err(format!(
987-
"debugfs command '{command}' failed for {}: {}. Install e2fsprogs (debugfs) and retry",
988-
image_path.display(),
989-
last_error.unwrap_or_else(|| "debugfs not found".to_string())
990-
))
991970
}
992971

993972
fn sandbox_guest_user_ids(rootfs: &Path) -> Result<Option<(u32, u32)>, String> {
@@ -1037,92 +1016,82 @@ fn run_debugfs_batch(image_path: &Path, commands: &[String]) -> Result<(), Strin
10371016
}
10381017

10391018
fn run_debugfs_batch_file(image_path: &Path, command_path: &Path) -> Result<(), String> {
1040-
let mut last_error = None;
1041-
for candidate in e2fs_tool_candidates("debugfs") {
1042-
let label = candidate.display().to_string();
1043-
let output = Command::new(&candidate)
1044-
.arg("-w")
1045-
.arg("-f")
1046-
.arg(command_path)
1047-
.arg(image_path)
1048-
.output();
1049-
match output {
1050-
Ok(output) if output.status.success() => return Ok(()),
1051-
Ok(output) => {
1052-
last_error = Some(format!(
1053-
"{label} failed with status {}\nstdout: {}\nstderr: {}",
1054-
output.status,
1055-
String::from_utf8_lossy(&output.stdout),
1056-
String::from_utf8_lossy(&output.stderr)
1057-
));
1058-
}
1059-
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
1060-
last_error = Some(format!("{label} not found"));
1061-
}
1062-
Err(err) => {
1063-
last_error = Some(format!("run {label}: {err}"));
1064-
}
1065-
}
1019+
let output = e2fs_command("debugfs")?
1020+
.arg("-w")
1021+
.arg("-f")
1022+
.arg(command_path)
1023+
.arg(image_path)
1024+
.output();
1025+
match output {
1026+
Ok(output) if output.status.success() => Ok(()),
1027+
Ok(output) => Err(format!(
1028+
"debugfs batch {} failed for {}: debugfs failed with status {}\nstdout: {}\nstderr: {}. Install e2fsprogs (debugfs) and retry",
1029+
command_path.display(),
1030+
image_path.display(),
1031+
output.status,
1032+
String::from_utf8_lossy(&output.stdout),
1033+
String::from_utf8_lossy(&output.stderr)
1034+
)),
1035+
Err(error) => Err(format!(
1036+
"debugfs batch {} failed for {}: {error}. Install e2fsprogs (debugfs) and retry",
1037+
command_path.display(),
1038+
image_path.display()
1039+
)),
10661040
}
1067-
Err(format!(
1068-
"debugfs batch {} failed for {}: {}. Install e2fsprogs (debugfs) and retry",
1069-
command_path.display(),
1070-
image_path.display(),
1071-
last_error.unwrap_or_else(|| "debugfs not found".to_string())
1072-
))
10731041
}
10741042

10751043
fn run_debugfs(image_path: &Path, command: &str) -> Result<(), String> {
1076-
let mut last_error = None;
1077-
for candidate in e2fs_tool_candidates("debugfs") {
1078-
let label = candidate.display().to_string();
1079-
let output = Command::new(&candidate)
1080-
.arg("-w")
1081-
.arg("-R")
1082-
.arg(command)
1083-
.arg(image_path)
1084-
.output();
1085-
match output {
1086-
Ok(output) if output.status.success() => return Ok(()),
1087-
Ok(output) => {
1088-
last_error = Some(format!(
1089-
"{label} failed with status {}\nstdout: {}\nstderr: {}",
1090-
output.status,
1091-
String::from_utf8_lossy(&output.stdout),
1092-
String::from_utf8_lossy(&output.stderr)
1093-
));
1094-
}
1095-
Err(err) if err.kind() == std::io::ErrorKind::NotFound => {
1096-
last_error = Some(format!("{label} not found"));
1097-
}
1098-
Err(err) => {
1099-
last_error = Some(format!("run {label}: {err}"));
1100-
}
1101-
}
1044+
let output = e2fs_command("debugfs")?
1045+
.arg("-w")
1046+
.arg("-R")
1047+
.arg(command)
1048+
.arg(image_path)
1049+
.output();
1050+
match output {
1051+
Ok(output) if output.status.success() => Ok(()),
1052+
Ok(output) => Err(format!(
1053+
"debugfs command '{command}' failed for {}: debugfs failed with status {}\nstdout: {}\nstderr: {}. Install e2fsprogs (debugfs) and retry",
1054+
image_path.display(),
1055+
output.status,
1056+
String::from_utf8_lossy(&output.stdout),
1057+
String::from_utf8_lossy(&output.stderr)
1058+
)),
1059+
Err(error) => Err(format!(
1060+
"debugfs command '{command}' failed for {}: {error}. Install e2fsprogs (debugfs) and retry",
1061+
image_path.display()
1062+
)),
11021063
}
1103-
Err(format!(
1104-
"debugfs command '{command}' failed for {}: {}. Install e2fsprogs (debugfs) and retry",
1105-
image_path.display(),
1106-
last_error.unwrap_or_else(|| "debugfs not found".to_string())
1107-
))
11081064
}
11091065

1110-
/// Resolve the places an e2fsprogs binary may live, starting with `PATH`.
1111-
///
1112-
/// Distributions install `mke2fs`, `e2fsck`, and `debugfs` under `/usr/sbin`
1113-
/// or `/sbin`, which most Linux hosts leave out of a non-root user's `PATH`,
1114-
/// so those directories are probed explicitly. Homebrew keeps e2fsprogs
1115-
/// keg-only on macOS, so its prefixes are probed as well.
1116-
fn e2fs_tool_candidates(tool: &str) -> Vec<PathBuf> {
1117-
let mut candidates = vec![PathBuf::from(tool)];
1118-
for dir in ["/usr/local/sbin", "/usr/sbin", "/sbin"] {
1119-
candidates.push(Path::new(dir).join(tool));
1120-
}
1121-
for root in ["/opt/homebrew/opt/e2fsprogs", "/usr/local/opt/e2fsprogs"] {
1122-
candidates.push(Path::new(root).join("sbin").join(tool));
1123-
candidates.push(Path::new(root).join("bin").join(tool));
1124-
}
1125-
candidates
1066+
fn e2fs_command(tool: impl AsRef<OsStr>) -> Result<Command, String> {
1067+
let path = e2fs_search_path(std::env::var_os("PATH").as_deref())?;
1068+
let mut command = Command::new(tool);
1069+
command.env("PATH", path);
1070+
Ok(command)
1071+
}
1072+
1073+
fn e2fs_search_path(existing: Option<&OsStr>) -> Result<OsString, String> {
1074+
let mut paths = existing
1075+
.map(std::env::split_paths)
1076+
.into_iter()
1077+
.flatten()
1078+
.collect::<Vec<_>>();
1079+
1080+
#[cfg(target_os = "linux")]
1081+
paths.extend(["/usr/local/sbin", "/usr/sbin", "/sbin"].map(PathBuf::from));
1082+
1083+
#[cfg(target_os = "macos")]
1084+
paths.extend(
1085+
[
1086+
"/opt/homebrew/opt/e2fsprogs/sbin",
1087+
"/opt/homebrew/opt/e2fsprogs/bin",
1088+
"/usr/local/opt/e2fsprogs/sbin",
1089+
"/usr/local/opt/e2fsprogs/bin",
1090+
]
1091+
.map(PathBuf::from),
1092+
);
1093+
1094+
std::env::join_paths(paths).map_err(|error| format!("construct e2fsprogs PATH: {error}"))
11261095
}
11271096

11281097
fn temporary_injection_path(image_path: &Path) -> PathBuf {
@@ -1567,10 +1536,15 @@ mod tests {
15671536

15681537
#[test]
15691538
fn recover_rootfs_image_accepts_clean_ext4_image() {
1570-
if !e2fs_tool_candidates("e2fsck")
1571-
.iter()
1572-
.any(|candidate| Command::new(candidate).arg("-V").output().is_ok())
1573-
{
1539+
let available = e2fs_command("e2fsck")
1540+
.and_then(|mut command| {
1541+
command
1542+
.arg("-V")
1543+
.output()
1544+
.map_err(|error| error.to_string())
1545+
})
1546+
.is_ok();
1547+
if !available {
15741548
return;
15751549
}
15761550

@@ -1678,17 +1652,31 @@ mod tests {
16781652
}
16791653

16801654
#[test]
1681-
fn e2fs_tool_candidates_probe_path_then_system_sbin_directories() {
1682-
let candidates = e2fs_tool_candidates("mke2fs");
1683-
1684-
assert_eq!(candidates.first(), Some(&PathBuf::from("mke2fs")));
1685-
for expected in ["/usr/local/sbin/mke2fs", "/usr/sbin/mke2fs", "/sbin/mke2fs"] {
1686-
assert!(
1687-
candidates.contains(&PathBuf::from(expected)),
1688-
"expected {expected} in {candidates:?}"
1689-
);
1690-
}
1691-
assert!(candidates.contains(&PathBuf::from("/opt/homebrew/opt/e2fsprogs/sbin/mke2fs")));
1655+
fn e2fs_search_path_preserves_path_before_platform_fallbacks() {
1656+
let search_path = e2fs_search_path(Some(OsStr::new("/custom/bin")))
1657+
.expect("construct e2fsprogs search path");
1658+
let paths = std::env::split_paths(&search_path).collect::<Vec<_>>();
1659+
1660+
assert_eq!(paths.first(), Some(&PathBuf::from("/custom/bin")));
1661+
#[cfg(target_os = "linux")]
1662+
assert_eq!(
1663+
&paths[1..],
1664+
[
1665+
PathBuf::from("/usr/local/sbin"),
1666+
PathBuf::from("/usr/sbin"),
1667+
PathBuf::from("/sbin"),
1668+
]
1669+
);
1670+
#[cfg(target_os = "macos")]
1671+
assert_eq!(
1672+
&paths[1..],
1673+
[
1674+
PathBuf::from("/opt/homebrew/opt/e2fsprogs/sbin"),
1675+
PathBuf::from("/opt/homebrew/opt/e2fsprogs/bin"),
1676+
PathBuf::from("/usr/local/opt/e2fsprogs/sbin"),
1677+
PathBuf::from("/usr/local/opt/e2fsprogs/bin"),
1678+
]
1679+
);
16921680
}
16931681

16941682
#[test]

0 commit comments

Comments
 (0)