use crate::error::Error;
use crate::identity::pid_stat::{self, PidStat};
use crate::identity::stat_parse::parse_ppid;
use crate::identity::Kernel;
use crate::identity::RawPid;
pub(crate) fn process_parents(kernel: &dyn Kernel) -> Result<Vec<(RawPid, RawPid)>, Error> {
let mut out = Vec::new();
let dir = crate::identity::proc_view_with(kernel).into_dir().map_err(|why| {
match why.unsupported("listing the process table") {
Some(unsupported) => {
log::warn!(
"enumerate::process_parents: {report}",
report = crate::error::Report(&unsupported)
);
unsupported
}
None => unassessable(&why.reason, why.source),
}
})?;
let pids = kernel
.pids(&dir)
.map_err(|e| unassessable("/proc could not be listed", Some(e)))?;
for pid in pids {
let stat = match pid_stat::read_in_scan(kernel, &dir, pid) {
Ok(PidStat::Read(stat)) => stat,
Ok(PidStat::Skipped(e)) => {
log::debug!(
"enumerate::process_parents: {pid}/stat unreadable ({report}); omitting it",
report = crate::error::Report(&e)
);
continue;
}
Err(unreadable) => return Err(stat_unreadable(unreadable)),
};
match ppid_of_stat(pid, &stat) {
Ok(ppid) => out.push((pid, ppid)),
Err(e) => {
debug_assert!(
false,
"the kernel printed an unparseable stat: {}",
crate::error::Report(&e)
);
return Err(e);
}
}
}
Ok(out)
}
fn ppid_of_stat(pid: RawPid, stat: &[u8]) -> Result<RawPid, Error> {
parse_ppid(stat).ok_or_else(|| unassessable(&format!("{pid}/stat has no parseable ppid field"), None))
}
fn stat_unreadable(unreadable: pid_stat::Unreadable) -> Error {
snapshot_failed(
"the process snapshot could not be taken".to_owned(),
Some(std::sync::Arc::new(unreadable.into_cause())),
)
}
fn unassessable(why: &str, source: Option<std::io::Error>) -> Error {
snapshot_failed(
format!("the process snapshot could not be taken: {why}"),
source.map(Error::io_cause),
)
}
fn snapshot_failed(detail: String, source: Option<std::sync::Arc<Error>>) -> Error {
let error = Error::Unassessable { detail, source };
log::warn!("enumerate::process_parents: {}", crate::error::Report(&error));
error
}
#[cfg(test)]
#[path = "linux_tests.rs"]
mod linux_tests;
#[cfg(test)]
#[path = "linux_namespace_tests.rs"]
mod linux_namespace_tests;