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:
2026-11-26 06:20:05 -06:00
parent 2efae3fcd8
commit 7628161f07
49 changed files with 5926 additions and 0 deletions

7
.gitignore vendored Normal file
View File

@@ -0,0 +1,7 @@
__pycache__/
*.py[cod]
.venv/
build/
dist/
release/
*.spec

11
ARCHITECTURE.md Normal file
View File

@@ -0,0 +1,11 @@
# Adaptive Resource Monitor architecture
The Windows application runs one Qt event loop. A timer refreshes the tray icon and visible views from a GUI-owned model. One supervised worker per local provider or remote machine owns its sampling schedule, baseline counters and connection. Workers publish immutable, timestamped results through queued signals. A separate worker owns SQLite, including retention, reads and writes. Providers and storage never run on the GUI thread.
The common model uses machine, device and metric identifiers, physical units, an observation timestamp, availability and a safe diagnostic. Counter deltas use monotonic elapsed time. The first observation, counter resets and delayed observations form gaps. History buffers are bounded and charts use observation timestamps. Machine or category aggregation skips unavailable values and uses maxima of normalized readings where appropriate. VRAM capacity is a sum over measured devices.
Windows collectors use psutil for CPU, memory and interfaces, native performance data for physical disks and WDDM GPU engines, DXGI for adapter identification, and NVML for NVIDIA hardware sensors. WDDM is the native shared path for AMD and Intel. Each collector can report a partial hardware capability. Linux SSH collection uses a self-contained read-only script over a persistent SSH channel. Windows Credential Manager holds saved authentication material and an application-owned known-host store holds accepted SSH keys. A new key requires explicit approval. Remote Windows uses the same provider interface when a verified implementation is available.
Qt paints the tray icon and reports click/menu activation. Windows notification-area geometry and the actual cursor drive hover detection. The branded icon covers initialization and the optional Application Icon display. The expanded window combines the resource monitor and About tab. About and the Windows packages draw on the shared asset and identity definitions in arm/branding.py. All operations against monitored machines are telemetry reads.
Configuration and logs live in per-user application data. The portable ZIP and installer share the frozen x64 application and the Python version source. The release check records automated results, native workstation results, unverified behavior and SHA-256 digests.

BIN
ARM_Application.ico Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 170 KiB

BIN
ARM_Application_Icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 183 KiB

BIN
ARM_Application_Image.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 1.4 MiB

BIN
ARM_Compact_Icon.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 52 KiB

BIN
ARM_Emblem.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 271 KiB

31
BUILD.md Normal file
View File

@@ -0,0 +1,31 @@
# Windows x64 build
Use native x64 Python 3.12 and Inno Setup 7. From the repository in PowerShell:
~~~powershell
py -3.12 -m venv .venv
.\.venv\Scripts\python.exe -m pip install -r requirements-build.txt
.\.venv\Scripts\python.exe -m unittest discover -s tests -v
.\.venv\Scripts\python.exe tests\windows_gui.py
.\.venv\Scripts\python.exe tools\build_windows.py --iscc 'C:\Program Files\Inno Setup 7\ISCC.exe'
.\.venv\Scripts\python.exe tests\windows_gui.py --package .\release
Get-FileHash .\release\*.zip, .\release\*.exe -Algorithm SHA256
~~~
The build script uses a disposable staging directory. It generates the product
version resource and invokes PyInstaller and Inno Setup. The final ZIP, installer
and SHA-256 manifest are written to release. Remove a one-off virtual environment
after validation when it is no longer needed.
The executable, installer, shortcuts, window and fallback tray icon share
the supplied ARM_Application.ico. Both distributions carry the app image,
emblem, Design Creations logo, change log, third-party notices and build
identity used by the About tab.
The installer is per user and permits choosing the install directory. Desktop
shortcut and autostart are optional. The Start Menu shortcut is installed.
Settings and history stay under the user's local app data across upgrades and
uninstall. Extract the portable ZIP before running AdaptiveResourceMonitor.exe.
Both packages contain their Python and Qt runtime.
The alpha artifacts are unsigned. An Authenticode signing and distribution
workflow requires the publisher's certificate and publication authorization.

15
CHANGELOG.md Normal file
View File

@@ -0,0 +1,15 @@
# Changelog
## v0.2.0.0_alpha — 2026-11-26
- Added the Design Creations About tab with application and build details, version history, project links and third-party notices.
- Organized the tray menu around monitoring targets, visualization modes and application controls. The live history display remains the default, with a selectable branded icon.
- Applied the supplied ARM artwork to the Windows application, installer wizard, shortcuts and installed application metadata.
## v0.1.0.0_alpha
- Added the native Windows tray monitor, GPU-aware local telemetry, hover
panel, expanded monitor, device selection, settings and resource history.
- Added independent Linux SSH targets with Windows Credential Manager,
host key approval and reconnection.
- Added Windows x64 installer and portable build support and Windows validation.

158
IMPLEMENTATION_REPORT.md Normal file
View File

