Add independent per-machine monitoring

Show separate resource histories for each machine in All Systems, configure the primary tray icon independently with optional per-machine icons, and display network IN/OUT as distinct traces. Migrate legacy monitor and tray selections while preserving saved preferences.
This commit is contained in:
2026-11-26 07:13:02 -06:00
parent 7628161f07
commit 5b2251c8f2
24 changed files with 1092 additions and 249 deletions

View File

@@ -11,14 +11,14 @@ from time import time
import winreg
import psutil
from PySide6.QtCore import QLockFile, QObject, Qt, QTimer, QUrl, Signal
from PySide6.QtCore import QLockFile, QObject, QSignalBlocker, Qt, QTimer, QUrl, Signal
from PySide6.QtGui import QDesktopServices
from PySide6.QtWidgets import QApplication, QDialog, QMessageBox, QSystemTrayIcon
from .about import AboutPage
from .branding import DARK, LIGHT, PUBLISHER, WEBSITE, application_icon, set_windows_identity
from .collect import Collectors
from .config import STATIC_TRAY_MODE, ConfigStore, Target, data_path
from .config import STATIC_TRAY_MODE, ConfigStore, Target, data_path, machine_ids, monitor_choices
from .credentials import CredentialStore
from .dialogs import ConnectionsDialog, SettingsDialog, TargetDialog
from .graphs import Dashboard, tray_icon
@@ -81,13 +81,16 @@ class Application(QObject):
self.collectors.changed.connect(self.sync_status)
self.icons = {}
self.menus = {}
self.monitor_machines = {}
self.about_page = AboutPage(self.root)
self.expanded = Monitor(self.dashboard, True, self.request_archive, self.open_expanded,
self.set_pin, self.about_page)
self.expanded.setWindowIcon(self.brand_icon)
self.popup = Monitor(self.dashboard, False, self.request_archive, self.open_expanded, self.set_pin)
self.hover = HoverMonitor(self.popup, self.dashboard, self.icons, self.tray_machine)
self.hover = HoverMonitor(self.popup, self.dashboard, self.icons)
for view in (self.popup, self.expanded):
view.machine.currentIndexChanged.connect(partial(self.monitor_selected, view))
self.popup.interval.currentIndexChanged.connect(
lambda _: self.remember_monitor(span=self.popup.span))
self.tray_timer = QTimer(self)
self.tray_timer.timeout.connect(self.render)
self.hover_timer = QTimer(self)
@@ -124,6 +127,7 @@ class Application(QObject):
self.sync_icons()
self.popup.sync()
self.expanded.sync()
self.restore_monitor()
self.render()
def configure_history(self):
@@ -148,32 +152,28 @@ class Application(QObject):
self.retired_storage = [db for db in self.retired_storage if db.thread.is_alive()]
def apply(self, settings):
if settings.hover_machine and settings.hover_machine not in monitor_choices(settings):
settings = replace(settings, hover_machine="")
if settings.tray_machine not in machine_ids(settings):
settings = replace(settings, tray_machine=LOCAL)
self.store.save(settings)
old_default = self.settings.default_machine
old_hover = self.settings.hover_range
self.settings = settings
self.configure()
if old_default != settings.default_machine:
self.popup.set_machine(settings.default_machine)
self.expanded.set_machine(settings.default_machine)
if old_hover != settings.hover_range:
self.popup.interval.setCurrentIndex(self.popup.interval.findData(settings.hover_range))
self.expanded.archive()
LOG.info("Settings updated")
def sync_status(self):
self.popup.sync()
self.expanded.sync()
self.hover.reposition()
self.sync_menus()
self.refresh_views()
def scopes(self):
cfg = self.settings
if cfg.tray_mode == "Consolidated":
return [ALL]
if cfg.tray_mode == "Selected remote":
return [cfg.tray_remote] if any(t.identifier == cfg.tray_remote for t in cfg.targets) else [LOCAL]
return [LOCAL] + ([t.identifier for t in cfg.targets if t.tray] if cfg.tray_mode == "Separate" else [])
if not cfg.separate_tray_icons:
return [cfg.tray_machine]
return list(dict.fromkeys((cfg.tray_machine, LOCAL, *(t.identifier for t in cfg.targets if t.tray))))
def sync_icons(self):
scopes = self.scopes()
@@ -184,7 +184,6 @@ class Application(QObject):
icon.setContextMenu(None)
icon.deleteLater()
self.menus.pop(machine).deleteLater()
self.monitor_machines.pop(machine, None)
for machine in scopes:
if machine in self.icons:
continue
@@ -203,17 +202,45 @@ class Application(QObject):
if not menu.isVisible():
menu.refresh()
def tray_machine(self, scope):
choices = {ALL, *self.dashboard.machines()}
chosen = self.monitor_machines.get(scope, scope)
return chosen if chosen in choices else scope if scope in choices else LOCAL
def monitor_machine(self):
choices = monitor_choices(self.settings)
return next((choice for choice in (self.settings.hover_machine, self.settings.default_machine)
if choice in choices), LOCAL)
def restore_monitor(self):
machine = self.monitor_machine()
self.popup.set_machine(machine)
self.expanded.set_machine(machine)
with QSignalBlocker(self.popup.interval):
self.popup.interval.setCurrentIndex(self.popup.interval.findData(self.settings.hover_range))
self.hover.reposition()
self.sync_menus()
def monitor_selected(self, view, _index):
self.remember_monitor(machine=view.selected_machine)
def remember_monitor(self, machine=None, span=None):
changes = {}
if machine in monitor_choices(self.settings) and machine != self.settings.hover_machine:
changes["hover_machine"] = machine
if span is not None and span != self.settings.hover_range:
changes["hover_range"] = span
if not changes:
return
updated = replace(self.settings, **changes)
try:
self.store.save(updated)
except OSError as exc:
self.restore_monitor()
QMessageBox.warning(self.popup, "Monitor selection", str(exc))
return
# Display preferences need no collector restart or archive reset.
self.settings = self.collectors.settings = updated
self.restore_monitor()
def select_machine(self, machine, scope):
self.monitor_machines[scope] = machine
self.expanded.set_machine(machine)
self.remember_monitor(machine=machine)
self.hover.show(scope)
self.render()
self.sync_menus()
def set_tray_display(self, mode):
if mode == self.settings.mode:
@@ -228,7 +255,7 @@ class Application(QObject):
if reason == QSystemTrayIcon.ActivationReason.Trigger:
self.toggle_pin(machine)
elif reason == QSystemTrayIcon.ActivationReason.DoubleClick:
self.open_expanded(self.tray_machine(machine))
self.open_expanded()
def toggle_pin(self, machine):
self.hover.pin(not self.popup.pinned or self.hover.anchor != machine, machine)
@@ -241,14 +268,12 @@ class Application(QObject):
def render(self):
now = time()
for machine, icon in self.icons.items():
scope = self.tray_machine(machine)
members = self.dashboard.machines() if scope == ALL else (scope,)
initializing = all(self.dashboard.state(member) == Connection.CONNECTING
and member not in self.collectors.last for member in members)
initializing = (self.dashboard.state(machine) == Connection.CONNECTING
and machine not in self.collectors.last)
if self.settings.mode == STATIC_TRAY_MODE or initializing:
image = self.brand_icon
else:
image = tray_icon(self.dashboard, scope, now)
image = tray_icon(self.dashboard, machine, now)
if icon.icon().cacheKey() != image.cacheKey():
icon.setIcon(image)
@@ -258,8 +283,9 @@ class Application(QObject):
view.refresh()
def open_expanded(self, machine=None, history=False):
if machine in self.dashboard.machines() or machine == ALL:
self.expanded.set_machine(machine)
if machine not in monitor_choices(self.settings):
machine = self.monitor_machine()
self.expanded.set_machine(machine)
if history:
index = self.expanded.interval.findData(3600)
self.expanded.interval.setCurrentIndex(max(0, index))
@@ -271,12 +297,12 @@ class Application(QObject):
if not self.storage:
return
kind, device = selection
signature = (scope, span, selection)
machines = self.dashboard.monitored() if scope == ALL else [scope]
signature = (scope, span, selection, tuple(machines))
if signature == self.archive_signature:
return
self.archive_signature = signature
self.archive_token += 1
machines = self.dashboard.machines() if scope == ALL else [scope]
keys = {(machine, device, metric) for machine in machines for metric in METRIC_NAMES}
if kind:
keys.update((machine, TOTAL, metric) for machine in machines for metric in METRIC_NAMES)
@@ -286,7 +312,7 @@ class Application(QObject):
if token != self.archive_token:
return
self.dashboard.archived = results
if self.expanded.isVisible():
if self.expanded.monitor_visible:
self.expanded.refresh()
def report_history_error(self, message):
@@ -504,7 +530,7 @@ def main():
try:
controller = Application(app, root)
if not controller.settings.minimized:
controller.open_expanded(controller.settings.default_machine)
controller.open_expanded()
return app.exec()
finally:
if controller is not None:

