use std::path::Path;
use std::process::{Command, Stdio};
use crate::model::{Icon, Item, ItemKey, Source};
const RESULTS: usize = 12;
#[derive(Debug, Clone)]
struct Process {
pid: u32,
name: String,
cmdline: String,
rss: u64,
}
#[must_use]
pub fn matching(needle: &str) -> Vec<Item> {
let needle = needle.to_lowercase();
let tokens: Vec<&str> = needle.split_whitespace().collect();
let mut processes: Vec<Process> = list()
.into_iter()
.filter(|process| {
let haystack = format!(
"{} {} {}",
process.name.to_lowercase(),
process.cmdline.to_lowercase(),
process.pid
);
tokens.iter().all(|token| haystack.contains(token))
})
.collect();
processes.sort_by_key(|process| std::cmp::Reverse(process.rss));
processes.truncate(RESULTS);
processes
.into_iter()
.map(|process| Item {
key: ItemKey(format!("process:{}", process.name)),
id: 0,
title: process.name,
subtitle: format!(
"PID {} · {} · {}",
process.pid,
human_bytes(process.rss),
truncate(&process.cmdline, 80),
),
icon: Some(Icon::Name("utilities-system-monitor-symbolic".to_owned())),
category_icon: None,
window: None,
source: Source::Process { pid: process.pid },
autocomplete: None,
score: 0.0,
})
.collect()
}
pub fn terminate(pid: u32, force: bool) {
let signal = if force { "-KILL" } else { "-TERM" };
let result = Command::new("kill")
.arg(signal)
.arg(pid.to_string())
.stdin(Stdio::null())
.stdout(Stdio::null())
.stderr(Stdio::null())
.status();
match result {
Ok(status) if status.success() => {}
Ok(status) => tracing::warn!(pid, ?status, "kill refused; process may have exited"),
Err(error) => tracing::error!(pid, %error, "could not run kill"),
}
}
fn list() -> Vec<Process> {
use std::os::unix::fs::MetadataExt;
let uid = effective_uid();
let own_pid = std::process::id();
let Ok(entries) = std::fs::read_dir("/proc") else {
return Vec::new();
};
entries
.flatten()
.filter_map(|entry| {
let pid: u32 = entry.file_name().to_str()?.parse().ok()?;
if pid == own_pid {
return None;
}
let metadata = entry.metadata().ok()?;
if u64::from(metadata.uid()) != uid {
return None;
}
let path = entry.path();
read_process(&path, pid)
})
.collect()
}
fn read_process(path: &Path, pid: u32) -> Option<Process> {
let cmdline_raw = std::fs::read(path.join("cmdline")).ok()?;
if cmdline_raw.is_empty() {
return None;
}
let cmdline: String = cmdline_raw
.split(|byte| *byte == 0)
.filter(|part| !part.is_empty())
.map(|part| String::from_utf8_lossy(part).into_owned())
.collect::<Vec<_>>()
.join(" ");
let name = std::fs::read_to_string(path.join("comm"))
.ok()?
.trim()
.to_owned();
let rss = std::fs::read_to_string(path.join("statm"))
.ok()
.and_then(|statm| {
statm
.split_whitespace()
.nth(1)
.and_then(|pages| pages.parse::<u64>().ok())
})
.map_or(0, |pages| pages * 4096);
Some(Process {
pid,
name,
cmdline,
rss,
})
}
fn effective_uid() -> u64 {
std::fs::read_to_string("/proc/self/status")
.ok()
.and_then(|status| {
status.lines().find_map(|line| {
let rest = line.strip_prefix("Uid:")?;
rest.split_whitespace().nth(1)?.parse().ok()
})
})
.unwrap_or(u64::MAX)
}
fn human_bytes(bytes: u64) -> String {
const MB: u64 = 1024 * 1024;
const GB: u64 = 1024 * MB;
if bytes >= GB {
format!("{:.1} GB", bytes as f64 / GB as f64)
} else {
format!("{} MB", bytes / MB)
}
}
fn truncate(text: &str, limit: usize) -> String {
if text.chars().count() <= limit {
text.to_owned()
} else {
let cut: String = text.chars().take(limit).collect();
format!("{cut}…")
}
}
#[cfg(test)]
mod tests {
use super::*;
use std::time::{Duration, Instant};
#[test]
fn finds_and_terminates_a_real_process() {
let mut child = Command::new("sleep")
.arg("300")
.stdin(Stdio::null())
.stdout(Stdio::null())
.spawn()
.expect("spawn sleep");
let pid = child.id();
std::thread::sleep(Duration::from_millis(50));
let items = matching(&pid.to_string());
assert!(
items
.iter()
.any(|item| item.source == Source::Process { pid }),
"spawned process appears in the listing"
);
terminate(pid, false);
let deadline = Instant::now() + Duration::from_secs(5);
loop {
match child.try_wait().expect("try_wait") {
Some(_) => break,
None if Instant::now() > deadline => panic!("process survived SIGTERM"),
None => std::thread::sleep(Duration::from_millis(20)),
}
}
}
#[test]
fn all_tokens_must_match() {
let mut child = Command::new("sleep")
.arg("300")
.stdin(Stdio::null())
.stdout(Stdio::null())
.spawn()
.expect("spawn sleep");
let pid = child.id();
std::thread::sleep(Duration::from_millis(50));
let items = matching(&format!("sleep no-such-token-{pid}"));
assert!(items.is_empty());
terminate(pid, true);
let _ = child.wait();
}
#[test]
fn other_processes_do_not_leak_into_a_pid_query() {
assert!(matching("zzqx-definitely-not-a-process").is_empty());
}
#[test]
fn bytes_render_for_humans() {
assert_eq!(human_bytes(512 * 1024 * 1024), "512 MB");
assert_eq!(human_bytes(3 * 1024 * 1024 * 1024), "3.0 GB");
}
}