Add branded Windows resource monitor
Introduce a native tray monitor for local and Linux-over-SSH telemetry, with configurable graphs, optional SQLite history, remote target management, and Windows packaging. Add Design Creations branding, an About tab, project documentation, and automated validation.
This commit is contained in:
1
arm/__init__.py
Normal file
1
arm/__init__.py
Normal file
@@ -0,0 +1 @@
|
||||
"""Adaptive Resource Monitor."""
|
||||
232
arm/about.py
Normal file
232
arm/about.py
Normal file
@@ -0,0 +1,232 @@
|
||||
"""The Design Creations About tab and bundled project documents."""
|
||||
import json
|
||||
import logging
|
||||
import platform
|
||||
import struct
|
||||
import sys
|
||||
import winreg
|
||||
from html import escape
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import QRectF, Qt, QUrl
|
||||
from PySide6.QtGui import QDesktopServices, QFont, QPainter, QPixmap
|
||||
from PySide6.QtWidgets import (
|
||||
QDialog, QDialogButtonBox, QFormLayout, QGroupBox, QHBoxLayout, QLabel,
|
||||
QPushButton, QTextBrowser, QVBoxLayout, QWidget,
|
||||
)
|
||||
|
||||
from .branding import (
|
||||
APPLICATION_IMAGE, COMPANY_LOGO, COPYRIGHT, DEVELOPER, DESCRIPTION, INSTALL_ID,
|
||||
SUPPORT_URL, WEBSITE, asset, document,
|
||||
)
|
||||
from .version import NAME, VERSION
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
DOCS = {
|
||||
"README.md": "Project Guide",
|
||||
"CHANGELOG.md": "Change Log",
|
||||
"LICENSE.md": "Software License",
|
||||
"THIRD_PARTY.md": "Third-party Notices",
|
||||
}
|
||||
UPDATE_STATUS = "No update channel configured."
|
||||
UNINSTALL_KEY = rf"Software\Microsoft\Windows\CurrentVersion\Uninstall\{INSTALL_ID}_is1"
|
||||
|
||||
|
||||
def release_classification():
|
||||
return VERSION.partition("_")[2].capitalize() or "Stable"
|
||||
|
||||
|
||||
def installation():
|
||||
if not getattr(sys, "frozen", False):
|
||||
return "Source checkout", document("README.md").parent
|
||||
directory = Path(sys.executable).resolve().parent
|
||||
for view in (winreg.KEY_WOW64_64KEY, winreg.KEY_WOW64_32KEY):
|
||||
try:
|
||||
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, UNINSTALL_KEY, 0, winreg.KEY_READ | view) as key:
|
||||
path, _ = winreg.QueryValueEx(key, "InstallLocation")
|
||||
if path and Path(path).resolve() == directory:
|
||||
return "Windows installed", directory
|
||||
except OSError:
|
||||
continue
|
||||
return "Windows portable", directory
|
||||
|
||||
|
||||
def build_data():
|
||||
try:
|
||||
data = json.loads(document("BUILD.json").read_text(encoding="utf-8"))
|
||||
return data if isinstance(data, dict) else {}
|
||||
except (OSError, ValueError):
|
||||
return {}
|
||||
|
||||
|
||||
def link(url, text, color):
|
||||
return f'<a style="color:{color}" href="{escape(url, quote=True)}">{escape(text)}</a>'
|
||||
|
||||
|
||||
class BrandImage(QWidget):
|
||||
def __init__(self, picture, description, size=(138, 116)):
|
||||
super().__init__()
|
||||
self.setFixedSize(*size)
|
||||
self.setAccessibleName(description)
|
||||
self.picture = picture
|
||||
|
||||
def paintEvent(self, _event):
|
||||
if self.picture.isNull():
|
||||
return
|
||||
size = self.picture.size().scaled(self.size(), Qt.AspectRatioMode.KeepAspectRatio)
|
||||
destination = QRectF((self.width() - size.width()) / 2, (self.height() - size.height()) / 2,
|
||||
size.width(), size.height())
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.SmoothPixmapTransform)
|
||||
painter.drawPixmap(destination, self.picture, QRectF(self.picture.rect()))
|
||||
|
||||
|
||||
class AboutPage(QWidget):
|
||||
def __init__(self, data_root):
|
||||
super().__init__()
|
||||
self.data_root = data_root
|
||||
self.setObjectName("armAbout")
|
||||
self.setAccessibleName(f"About {NAME}")
|
||||
self.documents = {name: label for name, label in DOCS.items() if document(name).is_file()}
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(10, 9, 10, 10)
|
||||
layout.setSpacing(9)
|
||||
header = QHBoxLayout()
|
||||
header.setSpacing(12)
|
||||
self.app_image = BrandImage(QPixmap(str(asset(APPLICATION_IMAGE))), f"{NAME} application image")
|
||||
self.company_image = BrandImage(QPixmap(str(asset(COMPANY_LOGO))), "Design Creations logo")
|
||||
header.addWidget(self.app_image)
|
||||
|
||||
center = Qt.AlignmentFlag.AlignCenter
|
||||
identity = QVBoxLayout()
|
||||
identity.setSpacing(4)
|
||||
identity.addStretch()
|
||||
self.title = QLabel(NAME, alignment=center)
|
||||
self.title.setWordWrap(True)
|
||||
self.title.setFont(QFont("Georgia", 26, QFont.Weight.Bold))
|
||||
identity.addWidget(self.title)
|
||||
attribution = QLabel(f"{DEVELOPER} · {COPYRIGHT}", alignment=center)
|
||||
attribution.setWordWrap(True)
|
||||
identity.addWidget(attribution)
|
||||
self.website = QLabel(alignment=center)
|
||||
self.website.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
|
||||
self.website.linkActivated.connect(self.open_link)
|
||||
identity.addWidget(self.website)
|
||||
identity.addStretch()
|
||||
header.addLayout(identity, 1)
|
||||
header.addWidget(self.company_image)
|
||||
layout.addLayout(header)
|
||||
|
||||
information = QGroupBox("Application Information")
|
||||
details = QFormLayout(information)
|
||||
details.setHorizontalSpacing(14)
|
||||
description = QLabel(DESCRIPTION)
|
||||
description.setWordWrap(True)
|
||||
details.addRow(description)
|
||||
self.version = QLabel(VERSION)
|
||||
details.addRow("Installed version", self.version)
|
||||
details.addRow("Release classification", QLabel(release_classification()))
|
||||
license_info = ("See Software License below." if "LICENSE.md" in self.documents
|
||||
else "Project license terms unavailable.")
|
||||
details.addRow("Software license", QLabel(license_info))
|
||||
details.addRow("Updates", QLabel(UPDATE_STATUS))
|
||||
view = QPushButton("View Details")
|
||||
view.clicked.connect(self.show_details)
|
||||
buttons = QHBoxLayout()
|
||||
buttons.addWidget(view)
|
||||
buttons.addStretch()
|
||||
details.addRow(buttons)
|
||||
layout.addWidget(information)
|
||||
|
||||
self.links = QLabel(alignment=center)
|
||||
self.links.setWordWrap(True)
|
||||
self.links.setTextInteractionFlags(Qt.TextInteractionFlag.TextBrowserInteraction)
|
||||
self.links.linkActivated.connect(self.open_link)
|
||||
layout.addWidget(self.links)
|
||||
|
||||
self.document_group = QGroupBox("Change Log")
|
||||
document_layout = QVBoxLayout(self.document_group)
|
||||
self.browser = QTextBrowser()
|
||||
self.browser.setAccessibleName("Project documentation")
|
||||
self.browser.setOpenLinks(False)
|
||||
self.browser.anchorClicked.connect(lambda url: self.open_link(url.toString()))
|
||||
self.browser.setMinimumHeight(135)
|
||||
document_layout.addWidget(self.browser)
|
||||
layout.addWidget(self.document_group, 1)
|
||||
self.show_document("CHANGELOG.md")
|
||||
|
||||
def theme(self, colors):
|
||||
self.setStyleSheet(f"""
|
||||
QWidget#armAbout {{ background: {colors.background}; }}
|
||||
QWidget#armAbout QLabel {{ color: {colors.text}; }}
|
||||
QWidget#armAbout QGroupBox {{
|
||||
color: {colors.accent}; border: 1px solid {colors.border};
|
||||
border-radius: 4px; margin-top: 8px; padding: 7px 6px 5px;
|
||||
}}
|
||||
QWidget#armAbout QGroupBox::title {{
|
||||
subcontrol-origin: margin; left: 8px; padding: 0 4px;
|
||||
}}
|
||||
QWidget#armAbout QTextBrowser {{
|
||||
background: {colors.panel}; color: {colors.text};
|
||||
border: 1px solid {colors.border}; selection-background-color: {colors.highlight};
|
||||
}}
|
||||
QWidget#armAbout QPushButton {{
|
||||
background: {colors.panel}; color: {colors.text}; padding: 4px 10px;
|
||||
border: 1px solid {colors.border}; border-radius: 3px;
|
||||
}}
|
||||
QWidget#armAbout QPushButton:hover, QWidget#armAbout QPushButton:focus {{
|
||||
background: {colors.highlight}; border-color: {colors.accent};
|
||||
}}
|
||||
""")
|
||||
self.website.setText(link(WEBSITE, "www.designcreations.us", colors.accent))
|
||||
items = [link(name, label, colors.accent) for name, label in self.documents.items()]
|
||||
items.append(link(SUPPORT_URL, "Contact & Support", colors.accent))
|
||||
self.links.setText(" | ".join(items))
|
||||
|
||||
def show_document(self, name):
|
||||
if name not in self.documents:
|
||||
return
|
||||
path = document(name)
|
||||
self.document_group.setTitle(self.documents[name])
|
||||
try:
|
||||
self.browser.setMarkdown(path.read_text(encoding="utf-8"))
|
||||
except (OSError, UnicodeError) as exc:
|
||||
LOG.warning("Unable to read About document %s: %s", name, exc)
|
||||
self.browser.setPlainText(f"Unable to open {name}.")
|
||||
self.browser.verticalScrollBar().setValue(0)
|
||||
|
||||
def open_link(self, target):
|
||||
if target in self.documents:
|
||||
self.show_document(target)
|
||||
elif QUrl(target).scheme() == "https":
|
||||
QDesktopServices.openUrl(QUrl(target))
|
||||
|
||||
def show_details(self):
|
||||
kind, directory = installation()
|
||||
build = build_data()
|
||||
revision = build.get("source_revision") or "Unavailable"
|
||||
if build.get("source_modified"):
|
||||
revision += " (including local changes)"
|
||||
rows = (
|
||||
("Application", NAME), ("Version", VERSION), ("Release classification", release_classification()),
|
||||
("Build time (UTC)", build.get("built_at") or "Source checkout"),
|
||||
("Source revision", revision),
|
||||
("Platform", f"{platform.system()} · {platform.machine()} · {struct.calcsize('P') * 8}-bit"),
|
||||
("Installation type", kind), ("Installation location", str(directory)),
|
||||
("Application data", str(self.data_root)), ("Updates", UPDATE_STATUS),
|
||||
)
|
||||
dialog = QDialog(self)
|
||||
dialog.setWindowTitle("Application Details")
|
||||
layout = QVBoxLayout(dialog)
|
||||
form = QFormLayout()
|
||||
for name, value in rows:
|
||||
label = QLabel(str(value))
|
||||
label.setWordWrap(True)
|
||||
label.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
form.addRow(name, label)
|
||||
layout.addLayout(form)
|
||||
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Close)
|
||||
buttons.rejected.connect(dialog.reject)
|
||||
layout.addWidget(buttons)
|
||||
dialog.resize(620, dialog.sizeHint().height())
|
||||
dialog.exec()
|
||||
512
arm/application.py
Normal file
512
arm/application.py
Normal file
@@ -0,0 +1,512 @@
|
||||
from dataclasses import replace
|
||||
from functools import partial
|
||||
import logging
|
||||
from logging.handlers import RotatingFileHandler
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
from threading import Thread
|
||||
from time import time
|
||||
import winreg
|
||||
|
||||
import psutil
|
||||
from PySide6.QtCore import QLockFile, QObject, 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 .credentials import CredentialStore
|
||||
from .dialogs import ConnectionsDialog, SettingsDialog, TargetDialog
|
||||
from .graphs import Dashboard, tray_icon
|
||||
from .history_db import HistoryDb
|
||||
from .model import ALL, LOCAL, TOTAL, Connection
|
||||
from .providers.ssh import update_host_key
|
||||
from .tray import HoverMonitor
|
||||
from .tray_menu import TrayMenu
|
||||
from .version import NAME, VERSION
|
||||
from .views import METRIC_NAMES, Monitor
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
RUN_KEY = r"Software\Microsoft\Windows\CurrentVersion\Run"
|
||||
RUN_VALUE = "AdaptiveResourceMonitor"
|
||||
|
||||
|
||||
def setup_logging(root, level):
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
handler = RotatingFileHandler(root / "arm.log", maxBytes=1024 * 1024, backupCount=3, encoding="utf-8")
|
||||
handler.setFormatter(logging.Formatter("%(asctime)s %(levelname)s %(name)s %(message)s"))
|
||||
root_logger = logging.getLogger()
|
||||
root_logger.addHandler(handler)
|
||||
root_logger.setLevel(level)
|
||||
# The application logs SSH transitions with predictable, credential-free messages.
|
||||
logging.getLogger("paramiko").setLevel(logging.CRITICAL + 1)
|
||||
sys.excepthook = lambda kind, value, trace: LOG.error("Unhandled exception", exc_info=(kind, value, trace))
|
||||
return handler
|
||||
|
||||
|
||||
class Application(QObject):
|
||||
archived = Signal(object, object)
|
||||
history_error = Signal(str)
|
||||
process_info = Signal(str)
|
||||
|
||||
def __init__(self, qt, root):
|
||||
super().__init__()
|
||||
self.qt, self.root = qt, Path(root)
|
||||
self.brand_icon = application_icon()
|
||||
self.qt.setWindowIcon(self.brand_icon)
|
||||
self.store = ConfigStore(self.root / "settings.json")
|
||||
self.settings = self.store.load()
|
||||
self.logger = setup_logging(self.root, self.settings.log_level)
|
||||
LOG.info("%s %s starting", NAME, VERSION)
|
||||
self.credentials = CredentialStore()
|
||||
self.hosts = self.root / "known_hosts"
|
||||
self.storage = None
|
||||
self.retired_storage = []
|
||||
self.storage_signature = None
|
||||
self.archive_token = 0
|
||||
self.archive_signature = None
|
||||
self.history_message = ""
|
||||
self.process_message = ""
|
||||
self.diagnostic_thread = None
|
||||
self.test_keys = {}
|
||||
self.archived.connect(self.accept_archive)
|
||||
self.history_error.connect(self.report_history_error)
|
||||
self.process_info.connect(self.accept_process_info)
|
||||
self.collectors = Collectors(self.settings, self.credentials, self.hosts)
|
||||
self.dashboard = Dashboard(self.collectors)
|
||||
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.tray_timer = QTimer(self)
|
||||
self.tray_timer.timeout.connect(self.render)
|
||||
self.hover_timer = QTimer(self)
|
||||
self.hover_timer.setInterval(80)
|
||||
self.hover_timer.timeout.connect(self.hover.tick)
|
||||
self.hover_timer.start()
|
||||
self.view_timer = QTimer(self)
|
||||
self.view_timer.setInterval(500)
|
||||
self.view_timer.timeout.connect(self.refresh_views)
|
||||
self.view_timer.start()
|
||||
self.manager = None
|
||||
self.settings_dialog = None
|
||||
self._closed = False
|
||||
self.qt.styleHints().colorSchemeChanged.connect(self.change_brand_theme)
|
||||
self.change_brand_theme()
|
||||
self.configure()
|
||||
|
||||
def change_brand_theme(self, scheme=None):
|
||||
scheme = scheme or self.qt.styleHints().colorScheme()
|
||||
self.brand_colors = DARK if scheme == Qt.ColorScheme.Dark else LIGHT
|
||||
self.about_page.theme(self.brand_colors)
|
||||
self.expanded.brand_tabs(self.brand_colors)
|
||||
for menu in self.menus.values():
|
||||
menu.theme(self.brand_colors)
|
||||
|
||||
def configure(self):
|
||||
settings = self.settings
|
||||
scheme = {"Light": Qt.ColorScheme.Light, "Dark": Qt.ColorScheme.Dark, "System": Qt.ColorScheme.Unknown}
|
||||
self.qt.styleHints().setColorScheme(scheme[settings.theme])
|
||||
logging.getLogger().setLevel(settings.log_level)
|
||||
self.configure_history()
|
||||
self.collectors.apply(settings)
|
||||
self.tray_timer.start(round(1000 * settings.tray_refresh))
|
||||
self.sync_icons()
|
||||
self.popup.sync()
|
||||
self.expanded.sync()
|
||||
self.render()
|
||||
|
||||
def configure_history(self):
|
||||
cfg = self.settings
|
||||
path = Path(cfg.history_file).expanduser() if cfg.history_file else self.root / "history.sqlite"
|
||||
signature = (path, cfg.retention_days, cfg.max_history_mb) if cfg.persistent else None
|
||||
if signature == self.storage_signature:
|
||||
return
|
||||
previous = self.storage
|
||||
if previous:
|
||||
previous.stop()
|
||||
self.retired_storage.append(previous)
|
||||
self.storage_signature = signature
|
||||
predecessor = previous or next((db for db in reversed(self.retired_storage) if db.thread.is_alive()), None)
|
||||
self.storage = (HistoryDb(*signature, self.archived.emit, self.history_error.emit, previous=predecessor)
|
||||
if signature else None)
|
||||
self.collectors.storage = self.storage
|
||||
self.archive_token += 1
|
||||
self.archive_signature = None
|
||||
self.history_message = ""
|
||||
self.dashboard.archived.clear()
|
||||
self.retired_storage = [db for db in self.retired_storage if db.thread.is_alive()]
|
||||
|
||||
def apply(self, settings):
|
||||
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.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 [])
|
||||
|
||||
def sync_icons(self):
|
||||
scopes = self.scopes()
|
||||
for machine in list(self.icons):
|
||||
if machine not in scopes:
|
||||
icon = self.icons.pop(machine)
|
||||
icon.hide()
|
||||
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
|
||||
icon = QSystemTrayIcon(self)
|
||||
icon.setIcon(self.brand_icon)
|
||||
icon.activated.connect(partial(self.activate_icon, machine))
|
||||
self.icons[machine] = icon
|
||||
self.menus[machine] = TrayMenu(self, machine)
|
||||
self.menus[machine].theme(self.brand_colors)
|
||||
icon.setContextMenu(self.menus[machine])
|
||||
icon.show()
|
||||
self.sync_menus()
|
||||
|
||||
def sync_menus(self):
|
||||
for menu in self.menus.values():
|
||||
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 select_machine(self, machine, scope):
|
||||
self.monitor_machines[scope] = machine
|
||||
self.expanded.set_machine(machine)
|
||||
self.hover.show(scope)
|
||||
self.render()
|
||||
self.sync_menus()
|
||||
|
||||
def set_tray_display(self, mode):
|
||||
if mode == self.settings.mode:
|
||||
return
|
||||
try:
|
||||
self.apply(replace(self.settings, mode=mode))
|
||||
except (OSError, ValueError) as exc:
|
||||
self.sync_menus()
|
||||
QMessageBox.warning(self.expanded, "Tray Display", str(exc))
|
||||
|
||||
def activate_icon(self, machine, reason):
|
||||
if reason == QSystemTrayIcon.ActivationReason.Trigger:
|
||||
self.toggle_pin(machine)
|
||||
elif reason == QSystemTrayIcon.ActivationReason.DoubleClick:
|
||||
self.open_expanded(self.tray_machine(machine))
|
||||
|
||||
def toggle_pin(self, machine):
|
||||
self.hover.pin(not self.popup.pinned or self.hover.anchor != machine, machine)
|
||||
self.sync_menus()
|
||||
|
||||
def set_pin(self, enabled):
|
||||
self.hover.pin(enabled)
|
||||
self.sync_menus()
|
||||
|
||||
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)
|
||||
if self.settings.mode == STATIC_TRAY_MODE or initializing:
|
||||
image = self.brand_icon
|
||||
else:
|
||||
image = tray_icon(self.dashboard, scope, now)
|
||||
if icon.icon().cacheKey() != image.cacheKey():
|
||||
icon.setIcon(image)
|
||||
|
||||
def refresh_views(self):
|
||||
for view in (self.popup, self.expanded):
|
||||
if view.monitor_visible:
|
||||
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 history:
|
||||
index = self.expanded.interval.findData(3600)
|
||||
self.expanded.interval.setCurrentIndex(max(0, index))
|
||||
self.expanded.show_page()
|
||||
self.expanded.refresh()
|
||||
self.expanded.archive()
|
||||
|
||||
def request_archive(self, scope, span, selection):
|
||||
if not self.storage:
|
||||
return
|
||||
kind, device = selection
|
||||
signature = (scope, span, selection)
|
||||
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)
|
||||
self.storage.request(self.archive_token, sorted(keys), time() - span)
|
||||
|
||||
def accept_archive(self, token, results):
|
||||
if token != self.archive_token:
|
||||
return
|
||||
self.dashboard.archived = results
|
||||
if self.expanded.isVisible():
|
||||
self.expanded.refresh()
|
||||
|
||||
def report_history_error(self, message):
|
||||
self.history_message = message
|
||||
self.archive_signature = None
|
||||
|
||||
def clear_history(self, parent):
|
||||
if not self.storage:
|
||||
QMessageBox.information(parent, "Resource History", "Enable recording to access and clear the selected database.")
|
||||
return
|
||||
if QMessageBox.question(parent, "Clear Resource History", "Delete all readings in the selected history database?",
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
||||
QMessageBox.StandardButton.No) == QMessageBox.StandardButton.Yes:
|
||||
self.archive_token += 1
|
||||
self.archive_signature = None
|
||||
self.storage.send("clear", self.archive_token)
|
||||
|
||||
def diagnostics(self):
|
||||
if self.diagnostic_thread is None or not self.diagnostic_thread.is_alive():
|
||||
self.diagnostic_thread = Thread(target=self.sample_process, name="ARM diagnostics", daemon=True)
|
||||
self.diagnostic_thread.start()
|
||||
lines = [f"{NAME} {VERSION}", f"Log file {self.root / 'arm.log'}", self.process_message]
|
||||
for key, status in self.collectors.provider_status.items():
|
||||
duration = self.collectors.timings.get(key)
|
||||
timing = f" · {1000 * duration:.1f} ms" if duration is not None else ""
|
||||
lines.append(f"{self.dashboard.name(key[0])} · {key[1]} · {status.state}{timing}")
|
||||
lines.extend(f"{target.name} · {self.dashboard.state(target.identifier)}"
|
||||
for target in self.settings.targets)
|
||||
if self.history_message:
|
||||
lines.append(self.history_message)
|
||||
return "\n".join(lines)
|
||||
|
||||
def sample_process(self):
|
||||
from time import monotonic
|
||||
try:
|
||||
proc = psutil.Process()
|
||||
values = proc.cpu_times()
|
||||
now = monotonic()
|
||||
total = values.user + values.system
|
||||
previous = getattr(self, "_last_cpu", (0, now))
|
||||
self._last_cpu = total, now
|
||||
percent = (total - previous[0]) / (now - previous[1]) * 100 if now > previous[1] else 0
|
||||
self.process_info.emit(f"ARM CPU {percent:.2f}% of one logical processor · RSS {proc.memory_info().rss / 2**20:.1f} MiB")
|
||||
except (OSError, psutil.Error) as exc:
|
||||
self.process_info.emit(f"Application resource usage unavailable ({type(exc).__name__})")
|
||||
|
||||
def accept_process_info(self, message):
|
||||
self.process_message = message
|
||||
|
||||
def open_settings(self):
|
||||
if self.settings_dialog:
|
||||
self.settings_dialog.raise_()
|
||||
return
|
||||
dialog = SettingsDialog(self)
|
||||
self.settings_dialog = dialog
|
||||
try:
|
||||
dialog.exec()
|
||||
finally:
|
||||
self.settings_dialog = None
|
||||
dialog.deleteLater()
|
||||
|
||||
def manage(self):
|
||||
if self.manager:
|
||||
self.manager.raise_()
|
||||
return
|
||||
dialog = ConnectionsDialog(self)
|
||||
self.manager = dialog
|
||||
try:
|
||||
dialog.exec()
|
||||
finally:
|
||||
self.manager = None
|
||||
dialog.deleteLater()
|
||||
|
||||
def add_target(self, parent=None):
|
||||
new = Target(interval=self.settings.remote_interval, timeout=self.settings.connection_timeout,
|
||||
reconnect=self.settings.reconnect, enabled=False)
|
||||
TargetDialog(self, new, parent if isinstance(parent, QDialog) else None).exec()
|
||||
|
||||
def save_target(self, target, secret, forget):
|
||||
old = next((t for t in self.settings.targets if t.identifier == target.identifier), None)
|
||||
previous = old.credential if old else ""
|
||||
reference = self.credentials.save(target.username, secret) if secret else ("" if forget else previous)
|
||||
target = replace(target, credential=reference)
|
||||
others = [target if t.identifier == target.identifier else t for t in self.settings.targets]
|
||||
if old is None:
|
||||
others.append(target)
|
||||
try:
|
||||
self.apply(replace(self.settings, targets=others))
|
||||
except (OSError, ValueError):
|
||||
if secret:
|
||||
self.credentials.delete(reference)
|
||||
raise
|
||||
if previous and previous != reference and all(t.credential != previous for t in others):
|
||||
self.remove_secret(previous)
|
||||
self.test_keys.pop(target.identifier, None)
|
||||
|
||||
def remove_target(self, target):
|
||||
self.collectors.cancel_test(target.identifier)
|
||||
others = [t for t in self.settings.targets if t.identifier != target.identifier]
|
||||
self.apply(replace(self.settings, targets=others,
|
||||
default_machine=LOCAL if self.settings.default_machine == target.identifier else self.settings.default_machine))
|
||||
if all(t.credential != target.credential for t in others):
|
||||
self.remove_secret(target.credential)
|
||||
self.test_keys.pop(target.identifier, None)
|
||||
|
||||
def remove_secret(self, reference):
|
||||
try:
|
||||
self.credentials.delete(reference)
|
||||
except (ValueError, OSError) as exc:
|
||||
LOG.warning("Could not delete ARM credential (%s)", type(exc).__name__)
|
||||
|
||||
def approve_key(self, target, parent):
|
||||
status = self.collectors.statuses.get(target.identifier)
|
||||
trust = (status.trust if status else None) or self.test_keys.get(target.identifier)
|
||||
label = target.host if target.port == 22 else f"[{target.host}]:{target.port}"
|
||||
if not trust or trust.label != label:
|
||||
QMessageBox.information(parent, "SSH Host Key", "Test the connection to request a host key.")
|
||||
return
|
||||
result = QMessageBox.question(
|
||||
parent, "Verify SSH Host Key",
|
||||
f"SSH host {label}\n{trust.key.get_name()}\n{trust.fingerprint}\n\n"
|
||||
"Compare the fingerprint with one obtained directly from the server or its administrator. Does it match?",
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No, QMessageBox.StandardButton.No)
|
||||
if result == QMessageBox.StandardButton.Yes:
|
||||
try:
|
||||
update_host_key(self.hosts, label, trust.key)
|
||||
except (ValueError, OSError) as exc:
|
||||
QMessageBox.warning(parent, "SSH Host Key", str(exc))
|
||||
return
|
||||
self.test_keys.pop(target.identifier, None)
|
||||
if target.enabled:
|
||||
self.collectors.reconnect(target.identifier)
|
||||
else:
|
||||
self.collectors.test(target)
|
||||
|
||||
def forget_key(self, target, parent):
|
||||
label = target.host if target.port == 22 else f"[{target.host}]:{target.port}"
|
||||
if QMessageBox.question(parent, "Forget SSH Host Key", f"Remove SSH trust for {label}?",
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
||||
QMessageBox.StandardButton.No) == QMessageBox.StandardButton.Yes:
|
||||
try:
|
||||
update_host_key(self.hosts, label)
|
||||
except (OSError, ValueError) as exc:
|
||||
QMessageBox.warning(parent, "SSH Host Key", str(exc))
|
||||
return
|
||||
self.test_keys.pop(target.identifier, None)
|
||||
self.collectors.disconnect(target.identifier)
|
||||
|
||||
def startup_enabled(self):
|
||||
try:
|
||||
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, RUN_KEY) as key:
|
||||
return bool(winreg.QueryValueEx(key, RUN_VALUE)[0])
|
||||
except FileNotFoundError:
|
||||
return False
|
||||
|
||||
def set_startup(self, enabled):
|
||||
argv = [sys.executable] if getattr(sys, "frozen", False) else [sys.executable, str(Path(sys.argv[0]).resolve())]
|
||||
with winreg.CreateKey(winreg.HKEY_CURRENT_USER, RUN_KEY) as key:
|
||||
if enabled:
|
||||
winreg.SetValueEx(key, RUN_VALUE, 0, winreg.REG_SZ, subprocess.list2cmdline(argv))
|
||||
else:
|
||||
try:
|
||||
winreg.DeleteValue(key, RUN_VALUE)
|
||||
except FileNotFoundError:
|
||||
pass
|
||||
self.sync_menus()
|
||||
|
||||
def toggle_startup(self):
|
||||
try:
|
||||
self.set_startup(not self.startup_enabled())
|
||||
except OSError as exc:
|
||||
QMessageBox.warning(self.expanded, "Start with Windows", str(exc))
|
||||
|
||||
def about(self):
|
||||
self.expanded.show_page(about=True)
|
||||
|
||||
def open_website(self):
|
||||
QDesktopServices.openUrl(QUrl(WEBSITE))
|
||||
|
||||
def close(self):
|
||||
if self._closed:
|
||||
return
|
||||
self._closed = True
|
||||
for timer in (self.tray_timer, self.hover_timer, self.view_timer):
|
||||
timer.stop()
|
||||
for icon in self.icons.values():
|
||||
icon.hide()
|
||||
self.popup.hide()
|
||||
self.expanded.hide()
|
||||
self.collectors.close()
|
||||
if self.storage:
|
||||
self.storage.close()
|
||||
for database in self.retired_storage:
|
||||
database.close()
|
||||
LOG.info("%s stopped", NAME)
|
||||
logging.getLogger().removeHandler(self.logger)
|
||||
self.logger.close()
|
||||
|
||||
|
||||
def main():
|
||||
set_windows_identity()
|
||||
app = QApplication(sys.argv)
|
||||
app.setApplicationName(NAME)
|
||||
app.setApplicationVersion(VERSION)
|
||||
app.setOrganizationName(PUBLISHER)
|
||||
app.setOrganizationDomain(QUrl(WEBSITE).host())
|
||||
app.setQuitOnLastWindowClosed(False)
|
||||
root = data_path()
|
||||
root.mkdir(parents=True, exist_ok=True)
|
||||
lock = QLockFile(str(root / "active.lock"))
|
||||
lock.setStaleLockTime(0)
|
||||
if not lock.tryLock(0):
|
||||
return 0
|
||||
controller = None
|
||||
try:
|
||||
controller = Application(app, root)
|
||||
if not controller.settings.minimized:
|
||||
controller.open_expanded(controller.settings.default_machine)
|
||||
return app.exec()
|
||||
finally:
|
||||
if controller is not None:
|
||||
controller.close()
|
||||
lock.unlock()
|
||||
72
arm/branding.py
Normal file
72
arm/branding.py
Normal file
@@ -0,0 +1,72 @@
|
||||
"""Shared Design Creations identity and asset locations."""
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
import sys
|
||||
|
||||
DEVELOPER = "Sonja M Thomas"
|
||||
PUBLISHER = "SLT Design Creations, LLC"
|
||||
COPYRIGHT = f"Copyright 2010-2026 {PUBLISHER}"
|
||||
WEBSITE = "https://www.designcreations.us/"
|
||||
SUPPORT_URL = "https://www.designcreations.us/contact/index.php"
|
||||
APP_MODEL_ID = "SLTDesignCreations.AdaptiveResourceMonitor"
|
||||
INSTALL_ID = "{FB4FA82E-8715-4AC8-BD23-48E33E998D1B}"
|
||||
DESCRIPTION = (
|
||||
"Adaptive Resource Monitor is a lightweight, real-time system resource monitoring "
|
||||
"application providing combined system tray visualization, historical resource graphs, "
|
||||
"and centralized monitoring of local and remote computers."
|
||||
)
|
||||
|
||||
APPLICATION_IMAGE = "ARM_Application_Image.png"
|
||||
APPLICATION_LOGO = "ARM_Emblem.png"
|
||||
APPLICATION_ICON = "ARM_Application.ico"
|
||||
COMPANY_LOGO = "dc-design-creations.png"
|
||||
BUNDLED_ASSETS = (APPLICATION_IMAGE, APPLICATION_LOGO, APPLICATION_ICON, COMPANY_LOGO)
|
||||
ICON_SIZES = (16, 20, 24, 32, 40, 48, 64, 128, 256)
|
||||
SOURCE_ROOT = Path(__file__).resolve().parent.parent
|
||||
|
||||
|
||||
def asset(name):
|
||||
bundle = getattr(sys, "_MEIPASS", None)
|
||||
return (Path(bundle) / "branding" if bundle else SOURCE_ROOT) / name
|
||||
|
||||
|
||||
def document(name):
|
||||
if getattr(sys, "frozen", False):
|
||||
directory = Path(sys.executable).resolve().parent
|
||||
if name == "THIRD_PARTY.md":
|
||||
return directory / "Third-party notices" / "README.md"
|
||||
return directory / name
|
||||
if name == "THIRD_PARTY.md":
|
||||
return SOURCE_ROOT / "packaging" / name
|
||||
return SOURCE_ROOT / name
|
||||
|
||||
|
||||
def application_icon():
|
||||
from PySide6.QtGui import QIcon
|
||||
|
||||
icon = QIcon(str(asset(APPLICATION_ICON)))
|
||||
return icon if not icon.isNull() else QIcon(str(asset(APPLICATION_LOGO)))
|
||||
|
||||
|
||||
def set_windows_identity():
|
||||
import ctypes as ct
|
||||
|
||||
assign = ct.WinDLL("shell32").SetCurrentProcessExplicitAppUserModelID
|
||||
assign.argtypes = [ct.c_wchar_p]
|
||||
assign.restype = ct.c_long
|
||||
return assign(APP_MODEL_ID)
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Colors:
|
||||
background: str
|
||||
panel: str
|
||||
text: str
|
||||
muted: str
|
||||
border: str
|
||||
accent: str
|
||||
highlight: str
|
||||
|
||||
|
||||
DARK = Colors("#1a1612", "#211a14", "#f1e7d9", "#d5c1a8", "#704b28", "#ffc25f", "#49301a")
|
||||
LIGHT = Colors("#fbf3e6", "#fff9ee", "#302116", "#66503d", "#b78a5a", "#803f08", "#ebd1ab")
|
||||
298
arm/collect.py
Normal file
298
arm/collect.py
Normal file
@@ -0,0 +1,298 @@
|
||||
"""Collector lifecycle and the Qt delivery boundary."""
|
||||
from collections import defaultdict
|
||||
from dataclasses import replace
|
||||
import logging
|
||||
import threading
|
||||
from time import monotonic, time
|
||||
|
||||
import paramiko
|
||||
from PySide6.QtCore import QObject, Signal
|
||||
|
||||
from .model import Availability, Connection, History, LOCAL, Reading, Status, TOTAL
|
||||
from .providers.gpu import WddmGpu
|
||||
from .providers.ssh import LinuxSsh, UntrustedHost
|
||||
from .providers.windows import Cpu, Disk, Memory, Network, os_name
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
LOCAL_PROVIDERS = (Cpu, Memory, Disk, Network, WddmGpu)
|
||||
|
||||
|
||||
def problem(exc):
|
||||
if isinstance(exc, paramiko.BadHostKeyException):
|
||||
return "SSH host key changed. Verify the replacement before updating trust.", False
|
||||
if isinstance(exc, paramiko.AuthenticationException):
|
||||
return "SSH authentication failed. Check the selected credentials.", False
|
||||
if isinstance(exc, FileNotFoundError):
|
||||
return "A required local file is unavailable.", False
|
||||
if isinstance(exc, TimeoutError):
|
||||
detail = str(exc) if str(exc) in {
|
||||
"SSH hostname lookup timed out", "SSH handshake or channel setup timed out",
|
||||
"SSH telemetry response timed out",
|
||||
} else "Connection or telemetry timed out."
|
||||
return detail, True
|
||||
if isinstance(exc, (OSError, EOFError, paramiko.SSHException)):
|
||||
return f"SSH connection interrupted ({type(exc).__name__}).", True
|
||||
return f"Collection failed ({type(exc).__name__}).", True
|
||||
|
||||
|
||||
class Worker(threading.Thread):
|
||||
def __init__(self, key, factory, interval, emit, *, remote=False, retry=True, once=False):
|
||||
super().__init__(name=f"ARM {key[1]}", daemon=False)
|
||||
self.key = key
|
||||
self.machine = key[0]
|
||||
self.factory, self.interval, self.emit = factory, interval, emit
|
||||
self.remote, self.retry, self.once = remote, retry, once
|
||||
self.stopping = threading.Event()
|
||||
self.provider = None
|
||||
|
||||
def stop(self):
|
||||
self.stopping.set()
|
||||
current = self.provider
|
||||
if current is not None:
|
||||
current.cancel()
|
||||
|
||||
def status(self, state, detail="", trust=None):
|
||||
self.emit(self, Status(self.machine, state, detail, trust), "", 0)
|
||||
|
||||
def run(self):
|
||||
failures = 0
|
||||
next_due = monotonic()
|
||||
while not self.stopping.is_set():
|
||||
try:
|
||||
if self.provider is None:
|
||||
if self.remote:
|
||||
self.status(Connection.CONNECTING)
|
||||
LOG.info("Initializing provider %s for %s", self.key[1], self.machine)
|
||||
self.provider = self.factory()
|
||||
if self.stopping.is_set():
|
||||
break
|
||||
started = monotonic()
|
||||
sample = self.provider.sample()
|
||||
duration = monotonic() - started
|
||||
if self.remote and failures:
|
||||
LOG.info("SSH telemetry recovered for %s", self.machine)
|
||||
failures = 0
|
||||
self.emit(self, sample, getattr(self.provider, "os", ""), duration)
|
||||
if self.once:
|
||||
break
|
||||
next_due += self.interval
|
||||
if next_due <= monotonic():
|
||||
next_due = max(started + self.interval, monotonic() + self.interval / 2)
|
||||
self.stopping.wait(max(0, next_due - monotonic()))
|
||||
except UntrustedHost as exc:
|
||||
self.status(Connection.TRUST, "Verify the SSH host key fingerprint.", exc.host_key)
|
||||
LOG.info("SSH key approval needed for %s", self.machine)
|
||||
break
|
||||
except Exception as exc:
|
||||
if self.stopping.is_set():
|
||||
break
|
||||
failures += 1
|
||||
detail, retryable = problem(exc) if self.remote else (
|
||||
f"{self.key[1]} failed ({type(exc).__name__})", True)
|
||||
will_retry = self.retry and retryable and not self.once
|
||||
state = Connection.RETRYING if will_retry else Connection.ERROR
|
||||
level = logging.WARNING if failures == 1 else logging.DEBUG
|
||||
LOG.log(level, "%s for %s. %s%s", self.key[1], self.machine, detail,
|
||||
" Retrying." if will_retry else "")
|
||||
self.status(state, detail)
|
||||
self.close_provider()
|
||||
if not will_retry:
|
||||
break
|
||||
self.stopping.wait(min(60, 2 ** min(failures, 6)))
|
||||
next_due = monotonic()
|
||||
self.close_provider()
|
||||
|
||||
def close_provider(self):
|
||||
if self.provider is not None:
|
||||
try:
|
||||
self.provider.close()
|
||||
except Exception as exc:
|
||||
LOG.warning("Worker cleanup failed for %s (%s)", self.key[1], type(exc).__name__)
|
||||
finally:
|
||||
self.provider = None
|
||||
|
||||
|
||||
class Collectors(QObject):
|
||||
delivered = Signal(object, object, str, float)
|
||||
changed = Signal()
|
||||
test_finished = Signal(object)
|
||||
|
||||
def __init__(self, settings, credentials, hosts, storage=None):
|
||||
super().__init__()
|
||||
self.settings = settings
|
||||
self.credentials, self.hosts, self.storage = credentials, hosts, storage
|
||||
self.workers = {}
|
||||
self.retired = []
|
||||
self.keys = {}
|
||||
self.tests = {}
|
||||
self.manual = {}
|
||||
self.history = History()
|
||||
self.statuses = {LOCAL: Status(LOCAL, Connection.CONNECTING)}
|
||||
self.devices = defaultdict(dict)
|
||||
self.device_groups = defaultdict(dict)
|
||||
self.intervals = {LOCAL: settings.local_interval}
|
||||
self.systems = {LOCAL: os_name()}
|
||||
self.provider_status = {}
|
||||
self.last = {}
|
||||
self.timings = {}
|
||||
self.delivered.connect(self.receive)
|
||||
|
||||
def start(self):
|
||||
self.apply(self.settings)
|
||||
|
||||
def apply(self, settings):
|
||||
self.settings = settings
|
||||
self.retired = [worker for worker in self.retired if worker.is_alive()]
|
||||
wanted = {}
|
||||
for provider in LOCAL_PROVIDERS:
|
||||
key = (LOCAL, provider.identifier)
|
||||
filters = {"GPU": settings.gpus, "Storage": settings.disks, "Network": settings.interfaces}
|
||||
signature = (settings.local_interval, tuple(filters.get(key[1], ())))
|
||||
wanted[key] = (signature, lambda provider=provider: provider(settings), settings.local_interval, False, True)
|
||||
self.intervals[LOCAL] = settings.local_interval
|
||||
ids = {target.identifier for target in settings.targets}
|
||||
for machine in list(self.statuses):
|
||||
if machine not in ids and machine != LOCAL:
|
||||
self.statuses.pop(machine)
|
||||
self.devices.pop(machine, None)
|
||||
self.device_groups.pop(machine, None)
|
||||
self.intervals.pop(machine, None)
|
||||
self.manual.pop(machine, None)
|
||||
self.last.pop(machine, None)
|
||||
self.systems.pop(machine, None)
|
||||
self.history.remove_machine(machine)
|
||||
self.timings.pop((machine, "Linux SSH"), None)
|
||||
for target in settings.targets:
|
||||
machine = target.identifier
|
||||
self.intervals[machine] = target.interval
|
||||
if target.os_type == "Windows":
|
||||
self.statuses[machine] = Status(machine, Connection.UNSUPPORTED, "Remote Windows telemetry is planned")
|
||||
elif not target.enabled:
|
||||
self.gap_if_connected(machine)
|
||||
self.statuses[machine] = Status(machine, Connection.DISABLED)
|
||||
elif self.manual.get(machine) is False:
|
||||
self.gap_if_connected(machine)
|
||||
self.statuses[machine] = Status(machine, Connection.OFFLINE)
|
||||
else:
|
||||
signature = repr(target)
|
||||
wanted[(machine, "Linux SSH")] = (signature, self.factory(target),
|
||||
target.interval, True, target.reconnect)
|
||||
for key in list(self.workers):
|
||||
if key not in wanted or self.keys[key] != wanted[key][0]:
|
||||
self.retire(key)
|
||||
for key, (signature, factory, interval, remote, retry) in wanted.items():
|
||||
if key not in self.workers:
|
||||
if remote:
|
||||
self.statuses[key[0]] = Status(key[0], Connection.CONNECTING)
|
||||
worker = Worker(key, factory, interval, self.delivered.emit, remote=remote, retry=retry)
|
||||
self.keys[key], self.workers[key] = signature, worker
|
||||
worker.start()
|
||||
self.changed.emit()
|
||||
|
||||
def factory(self, target):
|
||||
return lambda: LinuxSsh(target, self.credentials, self.hosts)
|
||||
|
||||
def retire(self, key):
|
||||
worker = self.workers.pop(key)
|
||||
self.keys.pop(key)
|
||||
worker.stop()
|
||||
self.retired.append(worker)
|
||||
|
||||
def reconnect(self, machine):
|
||||
self.manual[machine] = True
|
||||
self.gap_if_connected(machine)
|
||||
key = (machine, "Linux SSH")
|
||||
if key in self.workers:
|
||||
self.retire(key)
|
||||
self.apply(self.settings)
|
||||
|
||||
def disconnect(self, machine):
|
||||
self.manual[machine] = False
|
||||
self.apply(self.settings)
|
||||
|
||||
def test(self, target):
|
||||
if target.os_type != "Linux":
|
||||
self.test_finished.emit(Status(target.identifier, Connection.UNSUPPORTED))
|
||||
return
|
||||
self.cancel_test(target.identifier)
|
||||
key = (target.identifier, "Test SSH")
|
||||
worker = Worker(key, self.factory(replace(target)), target.interval, self.delivered.emit,
|
||||
remote=True, retry=False, once=True)
|
||||
self.tests[key] = worker
|
||||
worker.start()
|
||||
|
||||
def cancel_test(self, machine):
|
||||
worker = self.tests.pop((machine, "Test SSH"), None)
|
||||
if worker is not None:
|
||||
worker.stop()
|
||||
self.retired.append(worker)
|
||||
|
||||
def receive(self, sender, message, os_label, duration):
|
||||
key = sender.key
|
||||
if self.tests.get(key) is sender:
|
||||
if isinstance(message, Status) and message.state == Connection.CONNECTING:
|
||||
return
|
||||
self.tests.pop(key, None)
|
||||
self.retired.append(sender)
|
||||
result = message if isinstance(message, Status) else Status(sender.machine, Connection.ONLINE, os_label)
|
||||
self.test_finished.emit(result)
|
||||
return
|
||||
if self.workers.get(key) is not sender:
|
||||
return
|
||||
machine = sender.machine
|
||||
if isinstance(message, Status):
|
||||
if machine == LOCAL:
|
||||
self.provider_status[key] = message
|
||||
self.insert_gap(machine, key[1], message.detail)
|
||||
else:
|
||||
old = self.statuses.get(machine)
|
||||
self.statuses[machine] = message
|
||||
if old and old.state == Connection.ONLINE:
|
||||
self.insert_gap(machine, key[1], message.detail)
|
||||
self.changed.emit()
|
||||
return
|
||||
old = self.statuses.get(machine)
|
||||
self.provider_status[key] = Status(machine, Connection.ONLINE)
|
||||
self.statuses[machine] = self.provider_status[key]
|
||||
self.last[machine] = max(self.last.get(machine, 0), message.timestamp)
|
||||
if os_label:
|
||||
self.systems[machine] = os_label
|
||||
self.timings[key] = duration
|
||||
self.device_groups[machine][key[1]] = {device.identifier: device for device in message.devices}
|
||||
self.devices[machine] = {device.identifier: device for group in self.device_groups[machine].values()
|
||||
for device in group.values()}
|
||||
self.history.add(message.readings)
|
||||
if self.storage:
|
||||
self.storage.record(message.readings)
|
||||
if not old or old.state != Connection.ONLINE:
|
||||
self.changed.emit()
|
||||
|
||||
def insert_gap(self, machine, provider, diagnostic):
|
||||
now = time()
|
||||
kind = {"CPU": "cpu", "GPU": "gpu", "Storage": "disk", "Network": "net",
|
||||
"Memory": "ram"}.get(provider)
|
||||
availability = Availability.ERROR if machine == LOCAL else Availability.DISCONNECTED
|
||||
items = []
|
||||
for key, history in self.history.series.items():
|
||||
if key[0] == machine and history and (kind is None or key[2].split(".")[0] == kind):
|
||||
old = history[-1]
|
||||
items.append(Reading(machine, old.device, old.metric, None, old.unit, now,
|
||||
availability, diagnostic))
|
||||
self.history.add(items)
|
||||
if self.storage:
|
||||
self.storage.record(items)
|
||||
|
||||
def gap_if_connected(self, machine):
|
||||
old = self.statuses.get(machine)
|
||||
if old and old.state == Connection.ONLINE:
|
||||
self.insert_gap(machine, "Linux SSH", "Connection closed")
|
||||
|
||||
def close(self):
|
||||
workers = list(self.workers.values()) + list(self.tests.values()) + self.retired
|
||||
self.workers.clear()
|
||||
self.tests.clear()
|
||||
self.retired = []
|
||||
for worker in workers:
|
||||
worker.stop()
|
||||
for worker in workers:
|
||||
worker.join()
|
||||
184
arm/config.py
Normal file
184
arm/config.py
Normal file
@@ -0,0 +1,184 @@
|
||||
import json
|
||||
import logging
|
||||
import math
|
||||
import os
|
||||
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
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
APP_DIR = "Adaptive Resource Monitor"
|
||||
STATIC_TRAY_MODE = "Application Icon"
|
||||
TRAY_MODES = ("Overlay", "Stacked", "Composite", STATIC_TRAY_MODE)
|
||||
|
||||
|
||||
def data_path():
|
||||
return Path(os.environ.get("LOCALAPPDATA", Path.home() / "AppData" / "Local")) / APP_DIR
|
||||
|
||||
|
||||
def existing_values(cls, source):
|
||||
return {f.name: source[f.name] for f in fields(cls) if f.name in source}
|
||||
|
||||
|
||||
def strings(value):
|
||||
return list(dict.fromkeys(x for x in value if isinstance(x, str))) if isinstance(value, list) else []
|
||||
|
||||
|
||||
def number(value, default, lower, upper, integer=False):
|
||||
if isinstance(value, (int, float)) and math.isfinite(value):
|
||||
return (int if integer else float)(min(upper, max(lower, value)))
|
||||
return default
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Target:
|
||||
identifier: str = field(default_factory=lambda: str(uuid4()))
|
||||
name: str = ""
|
||||
host: str = ""
|
||||
os_type: str = "Linux"
|
||||
method: str = "SSH"
|
||||
port: int = 22
|
||||
username: str = ""
|
||||
auth: str = "Password"
|
||||
key_file: str = ""
|
||||
credential: str = ""
|
||||
enabled: bool = True
|
||||
interval: float = 2
|
||||
reconnect: bool = True
|
||||
timeout: int = 6
|
||||
resources: list[str] = field(default_factory=lambda: list(RESOURCES))
|
||||
gpus: list[str] = field(default_factory=list)
|
||||
disks: list[str] = field(default_factory=list)
|
||||
interfaces: list[str] = field(default_factory=list)
|
||||
tray: bool = True
|
||||
|
||||
@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):
|
||||
cfg.identifier = str(uuid4())
|
||||
for key in ("name", "host", "username", "key_file", "credential"):
|
||||
if not isinstance(getattr(cfg, key), str):
|
||||
setattr(cfg, key, "")
|
||||
cfg.os_type = cfg.os_type if cfg.os_type in ("Linux", "Windows") else "Linux"
|
||||
cfg.method = "SSH" if cfg.os_type == "Linux" else "Planned"
|
||||
cfg.auth = cfg.auth if cfg.auth in ("Password", "Private key") else "Password"
|
||||
cfg.port = number(cfg.port, 22, 1, 65535, True)
|
||||
cfg.timeout = number(cfg.timeout, 6, 2, 30, True)
|
||||
cfg.interval = cfg.interval if cfg.interval in INTERVALS else 2
|
||||
for key in ("resources", "gpus", "disks", "interfaces"):
|
||||
setattr(cfg, key, strings(getattr(cfg, key)))
|
||||
return cfg
|
||||
|
||||
|
||||
@dataclass(slots=True)
|
||||
class Settings:
|
||||
minimized: bool = True
|
||||
theme: str = "System"
|
||||
default_machine: str = LOCAL
|
||||
mode: str = "Overlay"
|
||||
tray_mode: str = "Local"
|
||||
tray_remote: str = ""
|
||||
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()})
|
||||
background: str = "#171a22"
|
||||
transparent: bool = False
|
||||
tray_refresh: float = 1
|
||||
tray_range: int = 60
|
||||
disk_mode: str = "disk.total"
|
||||
disk_scale: float = 0
|
||||
net_scale: float = 0
|
||||
hover_delay: int = 350
|
||||
dismiss_delay: int = 500
|
||||
popup_width: int = 500
|
||||
popup_height: int = 330
|
||||
popup_columns: int = 2
|
||||
hover_range: int = 60
|
||||
hover_resources: list[str] = field(default_factory=lambda: list(RESOURCES))
|
||||
local_interval: float = 1
|
||||
remote_interval: float = 2
|
||||
gpus: list[str] = field(default_factory=list)
|
||||
disks: list[str] = field(default_factory=list)
|
||||
interfaces: list[str] = field(default_factory=list)
|
||||
connection_timeout: int = 6
|
||||
reconnect: bool = True
|
||||
persistent: bool = False
|
||||
retention_days: int = 7
|
||||
max_history_mb: int = 128
|
||||
history_file: str = ""
|
||||
log_level: str = "INFO"
|
||||
targets: list[Target] = field(default_factory=list)
|
||||
|
||||
@classmethod
|
||||
def from_dict(cls, source):
|
||||
cfg = cls(**existing_values(cls, source))
|
||||
for key in ("tray_refresh", "local_interval", "remote_interval"):
|
||||
if getattr(cfg, key) not in INTERVALS:
|
||||
setattr(cfg, key, 1)
|
||||
for key in ("tray_range", "hover_range"):
|
||||
if not isinstance(getattr(cfg, key), int) or getattr(cfg, key) not in RANGES:
|
||||
setattr(cfg, key, 60)
|
||||
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"):
|
||||
if not isinstance(getattr(cfg, key), str):
|
||||
setattr(cfg, key, getattr(cls(), key))
|
||||
for key in ("resources", "hover_resources", "gpus", "disks", "interfaces"):
|
||||
setattr(cfg, key, strings(getattr(cfg, key)))
|
||||
for key, default, lower, upper in (
|
||||
("popup_width", 500, 300, 1800), ("popup_height", 330, 210, 1200),
|
||||
("popup_columns", 2, 1, 3), ("hover_delay", 350, 0, 5000),
|
||||
("dismiss_delay", 500, 100, 10000), ("retention_days", 7, 1, 365),
|
||||
("max_history_mb", 128, 16, 4096), ("connection_timeout", 6, 2, 30),
|
||||
):
|
||||
setattr(cfg, key, number(getattr(cfg, key), default, lower, upper, True))
|
||||
for key in ("disk_scale", "net_scale"):
|
||||
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()}
|
||||
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())
|
||||
return cfg
|
||||
|
||||
|
||||
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()):
|
||||
return value
|
||||
return default
|
||||
|
||||
|
||||
class ConfigStore:
|
||||
def __init__(self, path):
|
||||
self.path = Path(path)
|
||||
|
||||
def load(self):
|
||||
if not self.path.is_file():
|
||||
return Settings()
|
||||
try:
|
||||
source = json.loads(self.path.read_text(encoding="utf-8"))
|
||||
if isinstance(source, dict):
|
||||
return Settings.from_dict(source)
|
||||
except (ValueError, OSError):
|
||||
LOG.warning("Could not load settings")
|
||||
return Settings()
|
||||
|
||||
def save(self, settings):
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = self.path.with_suffix(".tmp")
|
||||
try:
|
||||
temporary.write_text(json.dumps(asdict(settings), indent=2) + "\n", encoding="utf-8")
|
||||
temporary.replace(self.path)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
76
arm/credentials.py
Normal file
76
arm/credentials.py
Normal file
@@ -0,0 +1,76 @@
|
||||
"""Application-owned generic credentials in Windows Credential Manager."""
|
||||
import ctypes as ct
|
||||
from ctypes import wintypes as w
|
||||
from uuid import uuid4
|
||||
|
||||
PREFIX = "AdaptiveResourceMonitor:"
|
||||
NOT_FOUND = 1168
|
||||
|
||||
|
||||
class _Credential(ct.Structure):
|
||||
_fields_ = [("flags", w.DWORD), ("type", w.DWORD), ("target", w.LPWSTR),
|
||||
("comment", w.LPWSTR), ("written", w.FILETIME), ("size", w.DWORD),
|
||||
("blob", ct.POINTER(ct.c_ubyte)), ("persist", w.DWORD),
|
||||
("attribute_count", w.DWORD), ("attributes", ct.c_void_p),
|
||||
("alias", w.LPWSTR), ("username", w.LPWSTR)]
|
||||
|
||||
|
||||
class CredentialStore:
|
||||
def __init__(self):
|
||||
dll = ct.WinDLL("advapi32", use_last_error=True)
|
||||
self._write = dll.CredWriteW
|
||||
self._write.argtypes = (ct.POINTER(_Credential), w.DWORD)
|
||||
self._write.restype = w.BOOL
|
||||
self._read = dll.CredReadW
|
||||
self._read.argtypes = (w.LPCWSTR, w.DWORD, w.DWORD, ct.POINTER(ct.POINTER(_Credential)))
|
||||
self._read.restype = w.BOOL
|
||||
self._delete = dll.CredDeleteW
|
||||
self._delete.argtypes = (w.LPCWSTR, w.DWORD, w.DWORD)
|
||||
self._delete.restype = w.BOOL
|
||||
self._free = dll.CredFree
|
||||
self._free.argtypes = (ct.c_void_p,)
|
||||
self._free.restype = None
|
||||
|
||||
@staticmethod
|
||||
def _target(reference):
|
||||
if reference.startswith(PREFIX) and len(reference) == len(PREFIX) + 32:
|
||||
if all(char in "0123456789abcdef" for char in reference[len(PREFIX):]):
|
||||
return reference
|
||||
raise ValueError("Invalid ARM credential reference")
|
||||
|
||||
def save(self, username, secret):
|
||||
reference = PREFIX + uuid4().hex
|
||||
payload = bytearray(secret, "utf-16-le")
|
||||
if not 0 < len(payload) <= 2560:
|
||||
raise ValueError("Credential length is unsupported")
|
||||
blob = (ct.c_ubyte * len(payload)).from_buffer(payload)
|
||||
item = _Credential()
|
||||
item.type, item.target, item.username = 1, reference, username
|
||||
item.persist, item.size, item.blob = 2, len(blob), blob
|
||||
try:
|
||||
if not self._write(ct.byref(item), 0):
|
||||
raise ct.WinError(ct.get_last_error())
|
||||
finally:
|
||||
ct.memset(blob, 0, len(blob))
|
||||
return reference
|
||||
|
||||
def read(self, reference):
|
||||
if not reference:
|
||||
return None
|
||||
pointer = ct.POINTER(_Credential)()
|
||||
if not self._read(self._target(reference), 1, 0, ct.byref(pointer)):
|
||||
error = ct.get_last_error()
|
||||
if error == NOT_FOUND:
|
||||
return None
|
||||
raise ct.WinError(error)
|
||||
try:
|
||||
item = pointer.contents
|
||||
return ct.string_at(item.blob, item.size).decode("utf-16-le")
|
||||
finally:
|
||||
self._free(pointer)
|
||||
|
||||
def delete(self, reference):
|
||||
if reference and not self._delete(self._target(reference), 1, 0):
|
||||
error = ct.get_last_error()
|
||||
if error != NOT_FOUND:
|
||||
raise ct.WinError(error)
|
||||
476
arm/dialogs.py
Normal file
476
arm/dialogs.py
Normal file
@@ -0,0 +1,476 @@
|
||||
from dataclasses import replace
|
||||
from pathlib import Path
|
||||
|
||||
from PySide6.QtCore import Qt, QTimer
|
||||
from PySide6.QtGui import QColor
|
||||
from PySide6.QtWidgets import (
|
||||
QCheckBox, QColorDialog, QComboBox, QDialog, QDialogButtonBox, QDoubleSpinBox,
|
||||
QFileDialog, QFormLayout, QHBoxLayout, QLabel, QLineEdit, QListWidget, QListWidgetItem,
|
||||
QMessageBox, QPushButton, QScrollArea, QSpinBox, QTabWidget, QTableWidget, QTableWidgetItem,
|
||||
QAbstractItemView, QHeaderView, QVBoxLayout, QWidget,
|
||||
)
|
||||
|
||||
from .config import TRAY_MODES
|
||||
from .model import DISK_MODES, LOCAL, RANGES, RESOURCES, Connection
|
||||
from .views import fill, interval_choices, machine_choices, plain
|
||||
|
||||
|
||||
def checkbox(value):
|
||||
check = QCheckBox()
|
||||
check.setChecked(value)
|
||||
return check
|
||||
|
||||
|
||||
def combo(values, value):
|
||||
control = QComboBox()
|
||||
fill(control, values, value)
|
||||
return control
|
||||
|
||||
|
||||
def spin(value, low, high, suffix=""):
|
||||
control = QSpinBox()
|
||||
control.setRange(low, high)
|
||||
control.setValue(value)
|
||||
control.setSuffix(suffix)
|
||||
return control
|
||||
|
||||
|
||||
def scale_spin(value):
|
||||
control = QDoubleSpinBox()
|
||||
control.setRange(0, 1048576)
|
||||
control.setDecimals(2)
|
||||
control.setSuffix(" MiB/s")
|
||||
control.setSpecialValueText("Automatic")
|
||||
control.setValue(value / 2**20)
|
||||
return control
|
||||
|
||||
|
||||
def path_control(value, select, parent):
|
||||
field = QLineEdit(value)
|
||||
browse = QPushButton("Browse…")
|
||||
browse.clicked.connect(lambda: pick_path(field, select, parent))
|
||||
widget = QWidget()
|
||||
row = QHBoxLayout(widget)
|
||||
row.setContentsMargins(0, 0, 0, 0)
|
||||
row.addWidget(field, 1)
|
||||
row.addWidget(browse)
|
||||
return widget, field
|
||||
|
||||
|
||||
def pick_path(field, select, parent):
|
||||
filename = select(parent, "Choose file", field.text())[0]
|
||||
if filename:
|
||||
field.setText(filename)
|
||||
|
||||
|
||||
class Choices(QListWidget):
|
||||
def __init__(self, values, active):
|
||||
super().__init__()
|
||||
self.setMaximumHeight(113)
|
||||
self.setSelectionMode(QAbstractItemView.SelectionMode.NoSelection)
|
||||
selected = set(active)
|
||||
for label, key in values:
|
||||
item = QListWidgetItem(label, self)
|
||||
item.setData(Qt.ItemDataRole.UserRole, key)
|
||||
item.setFlags(item.flags() | Qt.ItemFlag.ItemIsUserCheckable)
|
||||
item.setCheckState(Qt.CheckState.Checked if key in selected else Qt.CheckState.Unchecked)
|
||||
|
||||
def keys(self):
|
||||
return [self.item(i).data(Qt.ItemDataRole.UserRole) for i in range(self.count())
|
||||
if self.item(i).checkState() == Qt.CheckState.Checked]
|
||||
|
||||
|
||||
class DeviceChoices(Choices):
|
||||
def __init__(self, devices, kind, selected):
|
||||
available = {device.identifier: device.name for device in devices.values() if device.kind == kind}
|
||||
available.update((key, key) for key in selected if key not in available)
|
||||
super().__init__([(f"{label} ({key})" if label != key else label, key)
|
||||
for key, label in available.items()], selected)
|
||||
self.setMaximumHeight(75)
|
||||
self.setToolTip("With no checked device, the provider uses its automatic selection.")
|
||||
if not available:
|
||||
self.setVisible(False)
|
||||
|
||||
|
||||
class SettingsDialog(QDialog):
|
||||
def __init__(self, app):
|
||||
super().__init__()
|
||||
self.app = app
|
||||
self.cfg = app.settings
|
||||
self.setWindowTitle("ARM Settings")
|
||||
self.resize(610, 610)
|
||||
self.controls = {}
|
||||
self.tabs = QTabWidget()
|
||||
self.colors = dict(self.cfg.colors)
|
||||
self.background = self.cfg.background
|
||||
layout = QVBoxLayout(self)
|
||||
layout.addWidget(self.tabs)
|
||||
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Save | QDialogButtonBox.StandardButton.Cancel)
|
||||
buttons.accepted.connect(self.save)
|
||||
buttons.rejected.connect(self.reject)
|
||||
layout.addWidget(buttons)
|
||||
self.general()
|
||||
self.tray()
|
||||
self.hover()
|
||||
self.monitoring()
|
||||
self.remote()
|
||||
self.history()
|
||||
self.diagnostics()
|
||||
self.timer = QTimer(self)
|
||||
self.timer.setInterval(1500)
|
||||
self.timer.timeout.connect(self.update_diagnostics)
|
||||
self.timer.start()
|
||||
self.update_diagnostics()
|
||||
|
||||
def section(self, title):
|
||||
page = QWidget()
|
||||
form = QFormLayout(page)
|
||||
form.setFieldGrowthPolicy(QFormLayout.FieldGrowthPolicy.AllNonFixedFieldsGrow)
|
||||
scroll = QScrollArea()
|
||||
scroll.setWidgetResizable(True)
|
||||
scroll.setWidget(page)
|
||||
self.tabs.addTab(scroll, title)
|
||||
return form
|
||||
|
||||
def add(self, form, label, name, widget, read):
|
||||
form.addRow(label, widget)
|
||||
self.controls[name] = read
|
||||
|
||||
def check(self, form, label, name):
|
||||
widget = checkbox(getattr(self.cfg, name))
|
||||
self.add(form, label, name, widget, widget.isChecked)
|
||||
|
||||
def select(self, form, label, name, values):
|
||||
widget = combo(values, getattr(self.cfg, name))
|
||||
self.add(form, label, name, widget, widget.currentData)
|
||||
|
||||
def integer(self, form, label, name, low, high, suffix=""):
|
||||
widget = spin(getattr(self.cfg, name), low, high, suffix)
|
||||
self.add(form, label, name, widget, widget.value)
|
||||
|
||||
def resource_choices(self, form, label, name):
|
||||
widget = Choices([(title, key) for key, (title, _, _) in RESOURCES.items()], getattr(self.cfg, name))
|
||||
self.add(form, label, name, widget, widget.keys)
|
||||
|
||||
def general(self):
|
||||
form = self.section("General")
|
||||
self.startup = checkbox(self.app.startup_enabled())
|
||||
form.addRow("Start with Windows", self.startup)
|
||||
self.check(form, "Start minimized", "minimized")
|
||||
self.select(form, "Theme", "theme", [(value, value) for value in ("System", "Light", "Dark")])
|
||||
self.select(form, "Default machine", "default_machine", machine_choices(self.app.dashboard))
|
||||
|
||||
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, "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()])
|
||||
for label, key in (("Disk throughput scale", "disk_scale"), ("Network throughput scale", "net_scale")):
|
||||
widget = scale_spin(getattr(self.cfg, key))
|
||||
self.add(form, label, key, widget, lambda widget=widget: widget.value() * 2**20)
|
||||
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()
|
||||
]:
|
||||
button = QPushButton(color)
|
||||
button.clicked.connect(lambda _, key=key, button=button: self.choose_color(key, button))
|
||||
form.addRow(f"{title} color", button)
|
||||
|
||||
def choose_color(self, key, button):
|
||||
color = QColorDialog.getColor(QColor(button.text()), self)
|
||||
if color.isValid():
|
||||
button.setText(color.name())
|
||||
if key == "background":
|
||||
self.background = color.name()
|
||||
else:
|
||||
self.colors[key] = color.name()
|
||||
|
||||
def hover(self):
|
||||
form = self.section("Hover Monitor")
|
||||
self.integer(form, "Hover delay", "hover_delay", 0, 5000, " ms")
|
||||
self.integer(form, "Dismissal delay", "dismiss_delay", 100, 10000, " ms")
|
||||
self.integer(form, "Width", "popup_width", 300, 1800, " px")
|
||||
self.integer(form, "Height", "popup_height", 210, 1200, " px")
|
||||
self.integer(form, "Graph columns", "popup_columns", 1, 3)
|
||||
self.select(form, "Default history range", "hover_range",
|
||||
[(v, k) for k, v in RANGES.items() if k <= 3600])
|
||||
self.resource_choices(form, "Visible graphs", "hover_resources")
|
||||
|
||||
def monitoring(self):
|
||||
form = self.section("Monitoring")
|
||||
self.select(form, "Local sampling interval", "local_interval", interval_choices())
|
||||
self.select(form, "Default remote sampling interval", "remote_interval", interval_choices())
|
||||
devices = self.app.collectors.devices[LOCAL]
|
||||
for kind, key, label in (("gpu", "gpus", "GPUs"), ("disk", "disks", "Disks"), ("net", "interfaces", "Interfaces")):
|
||||
widget = DeviceChoices(devices, kind, getattr(self.cfg, key))
|
||||
self.add(form, label, key, widget, widget.keys)
|
||||
note = plain(QLabel("An empty selection uses automatic device selection. When selecting interfaces, choose one layer of each bridge or VPN path."))
|
||||
note.setWordWrap(True)
|
||||
form.addRow(note)
|
||||
|
||||
def remote(self):
|
||||
form = self.section("Remote Connections")
|
||||
self.integer(form, "Default connection timeout", "connection_timeout", 2, 30, " s")
|
||||
self.check(form, "Retry new targets automatically", "reconnect")
|
||||
manage = QPushButton("Manage targets, credentials and SSH host keys")
|
||||
manage.clicked.connect(self.app.manage)
|
||||
form.addRow(manage)
|
||||
|
||||
def history(self):
|
||||
form = self.section("History")
|
||||
self.check(form, "Record persistent history", "persistent")
|
||||
self.integer(form, "Retention", "retention_days", 1, 365, " days")
|
||||
self.integer(form, "Maximum database size", "max_history_mb", 16, 4096, " MiB")
|
||||
widget, field = path_control(self.cfg.history_file, QFileDialog.getSaveFileName, self)
|
||||
field.setPlaceholderText(str(self.app.root / "history.sqlite"))
|
||||
self.add(form, "Database location", "history_file", widget, field.text)
|
||||
clear = QPushButton("Clear recorded history…")
|
||||
clear.clicked.connect(lambda: self.app.clear_history(self))
|
||||
form.addRow(clear)
|
||||
|
||||
def diagnostics(self):
|
||||
form = self.section("Diagnostics")
|
||||
self.select(form, "Logging level", "log_level", [(v, v) for v in ("DEBUG", "INFO", "WARNING", "ERROR")])
|
||||
self.diagnostic = plain()
|
||||
self.diagnostic.setWordWrap(True)
|
||||
self.diagnostic.setTextInteractionFlags(Qt.TextInteractionFlag.TextSelectableByMouse)
|
||||
form.addRow(self.diagnostic)
|
||||
|
||||
def update_diagnostics(self):
|
||||
self.diagnostic.setText(self.app.diagnostics())
|
||||
|
||||
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)
|
||||
try:
|
||||
self.app.apply(cfg)
|
||||
if self.startup.isChecked() != self.app.startup_enabled():
|
||||
self.app.set_startup(self.startup.isChecked())
|
||||
except (OSError, ValueError) as exc:
|
||||
QMessageBox.warning(self, "Settings", str(exc))
|
||||
return
|
||||
self.accept()
|
||||
|
||||
|
||||
class TargetDialog(QDialog):
|
||||
def __init__(self, app, target, parent):
|
||||
super().__init__(parent)
|
||||
self.app, self.target = app, target
|
||||
self.setWindowTitle("Remote Machine")
|
||||
self.resize(520, 635)
|
||||
self.name = QLineEdit(target.name)
|
||||
self.host = QLineEdit(target.host)
|
||||
self.os = combo([(s, s) for s in ("Linux", "Windows")], target.os_type)
|
||||
self.method = plain()
|
||||
self.port = spin(target.port, 1, 65535)
|
||||
self.username = QLineEdit(target.username)
|
||||
self.auth = combo([(s, s) for s in ("Password", "Private key")], target.auth)
|
||||
self.secret = QLineEdit()
|
||||
self.secret.setEchoMode(QLineEdit.EchoMode.Password)
|
||||
self.secret.setPlaceholderText("Saved in Windows Credential Manager" if target.credential else "Enter a secret if required")
|
||||
self.remove_secret = checkbox(False)
|
||||
key_widget, self.key = path_control(target.key_file, QFileDialog.getOpenFileName, self)
|
||||
self.interval = combo(interval_choices(), target.interval)
|
||||
self.timeout = spin(target.timeout, 2, 30, " s")
|
||||
self.enabled, self.reconnect, self.tray = [checkbox(value) for value in (target.enabled, target.reconnect, target.tray)]
|
||||
self.resources = Choices([(title, key) for key, (title, _, _) in RESOURCES.items()], target.resources)
|
||||
devices = app.collectors.devices[target.identifier]
|
||||
self.ids = {}
|
||||
page = QWidget()
|
||||
form = QFormLayout(page)
|
||||
for title, widget in (
|
||||
("Display name", self.name), ("Host or IP", self.host), ("Operating system", self.os),
|
||||
("Connection", self.method), ("Port", self.port), ("Username", self.username),
|
||||
("Authentication", self.auth), ("Private key", key_widget), ("Password or key passphrase", self.secret),
|
||||
("Remove saved secret", self.remove_secret), ("Sampling interval", self.interval),
|
||||
("Timeout", self.timeout), ("Enable monitoring", self.enabled), ("Reconnect automatically", self.reconnect),
|
||||
("Include in separate tray icons", self.tray), ("Resources", self.resources),
|
||||
):
|
||||
form.addRow(title, widget)
|
||||
for kind, key, label in (("gpu", "gpus", "GPU identifiers"), ("disk", "disks", "Disk identifiers"),
|
||||
("net", "interfaces", "Interface identifiers")):
|
||||
choices = DeviceChoices(devices, kind, getattr(target, key))
|
||||
manual = QLineEdit(",".join(x for x in getattr(target, key) if x not in devices))
|
||||
manual.setPlaceholderText("Additional identifiers, separated by commas")
|
||||
form.addRow(label, choices)
|
||||
form.addRow("", manual)
|
||||
self.ids[key] = (choices, manual)
|
||||
scroll = QScrollArea()
|
||||
scroll.setWidgetResizable(True)
|
||||
scroll.setWidget(page)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.addWidget(scroll)
|
||||
buttons = QDialogButtonBox(QDialogButtonBox.StandardButton.Save | QDialogButtonBox.StandardButton.Cancel)
|
||||
buttons.accepted.connect(self.save)
|
||||
buttons.rejected.connect(self.reject)
|
||||
layout.addWidget(buttons)
|
||||
|
||||
def update():
|
||||
linux = self.os.currentData() == "Linux"
|
||||
self.method.setText("SSH" if linux else "Planned")
|
||||
key_widget.setEnabled(linux and self.auth.currentData() == "Private key")
|
||||
for widget in (self.username, self.port, self.auth, self.secret, self.remove_secret):
|
||||
widget.setEnabled(linux)
|
||||
|
||||
self.os.currentIndexChanged.connect(update)
|
||||
self.auth.currentIndexChanged.connect(update)
|
||||
update()
|
||||
|
||||
def save(self):
|
||||
host, name, user = (field.text().strip() for field in (self.host, self.name, self.username))
|
||||
os_type, auth = self.os.currentData(), self.auth.currentData()
|
||||
key = self.key.text().strip()
|
||||
if not name or not host or any(char.isspace() for char in host) or any(c in host for c in "[],"):
|
||||
QMessageBox.warning(self, "Remote Machine", "Enter a display name and a valid hostname or IP address.")
|
||||
return
|
||||
if os_type == "Linux" and (not user or (auth == "Private key" and not Path(key).is_file())):
|
||||
QMessageBox.warning(self, "Remote Machine", "Enter an SSH username and choose an existing key file if using key authentication.")
|
||||
return
|
||||
filters = {k: list(dict.fromkeys(choices.keys() + [v.strip() for v in line.text().split(",") if v.strip()]))
|
||||
for k, (choices, line) in self.ids.items()}
|
||||
target = replace(self.target, name=name, host=host, username=user, os_type=os_type,
|
||||
method="SSH" if os_type == "Linux" else "Planned", port=self.port.value(),
|
||||
auth=auth, key_file=key, interval=self.interval.currentData(),
|
||||
timeout=self.timeout.value(), enabled=self.enabled.isChecked(),
|
||||
reconnect=self.reconnect.isChecked(), tray=self.tray.isChecked(),
|
||||
resources=self.resources.keys(), **filters)
|
||||
identity = ("host", "username", "auth", "port", "os_type")
|
||||
forget = self.remove_secret.isChecked() or any(
|
||||
getattr(self.target, k) != getattr(target, k) for k in identity)
|
||||
try:
|
||||
self.app.save_target(target, self.secret.text() if os_type == "Linux" else "", forget)
|
||||
except (OSError, ValueError) as exc:
|
||||
QMessageBox.warning(self, "Remote Machine", str(exc))
|
||||
return
|
||||
self.secret.clear()
|
||||
self.accept()
|
||||
|
||||
|
||||
class ConnectionsDialog(QDialog):
|
||||
def __init__(self, app):
|
||||
super().__init__()
|
||||
self.app = app
|
||||
self.setWindowTitle("Remote Targets")
|
||||
self.resize(730, 385)
|
||||
self.table = QTableWidget(0, 4)
|
||||
self.table.setHorizontalHeaderLabels(("Machine", "Host", "Connection", "Status"))
|
||||
self.table.verticalHeader().setVisible(False)
|
||||
self.table.setSelectionBehavior(QAbstractItemView.SelectionBehavior.SelectRows)
|
||||
self.table.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection)
|
||||
self.table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers)
|
||||
self.table.horizontalHeader().setSectionResizeMode(QHeaderView.ResizeMode.Stretch)
|
||||
self.table.cellDoubleClicked.connect(lambda *_: self.edit())
|
||||
self.info = plain()
|
||||
self.info.setWordWrap(True)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.addWidget(self.table)
|
||||
layout.addWidget(self.info)
|
||||
for actions in (
|
||||
(("Add", self.add), ("Edit", self.edit), ("Remove", self.remove), ("Test connection", self.test),
|
||||
("Connect", self.connect_target), ("Disconnect", self.disconnect), ("Enable / disable", self.toggle)),
|
||||
(("Approve SSH host key", self.approve), ("Forget SSH host key…", self.forget)),
|
||||
):
|
||||
row = QHBoxLayout()
|
||||
for title, action in actions:
|
||||
button = QPushButton(title)
|
||||
button.clicked.connect(action)
|
||||
row.addWidget(button)
|
||||
row.addStretch()
|
||||
layout.addLayout(row)
|
||||
self.test_results = {}
|
||||
self.table.itemSelectionChanged.connect(self.status_text)
|
||||
app.collectors.changed.connect(self.sync)
|
||||
app.collectors.test_finished.connect(self.test_finished)
|
||||
self.sync()
|
||||
|
||||
def selected(self):
|
||||
row = self.table.currentRow()
|
||||
item = self.table.item(row, 0)
|
||||
identifier = item.data(Qt.ItemDataRole.UserRole) if item else None
|
||||
return next((target for target in self.app.settings.targets if target.identifier == identifier), None)
|
||||
|
||||
def sync(self):
|
||||
prior = self.selected()
|
||||
self.table.setRowCount(len(self.app.settings.targets))
|
||||
for row, target in enumerate(self.app.settings.targets):
|
||||
state = self.app.dashboard.state(target.identifier)
|
||||
for column, value in enumerate((target.name, f"{target.host}:{target.port}", target.method, state.value)):
|
||||
item = QTableWidgetItem(value)
|
||||
if column == 0:
|
||||
item.setData(Qt.ItemDataRole.UserRole, target.identifier)
|
||||
self.table.setItem(row, column, item)
|
||||
if prior and prior.identifier == target.identifier:
|
||||
self.table.selectRow(row)
|
||||
if self.table.currentRow() < 0 and self.table.rowCount():
|
||||
self.table.selectRow(0)
|
||||
self.status_text()
|
||||
|
||||
def status_text(self):
|
||||
target = self.selected()
|
||||
if not target:
|
||||
self.info.clear()
|
||||
return
|
||||
status = self.app.collectors.statuses.get(target.identifier)
|
||||
test = self.test_results.get(target.identifier, "")
|
||||
self.info.setText(" · ".join(v for v in (status.detail if status else "", test) if v))
|
||||
|
||||
def add(self):
|
||||
self.app.add_target(self)
|
||||
|
||||
def edit(self):
|
||||
if target := self.selected():
|
||||
self.test_results.pop(target.identifier, None)
|
||||
TargetDialog(self.app, target, self).exec()
|
||||
|
||||
def remove(self):
|
||||
if target := self.selected():
|
||||
if QMessageBox.question(self, "Remove Machine", f"Remove profile {target.name} and its saved credential?",
|
||||
QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No,
|
||||
QMessageBox.StandardButton.No) == QMessageBox.StandardButton.Yes:
|
||||
try:
|
||||
self.test_results.pop(target.identifier, None)
|
||||
self.app.remove_target(target)
|
||||
except OSError as exc:
|
||||
QMessageBox.warning(self, "Remove Machine", str(exc))
|
||||
|
||||
def test(self):
|
||||
if target := self.selected():
|
||||
self.test_results[target.identifier] = "Testing SSH telemetry…"
|
||||
self.status_text()
|
||||
self.app.collectors.test(target)
|
||||
|
||||
def test_finished(self, status):
|
||||
self.test_results[status.machine] = f"Test: {status.state} {status.detail}"
|
||||
if status.trust:
|
||||
self.app.test_keys[status.machine] = status.trust
|
||||
self.status_text()
|
||||
|
||||
def connect_target(self):
|
||||
if target := self.selected():
|
||||
if not target.enabled:
|
||||
self.app.save_target(replace(target, enabled=True), "", False)
|
||||
self.app.collectors.reconnect(target.identifier)
|
||||
|
||||
def disconnect(self):
|
||||
if target := self.selected():
|
||||
self.app.collectors.disconnect(target.identifier)
|
||||
|
||||
def toggle(self):
|
||||
if target := self.selected():
|
||||
self.app.save_target(replace(target, enabled=not target.enabled), "", False)
|
||||
if not target.enabled:
|
||||
self.app.collectors.reconnect(target.identifier)
|
||||
|
||||
def approve(self):
|
||||
if target := self.selected():
|
||||
self.app.approve_key(target, self)
|
||||
|
||||
def forget(self):
|
||||
if target := self.selected():
|
||||
self.app.forget_key(target, self)
|
||||
253
arm/graphs.py
Normal file
253
arm/graphs.py
Normal file
@@ -0,0 +1,253 @@
|
||||
"""Timestamp-based plots shared by the monitoring windows and tray."""
|
||||
from time import time
|
||||
|
||||
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
|
||||
|
||||
METRICS = {kind: d[2] for kind, d in RESOURCES.items()}
|
||||
|
||||
|
||||
def metric_for(kind, settings):
|
||||
return settings.disk_mode if kind == "disk" else METRICS[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)
|
||||
|
||||
|
||||
def plot_scale(metric, settings, readings):
|
||||
if metric not in ("disk.read", "disk.write", "disk.total", "net.receive", "net.transmit", "net.total"):
|
||||
return 100
|
||||
reference = settings.disk_scale if metric.startswith("disk") else settings.net_scale
|
||||
return graph_scale(readings, reference)
|
||||
|
||||
|
||||
def bucket_peaks(points, now, span, columns):
|
||||
"""Thin densely sampled history to the largest actual observation per column."""
|
||||
result = []
|
||||
last_column = None
|
||||
for stamp, value in points:
|
||||
column = int((stamp - now + span) / span * columns)
|
||||
if not 0 <= column <= columns:
|
||||
continue
|
||||
if value is None:
|
||||
if result and result[-1][1] is not None:
|
||||
result.append((stamp, None))
|
||||
last_column = None
|
||||
elif column == last_column:
|
||||
if value >= result[-1][1]:
|
||||
result[-1] = stamp, value
|
||||
else:
|
||||
result.append((stamp, value))
|
||||
last_column = column
|
||||
return result
|
||||
|
||||
|
||||
def across_series(series, now, span, gap, columns):
|
||||
"""Peak per time bin, with identity attached to the winning observation."""
|
||||
step = max(span / columns, min(gap, span) / 3)
|
||||
size = max(1, int(span / step))
|
||||
bins = {}
|
||||
for label, readings in series.items():
|
||||
for stamp, value in readings:
|
||||
index = min(size, int((stamp - now + span) / step))
|
||||
if value is None:
|
||||
bins.setdefault(index, (stamp, None, label))
|
||||
continue
|
||||
old = bins.get(index)
|
||||
if old is None or old[1] is None or value > old[1]:
|
||||
bins[index] = stamp, value, label
|
||||
return [bins[index] for index in sorted(bins)]
|
||||
|
||||
|
||||
def stroke(painter, rect, points, now, span, gap, color, width=1.3):
|
||||
if not points:
|
||||
return
|
||||
points = bucket_peaks(points, now, span, max(2, int(rect.width())))
|
||||
path = QPainterPath()
|
||||
previous = None
|
||||
for stamp, value in points:
|
||||
if value is None:
|
||||
previous = None
|
||||
continue
|
||||
fraction = (stamp - (now - span)) / span
|
||||
x = rect.left() + fraction * max(0, rect.width() - .5)
|
||||
y = rect.bottom() - value / 100 * rect.height()
|
||||
point = QPointF(x, y)
|
||||
if previous is None or stamp - previous > gap:
|
||||
path.moveTo(point)
|
||||
path.lineTo(point + QPointF(.2, 0))
|
||||
path.moveTo(point)
|
||||
else:
|
||||
path.lineTo(point)
|
||||
previous = stamp
|
||||
painter.setPen(QPen(QColor(color), width))
|
||||
painter.drawPath(path)
|
||||
|
||||
|
||||
class Dashboard:
|
||||
def __init__(self, collectors):
|
||||
self.collectors = collectors
|
||||
self.archived = {}
|
||||
|
||||
@property
|
||||
def settings(self):
|
||||
return self.collectors.settings
|
||||
|
||||
def name(self, machine):
|
||||
if machine == LOCAL:
|
||||
return "Local Machine"
|
||||
if machine == ALL:
|
||||
return "All Systems"
|
||||
return next((t.name for t in self.settings.targets if t.identifier == machine), "Unknown machine")
|
||||
|
||||
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 state(self, machine):
|
||||
status = self.collectors.statuses.get(machine)
|
||||
return status.state if status else Connection.OFFLINE
|
||||
|
||||
def interval(self, machine):
|
||||
return self.collectors.intervals.get(machine, 1)
|
||||
|
||||
def history(self, key, cutoff, archive=False):
|
||||
live = self.collectors.history.since(*key, cutoff)
|
||||
if not archive:
|
||||
return live
|
||||
archived = self.archived.get(key, ())
|
||||
limit = live[0].timestamp if live else float("inf")
|
||||
return [r for r in archived if cutoff <= r.timestamp < limit] + live
|
||||
|
||||
def observation(self, machine, kind, device, metric, now):
|
||||
key = (machine, device, metric)
|
||||
candidate = self.collectors.history.latest(*key)
|
||||
provider = {"cpu": "CPU", "ram": "Memory", "gpu": "GPU", "vram": "GPU",
|
||||
"disk": "Storage", "net": "Network"}.get(kind)
|
||||
provider_state = self.collectors.provider_status.get((machine, provider))
|
||||
status = provider_state.state if machine == LOCAL and provider_state else self.state(machine)
|
||||
if status != Connection.ONLINE:
|
||||
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)
|
||||
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
|
||||
|
||||
|
||||
def paint_tray(painter, size, data, settings, period, now, status):
|
||||
if not settings.transparent:
|
||||
painter.fillRect(QRectF(0, 0, size, size), QColor(settings.background))
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
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):
|
||||
band = QRectF(rect.x(), rect.y() + height * index, rect.width(), max(1, height - .35))
|
||||
shade = QColor(settings.colors[kind])
|
||||
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)
|
||||
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)
|
||||
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)
|
||||
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)
|
||||
else:
|
||||
for kind, points, gap in data:
|
||||
stroke(painter, rect, points, now, period, gap, settings.colors[kind])
|
||||
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):
|
||||
settings = dashboard.settings
|
||||
now = time() if now is None else now
|
||||
period = settings.tray_range
|
||||
data = []
|
||||
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)
|
||||
icon = QIcon()
|
||||
for size in (16, 20, 24, 32, 40, 48):
|
||||
pixmap = QPixmap(size, size)
|
||||
pixmap.fill(Qt.GlobalColor.transparent)
|
||||
painter = QPainter(pixmap)
|
||||
paint_tray(painter, size, data, settings, period, now, status)
|
||||
painter.end()
|
||||
icon.addPixmap(pixmap)
|
||||
return icon
|
||||
|
||||
|
||||
class Plot(QWidget):
|
||||
def __init__(self):
|
||||
super().__init__()
|
||||
self.setMinimumHeight(24)
|
||||
self.setSizePolicy(QSizePolicy.Policy.Expanding, QSizePolicy.Policy.Expanding)
|
||||
self.data = None
|
||||
self.setAccessibleName("Resource history")
|
||||
|
||||
def set_data(self, series, now, period, gap):
|
||||
self.data = series, now, period, gap
|
||||
self.update()
|
||||
|
||||
def paintEvent(self, event):
|
||||
painter = QPainter(self)
|
||||
painter.setRenderHint(QPainter.RenderHint.Antialiasing)
|
||||
rect = QRectF(self.rect()).adjusted(1, 1, -1, -2)
|
||||
painter.fillRect(rect, QColor("#151923"))
|
||||
painter.setPen(QPen(QColor("#3c4556"), .7))
|
||||
for step in range(1, 5):
|
||||
x = rect.x() + rect.width() * step / 5
|
||||
painter.drawLine(QPointF(x, rect.top()), QPointF(x, rect.bottom()))
|
||||
for step in range(1, 3):
|
||||
y = rect.y() + rect.height() * step / 3
|
||||
painter.drawLine(QPointF(rect.left(), y), QPointF(rect.right(), y))
|
||||
if self.data:
|
||||
series, now, period, gap = self.data
|
||||
for points, color in series:
|
||||
stroke(painter, rect, points, now, period, gap, color)
|
||||
|
||||
def sizeHint(self):
|
||||
return QSize(155, 46)
|
||||
152
arm/history_db.py
Normal file
152
arm/history_db.py
Normal file
@@ -0,0 +1,152 @@
|
||||
"""SQLite activity is confined to one background thread."""
|
||||
from contextlib import closing
|
||||
from pathlib import Path
|
||||
from queue import Empty, Full, Queue
|
||||
import logging
|
||||
import sqlite3
|
||||
import threading
|
||||
from time import monotonic, time
|
||||
|
||||
from .model import Availability, Reading
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
BATCH_SECONDS = 4
|
||||
SQL_INSERT = "INSERT OR IGNORE INTO readings VALUES (?,?,?,?,?,?,?,?)"
|
||||
SQL_SCHEMA = """
|
||||
CREATE TABLE IF NOT EXISTS readings (
|
||||
machine TEXT, device TEXT, metric TEXT, stamp REAL, value REAL, unit TEXT,
|
||||
status TEXT, detail TEXT, PRIMARY KEY (machine,device,metric,stamp)
|
||||
) WITHOUT ROWID;
|
||||
CREATE INDEX IF NOT EXISTS retention ON readings(stamp);
|
||||
"""
|
||||
|
||||
|
||||
class HistoryDb:
|
||||
def __init__(self, path, retention, maximum, deliver, failure, previous=None):
|
||||
self.path = Path(path)
|
||||
self.retention = retention
|
||||
self.maximum = maximum * 1024 * 1024
|
||||
self.deliver, self.failure = deliver, failure
|
||||
self.previous = previous
|
||||
self.tasks = Queue(maxsize=128)
|
||||
self.stopping = threading.Event()
|
||||
self.thread = threading.Thread(target=self.run, name="ARM history")
|
||||
self.thread.start()
|
||||
|
||||
def send(self, operation, args=None):
|
||||
if not self.stopping.is_set():
|
||||
try:
|
||||
self.tasks.put_nowait((operation, args))
|
||||
return True
|
||||
except Full:
|
||||
self.failure("History queue is full")
|
||||
return False
|
||||
|
||||
def record(self, readings):
|
||||
if readings:
|
||||
self.send("record", readings)
|
||||
|
||||
def request(self, token, keys, cutoff):
|
||||
self.send("request", (token, tuple(keys), cutoff))
|
||||
|
||||
def stop(self):
|
||||
self.stopping.set()
|
||||
|
||||
def close(self):
|
||||
self.stop()
|
||||
self.thread.join()
|
||||
|
||||
def run(self):
|
||||
previous, self.previous = self.previous, None
|
||||
if previous:
|
||||
previous.thread.join()
|
||||
try:
|
||||
self.path.parent.mkdir(parents=True, exist_ok=True)
|
||||
with closing(sqlite3.connect(self.path, timeout=2)) as connection:
|
||||
self.operate(connection)
|
||||
except (OSError, sqlite3.Error) as exc:
|
||||
message = f"History database failed ({type(exc).__name__}: {exc})"
|
||||
LOG.error("%s", message)
|
||||
self.failure(message)
|
||||
|
||||
def operate(self, conn):
|
||||
conn.execute("PRAGMA auto_vacuum=INCREMENTAL")
|
||||
conn.execute("PRAGMA journal_mode=WAL")
|
||||
conn.execute("PRAGMA synchronous=NORMAL")
|
||||
conn.execute("PRAGMA journal_size_limit=4194304")
|
||||
conn.executescript(SQL_SCHEMA)
|
||||
page_size = conn.execute("PRAGMA page_size").fetchone()[0]
|
||||
pending = []
|
||||
last_flush = monotonic()
|
||||
self.trim(conn, page_size)
|
||||
last_trim = monotonic()
|
||||
while not self.stopping.is_set() or not self.tasks.empty():
|
||||
try:
|
||||
operation, args = self.tasks.get(timeout=.25)
|
||||
except Empty:
|
||||
operation, args = "", None
|
||||
if operation == "record":
|
||||
pending.extend(
|
||||
(r.machine, r.device, r.metric, r.timestamp, r.value, r.unit, r.availability.value, r.diagnostic)
|
||||
for r in args
|
||||
)
|
||||
elif operation == "clear":
|
||||
pending.clear()
|
||||
with conn:
|
||||
conn.execute("DELETE FROM readings")
|
||||
conn.execute("VACUUM")
|
||||
conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
||||
self.deliver(args, {})
|
||||
elif operation == "request":
|
||||
token, keys, cutoff = args
|
||||
result = {}
|
||||
with conn:
|
||||
for key in keys:
|
||||
# Bound how much history is loaded for each requested plot.
|
||||
# Group older sequences by time, preserving real peak observations.
|
||||
step = max(1, (time() - cutoff) / 2000)
|
||||
sql = (
|
||||
"SELECT stamp,value,unit,status,detail,max(coalesce(value,-1)) "
|
||||
"FROM readings WHERE machine=? AND device=? AND metric=? AND stamp>=? "
|
||||
"GROUP BY cast((stamp-?)/? as integer) ORDER BY stamp"
|
||||
)
|
||||
rows = conn.execute(sql, (*key, cutoff, cutoff, step))
|
||||
result[key] = [Reading(*key, value, unit, stamp, Availability(status), detail)
|
||||
for stamp, value, unit, status, detail, _ in rows]
|
||||
self.deliver(token, result)
|
||||
tick = monotonic()
|
||||
if pending and (tick - last_flush >= BATCH_SECONDS or len(pending) >= 12000):
|
||||
self.flush(conn, pending)
|
||||
last_flush = tick
|
||||
if tick - last_trim >= 60:
|
||||
self.trim(conn, page_size)
|
||||
last_trim = tick
|
||||
self.flush(conn, pending)
|
||||
self.trim(conn, page_size)
|
||||
conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
||||
|
||||
@staticmethod
|
||||
def flush(conn, pending):
|
||||
if pending:
|
||||
with conn:
|
||||
conn.executemany(SQL_INSERT, pending)
|
||||
pending.clear()
|
||||
|
||||
def trim(self, conn, page_size):
|
||||
cutoff = time() - self.retention * 86400
|
||||
with conn:
|
||||
conn.execute("DELETE FROM readings WHERE stamp<?", (cutoff,))
|
||||
pages = conn.execute("PRAGMA page_count").fetchone()[0]
|
||||
if pages * page_size > self.maximum:
|
||||
free = conn.execute("PRAGMA freelist_count").fetchone()[0]
|
||||
count = conn.execute("SELECT count(*) FROM readings").fetchone()[0]
|
||||
fraction = max(0, 1 - (self.maximum * .90 / (max(1, pages - free) * page_size)))
|
||||
if fraction and count:
|
||||
position = min(count - 1, int(fraction * count))
|
||||
oldest = conn.execute("SELECT stamp FROM readings ORDER BY stamp LIMIT 1 OFFSET ?",
|
||||
(position,)).fetchone()
|
||||
if oldest:
|
||||
conn.execute("DELETE FROM readings WHERE stamp<=?", oldest)
|
||||
if pages * page_size > self.maximum:
|
||||
conn.execute("VACUUM")
|
||||
conn.execute("PRAGMA wal_checkpoint(TRUNCATE)")
|
||||
221
arm/model.py
Normal file
221
arm/model.py
Normal file
@@ -0,0 +1,221 @@
|
||||
from collections import defaultdict, deque
|
||||
from dataclasses import dataclass
|
||||
from enum import StrEnum
|
||||
from math import isfinite
|
||||
from time import time
|
||||
|
||||
LOCAL = "local"
|
||||
ALL = "@all"
|
||||
TOTAL = "@total"
|
||||
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",
|
||||
604800: "7 days", 2592000: "30 days"}
|
||||
RESOURCES = {
|
||||
"cpu": ("CPU", "#68df79", "cpu.util"),
|
||||
"gpu": ("GPU", "#d394ff", "gpu.util"),
|
||||
"ram": ("RAM", "#66aaff", "ram.util"),
|
||||
"vram": ("VRAM", "#ffd75a", "gpu.vram_pct"),
|
||||
"disk": ("Disk I/O", "#ff686b", "disk.total"),
|
||||
"net": ("Network", "#58e7e7", "net.total"),
|
||||
}
|
||||
DISK_MODES = {"disk.active": "Active time", "disk.read": "Read throughput",
|
||||
"disk.write": "Write throughput", "disk.total": "Combined throughput"}
|
||||
|
||||
|
||||
class Availability(StrEnum):
|
||||
VALID = "valid"
|
||||
UNAVAILABLE = "unavailable"
|
||||
UNSUPPORTED = "unsupported"
|
||||
ERROR = "error"
|
||||
STALE = "stale"
|
||||
DISCONNECTED = "disconnected"
|
||||
|
||||
|
||||
class Connection(StrEnum):
|
||||
OFFLINE = "Disconnected"
|
||||
CONNECTING = "Connecting"
|
||||
ONLINE = "Connected"
|
||||
RETRYING = "Reconnecting"
|
||||
ERROR = "Connection failed"
|
||||
TRUST = "Host key approval required"
|
||||
UNSUPPORTED = "Unsupported"
|
||||
DISABLED = "Monitoring disabled"
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Device:
|
||||
kind: str
|
||||
identifier: str
|
||||
name: str
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Reading:
|
||||
machine: str
|
||||
device: str
|
||||
metric: str
|
||||
value: float | None
|
||||
unit: str
|
||||
timestamp: float
|
||||
availability: Availability = Availability.VALID
|
||||
diagnostic: str = ""
|
||||
|
||||
@property
|
||||
def valid(self):
|
||||
return (self.availability == Availability.VALID and self.value is not None
|
||||
and isinstance(self.value, (int, float)) and isfinite(self.value))
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Sample:
|
||||
machine: str
|
||||
provider: str
|
||||
timestamp: float
|
||||
readings: tuple[Reading, ...]
|
||||
devices: tuple[Device, ...] = ()
|
||||
|
||||
|
||||
@dataclass(frozen=True, slots=True)
|
||||
class Status:
|
||||
machine: str
|
||||
state: Connection
|
||||
detail: str = ""
|
||||
trust: object = None
|
||||
|
||||
|
||||
def readings(machine, timestamp, device, metrics):
|
||||
return tuple(
|
||||
Reading(machine, device, key, value, unit, timestamp, Availability.VALID if value is not None
|
||||
else Availability.UNAVAILABLE)
|
||||
for key, (value, unit) in metrics.items()
|
||||
)
|
||||
|
||||
|
||||
def rate(previous, current, elapsed, interval):
|
||||
if previous is None or current is None or current < previous:
|
||||
return None
|
||||
if not 0 < elapsed <= max(interval * 3, 2):
|
||||
return None
|
||||
return (current - previous) / elapsed
|
||||
|
||||
|
||||
def usage(used, total):
|
||||
return min(100.0, 100.0 * used / total) if used is not None and total and used >= 0 else None
|
||||
|
||||
|
||||
def sum_known(values):
|
||||
values = [v for v in values if v is not None]
|
||||
return sum(values) if values else None
|
||||
|
||||
|
||||
def max_known(values):
|
||||
return max((v for v in values if v is not None), default=None)
|
||||
|
||||
|
||||
def aggregate(machine, stamp, kind, data):
|
||||
if not data:
|
||||
return ()
|
||||
metrics = {}
|
||||
for key, (_, unit) in data[0].items():
|
||||
maximum = key in {"gpu.util", "gpu.encode", "gpu.decode", "gpu.compute", "disk.active"}
|
||||
if key in {"gpu.vram_used", "gpu.vram_total", "gpu.vram_free"}:
|
||||
# Include only devices with a measured capacity and usage pair.
|
||||
values = (item[key][0] for item in data
|
||||
if item["gpu.vram_used"][0] is not None and item["gpu.vram_total"][0])
|
||||
else:
|
||||
values = (item[key][0] for item in data)
|
||||
metrics[key] = ((max_known if maximum else sum_known)(values), unit)
|
||||
if kind == "gpu":
|
||||
for key in ("temperature", "clock", "memory_clock", "power_limit", "fan"):
|
||||
metrics.pop(f"gpu.{key}", None)
|
||||
metrics["gpu.vram_pct"] = (usage(metrics["gpu.vram_used"][0],
|
||||
metrics["gpu.vram_total"][0]), "%")
|
||||
for key in ("shared_pct", "shared_used", "shared_total"):
|
||||
metrics.pop(f"gpu.{key}", None)
|
||||
if kind == "net":
|
||||
metrics.pop("net.up", None)
|
||||
metrics.pop("net.link", None)
|
||||
metrics["net.util"] = (max_known(item["net.util"][0] for item in data), "%")
|
||||
return readings(machine, stamp, TOTAL, metrics)
|
||||
|
||||
|
||||
class History:
|
||||
def __init__(self, max_seconds=3600, max_points=7400):
|
||||
self.max_seconds = max_seconds
|
||||
self.series = defaultdict(lambda: deque(maxlen=max_points))
|
||||
self.last_valid = {}
|
||||
|
||||
def add(self, items):
|
||||
for item in items:
|
||||
key = (item.machine, item.device, item.metric)
|
||||
buf = self.series[key]
|
||||
if buf and item.timestamp <= buf[-1].timestamp:
|
||||
continue
|
||||
buf.append(item)
|
||||
if item.valid:
|
||||
self.last_valid[key] = item
|
||||
cutoff = item.timestamp - self.max_seconds
|
||||
while buf and buf[0].timestamp < cutoff:
|
||||
buf.popleft()
|
||||
|
||||
def since(self, machine, device, metric, cutoff):
|
||||
buf = self.series.get((machine, device, metric), ())
|
||||
result = []
|
||||
for item in reversed(buf):
|
||||
if item.timestamp < cutoff:
|
||||
break
|
||||
result.append(item)
|
||||
return list(reversed(result))
|
||||
|
||||
def latest(self, machine, device, metric):
|
||||
buf = self.series.get((machine, device, metric))
|
||||
return buf[-1] if buf else None
|
||||
|
||||
def remove_machine(self, machine):
|
||||
for key in list(self.series):
|
||||
if key[0] == machine:
|
||||
del self.series[key]
|
||||
self.last_valid.pop(key, None)
|
||||
|
||||
|
||||
def graph_scale(items, reference=0):
|
||||
if reference > 0:
|
||||
return reference
|
||||
peak = max((r.value for r in items if r.valid), default=0)
|
||||
step = 1024.0
|
||||
while step < peak:
|
||||
step *= 2
|
||||
return step
|
||||
|
||||
|
||||
def normalized(reading, scale):
|
||||
if not reading.valid or scale <= 0:
|
||||
return None
|
||||
return min(100, max(0, reading.value * 100 / scale))
|
||||
|
||||
|
||||
def current_reading(reading, status, interval, now=None):
|
||||
if reading is None or not reading.valid:
|
||||
return reading
|
||||
now = time() if now is None else now
|
||||
if status != Connection.ONLINE or now - reading.timestamp > max(3 * interval, 2):
|
||||
return Reading(reading.machine, reading.device, reading.metric, reading.value,
|
||||
reading.unit, reading.timestamp, Availability.STALE)
|
||||
return reading
|
||||
|
||||
|
||||
def format_value(value, unit):
|
||||
if value is None:
|
||||
return "Unavailable"
|
||||
if unit in {"B", "B/s"}:
|
||||
suffix = "/s" if unit == "B/s" else ""
|
||||
for base in ("B", "KiB", "MiB", "GiB", "TiB"):
|
||||
if abs(value) < 1024 or base == "TiB":
|
||||
return f"{value:,.1f} {base}{suffix}"
|
||||
value /= 1024
|
||||
if unit == "Mb/s" and value >= 1000:
|
||||
return f"{value / 1000:,.2f} Gb/s"
|
||||
if unit in {"count", "bool"}:
|
||||
return ("Up" if value else "Down") if unit == "bool" else f"{int(value)}"
|
||||
return f"{value:,.1f} {unit}"
|
||||
17
arm/providers/__init__.py
Normal file
17
arm/providers/__init__.py
Normal file
@@ -0,0 +1,17 @@
|
||||
"""Independent telemetry providers."""
|
||||
import logging
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Provider:
|
||||
def close(self):
|
||||
"""Release resources in the sampling worker."""
|
||||
|
||||
def cancel(self):
|
||||
"""Request cancellation without waiting on a blocking query."""
|
||||
|
||||
|
||||
class WindowsRemoteProvider(Provider):
|
||||
def sample(self):
|
||||
raise NotImplementedError("Remote Windows telemetry is planned")
|
||||
212
arm/providers/gpu.py
Normal file
212
arm/providers/gpu.py
Normal file
@@ -0,0 +1,212 @@
|
||||
import logging
|
||||
import re
|
||||
from collections import Counter, defaultdict
|
||||
from time import perf_counter as monotonic, time
|
||||
|
||||
from . import Provider
|
||||
from .native import Pdh, adapter_identity, adapters
|
||||
from ..model import LOCAL, Device, Sample, aggregate, readings, usage
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
LUID = re.compile(r"(luid_0x[0-9a-f]+_0x[0-9a-f]+)(?:_phys_(\d+))?", re.I)
|
||||
ENGINE = re.compile(r"_eng_(\d+)_engtype_(.+?)(?:#\d+)?$", re.I)
|
||||
GPU_UNITS = {
|
||||
"util": "%", "vram_used": "B", "vram_total": "B", "vram_free": "B", "vram_pct": "%",
|
||||
"shared_used": "B", "shared_total": "B", "shared_pct": "%",
|
||||
"temperature": "°C", "clock": "MHz", "memory_clock": "MHz", "power": "W",
|
||||
"power_limit": "W", "fan": "%", "encode": "%", "decode": "%", "compute": "%",
|
||||
}
|
||||
|
||||
|
||||
def gpu_metrics(values):
|
||||
for key, capacity, used in (("vram", "vram_total", "vram_used"),
|
||||
("shared", "shared_total", "shared_used")):
|
||||
values[f"{key}_pct"] = usage(values.get(used), values.get(capacity))
|
||||
if values.get("vram_used") is not None and values.get("vram_total"):
|
||||
values.setdefault("vram_free", max(0, values["vram_total"] - values["vram_used"]))
|
||||
return {f"gpu.{key}": (values.get(key), unit) for key, unit in GPU_UNITS.items()}
|
||||
|
||||
|
||||
def engine_usage(rows):
|
||||
engines = defaultdict(lambda: defaultdict(float))
|
||||
for label, value in rows.items():
|
||||
adapter, engine = LUID.search(label), ENGINE.search(label)
|
||||
if adapter and engine:
|
||||
engines[adapter[1].lower()][(adapter[2], engine[1], engine[2].lower())] += value
|
||||
result = {}
|
||||
for identifier, nodes in engines.items():
|
||||
values = {"util": min(100, max(nodes.values()))}
|
||||
for key, tokens in {"encode": ("videoencode",), "decode": ("videodecode",),
|
||||
"compute": ("compute", "cuda")}.items():
|
||||
values[key] = max((min(100, value) for node, value in nodes.items()
|
||||
if any(token in node[-1] for token in tokens)), default=None)
|
||||
result[identifier] = values
|
||||
return result
|
||||
|
||||
|
||||
def memory_usage(rows):
|
||||
values = defaultdict(float)
|
||||
for label, value in rows.items():
|
||||
adapter = LUID.search(label)
|
||||
if adapter:
|
||||
values[adapter[1].lower()] += value
|
||||
return values
|
||||
|
||||
|
||||
class Nvml:
|
||||
def __init__(self):
|
||||
self.api = None
|
||||
self.devices = []
|
||||
try:
|
||||
import pynvml
|
||||
pynvml.nvmlInit()
|
||||
self.api = pynvml
|
||||
for index in range(pynvml.nvmlDeviceGetCount()):
|
||||
handle = self.get("HandleByIndex", index)
|
||||
if handle is None:
|
||||
continue
|
||||
name, pci, identifier = (self.get(key, handle) for key in ("Name", "PciInfo", "UUID"))
|
||||
if name and pci and identifier:
|
||||
if isinstance(name, bytes):
|
||||
name = name.decode("utf-8", "replace")
|
||||
if isinstance(identifier, bytes):
|
||||
identifier = identifier.decode("ascii", "replace")
|
||||
self.devices.append((str(identifier), name, pci.pciDeviceId >> 16,
|
||||
(pci.bus, pci.device), handle))
|
||||
LOG.info("NVML found %d GPU(s)", len(self.devices))
|
||||
except (ImportError, OSError):
|
||||
LOG.info("NVML unavailable")
|
||||
except Exception as exc:
|
||||
LOG.info("NVML unavailable (%s)", type(exc).__name__)
|
||||
|
||||
def get(self, key, *args):
|
||||
try:
|
||||
return getattr(self.api, "nvmlDeviceGet" + key)(*args)
|
||||
except (self.api.NVMLError, AttributeError):
|
||||
return None
|
||||
|
||||
def metrics(self, handle):
|
||||
n = self.api
|
||||
sensors = {}
|
||||
utilization = self.get("UtilizationRates", handle)
|
||||
if utilization is not None:
|
||||
sensors["util"] = utilization.gpu
|
||||
mem = self.get("MemoryInfo", handle)
|
||||
if mem is not None:
|
||||
for attr in ("total", "used", "free"):
|
||||
sensors[f"vram_{attr}"] = getattr(mem, attr)
|
||||
for key, command, args, factor in (
|
||||
("temperature", "Temperature", (n.NVML_TEMPERATURE_GPU,), 1),
|
||||
("clock", "ClockInfo", (n.NVML_CLOCK_GRAPHICS,), 1),
|
||||
("memory_clock", "ClockInfo", (n.NVML_CLOCK_MEM,), 1),
|
||||
("power", "PowerUsage", (), .001), ("power_limit", "PowerManagementLimit", (), .001),
|
||||
("fan", "FanSpeed", (), 1), ("encode", "EncoderUtilization", (), 1),
|
||||
("decode", "DecoderUtilization", (), 1),
|
||||
):
|
||||
value = self.get(command, handle, *args)
|
||||
if value is not None:
|
||||
sensors[key] = value[0] * factor if isinstance(value, (tuple, list)) else value * factor
|
||||
return sensors
|
||||
|
||||
def close(self):
|
||||
if self.api:
|
||||
try:
|
||||
self.api.nvmlShutdown()
|
||||
except self.api.NVMLError as exc:
|
||||
LOG.debug("NVML shutdown returned %s", type(exc).__name__)
|
||||
|
||||
|
||||
class WddmGpu(Provider):
|
||||
identifier = "GPU"
|
||||
|
||||
def __init__(self, settings):
|
||||
self.selected = settings.gpus
|
||||
self.interval = settings.local_interval
|
||||
self.last_tick = 0
|
||||
self.nvml = Nvml()
|
||||
try:
|
||||
self.devices = adapters()
|
||||
except OSError:
|
||||
LOG.warning("DXGI hardware enumeration failed", exc_info=True)
|
||||
self.devices = []
|
||||
self.counters = Pdh({
|
||||
"engine": r"\GPU Engine(*)\Utilization Percentage",
|
||||
"dedicated": r"\GPU Adapter Memory(*)\Dedicated Usage",
|
||||
"shared": r"\GPU Adapter Memory(*)\Shared Usage",
|
||||
})
|
||||
groups = {}
|
||||
self.locations = {}
|
||||
identities = [(adapter, *adapter_identity(adapter)) for adapter in self.devices]
|
||||
physical = {(a.vendor, a.device, a.subsystem) for a, location, _ in identities if location is not None}
|
||||
for adapter, location, flags in identities:
|
||||
if location is None and (adapter.vendor, adapter.device, adapter.subsystem) in physical:
|
||||
LOG.info("Skipping non-PCI DXGI alias %s (%s, type %s)", adapter.identifier, adapter.name, flags)
|
||||
continue
|
||||
identifier = (f"pci:{adapter.vendor:04x}:{location[0]:02x}:{location[1]:02x}.{location[2]}"
|
||||
if location is not None else adapter.identifier)
|
||||
groups.setdefault(identifier, []).append(adapter)
|
||||
self.locations[identifier] = location
|
||||
LOG.info("DXGI adapter %s %s (%s)", adapter.identifier, adapter.name, identifier)
|
||||
self.groups = groups
|
||||
nvml_counts = Counter(device for _, _, device, _, _ in self.nvml.devices)
|
||||
self.matches = {}
|
||||
for identifier, name, device, pci, handle in self.nvml.devices:
|
||||
candidates = [key for key, group in groups.items()
|
||||
if group[0].vendor == 0x10de and group[0].device == device]
|
||||
matches = [key for key in candidates
|
||||
if self.locations[key] is not None and self.locations[key][:2] == pci]
|
||||
if len(matches) == 1:
|
||||
self.matches[matches[0]] = handle
|
||||
elif len(candidates) == 1 and nvml_counts[device] == 1:
|
||||
self.matches[candidates[0]] = handle
|
||||
elif not matches and not any(a.vendor == 0x10de for a in self.devices):
|
||||
self.matches[identifier] = (name, handle)
|
||||
else:
|
||||
LOG.info("NVML adapter identity unresolved for %s; using WDDM for that adapter", name)
|
||||
|
||||
def sample(self):
|
||||
stamp, tick = time(), monotonic()
|
||||
baseline = not 0 < tick - self.last_tick <= max(self.interval * 3, 2)
|
||||
self.last_tick = tick
|
||||
data = self.counters.collect()
|
||||
engines = engine_usage(data.get("engine", {})) if not baseline else {}
|
||||
dedicated = memory_usage(data.get("dedicated", {}))
|
||||
shared = memory_usage(data.get("shared", {}))
|
||||
items, devices, totals = [], [], []
|
||||
|
||||
def collect(identifier, name, metrics):
|
||||
devices.append(Device("gpu", identifier, name))
|
||||
values = gpu_metrics(metrics)
|
||||
items.extend(readings(LOCAL, stamp, identifier, values))
|
||||
if not self.selected or identifier in self.selected:
|
||||
totals.append(values)
|
||||
|
||||
for identifier, group in self.groups.items():
|
||||
adapter = group[0]
|
||||
aliases = [item.identifier for item in group]
|
||||
# Driver aliases refer to one PCI function. Take the largest reported
|
||||
# adapter reading instead of adding capacity or mirrored counters twice.
|
||||
metrics = {engine: max((engines[key][engine] for key in aliases
|
||||
if key in engines and engines[key].get(engine) is not None),
|
||||
default=None)
|
||||
for engine in ("util", "encode", "decode", "compute")}
|
||||
if adapter.dedicated:
|
||||
metrics["vram_used"] = max((dedicated[key] for key in aliases if key in dedicated),
|
||||
default=None)
|
||||
metrics["vram_total"] = adapter.dedicated or None
|
||||
metrics["shared_total"] = adapter.shared or None
|
||||
metrics["shared_used"] = max((shared[key] for key in aliases if key in shared), default=None)
|
||||
if identifier in self.matches:
|
||||
metrics.update(self.nvml.metrics(self.matches[identifier]))
|
||||
collect(identifier, adapter.name, metrics)
|
||||
|
||||
for identifier, match in self.matches.items():
|
||||
if isinstance(match, tuple):
|
||||
name, handle = match
|
||||
collect(identifier, name, self.nvml.metrics(handle))
|
||||
return Sample(LOCAL, self.identifier, stamp, tuple(items) + aggregate(LOCAL, stamp, "gpu", totals),
|
||||
tuple(devices))
|
||||
|
||||
def close(self):
|
||||
self.counters.close()
|
||||
self.nvml.close()
|
||||
101
arm/providers/linux_probe.sh
Normal file
101
arm/providers/linux_probe.sh
Normal file
@@ -0,0 +1,101 @@
|
||||
# The client sends a single dot for each observation over the existing channel.
|
||||
export LC_ALL=C
|
||||
os=$(uname -sr)
|
||||
nvidia=$(command -v nvidia-smi || :)
|
||||
sample() {
|
||||
printf '@arm-begin\nos\t%s\n' "$os"
|
||||
while read -r name value; do
|
||||
case "$name" in
|
||||
cpu|cpu[0-9]*) printf 'cpu\t%s\t%s\n' "$name" "$value";;
|
||||
btime) printf 'boot\t%s\n' "$value";;
|
||||
esac
|
||||
done < /proc/stat
|
||||
while read -r name value unit; do
|
||||
case "$name" in
|
||||
MemTotal:|MemAvailable:|SwapTotal:|SwapFree:|Committed_AS:|CommitLimit:)
|
||||
printf 'ram\t%s\t%s\n' "${name%:}" "$value";;
|
||||
esac
|
||||
done < /proc/meminfo
|
||||
model= frequency= physical= core= processor=
|
||||
while IFS=: read -r key value; do
|
||||
case "${key// /}" in
|
||||
processor*) processor=$value;;
|
||||
modelname*|Hardware*) [[ -n $model ]] || model=$value;;
|
||||
cpuMHz*) [[ -n $frequency ]] || frequency=$value;;
|
||||
physicalid*) physical=$value;;
|
||||
coreid*) core=$value;;
|
||||
'') [[ -z $processor ]] || printf 'core\t%s\t%s\t%s\n' "$processor" "$physical" "$core"
|
||||
physical= core= processor=;;
|
||||
esac
|
||||
done < /proc/cpuinfo
|
||||
[[ -z $processor ]] || printf 'core\t%s\t%s\t%s\n' "$processor" "$physical" "$core"
|
||||
printf 'cpuinfo\t%s\t%s\n' "$model" "$frequency"
|
||||
for sensor in /sys/class/hwmon/hwmon*; do
|
||||
[[ -r $sensor/name ]] || continue
|
||||
read -r driver < "$sensor/name"
|
||||
case "$driver" in
|
||||
coretemp|k10temp|zenpower)
|
||||
temp= power=
|
||||
[[ ! -r $sensor/temp1_input ]] || read -r temp < "$sensor/temp1_input"
|
||||
[[ ! -r $sensor/power1_input ]] || read -r power < "$sensor/power1_input"
|
||||
printf 'cpusensor\t%s\t%s\n' "$temp" "$power";;
|
||||
esac
|
||||
done
|
||||
while read -r major minor dev rest; do
|
||||
[[ -d /sys/block/$dev && -e /sys/block/$dev/device ]] || continue
|
||||
printf 'disk\t%s\t%s\n' "$dev" "$rest"
|
||||
done < /proc/diskstats
|
||||
while IFS=: read -r dev rest; do
|
||||
[[ -n $rest ]] || continue
|
||||
dev=${dev//[[:space:]]/}
|
||||
path=/sys/class/net/$dev
|
||||
[[ -d $path ]] || continue
|
||||
speed= state= physical=0
|
||||
[[ ! -e $path/device ]] || physical=1
|
||||
[[ ! -r $path/operstate ]] || read -r state < "$path/operstate"
|
||||
{ [[ ! -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"
|
||||
done < /proc/net/dev
|
||||
for path in /sys/class/drm/card[0-9]*; do
|
||||
[[ ${path##*/} =~ ^card[0-9]+$ && -r $path/device/vendor ]] || continue
|
||||
dev=$path/device
|
||||
vendor= id= slot= busy= used= total= temperature= clock= memory_clock= power= cap=
|
||||
read -r vendor < "$dev/vendor"
|
||||
if [[ $vendor == 0x10de && -n $nvidia ]]; then continue; fi
|
||||
[[ ! -r $dev/device ]] || read -r id < "$dev/device"
|
||||
if [[ -r $dev/uevent ]]; then
|
||||
while IFS== read -r key value; do
|
||||
[[ $key != PCI_SLOT_NAME ]] || slot=$value
|
||||
done < "$dev/uevent"
|
||||
fi
|
||||
[[ ! -r $dev/gpu_busy_percent ]] || read -r busy < "$dev/gpu_busy_percent"
|
||||
[[ ! -r $dev/mem_info_vram_used ]] || read -r used < "$dev/mem_info_vram_used"
|
||||
[[ ! -r $dev/mem_info_vram_total ]] || read -r total < "$dev/mem_info_vram_total"
|
||||
[[ ! -r $dev/pp_dpm_sclk ]] || while read -r _ val tag; do
|
||||
[[ $tag != '*' ]] || clock=${val%[Mm][Hh][Zz]}
|
||||
done < "$dev/pp_dpm_sclk"
|
||||
[[ ! -r $dev/pp_dpm_mclk ]] || while read -r _ val tag; do
|
||||
[[ $tag != '*' ]] || memory_clock=${val%[Mm][Hh][Zz]}
|
||||
done < "$dev/pp_dpm_mclk"
|
||||
for sensor in "$dev"/hwmon/hwmon*; do
|
||||
[[ -d $sensor ]] || continue
|
||||
[[ ! -r $sensor/temp1_input ]] || read -r temperature < "$sensor/temp1_input"
|
||||
[[ ! -r $sensor/power1_average ]] || read -r power < "$sensor/power1_average"
|
||||
[[ ! -r $sensor/power1_cap ]] || read -r cap < "$sensor/power1_cap"
|
||||
break
|
||||
done
|
||||
printf 'drm\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\t%s\n' \
|
||||
"${slot:-${path##*/}}" "$vendor" "$id" "$busy" "$used" "$total" "$temperature" \
|
||||
"$clock" "$memory_clock" "$power,$cap"
|
||||
done
|
||||
if [[ -n $nvidia ]] && command -v timeout >/dev/null; then
|
||||
timeout 2 "$nvidia" --format=csv,noheader,nounits \
|
||||
--query-gpu=pci.bus_id,name,utilization.gpu,memory.used,memory.total,temperature.gpu,clocks.gr,clocks.mem,power.draw,power.limit,fan.speed,utilization.encoder,utilization.decoder \
|
||||
2>/dev/null | while IFS= read -r gpu; do printf 'nvidia\t%s\n' "$gpu"; done
|
||||
fi
|
||||
printf '@arm-end\n'
|
||||
}
|
||||
while IFS= read -r action; do
|
||||
[[ $action == . ]] || break
|
||||
sample
|
||||
done
|
||||
266
arm/providers/native.py
Normal file
266
arm/providers/native.py
Normal file
@@ -0,0 +1,266 @@
|
||||
"""Windows performance data and adapter identity."""
|
||||
import ctypes as ct
|
||||
from ctypes import wintypes as w
|
||||
import logging
|
||||
from mmap import PAGESIZE
|
||||
import uuid
|
||||
import winreg
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class _Double(ct.Structure):
|
||||
_fields_ = [("status", w.DWORD), ("value", ct.c_double)]
|
||||
|
||||
|
||||
class _Item(ct.Structure):
|
||||
_fields_ = [("name", w.LPWSTR), ("data", _Double)]
|
||||
|
||||
|
||||
class Pdh:
|
||||
MORE_DATA = 0x800007D2
|
||||
|
||||
def __init__(self, paths):
|
||||
self.dll = ct.WinDLL("pdh")
|
||||
hndl = w.HANDLE
|
||||
for name, args in {
|
||||
"PdhOpenQueryW": [w.LPCWSTR, ct.c_size_t, ct.POINTER(hndl)],
|
||||
"PdhAddEnglishCounterW": [hndl, w.LPCWSTR, ct.c_size_t, ct.POINTER(hndl)],
|
||||
"PdhCollectQueryData": [hndl],
|
||||
"PdhGetFormattedCounterArrayW": [
|
||||
hndl, w.DWORD, ct.POINTER(w.DWORD), ct.POINTER(w.DWORD), ct.c_void_p],
|
||||
"PdhCloseQuery": [hndl],
|
||||
}.items():
|
||||
fn = getattr(self.dll, name)
|
||||
fn.argtypes = args
|
||||
fn.restype = w.DWORD
|
||||
self.query = hndl()
|
||||
result = self.dll.PdhOpenQueryW(None, 0, ct.byref(self.query))
|
||||
if result:
|
||||
raise OSError(f"PdhOpenQuery returned {result:#x}")
|
||||
self.counters = {}
|
||||
for key, path in paths.items():
|
||||
counter = hndl()
|
||||
result = self.dll.PdhAddEnglishCounterW(self.query, path, 0, ct.byref(counter))
|
||||
if result:
|
||||
LOG.info("Windows counter unavailable %s (%#x)", key, result)
|
||||
else:
|
||||
self.counters[key] = counter
|
||||
|
||||
def collect(self):
|
||||
result = self.dll.PdhCollectQueryData(self.query)
|
||||
if result and self.counters:
|
||||
LOG.debug("Windows query unavailable (%#x)", result)
|
||||
return {key: self._array(counter) for key, counter in self.counters.items()}
|
||||
|
||||
def _array(self, counter):
|
||||
length, count = w.DWORD(), w.DWORD()
|
||||
getter = self.dll.PdhGetFormattedCounterArrayW
|
||||
for _ in range(3):
|
||||
result = getter(counter, 0x200, ct.byref(length), ct.byref(count), None)
|
||||
if result != self.MORE_DATA or not 0 < length.value <= 32 * 1024 * 1024:
|
||||
return {}
|
||||
data = ct.create_string_buffer(length.value)
|
||||
result = getter(counter, 0x200, ct.byref(length), ct.byref(count), data)
|
||||
if not result:
|
||||
rows = ct.cast(data, ct.POINTER(_Item))
|
||||
return {rows[i].name: rows[i].data.value for i in range(count.value)
|
||||
if rows[i].data.status in (0, 1) and rows[i].name}
|
||||
if result != self.MORE_DATA:
|
||||
break
|
||||
return {}
|
||||
|
||||
def close(self):
|
||||
if self.query:
|
||||
self.dll.PdhCloseQuery(self.query)
|
||||
self.query = None
|
||||
|
||||
|
||||
class _Luid(ct.Structure):
|
||||
_fields_ = [("low", w.DWORD), ("high", w.LONG)]
|
||||
|
||||
|
||||
class Adapter(ct.Structure):
|
||||
_fields_ = [("name", w.WCHAR * 128), ("vendor", w.UINT), ("device", w.UINT),
|
||||
("subsystem", w.UINT), ("revision", w.UINT), ("dedicated", ct.c_size_t),
|
||||
("system", ct.c_size_t), ("shared", ct.c_size_t), ("luid", _Luid),
|
||||
("flags", w.UINT)]
|
||||
|
||||
@property
|
||||
def identifier(self):
|
||||
return f"luid_0x{self.luid.high & 0xffffffff:08x}_0x{self.luid.low:08x}"
|
||||
|
||||
|
||||
class _OpenAdapter(ct.Structure):
|
||||
_fields_ = [("luid", _Luid), ("handle", w.UINT)]
|
||||
|
||||
|
||||
class _QueryAdapter(ct.Structure):
|
||||
_fields_ = [("handle", w.UINT), ("kind", w.UINT), ("data", ct.c_void_p), ("size", w.UINT)]
|
||||
|
||||
|
||||
def adapter_identity(adapter):
|
||||
gdi = ct.WinDLL("gdi32")
|
||||
opened = _OpenAdapter(adapter.luid)
|
||||
create = gdi.D3DKMTOpenAdapterFromLuid
|
||||
create.argtypes = [ct.POINTER(_OpenAdapter)]
|
||||
if create(ct.byref(opened)):
|
||||
return None, None
|
||||
close = gdi.D3DKMTCloseAdapter
|
||||
close.argtypes = [ct.POINTER(w.UINT)]
|
||||
try:
|
||||
result = (w.UINT * 3)()
|
||||
query = gdi.D3DKMTQueryAdapterInfo
|
||||
query.argtypes = [ct.POINTER(_QueryAdapter)]
|
||||
args = _QueryAdapter(opened.handle, 6, ct.addressof(result), ct.sizeof(result))
|
||||
location = (tuple(result) if not query(ct.byref(args)) and result[0] <= 255
|
||||
and result[1] <= 31 and result[2] <= 7 else None)
|
||||
flags = w.UINT()
|
||||
args = _QueryAdapter(opened.handle, 15, ct.addressof(flags), ct.sizeof(flags))
|
||||
return location, flags.value if not query(ct.byref(args)) else None
|
||||
finally:
|
||||
close(ct.byref(w.UINT(opened.handle)))
|
||||
|
||||
|
||||
def _method(ptr, slot, result, *args):
|
||||
table = ct.cast(ptr, ct.POINTER(ct.POINTER(ct.c_void_p))).contents
|
||||
return ct.WINFUNCTYPE(result, ct.c_void_p, *args)(table[slot])
|
||||
|
||||
|
||||
def adapters():
|
||||
create = ct.WinDLL("dxgi").CreateDXGIFactory1
|
||||
create.argtypes = [ct.c_void_p, ct.POINTER(ct.c_void_p)]
|
||||
create.restype = ct.c_long
|
||||
factory = ct.c_void_p()
|
||||
identifier = ct.create_string_buffer(uuid.UUID("770aae78-f26f-4dba-a829-253c83d1b387").bytes_le)
|
||||
result = create(identifier, ct.byref(factory))
|
||||
if result:
|
||||
raise OSError(f"DXGI initialization returned {result & 0xffffffff:#x}")
|
||||
devices = []
|
||||
try:
|
||||
enum = _method(factory, 12, ct.c_long, w.UINT, ct.POINTER(ct.c_void_p))
|
||||
for index in range(128):
|
||||
adapter = ct.c_void_p()
|
||||
if enum(factory, index, ct.byref(adapter)):
|
||||
break
|
||||
try:
|
||||
description = Adapter()
|
||||
if not _method(adapter, 10, ct.c_long, ct.POINTER(Adapter))(adapter, ct.byref(description)):
|
||||
if not description.flags & 2 and description.vendor in (0x10de, 0x1002, 0x8086):
|
||||
devices.append(description)
|
||||
finally:
|
||||
_method(adapter, 2, w.ULONG)(adapter)
|
||||
finally:
|
||||
_method(factory, 2, w.ULONG)(factory)
|
||||
return devices
|
||||
|
||||
|
||||
class _Perf(ct.Structure):
|
||||
_fields_ = [("size", w.DWORD)] + [(name, ct.c_size_t) for name in (
|
||||
"commit", "commit_limit", "commit_peak", "physical", "available", "cache",
|
||||
"kernel", "paged", "nonpaged", "page_size")] + [
|
||||
(name, w.DWORD) for name in ("handles", "processes", "threads")]
|
||||
|
||||
|
||||
def commit():
|
||||
info = _Perf()
|
||||
info.size = ct.sizeof(info)
|
||||
get = ct.WinDLL("kernel32").K32GetPerformanceInfo
|
||||
get.argtypes = [ct.POINTER(_Perf), w.DWORD]
|
||||
get.restype = w.BOOL
|
||||
if get(ct.byref(info), info.size):
|
||||
return info.commit * info.page_size, info.commit_limit * info.page_size
|
||||
return None, None
|
||||
|
||||
|
||||
class _PageFile(ct.Structure):
|
||||
_fields_ = [("size", w.DWORD), ("reserved", w.DWORD), ("total", ct.c_size_t),
|
||||
("used", ct.c_size_t), ("peak", ct.c_size_t)]
|
||||
|
||||
|
||||
def pagefiles():
|
||||
rows = []
|
||||
callback = ct.WINFUNCTYPE(w.BOOL, ct.c_void_p, ct.POINTER(_PageFile), w.LPCWSTR)
|
||||
|
||||
@callback
|
||||
def collect(_context, info, _filename):
|
||||
rows.append((info.contents.used, info.contents.total))
|
||||
return True
|
||||
|
||||
enumerate_files = ct.WinDLL("psapi").EnumPageFilesW
|
||||
enumerate_files.argtypes = [callback, ct.c_void_p]
|
||||
enumerate_files.restype = w.BOOL
|
||||
if enumerate_files(collect, None):
|
||||
return (sum(used for used, _ in rows) * PAGESIZE,
|
||||
sum(total for _, total in rows) * PAGESIZE)
|
||||
return None, None
|
||||
|
||||
|
||||
def cpu_identity():
|
||||
try:
|
||||
with winreg.OpenKey(winreg.HKEY_LOCAL_MACHINE, r"HARDWARE\DESCRIPTION\System\CentralProcessor\0") as key:
|
||||
return winreg.QueryValueEx(key, "ProcessorNameString")[0].strip()
|
||||
except OSError:
|
||||
return "Windows CPU"
|
||||
|
||||
|
||||
def physical_cores():
|
||||
get = ct.WinDLL("kernel32").GetLogicalProcessorInformationEx
|
||||
get.argtypes = [ct.c_int, ct.c_void_p, ct.POINTER(w.DWORD)]
|
||||
get.restype = w.BOOL
|
||||
length = w.DWORD()
|
||||
get(0, None, ct.byref(length))
|
||||
if not length.value:
|
||||
return []
|
||||
buf = ct.create_string_buffer(length.value)
|
||||
if not get(0, buf, ct.byref(length)):
|
||||
return []
|
||||
offset, cores = 0, []
|
||||
while offset + 32 <= length.value:
|
||||
size = w.DWORD.from_buffer(buf, offset + 4).value
|
||||
groups = w.WORD.from_buffer(buf, offset + 30).value
|
||||
if size < 32 + groups * 16 or offset + size > length.value:
|
||||
break
|
||||
processors = []
|
||||
for group_index in range(groups):
|
||||
start = offset + 32 + group_index * 16
|
||||
mask = ct.c_uint64.from_buffer(buf, start).value
|
||||
group = w.WORD.from_buffer(buf, start + 8).value
|
||||
processors.extend(group * 64 + bit for bit in range(64) if mask & (1 << bit))
|
||||
if processors:
|
||||
cores.append(processors)
|
||||
offset += size
|
||||
return cores
|
||||
|
||||
|
||||
class _InterfaceRow(ct.Structure):
|
||||
_fields_ = [("luid", ct.c_uint64), ("index", w.ULONG), ("guid", ct.c_byte * 16),
|
||||
("alias", w.WCHAR * 257), ("description", w.WCHAR * 257),
|
||||
("address_length", w.ULONG), ("address", ct.c_byte * 32),
|
||||
("permanent", ct.c_byte * 32), ("mtu", w.ULONG), ("type", w.ULONG),
|
||||
("tunnel", w.ULONG), ("media", w.ULONG), ("physical_medium", w.ULONG),
|
||||
("access", w.ULONG), ("direction", w.ULONG), ("flags", ct.c_ubyte),
|
||||
("oper_status", w.ULONG), ("admin_status", w.ULONG), ("connect", w.ULONG),
|
||||
("network_guid", ct.c_byte * 16), ("connection_type", w.ULONG),
|
||||
("transmit", ct.c_uint64), ("receive", ct.c_uint64),
|
||||
("counters", ct.c_uint64 * 18)]
|
||||
|
||||
|
||||
def interface_info():
|
||||
ip = ct.WinDLL("iphlpapi")
|
||||
get = ip.GetIfTable2
|
||||
get.argtypes = [ct.POINTER(ct.c_void_p)]
|
||||
get.restype = w.ULONG
|
||||
free = ip.FreeMibTable
|
||||
free.argtypes = [ct.c_void_p]
|
||||
free.restype = None
|
||||
table = ct.c_void_p()
|
||||
if get(ct.byref(table)):
|
||||
return {}
|
||||
try:
|
||||
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}
|
||||
finally:
|
||||
free(table)
|
||||
367
arm/providers/ssh.py
Normal file
367
arm/providers/ssh.py
Normal file
@@ -0,0 +1,367 @@
|
||||
import base64
|
||||
import csv
|
||||
import hashlib
|
||||
import io
|
||||
from math import isfinite
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import shlex
|
||||
import threading
|
||||
from collections import defaultdict
|
||||
from dataclasses import dataclass
|
||||
import logging
|
||||
from time import perf_counter as monotonic, time
|
||||
|
||||
import paramiko
|
||||
|
||||
from . import Provider
|
||||
from .gpu import gpu_metrics
|
||||
from .windows import cpu_group, disk_metrics, net_metrics
|
||||
from ..model import Device, Sample, TOTAL, aggregate, rate, readings, usage
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
SCRIPT = Path(__file__).with_name("linux_probe.sh")
|
||||
HOST_LOCK = threading.Lock()
|
||||
MAX_FRAME = 1024 * 1024
|
||||
VENDORS = {"0x1002": "AMD", "0x8086": "Intel", "0x10de": "NVIDIA"}
|
||||
|
||||
|
||||
def probe_command():
|
||||
# Passing the fixed program in -c leaves channel stdin dedicated to tokens.
|
||||
return "bash --noprofile --norc -c " + shlex.quote(SCRIPT.read_text(encoding="utf-8"))
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class HostKey:
|
||||
label: str
|
||||
key: object
|
||||
|
||||
@property
|
||||
def fingerprint(self):
|
||||
sha = hashlib.sha256(self.key.asbytes()).digest()
|
||||
return "SHA256:" + base64.b64encode(sha).decode("ascii").rstrip("=")
|
||||
|
||||
|
||||
class UntrustedHost(paramiko.SSHException):
|
||||
def __init__(self, label, key):
|
||||
super().__init__("New SSH host key")
|
||||
self.host_key = HostKey(label, key)
|
||||
|
||||
|
||||
class RecordUnknownKey(paramiko.MissingHostKeyPolicy):
|
||||
def missing_host_key(self, client, hostname, key):
|
||||
raise UntrustedHost(hostname, key)
|
||||
|
||||
|
||||
def known_hosts(path):
|
||||
keys = paramiko.HostKeys()
|
||||
if path.is_file():
|
||||
keys.load(str(path))
|
||||
return keys
|
||||
|
||||
|
||||
def update_host_key(path, label, key=None):
|
||||
with HOST_LOCK:
|
||||
keys = known_hosts(path)
|
||||
if key is None:
|
||||
if label in keys:
|
||||
del keys[label]
|
||||
else:
|
||||
if label in keys and not keys.check(label, key):
|
||||
raise ValueError("A different key is already stored for this host")
|
||||
keys.add(label, key.get_name(), key)
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
temporary = path.with_suffix(".tmp")
|
||||
try:
|
||||
keys.save(str(temporary))
|
||||
temporary.replace(path)
|
||||
finally:
|
||||
temporary.unlink(missing_ok=True)
|
||||
|
||||
|
||||
class LinuxSsh(Provider):
|
||||
identifier = "Linux SSH"
|
||||
|
||||
def __init__(self, target, secrets, hosts):
|
||||
self.target = target
|
||||
self.secrets = secrets
|
||||
self.hosts = hosts
|
||||
self.transport = None
|
||||
self.channel = None
|
||||
self.sock = None
|
||||
self.pending = bytearray()
|
||||
self.cancelled = threading.Event()
|
||||
self.collector = LinuxParser(target)
|
||||
self.os = "Linux"
|
||||
self.command = probe_command()
|
||||
|
||||
def _resolve(self):
|
||||
target = self.target
|
||||
resolved = []
|
||||
done = threading.Event()
|
||||
|
||||
def resolve():
|
||||
try:
|
||||
resolved.extend(socket.getaddrinfo(target.host, target.port, type=socket.SOCK_STREAM))
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
done.set()
|
||||
|
||||
threading.Thread(target=resolve, daemon=True, name="ARM SSH DNS").start()
|
||||
deadline = monotonic() + target.timeout
|
||||
while not self.cancelled.is_set() and not done.wait(.1):
|
||||
if monotonic() >= deadline:
|
||||
raise TimeoutError("SSH hostname lookup timed out")
|
||||
if not resolved or self.cancelled.is_set():
|
||||
raise OSError("SSH hostname could not be resolved")
|
||||
return resolved
|
||||
|
||||
def connect(self):
|
||||
expired = threading.Event()
|
||||
|
||||
def timeout():
|
||||
expired.set()
|
||||
self.close_socket()
|
||||
|
||||
watchdog = threading.Timer(self.target.timeout, timeout)
|
||||
watchdog.daemon = True
|
||||
watchdog.start()
|
||||
try:
|
||||
self._connect(expired)
|
||||
except Exception:
|
||||
if expired.is_set():
|
||||
raise TimeoutError("SSH handshake or channel setup timed out") from None
|
||||
raise
|
||||
finally:
|
||||
watchdog.cancel()
|
||||
if expired.is_set():
|
||||
raise TimeoutError("SSH handshake or channel setup timed out")
|
||||
|
||||
def _connect(self, expired):
|
||||
target = self.target
|
||||
deadline = monotonic() + target.timeout
|
||||
for family, mode, proto, _, addr in self._resolve():
|
||||
if expired.is_set() or self.cancelled.is_set() or monotonic() >= deadline:
|
||||
break
|
||||
sock = socket.socket(family, mode, proto)
|
||||
self.sock = sock
|
||||
try:
|
||||
sock.settimeout(max(.1, deadline - monotonic()))
|
||||
sock.connect(addr)
|
||||
if self.cancelled.is_set():
|
||||
raise OSError("SSH connection cancelled")
|
||||
break
|
||||
except OSError:
|
||||
sock.close()
|
||||
self.sock = None
|
||||
if self.sock is None or self.cancelled.is_set():
|
||||
raise OSError("SSH connection unavailable")
|
||||
client = paramiko.SSHClient()
|
||||
self.transport = client
|
||||
if self.hosts.is_file():
|
||||
with HOST_LOCK:
|
||||
client.load_host_keys(str(self.hosts))
|
||||
client.set_missing_host_key_policy(RecordUnknownKey())
|
||||
secret = self.secrets.read(target.credential)
|
||||
if target.auth == "Password" and secret is None:
|
||||
raise paramiko.AuthenticationException("No saved password")
|
||||
if target.auth == "Private key" and not target.key_file:
|
||||
raise paramiko.AuthenticationException("No private key selected")
|
||||
client.connect(target.host, port=target.port, username=target.username,
|
||||
password=secret if target.auth == "Password" else None,
|
||||
passphrase=secret if target.auth == "Private key" else None,
|
||||
key_filename=target.key_file if target.auth == "Private key" else None,
|
||||
timeout=target.timeout, banner_timeout=target.timeout, auth_timeout=target.timeout,
|
||||
channel_timeout=target.timeout, allow_agent=False, look_for_keys=False, sock=self.sock)
|
||||
transport = client.get_transport()
|
||||
transport.set_keepalive(15)
|
||||
self.channel = transport.open_session(timeout=target.timeout)
|
||||
self.channel.settimeout(.25)
|
||||
self.channel.set_combine_stderr(True)
|
||||
self.channel.exec_command(self.command)
|
||||
|
||||
def sample(self):
|
||||
if self.channel is None:
|
||||
self.connect()
|
||||
self.channel.sendall(b".\n")
|
||||
deadline = monotonic() + self.target.timeout
|
||||
while monotonic() < deadline and not self.cancelled.is_set():
|
||||
start = self.pending.find(b"@arm-begin\n")
|
||||
if start >= 0:
|
||||
end = self.pending.find(b"@arm-end\n", start)
|
||||
if end >= 0:
|
||||
frame = bytes(self.pending[start + 11:end])
|
||||
del self.pending[:end + 9]
|
||||
stamp = time()
|
||||
packet, self.os = self.collector.parse(frame.decode("utf-8", "replace"), stamp, monotonic())
|
||||
return packet
|
||||
try:
|
||||
chunk = self.channel.recv(32768)
|
||||
except socket.timeout:
|
||||
continue
|
||||
if not chunk:
|
||||
raise EOFError("SSH telemetry channel closed")
|
||||
self.pending.extend(chunk)
|
||||
if len(self.pending) > MAX_FRAME:
|
||||
raise ValueError("SSH telemetry response exceeds limit")
|
||||
raise TimeoutError("SSH telemetry response timed out")
|
||||
|
||||
def cancel(self):
|
||||
self.cancelled.set()
|
||||
self.close_socket()
|
||||
|
||||
def close_socket(self):
|
||||
sock = self.sock
|
||||
if sock is not None:
|
||||
try:
|
||||
sock.shutdown(socket.SHUT_RDWR)
|
||||
except OSError:
|
||||
pass
|
||||
sock.close()
|
||||
|
||||
def close(self):
|
||||
self.cancel()
|
||||
if self.transport is not None:
|
||||
self.transport.close()
|
||||
|
||||
|
||||
def num(value, factor=1):
|
||||
try:
|
||||
n = float(value) * factor
|
||||
return n if isfinite(n) else None
|
||||
except (TypeError, ValueError):
|
||||
return None
|
||||
|
||||
|
||||
def integers(row, count):
|
||||
result = row.split()
|
||||
if len(result) >= count and all(v.isdecimal() for v in result):
|
||||
return tuple(map(int, result))
|
||||
return ()
|
||||
|
||||
|
||||
class LinuxParser:
|
||||
def __init__(self, target):
|
||||
self.target = target
|
||||
self.previous = {}
|
||||
self.last = 0
|
||||
self.boot = ""
|
||||
|
||||
def parse(self, frame, stamp, tick):
|
||||
sections = defaultdict(list)
|
||||
for line in frame.splitlines():
|
||||
key, *values = line.split("\t")
|
||||
sections[key].append(values)
|
||||
boot = sections["boot"][0][0] if sections["boot"] and sections["boot"][0] else ""
|
||||
if boot != self.boot:
|
||||
self.previous.clear()
|
||||
elapsed = tick - self.last
|
||||
self.boot, self.last = boot, tick
|
||||
machine = self.target.identifier
|
||||
items, devices = [], []
|
||||
next_counters = {}
|
||||
|
||||
def add(kind, identifier, name, values):
|
||||
devices.append(Device(kind, identifier, name))
|
||||
items.extend(readings(machine, stamp, identifier, values))
|
||||
|
||||
def counters(key, current):
|
||||
previous = self.previous.get(key, [None] * len(current))
|
||||
next_counters[key] = current
|
||||
return [rate(old, now, elapsed, self.target.interval) for old, now in zip(previous, current)]
|
||||
|
||||
cpu_values = {}
|
||||
for name, row in (row for row in sections["cpu"] if len(row) == 2):
|
||||
raw = integers(row, 5)
|
||||
if raw:
|
||||
total = sum(raw[:8])
|
||||
busy = total - raw[3] - raw[4]
|
||||
d_busy, d_total = counters(name, (busy, total))
|
||||
cpu_values[name] = (d_busy, d_total)
|
||||
if name != "cpu":
|
||||
add("cpu", name, f"Logical processor {name[3:]}", {"cpu.util": (usage(d_busy, d_total), "%")})
|
||||
core_map = defaultdict(list)
|
||||
for proc, package, core in (row for row in sections["core"] if len(row) == 3):
|
||||
package, core = package.strip(), core.strip()
|
||||
if core:
|
||||
core_map[(package, core)].append("cpu" + proc.strip())
|
||||
for (package, core), processors in core_map.items():
|
||||
add("cpu", f"core:{package}:{core}", f"Package {package or '0'} core {core}",
|
||||
{"cpu.util": (cpu_group(cpu_values, processors), "%")})
|
||||
model, frequency = (sections["cpuinfo"][0] + ["", ""])[:2] if sections["cpuinfo"] else ("", "")
|
||||
if model.strip():
|
||||
devices.append(Device("cpu-info", "identity", model.strip()))
|
||||
sensors = [row for row in sections["cpusensor"] if len(row) == 2]
|
||||
temperatures = [val for temp, _ in sensors if (val := num(temp, .001)) is not None]
|
||||
powers = [val for _, power in sensors if (val := num(power, .000001)) is not None]
|
||||
items.extend(readings(machine, stamp, TOTAL, {
|
||||
"cpu.util": (usage(*cpu_values.get("cpu", (None, None))), "%"),
|
||||
"cpu.physical": (len(core_map) or None, "count"),
|
||||
"cpu.logical": (sum(key != "cpu" for key in cpu_values) if cpu_values else None, "count"),
|
||||
"cpu.frequency": (num(frequency), "MHz"), "cpu.temperature": (max(temperatures, default=None), "°C"),
|
||||
"cpu.power": (sum(powers) if powers else None, "W"),
|
||||
}))
|
||||
mem = {key: num(value, 1024) for key, value in sections["ram"] if value} if all(
|
||||
len(row) == 2 for row in sections["ram"]) else {}
|
||||
total, available = mem.get("MemTotal"), mem.get("MemAvailable")
|
||||
used = difference(total, available)
|
||||
items.extend(readings(machine, stamp, TOTAL, {
|
||||
"ram.total": (total, "B"), "ram.available": (available, "B"), "ram.used": (used, "B"),
|
||||
"ram.util": (usage(used, total), "%"),
|
||||
"ram.pagefile_total": (mem.get("SwapTotal"), "B"),
|
||||
"ram.pagefile_used": (difference(mem.get("SwapTotal"), mem.get("SwapFree")), "B"),
|
||||
"ram.committed": (mem.get("Committed_AS"), "B"), "ram.commit_limit": (mem.get("CommitLimit"), "B"),
|
||||
}))
|
||||
|
||||
filtered = {"disk": [], "net": [], "gpu": []}
|
||||
|
||||
def selected(kind, identifier, name, values, included):
|
||||
add(kind, identifier, name, values)
|
||||
if included:
|
||||
filtered[kind].append(values)
|
||||
|
||||
for key, row in (row for row in sections["disk"] if len(row) == 2):
|
||||
v = integers(row, 11)
|
||||
if v:
|
||||
read, write, reads, writes, active = counters("disk:" + key, (v[2]*512, v[6]*512, v[0], v[4], v[9]))
|
||||
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):
|
||||
v = integers(row, 16)
|
||||
if v:
|
||||
receive, transmit = counters("net:" + key, (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
|
||||
selected("net", key, key, net_metrics(receive, transmit, up, link, link),
|
||||
key in self.target.interfaces if self.target.interfaces else physical == "1")
|
||||
for key, vendor, ident, util, used, total, temp, clock, memclk, power in (
|
||||
row for row in sections["drm"] if len(row) == 10):
|
||||
parts = power.split(",", 1)
|
||||
metrics = gpu_metrics({"util": num(util), "vram_used": num(used), "vram_total": num(total),
|
||||
"temperature": num(temp, .001), "clock": num(clock), "memory_clock": num(memclk),
|
||||
"power": num(parts[0], .000001), "power_limit": num(parts[-1], .000001)})
|
||||
name = f"{VENDORS.get(vendor, vendor)} {ident} ({key})"
|
||||
selected("gpu", key, name, metrics, not self.target.gpus or key in self.target.gpus)
|
||||
for row in csv.reader(io.StringIO("\n".join("\t".join(row) for row in sections["nvidia"])), skipinitialspace=True):
|
||||
if len(row) != 13:
|
||||
continue
|
||||
key, name, util, used, total, temp, clock, memclk, power, limit, fan, enc, dec = row
|
||||
metrics = gpu_metrics({"util": num(util), "vram_used": num(used, 2**20),
|
||||
"vram_total": num(total, 2**20), "temperature": num(temp), "clock": num(clock),
|
||||
"memory_clock": num(memclk), "power": num(power), "power_limit": num(limit),
|
||||
"fan": num(fan), "encode": num(enc), "decode": num(dec)})
|
||||
selected("gpu", key, name, metrics, not self.target.gpus or key in self.target.gpus)
|
||||
self.previous = next_counters
|
||||
for kind, values in filtered.items():
|
||||
items.extend(aggregate(machine, stamp, kind, values))
|
||||
if not cpu_values or not mem:
|
||||
raise ValueError("Linux telemetry response lacks required system information")
|
||||
return Sample(machine, "Linux SSH", stamp, tuple(items), tuple(devices)), (
|
||||
sections["os"][0][0] if sections["os"] and sections["os"][0] else "Linux")
|
||||
|
||||
|
||||
def difference(total, available):
|
||||
return max(0, total - available) if total is not None and available is not None else None
|
||||
197
arm/providers/windows.py
Normal file
197
arm/providers/windows.py
Normal file
@@ -0,0 +1,197 @@
|
||||
import logging
|
||||
import platform
|
||||
from time import perf_counter as monotonic, time
|
||||
|
||||
import psutil
|
||||
|
||||
from . import Provider
|
||||
from .native import Pdh, commit, cpu_identity, interface_info, pagefiles, physical_cores
|
||||
from ..model import (
|
||||
LOCAL, TOTAL, Availability, Device, Reading, Sample, aggregate, rate, readings, usage,
|
||||
)
|
||||
|
||||
LOG = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class Cpu(Provider):
|
||||
identifier = "CPU"
|
||||
|
||||
def __init__(self, settings):
|
||||
self.interval = settings.local_interval
|
||||
self.last = {}
|
||||
self.name = cpu_identity()
|
||||
self.cores = physical_cores()
|
||||
self.stamp = 0
|
||||
|
||||
@staticmethod
|
||||
def times(row):
|
||||
return row.user + row.system + row.idle, row.user + row.system
|
||||
|
||||
def sample(self):
|
||||
stamp, now = time(), monotonic()
|
||||
times = {index: self.times(value) for index, value in enumerate(psutil.cpu_times(percpu=True))}
|
||||
elapsed = now - self.stamp
|
||||
devices = [Device("cpu", f"cpu:{i}", f"Logical processor {i}") for i in times]
|
||||
devices.append(Device("cpu-info", "identity", self.name))
|
||||
values = {}
|
||||
items = []
|
||||
for index, (total, busy) in times.items():
|
||||
previous = self.last.get(index, (None, None))
|
||||
values[index] = (
|
||||
rate(previous[1], busy, elapsed, self.interval),
|
||||
rate(previous[0], total, elapsed, self.interval),
|
||||
)
|
||||
items.extend(readings(LOCAL, stamp, f"cpu:{index}", {
|
||||
"cpu.util": (usage(*values[index]), "%")
|
||||
}))
|
||||
cores = self.cores if {p for core in self.cores for p in core} == set(times) else []
|
||||
for index, core in enumerate(cores):
|
||||
device = f"core:{index}"
|
||||
devices.append(Device("cpu", device, f"Physical core {index}"))
|
||||
items.extend(readings(LOCAL, stamp, device, {"cpu.util": (cpu_group(values, core), "%")}))
|
||||
self.last, self.stamp = times, now
|
||||
frequency = psutil.cpu_freq()
|
||||
items.extend(readings(LOCAL, stamp, TOTAL, {
|
||||
"cpu.util": (cpu_group(values, times), "%"),
|
||||
"cpu.frequency": (frequency.current if frequency else None, "MHz"),
|
||||
"cpu.physical": (len(cores) or psutil.cpu_count(logical=False), "count"),
|
||||
"cpu.logical": (len(times), "count"),
|
||||
}))
|
||||
items.extend(Reading(LOCAL, TOTAL, metric, None, unit, stamp, Availability.UNSUPPORTED,
|
||||
"No supported Windows CPU sensor provider")
|
||||
for metric, unit in (("cpu.temperature", "°C"), ("cpu.power", "W")))
|
||||
return Sample(LOCAL, self.identifier, stamp, tuple(items), tuple(devices))
|
||||
|
||||
|
||||
def cpu_group(values, indexes):
|
||||
pairs = [values[index] for index in indexes if index in values]
|
||||
if pairs and all(busy is not None and total is not None for busy, total in pairs):
|
||||
return usage(sum(busy for busy, _ in pairs), sum(total for _, total in pairs))
|
||||
return None
|
||||
|
||||
|
||||
class Memory(Provider):
|
||||
identifier = "Memory"
|
||||
|
||||
def __init__(self, settings):
|
||||
pass
|
||||
|
||||
def sample(self):
|
||||
stamp = time()
|
||||
mem = psutil.virtual_memory()
|
||||
swap_used, swap_total = pagefiles()
|
||||
used = mem.total - mem.available
|
||||
committed, limit = commit()
|
||||
return Sample(LOCAL, self.identifier, stamp, readings(LOCAL, stamp, TOTAL, {
|
||||
"ram.util": (usage(used, mem.total), "%"), "ram.total": (mem.total, "B"),
|
||||
"ram.used": (used, "B"), "ram.available": (mem.available, "B"),
|
||||
"ram.pagefile_used": (swap_used, "B"), "ram.pagefile_total": (swap_total, "B"),
|
||||
"ram.committed": (committed, "B"), "ram.commit_limit": (limit, "B"),
|
||||
}))
|
||||
|
||||
|
||||
class Counters(Provider):
|
||||
def __init__(self, settings):
|
||||
self.interval = settings.local_interval
|
||||
self.stamp = 0
|
||||
self.last = {}
|
||||
|
||||
def measure(self, stamp, now, rows, selected, convert):
|
||||
items, devices, totals = [], [], []
|
||||
elapsed = now - self.stamp
|
||||
for key, row in rows.items():
|
||||
devices.append(Device(self.kind, key, key))
|
||||
values = convert(key, row, self.last.get(key), elapsed)
|
||||
items.extend(readings(LOCAL, stamp, key, values))
|
||||
if key in selected:
|
||||
totals.append(values)
|
||||
self.last, self.stamp = rows, now
|
||||
return Sample(LOCAL, self.identifier, stamp, tuple(items) +
|
||||
aggregate(LOCAL, stamp, self.kind, totals), tuple(devices))
|
||||
|
||||
|
||||
def deltas(current, previous, fields, elapsed, interval):
|
||||
return [rate(getattr(previous, key, None), getattr(current, key, None), elapsed, interval) for key in fields]
|
||||
|
||||
|
||||
def combined(first, second):
|
||||
return first + second if first is not None and second is not None else None
|
||||
|
||||
|
||||
def disk_metrics(read, write, reads, writes, active):
|
||||
return {"disk.read": (read, "B/s"), "disk.write": (write, "B/s"),
|
||||
"disk.total": (combined(read, write), "B/s"), "disk.read_ops": (reads, "ops/s"),
|
||||
"disk.write_ops": (writes, "ops/s"), "disk.active": (active, "%")}
|
||||
|
||||
|
||||
def net_metrics(receive, transmit, up, rx_link, tx_link):
|
||||
link = max(rx_link or 0, tx_link or 0) or None
|
||||
rx_util = usage(receive * 8, rx_link * 1e6) if up and rx_link and receive is not None else None
|
||||
tx_util = usage(transmit * 8, tx_link * 1e6) if up and tx_link and transmit is not None else None
|
||||
return {"net.receive": (receive, "B/s"), "net.transmit": (transmit, "B/s"),
|
||||
"net.total": (combined(receive, transmit), "B/s"), "net.up": (up, "bool"),
|
||||
"net.link": (link, "Mb/s"), "net.util": (max(rx_util, tx_util) if
|
||||
rx_util is not None and tx_util is not None else None, "%")}
|
||||
|
||||
|
||||
class Disk(Counters):
|
||||
identifier = "Storage"
|
||||
kind = "disk"
|
||||
|
||||
def __init__(self, settings):
|
||||
super().__init__(settings)
|
||||
self.selected = settings.disks
|
||||
self.native = Pdh({"idle": r"\PhysicalDisk(*)\% Idle Time"})
|
||||
|
||||
def sample(self):
|
||||
stamp, now = time(), monotonic()
|
||||
rows = psutil.disk_io_counters(perdisk=True, nowrap=False) or {}
|
||||
rows = {key: row for key, row in rows.items() if key.lower().startswith("physicaldrive")}
|
||||
idle = self.native.collect().get("idle", {})
|
||||
idle = {key.split(" ", 1)[0]: max(0, min(100, 100 - value)) for key, value in idle.items()
|
||||
if key[0].isdigit()}
|
||||
|
||||
def convert(key, row, previous, elapsed):
|
||||
values = deltas(row, previous, ("read_bytes", "write_bytes", "read_count", "write_count"),
|
||||
elapsed, self.interval)
|
||||
active = idle.get(key.removeprefix("PhysicalDrive")) if values[0] is not None else None
|
||||
return disk_metrics(*values, active)
|
||||
|
||||
return self.measure(stamp, now, rows, self.selected or rows, convert)
|
||||
|
||||
def close(self):
|
||||
self.native.close()
|
||||
|
||||
|
||||
class Network(Counters):
|
||||
identifier = "Network"
|
||||
kind = "net"
|
||||
|
||||
def __init__(self, settings):
|
||||
super().__init__(settings)
|
||||
self.selected = settings.interfaces
|
||||
|
||||
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]]
|
||||
|
||||
def convert(key, row, previous, elapsed):
|
||||
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))
|
||||
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)
|
||||
|
||||
|
||||
def os_name():
|
||||
build = platform.version().rsplit(".", 1)[-1]
|
||||
return f"Windows {'11' if build.isdecimal() and int(build) >= 22000 else '10'} ({build})"
|
||||
135
arm/tray.py
Normal file
135
arm/tray.py
Normal file
@@ -0,0 +1,135 @@
|
||||
"""Use the cursor and Explorer's registered icon geometry for hover."""
|
||||
import ctypes as ct
|
||||
from ctypes import wintypes as w
|
||||
from time import monotonic
|
||||
|
||||
from PySide6.QtCore import QPoint, QRect, QSignalBlocker, QSize
|
||||
from PySide6.QtGui import QCursor, QGuiApplication
|
||||
|
||||
|
||||
class NativeCursor:
|
||||
def __init__(self):
|
||||
user = ct.WinDLL("user32")
|
||||
self.position = user.GetCursorPos
|
||||
self.position.argtypes = [ct.POINTER(w.POINT)]
|
||||
self.position.restype = w.BOOL
|
||||
|
||||
def raw(self):
|
||||
pt = w.POINT()
|
||||
if self.position(ct.byref(pt)):
|
||||
return QPoint(pt.x, pt.y)
|
||||
return None
|
||||
|
||||
|
||||
def place_popup(area, icon, size):
|
||||
width, height = min(size.width(), area.width()), min(size.height(), area.height())
|
||||
# Pick the edge adjacent to the icon, including vertical taskbars.
|
||||
distances = {
|
||||
"top": abs(icon.center().y() - area.top()),
|
||||
"bottom": abs(icon.center().y() - area.bottom()),
|
||||
"left": abs(icon.center().x() - area.left()),
|
||||
"right": abs(icon.center().x() - area.right()),
|
||||
}
|
||||
edge = min(distances, key=distances.get)
|
||||
x, y = icon.center().x() - width // 2, icon.center().y() - height // 2
|
||||
if edge == "bottom":
|
||||
y = min(area.bottom() - height + 1, icon.top() - height - 2)
|
||||
elif edge == "top":
|
||||
y = max(area.top(), icon.bottom() + 2)
|
||||
elif edge == "right":
|
||||
x = min(area.right() - width + 1, icon.left() - width - 2)
|
||||
else:
|
||||
x = max(area.left(), icon.right() + 2)
|
||||
x = max(area.left(), min(x, area.right() - width + 1))
|
||||
y = max(area.top(), min(y, area.bottom() - height + 1))
|
||||
return QRect(x, y, width, height)
|
||||
|
||||
|
||||
class HoverState:
|
||||
def __init__(self):
|
||||
self.candidate = None
|
||||
self.entered = 0
|
||||
self.left = None
|
||||
|
||||
def update(self, now, hovered, over_popup, visible, pinned, hover_delay, dismiss_delay):
|
||||
if hovered != self.candidate:
|
||||
self.candidate, self.entered = hovered, now
|
||||
if pinned:
|
||||
self.left = None
|
||||
return None
|
||||
if hovered is not None:
|
||||
self.left = None
|
||||
if not visible and now - self.entered >= hover_delay:
|
||||
return "show"
|
||||
elif visible and not over_popup:
|
||||
if self.left is None:
|
||||
self.left = now
|
||||
elif now - self.left >= dismiss_delay:
|
||||
self.left = None
|
||||
return "hide"
|
||||
else:
|
||||
self.left = None
|
||||
return None
|
||||
|
||||
|
||||
class HoverMonitor:
|
||||
def __init__(self, popup, dashboard, icons, monitor_scope):
|
||||
self.popup, self.dashboard, self.icons = popup, dashboard, icons
|
||||
self.monitor_scope = monitor_scope
|
||||
self.cursor = NativeCursor()
|
||||
self.state = HoverState()
|
||||
self.anchor = None
|
||||
|
||||
def tick(self):
|
||||
raw, cursor = self.cursor.raw(), QCursor.pos()
|
||||
if raw is None:
|
||||
return
|
||||
hovered = None
|
||||
for machine, tray in self.icons.items():
|
||||
# Qt's Windows backend calls Shell_NotifyIconGetRect and exposes
|
||||
# the result in native pixels through QSystemTrayIcon.geometry().
|
||||
if tray.geometry().contains(raw):
|
||||
hovered = machine
|
||||
break
|
||||
over = self.popup.isVisible() and (self.popup.frameGeometry().contains(cursor)
|
||||
or self.popup.interval.view().isVisible()
|
||||
or self.popup.machine.view().isVisible())
|
||||
cfg = self.dashboard.settings
|
||||
visible = self.popup.isVisible() and (self.anchor == hovered or hovered is None or over)
|
||||
action = self.state.update(monotonic(), hovered, over, visible, self.popup.pinned,
|
||||
cfg.hover_delay / 1000, cfg.dismiss_delay / 1000)
|
||||
if action == "show":
|
||||
self.show(hovered)
|
||||
elif action == "hide":
|
||||
self.popup.hide()
|
||||
|
||||
def show(self, machine):
|
||||
tray = self.icons.get(machine)
|
||||
raw_rect = tray.geometry() if tray else QRect()
|
||||
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():
|
||||
ratio = screen.devicePixelRatio()
|
||||
corner = qt + QPoint(round((raw_rect.x() - raw.x()) / ratio), round((raw_rect.y() - raw.y()) / ratio))
|
||||
rect = QRect(corner, QSize(max(1, round(raw_rect.width() / ratio)),
|
||||
max(1, round(raw_rect.height() / ratio))))
|
||||
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.popup.show()
|
||||
self.popup.refresh()
|
||||
|
||||
def pin(self, value, machine=None):
|
||||
self.popup.pinned = value
|
||||
with QSignalBlocker(self.popup.pin):
|
||||
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)
|
||||
135
arm/tray_menu.py
Normal file
135
arm/tray_menu.py
Normal file
@@ -0,0 +1,135 @@
|
||||
"""Design Creations tray commands for each visible ARM icon."""
|
||||
from PySide6.QtCore import QSize
|
||||
from PySide6.QtGui import QActionGroup, QFont, QIcon
|
||||
from PySide6.QtWidgets import QHBoxLayout, QLabel, QMenu, QStyle, QVBoxLayout, QWidget, QWidgetAction
|
||||
|
||||
from .about import BrandImage
|
||||
from .config import TRAY_MODES
|
||||
from .model import ALL, LOCAL
|
||||
from .version import NAME, VERSION
|
||||
|
||||
SP = QStyle.StandardPixmap
|
||||
|
||||
|
||||
class TrayMenu(QMenu):
|
||||
def __init__(self, app, scope):
|
||||
super().__init__()
|
||||
self.app, self.scope = app, scope
|
||||
self.setAccessibleName(f"{NAME} tray menu")
|
||||
self.add_header()
|
||||
self.addSeparator()
|
||||
open_monitor = self.action(self, "Open Resource Monitor", SP.SP_ComputerIcon,
|
||||
lambda: app.open_expanded(app.tray_machine(scope)))
|
||||
self.setDefaultAction(open_monitor)
|
||||
self.pin = self.action(self, "Pin Resource Monitor", None, lambda: app.toggle_pin(scope))
|
||||
self.pin.setCheckable(True)
|
||||
|
||||
self.addSeparator()
|
||||
machines = self.submenu("Monitor Machine", SP.SP_ComputerIcon)
|
||||
self.machine_group = QActionGroup(self)
|
||||
self.machine_group.setExclusive(True)
|
||||
self.local = self.machine_action(machines, "Local Machine", LOCAL)
|
||||
self.remote = machines.addMenu(self.standard_icon(SP.SP_DriveNetIcon), "Configured Remote Machines")
|
||||
self.all = self.machine_action(machines, "All Systems", ALL)
|
||||
self.remote_entries = {}
|
||||
self.targets = None
|
||||
|
||||
display = self.submenu("Tray Display", SP.SP_FileDialogDetailedView)
|
||||
mode_group = QActionGroup(self)
|
||||
mode_group.setExclusive(True)
|
||||
self.modes = {}
|
||||
for mode in TRAY_MODES:
|
||||
action = self.action(display, mode, None, lambda mode=mode: app.set_tray_display(mode))
|
||||
action.setCheckable(True)
|
||||
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))
|
||||
|
||||
self.addSeparator()
|
||||
targets = self.submenu("Remote Targets", SP.SP_DriveNetIcon)
|
||||
self.action(targets, "Add Remote Target", SP.SP_FileDialogNewFolder, app.add_target)
|
||||
self.action(targets, "Manage Remote Targets", SP.SP_DriveNetIcon, app.manage)
|
||||
self.action(self, "Settings", SP.SP_FileDialogDetailedView, app.open_settings)
|
||||
self.start = self.action(self, "Start with Windows", None, app.toggle_startup)
|
||||
self.start.setCheckable(True)
|
||||
|
||||
self.addSeparator()
|
||||
self.action(self, f"About {NAME}", SP.SP_MessageBoxInformation, app.about)
|
||||
self.action(self, "Design Creations Website", SP.SP_DriveNetIcon, app.open_website)
|
||||
self.addSeparator()
|
||||
self.action(self, f"Exit {NAME}", None, app.qt.quit)
|
||||
self.aboutToShow.connect(self.refresh)
|
||||
|
||||
def add_header(self):
|
||||
wrapper = QWidget()
|
||||
wrapper.setObjectName("trayIdentity")
|
||||
header = QHBoxLayout(wrapper)
|
||||
header.setContentsMargins(10, 5, 10, 3)
|
||||
header.setSpacing(8)
|
||||
artwork = BrandImage(self.app.brand_icon.pixmap(QSize(24, 24), self.devicePixelRatioF()),
|
||||
f"{NAME} icon", (24, 24))
|
||||
header.addWidget(artwork)
|
||||
labels = QVBoxLayout()
|
||||
labels.setSpacing(0)
|
||||
title = QLabel(NAME)
|
||||
title.setFont(QFont("Georgia", 10, QFont.Weight.Bold))
|
||||
self.version = QLabel(VERSION)
|
||||
self.version.setObjectName("trayVersion")
|
||||
labels.addWidget(title)
|
||||
labels.addWidget(self.version)
|
||||
header.addLayout(labels)
|
||||
identity = QWidgetAction(self)
|
||||
identity.setDefaultWidget(wrapper)
|
||||
identity.setEnabled(False)
|
||||
self.addAction(identity)
|
||||
|
||||
def standard_icon(self, icon):
|
||||
return self.style().standardIcon(icon) if icon is not None else QIcon()
|
||||
|
||||
def action(self, menu, title, icon, callback):
|
||||
action = menu.addAction(self.standard_icon(icon), title)
|
||||
action.triggered.connect(lambda _checked=False: callback())
|
||||
return action
|
||||
|
||||
def submenu(self, title, icon):
|
||||
return self.addMenu(self.standard_icon(icon), title)
|
||||
|
||||
def machine_action(self, menu, name, machine):
|
||||
action = self.action(menu, name, None, lambda: self.app.select_machine(machine, self.scope))
|
||||
action.setCheckable(True)
|
||||
self.machine_group.addAction(action)
|
||||
return action
|
||||
|
||||
def refresh(self):
|
||||
app = self.app
|
||||
targets = [(t.identifier, t.name, app.dashboard.state(t.identifier).value) for t in app.settings.targets]
|
||||
if targets != self.targets:
|
||||
self.targets = targets
|
||||
self.remote.clear()
|
||||
self.remote_entries = {
|
||||
machine: self.machine_action(self.remote, f"{name.replace('&', '&&')} · {status}", machine)
|
||||
for machine, name, status in targets
|
||||
}
|
||||
self.remote.menuAction().setVisible(bool(targets))
|
||||
choices = {LOCAL: self.local, ALL: self.all, **self.remote_entries}
|
||||
choices[app.tray_machine(self.scope)].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())
|
||||
|
||||
def theme(self, colors):
|
||||
self.setStyleSheet(f"""
|
||||
QMenu {{
|
||||
background-color: {colors.background}; color: {colors.text};
|
||||
border: 1px solid {colors.border}; padding: 3px;
|
||||
}}
|
||||
QMenu::item {{ padding: 4px 25px 4px 27px; }}
|
||||
QMenu::item:selected {{ background: {colors.highlight}; color: {colors.text}; }}
|
||||
QMenu::separator {{
|
||||
height: 1px; background: {colors.border}; margin: 3px 6px;
|
||||
}}
|
||||
QWidget#trayIdentity {{ background-color: {colors.background}; }}
|
||||
QWidget#trayIdentity QLabel {{ color: {colors.text}; }}
|
||||
QLabel#trayVersion {{ color: {colors.muted}; }}
|
||||
""")
|
||||
2
arm/version.py
Normal file
2
arm/version.py
Normal file
@@ -0,0 +1,2 @@
|
||||
VERSION = "v0.2.0.0_alpha"
|
||||
NAME = "Adaptive Resource Monitor"
|
||||
338
arm/views.py
Normal file
338
arm/views.py
Normal file
@@ -0,0 +1,338 @@
|
||||
from time import time, strftime, localtime
|
||||
|
||||
from PySide6.QtCore import Qt, QSignalBlocker, QTimer
|
||||
from PySide6.QtWidgets import (
|
||||
QAbstractItemView, QComboBox, QFrame, QGridLayout, QHeaderView, QHBoxLayout, QLabel,
|
||||
QPushButton, QTableWidget, QTableWidgetItem, QTabWidget, QVBoxLayout, QWidget,
|
||||
)
|
||||
|
||||
from .graphs import Plot, metric_for
|
||||
from .model import ALL, LOCAL, TOTAL, Connection, INTERVALS, RANGES, RESOURCES, format_value
|
||||
|
||||
METRIC_NAMES = {
|
||||
"cpu.util": "CPU utilization", "cpu.frequency": "Frequency", "cpu.temperature": "CPU temperature",
|
||||
"cpu.power": "CPU power", "cpu.physical": "Physical cores", "cpu.logical": "Logical processors",
|
||||
"ram.util": "Physical RAM utilization", "ram.total": "Physical RAM capacity", "ram.used": "Physical RAM used",
|
||||
"ram.available": "Physical RAM available", "ram.committed": "Committed memory",
|
||||
"ram.commit_limit": "Commit limit", "ram.pagefile_used": "Pagefile / swap used",
|
||||
"ram.pagefile_total": "Pagefile / swap capacity", "gpu.util": "GPU utilization",
|
||||
"gpu.vram_pct": "Dedicated VRAM utilization", "gpu.vram_used": "Dedicated VRAM used",
|
||||
"gpu.vram_total": "Dedicated VRAM capacity", "gpu.vram_free": "Dedicated VRAM free",
|
||||
"gpu.shared_used": "Shared GPU memory used", "gpu.shared_total": "Shared GPU memory limit",
|
||||
"gpu.shared_pct": "Shared GPU memory utilization", "gpu.temperature": "GPU temperature",
|
||||
"gpu.clock": "GPU clock", "gpu.memory_clock": "Memory clock", "gpu.power": "GPU power",
|
||||
"gpu.power_limit": "Power limit", "gpu.fan": "Fan speed", "gpu.encode": "Video encode",
|
||||
"gpu.decode": "Video decode", "gpu.compute": "Compute engine", "disk.active": "Disk active time",
|
||||
"disk.total": "Disk combined", "disk.read": "Disk read", "disk.write": "Disk write",
|
||||
"disk.read_ops": "Read operations", "disk.write_ops": "Write operations",
|
||||
"net.total": "Network combined", "net.receive": "Network receive", "net.transmit": "Network transmit",
|
||||
"net.up": "Link status", "net.link": "Negotiated link speed", "net.util": "Peak link utilization",
|
||||
}
|
||||
|
||||
|
||||
def fill(combo, values, selected=None):
|
||||
with QSignalBlocker(combo):
|
||||
combo.clear()
|
||||
for label, value in values:
|
||||
combo.addItem(label, value)
|
||||
index = combo.findData(selected)
|
||||
combo.setCurrentIndex(max(index, 0))
|
||||
|
||||
|
||||
def machine_choices(dashboard):
|
||||
return [(dashboard.name(machine), machine) for machine in dashboard.machines()] + [("All Systems", ALL)]
|
||||
|
||||
|
||||
def interval_choices():
|
||||
return [(f"{value:g} s", value) for value in INTERVALS]
|
||||
|
||||
|
||||
def set_label(label, value):
|
||||
if label.text() != value:
|
||||
label.setText(value)
|
||||
|
||||
|
||||
def heading(label):
|
||||
label.setStyleSheet("font-weight: 600")
|
||||
label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
return label
|
||||
|
||||
|
||||
def plain(label=None):
|
||||
label = label or QLabel()
|
||||
label.setTextFormat(Qt.TextFormat.PlainText)
|
||||
return label
|
||||
|
||||
|
||||
def display_value(item):
|
||||
if not item:
|
||||
return "Unavailable"
|
||||
if item.value is None:
|
||||
return item.availability.value.capitalize()
|
||||
description = format_value(item.value, item.unit)
|
||||
return description if item.valid else f"{description} · {item.availability}"
|
||||
|
||||
|
||||
class Card(QFrame):
|
||||
def __init__(self, resource, detailed):
|
||||
super().__init__()
|
||||
self.title = heading(QLabel(RESOURCES[resource][0]))
|
||||
self.value = plain()
|
||||
self.plot = Plot()
|
||||
self.footer = plain()
|
||||
self.footer.setWordWrap(True)
|
||||
layout = QVBoxLayout(self)
|
||||
layout.setContentsMargins(6, 3, 6, 4)
|
||||
layout.setSpacing(3)
|
||||
row = QHBoxLayout()
|
||||
row.addWidget(self.title, 0)
|
||||
row.addStretch()
|
||||
row.addWidget(self.value)
|
||||
layout.addLayout(row)
|
||||
layout.addWidget(self.plot, 1)
|
||||
layout.addWidget(self.footer)
|
||||
self.footer.setVisible(detailed)
|
||||
|
||||
|
||||
class Monitor(QWidget):
|
||||
def __init__(self, dashboard, expanded, request_archive, switch_expanded, set_pin, about_page=None):
|
||||
flags = Qt.WindowType.Window if expanded else (
|
||||
Qt.WindowType.Tool | Qt.WindowType.FramelessWindowHint | Qt.WindowType.WindowStaysOnTopHint)
|
||||
super().__init__(None, flags)
|
||||
self.dashboard, self.expanded = dashboard, expanded
|
||||
self.request_archive = request_archive
|
||||
self.setWindowTitle("Adaptive Resource Monitor" if expanded else "ARM Monitor")
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_DeleteOnClose, False)
|
||||
if not expanded:
|
||||
self.setAttribute(Qt.WidgetAttribute.WA_ShowWithoutActivating, True)
|
||||
self.setObjectName("hoverMonitor")
|
||||
self.pinned = False
|
||||
self.machine = QComboBox()
|
||||
self.machine.setAccessibleName("Machine")
|
||||
self.interval = QComboBox()
|
||||
self.interval.setAccessibleName("History range")
|
||||
self.device = QComboBox()
|
||||
self.device.setAccessibleName("Hardware device")
|
||||
self.header = plain()
|
||||
self.header.setWordWrap(True)
|
||||
top = QHBoxLayout()
|
||||
for control in (self.machine, self.interval):
|
||||
top.addWidget(control)
|
||||
if expanded:
|
||||
top.addWidget(self.device, 1)
|
||||
else:
|
||||
pin = QPushButton("Pin")
|
||||
pin.setCheckable(True)
|
||||
pin.toggled.connect(set_pin)
|
||||
self.pin = pin
|
||||
details = QPushButton("Details")
|
||||
details.clicked.connect(lambda: switch_expanded(self.machine.currentData()))
|
||||
top.addWidget(pin)
|
||||
top.addWidget(details)
|
||||
self.cards = {kind: Card(kind, expanded) for kind in RESOURCES}
|
||||
self.grid = QGridLayout()
|
||||
self.grid.setSpacing(5)
|
||||
if expanded:
|
||||
self.tabs = QTabWidget()
|
||||
self.tabs.setObjectName("armMainTabs")
|
||||
self.resource_page = QWidget()
|
||||
self.about_page = about_page
|
||||
self.tabs.addTab(self.resource_page, "Resource Monitor")
|
||||
self.tabs.addTab(self.about_page, "About")
|
||||
frame = QVBoxLayout(self)
|
||||
frame.setContentsMargins(4, 4, 4, 4)
|
||||
frame.addWidget(self.tabs)
|
||||
layout = QVBoxLayout(self.resource_page if expanded else self)
|
||||
layout.setContentsMargins(8, 7, 8, 7)
|
||||
layout.setSpacing(4)
|
||||
layout.addLayout(top)
|
||||
layout.addWidget(self.header)
|
||||
layout.addLayout(self.grid, 3)
|
||||
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.resize(900, 690)
|
||||
self.machine.currentIndexChanged.connect(self.sync_devices)
|
||||
self.device.currentIndexChanged.connect(self.selection_changed)
|
||||
self.machine.currentIndexChanged.connect(self.selection_changed)
|
||||
self.interval.currentIndexChanged.connect(self.selection_changed)
|
||||
self.archive_due = QTimer(self)
|
||||
self.archive_due.setSingleShot(True)
|
||||
self.archive_due.setInterval(350)
|
||||
self.archive_due.timeout.connect(self.archive)
|
||||
if expanded:
|
||||
self.tabs.currentChanged.connect(self.selection_changed)
|
||||
self.setStyleSheet("QWidget#hoverMonitor { border: 1px solid palette(mid); }")
|
||||
self.sync()
|
||||
|
||||
@property
|
||||
def monitor_visible(self):
|
||||
return self.isVisible() and (not self.expanded or self.tabs.currentWidget() is self.resource_page)
|
||||
|
||||
def show_page(self, about=False):
|
||||
self.tabs.setCurrentWidget(self.about_page if about else self.resource_page)
|
||||
self.show()
|
||||
self.raise_()
|
||||
self.activateWindow()
|
||||
|
||||
def brand_tabs(self, colors):
|
||||
self.tabs.setStyleSheet(f"""
|
||||
QTabWidget#armMainTabs::pane {{ border: 1px solid {colors.border}; }}
|
||||
QTabWidget#armMainTabs QTabBar::tab {{
|
||||
padding: 5px 12px; background: {colors.panel}; color: {colors.text};
|
||||
border: 1px solid {colors.border}; border-top-left-radius: 4px;
|
||||
border-top-right-radius: 4px;
|
||||
}}
|
||||
QTabWidget#armMainTabs QTabBar::tab:selected {{
|
||||
color: {colors.accent}; background: {colors.highlight};
|
||||
}}
|
||||
""")
|
||||
|
||||
@property
|
||||
def selected_machine(self):
|
||||
return self.machine.currentData() or LOCAL
|
||||
|
||||
@property
|
||||
def selection(self):
|
||||
return self.device.currentData() or ("", TOTAL)
|
||||
|
||||
@property
|
||||
def span(self):
|
||||
return self.interval.currentData() or 60
|
||||
|
||||
def sync_devices(self):
|
||||
if not self.expanded:
|
||||
return
|
||||
machine = self.selected_machine
|
||||
devices = self.dashboard.collectors.devices.get(machine, {})
|
||||
kinds = {"cpu": "CPU", "gpu": "GPU", "disk": "Disk", "net": "Network"}
|
||||
values = [("Selected devices · aggregate", ("", TOTAL))] + [
|
||||
(f"{kinds[device.kind]} · {device.name}", (device.kind, device.identifier))
|
||||
for device in devices.values() if device.kind in kinds
|
||||
]
|
||||
if self.device.count() != len(values) or any(
|
||||
self.device.itemData(i) != data for i, (_, data) in enumerate(values)):
|
||||
fill(self.device, values, self.device.currentData())
|
||||
|
||||
def sync(self):
|
||||
settings = self.dashboard.settings
|
||||
fill(self.machine, machine_choices(self.dashboard), self.machine.currentData() 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)))
|
||||
self.sync_devices()
|
||||
columns = 2 if self.expanded else settings.popup_columns
|
||||
kinds = tuple(self.cards) if self.expanded else tuple(
|
||||
kind for kind in self.cards if kind in settings.hover_resources)
|
||||
for resource, card in self.cards.items():
|
||||
self.grid.removeWidget(card)
|
||||
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)
|
||||
|
||||
def set_machine(self, machine):
|
||||
index = self.machine.findData(machine)
|
||||
if index >= 0:
|
||||
self.machine.setCurrentIndex(index)
|
||||
self.refresh()
|
||||
|
||||
def selection_changed(self):
|
||||
if self.monitor_visible:
|
||||
self.refresh()
|
||||
self.archive_due.start()
|
||||
|
||||
def archive(self):
|
||||
if self.expanded and self.monitor_visible:
|
||||
self.request_archive(self.selected_machine, self.span, self.selection)
|
||||
|
||||
def refresh(self):
|
||||
self.sync_devices()
|
||||
now, span, scope = time(), self.span, self.selected_machine
|
||||
collectors = self.dashboard.collectors
|
||||
cfg = self.dashboard.settings
|
||||
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}"
|
||||
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%")
|
||||
if self.expanded:
|
||||
self.refresh_table(scope, selected, now, span, archive)
|
||||
|
||||
def refresh_table(self, scope, 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))
|
||||
for row, columns in enumerate(data):
|
||||
for column, value in enumerate(columns):
|
||||
item = self.table.item(row, column)
|
||||
if item is None:
|
||||
self.table.setItem(row, column, QTableWidgetItem(value))
|
||||
elif item.text() != value:
|
||||
item.setText(value)
|
||||
Reference in New Issue
Block a user