@@ -0,0 +1,158 @@
# Adaptive Resource Monitor implementation report
## v0.2.0.0_alpha — Design Creations branding
The Feature counter advanced from 1 to 2 for the new About tab and selectable
tray display. The About tab and tray menu use the same authoritative version
source as the executable and installer.
The About design follows the inspected Ink & Iron Workshop About screen and
installed UI components, including the application and company graphics
flanking a centered serif title, compact information group, View Details
control and inline changelog. Patch Studio and Adaptive Maintenance source
provided additional read-only references for document navigation, attribution
and Windows application identity. Adaptive File Transfer corroborated the
attribution. The Workshop source checkout was unavailable locally. The
inspected Workshop UI and peer references did not expose a tray menu to mirror,
so ARM applies their palette and menu spacing to the requested commands.
ARM uses the supplied 1040 × 1069 application image, transparent emblem,
Design Creations logo and nine-size ICO as its canonical runtime assets.
The original compact icon variants remain source artwork. The Windows
executable, installer and shortcut definitions share the branded icon and
application identity. About includes the bundled Project Guide and a verified
public contact link. The configured Git origin's web view returned HTTP 404
to an anonymous request. ARM has no declared software license or update
channel. Dependency notices remain available. [Design Creations](https://www.designcreations.us/) · [Contact & Support](https://www.designcreations.us/contact/index.php)
### Branding validation
All 13 automated tests passed. Native Qt runs on a private Windows desktop
passed at 100% and 150% scale. They checked the About tab, its document and
details controls, website and support URL routing, tray menu navigation,
monitor pinning, local and remote target selection, and all four tray
displays. The runs observed live local telemetry and loopback SSH telemetry.
The normal graph replaced the branded startup fallback when data arrived.
All nine ICO frames had transparent and opaque pixels, with effectively
transparent corners. The visible artwork and installer wizard were reviewed
from private-desktop captures.
Both x64 packages passed their SHA-256 checks. The embedded icon groups
contained all nine sizes. The portable app and installed app opened with
the branded native window icon and shut down cleanly. A disposable
v0.1.0.0_alpha installation was upgraded to v0.2.0.0_alpha, reinstalled
and uninstalled. The checks verified the company name, support and website
entries in the installed application registry and preserved sample
settings, a machine profile with its credential reference, and history.
Shortcut definitions share the executable icon and AppUserModelID.
Visual verification in the active Explorer notification area, taskbar,
Task Manager and desktop shortcut was outside the isolated test.
| Final release file | Bytes | SHA-256 |
| --- | ---: | --- |
| Windows x64 installer | 44,498,649 | `804f6c3d594a71a01d7b44137758095e42f65f5ec2e062695db48a2f1e2b59e2` |
| Windows x64 portable ZIP | 58,353,462 | `3e441381516a223516b778a306ee1e881deed4b9b343197d04d769b7364a76ea` |
Cleanup removed the temporary installer and dependency staging, four build
staging directories, disposable Windows installs, temporary profiles and
SSH fixtures, private-desktop captures and superseded packages. Measured
file sizes reclaimed totaled 1,979,949,758 bytes (1.84 GiB), excluding
short-lived unit-test scratch files. The project retains the current
installer, portable ZIP and checksum manifest as release deliverables,
along with the source, supplied artwork, documentation and maintained tests.
## v0.1.0.0_alpha — Initial implementation
## Implementation matrix
| Requirement | Implementation | Automated evidence | Native or live evidence and limits |
| --- | --- | --- | --- |
| Dynamic Windows tray and Overlay, Stacked, Composite | Implemented using QSystemTrayIcon and QPainter | Resource normalization and peak aggregation tests | Native Qt builds distinct icon images for all three modes. Explorer registration and recovery need a live taskbar. |
| Custom popup, sizing, dismissal and pinning | Implemented with Windows cursor position and Qt's native notification-area rectangle | Hover state, dismissal, placement and negative-coordinate tests | Popup, six graphs and pinning exercised on a private desktop. Actual pointer movement over an Explorer icon, desktop sleep/resume, and physical mixed-DPI taskbars remain open. |
| Expanded monitor, ranges and multiple machines | Implemented with resource charts, per-device detail, current and history statistics, connection state and timestamps | History and machine-peak tests | Expanded window, live values and device selection exercised. Archived statistics use retained plot observations for long selections. |
| Windows CPU and memory | Implemented using timed CPU deltas, physical and logical topology, memory, commit and pagefile | First-sample and native provider tests | Verified workstation telemetry. Windows CPU temperature and power are unsupported in this alpha. |
| AMD, Intel, NVIDIA and dedicated VRAM | Implemented with DXGI PCI identity, native WDDM engine and memory counters and NVIDIA NVML sensors | Engine aggregation, valid zero, matched capacity and sampled provider tests | AMD Radeon 780M and NVIDIA RTX 5050 Laptop GPU detected with native readings. No Intel GPU was available. AMD and Intel use WDDM counters on Windows and expose only the features supplied by those counters. Vendor clock, thermal, fan and power readings for these two vendors on Windows are deferred. |
| Storage and network | Implemented with whole physical disk counters, mode selection, directional network data and default physical-adapter inclusion | Counter reset and network-selection fixtures | Two physical drives and active network throughput verified. No live 10 GbE, VPN or storage pool validation. |
| SSH Linux and connection management | Implemented with one persistent channel per target, password and key authentication, host verification, reconnect and status | Loopback password and encrypted private-key tests, unknown and changed keys, reconnect after loss, and Linux counter fixtures | Windows loopback sessions exercised. Live Linux validation on Linux target A and Linux target B requires authorized connection details. Their hosts and credentials were neither inferred nor accessed. |
| Credentials and settings | Implemented with Windows Credential Manager references and atomic per-user settings | Credential round trip, namespace validation and settings persistence | Settings and target operations exercised on the isolated Windows desktop. |
| Independent collection and optional history | Implemented with collector and SQLite workers, in-memory rings, gap detection, batching, retention and clear | Worker stop, ring, SQLite flush/read/clear tests | Tested locally and with the loopback targets. Maximum database size is enforced periodically. SQLite working files can temporarily exceed the target. |
| Startup and shutdown | Implemented with a per-user startup toggle, clean exit and independent monitor window | Worker shutdown and SQLite drain tests | Native startup and shutdown exercised. Windows sign-in autostart remains a live acceptance check. |
| Windows x64 distribution | Implemented with a PyInstaller payload, Inno Setup installer and portable ZIP | Build verifies archive integrity and artifact hashes | See package validation below. Windows 10 and ARM64 were outside workstation validation. |
| Remote Windows and optional agent | Provider interface and profile status implemented. Transport and agent deferred. | Unsupported status surfaced by the UI | No remote Windows telemetry claim or deployment. |
## Workstation evidence
Native validation uses a private Windows desktop without switching the author’s
desktop or sending it input. The workstation is Windows 11 x64 build 26300.
The application registered Qt tray objects. The private desktop has no Explorer
notification area and returned no icon rectangle. Qt’s Windows backend calls
Shell_NotifyIconGetRect and handles the shell's TaskbarCreated message. These
source paths do not constitute a live shell-restart result. [Qt Windows tray backend](https://github.com/qt/qtbase/blob/v6.11.2/src/plugins/platforms/windows/qwindowssystemtrayicon.cpp)
The automated suite passed 13 tests on November 26, 2026. A Windows Bash
protocol check produced two delimited responses from one process. Live
procfs, sysfs and hardware validation is represented separately in the matrix.
The native Windows GUI suite passed at 100% scale and its smoke run passed at
150% scale. The full run produced distinct Overlay, Stacked and Composite
icon images and exercised separate and consolidated tray objects, popup
pinning, expanded graphs, settings and target management. The two concurrent
SSH fixtures delivered 13 and 7 readings. The AMD Radeon 780M and NVIDIA
GeForce RTX 5050 Laptop GPU both supplied dedicated memory readings. The
full run also observed AMD engine activity and NVIDIA temperature and power.
## Resource consumption
Measurements use process CPU time and resident memory in the native private
desktop. Total-machine CPU is normalized by 16 logical processors. Loopback
targets use an authenticated test server on the same workstation and supply
fixture frames. These results cover the application and same-process loopback
fixture threads in the remote scenarios.
| Scenario | CPU, entire workstation | CPU, one logical processor | Working set |
| --- | ---: | ---: | ---: |
| Local tray only | 0.106% | 1.693% | 138.53 MiB |
| Pinned popup | 0.220% | 3.516% | 140.16 MiB |
| Expanded window | 0.342% | 5.469% | 143.12 MiB |
| One SSH loopback target | 0.155% | 2.474% | 146.64 MiB |
| Two SSH loopback targets | 0.146% | 2.344% | 147.08 MiB |
| Two manually disconnected targets | 0.098% | 1.562% | 148.02 MiB |
Each row is a 12-second observation. Local tray-only collection ran at one
second and measured below 1% of total workstation CPU capacity. Explorer's
work and long-duration memory growth require separate measurement.
## Distribution and cleanup
The original release contained the x64 installer, the portable ZIP and their
SHA-256 manifest. The alpha artifacts were unsigned. Signing, live Explorer
validation, real remote Linux validation and extended-duration performance
characterization are outstanding production acceptance items.
PyInstaller 6.22.3 froze the application with its Python and Qt runtime.
Inno Setup 7.1.1 compiled the installer. Both PE headers identify x64.
The portable archive passed its CRC check and contains the Qt Windows plugin
and Linux telemetry program. The supplied ARM icon is in the application
and installer resources.
The final portable and installed builds each opened twice on an isolated
Windows desktop. Closing the monitor window left the tray process running.
Both processes exited cleanly when their private message loops were told to
quit. A silent installation, same-version reinstall and uninstall each
returned code 0. Their temporary profile, settings and history test files
were preserved through reinstall and uninstall. Launching on a
Python-free Windows system and a version-to-version upgrade remain untested.
| Final release file | Bytes | SHA-256 |
| --- | ---: | --- |
| Windows x64 installer | 40,558,009 | `b6d0a56975311b8c26eb1a67542dbb88cb6f566232bdef5bbbd669b8a9e8c239` |
| Windows x64 portable ZIP | 56,159,793 | `6b39ccac9db4f4dfb46f8904723967724b0405b986db6d508d9b6fc2249da41f` |
Cleanup removed the disposable installation and uninstall registration,
portable extractions, private-desktop test profiles and logs, SQLite fixtures,
SSH fixtures and test credentials, compiler and dependency staging, failed
and successful build intermediates, and superseded packages. Measured file
sizes reclaimed total 1,142,127,048 bytes (1.06 GiB). This excludes short-lived
unit-test fixtures and the automatically deleted build attempt whose size
was unmeasured. That milestone retained the verified installer, portable
ZIP and SHA-256 manifest until the branding release superseded them.

View File

@@ -1,2 +1,26 @@
# Adaptive_Resource_Monitor
Adaptive Resource Monitor is a native Windows tray utility for CPU, GPU,
RAM, VRAM, storage and network history. It combines the six resources into
one dynamic icon by default. Click the icon to pin the monitor or open the
expanded window from its context menu. Windows may initially place the icon
in the taskbar overflow. Move it into the visible notification area for
continuous access.
Use Settings to switch between Overlay, Stacked and Composite, choose devices,
set sampling and graph options, or enable SQLite history. Use Manage Remote Targets
to add a Linux machine. A confirmed SSH key and working authentication are
required. The default configuration monitors only the local machine and keeps
history in memory.
The tray menu also offers an Application Icon display. The branded fallback
appears while monitoring initializes. Monitor Machine selects the history
shown by that tray icon and its popup. Open the About tab from the monitor
window or tray menu for build information, version history and support links.
The application version is defined in [arm/version.py](arm/version.py).
See [BUILD.md](BUILD.md) for Windows build and verification commands,
[TELEMETRY_PROVIDERS.md](TELEMETRY_PROVIDERS.md) for metric definitions,
[REMOTE_MONITORING.md](REMOTE_MONITORING.md) for SSH setup, and
[IMPLEMENTATION_REPORT.md](IMPLEMENTATION_REPORT.md) for verification status.

26
REMOTE_MONITORING.md Normal file
View File

@@ -0,0 +1,26 @@
# Remote monitoring
In Manage Remote Targets, add a Linux target with its real hostname, port and
username. Choose Password or Private key and enter a password or key
passphrase when required. New targets start disabled. Use Test connection to
request the key and run a single telemetry sample. Compare the SHA-256
fingerprint to one obtained directly from the system or its administrator,
then use Approve SSH host key and enable the target.
Each target owns its own SSH connection, sampling interval, timeout and retry
schedule. Transient failures retry with exponential backoff when enabled.
Authentication failures, new keys and changed keys require user action.
The monitor labels the last valid sample stale when its provider goes offline.
Linux requires Bash, procfs and readable sysfs. NVIDIA telemetry additionally
uses an installed nvidia-smi and timeout when available. AMD and Intel use
available sysfs attributes. Root access and package installation are unnecessary.
Windows targets can be stored as profiles. Their provider reports Unsupported
in this alpha. Microsoft's remote performance counter APIs depend on RPC or
Remote Registry in some cases. CIM over WinRM has an authenticated transport
and can expose Windows performance classes with appropriate per-host rights.
A later optional agent should expose a small versioned telemetry schema
over mutually authenticated TLS and restrict requests to metrics and sampling
configuration. These routes have no deployed implementation in this version.
See [remote performance counter access](https://learn.microsoft.com/en-gb/windows/win32/perfctrs/accessing-remote-counter-data)
and [WinRM authentication](https://learn.microsoft.com/en-us/windows/win32/winrm/authentication-for-remote-connections).

7
REQUIREMENTS.md Normal file
View File

@@ -0,0 +1,7 @@
# Initial Windows alpha requirements
The initial version is `v0.1.0.0_alpha`. The local application is a Windows 10/11 x64 system tray utility with live CPU, GPU, RAM, VRAM, disk and network history. The default icon overlays all six resources. Stacked and peak composite views, configurable sampling, a native hover monitor, expanded and per-device views, and optional retained history are part of the milestone.
Remote targets have independent state and schedules. Linux uses password or key SSH authentication, explicit host-key trust, Windows Credential Manager and read-only telemetry. Configured targets can be monitored individually or consolidated. Remote Windows design is documented separately from verified support.
Deliver a frozen portable ZIP, a native installer, checksums, automated tests and native Windows validation. See [implementation report](IMPLEMENTATION_REPORT.md) for the requirement matrix, evidence and acceptance limits.

20
SECURITY.md Normal file
View File

@@ -0,0 +1,20 @@
# Security
ARM collects read-only telemetry. It never accepts a command from a profile.
The Linux provider starts a fixed Bash program over SSH and sends a single
sampling token for each observation. It asks for neither a PTY nor privilege
elevation. The application does not listen on a network port.
Linux passwords and optional private-key passphrases are generic Windows
Credential Manager entries in ARM's own namespace. Profiles contain the
credential reference and optional path to a private key. Replace or remove a
stored secret from the profile editor. Rotate a changed SSH host key by verifying
the replacement with the host administrator, forgetting the old key and
approving the verified fingerprint. Unknown keys stop at an approval prompt.
A changed key is rejected. Key approval is local to ARM.
Settings, known hosts, logs and optional history belong to the current Windows
user under %LOCALAPPDATA%\Adaptive Resource Monitor. History and device names
can reveal information about the monitored environment. The portable package
also uses this user directory. Uninstall preserves the user data. No remote
host is contacted until a target is enabled or tested.

48
TELEMETRY_PROVIDERS.md Normal file
View File

@@ -0,0 +1,48 @@
# Telemetry providers
| Resource | Windows | Linux over SSH |
| --- | --- | --- |
| CPU | psutil CPU time deltas, processor topology, registry identity and reported frequency | procfs CPU time deltas and processor information, selected hwmon sensors |
| RAM | psutil physical memory, Windows commit and installed pagefile counters | procfs MemAvailable, swap and commit fields |
| GPU | DXGI inventory, WDDM performance counters, NVIDIA NVML when available | DRM sysfs, vendor sysfs fields and optional NVIDIA SMI |
| VRAM | Dedicated allocation and shared usage via WDDM, dedicated memory via NVML when available | Vendor-exposed dedicated memory totals and usage |
| Disk | PhysicalDrive counters and physical-disk idle time | Whole-device diskstats for sysfs devices with a backing device |
| Network | Per-interface counters, operational state and directional link speeds | Per-interface procfs counters, sysfs state and negotiated speed |
Physical RAM used is total minus available, including reclaimable memory
according to each OS. Commit and pagefile or swap describe separate accounting.
Per-processor CPU utilization uses elapsed time deltas. Linux guest fields
already counted by user and nice are excluded from the denominator addition.
A failed counter, a first delta, a reset and an extended sleep produce gaps.
WDDM sums processes using the same engine and takes the busiest engine per GPU.
NVML utilization takes precedence when provided. Windows matches NVML to the
DXGI adapter by PCI address where available, or a unique device ID. Aggregate
GPU percentage is the maximum of included GPUs. Aggregate VRAM uses actual
dedicated capacity and usage pairs across GPUs. The total is capacity spread
over separate devices. Shared memory is shown per GPU to avoid summing a
shared system-memory budget. CPU temperature and power on Windows and
AMD or Intel clock, thermal, power and fan data are driver-dependent gaps
in this alpha. WDDM explicitly named encode, decode and compute engines are
shown when present. Unobserved engine types show Unavailable.
Disk totals cover included whole physical disks. Active time uses the busiest
included disk. Network defaults to physical adapters and excludes loopback,
VPN and virtual bridge layers from the aggregate by default. All recognized
interfaces remain available for manual selection. If layers overlap, select
one layer from each network path. Link utilization is the greater directional
rate compared with that direction's negotiated speed. Throughput is shown
in bytes per second. Fixed scales are display references. Automatically
scaled I/O is normalized against the next power-of-two scale in the plot range.
Composite mode and the consolidated tray surface the largest normalized
observation. The consolidated monitor names the machine contributing the
current maximum and skips unavailable or stale current readings. Amber marks
a connection that needs attention. A disconnected machine retains its last
valid values with a stale label.
The provider interfaces are documented in
[DXGI adapter description](https://learn.microsoft.com/en-us/windows/win32/api/dxgi/ns-dxgi-dxgi_adapter_desc1),
[GPU engine accounting](https://devblogs.microsoft.com/directx/gpus-in-the-task-manager/),
[NVIDIA NVML](https://developer.nvidia.com/management-library-nvml),
and [Windows commit counters](https://learn.microsoft.com/en-us/windows/win32/api/psapi/nf-psapi-getperformanceinfo).

12
VERSIONING.md Normal file
View File

@@ -0,0 +1,12 @@
# Versioning
Use vMAJOR.FEATURE.MINOR.BUGFIX_TAG. The four counters are independent and
cumulative. Increment the appropriate counter and retain the other values.
The initial milestone uses the alpha tag. Version updates happen once
per milestone.
Edit arm/version.py to update the authoritative version. The application,
About tab, executable text resource, installer version, portable VERSION.txt,
and artifact filenames derive from it. The Windows binary version resource
uses the four numeric fields because the PE numeric version cannot contain
a prefix or tag. The Windows product and file version strings retain both.

1
arm/__init__.py Normal file
View File

@@ -0,0 +1 @@
"""Adaptive Resource Monitor."""

232
arm/about.py Normal file
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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
View 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()

View 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
View 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
View 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
View 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
View 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
View 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
View File

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

338
arm/views.py Normal file
View 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)

BIN
dc-design-creations.png Normal file

Binary file not shown.

After

Width:  |  Height:  |  Size: 211 KiB

5
monitor.pyw Normal file
View File

@@ -0,0 +1,5 @@
from arm.application import main
if __name__ == "__main__":
raise SystemExit(main())

14
packaging/THIRD_PARTY.md Normal file
View File

@@ -0,0 +1,14 @@
# Third-party runtime components
The Windows package includes CPython, Qt 6 and its PySide6 Python bindings,
psutil, Paramiko and its cryptographic dependencies, NVIDIA's NVML Python
bindings, and the PyInstaller bootloader. The NVIDIA display driver's NVML DLL
is provided by the driver. License text distributed by the dependency wheels
is included in this directory.
Qt is dynamically linked. The Qt DLLs and PySide bindings are separately
replaceable under the applicable Qt licenses. The exact tested versions and
rebuild instructions are in the ARM source repository. Qt source is available
from the [Qt source archive](https://download.qt.io/archive/qt/) and PySide
source from the [Qt for Python source archive](https://download.qt.io/official_releases/QtForPython/).
Python source is available from [python.org](https://www.python.org/downloads/source/).

67
packaging/setup.iss Normal file
View File

@@ -0,0 +1,67 @@
#define RunKey "Software\Microsoft\Windows\CurrentVersion\Run"
[Setup]
AppId={#SetupId}
AppName={#Product}
AppVersion={#AppVersion}
AppVerName={#Product} {#AppVersion}
AppPublisher={#ArmPublisher}
AppPublisherURL={#AppWebsite}
AppSupportURL={#AppSupport}
AppCopyright={#ArmCopyright}
AppComments={#AppDescription}
DefaultDirName={localappdata}\Programs\Adaptive Resource Monitor
DefaultGroupName={#Product}
DisableProgramGroupPage=auto
AllowNoIcons=yes
DisableDirPage=no
PrivilegesRequired=lowest
ArchitecturesAllowed=x64os
ArchitecturesInstallIn64BitMode=x64os
SetupArchitecture=x64
MinVersion=10.0.17763
OutputBaseFilename=AdaptiveResourceMonitor-{#AppVersion}-windows-x64-setup
VersionInfoVersion={#FileVersion}
VersionInfoTextVersion={#AppVersion}
VersionInfoProductName={#Product}
VersionInfoProductTextVersion={#AppVersion}
VersionInfoCompany={#ArmPublisher}
VersionInfoCopyright={#ArmCopyright}
Compression=lzma2
SolidCompression=yes
WizardStyle=modern
SetupIconFile={#AppIcon}
WizardImageFile={#WizardImage}
WizardSmallImageFile={#WizardEmblem}
UninstallDisplayIcon={app}\{#Executable}
[Tasks]
Name: "desktopicon"; Description: "Create a desktop shortcut"; Flags: unchecked
Name: "startup"; Description: "Start Adaptive Resource Monitor with Windows"; Flags: unchecked
[Files]
Source: "{#Payload}\*"; DestDir: "{app}"; Flags: ignoreversion recursesubdirs createallsubdirs
[Icons]
Name: "{group}\{#Product}"; Filename: "{app}\{#Executable}"; IconFilename: "{app}\{#Executable}"; AppUserModelID: "{#AppModelId}"
Name: "{userdesktop}\{#Product}"; Filename: "{app}\{#Executable}"; IconFilename: "{app}\{#Executable}"; AppUserModelID: "{#AppModelId}"; Tasks: desktopicon
[Registry]
Root: HKCU; Subkey: "{#RunKey}"; ValueType: string; ValueName: "AdaptiveResourceMonitor"; ValueData: """{app}\{#Executable}"""; Tasks: startup
[Run]
Filename: "{app}\{#Executable}"; Description: "Open Adaptive Resource Monitor"; Flags: nowait postinstall skipifsilent
[Code]
procedure CurUninstallStepChanged(Step: TUninstallStep);
var
Value, Target: String;
begin
if Step = usPostUninstall then
begin
Target := ExpandConstant('{app}\{#Executable}');
if RegQueryStringValue(HKCU, '{#RunKey}', 'AdaptiveResourceMonitor', Value) then
if (CompareText(Value, Target) = 0) or (CompareText(Value, '"' + Target + '"') = 0) then
RegDeleteValue(HKCU, '{#RunKey}', 'AdaptiveResourceMonitor');
end;
end;

View File

@@ -0,0 +1,16 @@
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<assembly xmlns="urn:schemas-microsoft-com:asm.v1" manifestVersion="1.0">
<trustInfo xmlns="urn:schemas-microsoft-com:asm.v3">
<security><requestedPrivileges><requestedExecutionLevel level="asInvoker" uiAccess="false"/></requestedPrivileges></security>
</trustInfo>
<compatibility xmlns="urn:schemas-microsoft-com:compatibility.v1">
<application><supportedOS Id="{8e0f7a12-bfb3-4fe8-b9a5-48fd50a15a9a}"/></application>
</compatibility>
<application xmlns="urn:schemas-microsoft-com:asm.v3">
<windowsSettings>
<dpiAware xmlns="http://schemas.microsoft.com/SMI/2005/WindowsSettings">true/pm</dpiAware>
<dpiAwareness xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">PerMonitorV2</dpiAwareness>
<longPathAware xmlns="http://schemas.microsoft.com/SMI/2016/WindowsSettings">true</longPathAware>
</windowsSettings>
</application>
</assembly>

2
requirements-build.txt Normal file
View File

@@ -0,0 +1,2 @@
-r requirements.txt
pyinstaller==6.22.3

4
requirements.txt Normal file
View File

@@ -0,0 +1,4 @@
PySide6==6.11.2
psutil==7.2.2
paramiko==4.0.0
nvidia-ml-py==13.615.71

125
tests/ssh_fixture.py Normal file
View File

@@ -0,0 +1,125 @@
"""Loopback-only test endpoint with a fixed synthetic telemetry frame."""
import socket
import threading
import paramiko
from arm.providers.ssh import probe_command
SECRET = "arm-fixture-only"
COMMAND = probe_command().encode()
FRAME = (
"os\tLinux fixture\nboot\t{boot}\ncpu\tcpu\t{busy} 0 200 500 0 0 0 0 0 0\n"
"cpu\tcpu0\t{busy} 0 200 500 0 0 0 0 0 0\n"
"ram\tMemTotal\t16384\nram\tMemAvailable\t12000\n"
"ram\tSwapTotal\t2024\nram\tSwapFree\t1024\n"
"disk\tnvme0n1\t1 0 {busy} 3 4 0 {busy} 3 0 50 99\n"
"net\teth0\t1\tup\t10000\t{busy} 0 0 0 0 0 0 0 {busy} 0 0 0 0 0 0 0\n"
"net\tvpn0\t0\tup\t\t{busy} 0 0 0 0 0 0 0 {busy} 0 0 0 0 0 0 0\n"
"drm\t0000:01:00.0\t0x1002\t0x1234\t80\t128\t512\t40000\t1500\t800\t10000000,50000000\n"
)
class Secret:
def __init__(self, secret=SECRET):
self.secret = secret
def read(self, reference):
return self.secret
class Auth(paramiko.ServerInterface):
def __init__(self, key=None):
self.exec = threading.Event()
self.command = None
self.key = key
def check_auth_password(self, username, password):
return (paramiko.AUTH_SUCCESSFUL if (username, password) == ("tester", SECRET)
else paramiko.AUTH_FAILED)
def check_auth_publickey(self, username, key):
return paramiko.AUTH_SUCCESSFUL if username == "tester" and key == self.key else paramiko.AUTH_FAILED
def check_channel_request(self, kind, channel_id):
return paramiko.OPEN_SUCCEEDED if kind == "session" else paramiko.OPEN_FAILED_ADMINISTRATIVELY_PROHIBITED
def check_channel_exec_request(self, channel, command):
self.command = command
self.exec.set()
return command == COMMAND
class Fixture:
def __init__(self, *, key=None, drop_first=False, public=None):
self.key = key or paramiko.RSAKey.generate(2048)
self.drop_first, self.public = drop_first, public
self.listener = socket.socket()
self.listener.bind(("127.0.0.1", 0))
self.listener.listen()
self.listener.settimeout(.25)
self.port = self.listener.getsockname()[1]
self.connections = 0
self.samples = 0
self.commands = []
self.errors = []
self.stop = threading.Event()
self.thread = threading.Thread(target=self.run)
def __enter__(self):
self.thread.start()
return self
def __exit__(self, *_):
self.stop.set()
self.listener.close()
self.thread.join(5)
if self.thread.is_alive():
raise TimeoutError("SSH test fixture did not stop")
if self.errors:
raise AssertionError(self.errors)
def run(self):
while not self.stop.is_set():
try:
sock, _ = self.listener.accept()
except socket.timeout:
continue
except OSError:
break
self.connections += 1
transport = paramiko.Transport(sock)
transport.add_server_key(self.key)
server = Auth(self.public)
try:
transport.start_server(server=server)
channel = transport.accept(timeout=2)
if channel is None or not server.exec.wait(1):
continue
self.commands.append(server.command)
channel.settimeout(.2)
buf = b""
while not self.stop.is_set():
try:
data = channel.recv(32768)
except socket.timeout:
continue
if not data:
break
buf += data
while b"\n" in buf:
line, buf = buf.split(b"\n", 1)
if line != b".":
continue
self.samples += 1
if self.drop_first and self.samples == 1:
transport.close()
break
frame = FRAME.format(boot=102, busy=100 + self.samples * 10)
channel.sendall(b"@arm-begin\n" + frame.encode() + b"@arm-end\n")
except (OSError, EOFError, paramiko.SSHException):
pass
except Exception as exc:
self.errors.append(exc)
finally:
transport.close()

105
tests/test_model.py Normal file
View File

@@ -0,0 +1,105 @@
import tempfile
from pathlib import Path
from types import SimpleNamespace
import unittest
from arm.config import ConfigStore, Settings, Target
from arm.credentials import CredentialStore
from arm.graphs import Dashboard, across_series
from arm.model import (ALL, LOCAL, TOTAL, Availability, Connection, History, Status,
aggregate, current_reading, graph_scale, rate, readings)
from arm.providers.gpu import engine_usage, gpu_metrics
from arm.tray import HoverState, place_popup
from PySide6.QtCore import QRect, QSize
class ModelTests(unittest.TestCase):
def test_rate_baseline_reset_delayed_and_zero(self):
self.assertIsNone(rate(None, 33, 1, 1))
self.assertIsNone(rate(100, 99, 1, 1))
self.assertIsNone(rate(9, 10, 10, 1))
self.assertEqual(rate(9, 9, 1, 1), 0)
self.assertEqual(rate(100, 200, .5, 1), 200)
def test_history_and_scaling(self):
history = History(10, 3)
for i in range(1, 6):
history.add(readings(LOCAL, i, TOTAL, {"disk.total": (i * 1000, "B/s")}))
series = history.since(LOCAL, TOTAL, "disk.total", 0)
self.assertEqual([r.timestamp for r in series], [3, 4, 5])
self.assertEqual(graph_scale(series), 8192)
self.assertEqual(graph_scale(series, 21000), 21000)
self.assertEqual(current_reading(series[-1], Connection.OFFLINE, 1, 6).availability, Availability.STALE)
self.assertEqual(len(history.since(LOCAL, TOTAL, "disk.total", 4.5)), 1)
def test_gpu_capacity_pairs_peak_and_engines(self):
gpus = [gpu_metrics({"util": 100, "vram_used": 3, "vram_total": 10}),
gpu_metrics({"util": 0, "vram_used": 7, "vram_total": 20}),
gpu_metrics({"util": 16, "vram_total": 100})]
result = {r.metric: r.value for r in aggregate(LOCAL, 1, "gpu", gpus)}
self.assertEqual(result["gpu.util"], 100)
self.assertEqual(result["gpu.vram_total"], 30)
self.assertAlmostEqual(result["gpu.vram_pct"], 100 / 3)
self.assertEqual(result["gpu.vram_free"], 20)
values = engine_usage({
"pid_2_luid_0x00000000_0x00000001_phys_0_eng_2_engtype_3D": 40,
"pid_3_luid_0x00000000_0x00000001_phys_0_eng_2_engtype_3D": 35,
"pid_3_luid_0x00000000_0x00000001_phys_0_eng_4_engtype_Compute": 20,
})
self.assertEqual(next(iter(values.values()))["util"], 75)
self.assertEqual(next(iter(values.values()))["compute"], 20)
def test_multi_machine_ignores_disconnect_and_names_peak(self):
target = Target(name="Remote")
coll = SimpleNamespace(settings=Settings(targets=[target]), history=History(),
statuses={LOCAL: Status(LOCAL, Connection.ONLINE),
target.identifier: Status(target.identifier, Connection.ONLINE)},
provider_status={}, intervals={})
view = Dashboard(coll)
for m, peak in ((LOCAL, 12), (target.identifier, 100)):
coll.history.add(readings(m, 29, TOTAL, {"cpu.util": (peak, "%")}))
_, _, _, value, chosen, _ = view.get(ALL, "cpu", "cpu.util", TOTAL, 30, 30, 40)
self.assertEqual((value.value, chosen), (100, target.identifier))
coll.statuses[target.identifier] = Status(target.identifier, Connection.OFFLINE)
_, _, _, value, chosen, _ = view.get(ALL, "cpu", "cpu.util", TOTAL, 30, 30, 40)
self.assertEqual((value.value, chosen), (12, LOCAL))
self.assertEqual(across_series({"ram": [(29, None)], "cpu": [(29, 90)]}, 30, 30, 3, 25)[0],
(29, 90, "cpu"))
def test_hover_and_taskbar_edges(self):
state = HoverState()
self.assertIsNone(state.update(1, LOCAL, False, False, False, .3, .5))
self.assertEqual(state.update(1.5, LOCAL, False, False, False, .3, .5), "show")
self.assertIsNone(state.update(2, None, False, True, False, .3, .5))
self.assertIsNone(state.update(2.1, None, True, True, False, .3, .5))
self.assertIsNone(state.update(3, None, False, True, False, .3, .5))
self.assertEqual(state.update(3.6, None, False, True, False, .3, .5), "hide")
self.assertIsNone(state.update(7, None, False, True, True, .3, .5))
available = QRect(-1200, 40, 1200, 740)
for rect in (QRect(-20, 784, 18, 18), QRect(-80, 5, 16, 16), QRect(-1220, 10, 16, 16)):
self.assertTrue(available.contains(place_popup(available, rect, QSize(500, 330))))
def test_settings_backward_compat_and_reference(self):
with tempfile.TemporaryDirectory(prefix="arm-config-test-") as root:
path = Path(root) / "settings.json"
path.write_text('{"popup_width": 9999,"hover_range":[]}', encoding="utf-8")
store = ConfigStore(path)
self.assertEqual(store.load().popup_width, 1800)
cfg = Settings(mode="Stacked", targets=[Target(credential="test-reference")])
store.save(cfg)
self.assertEqual(store.load(), cfg)
cfg.mode = "Application Icon"
store.save(cfg)
self.assertEqual(store.load(), cfg)
self.assertNotIn('"password":', path.read_text(encoding="utf-8").lower())
def test_real_credential_namespace_and_roundtrip(self):
vault = CredentialStore()
ref = vault.save("ARM unit test", "Test-only µ password")
try:
self.assertEqual(vault.read(ref), "Test-only µ password")
with self.assertRaises(ValueError):
vault.read("UnrelatedCredential")
finally:
vault.delete(ref)
self.assertIsNone(vault.read(ref))

147
tests/test_providers.py Normal file
View File

@@ -0,0 +1,147 @@
from pathlib import Path
from queue import Queue
from tempfile import TemporaryDirectory
from time import sleep, time
import unittest
import paramiko
from arm.collect import Worker, problem
from arm.config import Settings, Target
from arm.history_db import HistoryDb
from arm.model import Connection, LOCAL, TOTAL, Sample, Status, readings
from arm.providers.gpu import WddmGpu
from arm.providers.ssh import LinuxParser, LinuxSsh, UntrustedHost, update_host_key
from arm.providers.windows import Cpu, Disk, Memory, Network
from ssh_fixture import COMMAND, FRAME, Fixture, Secret
def reading(sample, metric, device=TOTAL):
return next(r for r in sample.readings if r.metric == metric and r.device == device)
class Providers(unittest.TestCase):
def test_windows_live_collector_shapes_and_first_sample(self):
providers = [kind(Settings()) for kind in (Cpu, Memory, Disk, Network, WddmGpu)]
try:
first = [p.sample() for p in providers]
self.assertIsNone(reading(first[0], "cpu.util").value)
self.assertIsNone(reading(first[2], "disk.total").value)
sleep(.85)
second = [p.sample() for p in providers]
self.assertTrue(reading(second[0], "cpu.util").valid)
self.assertTrue(reading(second[1], "ram.util").valid)
for sample in second:
self.assertTrue(all(r.timestamp == sample.timestamp for r in sample.readings))
finally:
for provider in providers:
provider.close()
def test_linux_rates_resets_and_interface_scope(self):
parser = LinuxParser(Target(interval=1))
first, os_label = parser.parse(FRAME.format(boot=1, busy=100), 10, 10)
second, _ = parser.parse(FRAME.format(boot=1, busy=200), 11, 11)
self.assertEqual(os_label, "Linux fixture")
self.assertIsNone(reading(first, "cpu.util").value)
self.assertEqual(reading(second, "cpu.util").value, 100)
self.assertEqual(reading(second, "disk.read").value, 51200)
self.assertEqual(reading(second, "net.total").value, 200)
self.assertEqual(reading(second, "net.total", "vpn0").value, 200)
self.assertEqual(reading(second, "gpu.vram_pct").value, 25)
reset, _ = parser.parse(FRAME.format(boot=2, busy=400), 12, 12)
self.assertIsNone(reading(reset, "disk.read").value)
def test_loopback_password_verification_persistence_and_changed_key(self):
with TemporaryDirectory(prefix="arm-ssh-test-") as root, Fixture() as server:
known = Path(root) / "known_hosts"
profile = Target(host="127.0.0.1", port=server.port, username="tester", timeout=3)
sampler = LinuxSsh(profile, Secret(), known)
with self.assertRaises(UntrustedHost) as blocked:
try:
sampler.sample()
finally:
sampler.close()
host_key = blocked.exception.host_key
self.assertTrue(host_key.fingerprint.startswith("SHA256:"))
wrong = paramiko.RSAKey.generate(2048)
update_host_key(known, host_key.label, wrong)
sampler = LinuxSsh(profile, Secret(), known)
try:
with self.assertRaises(paramiko.BadHostKeyException) as changed:
sampler.sample()
self.assertFalse(problem(changed.exception)[1])
finally:
sampler.close()
update_host_key(known, host_key.label)
update_host_key(known, host_key.label, host_key.key)
sampler = LinuxSsh(profile, Secret("wrong"), known)
try:
with self.assertRaises(paramiko.AuthenticationException):
sampler.sample()
finally:
sampler.close()
sampler = LinuxSsh(profile, Secret(), known)
try:
self.assertFalse(reading(sampler.sample(), "cpu.util").valid)
self.assertTrue(reading(sampler.sample(), "cpu.util").valid)
self.assertEqual(server.samples, 2)
self.assertEqual(server.commands, [COMMAND])
finally:
sampler.close()
def test_loopback_private_key(self):
private = paramiko.RSAKey.generate(2048)
with TemporaryDirectory(prefix="arm-key-test-") as root, Fixture(public=private) as server:
root = Path(root)
profile = Target(host="127.0.0.1", port=server.port, username="tester", timeout=3,
auth="Private key", key_file=str(root / "test_key"))
private.write_private_key_file(profile.key_file, password="ephemeral")
known = root / "known_hosts"
update_host_key(known, f"[127.0.0.1]:{server.port}", server.key)
sampler = LinuxSsh(profile, Secret("ephemeral"), known)
try:
self.assertTrue(reading(sampler.sample(), "ram.util").valid)
finally:
sampler.close()
def test_worker_reconnect_and_close(self):
with TemporaryDirectory(prefix="arm-retry-test-") as root, Fixture(drop_first=True) as server:
profile = Target(host="127.0.0.1", port=server.port, username="tester", timeout=3, interval=.5)
known = Path(root) / "known_hosts"
update_host_key(known, f"[127.0.0.1]:{server.port}", server.key)
events = Queue()
worker = Worker((profile.identifier, "test"), lambda: LinuxSsh(profile, Secret(), known),
.5, lambda _, message, *_tail: events.put(message), remote=True)
worker.start()
try:
results = [events.get(timeout=8) for _ in range(4)]
states = [item.state for item in results if isinstance(item, Status)]
self.assertEqual(states, [Connection.CONNECTING, Connection.RETRYING, Connection.CONNECTING])
self.assertTrue(isinstance(results[-1], Sample))
self.assertGreaterEqual(server.connections, 2)
finally:
worker.stop()
worker.join(5)
self.assertFalse(worker.is_alive())
def test_sqlite_flush_read_clear_and_stop(self):
with TemporaryDirectory(prefix="arm-db-test-") as root:
stamp = time()
replies, errors = Queue(), Queue()
key = (LOCAL, TOTAL, "cpu.util")
path = Path(root) / "history.sqlite"
first = HistoryDb(path, 1, 16, lambda *result: replies.put(result), errors.put)
first.record(readings(LOCAL, stamp, TOTAL, {"cpu.util": (31, "%")}))
first.close()
next_db = HistoryDb(path, 1, 16, lambda *result: replies.put(result), errors.put)
try:
next_db.request(1, [key], stamp - 1)
self.assertEqual(replies.get(timeout=5)[1][key][0].value, 31)
next_db.send("clear", 2)
self.assertEqual(replies.get(timeout=5), (2, {}))
next_db.request(3, [key], stamp - 1)
self.assertEqual(replies.get(timeout=5)[1][key], [])
finally:
next_db.close()
self.assertTrue(errors.empty())
self.assertFalse(next_db.thread.is_alive())

660
tests/windows_gui.py Normal file
View File

@@ -0,0 +1,660 @@
"""Native Qt tests on a private Windows desktop without switching desktops."""
import argparse
import ctypes as ct
from ctypes import wintypes as w
from dataclasses import replace
import hashlib
import json
import os
from pathlib import Path
import shutil
import struct
import subprocess
import sys
import tempfile
from time import monotonic, sleep
from uuid import uuid4
from zipfile import ZipFile
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
USER = ct.WinDLL("user32", use_last_error=True)
KERNEL = ct.WinDLL("kernel32", use_last_error=True)
def bind(dll, name, result, *args):
fn = getattr(dll, name)
fn.restype, fn.argtypes = result, args
return fn
class Startup(ct.Structure):
_fields_ = [("cb", w.DWORD), ("reserved", w.LPWSTR), ("desktop", w.LPWSTR),
("title", w.LPWSTR)] + [(key, w.DWORD) for key in (
"x", "y", "width", "height", "cols", "rows", "fill", "flags")] + [
("show", w.WORD), ("reserved2_size", w.WORD), ("reserved2", ct.c_void_p),
("stdin", w.HANDLE), ("stdout", w.HANDLE), ("stderr", w.HANDLE),
]
class ProcessInfo(ct.Structure):
_fields_ = [("process", w.HANDLE), ("thread", w.HANDLE), ("pid", w.DWORD), ("tid", w.DWORD)]
def start_isolated(argv, desktop_name, timeout=210):
create_desktop = bind(USER, "CreateDesktopW", w.HANDLE,
w.LPCWSTR, w.LPCWSTR, ct.c_void_p, w.DWORD, w.DWORD, ct.c_void_p)
close_desktop = bind(USER, "CloseDesktop", w.BOOL, w.HANDLE)
desktop = create_desktop(desktop_name, None, None, 0, 0x01ff, None)
if not desktop:
raise ct.WinError(ct.get_last_error())
close = bind(KERNEL, "CloseHandle", w.BOOL, w.HANDLE)
create = bind(KERNEL, "CreateProcessW", w.BOOL, w.LPCWSTR, w.LPWSTR, ct.c_void_p,
ct.c_void_p, w.BOOL, w.DWORD, ct.c_void_p, w.LPCWSTR,
ct.POINTER(Startup), ct.POINTER(ProcessInfo))
wait = bind(KERNEL, "WaitForSingleObject", w.DWORD, w.HANDLE, w.DWORD)
status = bind(KERNEL, "GetExitCodeProcess", w.BOOL, w.HANDLE, ct.POINTER(w.DWORD))
terminate = bind(KERNEL, "TerminateProcess", w.BOOL, w.HANDLE, w.UINT)
launch = Startup()
launch.cb, launch.desktop = ct.sizeof(Startup), f"WinSta0\\{desktop_name}"
process = ProcessInfo()
try:
command = ct.create_unicode_buffer(subprocess.list2cmdline(argv))
if not create(str(argv[0]), command, None, None, False, 0x08000000, None, str(ROOT),
ct.byref(launch), ct.byref(process)):
raise ct.WinError(ct.get_last_error())
try:
if wait(process.process, timeout * 1000):
terminate(process.process, 30)
wait(process.process, 10_000)
raise TimeoutError("Isolated Windows GUI test exceeded its time allowance")
exit_code = w.DWORD()
if not status(process.process, ct.byref(exit_code)):
raise ct.WinError(ct.get_last_error())
return exit_code.value
finally:
close(process.thread)
close(process.process)
finally:
close_desktop(desktop)
def verify_desktop(expected):
current_tid = bind(KERNEL, "GetCurrentThreadId", w.DWORD)()
desk = bind(USER, "GetThreadDesktop", w.HANDLE, w.DWORD)(current_tid)
get = bind(USER, "GetUserObjectInformationW", w.BOOL,
w.HANDLE, ct.c_int, ct.c_void_p, w.DWORD, ct.POINTER(w.DWORD))
buf, required = ct.create_unicode_buffer(256), w.DWORD()
if not get(desk, 2, buf, ct.sizeof(buf), ct.byref(required)) or buf.value != expected:
raise RuntimeError("Application test is not on the requested private desktop")
return buf.value
def window_process(hwnd):
pid = w.DWORD()
thread = bind(USER, "GetWindowThreadProcessId", w.DWORD, w.HWND, ct.POINTER(w.DWORD))(hwnd, ct.byref(pid))
return thread, pid.value
def run_frozen(exe, profile_root, output):
from arm.config import ConfigStore, Settings, Target
from arm.version import NAME, VERSION
# Separate settings and logs for each run. Existing profiles stay untouched.
appdir = profile_root / NAME
env = dict(os.environ, LOCALAPPDATA=str(profile_root))
for key in ("PYTHONPATH", "QT_QPA_PLATFORM", "QT_SCALE_FACTOR"):
env.pop(key, None)
config = ConfigStore(appdir / "settings.json")
if not config.path.is_file():
config.save(Settings(minimized=False, mode="Composite", targets=[
Target(name="Saved test profile", host="127.0.0.1", enabled=False, credential="test-reference")
]))
original = config.path.read_bytes()
find = bind(USER, "FindWindowW", w.HWND, w.LPCWSTR, w.LPCWSTR)
visible = bind(USER, "IsWindowVisible", w.BOOL, w.HWND)
post = bind(USER, "PostMessageW", w.BOOL, w.HWND, w.UINT, w.WPARAM, w.LPARAM)
post_thread = bind(USER, "PostThreadMessageW", w.BOOL, w.DWORD, w.UINT, w.WPARAM, w.LPARAM)
send = bind(USER, "SendMessageTimeoutW", ct.c_size_t, w.HWND, w.UINT, w.WPARAM, w.LPARAM,
w.UINT, w.UINT, ct.POINTER(ct.c_size_t))
for iteration in range(2):
with subprocess.Popen([str(exe)], env=env, cwd=exe.parent) as proc:
try:
deadline, hwnd = monotonic() + 25, None
while monotonic() < deadline and proc.poll() is None:
found = find(None, NAME)
if found:
thread, pid = window_process(found)
if pid == proc.pid and visible(found):
hwnd = found
break
sleep(.15)
assert hwnd, f"Frozen application did not open its native window, exit {proc.poll()}"
sleep(2.5)
replacement = find(None, NAME)
if replacement and window_process(replacement)[1] == proc.pid:
hwnd = replacement
assert proc.poll() is None, f"Frozen application exited before close, code {proc.returncode}"
icon = ct.c_size_t()
assert send(hwnd, 0x7f, 1, 0, 2, 2000, ct.byref(icon)) and icon.value, "Missing window icon"
if not post(hwnd, 0x10, 0, 0):
raise ct.WinError(ct.get_last_error())
sleep(.45)
assert proc.poll() is None and not visible(hwnd), "Window close should leave tray running"
assert post_thread(thread, 0x12, 0, 0), "Posting WM_QUIT failed"
assert proc.wait(10) == 0
finally:
if proc.poll() is None:
proc.terminate()
proc.wait(8)
assert config.path.read_bytes() == original
data = (appdir / "arm.log").read_text(encoding="utf-8")
assert data.count(f"{NAME} {VERSION} starting") == iteration + 1
assert data.count(f"{NAME} stopped") == iteration + 1
assert all(word in data for word in ("Initializing provider CPU", "Initializing provider GPU"))
assert " ERROR " not in data, data
output["frozen_launches"] = 2
output["frozen_version"] = VERSION
def verify_executable(path, version):
import pefile
from arm.branding import COPYRIGHT, ICON_SIZES, PUBLISHER
pe = pefile.PE(str(path))
try:
assert pe.FILE_HEADER.Machine == 0x8664
fields = next(node.StringTable[0].entries for block in pe.FileInfo for node in block
if hasattr(node, "StringTable"))
assert fields[b"CompanyName"].decode().strip() == PUBLISHER
assert fields[b"LegalCopyright"].decode().strip() == COPYRIGHT
assert fields[b"ProductVersion"].decode().strip() == version
group = next(entry for entry in pe.DIRECTORY_ENTRY_RESOURCE.entries if entry.id == 14)
sizes = set()
for ident in group.directory.entries:
ref = ident.directory.entries[0].data.struct
data = pe.get_data(ref.OffsetToData, ref.Size)
count = struct.unpack_from("<H", data, 4)[0]
sizes.update((data[6 + 14*i] or 256) for i in range(count))
assert set(ICON_SIZES) <= sizes, (path.name, sizes)
finally:
pe.close()
def capture_native_window(hwnd, path):
from PySide6.QtGui import QImage
gdi = ct.WinDLL("gdi32", use_last_error=True)
rect = w.RECT()
assert bind(USER, "GetWindowRect", w.BOOL, w.HWND, ct.POINTER(w.RECT))(hwnd, ct.byref(rect))
width, height = rect.right - rect.left, rect.bottom - rect.top
dc = bind(gdi, "CreateCompatibleDC", w.HDC, w.HDC)(None)
assert dc
info = ct.create_string_buffer(struct.pack("<IiiHHIIiiII", 40, width, -height, 1, 32,
0, 0, 0, 0, 0, 0))
bits = ct.c_void_p()
bitmap = bind(gdi, "CreateDIBSection", w.HBITMAP, w.HDC, ct.c_void_p, w.UINT,
ct.POINTER(ct.c_void_p), w.HANDLE, w.DWORD)(dc, info, 0, ct.byref(bits), None, 0)
select = bind(gdi, "SelectObject", w.HANDLE, w.HDC, w.HANDLE)
original = select(dc, bitmap)
try:
printed = bind(USER, "PrintWindow", w.BOOL, w.HWND, w.HDC, w.UINT)(hwnd, dc, 2)
assert printed, "Windows installer did not paint into the capture"
pixels = ct.string_at(bits.value, width * height * 4)
picture = QImage(pixels, width, height, width * 4, QImage.Format.Format_RGB32)
assert picture.save(str(path))
finally:
select(dc, original)
bind(gdi, "DeleteObject", w.BOOL, w.HANDLE)(bitmap)
bind(gdi, "DeleteDC", w.BOOL, w.HDC)(dc)
def run_installer_wizard(args, result, captures=None):
from arm.version import NAME
find = bind(USER, "FindWindowW", w.HWND, w.LPCWSTR, w.LPCWSTR)
visible = bind(USER, "IsWindowVisible", w.BOOL, w.HWND)
with subprocess.Popen([args[0], "/SILENT", *args[2:]]) as process:
try:
limit = monotonic() + 18
while monotonic() < limit and process.poll() is None:
wizard = find("TWizardForm", None)
if wizard and visible(wizard):
caption = ct.create_unicode_buffer(512)
bind(USER, "GetWindowTextW", ct.c_int, w.HWND, w.LPWSTR, ct.c_int)(wizard, caption, 512)
if NAME in caption.value:
result["native_installer_wizard"] = caption.value
if captures:
capture_native_window(wizard, captures / "installer-wizard.png")
break
sleep(.07)
finally:
code = process.wait(45)
assert "native_installer_wizard" in result, "Installer wizard did not become visible on the private desktop"
return code
def validate_packages(release, work, result, upgrade_from=None, captures=None):
from arm.about import UNINSTALL_KEY
from arm.branding import BUNDLED_ASSETS, PUBLISHER, SUPPORT_URL, WEBSITE, asset
from arm.config import ConfigStore, Settings, Target
from arm.version import NAME, VERSION
stem = f"AdaptiveResourceMonitor-{VERSION}-windows-x64"
portable, setup = release / f"{stem}-portable.zip", release / f"{stem}-setup.exe"
exe = "AdaptiveResourceMonitor.exe"
digests = {}
for artifact in (portable, setup):
with artifact.open("rb") as stream:
digests[artifact.name] = hashlib.file_digest(stream, "sha256").hexdigest()
for line in (release / "SHA256SUMS.txt").read_text(encoding="ascii").splitlines():
digest, name = line.split(" ", 1)
assert digests[name] == digest
with ZipFile(portable) as package:
assert package.testzip() is None
package.extractall(work / "portable")
payload = work / "portable" / "AdaptiveResourceMonitor"
assert (payload / "VERSION.txt").read_text().strip() == VERSION
assert json.loads((payload / "BUILD.json").read_text())["version"] == VERSION
assert VERSION in (payload / "CHANGELOG.md").read_text(encoding="utf-8")
assert (payload / "Third-party notices" / "README.md").is_file()
for name in BUNDLED_ASSETS:
assert (payload / "_internal" / "branding" / name).read_bytes() == asset(name).read_bytes()
verify_executable(setup, VERSION)
verify_executable(payload / exe, VERSION)
result["verified_pe_icons_and_company_metadata"] = True
run_frozen(payload / exe, work / "portable-profile", result)
import winreg
key = UNINSTALL_KEY
for hive in (winreg.HKEY_CURRENT_USER, winreg.HKEY_LOCAL_MACHINE):
for view in (winreg.KEY_WOW64_64KEY, winreg.KEY_WOW64_32KEY):
try:
with winreg.OpenKey(hive, key, 0, winreg.KEY_READ | view):
raise RuntimeError("A pre-existing ARM installation prevents a disposable installer test")
except FileNotFoundError:
pass
setup_copy = work / setup.name
shutil.copyfile(setup, setup_copy)
installed = work / "installed"
profile = work / "installed-profile"
configuration = profile / NAME / "settings.json"
ConfigStore(configuration).save(Settings(minimized=False, mode="Composite", targets=[
Target(name="Preserved test target", host="127.0.0.1", enabled=False, credential="arm-test-reference")
]))
saved = configuration.read_bytes()
history = profile / NAME / "preserve.sqlite"
history.write_text("test data", encoding="utf-8")
args = [str(setup_copy), "/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART", "/NOICONS",
"/TASKS=", f"/DIR={installed}", f"/LOG={work / 'install.log'}"]
try:
if upgrade_from:
prior_copy = work / "prior-setup.exe"
shutil.copyfile(upgrade_from, prior_copy)
result["prior_install_exit"] = subprocess.run([str(prior_copy), *args[1:]], timeout=45).returncode
assert result["prior_install_exit"] == 0
assert (installed / exe).is_file()
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key) as item:
result["upgraded_from"] = winreg.QueryValueEx(item, "DisplayVersion")[0]
assert result["upgraded_from"] != VERSION
for upgrade in (False, True):
mode = "reinstall" if upgrade else ("upgrade" if upgrade_from else "install")
code = (subprocess.run(args, timeout=45).returncode if upgrade
else run_installer_wizard(args, result, captures))
result[f"{mode}_exit"] = code
assert code == 0 and (installed / exe).is_file()
assert configuration.read_bytes() == saved
assert history.read_text(encoding="utf-8") == "test data"
with winreg.OpenKey(winreg.HKEY_CURRENT_USER, key) as item:
for field, value in (("Publisher", PUBLISHER), ("DisplayVersion", VERSION),
("URLInfoAbout", WEBSITE), ("HelpLink", SUPPORT_URL)):
assert winreg.QueryValueEx(item, field)[0] == value
assert exe in winreg.QueryValueEx(item, "DisplayIcon")[0]
if not upgrade:
installed_result = {}
run_frozen(installed / exe, profile, installed_result)
result["installed_launches"] = installed_result["frozen_launches"]
result["verified_installed_metadata"] = True
finally:
remove = next(iter(installed.glob("unins*.exe")), None)
if remove:
outcome = subprocess.run([str(remove), "/VERYSILENT", "/SUPPRESSMSGBOXES", "/NORESTART"],
timeout=45)
result["uninstall_exit"] = outcome.returncode
assert outcome.returncode == 0 and not (installed / exe).exists()
assert configuration.read_bytes() == saved
assert history.read_text(encoding="utf-8") == "test data"
def verify_branding(session, results, captures=None):
from PySide6.QtCore import QObject, QPoint, QTimer, QUrl, Slot
from PySide6.QtGui import QDesktopServices, QImage
from PySide6.QtWidgets import QLabel, QPushButton
from arm.branding import (
APPLICATION_ICON, APPLICATION_IMAGE, APPLICATION_LOGO, COMPANY_LOGO, ICON_SIZES,
SUPPORT_URL, WEBSITE, asset,
)
from arm.model import ALL, LOCAL
from arm.version import NAME, VERSION
def check_alpha(image):
rgba = image.convertToFormat(QImage.Format.Format_RGBA8888)
alpha = bytes(rgba.constBits())[3::4]
assert min(alpha) == 0 and max(alpha) == 255
corners = ((0, 0), (rgba.width() - 1, 0), (0, rgba.height() - 1),
(rgba.width() - 1, rgba.height() - 1))
assert all(rgba.pixelColor(x, y).alpha() <= 1 for x, y in corners)
ico = asset(APPLICATION_ICON).read_bytes()
count = struct.unpack_from("<H", ico, 4)[0]
sizes = {}
for i in range(count):
width, height, _, _, _, _, length, offset = struct.unpack_from("<BBBBHHII", ico, 6 + i * 16)
assert width == height
frame = QImage.fromData(ico[offset:offset + length])
assert frame.width() == (width or 256)
check_alpha(frame)
sizes[frame.width()] = True
assert tuple(sorted(sizes)) == ICON_SIZES
for name in (APPLICATION_IMAGE, APPLICATION_LOGO, COMPANY_LOGO):
check_alpha(QImage(str(asset(name))))
results["transparent_ico_frames"] = list(ICON_SIZES)
menu = session.menus[LOCAL]
assert menu.version.text() == VERSION and menu.local.isChecked()
assert not menu.remote.menuAction().isVisible()
actions = {action.text(): action for action in menu.actions()}
assert "Check for Updates" not in actions
actions[f"About {NAME}"].trigger()
assert session.expanded.tabs.currentWidget() is session.about_page
assert session.about_page.version.text() == VERSION
assert VERSION in session.about_page.browser.toPlainText()
assert not session.expanded.monitor_visible
assert not session.about_page.app_image.picture.isNull()
assert not session.about_page.company_image.picture.isNull()
session.about_page.open_link("THIRD_PARTY.md")
assert session.about_page.document_group.title() == "Third-party Notices"
assert "CPython" in session.about_page.browser.toPlainText()
session.about_page.open_link("README.md")
assert "dynamic icon" in session.about_page.browser.toPlainText()
session.about_page.open_link("CHANGELOG.md")
details = []
def inspect_details():
dialog = session.qt.activeModalWidget()
if dialog:
details.extend(label.text() for label in dialog.findChildren(QLabel))
dialog.reject()
QTimer.singleShot(0, inspect_details)
view = next(button for button in session.about_page.findChildren(QPushButton) if button.text() == "View Details")
view.click()
assert "Installation type" in details and "Source checkout" in details and VERSION in details
class BrowserTarget(QObject):
@Slot(QUrl)
def receive(self, url):
self.destination = url.toString()
sink = BrowserTarget()
QDesktopServices.setUrlHandler("https", sink, "receive")
try:
actions["Design Creations Website"].trigger()
assert sink.destination == WEBSITE
session.about_page.open_link(SUPPORT_URL)
assert sink.destination == SUPPORT_URL
finally:
QDesktopServices.unsetUrlHandler("https")
if captures:
session.apply(replace(session.settings, theme="Dark"))
session.qt.processEvents()
pixmap = session.expanded.grab()
assert round(pixmap.width() / pixmap.devicePixelRatio()) == session.expanded.width()
scale = round(session.expanded.devicePixelRatioF() * 100)
assert pixmap.save(str(captures / f"about-{scale}.png"))
menu.popup(QPoint(20, 20))
session.qt.processEvents()
assert menu.grab().save(str(captures / f"tray-menu-{scale}.png"))
menu.hide()
actions["Resource History"].trigger()
assert session.expanded.monitor_visible and session.expanded.span == 3600
menu.all.trigger()
assert session.popup.selected_machine == ALL and menu.all.isChecked()
menu.local.trigger()
assert session.popup.selected_machine == LOCAL
session.popup.hide()
session.expanded.close()
results["verified_about_and_tray_actions"] = True
def evaluate_app(work, results, short=False, captures=None):
import psutil
from PySide6.QtCore import QEventLoop, QTimer
from PySide6.QtGui import QGuiApplication
from PySide6.QtWidgets import QApplication, QSystemTrayIcon
from arm.application import Application
from arm.branding import set_windows_identity
from arm.config import STATIC_TRAY_MODE, ConfigStore, Settings, Target
from arm.dialogs import ConnectionsDialog, SettingsDialog
from arm.model import LOCAL, TOTAL, Connection, RESOURCES
from arm.providers.ssh import update_host_key
from ssh_fixture import Fixture, SECRET
from contextlib import ExitStack
from unittest.mock import patch
assert set_windows_identity() == 0
app = QApplication([])
assert QGuiApplication.platformName() == "windows"
app.setQuitOnLastWindowClosed(False)
root = work / "app"
session = Application(app, root)
process = psutil.Process()
results["platform"] = app.platformName()
results["qt_reports_system_tray"] = QSystemTrayIcon.isSystemTrayAvailable()
results["scale"] = [screen.devicePixelRatio() for screen in app.screens()]
def wait_for(condition, seconds=8):
loop = QEventLoop()
timer = QTimer()
timer.setInterval(100)
def check():
if condition():
loop.quit()
if condition():
return
timer.timeout.connect(check)
timer.start()
QTimer.singleShot(seconds * 1000, loop.quit)
loop.exec()
timer.stop()
assert condition(), "Expected condition did not arrive"
def measure(label, seconds=12):
usage = process.cpu_times()
started = monotonic()
loop = QEventLoop()
QTimer.singleShot(round(seconds * 1000), loop.quit)
loop.exec()
ended = process.cpu_times()
cpu = 100 * (ended.user + ended.system - usage.user - usage.system) / (monotonic() - started)
results.setdefault("performance", {})[label] = {
"cpu_percent_one_logical": round(cpu, 3),
"cpu_percent_machine": round(cpu / (psutil.cpu_count() or 1), 3),
"rss_mib": round(process.memory_info().rss / 2**20, 2),
"seconds": seconds,
}
try:
assert session.icons[LOCAL].icon().cacheKey() == session.brand_icon.cacheKey()
resources = ("cpu.util", "gpu.util", "ram.util", "gpu.vram_pct", "disk.total", "net.total")
wait_for(lambda: all((r := session.collectors.history.latest(LOCAL, TOTAL, key)) and r.valid
for key in resources), 12)
results["local_resources"] = {key: round(session.collectors.history.latest(LOCAL, TOTAL, key).value, 2)
for key in resources}
results["gpu_devices"] = [d.name for d in session.collectors.devices[LOCAL].values() if d.kind == "gpu"]
results["per_gpu"] = {
device.name: {
metric: round(item.value, 2)
for metric in ("gpu.util", "gpu.vram_total", "gpu.vram_used", "gpu.temperature", "gpu.power")
if (item := session.collectors.history.latest(LOCAL, device.identifier, metric)) and item.valid
}
for device in session.collectors.devices[LOCAL].values() if device.kind == "gpu"
}
results["physical_disks"] = [d.name for d in session.collectors.devices[LOCAL].values() if d.kind == "disk"]
if not short:
measure("tray")
results["registered_icon_rect"] = bool(session.icons[LOCAL].geometry().isValid())
session.render()
assert session.icons[LOCAL].icon().cacheKey() != session.brand_icon.cacheKey()
verify_branding(session, results, captures)
menu = session.menus[LOCAL]
modes = {}
for mode in ("Stacked", STATIC_TRAY_MODE, "Overlay", "Composite"):
menu.modes[mode].trigger()
assert menu.modes[mode].isChecked() and session.settings.mode == mode
qr = session.icons[LOCAL].icon().pixmap(32, 32).toImage()
modes[mode] = hashlib.sha256(bytes(qr.bits())).hexdigest()[:12]
assert (session.icons[LOCAL].icon().cacheKey() == session.brand_icon.cacheKey()) == (mode == STATIC_TRAY_MODE)
assert len(set(modes.values())) == 4, modes
results["rendered_modes"] = modes
assert ConfigStore(root / "settings.json").load().mode == "Composite"
menu.pin.trigger()
assert session.popup.isVisible() and session.popup.pinned
assert sum(card.isVisible() for card in session.popup.cards.values()) == len(RESOURCES)
wait_for(lambda: session.popup.frameGeometry().isValid())
if not short:
measure("pinned_popup")
session.popup.pin.click()
assert not session.popup.pinned
session.popup.hide()
session.open_expanded(LOCAL)
assert session.expanded.isVisible() and session.expanded.table.rowCount() > 20
assert session.expanded.device.count() > 10
assert app.primaryScreen().availableGeometry().contains(session.popup.frameGeometry())
if not short:
measure("expanded")
session.expanded.close()
assert not session.expanded.isVisible() and session.icons[LOCAL].isVisible()
if not short:
prefs, connections = SettingsDialog(session), ConnectionsDialog(session)
prefs.show()
connections.show()
assert prefs.isVisible() and connections.isVisible()
assert prefs.tabs.count() == 7 and connections.table.rowCount() == 0
prefs.close()
connections.close()
prefs.deleteLater()
connections.deleteLater()
with ExitStack() as stack:
servers = [stack.enter_context(Fixture()) for _ in range(1 if short else 2)]
targets = []
for i, server in enumerate(servers, 1):
target = Target(name=f"Loopback {i}", host="127.0.0.1", port=server.port,
username="tester", interval=2, timeout=6, tray=True)
update_host_key(session.hosts, f"[127.0.0.1]:{server.port}", server.key)
session.save_target(target, SECRET, False)
targets.append(target)
try:
wait_for(lambda: session.dashboard.state(target.identifier) == Connection.ONLINE, 15)
except AssertionError as exc:
raise AssertionError(f"SSH fixture {i}: {server.connections} TCP sessions, "
f"{len(server.commands)} commands, {server.samples} frames, "
f"{session.dashboard.state(target.identifier)}") from exc
assert "Connected" in menu.remote_entries[target.identifier].text()
from arm.graphs import tray_icon
with patch("arm.application.tray_icon", wraps=tray_icon) as draw:
menu.remote_entries[target.identifier].trigger()
assert draw.call_args.args[1] == target.identifier
assert session.popup.selected_machine == target.identifier
menu.local.trigger()
session.popup.hide()
if i == 1 and not short:
measure("one_loopback_ssh")
if not short:
measure("two_loopback_ssh")
session.apply(replace(session.settings, tray_mode="Separate", persistent=True))
assert set(session.icons) == {LOCAL, *(target.identifier for target in targets)}
results["loopback_frame_counts"] = [server.samples for server in servers]
for target in targets:
session.collectors.disconnect(target.identifier)
assert all(session.dashboard.state(t.identifier) == Connection.OFFLINE for t in targets)
session.apply(replace(session.settings, tray_mode="Local", persistent=False))
if not short:
measure("disconnected_remotes")
session.apply(replace(session.settings, tray_mode="Consolidated"))
assert len(session.icons) == 1
for target in list(session.settings.targets):
session.remove_target(target)
exit_action = next(action for action in next(iter(session.menus.values())).actions()
if action.text().startswith("Exit Adaptive Resource Monitor"))
QTimer.singleShot(0, exit_action.trigger)
assert app.exec() == 0
finally:
for target in list(session.settings.targets):
session.remove_target(target)
session.close()
assert not session.collectors.workers
data = (root / "arm.log").read_text(encoding="utf-8")
assert "Adaptive Resource Monitor stopped" in data and " ERROR " not in data, data
def child(args):
result = {"desktop": verify_desktop(args.desktop)}
try:
if args.package:
validate_packages(args.package, args.work, result, args.upgrade_from, args.captures)
else:
evaluate_app(args.work, result, args.short, args.captures)
except Exception:
import traceback
result["traceback"] = traceback.format_exc()
log = args.work / "app" / "arm.log"
if log.is_file():
result["application_log"] = log.read_text(encoding="utf-8").splitlines()[-35:]
for name in ("portable-profile", "installed-profile"):
log = args.work / name / "Adaptive Resource Monitor" / "arm.log"
if log.is_file():
result[name] = log.read_text(encoding="utf-8").splitlines()[-35:]
return 1
finally:
(args.work / "result.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
return 0
def parent(args):
desktop = f"ARM_Validation_{uuid4().hex[:10]}"
with tempfile.TemporaryDirectory(prefix="arm-desktop-test-") as directory:
work = Path(directory)
command = [sys.executable, str(Path(__file__).resolve()), "--desktop", desktop, "--work", str(work)]
if args.package:
command.extend(("--package", str(args.package.resolve())))
if args.upgrade_from:
command.extend(("--upgrade-from", str(args.upgrade_from.resolve())))
if args.captures:
command.extend(("--captures", str(args.captures.resolve(strict=True))))
if args.short:
command.append("--short")
exit_code = start_isolated(command, desktop)
data = work / "result.json"
if data.is_file():
print(data.read_text(encoding="utf-8"))
elif exit_code == 0:
raise RuntimeError("Isolated Windows process did not publish test evidence")
staged = sum(path.stat().st_size for path in work.rglob("*") if path.is_file())
print(f"Isolated Windows test exit {exit_code}. Removed {staged:,} bytes of temporary QA data.")
return exit_code
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--desktop")
parser.add_argument("--work", type=Path)
parser.add_argument("--package", type=Path)
parser.add_argument("--upgrade-from", type=Path)
parser.add_argument("--captures", type=Path)
parser.add_argument("--short", action="store_true")
args = parser.parse_args()
if args.desktop:
raise SystemExit(child(args))
raise SystemExit(parent(args))

175
tools/build_windows.py Normal file
View File

@@ -0,0 +1,175 @@
"""Freeze, compile and verify the ARM Windows release."""
import argparse
from datetime import datetime, timezone
from hashlib import file_digest
from importlib import metadata
import json
from pathlib import Path
import platform
import re
import shutil
import struct
import subprocess
import sys
from tempfile import TemporaryDirectory
from zipfile import ZIP_DEFLATED, ZipFile
ROOT = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(ROOT))
from arm.version import NAME, VERSION
from arm.branding import (
APPLICATION_ICON, APPLICATION_IMAGE, APPLICATION_LOGO, APP_MODEL_ID, BUNDLED_ASSETS,
COPYRIGHT, DESCRIPTION, INSTALL_ID, PUBLISHER, SUPPORT_URL, WEBSITE,
)
STEM = f"AdaptiveResourceMonitor-{VERSION}-windows-x64"
EXE = "AdaptiveResourceMonitor.exe"
ICON = ROOT / APPLICATION_ICON
VERSION_FILE = """
VSVersionInfo(
ffi=FixedFileInfo(filevers={numbers}, prodvers={numbers}, mask=0x3f,
flags=0, OS=0x40004, fileType=0x1, subtype=0x0, date=(0,0)),
kids=[StringFileInfo([StringTable('040904B0',[
StringStruct('CompanyName', {publisher!r}),
StringStruct('FileDescription', {name!r}),
StringStruct('FileVersion', {version!r}),
StringStruct('InternalName', 'AdaptiveResourceMonitor'),
StringStruct('LegalCopyright', {copyright!r}),
StringStruct('OriginalFilename', {exe!r}),
StringStruct('ProductName', {name!r}),
StringStruct('ProductVersion', {version!r})
])]),VarFileInfo([VarStruct('Translation',[1033,1200])])]
)
"""
def run(args):
result = subprocess.run(args, cwd=ROOT, check=False)
print(f"{Path(args[0]).name} exit code {result.returncode}", flush=True)
result.check_returncode()
def copy_notices(payload):
notices = payload / "Third-party notices"
notices.mkdir()
for package in ("PySide6", "PySide6-Essentials", "PySide6-Addons", "shiboken6", "psutil",
"paramiko", "cryptography", "cffi", "bcrypt", "PyNaCl", "PyInstaller",
"setuptools", "nvidia-ml-py", "invoke", "pycparser"):
try:
distribution = metadata.distribution(package)
except metadata.PackageNotFoundError:
continue
files = [entry for entry in (distribution.files or ())
if ".dist-info" in str(entry) and any(
token in entry.name.lower() for token in ("license", "copying", "notice"))]
for index, entry in enumerate(files):
shutil.copyfile(entry.locate(), notices / f"{package}-{index}-{entry.name}")
python_license = Path(sys.base_prefix) / "LICENSE.txt"
if python_license.is_file():
shutil.copyfile(python_license, notices / "Python-LICENSE.txt")
shutil.copyfile(ROOT / "packaging" / "THIRD_PARTY.md", notices / "README.md")
def digest(path):
with path.open("rb") as stream:
return file_digest(stream, "sha256").hexdigest()
def build_info():
data = {"built_at": datetime.now(timezone.utc).isoformat(timespec="seconds"),
"version": VERSION}
try:
for key, args in (("source_revision", ("rev-parse", "HEAD")),
("source_modified", ("status", "--porcelain"))):
result = subprocess.run(("git", *args), cwd=ROOT, text=True, capture_output=True)
if result.returncode == 0:
value = result.stdout.strip()
data[key] = bool(value) if key == "source_modified" else value
except FileNotFoundError:
pass
return data
def build(compiler, output):
if platform.system() != "Windows" or struct.calcsize("P") != 8 or platform.machine().lower() not in ("amd64", "x86_64"):
raise RuntimeError("Use native x64 Windows Python")
match = re.fullmatch(r"v(\d+)\.(\d+)\.(\d+)\.(\d+)_([a-z]+)", VERSION)
if not match:
raise ValueError("Unexpected ARM version format")
numbers = tuple(int(value) for value in match.groups()[:4])
output.mkdir(parents=True, exist_ok=True)
with TemporaryDirectory(prefix="arm-release-") as temporary:
temporary = Path(temporary)
print(f"Build staging {temporary}", flush=True)
version_file = temporary / "version.txt"
version_file.write_text(
VERSION_FILE.format(numbers=numbers, version=VERSION, name=NAME, exe=EXE,
publisher=PUBLISHER, copyright=COPYRIGHT),
encoding="utf-8",
)
assets = [part for asset in BUNDLED_ASSETS for part in ("--add-data", f"{ROOT / asset};branding")]
run([
sys.executable, "-m", "PyInstaller", "--noconfirm", "--noupx", "--windowed",
"--name", "AdaptiveResourceMonitor", "--paths", str(ROOT),
"--workpath", str(temporary / "work"), "--distpath", str(temporary / "dist"),
"--specpath", str(temporary), "--version-file", str(version_file),
"--manifest", str(ROOT / "packaging" / "windows.manifest"),
"--icon", str(ICON),
*assets,
"--add-data", f"{ROOT / 'arm' / 'providers' / 'linux_probe.sh'};arm/providers",
"--hidden-import", "pynvml", "--exclude-module", "tkinter",
str(ROOT / "monitor.pyw"),
])
payload = temporary / "dist" / "AdaptiveResourceMonitor"
(payload / "VERSION.txt").write_text(VERSION + "\n", encoding="utf-8")
(payload / "BUILD.json").write_text(json.dumps(build_info(), indent=2) + "\n", encoding="utf-8")
for name in ("README.md", "SECURITY.md", "REMOTE_MONITORING.md", "CHANGELOG.md"):
shutil.copyfile(ROOT / name, payload / name)
if (ROOT / "LICENSE.md").is_file():
shutil.copyfile(ROOT / "LICENSE.md", payload / "LICENSE.md")
copy_notices(payload)
setup_id = INSTALL_ID.replace("{", "{{", 1)
run([
str(compiler), "-qp", f"-O{temporary}", f"-DPayload={payload}",
f"-DAppVersion={VERSION}", f"-DFileVersion={'.'.join(map(str, numbers))}",
f"-DProduct={NAME}", f"-DExecutable={EXE}", f"-DAppIcon={ICON}",
f"-DSetupId={setup_id}", f"-DArmPublisher={PUBLISHER}", f"-DArmCopyright={COPYRIGHT}",
f"-DAppWebsite={WEBSITE}", f"-DAppSupport={SUPPORT_URL}", f"-DAppModelId={APP_MODEL_ID}",
f"-DAppDescription={DESCRIPTION}", f"-DWizardImage={ROOT / APPLICATION_IMAGE}",
f"-DWizardEmblem={ROOT / APPLICATION_LOGO}",
str(ROOT / "packaging" / "setup.iss"),
])
zip_path = temporary / f"{STEM}-portable.zip"
with ZipFile(zip_path, "w", ZIP_DEFLATED, compresslevel=6) as package:
for path in sorted(payload.rglob("*")):
if path.is_file():
package.write(path, Path("AdaptiveResourceMonitor") / path.relative_to(payload))
with ZipFile(zip_path) as package:
if package.testzip() is not None:
raise RuntimeError("Portable ZIP integrity check failed")
checksums = []
for source in (temporary / f"{STEM}-setup.exe", zip_path):
expected = digest(source)
destination = output / source.name
copied = destination.with_suffix(destination.suffix + ".tmp")
try:
shutil.copyfile(source, copied)
if digest(copied) != expected:
raise RuntimeError(f"Artifact copy failed verification for {source.name}")
copied.replace(destination)
finally:
copied.unlink(missing_ok=True)
checksums.append(f"{expected} {source.name}")
(output / "SHA256SUMS.txt").write_text("\n".join(checksums) + "\n", encoding="ascii")
for line in checksums:
print(line)
staged_bytes = sum(path.stat().st_size for path in temporary.rglob("*") if path.is_file())
print(f"Removed build staging ({staged_bytes:,} bytes)")
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--iscc", required=True, type=Path, help="Path to Inno Setup 7 ISCC.exe")
parser.add_argument("--output", default=ROOT / "release", type=Path)
args = parser.parse_args()
build(args.iscc.resolve(strict=True), args.output.resolve())