Skip to content

Commit

Permalink
Merge pull request nokyan#197 from nokyan/user-names-fix
Browse files Browse the repository at this point in the history
User names fix
  • Loading branch information
nokyan authored Apr 11, 2024
2 parents eacf7a2 + 344df1d commit 2b53298
Show file tree
Hide file tree
Showing 9 changed files with 48 additions and 66 deletions.
2 changes: 1 addition & 1 deletion Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 0 additions & 1 deletion Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ sysconf = "0.3.4"
nvml-wrapper = "0.10.0"
unescape = "0.1.0"
nix = { version = "0.28", features = ["signal"] }
uzers = "0.11.3"
plotters = { version = "0.3.5", default_features = false, features = [
"area_series",
] }
Expand Down
36 changes: 18 additions & 18 deletions lib/process_data/Cargo.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions lib/process_data/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -23,3 +23,4 @@ serde = { version = "1.0.180", features = ["serde_derive"] }
nvml-wrapper = "0.9.0"
syscalls = { version = "0.6.15", features = ["all"] }
libc = "0.2.150"
uzers = "0.11.3"
34 changes: 22 additions & 12 deletions lib/process_data/src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,10 +14,17 @@ use std::collections::{BTreeMap, HashMap, HashSet};
use std::fs::File;
use std::io::{Read, Write};
use std::os::linux::fs::MetadataExt;
use std::path::Path;
use std::str::FromStr;
use std::sync::RwLock;
use std::{path::PathBuf, time::SystemTime};

static USERS_CACHE: Lazy<HashMap<u32, String>> = Lazy::new(|| unsafe {
uzers::all_users()
.map(|user| (user.uid(), user.name().to_string_lossy().to_string()))
.collect()
});

static PAGESIZE: Lazy<usize> = Lazy::new(sysconf::pagesize);