View File

@@ -6,12 +6,13 @@ from pathlib import Path
from dataclasses import asdict, dataclass, field, fields
from uuid import uuid4
from .model import ALL, DISK_MODES, INTERVALS, LOCAL, RANGES, RESOURCES
from .model import ALL, DISK_MODES, INTERVALS, LOCAL, NETWORK, RANGES, RESOURCES
LOG = logging.getLogger(__name__)
APP_DIR = "Adaptive Resource Monitor"
STATIC_TRAY_MODE = "Application Icon"
TRAY_MODES = ("Overlay", "Stacked", "Composite", STATIC_TRAY_MODE)
LEGACY_PEAK = "@peak"
def data_path():
@@ -57,7 +58,7 @@ class Target:
@classmethod
def from_dict(cls, source):
cfg = cls(**existing_values(cls, source))
if not isinstance(cfg.identifier, str) or not cfg.identifier or cfg.identifier in (LOCAL, ALL):
if not isinstance(cfg.identifier, str) or not cfg.identifier or cfg.identifier in (LOCAL, ALL, LEGACY_PEAK):
cfg.identifier = str(uuid4())
for key in ("name", "host", "username", "key_file", "credential"):
if not isinstance(getattr(cfg, key), str):
@@ -79,10 +80,11 @@ class Settings:
theme: str = "System"
default_machine: str = LOCAL
mode: str = "Overlay"
tray_mode: str = "Local"
tray_remote: str = ""
tray_machine: str = LOCAL
separate_tray_icons: bool = False
resources: list[str] = field(default_factory=lambda: list(RESOURCES))
colors: dict[str, str] = field(default_factory=lambda: {r: info[1] for r, info in RESOURCES.items()})
network_colors: dict[str, str] = field(default_factory=lambda: {key: value[1] for key, value in NETWORK.items()})
background: str = "#171a22"
transparent: bool = False
tray_refresh: float = 1
@@ -96,6 +98,7 @@ class Settings:
popup_height: int = 330
popup_columns: int = 2
hover_range: int = 60
hover_machine: str = ""
hover_resources: list[str] = field(default_factory=lambda: list(RESOURCES))
local_interval: float = 1
remote_interval: float = 2
@@ -123,14 +126,13 @@ class Settings:
for key, choices, fallback in (
("theme", ("System", "Light", "Dark"), "System"),
("mode", TRAY_MODES, "Overlay"),
("tray_mode", ("Local", "Selected remote", "Separate", "Consolidated"), "Local"),
("disk_mode", DISK_MODES, "disk.total"),
("log_level", ("DEBUG", "INFO", "WARNING", "ERROR"), "INFO"),
):
value = getattr(cfg, key)
if not isinstance(value, str) or value not in choices:
setattr(cfg, key, fallback)
for key in ("default_machine", "tray_remote", "history_file"):
for key in ("default_machine", "history_file", "hover_machine"):
if not isinstance(getattr(cfg, key), str):
setattr(cfg, key, getattr(cls(), key))
for key in ("resources", "hover_resources", "gpus", "disks", "interfaces"):
@@ -146,12 +148,42 @@ class Settings:
setattr(cfg, key, number(getattr(cfg, key), 0, 0, 2**50))
colors = cfg.colors if isinstance(cfg.colors, dict) else {}
cfg.colors = {r: valid_color(colors.get(r), info[1]) for r, info in RESOURCES.items()}
network_colors = cfg.network_colors if isinstance(cfg.network_colors, dict) else {}
cfg.network_colors = {key: valid_color(network_colors.get(key), value[1])
for key, value in NETWORK.items()}
cfg.background = valid_color(cfg.background, "#171a22")
cfg.targets = [Target.from_dict(item) for item in cfg.targets if isinstance(item, dict)] if isinstance(cfg.targets, list) else []
cfg.targets = list({target.identifier: target for target in cfg.targets}.values())
legacy_tray = source.get("tray_mode")
if "tray_machine" not in source and legacy_tray == "Selected remote":
cfg.tray_machine = source.get("tray_remote")
if not isinstance(cfg.tray_machine, str) or cfg.tray_machine not in machine_ids(cfg):
cfg.tray_machine = LOCAL
if "separate_tray_icons" not in source:
cfg.separate_tray_icons = legacy_tray == "Separate"
elif not isinstance(cfg.separate_tray_icons, bool):
cfg.separate_tray_icons = False
if cfg.default_machine == LEGACY_PEAK:
cfg.default_machine = ALL
if cfg.hover_machine == LEGACY_PEAK:
cfg.hover_machine = ALL
if cfg.hover_machine not in monitor_choices(cfg):
cfg.hover_machine = ""
# The old consolidated setting selected the all-machine view implicitly
# when neither a saved monitor nor an explicit non-local default existed.
if legacy_tray == "Consolidated" and not cfg.hover_machine and cfg.default_machine == LOCAL:
cfg.hover_machine = ALL
return cfg
def machine_ids(settings):
return {LOCAL, *(target.identifier for target in settings.targets)}
def monitor_choices(settings):
return machine_ids(settings) | {ALL}
def valid_color(value, default):
if isinstance(value, str) and len(value) == 7 and value.startswith("#"):
if all(char in "0123456789abcdef" for char in value[1:].lower()):

