Stage 2 monitor app: Task Manager clone (Processes + Performance tabs)
Python port of the Task Manager clone: TPageControl with two tabs (tab clicks need app-level hit handling, fixed tab-width 140). Processes tab is a live XProcessList from /proc (sortable PID / Program / User / Mem / CPU% columns, header clicks toggle the direction). Performance tab is XHistoryGraph (60 s CPU + memory), XCoreGrid (per-core), XUsageBar (Memory, Disk /, Swap), XStackBar (memory breakdown) and XNetGraph (live /proc/net/dev rates). Data sampled every 500 ms (GLib timeout); window repaints every 2 s (a full redraw is ~38 rows x 5 text calls plus the graphs, and repainting every tick burned ~40% of a core); the process list refreshes every 2 s. Python monitor widgets draw dark btop-style panels, so the window background is dark. Also fixes two XProcessList issues the app exposed: the columns were fixed offsets drawn for the 360px demo widget (a wide widget was mostly empty) -> width-relative fractions, same as the C++ widget, plus a v/^ sort marker in the header; and _read_processes opened /proc/<pid>/status for every process on every scan (671 ms CPU for 400 processes) -> RSS now comes from stat field 24 and the uid lookup is cached per (pid, starttime), so a warm scan is ~75 ms (9x faster).
This commit is contained in:
1 parent
03065d35bf
commit
16ebfd719b
5 files changed
+598
-32
No files matched your search
+76
-32
@@ -153,16 +153,58 @@ def _read_cpu_times():
|
||||
return None
|
||||
|
||||
|
||||
# (pid, starttime) -> user name, so a rescan only opens /proc/<pid>/status
|
||||
# for processes it has never seen (a recycled pid has a new starttime,
|
||||
# so the cache cannot go stale). Opening status for every process on
|
||||
# every scan cost ~40% of the scan on a 400-process box; the stat file
|
||||
# alone carries everything else (rss is field 24, in pages).
|
||||
_UID_CACHE = {}
|
||||
_PAGE_KB = 4 # overridden below from sysconf when available
|
||||
try:
|
||||
_PAGE_KB = os.sysconf("SC_PAGE_SIZE") // 1024
|
||||
except (AttributeError, ValueError, OSError):
|
||||
pass
|
||||
|
||||
|
||||
def _user_for(pid, starttime):
|
||||
"""User name for a process, reading /proc/<pid>/status only on
|
||||
a cache miss. Returns "" when the process is gone."""
|
||||
key = (pid, starttime)
|
||||
user = _UID_CACHE.get(key)
|
||||
if user is not None:
|
||||
return user
|
||||
if len(_UID_CACHE) > 4096:
|
||||
_UID_CACHE.clear()
|
||||
user = ""
|
||||
try:
|
||||
import pwd
|
||||
except ImportError: # pragma: no cover - non-Unix
|
||||
pwd = None
|
||||
try:
|
||||
with open("/proc/%s/status" % pid) as handle:
|
||||
for line in handle:
|
||||
if line.startswith("Uid:"):
|
||||
uid = int(line.split()[1])
|
||||
user = str(uid)
|
||||
if pwd is not None:
|
||||
try:
|
||||
user = pwd.getpwuid(uid).pw_name
|
||||
except KeyError:
|
||||
pass
|
||||
break
|
||||
except (OSError, ValueError, IndexError):
|
||||
pass
|
||||
_UID_CACHE[key] = user
|
||||
return user
|
||||
|
||||
|
||||
def _read_processes():
|
||||
"""Live process rows from /proc: dicts with pid, name, user,
|
||||
mem_kb, utime, stime -- plus an internal ``t`` (monotonic time
|
||||
the stat was read, used for per-process CPU% denominators and
|
||||
stripped before the rows reach the widget). Returns None when
|
||||
/proc is unavailable."""
|
||||
try:
|
||||
import pwd
|
||||
except ImportError: # pragma: no cover - non-Unix
|
||||
pwd = None
|
||||
/proc is unavailable.
|
||||
"""
|
||||
rows = []
|
||||
try:
|
||||
pids = [d for d in os.listdir("/proc") if d.isdigit()]
|
||||
@@ -177,20 +219,9 @@ def _read_processes():
|
||||
rest = data[rparen + 2:].split()
|
||||
utime = int(rest[11])
|
||||
stime = int(rest[12])
|
||||
with open("/proc/%s/status" % pid) as handle:
|
||||
uid = None
|
||||
mem_kb = 0
|
||||
for line in handle:
|
||||
if line.startswith("Uid:"):
|
||||
uid = int(line.split()[1])
|
||||
elif line.startswith("VmRSS:"):
|
||||
mem_kb = int(line.split()[1])
|
||||
user = str(uid) if uid is None else str(uid)
|
||||
if pwd is not None and uid is not None:
|
||||
try:
|
||||
user = pwd.getpwuid(uid).pw_name
|
||||
except KeyError:
|
||||
pass
|
||||
starttime = int(rest[19])
|
||||
mem_kb = int(rest[21]) * _PAGE_KB
|
||||
user = _user_for(pid, starttime)
|
||||
rows.append({"pid": int(pid), "name": comm, "user": user,
|
||||
"mem_kb": mem_kb, "utime": utime,
|
||||
"stime": stime, "cpu": 0.0,
|
||||
@@ -1274,16 +1305,29 @@ class MonitorWidget(Widget):
|
||||
def _draw_process_list(self, cr):
|
||||
top = _panel(cr, self, self._title())
|
||||
rows = self._sorted_rows()
|
||||
cols = ((6, 52, "PID", "left"), (62, 130, "Program", "left"),
|
||||
(196, 44, "User", "left"), (244, 48, "Mem", "right"),
|
||||
(296, 56, "CPU%", "right"))
|
||||
# Column x-offsets as fractions of the inner width (same
|
||||
# fractions as the C++ widget: PID / Program / User / Mem /
|
||||
# CPU%). The old fixed offsets were drawn for the 360px demo
|
||||
# widget and left a wide widget mostly empty.
|
||||
iw = max(60, self.width - 12)
|
||||
xs = [6 + int(iw * f) for f in (0.0, 0.14, 0.52, 0.68, 0.82, 1.0)]
|
||||
# (x, label, sort key): sort keys follow _sorted_rows
|
||||
# (0 cpu, 1 mem, 2 pid, 3 name); User has no sort key.
|
||||
sort_col = _prop_int(self, "sort-by", 0)
|
||||
sort_desc = _prop_bool(self, "sort-desc", True)
|
||||
headers = [(xs[0], "PID", 2, "left"), (xs[1], "Program", 3, "left"),
|
||||
(xs[2], "User", None, "left"), (xs[4], "Mem", 1, "right"),
|
||||
(xs[5], "CPU%", 0, "right")]
|
||||
header_y = top + 13
|
||||
for x, _w, name, align in cols:
|
||||
for x, name, key, align in headers:
|
||||
label = name
|
||||
if key is not None and key == sort_col:
|
||||
label += " v" if sort_desc else " ^"
|
||||
if align == "right":
|
||||
_wtext(cr, self, name, x + _w, header_y, size=10,
|
||||
_wtext(cr, self, label, x - 4, header_y, size=10,
|
||||
rgb=_DIM, align="right", bold=True)
|
||||
else:
|
||||
_wtext(cr, self, name, x, header_y, size=10,
|
||||
_wtext(cr, self, label, x, header_y, size=10,
|
||||
rgb=_DIM, bold=True)
|
||||
row_h = 18
|
||||
y0 = top + 18
|
||||
@@ -1299,17 +1343,17 @@ class MonitorWidget(Widget):
|
||||
_rgb(cr, _AMBER, 0.12)
|
||||
cr.rectangle(0, y, self.width, row_h)
|
||||
cr.fill()
|
||||
_wtext(cr, self, str(row["pid"]), 6, y + 13, size=10,
|
||||
_wtext(cr, self, str(row["pid"]), xs[0], y + 13, size=10,
|
||||
rgb=_TEXT)
|
||||
_wtext(cr, self, row["name"], 62, y + 13, size=10,
|
||||
_wtext(cr, self, row["name"], xs[1], y + 13, size=10,
|
||||
rgb=_TEXT,
|
||||
max_width=128)
|
||||
_wtext(cr, self, row["user"], 196, y + 13, size=10,
|
||||
rgb=_TEXT, max_width=44)
|
||||
_wtext(cr, self, _fmt_bytes(row["mem_kb"] * 1024), 292,
|
||||
max_width=xs[2] - xs[1] - 6)
|
||||
_wtext(cr, self, row["user"], xs[2], y + 13, size=10,
|
||||
rgb=_TEXT, max_width=xs[3] - xs[2] - 6)
|
||||
_wtext(cr, self, _fmt_bytes(row["mem_kb"] * 1024), xs[4] - 4,
|
||||
y + 13, size=10, rgb=_TEXT, align="right")
|
||||
# In-cell CPU% bar behind the number.
|
||||
bar_x, bar_w = 300, 52
|
||||
bar_x, bar_w = xs[4] + 2, xs[5] - xs[4] - 6
|
||||
_box(cr, bar_x, y + 3, bar_w, 12, (0.20, 0.20, 0.23),
|
||||
(0.20, 0.20, 0.23))
|
||||
fill = max(0, bar_w * min(1.0, cpu / 100.0))
|
||||
|
||||
Reference in new issue
Block a user