-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy paththreadreaper.py
More file actions
executable file
·2566 lines (2383 loc) · 102 KB
/
threadreaper.py
File metadata and controls
executable file
·2566 lines (2383 loc) · 102 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
#!/usr/bin/env python3
# SPDX-License-Identifier: MIT
"""ThreadReaper — modern TUI thread manager for shared multi-user Linux hosts.
A single-file, zero-dependency Python 3.11+ curses TUI for monitoring
thread usage, hunting ghost processes (zombies / orphans / idle hogs /
frozen / stuck-on-disk), and decisively reclaiming threads when nearing
the per-user limit on shared seedboxes and developer servers.
Run with `--help` for usage. See README.md for full documentation.
"""
from __future__ import annotations
import argparse
import curses
import io
import json
import locale
import os
import pwd
import re
import resource
import signal
import sys
import time
import unicodedata
from collections import defaultdict, deque
from dataclasses import dataclass, field, asdict
from datetime import datetime
from pathlib import Path
from typing import Any, Callable, Iterable
__version__ = "1.0.0"
APP_NAME = "ThreadReaper"
# ─── Constants ──────────────────────────────────────────────────────────────
CLK_TCK = os.sysconf(os.sysconf_names["SC_CLK_TCK"])
PAGE_SIZE = os.sysconf(os.sysconf_names["SC_PAGESIZE"])
MY_UID = os.getuid()
MY_PID = os.getpid()
DEFAULT_REFRESH = 2.0
SIGTERM_TIMEOUT = 3.0
HISTORY_LEN = 60
CONFIG_DIR = Path(os.environ.get("THREADREAPER_HOME", str(Path.home() / ".threadreaper")))
EVENTS_LOG = CONFIG_DIR / "events.log"
# Processes whose names match these are never offered for killing without an
# extra confirmation. Best-effort safety net for the inexperienced.
PROTECTED_NAMES = {
"systemd", "init", "sshd", "agetty", "login", "logind",
"systemd-logind", "systemd-journal", "dbus-daemon", "(sd-pam)",
}
# Binaries we treat as "user-space" — used as part of orphan classification.
KNOWN_SYSTEM_BINS = PROTECTED_NAMES | {
"cron", "crond", "rsyslogd", "udevd", "kthreadd", "ksoftirqd",
"kworker", "rcu_sched", "migration", "watchdog", "nginx", "apache2",
"httpd", "redis-server", "postgres", "mysqld", "mariadbd",
}
SORT_COLUMNS = ["threads", "cpu", "rss", "pid", "name", "age"]
SORT_LABELS = {
"threads": "Threads",
"cpu": "CPU",
"rss": "Memory",
"pid": "PID",
"name": "Name",
"age": "Age",
}
SEVERITY_WEIGHTS = {
"zombie": 1.6,
"orphan": 1.3,
"frozen": 1.1,
"stuck": 1.0,
"idle_hog": 0.9,
}
GHOST_TYPES = ["zombie", "orphan", "idle_hog", "frozen", "stuck"]
# ─── Color pair IDs ─────────────────────────────────────────────────────────
C_DEFAULT = 1
C_DIM = 2
C_BOLD = 3
C_ACCENT = 4
C_HEADER = 5
C_BORDER = 6
C_OK = 7
C_WARN = 8
C_CRIT = 9
C_INFO = 10
C_HOG = 11
C_ZOMBIE = 12
C_ORPHAN = 13
C_FROZEN = 14
C_STUCK = 15
C_SELECTED = 16
C_PINNED = 17
C_GAUGE_OK = 18
C_GAUGE_WARN = 19
C_GAUGE_CRIT = 20
C_SAFETY_OK = 21
C_SAFETY_WARN = 22
C_SAFETY_BAD = 23
C_SPARK_OK = 24
C_SPARK_WARN = 25
C_SPARK_CRIT = 26
# ─── Symbols ────────────────────────────────────────────────────────────────
def _build_symbols(use_emoji: bool) -> dict[str, str]:
if use_emoji:
return {
"logo": "💀", "skull": "💀", "ghost": "👻", "pig": "🐷",
"ice": "🧊", "magnet": "🧲", "thread": "🧵", "trophy": "🏆",
"clipboard": "📋", "search": "🔍", "pin": "📌", "pinned": "📍",
"chain": "🔗", "chart": "📊", "activity": "📈", "folder": "📂",
"shield": "🛡️", "tree": "🌳", "fire": "🔥", "warn": "⚠️",
"ok": "✅", "bolt": "⚡", "check": "✔", "cross": "✘",
"bomb": "💣", "recycle": "♻️", "skip": "⏭", "play": "▶",
"sleep": "💤", "wait": "⏳", "pause": "⏸", "diamond": "◆",
"right": "▶", "arrow": "─▶", "refresh": "↻", "brain": "🧠",
"clock": "⏱", "radio": "📡", "door": "🚪", "disk": "💾",
"question": "❓", "rocket": "🚀", "star": "★", "filter": "⏷",
"sparkle": "✨", "compass": "🧭",
"bf": "█", "be": " ",
"bar0": " ", "bar1": "▏", "bar2": "▎", "bar3": "▍",
"bar4": "▌", "bar5": "▋", "bar6": "▊", "bar7": "▉",
"bar8": "█",
"spark": "▁▂▃▄▅▆▇█",
"spinner": "⠋⠙⠹⠸⠼⠴⠦⠧⠇⠏",
"safe_ok": "🟢", "safe_warn": "🟡", "safe_bad": "🔴",
"corner_tl": "╭", "corner_tr": "╮",
"corner_bl": "╰", "corner_br": "╯",
"horiz": "─", "vert": "│",
"branch_t": "├", "branch_l": "└", "branch_v": "│",
}
return {
"logo": "##", "skull": "[Z]", "ghost": "[G]", "pig": "[H]",
"ice": "[F]", "magnet": "[S]", "thread": "T", "trophy": "*",
"clipboard": "#", "search": ">", "pin": ".", "pinned": "*",
"chain": "->", "chart": "+", "activity": "~", "folder": "F",
"shield": "!", "tree": "^", "fire": "!", "warn": "!",
"ok": "v", "bolt": ">", "check": "v", "cross": "x",
"bomb": "X", "recycle": "<>", "skip": ">", "play": ">",
"sleep": "z", "wait": ".", "pause": "|", "diamond": ">",
"right": ">", "arrow": "->", "refresh": "r", "brain": "M",
"clock": "t", "radio": "~", "door": "<-", "disk": "D",
"question": "?", "rocket": ">>", "star": "*", "filter": "v",
"sparkle": "*", "compass": "+",
"bf": "#", "be": ".",
"bar0": " ", "bar1": ".", "bar2": ":", "bar3": "-",
"bar4": "=", "bar5": "+", "bar6": "*", "bar7": "#",
"bar8": "#",
"spark": ".:-=+*#%",
"spinner": "|/-\\",
"safe_ok": "[ok]", "safe_warn": "[??]", "safe_bad": "[!!]",
"corner_tl": "+", "corner_tr": "+",
"corner_bl": "+", "corner_br": "+",
"horiz": "-", "vert": "|",
"branch_t": "+", "branch_l": "+", "branch_v": "|",
}
SYM: dict[str, str] = {}
def state_icon(state: str) -> str:
return {
"R": SYM["play"], "S": SYM["sleep"], "D": SYM["wait"],
"T": SYM["pause"], "t": SYM["pause"], "Z": SYM["skull"],
"I": SYM["sleep"], "X": SYM["cross"],
}.get(state, "?")
def ghost_badge(gtype: str) -> tuple[str, str, int]:
return {
"zombie": (SYM["skull"], "ZOMBIE", C_ZOMBIE),
"orphan": (SYM["ghost"], "ORPHAN", C_ORPHAN),
"idle_hog": (SYM["pig"], "IDLE HOG", C_HOG),
"frozen": (SYM["ice"], "FROZEN", C_FROZEN),
"stuck": (SYM["magnet"], "STUCK D", C_STUCK),
}.get(gtype, (SYM["ghost"], "UNKNOWN", C_DIM))
# ─── Utility ────────────────────────────────────────────────────────────────
def wcswidth(s: str) -> int:
w = 0
for ch in s:
if unicodedata.category(ch) == "Mn":
continue
if unicodedata.east_asian_width(ch) in ("W", "F"):
w += 2
else:
w += 1
return w
def wc_truncate(s: str, maxw: int, suffix: str = "…") -> str:
if maxw <= 0:
return ""
if wcswidth(s) <= maxw:
return s
sw = wcswidth(suffix)
w = 0
out = []
for ch in s:
cw = 2 if unicodedata.east_asian_width(ch) in ("W", "F") else 1
if w + cw > maxw - sw:
break
out.append(ch)
w += cw
return "".join(out) + suffix
def wc_pad(s: str, width: int) -> str:
return s + " " * max(0, width - wcswidth(s))
def safe_addstr(win, y: int, x: int, text: str, attr: int = 0) -> None:
try:
h, w = win.getmaxyx()
except curses.error:
return
if y < 0 or y >= h or x >= w:
return
remain = w - x
if remain <= 0:
return
if wcswidth(text) > remain:
text = wc_truncate(text, remain, "")
try:
win.addstr(y, x, text, attr)
except curses.error:
pass
def smooth_bar(ratio: float, width: int) -> str:
"""Render a smooth horizontal bar using sub-cell Unicode blocks."""
if width <= 0:
return ""
ratio = max(0.0, min(1.0, ratio))
total = width * 8
filled = int(round(ratio * total))
full_cells = filled // 8
remainder = filled % 8
bar = SYM["bar8"] * full_cells
if remainder:
bar += SYM[f"bar{remainder}"]
return bar + SYM["bar0"] * max(0, width - wcswidth(bar))
def sparkline(values: Iterable[float], width: int, vmax: float | None = None) -> str:
"""Generate a sparkline string from a series of numbers."""
data = list(values)
if not data or width <= 0:
return " " * width
if len(data) > width:
# downsample by averaging chunks
step = len(data) / width
sampled = []
for i in range(width):
lo = int(i * step)
hi = int((i + 1) * step)
chunk = data[lo:hi] or [data[-1]]
sampled.append(sum(chunk) / len(chunk))
data = sampled
if vmax is None:
vmax = max(data) if data else 0
if vmax <= 0:
return " " * width
chars = SYM["spark"]
n = len(chars) - 1
out = []
for v in data:
idx = max(0, min(n, int(round(v / vmax * n))))
out.append(chars[idx])
pad = max(0, width - len(out))
return "".join(out) + " " * pad
def gauge_pair(ratio: float) -> int:
if ratio >= 0.9:
return C_GAUGE_CRIT
if ratio >= 0.7:
return C_GAUGE_WARN
return C_GAUGE_OK
def gauge_icon(ratio: float) -> str:
if ratio >= 0.9:
return SYM["fire"]
if ratio >= 0.7:
return SYM["warn"]
return SYM["ok"]
def format_bytes(n: int | float | None) -> str:
if n is None:
return "?"
n = float(n)
if n >= 1024 ** 3:
return f"{n / 1024**3:.1f}G"
if n >= 1024 ** 2:
return f"{n / 1024**2:.0f}M"
if n >= 1024:
return f"{n / 1024:.0f}K"
return f"{int(n)}B"
def format_duration(secs: float) -> str:
if secs < 0 or secs != secs:
return "?"
s = int(secs)
if s < 60:
return f"{s}s"
if s < 3600:
return f"{s // 60}m"
if s < 86400:
return f"{s // 3600}h{(s % 3600) // 60:02d}m"
return f"{s // 86400}d{(s % 86400) // 3600:02d}h"
def get_uptime() -> float:
try:
with open("/proc/uptime") as f:
return float(f.read().split()[0])
except (FileNotFoundError, PermissionError, ValueError):
return 0.0
def detect_thread_limit() -> int:
"""Best-effort detection of the effective per-user thread/process limit."""
try:
soft, _ = resource.getrlimit(resource.RLIMIT_NPROC)
if soft and soft != resource.RLIM_INFINITY:
return int(soft)
except (ValueError, OSError):
pass
# System-wide cap, used as a fallback
try:
with open("/proc/sys/kernel/threads-max") as f:
return int(f.read().strip())
except (FileNotFoundError, PermissionError, ValueError):
pass
return 2000
def proc_alive(pid: int) -> bool:
try:
os.kill(pid, 0)
return True
except ProcessLookupError:
return False
except PermissionError:
return True
def user_name(uid: int | None = None) -> str:
if uid is None:
uid = MY_UID
try:
return pwd.getpwuid(uid).pw_name
except (KeyError, OSError):
return str(uid)
def append_event(line: str) -> None:
"""Append a line to the events log (best-effort)."""
try:
CONFIG_DIR.mkdir(exist_ok=True)
with EVENTS_LOG.open("a") as f:
f.write(f"{datetime.now().isoformat(timespec='seconds')} {line}\n")
except OSError:
pass
def shorten_cmd(cmdline: str, name: str, maxw: int) -> str:
text = cmdline.strip() or name
return wc_truncate(text, maxw, "…")
# ─── Data classes ───────────────────────────────────────────────────────────
@dataclass
class ProcessInfo:
pid: int
ppid: int
name: str
cmdline: str
state: str
threads: int
utime: int
stime: int
rss_bytes: int
starttime: int
tty: int
vol_cs: int
nonvol_cs: int
io_read: int | None = None
io_write: int | None = None
loginuid: int | None = None
cgroup: str = ""
wchan: str = ""
fd_count: int = 0
exe: str = ""
cpu_percent: float = 0.0
age_secs: float = 0.0
@dataclass
class GhostInfo:
pid: int
ghost_type: str
confidence: float
reason: str
first_seen: float = 0.0
@property
def safety_icon(self) -> str:
if self.confidence >= 0.85:
return SYM["safe_ok"]
if self.confidence >= 0.65:
return SYM["safe_warn"]
return SYM["safe_bad"]
@property
def safety_color(self) -> int:
if self.confidence >= 0.85:
return C_SAFETY_OK
if self.confidence >= 0.65:
return C_SAFETY_WARN
return C_SAFETY_BAD
@dataclass
class KillRecord:
pid: int
name: str
ghost_type: str
threads: int
method: str
success: bool
when: float = field(default_factory=time.time)
@dataclass
class Theme:
name: str
use_default_bg: bool = True
accent: int = curses.COLOR_CYAN
border: int = curses.COLOR_WHITE
dim: int = curses.COLOR_WHITE
# ─── Proc scanner ───────────────────────────────────────────────────────────
class ProcScanner:
"""Reads /proc and produces ProcessInfo snapshots."""
def __init__(self, all_users: bool = False) -> None:
self.all_users = all_users
self.errors: dict[str, int] = defaultdict(int)
def scan(self) -> dict[int, ProcessInfo]:
out: dict[int, ProcessInfo] = {}
uptime = get_uptime()
try:
entries = list(os.scandir("/proc"))
except OSError:
return out
for entry in entries:
if not entry.name.isdigit():
continue
pid = int(entry.name)
if pid == MY_PID:
continue
info = self._read_one(pid, uptime)
if info is not None:
out[pid] = info
return out
# ── helpers ────────────────────────────────────────────────────────────
def _read_file(self, path: str) -> str:
try:
with open(path) as f:
return f.read()
except FileNotFoundError:
return ""
except PermissionError:
self.errors["perm"] += 1
return ""
except OSError:
return ""
def _read_one(self, pid: int, uptime: float) -> ProcessInfo | None:
base = f"/proc/{pid}"
stat = self._read_stat(base)
if stat is None:
return None
status = self._read_status(base)
if status is None:
return None
if not self.all_users and status["uid"] != MY_UID:
return None
cmdline = self._read_cmdline(base)
io_d = self._read_io(base)
loginuid = self._read_loginuid(base)
cgroup = self._read_file(f"{base}/cgroup")
wchan = self._read_file(f"{base}/wchan").strip()
fd_count = self._count_fds(base)
try:
exe = os.readlink(f"{base}/exe")
except OSError:
exe = ""
age = max(0.0, uptime - stat["starttime"] / CLK_TCK)
return ProcessInfo(
pid=pid,
ppid=stat["ppid"],
name=stat["name"],
cmdline=cmdline,
state=stat["state"],
threads=status.get("threads", stat["threads"]),
utime=stat["utime"],
stime=stat["stime"],
rss_bytes=stat["rss"] * PAGE_SIZE,
starttime=stat["starttime"],
tty=stat["tty"],
vol_cs=status.get("vol_cs", 0),
nonvol_cs=status.get("nonvol_cs", 0),
io_read=io_d.get("read") if io_d else None,
io_write=io_d.get("write") if io_d else None,
loginuid=loginuid,
cgroup=cgroup,
wchan=wchan,
fd_count=fd_count,
exe=exe,
age_secs=age,
)
def _read_stat(self, base: str) -> dict[str, Any] | None:
raw = self._read_file(f"{base}/stat")
if not raw:
return None
try:
end = raw.rfind(")")
name = raw[raw.index("(") + 1 : end]
fields = raw[end + 2 :].split()
if len(fields) < 22:
return None
return {
"name": name,
"state": fields[0],
"ppid": int(fields[1]),
"tty": int(fields[4]),
"utime": int(fields[11]),
"stime": int(fields[12]),
"threads": int(fields[17]),
"starttime": int(fields[19]),
"rss": int(fields[21]),
}
except (ValueError, IndexError):
return None
def _read_status(self, base: str) -> dict[str, Any] | None:
raw = self._read_file(f"{base}/status")
if not raw:
return None
out: dict[str, Any] = {}
try:
for line in raw.splitlines():
if line.startswith("Uid:"):
out["uid"] = int(line.split()[1])
elif line.startswith("Threads:"):
out["threads"] = int(line.split()[1])
elif line.startswith("voluntary_ctxt_switches:"):
out["vol_cs"] = int(line.split()[1])
elif line.startswith("nonvoluntary_ctxt_switches:"):
out["nonvol_cs"] = int(line.split()[1])
except (ValueError, IndexError):
return None
return out if "uid" in out else None
def _read_cmdline(self, base: str) -> str:
raw = self._read_file(f"{base}/cmdline")
return raw.replace("\x00", " ").strip() if raw else ""
def _read_io(self, base: str) -> dict[str, int] | None:
raw = self._read_file(f"{base}/io")
if not raw:
return None
out: dict[str, int] = {}
try:
for line in raw.splitlines():
parts = line.split(":")
if len(parts) != 2:
continue
k, v = parts[0].strip(), parts[1].strip()
if k == "read_bytes":
out["read"] = int(v)
elif k == "write_bytes":
out["write"] = int(v)
except ValueError:
return None
return out or None
def _read_loginuid(self, base: str) -> int | None:
raw = self._read_file(f"{base}/loginuid")
try:
v = int(raw.strip()) if raw else None
except ValueError:
return None
return v if v is not None and v != 4294967295 else None
def _count_fds(self, base: str) -> int:
try:
return len(os.listdir(f"{base}/fd"))
except OSError:
return 0
# ── lazy lookups (called only when needed) ─────────────────────────────
def read_fd_targets(self, pid: int, limit: int = 12) -> list[tuple[str, str]]:
out: list[tuple[str, str]] = []
fd_dir = f"/proc/{pid}/fd"
try:
fds = sorted(os.listdir(fd_dir), key=lambda x: int(x) if x.isdigit() else 0)
except OSError:
return out
for fd in fds:
if len(out) >= limit:
break
try:
target = os.readlink(f"{fd_dir}/{fd}")
except OSError:
continue
if target.startswith("socket:"):
ftype = "net"
elif target.startswith("pipe:"):
ftype = "pipe"
elif target.startswith("anon_inode:"):
ftype = "anon"
elif target.startswith("/dev/"):
continue
else:
ftype = "file"
out.append((target, ftype))
return out
def has_write_handles(self, pid: int) -> bool:
fd_dir = f"/proc/{pid}/fd"
try:
fds = os.listdir(fd_dir)
except OSError:
return False
for fd in fds:
try:
target = os.readlink(f"{fd_dir}/{fd}")
except OSError:
continue
if not target.startswith("/") or target.startswith(("/dev/", "/proc/", "/sys/")):
continue
info = self._read_file(f"/proc/{pid}/fdinfo/{fd}")
for line in info.splitlines():
if line.startswith("flags:"):
try:
flags = int(line.split()[1], 8)
if flags & 3 in (1, 2):
return True
except (ValueError, IndexError):
continue
return False
# ─── History ring (per-PID sparkline data) ──────────────────────────────────
class History:
def __init__(self, capacity: int = HISTORY_LEN) -> None:
self.cap = capacity
self.cpu: dict[int, deque[float]] = {}
self.threads: dict[int, deque[int]] = {}
self.total: deque[int] = deque(maxlen=capacity)
self.total_cpu: deque[float] = deque(maxlen=capacity)
def push(self, procs: dict[int, ProcessInfo]) -> None:
live = set(procs)
for pid, p in procs.items():
self.cpu.setdefault(pid, deque(maxlen=self.cap)).append(p.cpu_percent)
self.threads.setdefault(pid, deque(maxlen=self.cap)).append(p.threads)
# Drop dead PIDs to keep memory bounded
for pid in list(self.cpu):
if pid not in live:
del self.cpu[pid]
self.threads.pop(pid, None)
self.total.append(sum(p.threads for p in procs.values()))
self.total_cpu.append(sum(p.cpu_percent for p in procs.values()))
# ─── Ghost classifier ──────────────────────────────────────────────────────
class GhostClassifier:
def __init__(self, scanner: ProcScanner) -> None:
self.scanner = scanner
self.snapshots: deque[tuple[float, dict[int, ProcessInfo]]] = deque(maxlen=30)
self.cycle = 0
self.first_seen: dict[tuple[int, str], float] = {}
@property
def warmup_msg(self) -> str | None:
if self.cycle < 3:
return f"warming up ({self.cycle}/3 cycles)"
if self.cycle < 6:
return f"sampling ({self.cycle}/6)"
return None
def add(self, procs: dict[int, ProcessInfo]) -> None:
self.snapshots.append((time.time(), procs))
self.cycle += 1
def classify(self) -> list[GhostInfo]:
if not self.snapshots:
return []
now = time.time()
_, current = self.snapshots[-1]
found: dict[int, GhostInfo] = {}
for g in self._zombies(current, now):
self._keep_best(found, g)
for g in self._orphans(current, now):
self._keep_best(found, g)
if self.cycle >= 3:
for g in self._idle_hogs(current, now):
self._keep_best(found, g)
for g in self._stuck(current, now):
self._keep_best(found, g)
if self.cycle >= 6:
for g in self._frozen(current, now):
self._keep_best(found, g)
return sorted(found.values(), key=lambda g: g.confidence, reverse=True)
def _keep_best(self, found: dict[int, GhostInfo], g: GhostInfo) -> None:
cur = found.get(g.pid)
if cur is None or g.confidence > cur.confidence:
found[g.pid] = g
def _track(self, pid: int, gtype: str, now: float) -> float:
key = (pid, gtype)
if key not in self.first_seen:
self.first_seen[key] = now
return self.first_seen[key]
def _zombies(self, procs: dict[int, ProcessInfo], now: float) -> list[GhostInfo]:
out = []
for pid, p in procs.items():
if p.state == "Z":
fs = self._track(pid, "zombie", now)
dur = format_duration(now - fs) if now - fs > 1 else "just now"
out.append(GhostInfo(
pid=pid, ghost_type="zombie", confidence=1.0,
reason=f"Defunct (state Z) for {dur}. Parent PID {p.ppid} owes a wait().",
first_seen=fs,
))
return out
def _orphans(self, procs: dict[int, ProcessInfo], now: float) -> list[GhostInfo]:
out = []
home = os.path.expanduser("~")
for pid, p in procs.items():
if p.ppid != 1 or p.state == "Z":
continue
score = 0.0
reasons = []
if p.loginuid is not None:
score += 0.40
reasons.append("user-initiated")
if "user.slice" in p.cgroup or "user@" in p.cgroup:
score += 0.25
reasons.append("user.slice cgroup")
if home and home in p.cmdline:
score += 0.20
reasons.append("runs from $HOME")
n = p.name.lower()
if n not in KNOWN_SYSTEM_BINS and not n.startswith("k"):
score += 0.15
reasons.append("non-system binary")
if score >= 0.60:
fs = self._track(pid, "orphan", now)
out.append(GhostInfo(
pid=pid, ghost_type="orphan", confidence=min(score, 1.0),
reason=(f"Reparented to init (ppid=1). {', '.join(reasons)}. "
f"Alive for {format_duration(p.age_secs)}."),
first_seen=fs,
))
return out
def _idle_hogs(self, procs: dict[int, ProcessInfo], now: float) -> list[GhostInfo]:
out = []
if len(self.snapshots) < 3:
return out
snaps = list(self.snapshots)[-3:]
for pid, p in procs.items():
if p.threads < 20 or p.state == "Z":
continue
idle = 0
for i in range(1, len(snaps)):
tp, pp_map = snaps[i - 1]
tc, pc_map = snaps[i]
if pid not in pp_map or pid not in pc_map:
break
a, b = pp_map[pid], pc_map[pid]
dt = tc - tp
if dt <= 0:
continue
cpu_d = (b.utime + b.stime) - (a.utime + a.stime)
cpu_pct = (cpu_d / CLK_TCK) / dt * 100
cs_d = (b.vol_cs + b.nonvol_cs) - (a.vol_cs + a.nonvol_cs)
if cpu_pct < 0.1 and cs_d == 0:
idle += 1
if idle >= 2:
score = 0.55 + min(0.30, idle * 0.10)
# Mitigate false positives: active sockets => probably waiting
try:
for fd in os.listdir(f"/proc/{pid}/fd"):
try:
t = os.readlink(f"/proc/{pid}/fd/{fd}")
except OSError:
continue
if t.startswith("socket:"):
score -= 0.15
break
except OSError:
pass
score = max(0.40, min(1.0, score))
if score >= 0.55:
fs = self._track(pid, "idle_hog", now)
out.append(GhostInfo(
pid=pid, ghost_type="idle_hog", confidence=score,
reason=(f"{p.threads} threads with ~0% CPU and zero context "
f"switches across {idle} cycles."),
first_seen=fs,
))
return out
def _stuck(self, procs: dict[int, ProcessInfo], now: float) -> list[GhostInfo]:
out = []
if len(self.snapshots) < 3:
return out
snaps = list(self.snapshots)[-3:]
for pid, p in procs.items():
if p.state != "D":
continue
persistent = sum(1 for _, ps in snaps if pid in ps and ps[pid].state == "D")
if persistent >= 3:
fs = self._track(pid, "stuck", now)
conf = 0.7 + min(0.25, (persistent - 3) * 0.05)
out.append(GhostInfo(
pid=pid, ghost_type="stuck", confidence=conf,
reason=(f"Uninterruptible disk sleep across {persistent} cycles "
f"(wchan={p.wchan or 'unknown'})."),
first_seen=fs,
))
return out
def _frozen(self, procs: dict[int, ProcessInfo], now: float) -> list[GhostInfo]:
out = []
if len(self.snapshots) < 6:
return out
snaps = list(self.snapshots)[-6:]
for pid, p in procs.items():
if p.state == "Z":
continue
score = 0.0
reasons = []
first = snaps[0][1]
last = snaps[-1][1]
if pid not in first or pid not in last:
continue
pf, pl = first[pid], last[pid]
if (pl.utime + pl.stime) - (pf.utime + pf.stime) == 0:
score += 0.25
reasons.append("zero CPU")
if (pl.vol_cs + pl.nonvol_cs) - (pf.vol_cs + pf.nonvol_cs) == 0:
score += 0.25
reasons.append("zero ctx-switches")
if pl.io_read is not None and pf.io_read is not None:
if (pl.io_read + (pl.io_write or 0)) == (pf.io_read + (pf.io_write or 0)):
score += 0.25
reasons.append("zero I/O")
if pl.fd_count == pf.fd_count and pl.fd_count > 0:
score += 0.10
reasons.append("stable fd count")
if pl.wchan and pl.wchan in ("do_futex", "pipe_wait", "inode_lock"):
score += 0.10
reasons.append(f"blocked in {pl.wchan}")
if p.age_secs > 86400:
score += 0.05
reasons.append(f"alive {format_duration(p.age_secs)}")
if score >= 0.70 and p.threads >= 5:
fs = self._track(pid, "frozen", now)
out.append(GhostInfo(
pid=pid, ghost_type="frozen", confidence=min(score, 1.0),
reason="All activity metrics frozen: " + ", ".join(reasons) + ".",
first_seen=fs,
))
return out
# ─── Process tree ──────────────────────────────────────────────────────────
class ProcessTree:
def __init__(self, procs: dict[int, ProcessInfo]) -> None:
self.procs = procs
self.children: dict[int, list[int]] = defaultdict(list)
self.parent: dict[int, int] = {}
for pid, p in procs.items():
self.parent[pid] = p.ppid
self.children[p.ppid].append(pid)
def get_children(self, pid: int) -> list[int]:
return list(self.children.get(pid, []))
def descendants(self, pid: int) -> list[int]:
out, stack = [], list(self.children.get(pid, []))
while stack:
c = stack.pop()
out.append(c)
stack.extend(self.children.get(c, []))
return out
def chain(self, pid: int) -> list[int]:
out, seen = [], set()
cur = pid
while cur and cur not in seen and cur > 0:
seen.add(cur)
out.append(cur)
cur = self.parent.get(cur, 0)
return list(reversed(out))
def root_count(self, pids: Iterable[int]) -> int:
pids_set = set(pids)
roots = set()
for pid in pids_set:
for p in self.chain(pid):
if p in pids_set:
roots.add(p)
break
else:
roots.add(pid)
return len(roots)
def compute_cpu(snapshots: deque, current: dict[int, ProcessInfo]) -> None:
if len(snapshots) < 2:
return
tp, pp_map = snapshots[-2]
tc, _ = snapshots[-1]
dt = tc - tp
if dt <= 0:
return
for pid, p in current.items():
if pid in pp_map:
prev = pp_map[pid]
ticks = (p.utime + p.stime) - (prev.utime + prev.stime)
p.cpu_percent = max(0.0, (ticks / CLK_TCK) / dt * 100)
# ─── Reaper Mode ───────────────────────────────────────────────────────────
class ReaperMode:
def __init__(self, app: "App", ghosts: list[GhostInfo]) -> None:
self.app = app
self.stdscr = app.stdscr
self.queue = self._build_queue(ghosts)
self.index = 0
self.kills: list[KillRecord] = []
self.skipped: list[GhostInfo] = []
self.threads_before = app.total_threads
self.threads_reclaimed = 0
def _build_queue(self, ghosts: list[GhostInfo]) -> list[GhostInfo]:
scored = []
for g in ghosts:
p = self.app.procs.get(g.pid)
if not p:
continue
w = SEVERITY_WEIGHTS.get(g.ghost_type, 1.0)
impact = g.confidence * max(1, p.threads) * w
scored.append((impact, p.age_secs, g))
scored.sort(key=lambda x: (x[0], x[1]), reverse=True)
return [g for _, _, g in scored]