static RE_UID: Lazy<Regex> = Lazy::new(|| Regex::new(r"Uid:\s*(\d+)").unwrap());
Expand Down Expand Up @@ -122,7 +129,7 @@ pub struct GpuUsageStats {
#[derive(Debug, Default, Clone, Hash, PartialEq, Eq, Serialize, Deserialize)]
pub struct ProcessData {
pub pid: i32,
pub uid: u32,
pub user: String,
proc_path: PathBuf,
pub comm: String,
pub commandline: String,
Expand Down Expand Up @@ -174,7 +181,7 @@ impl ProcessData {
}
}

fn get_uid(proc_path: &PathBuf) -> Result<u32> {
fn get_uid(proc_path: &Path) -> Result<u32> {
let status = std::fs::read_to_string(proc_path.join("status"))?;
if let Some(captures) = RE_UID.captures(&status) {
let first_num_str = captures.get(1).context("no uid found")?;
Expand Down Expand Up @@ -216,12 +223,12 @@ impl ProcessData {
}

pub fn try_from_path(proc_path: PathBuf) -> Result<Self> {
let stat = std::fs::read_to_string(&proc_path.join("stat"))?;
let statm = std::fs::read_to_string(&proc_path.join("statm"))?;
let comm = std::fs::read_to_string(&proc_path.join("comm"))?;
let commandline = std::fs::read_to_string(&proc_path.join("cmdline"))?;
let cgroup = std::fs::read_to_string(&proc_path.join("cgroup"))?;
let io = std::fs::read_to_string(&proc_path.join("io")).ok();
let stat = std::fs::read_to_string(proc_path.join("stat"))?;
let statm = std::fs::read_to_string(proc_path.join("statm"))?;
let comm = std::fs::read_to_string(proc_path.join("comm"))?;
let commandline = std::fs::read_to_string(proc_path.join("cmdline"))?;
let cgroup = std::fs::read_to_string(proc_path.join("cgroup"))?;
let io = std::fs::read_to_string(proc_path.join("io")).ok();

let pid = proc_path
.file_name()
Expand All @@ -230,7 +237,10 @@ impl ProcessData {
.context("can't turn OsStr to str")?
.parse()?;

let uid = Self::get_uid(&proc_path)?;
let user = USERS_CACHE
.get(&Self::get_uid(&proc_path)?)
.cloned()
.unwrap_or(String::from("root"));

let stat = stat
.split(')') // since we don't care about the pid or the executable name, split after the executable name to make our life easier
Expand Down Expand Up @@ -284,7 +294,7 @@ impl ProcessData {

Ok(Self {
pid,
uid,
user,
comm,
commandline,
user_cpu_time,
Expand All @@ -305,12 +315,12 @@ impl ProcessData {
fn gpu_usage_stats(proc_path: &PathBuf, pid: i32) -> BTreeMap<PciSlot, GpuUsageStats> {
let nvidia_stats = Self::nvidia_gpu_stats_all(pid).unwrap_or_default();
let mut other_stats = Self::other_gpu_usage_stats(proc_path, pid).unwrap_or_default();
other_stats.extend(nvidia_stats.into_iter());
other_stats.extend(nvidia_stats);
other_stats
}

fn other_gpu_usage_stats(
proc_path: &PathBuf,
proc_path: &Path,
pid: i32,
) -> Result<BTreeMap<PciSlot, GpuUsageStats>> {
let fdinfo_dir = proc_path.join("fdinfo");
Expand Down
32 changes: 2 additions & 30 deletions src/ui/pages/processes/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ use self::process_name_cell::ResProcessNameCell;
mod imp {
use std::{
cell::{Cell, RefCell},
collections::HashMap,
sync::OnceLock,
};

Expand Down Expand Up @@ -66,8 +65,6 @@ mod imp {
pub column_view: RefCell<gtk::ColumnView>,
pub open_dialog: RefCell<Option<(i32, ResProcessDialog)>>,

pub username_cache: RefCell<HashMap<u32, String>>,

pub sender: OnceLock<Sender<Action>>,

pub popped_over_process: RefCell<Option<ProcessEntry>>,
Expand Down Expand Up @@ -151,7 +148,6 @@ mod imp {
sort_model: Default::default(),
column_view: Default::default(),
open_dialog: Default::default(),
username_cache: Default::default(),
sender: Default::default(),
uses_progress_bar: Cell::new(false),
icon: RefCell::new(ThemedIcon::new("generic-process-symbolic").into()),
Expand Down Expand Up @@ -471,7 +467,7 @@ impl ResProcesses {
pub fn open_information_dialog(&self, process: &ProcessItem) {
let imp = self.imp();
let process_dialog = ResProcessDialog::new();
process_dialog.init(process, self.get_user_name_by_uid(process.uid));
process_dialog.init(process, &process.user);
process_dialog.present(&MainWindow::default());
*imp.open_dialog.borrow_mut() = Some((process.pid, process_dialog));
}
Expand Down Expand Up @@ -534,10 +530,7 @@ impl ResProcesses {
// add the newly started process to the store
let items: Vec<ProcessEntry> = new_items
.drain()
.map(|(_, new_item)| {
let user_name = self.get_user_name_by_uid(new_item.uid);
ProcessEntry::new(new_item, &user_name)
})
.map(|(_, new_item)| ProcessEntry::new(new_item))
.collect();
store.extend_from_slice(&items);

Expand Down Expand Up @@ -596,27 +589,6 @@ impl ResProcesses {
dialog.present(&MainWindow::default());
}

fn get_user_name_by_uid(&self, uid: u32) -> String {
let imp = self.imp();

// we do this to avoid mut-borrows when possible
let cached = {
let borrow = imp.username_cache.borrow();
borrow.get(&uid).cloned()
};

if let Some(cached) = cached {
cached
} else {
let name = uzers::get_user_by_uid(uid).map_or_else(
|| i18n("root"),
|user| user.name().to_string_lossy().to_string(),
);
imp.username_cache.borrow_mut().insert(uid, name.clone());
name
}
}

fn add_name_column(&self, column_view: &ColumnView) -> ColumnViewColumn {
let name_col_factory = gtk::SignalListItemFactory::new();

Expand Down
4 changes: 2 additions & 2 deletions src/ui/pages/processes/process_entry.rs
Original file line number Diff line number Diff line change
Expand Up @@ -179,11 +179,11 @@ glib::wrapper! {
}

impl ProcessEntry {
pub fn new(process_item: ProcessItem, user: &str) -> Self {
pub fn new(process_item: ProcessItem) -> Self {
let this: Self = glib::Object::builder()
.property("name", &process_item.display_name)
.property("commandline", &process_item.commandline)
.property("user", user)
.property("user", &process_item.user)
.property("icon", &process_item.icon)
.property("pid", process_item.pid)
.build();
Expand Down
2 changes: 1 addition & 1 deletion src/utils/app.rs
Original file line number Diff line number Diff line change
Expand Up @@ -613,6 +613,7 @@ impl AppsContext {
};
ProcessItem {
pid: process.data.pid,
user: process.data.user.clone(),
display_name: full_comm.clone(),
icon: process.icon.clone(),
memory_usage: process.data.memory_usage,
Expand All @@ -624,7 +625,6 @@ impl AppsContext {
containerization: process.data.containerization,
starttime: process.starttime(),
cgroup: process.data.cgroup.clone(),
uid: process.data.uid,
read_speed: process.read_speed(),
read_total: process.data.read_bytes,
write_speed: process.write_speed(),
Expand Down
2 changes: 1 addition & 1 deletion src/utils/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -76,7 +76,7 @@ pub enum ProcessAction {
#[derive(Debug, Clone)]
pub struct ProcessItem {
pub pid: i32,
pub uid: u32,
pub user: String,
pub display_name: String,
pub icon: Icon,
pub memory_usage: usize,
Expand Down

0 comments on commit 2b53298

Please sign in to comment.