Files
Muse b197a366ec Disk Monitor app (Stage 2): live per-mount usage bars, Used/Free stack bar, read/write IO history graph
1024x768 window, 1 s refresh from /proc/mounts + os.statvfs and
/proc/diskstats. XUsageBar + XStackBar + XHistoryGraph; seeded demo
data replaced on first tick (push/set_segments start fresh own
data). Harness background is the widgets near-black panel color
(XStackBar paints no panel of its own). XSysBox deliberately unused
(no clear-history API, constructor seeds 60 demo samples).
Screenshot verified 1024x768 on :116. Tests: 363 OK.
2026-12-05 20:13:54 +00:00

198 lines
6.1 KiB
Python

#!/usr/bin/env python3
# Disk Monitor - monitor (Python/XFrame).
#
# One 1024x768 window: a live XUsageBar per disk mount (/proc/mounts
# + os.statvfs), an XStackBar splitting the largest mount into
# Used / Free (GiB), and an XHistoryGraph of disk read/write
# throughput in MB/s (/proc/diskstats, sectors differenced once a
# second). Refreshes every second; close the window to quit.
# Seeded demo series/segments are replaced by live data on the first
# tick (push()/set_segments() start fresh own data, never the demo).
#
# XSysBox is deliberately NOT used: it has no clear-history API and
# its constructor seeds 60 demo samples, so it cannot show live disk
# data without the seeded demo leaking into the history.
#
# Run with:
# PYTHONPATH=/root/monitor-wt/disk-monitor/lightgui_python \
# python3 examples/monitor_disk_monitor/main.py
# (or from the repo root with PYTHONPATH=.)
import os
import sys
import gi
gi.require_version("Gtk", "3.0")
gi.require_version("Gdk", "3.0")
from gi.repository import Gdk, GLib, Gtk # noqa: E402
from lightgui.xframe.core import create # noqa: E402
WIN_W, WIN_H = 1024, 768
MARGIN = 16
BAR_H, BAR_GAP = 44, 8
STACK_H = 170
REAL_FS = ("ext4", "xfs", "btrfs")
GIB = 1024.0 ** 3
_WIDGETS = []
_AREA = []
_MOUNTS = [] # dicts: dev/point/base/total/used/free/pct
_PREV_IO = [None] # (read_sectors, write_sectors)
def _base_device(dev):
"""Strip a partition suffix: sda2 -> sda, nvme0n1p2 -> nvme0n1."""
name = dev.rsplit("/", 1)[-1]
while name and name[-1].isdigit():
name = name[:-1]
if len(name) >= 2 and name[-1] == "p" and name[-2].isdigit():
name = name[:-1]
return name
def _read_mounts():
mounts = []
try:
with open("/proc/mounts") as f:
lines = f.read().splitlines()
except OSError:
return mounts
for line in lines:
parts = line.split()
if len(parts) < 3 or parts[2] not in REAL_FS:
continue
point = parts[1]
if any(m["point"] == point for m in mounts):
continue
try:
sv = os.statvfs(point)
except OSError:
continue
total = sv.f_blocks * sv.f_frsize
free = sv.f_bfree * sv.f_frsize
used = total - free
mounts.append({
"dev": parts[0], "point": point,
"base": _base_device(parts[0]),
"total": total / GIB, "used": used / GIB,
"free": free / GIB,
"pct": used / total * 100.0 if total else 0.0,
})
if len(mounts) >= 4:
break
return mounts
def _read_io():
"""(read_sectors, write_sectors) summed over the backing disks."""
bases = {m["base"] for m in _MOUNTS}
rd = wr = 0
ok = False
try:
with open("/proc/diskstats") as f:
lines = f.read().splitlines()
except OSError:
return None
for line in lines:
parts = line.split()
if len(parts) < 10 or parts[2] not in bases:
continue
rd += int(parts[5])
wr += int(parts[9])
ok = True
return (rd, wr) if ok else None
def _build_widgets():
widgets = []
n = len(_MOUNTS)
stack_y = MARGIN + n * (BAR_H + BAR_GAP) + 8
hist_y = stack_y + STACK_H + 8
hist_h = WIN_H - MARGIN - hist_y
col_w = WIN_W - 2 * MARGIN
for i, m in enumerate(_MOUNTS):
w = create("XUsageBar", "XUsageBar_%03d" % (i + 1),
MARGIN, MARGIN + i * (BAR_H + BAR_GAP), col_w, BAR_H)
w.set_prop("label", "%s %.0f GiB" % (m["point"], m["total"]))
w.set_value(m["pct"])
widgets.append(w)
stack = create("XStackBar", "XStackBar_001",
MARGIN, stack_y, col_w, STACK_H)
stack.set_prop("label", "%s disk usage" % _MOUNTS[0]["point"])
stack.set_segments([("Used", _MOUNTS[0]["used"], (0.0, 0.59, 0.24)),
("Free", _MOUNTS[0]["free"], (0.78, 0.78, 0.78))])
widgets.append(stack)
hist = create("XHistoryGraph", "XHistoryGraph_001",
MARGIN, hist_y, col_w, hist_h)
hist.set_prop("label", "Disk IO - MB/s (read / write)")
hist.set_prop("series-count", "2")
hist.set_prop("series-names", "Read MB/s|Write MB/s")
widgets.append(hist)
return widgets
def _tick():
live = _read_mounts()
for i, m in enumerate(_MOUNTS):
if i >= len(live):
break
m.update(live[i])
_WIDGETS[i].set_value(m["pct"])
stack = _WIDGETS[len(_MOUNTS)]
stack.set_segments([("Used", _MOUNTS[0]["used"], (0.0, 0.59, 0.24)),
("Free", _MOUNTS[0]["free"], (0.78, 0.78, 0.78))])
hist = _WIDGETS[len(_MOUNTS) + 1]
io = _read_io()
# 1 s tick, 512-byte sectors -> MB/s.
if io is not None and _PREV_IO[0] is not None:
hist.push((io[0] - _PREV_IO[0][0]) * 512.0 / 1e6, series=0)
hist.push((io[1] - _PREV_IO[0][1]) * 512.0 / 1e6, series=1)
_PREV_IO[0] = io
if _AREA:
_AREA[0].queue_draw()
return True
def _on_draw(area, cr):
# Dark btop-style harness background (0.07, 0.07, 0.09): the
# monitor widgets draw light-grey text on near-black panels, and
# XStackBar paints no panel of its own, so a white background
# would wash its legend out.
cr.set_source_rgb(0.07, 0.07, 0.09)
cr.paint()
for widget in _WIDGETS:
widget.draw(cr)
return False
def main():
_MOUNTS.extend(_read_mounts())
if not _MOUNTS:
_MOUNTS.append({"dev": "?", "point": "/", "base": "",
"total": 0.0, "used": 0.0, "free": 0.0,
"pct": 0.0})
_PREV_IO[0] = _read_io()
window = Gtk.Window(title="Disk Monitor - monitor")
window.set_default_size(WIN_W, WIN_H)
window.set_resizable(False)
window.connect("destroy", Gtk.main_quit)
vbox = Gtk.Box(orientation=Gtk.Orientation.VERTICAL, spacing=0)
window.add(vbox)
area = Gtk.DrawingArea()
area.set_hexpand(True)
area.set_vexpand(True)
area.connect("draw", _on_draw)
vbox.pack_start(area, True, True, 0)
_WIDGETS.extend(_build_widgets())
_AREA.append(area)
GLib.timeout_add(1000, _tick)
window.show_all()
Gtk.main()
return 0
if __name__ == "__main__":
sys.exit(main())