Skip to content
New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Introduce ProcessRefreshKind::tasks #1436

Merged
merged 20 commits into from
Jan 31, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
53 changes: 47 additions & 6 deletions src/common/system.rs
Original file line number Diff line number Diff line change
Expand Up @@ -263,7 +263,7 @@ impl System {
self.inner.refresh_cpu_specifics(refresh_kind)
}

/// Gets all processes and updates their information.
/// Gets all processes and updates their information, along with all the tasks each process has.
///
/// It does the same as:
///
Expand All @@ -277,7 +277,7 @@ impl System {
/// .with_memory()
/// .with_cpu()
/// .with_disk_usage()
/// .with_exe(UpdateKind::OnlyIfNotSet),
/// .with_exe(UpdateKind::OnlyIfNotSet)
/// );
/// ```
///
Expand All @@ -288,6 +288,11 @@ impl System {
/// ⚠️ On Linux, `sysinfo` keeps the `stat` files open by default. You can change this behaviour
/// by using [`set_open_files_limit`][crate::set_open_files_limit].
///
/// ⚠️ On Linux, if you dont need the tasks of each process, you can use
/// `refresh_processes_specifics` with `ProcessRefreshKind::everything().without_tasks()`.
/// Refreshesing all processes and their tasks can be quite expensive. For more information
/// see [`ProcessRefreshKind`].
///
/// Example:
///
/// ```no_run
Expand All @@ -308,7 +313,8 @@ impl System {
.with_memory()
.with_cpu()
.with_disk_usage()
.with_exe(UpdateKind::OnlyIfNotSet),
.with_exe(UpdateKind::OnlyIfNotSet)
.with_tasks(),
)
}

Expand Down Expand Up @@ -1868,6 +1874,15 @@ pub enum ProcessesToUpdate<'a> {
/// the information won't be retrieved if the information is accessible without needing
/// extra computation.
///
/// ⚠️ ** Linux Specific ** ⚠️
/// When using `ProcessRefreshKind::everything()`, in linux we will fetch all relevant
/// information from `/proc/<pid>/` as well as all the information from `/proc/<pid>/task/<tid>/`
/// folders. This makes the refresh mechanism a lot slower depending on the number of tasks
/// each process has.
///
/// If you don't care about tasks information, use `ProcessRefreshKind::everything().without_tasks()`
/// as much as possible.
///
/// ```
/// use sysinfo::{ProcessesToUpdate, ProcessRefreshKind, System};
///
Expand All @@ -1887,7 +1902,7 @@ pub enum ProcessesToUpdate<'a> {
/// ```
///
/// [`Process`]: crate::Process
#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct ProcessRefreshKind {
cpu: bool,
disk_usage: bool,
Expand All @@ -1898,11 +1913,35 @@ pub struct ProcessRefreshKind {
environ: UpdateKind,
cmd: UpdateKind,
exe: UpdateKind,
tasks: bool,
}

/// Creates a new `ProcessRefreshKind` with every refresh set to `false`, except for `tasks`.
/// By default, we want to list all processes and tasks are considered processes on their own
/// in linux so we still fetch them by default. However, the processes information are not
/// refreshed.
impl Default for ProcessRefreshKind {
fn default() -> Self {
Self {
cpu: false,
disk_usage: false,
memory: false,
user: UpdateKind::default(),
cwd: UpdateKind::default(),
root: UpdateKind::default(),
environ: UpdateKind::default(),
cmd: UpdateKind::default(),
exe: UpdateKind::default(),
tasks: true, // Process by default includes all tasks.
}
}
}

impl ProcessRefreshKind {
/// Creates a new `ProcessRefreshKind` with every refresh set to `false`.
///
/// Creates a new `ProcessRefreshKind` with every refresh set to `false`, except for `tasks`.
/// By default, we want to list all processes and tasks are considered processes on their own
/// in linux so we still fetch them by default. However, the processes information are not
/// refreshed.
/// ```
/// use sysinfo::{ProcessRefreshKind, UpdateKind};
///
Expand Down Expand Up @@ -1937,6 +1976,7 @@ impl ProcessRefreshKind {
environ: UpdateKind::OnlyIfNotSet,
cmd: UpdateKind::OnlyIfNotSet,
exe: UpdateKind::OnlyIfNotSet,
tasks: true,
}
}

Expand Down Expand Up @@ -1986,6 +2026,7 @@ It will retrieve the following information:
);
impl_get_set!(ProcessRefreshKind, cmd, with_cmd, without_cmd, UpdateKind);
impl_get_set!(ProcessRefreshKind, exe, with_exe, without_exe, UpdateKind);
impl_get_set!(ProcessRefreshKind, tasks, with_tasks, without_tasks);
}

