Skip to content

Commit

Permalink
Process: namespaces: Change from Vec to HashMap
Browse files Browse the repository at this point in the history
This change breaks the API for process namespaces, but it provides
a more efficent way of working with the namespaces of a process.

Signed-off-by: Jon Doron <jond@wiz.io>
  • Loading branch information
arilou committed Jul 18, 2022
1 parent 8c4292a commit 6faaeef
Showing 1 changed file with 23 additions and 8 deletions.
31 changes: 23 additions & 8 deletions src/process/namespaces.rs
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
use rustix::fs::AtFlags;
use std::{
collections::HashMap,
ffi::OsString,
fs::{self},
path::PathBuf,
Expand All @@ -12,22 +13,36 @@ use super::Process;
impl Process {
/// Describes namespaces to which the process with the corresponding PID belongs.
/// Doc reference: https://man7.org/linux/man-pages/man7/namespaces.7.html
pub fn namespaces(&self) -> ProcResult<Vec<Namespace>> {
/// The namespace type is the key for the HashMap, i.e 'net', 'user', etc.
pub fn namespaces(&self) -> ProcResult<HashMap<OsString, Namespace>> {
let ns = self.root.join("ns");
let mut namespaces = Vec::new();
let mut namespaces = HashMap::new();
for entry in fs::read_dir(ns)? {
let entry = entry?;
let path = entry.path();
let ns_type = entry.file_name();
let stat = rustix::fs::statat(&rustix::fs::cwd(), &path, AtFlags::empty())
.map_err(|_| build_internal_error!(format!("Unable to stat {:?}", path)))?;

namespaces.push(Namespace {
ns_type,
path,
identifier: stat.st_ino,
device_id: stat.st_dev,
})
namespaces
.insert(
ns_type.clone(),
Namespace {
ns_type,
path,
identifier: stat.st_ino,
device_id: stat.st_dev,
},
)
.map_or_else(
|| Ok(()),
|n| {
Err(build_internal_error!(format!(
"NsType appears more than once {:?}",
n.ns_type
)))
},
)?;
}

Ok(namespaces)
Expand Down

0 comments on commit 6faaeef

Please sign in to comment.