View File

@@ -11,7 +11,7 @@ from PySide6.QtWidgets import (
)
from .config import TRAY_MODES
from .model import DISK_MODES, LOCAL, RANGES, RESOURCES, Connection
from .model import DISK_MODES, LOCAL, NETWORK, RANGES, RESOURCES, Connection
from .views import fill, interval_choices, machine_choices, plain
@@ -102,6 +102,7 @@ class SettingsDialog(QDialog):
self.controls = {}
self.tabs = QTabWidget()
self.colors = dict(self.cfg.colors)
self.network_colors = dict(self.cfg.network_colors)
self.background = self.cfg.background
layout = QVBoxLayout(self)
layout.addWidget(self.tabs)
@@ -163,10 +164,9 @@ class SettingsDialog(QDialog):
def tray(self):
form = self.section("Tray Icon")
self.select(form, "Visualization", "mode", [(v, v) for v in TRAY_MODES])
self.select(form, "Machine icons", "tray_mode",
[(v, v) for v in ("Local", "Selected remote", "Separate", "Consolidated")])
self.select(form, "Selected remote machine", "tray_remote",
[("Choose a target", "")] + [(t.name, t.identifier) for t in self.cfg.targets])
self.select(form, "Tray icon machine", "tray_machine",
[("Local Machine", LOCAL)] + [(t.name, t.identifier) for t in self.cfg.targets])
self.check(form, "Separate machine icons", "separate_tray_icons")
self.select(form, "Refresh", "tray_refresh", interval_choices())
self.select(form, "History range", "tray_range", [(v, k) for k, v in RANGES.items() if k <= 3600])
self.select(form, "Disk graph", "disk_mode", [(v, k) for k, v in DISK_MODES.items()])
@@ -176,7 +176,9 @@ class SettingsDialog(QDialog):
self.resource_choices(form, "Visible resources", "resources")
self.check(form, "Transparent background", "transparent")
for key, title, color in [("background", "Background", self.background)] + [
(key, info[0], self.colors[key]) for key, info in RESOURCES.items()
(key, info[0], self.colors[key]) for key, info in RESOURCES.items() if key != "net"
] + [
(key, f"Network {direction}", self.network_colors[key]) for key, (direction, _) in NETWORK.items()
]:
button = QPushButton(color)
button.clicked.connect(lambda _, key=key, button=button: self.choose_color(key, button))
@@ -188,6 +190,8 @@ class SettingsDialog(QDialog):
button.setText(color.name())
if key == "background":
self.background = color.name()
elif key in NETWORK:
self.network_colors[key] = color.name()
else:
self.colors[key] = color.name()
@@ -247,7 +251,8 @@ class SettingsDialog(QDialog):
def save(self):
updates = {key: getter() for key, getter in self.controls.items()}
cfg = replace(self.app.settings, **updates, background=self.background, colors=self.colors)
cfg = replace(self.app.settings, **updates, background=self.background, colors=self.colors,
network_colors=self.network_colors)
try:
self.app.apply(cfg)
if self.startup.isChecked() != self.app.startup_enabled():

View File