/// Used to determine what you want to refresh specifically on the [`Cpu`] type.
Expand Down
25 changes: 14 additions & 11 deletions src/unix/linux/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -664,6 +664,7 @@ fn get_all_pid_entries(
parent_pid: Option<Pid>,
entry: DirEntry,
data: &mut Vec<ProcAndTasks>,
enable_task_stats: bool,
) -> Option<Pid> {
let Ok(file_type) = entry.file_type() else {
return None;
Expand All @@ -682,17 +683,19 @@ fn get_all_pid_entries(
let name = name?;
let pid = Pid::from(usize::from_str(name.to_str()?).ok()?);

let tasks_dir = Path::join(&entry, "task");

let tasks = if let Ok(entries) = fs::read_dir(tasks_dir) {
let mut tasks = HashSet::new();
for task in entries
.into_iter()
.filter_map(|entry| get_all_pid_entries(Some(name), Some(pid), entry.ok()?, data))
{
tasks.insert(task);
let tasks = if enable_task_stats {
let tasks_dir = Path::join(&entry, "task");
if let Ok(entries) = fs::read_dir(tasks_dir) {
let mut tasks = HashSet::new();
for task in entries.into_iter().filter_map(|entry| {
get_all_pid_entries(Some(name), Some(pid), entry.ok()?, data, enable_task_stats)
}) {
tasks.insert(task);
}
Some(tasks)
} else {
None
}
Some(tasks)
} else {
None
};
Expand Down Expand Up @@ -777,7 +780,7 @@ pub(crate) fn refresh_procs(
.map(|entry| {
let Ok(entry) = entry else { return Vec::new() };
let mut entries = Vec::new();
get_all_pid_entries(None, None, entry, &mut entries);
get_all_pid_entries(None, None, entry, &mut entries, refresh_kind.tasks());
entries
})
.flatten()
Expand Down
138 changes: 99 additions & 39 deletions tests/process.rs
Original file line number Diff line number Diff line change
Expand Up @@ -416,55 +416,115 @@ fn test_refresh_process_doesnt_remove() {
not(feature = "unknown-ci")
))]
fn test_refresh_tasks() {
// Skip if unsupported.
if !sysinfo::IS_SUPPORTED_SYSTEM || cfg!(feature = "apple-sandbox") {
return;
}
let task_name = "task_1_second";

// 1) Spawn a thread that waits on a channel, so we control when it exits.
let task_name = "controlled_test_thread";
let (tx, rx) = std::sync::mpsc::channel::<()>();

std::thread::Builder::new()
.name(task_name.into())
.spawn(|| {
std::thread::sleep(std::time::Duration::from_secs(1));
.name(task_name.to_string())
.spawn(move || {
// Wait until the main thread signals we can exit.
let _ = rx.recv();
})
.unwrap();

let pid = Pid::from_u32(std::process::id() as _);
let mut sys = System::new();

// Wait until the new thread shows up in the process/tasks list.
// We do a short loop and check each time by refreshing processes.
const MAX_POLLS: usize = 20;
const POLL_INTERVAL: std::time::Duration = std::time::Duration::from_millis(100);

for _ in 0..MAX_POLLS {
sys.refresh_processes(ProcessesToUpdate::All, /*refresh_users=*/ false);

// Check if our thread is present in two ways:
// (a) via parent's tasks
// (b) by exact name
let parent_proc = sys.process(pid);
let tasks_contain_thread = parent_proc
.and_then(|p| p.tasks())
.map(|tids| {
tids.iter().any(|tid| {
sys.process(*tid)
.map(|t| t.name() == task_name)
.unwrap_or(false)
})
})
.unwrap_or(false);

let by_exact_name_exists = sys
.processes_by_exact_name(task_name.as_ref())
.next()
.is_some();

if tasks_contain_thread && by_exact_name_exists {
// We confirmed the thread is now visible
break;
}
std::thread::sleep(POLL_INTERVAL);
}

// Checks that the task is listed as it should.
let mut s = System::new();
s.refresh_processes(ProcessesToUpdate::All, false);

assert!(s
.process(pid)
.unwrap()
.tasks()
.map(|tasks| tasks.iter().any(|task_pid| s
.process(*task_pid)
.map(|task| task.name() == task_name)
.unwrap_or(false)))
.unwrap_or(false));
assert!(s
.processes_by_exact_name(task_name.as_ref())
.next()
.is_some());

// Let's give some time to the system to clean up...
std::thread::sleep(std::time::Duration::from_secs(2));

s.refresh_processes(ProcessesToUpdate::All, true);
// At this point we know the task is visible in the system's process/tasks list.
// Let's validate a few more things:
// * ProcessRefreshKind::nothing() should have task information.
// * ProcessRefreshKind::nothing().with_tasks() should have task information.
// * ProcessRefreshKind::nothing().without_tasks() shouldn't have task information.
// * ProcessRefreshKind::everything() should have task information.
// * ProcessRefreshKind::everything() should have task information.
// * ProcessRefreshKind::everything().without_tasks() should not have task information.

let expectations = [
(ProcessRefreshKind::nothing(), true),
(ProcessRefreshKind::nothing().with_tasks(), true),
(ProcessRefreshKind::nothing().without_tasks(), false),
(ProcessRefreshKind::everything(), true),
(ProcessRefreshKind::everything().with_tasks(), true),
(ProcessRefreshKind::everything().without_tasks(), false),
];
for (kind, expect_tasks) in expectations.iter() {
let mut sys_new = System::new();
sys_new.refresh_processes_specifics(ProcessesToUpdate::All, true, *kind);
let proc = sys_new.process(pid).unwrap();
assert_eq!(proc.tasks().is_some(), *expect_tasks);
}

assert!(!s
.process(pid)
.unwrap()
.tasks()
.map(|tasks| tasks.iter().any(|task_pid| s
.process(*task_pid)
.map(|task| task.name() == task_name)
.unwrap_or(false)))
.unwrap_or(false));
assert!(s
.processes_by_exact_name(task_name.as_ref())
.next()
.is_none());
// 3) Signal the thread to exit.
drop(tx);

// 4) Wait until the thread is gone from the system’s process/tasks list.
for _ in 0..MAX_POLLS {
sys.refresh_processes(ProcessesToUpdate::All, /*refresh_users=*/ true);

let parent_proc = sys.process(pid as sysinfo::Pid);
let tasks_contain_thread = parent_proc
.and_then(|p| p.tasks())
.map(|tids| {
tids.iter().any(|tid| {
sys.process(*tid)
.map(|t| t.name() == task_name)
.unwrap_or(false)
})
})
.unwrap_or(false);

let by_exact_name_exists = sys
.processes_by_exact_name(task_name.as_ref())
.next()
.is_some();

// If it's gone from both checks, we're good.
if !tasks_contain_thread && !by_exact_name_exists {
break;
}
std::thread::sleep(POLL_INTERVAL);
}
}

// Checks that `refresh_process` is removing dead processes when asked.
Expand Down