Debian Codegraph @

debian/rust-vendor/procfs/src/process/namespaces.rs

raw
1 use super::Process;
2 use crate::{build_internal_error, ProcResult};
3 use procfs_core::process::{Namespace, Namespaces};
4 use rustix::fs::{AtFlags, Mode, OFlags};
5 use std::{collections::HashMap, ffi::OsString};
6
7 impl Process {
8 /// Describes namespaces to which the process with the corresponding PID belongs.
9 /// Doc reference: <https://man7.org/linux/man-pages/man7/namespaces.7.html>
10 /// The namespace type is the key for the HashMap, i.e 'net', 'user', etc.
11 pub fn namespaces(&self) -> ProcResult<Namespaces> {
12 let mut namespaces = HashMap::new();
13 let dir_ns = wrap_io_error!(
14 self.root.join("ns"),
15 rustix::fs::openat(
16 &self.fd,
17 "ns",
18 OFlags::RDONLY | OFlags::DIRECTORY | OFlags::CLOEXEC,
19 Mode::empty()
20 )
21 )?;
22 let dir = wrap_io_error!(self.root.join("ns"), rustix::fs::Dir::read_from(&dir_ns))?;
23 for entry in dir {
24 let entry = entry.map_err(|_| build_internal_error!(format!("Unable to get ns dir entry")))?;
25 match entry.file_name().to_bytes() {
26 b"." | b".." => continue,
27 _ => {}
28 };
29
30 let path = self.root.join("ns").join(entry.file_name().to_string_lossy().as_ref());
31 let ns_type = OsString::from(entry.file_name().to_string_lossy().as_ref());
32 let stat = rustix::fs::statat(&dir_ns, entry.file_name(), AtFlags::empty())
33 .map_err(|_| build_internal_error!(format!("Unable to stat {:?}", path)))?;
34
35 if let Some(n) = namespaces.insert(
36 ns_type.clone(),
37 Namespace {
38 ns_type,
39 path,
40 identifier: stat.st_ino,
41 device_id: stat.st_dev,
42 },
43 ) {
44 return Err(build_internal_error!(format!(
45 "NsType appears more than once {:?}",
46 n.ns_type
47 )));
48 }
49 }
50
51 Ok(Namespaces(namespaces))
52 }
53 }
54
55 #[cfg(test)]
56 mod tests {
57 use crate::process::Process;
58
59 #[test]
60 fn test_namespaces() {
61 let myself = Process::myself().unwrap();
62 let namespaces = myself.namespaces().unwrap();
63 print!("{:?}", namespaces);
64 }
65 }