@@ -5,7 +5,7 @@ from PySide6.QtCore import QPointF, QRectF, QSize, Qt
from PySide6.QtGui import QColor, QIcon, QPainter, QPainterPath, QPen, QPixmap
from PySide6.QtWidgets import QSizePolicy, QWidget
from .model import ALL, Connection, LOCAL, RESOURCES, TOTAL, current_reading, graph_scale, normalized
from .model import ALL, Connection, LOCAL, NETWORK, RESOURCES, TOTAL, current_reading, graph_scale, normalized
METRICS = {kind: d[2] for kind, d in RESOURCES.items()}
@@ -14,6 +14,12 @@ def metric_for(kind, settings):
return settings.disk_mode if kind == "disk" else METRICS[kind]
def resource_series(kind, settings):
if kind == "net":
return tuple(settings.network_colors.items())
return ((metric_for(kind, settings), settings.colors[kind]),)
def selected_resource(machine, kind, settings):
return machine == LOCAL or any(target.identifier == machine and kind in target.resources
for target in settings.targets)
@@ -47,8 +53,8 @@ def bucket_peaks(points, now, span, columns):
return result
def across_series(series, now, span, gap, columns):
"""Peak per time bin, with identity attached to the winning observation."""
def composite_samples(series, now, span, gap, columns):
"""Pick the strongest resource trace within each time bin of one machine."""
step = max(span / columns, min(gap, span) / 3)
size = max(1, int(span / step))
bins = {}
@@ -108,9 +114,8 @@ class Dashboard:
def machines(self):
return [LOCAL] + [target.identifier for target in self.settings.targets]
def members(self, scope, kind):
machines = self.machines() if scope == ALL else [scope]
return [machine for machine in machines if selected_resource(machine, kind, self.settings)]
def monitored(self):
return [LOCAL] + [target.identifier for target in self.settings.targets if target.enabled]
def state(self, machine):
status = self.collectors.statuses.get(machine)
@@ -138,26 +143,24 @@ class Dashboard:
candidate = self.collectors.history.last_valid.get(key, candidate)
return current_reading(candidate, status, self.interval(machine), now)
def get(self, scope, kind, metric, device, span, now, columns, archive=False):
machines = self.members(scope, kind)
rows = {machine: self.history((machine, device, metric), now - span, archive)
for machine in machines}
scale = plot_scale(metric, self.settings, (value for values in rows.values() for value in values))
points = {machine: [(item.timestamp, normalized(item, scale)) for item in values]
for machine, values in rows.items()}
gap = max((max(2, self.interval(machine) * 3) for machine in machines), default=3)
def series(self, machine, kind, metrics, device, span, now, archive=False):
"""Normalize one machine's resource traces against a shared reference."""
enabled = selected_resource(machine, kind, self.settings)
histories = {
metric: self.history((machine, device, metric), now - span, archive) if enabled else []
for metric in metrics
}
scale = plot_scale(metrics[0], self.settings,
(item for values in histories.values() for item in values))
gap = max(2, self.interval(machine) * 3)
if archive:
gap = max(gap, span / 1200)
actual = {machine: self.observation(machine, kind, device, metric, now) for machine in machines}
if scope == ALL:
chosen = max((m for m, r in actual.items() if r and r.valid), key=lambda m: actual[m].value,
default=None)
peak = across_series(points, now, span, gap, columns)
chart = [(stamp, value) for stamp, value, _ in peak]
else:
chosen = scope
chart = points.get(scope, [])
return chart, scale, gap, actual.get(chosen), chosen, rows
result = {}
for metric, values in histories.items():
points = [(item.timestamp, normalized(item, scale)) for item in values]
current = self.observation(machine, kind, device, metric, now) if enabled else None
result[metric] = points, current
return result, scale, gap
def paint_tray(painter, size, data, settings, period, now, status):
@@ -167,34 +170,41 @@ def paint_tray(painter, size, data, settings, period, now, status):
rect = QRectF(1, 1, size - 2, size - 3)
if settings.mode == "Stacked" and data:
height = rect.height() / len(data)
for index, (kind, points, gap) in enumerate(data):
for index, (traces, gap) in enumerate(data):
band = QRectF(rect.x(), rect.y() + height * index, rect.width(), max(1, height - .35))
shade = QColor(settings.colors[kind])
shade = QColor(traces[0][2])
shade.setAlpha(63)
painter.setPen(QPen(shade, .6))
painter.drawLine(band.bottomLeft(), band.bottomRight())
stroke(painter, band, points, now, period, gap, settings.colors[kind], .8)
for _, points, color in traces:
stroke(painter, band, points, now, period, gap, color, .8)
elif settings.mode == "Composite" and data:
gap = max(gap for _, _, gap in data)
combined = across_series({kind: points for kind, points, _ in data}, now, period, gap, size)
gap = max(gap for _, gap in data)
points = {metric: values for traces, _ in data for metric, values, _ in traces}
colors = {metric: color for traces, _ in data for metric, _, color in traces}
for metric in NETWORK:
if metric in points:
stroke(painter, rect, points[metric], now, period, gap, colors[metric], .7)
combined = composite_samples(points, now, period, gap, size)
for left, right in zip(combined, combined[1:]):
if left[1] is not None and right[1] is not None and right[0] - left[0] <= gap:
stroke(painter, rect, [(left[0], left[1]), (right[0], right[1])], now, period, gap,
settings.colors[right[2]], 1.4)
colors[right[2]], 1.4)
isolated = [point for index, point in enumerate(combined) if point[1] is not None and
(index == 0 or combined[index - 1][1] is None or point[0] - combined[index - 1][0] > gap)]
for stamp, value, kind in isolated:
stroke(painter, rect, [(stamp, value)], now, period, gap, settings.colors[kind], 1.4)
stroke(painter, rect, [(stamp, value)], now, period, gap, colors[kind], 1.4)
else:
for kind, points, gap in data:
stroke(painter, rect, points, now, period, gap, settings.colors[kind])
for traces, gap in data:
for _, points, color in traces:
stroke(painter, rect, points, now, period, gap, color)
if status:
painter.setPen(QPen(QColor("#151820"), 1))
painter.setBrush(QColor("#ffd06c"))
painter.drawEllipse(QRectF(size - 5.5, .5, 5, 5))
def tray_icon(dashboard, scope, now=None):
def tray_icon(dashboard, machine, now=None):
settings = dashboard.settings
now = time() if now is None else now
period = settings.tray_range
@@ -202,13 +212,11 @@ def tray_icon(dashboard, scope, now=None):
for kind in RESOURCES:
if kind not in settings.resources:
continue
chart, _, gap, *_ = dashboard.get(scope, kind, metric_for(kind, settings), TOTAL, period, now, 40)
data.append((kind, chart, gap))
machines = dashboard.machines() if scope == ALL else [scope]
status = any(dashboard.state(machine) != Connection.ONLINE for machine in machines)
if scope == LOCAL and dashboard.settings.tray_mode == "Local":
status |= any(dashboard.state(machine) in (Connection.RETRYING, Connection.ERROR, Connection.TRUST)
for machine in dashboard.machines() if machine != LOCAL)
series = resource_series(kind, settings)
plots, _, gap = dashboard.series(machine, kind, tuple(metric for metric, _ in series),
TOTAL, period, now)
data.append(([(metric, plots[metric][0], color) for metric, color in series], gap))
status = dashboard.state(machine) != Connection.ONLINE
icon = QIcon()
for size in (16, 20, 24, 32, 40, 48):
pixmap = QPixmap(size, size)

View File

