use super::*;
#[derive(Debug, PartialEq)]
pub enum Why {
FileExists(String),
ProcessGone(u32),
MatchesItself(String),
}
impl Why {
fn text(&self) -> String {
match self {
Why::FileExists(f) => format!("the file it waits for already exists: {f}"),
Why::ProcessGone(p) => format!("the process it waits for (pid {p}) is gone"),
Why::MatchesItself(p) => format!("`pgrep -f {p}` matches this loop's own command line, so it never ends"),
}
}
}
fn clean(tok: &str) -> &str {
tok.trim_matches(|c| matches!(c, '"' | '\'' | ';' | '(' | ')' | '{' | '}' | '`'))
}
fn is_loop_with_poll(script: &str) -> bool {
let words: Vec<&str> = script.split(|c: char| c.is_whitespace() || c == ';').map(clean).collect();
let looped = words.iter().any(|w| matches!(*w, "until" | "while" | "for"));
let polls = script.contains("sleep ") || script.contains("tail --pid") || script.contains("pgrep");
looped && polls
}
pub fn analyze(script: &str, cwd: &str, exists: &dyn Fn(&str) -> bool, alive: &dyn Fn(u32) -> bool) -> Vec<Why> {
let mut out = Vec::new();
if !is_loop_with_poll(script) {
return out;
}
let toks: Vec<&str> = script.split_whitespace().map(clean).collect();
for (i, t) in toks.iter().enumerate() {
let next = toks.get(i + 1).copied().unwrap_or("");
match *t {
"-s" | "-e" | "-f" if i > 0 && matches!(toks[i - 1], "[" | "[[" | "test" | "!") && !next.is_empty() => {
let p = if next.starts_with('/') { next.to_string() } else { format!("{cwd}/{next}") };
if !next.contains('$') && exists(&p) {
out.push(Why::FileExists(next.to_string()));
}
}
"kill" if next == "-0" => {
if let Some(p) = toks.get(i + 2).and_then(|v| v.parse::<u32>().ok()) {
if !alive(p) {
out.push(Why::ProcessGone(p));
}
}
}
"pgrep" => {
let mut j = i + 1;
let mut full = false;
while let Some(w) = toks.get(j) {
if w.starts_with('-') {
full |= w.contains('f') && !w.starts_with("--");
j += 1;
} else {
break;
}
}
if let (true, Some(pat)) = (full, toks.get(j)) {
if !pat.is_empty() && !pat.contains('[') && !pat.contains('$') && script.matches(pat).count() >= 1 {
out.push(Why::MatchesItself(pat.to_string()));
}
}
}
_ => {
let pid = t.strip_prefix("--pid=").or_else(|| if *t == "--pid" { Some(next) } else { None });
if let Some(p) = pid.and_then(|v| v.parse::<u32>().ok()) {
if !alive(p) {
out.push(Why::ProcessGone(p));
}
}
if let Some(p) = t.strip_prefix("/proc/").and_then(|r| r.split('/').next()).and_then(|v| v.parse::<u32>().ok()) {
if !alive(p) {
out.push(Why::ProcessGone(p));
}
}
}
}
}
out
}
#[cfg(target_os = "linux")]
mod linux {
use super::*;
use std::os::unix::fs::MetadataExt;
pub struct Proc {
pub pid: u32,
pub ppid: u32,
pub start: u64,
pub args: Vec<String>,
pub cwd: String,
}
fn stat(pid: u32) -> Option<(u32, u64)> {
let s = fs::read_to_string(format!("/proc/{pid}/stat")).ok()?;
let rest = &s[s.rfind(')')? + 2..];
let f: Vec<&str> = rest.split(' ').collect();
Some((f.get(1)?.parse().ok()?, f.get(19)?.parse().ok()?))
}
pub fn uptime_ticks() -> u64 {
fs::read_to_string("/proc/uptime").ok().and_then(|s| s.split(' ').next().and_then(|v| v.parse::<f64>().ok())).map(|s| (s * 100.0) as u64).unwrap_or(0)
}
pub fn alive(pid: u32) -> bool {
Path::new(&format!("/proc/{pid}")).exists()
}
pub fn mine() -> Vec<Proc> {
let me = fs::metadata("/proc/self").map(|m| m.uid()).unwrap_or(u32::MAX);
let mut v = Vec::new();
let Ok(rd) = fs::read_dir("/proc") else { return v };
for e in rd.flatten() {
let Some(pid) = e.file_name().to_str().and_then(|n| n.parse::<u32>().ok()) else { continue };
if fs::metadata(e.path()).map(|m| m.uid()).ok() != Some(me) {
continue;
}
let Some((ppid, start)) = stat(pid) else { continue };
let Ok(raw) = fs::read(e.path().join("cmdline")) else { continue };
let args: Vec<String> = raw.split(|b| *b == 0).filter(|a| !a.is_empty()).map(|a| String::from_utf8_lossy(a).into_owned()).collect();
let cwd = fs::read_link(e.path().join("cwd")).map(|p| p.display().to_string()).unwrap_or_default();
v.push(Proc { pid, ppid, start, args, cwd });
}
v
}
}
pub fn run(argv: &[String]) -> Result<(), String> {
const USAGE: &str = "usage: instinct doctor --waits [--min-age MINUTES] [--fix]";
#[cfg(not(target_os = "linux"))]
{
let _ = (argv, USAGE);
println!("not supported here: --waits reads Linux /proc");
Ok(())
}
#[cfg(target_os = "linux")]
{
let mut fix = false;
let mut min_age: u64 = 10;
let mut i = 0;
while i < argv.len() {
match argv[i].as_str() {
"--waits" => {}
"--fix" => fix = true,
"--min-age" => {
i += 1;
min_age = argv.get(i).and_then(|v| v.parse().ok()).ok_or(USAGE)?;
}
_ => return Err(USAGE.into()),
}
i += 1;
}
let procs = linux::mine();
let now = linux::uptime_ticks();
let own = std::process::id();
let mut safe = vec![own];
let mut cur = own;
while let Some(p) = procs.iter().find(|p| p.pid == cur) {
if p.ppid <= 1 || safe.contains(&p.ppid) {
break;
}
safe.push(p.ppid);
cur = p.ppid;
}
let mut found = 0;
for p in &procs {
let shell = p.args.first().map(|a| a.rsplit('/').next().unwrap_or("")).unwrap_or("");
if safe.contains(&p.pid) || !matches!(shell, "bash" | "sh" | "zsh" | "dash") {
continue;
}
let Some(ci) = p.args.iter().position(|a| a == "-c") else { continue };
let Some(script) = p.args.get(ci + 1) else { continue };
let age_min = now.saturating_sub(p.start) / 100 / 60;
if age_min < min_age {
continue;
}
let exists = |f: &str| Path::new(f).exists() && fs::metadata(f).map(|m| m.len() > 0 || f.ends_with('/')).unwrap_or(false);
let why = analyze(script, &p.cwd, &exists, &linux::alive);
if why.is_empty() {
continue;
}
found += 1;
let snippet: String = script.split_whitespace().collect::<Vec<_>>().join(" ").chars().take(100).collect();
println!("pid {} {} min old {snippet}", p.pid, age_min);
for w in &why {
println!(" why: {}", w.text());
}
if fix {
let mut targets: Vec<u32> = procs.iter().filter(|c| c.ppid == p.pid).map(|c| c.pid).collect();
targets.push(p.pid);
for t in targets {
let ok = std::process::Command::new("kill").arg(t.to_string()).stderr(std::process::Stdio::null()).status().map(|s| s.success()).unwrap_or(false);
println!(" {} pid {t}", if ok { "stopped" } else { "could not stop" });
}
}
}
if found == 0 {
println!("no stale wait loops older than {min_age} min");
} else if !fix {
println!("{found} stale wait loop(s). `instinct doctor --waits --fix` stops them (your user's processes only, each loop's own shell and children).");
}
Ok(())
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn finds_the_three_shapes_and_leaves_live_waits_alone() {
let yes = |_: &str| true;
let no = |_: &str| false;
let alive = |p: u32| p == 7;
let a = analyze("until [ -s /t/out.txt ]; do sleep 2; done", "/", &yes, &alive);
assert_eq!(a, vec![Why::FileExists("/t/out.txt".into())]);
assert!(analyze("until [ -s /t/out.txt ]; do sleep 2; done", "/", &no, &alive).is_empty());
assert_eq!(analyze("tail --pid=99 -f /dev/null; echo", "/", &no, &alive), vec![]); assert_eq!(analyze("while tail --pid=99 -f /dev/null; do sleep 1; done", "/", &no, &alive), vec![Why::ProcessGone(99)]);
assert!(analyze("while tail --pid=7 -f /dev/null; do sleep 1; done", "/", &no, &alive).is_empty());
let s = analyze("until ! pgrep -f \"xyz-sleeper\"; do sleep 1; done", "/", &no, &alive);
assert_eq!(s, vec![Why::MatchesItself("xyz-sleeper".into())]);
assert!(analyze("until ! pgrep -f \"[x]yz-sleeper\"; do sleep 1; done", "/", &no, &alive).is_empty());
}
}