@@ -7,6 +7,7 @@ from time import time
LOCAL = "local"
ALL = "@all"
TOTAL = "@total"
NETWORK = {"net.receive": ("IN", "#65df79"), "net.transmit": ("OUT", "#ff686b")}
INTERVALS = (0.5, 1, 2, 5, 10)
RANGES = {30: "30 seconds", 60: "60 seconds", 300: "5 minutes", 900: "15 minutes",
1800: "30 minutes", 3600: "1 hour", 21600: "6 hours", 86400: "1 day",

View File

@@ -50,11 +50,12 @@ sample() {
dev=${dev//[[:space:]]/}
path=/sys/class/net/$dev
[[ -d $path ]] || continue
speed= state= physical=0
speed= state= index= physical=0
[[ ! -e $path/device ]] || physical=1
[[ ! -r $path/operstate ]] || read -r state < "$path/operstate"
[[ ! -r $path/ifindex ]] || read -r index < "$path/ifindex"
{ [[ ! -r $path/speed ]] || read -r speed < "$path/speed"; } 2>/dev/null
printf 'net\t%s\t%s\t%s\t%s\t%s\n' "$dev" "$physical" "$state" "$speed" "$rest"
printf 'net\t%s\t%s\t%s\t%s\t%s\t%s\n' "$dev" "$physical" "$state" "$speed" "$rest" "$index"
done < /proc/net/dev
for path in /sys/class/drm/card[0-9]*; do
[[ ${path##*/} =~ ^card[0-9]+$ && -r $path/device/vendor ]] || continue

View File

@@ -261,6 +261,6 @@ def interface_info():
count = w.ULONG.from_address(table.value).value
rows = (_InterfaceRow * count).from_address(table.value + ct.alignment(_InterfaceRow))
return {row.alias: (bool(row.flags & 1) and row.type in (6, 71),
row.transmit, row.receive) for row in rows}
row.transmit, row.receive, bytes(row.guid)) for row in rows}
finally:
free(table)

View File

@@ -328,10 +328,10 @@ class LinuxParser:
selected("disk", key, key, disk_metrics(read, write, reads, writes,
min(100, active / 10) if active is not None else None),
not self.target.disks or key in self.target.disks)
for key, physical, state, speed, row in (row for row in sections["net"] if len(row) == 5):
for key, physical, state, speed, row, *identity in (row for row in sections["net"] if len(row) in (5, 6)):
v = integers(row, 16)
if v:
receive, transmit = counters("net:" + key, (v[0], v[8]))
receive, transmit = counters(("net", key, state, *identity), (v[0], v[8]))
link = num(speed)
up = state == "up" if state in ("up", "down", "lowerlayerdown", "dormant") else None
link = link if link and link > 0 and up else None

View File

@@ -170,26 +170,34 @@ class Network(Counters):
def __init__(self, settings):
super().__init__(settings)
self.selected = settings.interfaces
self.identities = {}
def sample(self):
stamp, now = time(), monotonic()
rows = psutil.net_io_counters(pernic=True, nowrap=False) or {}
stats = psutil.net_if_stats()
native = interface_info()
selected = self.selected or [key for key in rows if native.get(key, (False, 0, 0))[0]]
absent = (False, 0, 0, None)
selected = self.selected or [key for key in rows if native.get(key, absent)[0]]
identities = {key: (native.get(key, absent)[3], stats[key].isup if key in stats else None)
for key in rows}
def convert(key, row, previous, elapsed):
if self.identities.get(key) != identities[key]:
previous = None
values = deltas(row, previous, ("bytes_recv", "bytes_sent"), elapsed, self.interval)
stat = stats.get(key)
up = stat.isup if stat else None
_, tx_link, rx_link = native.get(key, (False, 0, 0))
_, tx_link, rx_link, _ = native.get(key, absent)
if tx_link in (0, 2**64 - 1):
tx_link = (stat.speed * 1e6) if stat and stat.speed > 0 else 0
if rx_link in (0, 2**64 - 1):
rx_link = (stat.speed * 1e6) if stat and stat.speed > 0 else 0
return net_metrics(*values, up, rx_link / 1e6 if up else None, tx_link / 1e6 if up else None)
return self.measure(stamp, now, rows, selected, convert)
sample = self.measure(stamp, now, rows, selected, convert)
self.identities = identities
return sample
def os_name():

View File

@@ -73,12 +73,12 @@ class HoverState:
class HoverMonitor:
def __init__(self, popup, dashboard, icons, monitor_scope):
def __init__(self, popup, dashboard, icons):
self.popup, self.dashboard, self.icons = popup, dashboard, icons
self.monitor_scope = monitor_scope
self.cursor = NativeCursor()
self.state = HoverState()
self.anchor = None
self.location = None
def tick(self):
raw, cursor = self.cursor.raw(), QCursor.pos()
@@ -109,7 +109,6 @@ class HoverMonitor:
screen = QGuiApplication.screenAt(QCursor.pos()) or QGuiApplication.primaryScreen()
if screen is None:
return
cfg = self.dashboard.settings
screen_rect = screen.geometry()
raw, qt = self.cursor.raw(), QCursor.pos()
if raw is not None and not raw_rect.isEmpty():
@@ -120,11 +119,17 @@ class HoverMonitor:
else:
rect = QRect(qt if screen_rect.contains(qt) else screen_rect.center(), QSize(1, 1))
self.anchor = machine
self.popup.set_machine(self.monitor_scope(machine))
position = place_popup(screen.availableGeometry(), rect, QSize(cfg.popup_width, cfg.popup_height))
self.popup.setGeometry(position)
self.location = screen, rect
self.reposition()
self.popup.show()
self.popup.refresh()
self.reposition()
def reposition(self):
if self.location is not None:
screen, rect = self.location
position = place_popup(screen.availableGeometry(), rect, self.popup.popup_size())
self.popup.setGeometry(position)
def pin(self, value, machine=None):
self.popup.pinned = value
@@ -132,4 +137,4 @@ class HoverMonitor:
self.popup.pin.setChecked(value)
self.popup.pin.setText("Unpin" if value else "Pin")
if value and (not self.popup.isVisible() or machine is not None):
self.show(machine or self.popup.selected_machine)
self.show(machine or self.anchor or next(iter(self.icons), None))

View File

@@ -19,7 +19,7 @@ class TrayMenu(QMenu):
self.add_header()
self.addSeparator()
open_monitor = self.action(self, "Open Resource Monitor", SP.SP_ComputerIcon,
lambda: app.open_expanded(app.tray_machine(scope)))
app.open_expanded)
self.setDefaultAction(open_monitor)
self.pin = self.action(self, "Pin Resource Monitor", None, lambda: app.toggle_pin(scope))
self.pin.setCheckable(True)
@@ -44,7 +44,7 @@ class TrayMenu(QMenu):
mode_group.addAction(action)
self.modes[mode] = action
self.action(self, "Resource History", SP.SP_FileDialogListView,
lambda: app.open_expanded(app.tray_machine(scope), True))
lambda: app.open_expanded(history=True))
self.addSeparator()
targets = self.submenu("Remote Targets", SP.SP_DriveNetIcon)
@@ -113,7 +113,7 @@ class TrayMenu(QMenu):
}
self.remote.menuAction().setVisible(bool(targets))
choices = {LOCAL: self.local, ALL: self.all, **self.remote_entries}
choices[app.tray_machine(self.scope)].setChecked(True)
choices[app.monitor_machine()].setChecked(True)
self.modes[app.settings.mode].setChecked(True)
self.pin.setChecked(app.popup.pinned and app.hover.anchor == self.scope)
self.start.setChecked(app.startup_enabled())

View File

@@ -1,2 +1,2 @@
VERSION = "v0.2.0.0_alpha"
VERSION = "v0.4.1.1_alpha"
NAME = "Adaptive Resource Monitor"

View File

@@ -1,13 +1,14 @@
from time import time, strftime, localtime
from PySide6.QtCore import Qt, QSignalBlocker, QTimer
from PySide6.QtCore import QSize, Qt, QSignalBlocker, QTimer
from PySide6.QtGui import QColor, QPalette
from PySide6.QtWidgets import (
QAbstractItemView, QComboBox, QFrame, QGridLayout, QHeaderView, QHBoxLayout, QLabel,
QPushButton, QTableWidget, QTableWidgetItem, QTabWidget, QVBoxLayout, QWidget,
QPushButton, QScrollArea, QSizePolicy, QTableWidget, QTableWidgetItem, QTabWidget, QVBoxLayout, QWidget,
)
from .graphs import Plot, metric_for
from .model import ALL, LOCAL, TOTAL, Connection, INTERVALS, RANGES, RESOURCES, format_value
from .graphs import Plot, resource_series, selected_resource
from .model import ALL, LOCAL, NETWORK, TOTAL, Connection, INTERVALS, RANGES, RESOURCES, format_value
METRIC_NAMES = {
"cpu.util": "CPU utilization", "cpu.frequency": "Frequency", "cpu.temperature": "CPU temperature",
@@ -40,7 +41,7 @@ def fill(combo, values, selected=None):
def machine_choices(dashboard):
return [(dashboard.name(machine), machine) for machine in dashboard.machines()] + [("All Systems", ALL)]
return [(dashboard.name(machine), machine) for machine in (*dashboard.machines(), ALL)]
def interval_choices():
@@ -74,24 +75,83 @@ def display_value(item):
class Card(QFrame):
def __init__(self, resource, detailed):
def __init__(self, resource, detailed, compact=False):
super().__init__()
self.title = heading(QLabel(RESOURCES[resource][0]))
self.value = plain()
self.plot = Plot()
self.plot.setAccessibleName(f"{RESOURCES[resource][0]} history")
self.footer = plain()
self.footer.setWordWrap(True)
layout = QVBoxLayout(self)
layout.setContentsMargins(6, 3, 6, 4)
layout.setSpacing(3)
margins = (5, 1, 5, 2) if compact else (6, 3, 6, 4)
layout.setContentsMargins(*margins)
layout.setSpacing(1 if compact else 3)
row = QHBoxLayout()
row.addWidget(self.title, 0)
row.addStretch()
row.addWidget(self.value)
layout.addLayout(row)
self.direction_labels = {}
if resource == "net":
layout.addLayout(row)
self.direction_labels = {metric: plain() for metric in NETWORK}
for label in self.direction_labels.values():
layout.addWidget(label)
elif compact:
layout.addLayout(row)
layout.addWidget(self.value)
else:
row.addWidget(self.value)
layout.addLayout(row)
layout.addWidget(self.plot, 1)
layout.addWidget(self.footer)
self.footer.setVisible(detailed)
self.footer.setVisible(detailed and not compact)
if compact:
self.setMinimumWidth(124)
self.plot.setFixedHeight(34 if detailed else 30)
def measurements_table():
table = QTableWidget(0, 6)
table.setHorizontalHeaderLabels(("Metric", "Current", "Minimum", "Maximum", "Average", "Machine / device"))
table.verticalHeader().setVisible(False)
table.setAlternatingRowColors(True)
table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
header = table.horizontalHeader()
header.setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
header.setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
return table
class MachineSection(QFrame):
def __init__(self, expanded, refresh):
super().__init__()
self.setFrameShape(QFrame.Shape.StyledPanel)
self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed)
self.title = heading(plain())
self.title.setWordWrap(True)
layout = QVBoxLayout(self)
layout.setContentsMargins(5, 4, 5, 4)
layout.setSpacing(2)
header = QHBoxLayout()
header.addWidget(self.title, 1)
layout.addLayout(header)
self.cards = {kind: Card(kind, detailed=expanded, compact=True) for kind in RESOURCES}
grid = QGridLayout()
grid.setSpacing(3)
for column, card in enumerate(self.cards.values()):
grid.addWidget(card, 0, column)
grid.setColumnStretch(column, 1)
layout.addLayout(grid)
self.table = measurements_table() if expanded else None
if self.table is not None:
self.table.setFixedHeight(185)
layout.addWidget(self.table)
self.table.hide()
details = QPushButton("Measurements")
details.setCheckable(True)
details.toggled.connect(self.table.setVisible)
details.toggled.connect(refresh)
header.addWidget(details)
class Monitor(QWidget):
@@ -147,17 +207,25 @@ class Monitor(QWidget):
layout.setSpacing(4)
layout.addLayout(top)
layout.addWidget(self.header)
layout.addLayout(self.grid, 3)
self.single = QWidget()
single_layout = QVBoxLayout(self.single)
single_layout.setContentsMargins(0, 0, 0, 0)
single_layout.addLayout(self.grid, 3)
layout.addWidget(self.single, 1)
self.simultaneous = QScrollArea()
self.simultaneous.setWidgetResizable(True)
self.simultaneous.setAccessibleName("Individual machine histories")
groups = QWidget()
self.group_rows = QVBoxLayout(groups)
self.group_rows.setContentsMargins(1, 1, 1, 1)
self.group_rows.setSpacing(4)
self.group_rows.setAlignment(Qt.AlignmentFlag.AlignTop)
self.simultaneous.setWidget(groups)
layout.addWidget(self.simultaneous, 1)
self.sections = {}
if expanded:
self.table = QTableWidget(0, 6)
self.table.setHorizontalHeaderLabels(("Metric", "Current", "Minimum", "Maximum", "Average", "Machine / device"))
self.table.verticalHeader().setVisible(False)
self.table.setAlternatingRowColors(True)
self.table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
header = self.table.horizontalHeader()
header.setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
header.setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents)
layout.addWidget(self.table, 2)
self.table = measurements_table()
single_layout.addWidget(self.table, 2)
self.resize(900, 690)
self.machine.currentIndexChanged.connect(self.sync_devices)
self.device.currentIndexChanged.connect(self.selection_changed)
@@ -207,10 +275,20 @@ class Monitor(QWidget):
def span(self):
return self.interval.currentData() or 60
def popup_size(self):
cfg = self.dashboard.settings
if self.selected_machine != ALL:
return QSize(cfg.popup_width, cfg.popup_height)
# Cap in HoverMonitor against the work area. The scroll area keeps
# six columns together even on a narrow monitor.
rows_height = sum(max(138, section.sizeHint().height()) for section in self.sections.values())
return QSize(max(cfg.popup_width, 875), max(cfg.popup_height, rows_height + 72))
def sync_devices(self):
if not self.expanded:
return
machine = self.selected_machine
self.device.setVisible(machine != ALL)
devices = self.dashboard.collectors.devices.get(machine, {})
kinds = {"cpu": "CPU", "gpu": "GPU", "disk": "Disk", "net": "Network"}
values = [("Selected devices · aggregate", ("", TOTAL))] + [
@@ -223,11 +301,11 @@ class Monitor(QWidget):
def sync(self):
settings = self.dashboard.settings
fill(self.machine, machine_choices(self.dashboard), self.machine.currentData() or settings.default_machine)
fill(self.machine, machine_choices(self.dashboard),
self.machine.currentData() or settings.hover_machine or settings.default_machine)
ranges = [(label, span) for span, label in RANGES.items()
if span <= 3600 or (self.expanded and settings.persistent and span <= settings.retention_days * 86400)]
fill(self.interval, ranges, (self.interval.currentData() or
(60 if self.expanded else settings.hover_range)))
fill(self.interval, ranges, (self.interval.currentData() or 60) if self.expanded else settings.hover_range)
self.sync_devices()
columns = 2 if self.expanded else settings.popup_columns
kinds = tuple(self.cards) if self.expanded else tuple(
@@ -237,16 +315,38 @@ class Monitor(QWidget):
card.setVisible(resource in kinds)
for index, kind in enumerate(kinds):
self.grid.addWidget(self.cards[kind], index // columns, index % columns)
if not self.expanded:
self.resize(settings.popup_width, settings.popup_height)
self.sync_sections()
def set_machine(self, machine):
index = self.machine.findData(machine)
if index >= 0:
self.machine.setCurrentIndex(index)
self.refresh()
with QSignalBlocker(self.machine):
self.machine.setCurrentIndex(index)
self.sync_devices()
self.sync_sections()
if self.monitor_visible:
self.selection_changed()
def sync_sections(self):
both = self.selected_machine == ALL
self.single.setVisible(not both)
self.simultaneous.setVisible(both)
if not both:
return
machines = self.dashboard.monitored()
for machine in self.sections.keys() - set(machines):
section = self.sections.pop(machine)
self.group_rows.removeWidget(section)
section.hide()
section.deleteLater()
for index, machine in enumerate(machines):
if machine not in self.sections:
section = MachineSection(self.expanded, self.refresh)
self.sections[machine] = section
self.group_rows.insertWidget(index, section)
def selection_changed(self):
self.sync_sections()
if self.monitor_visible:
self.refresh()
self.archive_due.start()
@@ -258,81 +358,109 @@ class Monitor(QWidget):
def refresh(self):
self.sync_devices()
now, span, scope = time(), self.span, self.selected_machine
collectors = self.dashboard.collectors
cfg = self.dashboard.settings
archive = self.expanded and cfg.persistent
if scope == ALL:
online = sum(self.dashboard.state(machine) == Connection.ONLINE for machine in self.dashboard.machines())
text = f"{online}/{len(self.dashboard.machines())} connected · Peak per resource"
else:
status = collectors.statuses.get(scope)
os_label = collectors.systems.get(scope) or next(
(t.os_type for t in cfg.targets if t.identifier == scope), "")
last = collectors.last.get(scope)
last_text = f" · Last sample {strftime('%H:%M:%S', localtime(last))}" if self.expanded and last else ""
text = f"{os_label} · {self.dashboard.state(scope)} · Sample {self.dashboard.interval(scope):g} s{last_text}"
if status and status.detail:
text += f" · {status.detail}"
if self.expanded:
cpu_name = next((d.name for d in collectors.devices[scope].values() if d.kind == "cpu-info"), "")
if cpu_name:
text += f" · {cpu_name}"
self.sync_sections()
self.refresh_sections(now, span, archive)
return
text = self.scope_status(scope)
set_label(self.header, text + f" · Tray {cfg.tray_refresh:g} s")
device_kind, selected = self.selection
archive = self.expanded and cfg.persistent
for kind, card in self.cards.items():
if not self.expanded and kind not in cfg.hover_resources:
continue
metric = metric_for(kind, cfg)
selected_device = selected if kind == device_kind or (kind == "vram" and device_kind == "gpu") else TOTAL
chart, scale, gap, current, machine, _ = self.dashboard.get(
scope, kind, metric, selected_device, span, now, max(20, card.plot.width()), archive)
label = display_value(current)
if machine and scope == ALL:
label += f" · {self.dashboard.name(machine)}"
if kind in ("ram", "vram") and scope != ALL:
key = "ram.used" if kind == "ram" else "gpu.vram_used"
actual = collectors.history.latest(scope, selected_device, key)
if actual and actual.valid:
label += f" · {format_value(actual.value, actual.unit)}"
set_label(card.value, label)
card.plot.set_data([(chart, cfg.colors[kind])], now, span, gap)
if self.expanded:
if metric in ("disk.total", "disk.read", "disk.write", "net.total"):
set_label(card.footer, f"Scale {format_value(scale, 'B/s')}")
else:
set_label(card.footer, "0–100%")
self.refresh_card(card, scope, kind, selected_device, now, span, archive)
if self.expanded:
self.refresh_table(scope, selected, now, span, archive)
self.refresh_table(self.table, scope, selected, now, span, archive)
def refresh_table(self, scope, device, now, span, archive):
def scope_status(self, scope, concise=False):
collectors = self.dashboard.collectors
cfg = self.dashboard.settings
status = collectors.statuses.get(scope)
os_label = collectors.systems.get(scope) or next(
(t.os_type for t in cfg.targets if t.identifier == scope), "")
last = collectors.last.get(scope)
last_text = f" · Last sample {strftime('%H:%M:%S', localtime(last))}" if self.expanded and last else ""
text = f"{os_label} · {self.dashboard.state(scope)} · Sample {self.dashboard.interval(scope):g} s{last_text}"
if status and status.detail:
text += f" · {status.detail}"
if self.expanded and not concise:
cpu_name = next((d.name for d in collectors.devices[scope].values() if d.kind == "cpu-info"), "")
if cpu_name:
text += f" · {cpu_name}"
return text
def refresh_sections(self, now, span, archive):
machines = self.dashboard.monitored()
online = sum(self.dashboard.state(machine) == Connection.ONLINE for machine in machines)
set_label(self.header, f"{online}/{len(machines)} connected · Individual machine histories")
for machine in machines:
section = self.sections[machine]
set_label(section.title, f"{self.dashboard.name(machine)} · {self.scope_status(machine, concise=True)}")
for kind, card in section.cards.items():
self.refresh_card(card, machine, kind, TOTAL, now, span, archive, compact=True)
if section.table is not None and section.table.isVisible():
self.refresh_table(section.table, machine, TOTAL, now, span, archive)
def refresh_card(self, card, scope, kind, device, now, span, archive, compact=False):
spec = resource_series(kind, self.dashboard.settings)
plots, scale, gap = self.dashboard.series(scope, kind, tuple(metric for metric, _ in spec),
device, span, now, archive)
lines = []
for metric, color in spec:
chart, current = plots[metric]
value = display_value(current)
if kind in ("ram", "vram") and not compact:
key = "ram.used" if kind == "ram" else "gpu.vram_used"
extra = self.dashboard.collectors.history.latest(scope, device, key)
if extra and extra.valid:
value += f" · {format_value(extra.value, extra.unit)}"
if kind == "net":
label = card.direction_labels[metric]
set_label(label, f"{NETWORK[metric][0]}: {value}")
foreground = QColor(color)
if card.palette().color(QPalette.ColorRole.Window).lightness() > 150:
foreground = foreground.darker(180)
style = f"color: {foreground.name()};"
if style != label.styleSheet():
label.setStyleSheet(style)
else:
set_label(card.value, value)
lines.append((chart, color))
card.plot.set_data(lines, now, span, gap)
rate_plot = kind == "net" or (kind == "disk" and spec[0][0] != "disk.active")
scale_text = f"Scale {format_value(scale, 'B/s')}" if rate_plot else "0–100%"
set_label(card.footer, scale_text)
if card.plot.toolTip() != scale_text:
card.plot.setToolTip(scale_text)
def refresh_table(self, table, machine, device, now, span, archive):
data = []
collectors = self.dashboard.collectors
machines = self.dashboard.machines() if scope == ALL else [scope]
for machine in machines:
device_info = collectors.devices.get(machine, {}).get(device)
label = self.dashboard.name(machine) + (f" · {device_info.name}" if device_info else "")
if scope == ALL:
label += f" · {self.dashboard.state(machine)}"
for metric, title in METRIC_NAMES.items():
archive_key = (machine, device, metric)
resource = ("vram" if metric.startswith("gpu.vram") else metric.split(".")[0])
current = self.dashboard.observation(machine, resource, device, metric, now)
if current is None and archive_key not in self.dashboard.archived:
continue
if machine not in self.dashboard.members(scope, resource):
continue
rows = self.dashboard.history(archive_key, now - span, archive)
values = [item.value for item in rows if item.valid]
current_value = display_value(current)
stats = [format_value(value, rows[-1].unit) if values else "—"
for value in ((min(values), max(values), sum(values) / len(values)) if values else (None,) * 3)]
data.append((title, current_value, *stats, label))
if self.table.rowCount() != len(data):
self.table.setRowCount(len(data))
device_info = collectors.devices.get(machine, {}).get(device)
label = self.dashboard.name(machine) + (f" · {device_info.name}" if device_info else "")
for metric, title in METRIC_NAMES.items():
resource = "vram" if metric.startswith("gpu.vram") else metric.split(".")[0]
if not selected_resource(machine, resource, self.dashboard.settings):
continue
archive_key = (machine, device, metric)
current = self.dashboard.observation(machine, resource, device, metric, now)
if current is None and (not archive or archive_key not in self.dashboard.archived):
continue
rows = self.dashboard.history(archive_key, now - span, archive)
values = [item.value for item in rows if item.valid]
current_value = display_value(current)
stats = ([format_value(value, rows[-1].unit) for value in (min(values), max(values), sum(values) / len(values))]
if values else ["—"] * 3)
data.append((title, current_value, *stats, label))
if table.rowCount() != len(data):
table.setRowCount(len(data))
for row, columns in enumerate(data):
for column, value in enumerate(columns):
item = self.table.item(row, column)
item = table.item(row, column)
if item is None:
self.table.setItem(row, column, QTableWidgetItem(value))
table.setItem(row, column, QTableWidgetItem(value))
elif item.text() != value:
item.setText(value)