diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 75b9c33..96336bb 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -2,7 +2,7 @@ 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. +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. Totals across devices use readings from the same machine and skip unavailable values. VRAM capacity is a sum over measured devices on that machine. All Systems displays each machine's series separately, and each dynamic tray icon reads a single machine. 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. diff --git a/CHANGELOG.md b/CHANGELOG.md index 5b5431e..e60f998 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,5 +1,17 @@ # Changelog +## v0.4.1.1_alpha — 2026-11-26 + +- Removed Aggregate - Peak and migrated saved selections to All Systems. +- Added an independent Tray icon machine setting, with Local Machine as the default and optional separate icons for individual machines. +- Preserved six independent resource graphs per monitored machine in All Systems, including network IN and OUT. + +## v0.4.0.1_alpha — 2026-11-26 + +- Added independent machine sections in All Systems. +- Added independent network IN and OUT traces, readings and color preferences with a shared throughput scale. +- Fixed immediate persistence of the hover machine and history range across reopen, reconnect and restart. + ## 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. diff --git a/IMPLEMENTATION_REPORT.md b/IMPLEMENTATION_REPORT.md index c5610bb..1cbd5d4 100644 --- a/IMPLEMENTATION_REPORT.md +++ b/IMPLEMENTATION_REPORT.md @@ -1,5 +1,130 @@ # Adaptive Resource Monitor implementation report +## v0.4.1.1_alpha — Independent tray machine + +The Minor counter advanced from 0 to 1. The existing Major, Feature and +Bugfix counters and alpha classification carry forward from v0.4.0.1_alpha. + +The hover monitor, expanded window and Monitor Machine menu offer Local +Machine, individual configured remotes and All Systems. All Systems shows +six independent resource charts for each enabled machine, including separate +network IN and OUT traces. The primary icon reads one source chosen under +Settings → Tray Icon → Tray icon machine. Local Machine is the default. +Optional individual icons honor each remote's tray setting. Overlay, Stacked +and Composite use resources from the icon's machine. The branded Application +Icon is still available in Settings and during initialization. + +Saved legacy Aggregate - Peak monitor selections load as All Systems. Legacy +explicit tray remotes and the separate-icon preference carry forward. If the +legacy consolidated setting supplied the implicit monitor scope, the monitor +opens in All Systems and the tray icon uses Local Machine. The next settings +save writes the current fields. The migration leaves the telemetry and history +formats intact. + +### Acceptance checks + +- All 18 automated model and provider tests passed, including legacy settings, + persisted monitor and tray selections, archived history, directional network + rates and independent collectors. +- Native application checks passed on private Windows desktops at 100% and 150% + Qt scaling. The local computer and two loopback SSH targets each had six + independent All Systems charts. Both remote network charts drew IN and OUT + from their own samples. The test switched the monitor among All Systems, + Local Machine and a different remote while the primary icon continued to + draw from the same configured remote. Separate icons drew from all three + individual sources. New and legacy settings restored the monitor and tray + selections on fresh application instances. +- Verified the portable ZIP CRC and both release-file hashes, x64 executable + headers, embedded icons and brand metadata. The portable executable opened + and shut down twice on a private Windows desktop. +- Tested the installer recipe with the release payload and a disposable AppId. + Installation of v0.4.0.1_alpha, upgrade to v0.4.1.1_alpha and uninstall + each returned 0. The native wizard displayed the release version. All 292 + installed files matched the release payload. The upgraded executable opened + and shut down twice. The test settings, credential reference, trust file and + history fixture survived. The existing installation, startup value, settings + and SSH trust matched their pre-test values. +- Actual Explorer notification-area hover and an in-place production upgrade + remain unverified for this version. The private desktops supplied no Explorer + tray rectangle. Remote validation for this revision used loopback SSH targets. + +### Windows x64 release + +| File | Bytes | SHA-256 | +| --- | ---: | --- | +| [Installer](release/v0.4.1.1_alpha/AdaptiveResourceMonitor-v0.4.1.1_alpha-windows-x64-setup.exe) | 44,507,774 | 5f82d702cb44318c72a2e4bd7053b42f7387785d2978f9ed5ee6915b6b554900 | +| [Portable ZIP](release/v0.4.1.1_alpha/AdaptiveResourceMonitor-v0.4.1.1_alpha-windows-x64-portable.zip) | 58,360,489 | 841b67a14d593f26369983e78f271b550f4a221de7de695adefb0f7567532b95 | + +The [checksum manifest](release/v0.4.1.1_alpha/SHA256SUMS.txt) accompanies both +files. Removed the test installation, staged dependencies and compiler, test +installers and extracted payloads, build intermediates, isolated profiles, +test data and diagnostics. Build and QA staging accounted for **847,063,485 +bytes** of removed files by logical size. Retained the two release packages +and their manifest as deliverables. Earlier releases and historical evidence +remain available. + +## v0.4.0.1_alpha — Simultaneous monitoring + +The Feature counter advanced twice for simultaneous monitoring and +bidirectional network visualization. The Bugfix counter advanced once +for hover selection persistence. The existing collector architecture, +About tab and branding remain in use. + +The production feedback for v0.2.0.0_alpha established native installation, +Explorer hover activation, popup pinning, local telemetry and remote +connections to Linux target A, Linux target B and Linux target C. The checks below cover the new +behavior on a private native Windows desktop. + +| Requirement | Implementation and verification | +| --- | --- | +| Independent simultaneous views | All Systems renders one row of six resource plots per enabled machine in the hover and expanded monitors. Expanded rows have a Measurements control. The private desktop showed Local Machine, Linux target A, Linux target B and Linux target C together, and a smaller popup viewport exercised both scrollbars. | +| Tray modes | Overlay, Stacked, Composite and Application Icon passed native regression checks. | +| Persistent hover selections | The shared machine selection and hover history range write immediately. Native tests covered dismiss and reopen, pin and unpin, opening and closing the expanded window, minimize and restore, an SSH disconnect and reconnect, and a fresh application process restoring All Systems and the five-minute interval. | +| Independent sampling | The collectors already own separate workers and intervals. An automated stalled-SSH test verified a second worker continued collecting. Live checks observed three distinct SSH workers and separate per-machine histories, with a one-second local interval and two-second remote intervals. | +| Network directions | IN is green and OUT is red by default. Both colors are configurable. A network chart uses one throughput scale across both directions, including the individual interface and archived-data views. Tests covered shared auto and fixed spans, Windows interface replacement, Linux interface replacement, reset and reboot, and legacy combined records. Linux target C produced 20 nonzero live samples in each direction during the run. | +| Existing data | Native monitoring used temporary copies of the existing settings and known-hosts files with the existing credential references. Original files passed before-and-after verification. The existing selected local interfaces reported zero traffic during this run. Linux target C showed unavailable GPU and VRAM values. | + +### Resource use with four connected machines + +| View | Sample time | CPU, whole workstation | CPU, one logical processor | Working set | +| --- | ---: | ---: | ---: | ---: | +| Tray | 12 s | 0.269% | 4.297% | 152.11 MiB | +| All Systems hover | 12 s | 0.358% | 5.729% | 159.46 MiB | +| All Systems expanded | 12 s | 0.260% | 4.167% | 162.32 MiB | + +### Native captures + + +### Release verification and cleanup + +All 17 automated tests passed. Native tray and About regression checks also +passed at 150% Qt scaling. The final portable executable opened and shut +down twice on the private desktop. The final setup and executable passed +x64 and embedded icon checks. + +The disposable upgrade used the v0.2.0.0_alpha and v0.4.0.1_alpha frozen +payloads with the release installer recipe and a separate test AppId. +Installation, upgrade and uninstall returned 0. The upgraded installed +executable opened and shut down twice. The settings and original +credential references remained byte-for-byte intact. The copied database +retained its legacy combined reading and received new IN and OUT records. +The production installation and its profile and trust files passed +before-and-after verification. The in-place upgrade and new live Explorer +hover on the active desktop remain production acceptance checks. + +| Final release file | Bytes | SHA-256 | +| --- | ---: | --- | +| Windows x64 installer | 44,510,942 | 14df73209ad422e5a7075a75a03cebbedbc41d5a3f72a26a17382734ccccf571 | +| Windows x64 portable ZIP | 58,362,591 | 753ee08ba4c8b452c56cbc560efd3c19e6cef5e583564f165e8d3269ab28f4a6 | + +Cleanup removed build staging, the compiler and dependencies, test profile +copies, portable extractions, disposable installs and installers, and +interim screenshots. Measured files reclaimed totaled 1,215,378,958 bytes +(1.13 GiB), excluding short-lived unit-test scratch files. The six requested +screenshots, current release and checksum manifest remain. The previous +release packages were retained because v0.2.0.0_alpha is still the +production installation. + ## v0.2.0.0_alpha — Design Creations branding The Feature counter advanced from 1 to 2 for the new About tab and selectable @@ -67,9 +192,9 @@ along with the source, supplied artwork, documentation and maintained tests. | 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. | +| Dynamic Windows tray and Overlay, Stacked, Composite | Implemented using QSystemTrayIcon and QPainter | Resource normalization and per-machine Composite 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. | +| Expanded monitor, ranges and multiple machines | Implemented with resource charts, per-device detail, current and history statistics, connection state and timestamps | History and independent machine 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. | @@ -95,7 +220,7 @@ 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 +icon images and exercised single and separate 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 diff --git a/README.md b/README.md index acac53e..87d14b3 100644 --- a/README.md +++ b/README.md @@ -14,8 +14,19 @@ 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 +appears while monitoring initializes. In Settings → Tray Icon, choose the +machine for the primary icon. It defaults to Local Machine. Enable Separate +machine icons to also show icons for Local Machine and remote targets with +their tray option enabled. + +Monitor Machine selects the history shown in the hover and expanded +monitors. All Systems shows six independent graphs for every enabled +machine. Changing the monitor selection leaves the tray icon source as +configured in Settings. Hover machine and history selections save as you +change them. Network IN and OUT have configurable colors and share one +throughput scale per machine. + +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). diff --git a/REQUIREMENTS.md b/REQUIREMENTS.md index 418875d..86d9625 100644 --- a/REQUIREMENTS.md +++ b/REQUIREMENTS.md @@ -1,7 +1,21 @@ # 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. +## Simultaneous monitoring and visualization -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. +All Systems shows six independent resource graphs for each enabled monitored +machine. The hover and expanded monitors offer Local Machine, configured +remote machines and All Systems. The hover machine and history range +persist immediately and survive a disconnected target. The primary tray +icon has an independent machine setting and defaults to Local Machine. +Optional individual tray icons and the Overlay, Stacked and Composite +visualizations use data from one machine per icon. + +Network plots show independent green receive and red transmit series by +default and share one automatic or fixed throughput scale. Historical +combined readings remain available in detailed measurements. + +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 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 viewed alongside one another in All Systems. 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. diff --git a/TELEMETRY_PROVIDERS.md b/TELEMETRY_PROVIDERS.md index de5085d..cd86ca8 100644 --- a/TELEMETRY_PROVIDERS.md +++ b/TELEMETRY_PROVIDERS.md @@ -32,14 +32,19 @@ 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. +in bytes per second. The IN and OUT traces use one fixed or automatic +scale. The automatic scale considers both series over the displayed history +interval. The SQLite metric schema already supports separate directions. +Existing combined-only readings stay in detailed measurements and leave a +gap in directional plots. Windows GUID and Linux interface-index changes +invalidate the previous counter baseline. Fixed scales are display +references. Automatic throughput scales use the next power of two. -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. +All Systems displays individual histories. Each dynamic tray icon reads +one machine. Its Composite mode highlights the strongest normalized +resource observation and keeps both network traces visible. Amber marks +that machine's connection when it 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), diff --git a/arm/application.py b/arm/application.py index 12841fe..d4bf684 100644 --- a/arm/application.py +++ b/arm/application.py @@ -11,14 +11,14 @@ from time import time import winreg import psutil -from PySide6.QtCore import QLockFile, QObject, Qt, QTimer, QUrl, Signal +from PySide6.QtCore import QLockFile, QObject, QSignalBlocker, Qt, QTimer, QUrl, Signal from PySide6.QtGui import QDesktopServices from PySide6.QtWidgets import QApplication, QDialog, QMessageBox, QSystemTrayIcon from .about import AboutPage from .branding import DARK, LIGHT, PUBLISHER, WEBSITE, application_icon, set_windows_identity from .collect import Collectors -from .config import STATIC_TRAY_MODE, ConfigStore, Target, data_path +from .config import STATIC_TRAY_MODE, ConfigStore, Target, data_path, machine_ids, monitor_choices from .credentials import CredentialStore from .dialogs import ConnectionsDialog, SettingsDialog, TargetDialog from .graphs import Dashboard, tray_icon @@ -81,13 +81,16 @@ class Application(QObject): self.collectors.changed.connect(self.sync_status) self.icons = {} self.menus = {} - self.monitor_machines = {} self.about_page = AboutPage(self.root) self.expanded = Monitor(self.dashboard, True, self.request_archive, self.open_expanded, self.set_pin, self.about_page) self.expanded.setWindowIcon(self.brand_icon) self.popup = Monitor(self.dashboard, False, self.request_archive, self.open_expanded, self.set_pin) - self.hover = HoverMonitor(self.popup, self.dashboard, self.icons, self.tray_machine) + self.hover = HoverMonitor(self.popup, self.dashboard, self.icons) + for view in (self.popup, self.expanded): + view.machine.currentIndexChanged.connect(partial(self.monitor_selected, view)) + self.popup.interval.currentIndexChanged.connect( + lambda _: self.remember_monitor(span=self.popup.span)) self.tray_timer = QTimer(self) self.tray_timer.timeout.connect(self.render) self.hover_timer = QTimer(self) @@ -124,6 +127,7 @@ class Application(QObject): self.sync_icons() self.popup.sync() self.expanded.sync() + self.restore_monitor() self.render() def configure_history(self): @@ -148,32 +152,28 @@ class Application(QObject): self.retired_storage = [db for db in self.retired_storage if db.thread.is_alive()] def apply(self, settings): + if settings.hover_machine and settings.hover_machine not in monitor_choices(settings): + settings = replace(settings, hover_machine="") + if settings.tray_machine not in machine_ids(settings): + settings = replace(settings, tray_machine=LOCAL) self.store.save(settings) - old_default = self.settings.default_machine - old_hover = self.settings.hover_range self.settings = settings self.configure() - if old_default != settings.default_machine: - self.popup.set_machine(settings.default_machine) - self.expanded.set_machine(settings.default_machine) - if old_hover != settings.hover_range: - self.popup.interval.setCurrentIndex(self.popup.interval.findData(settings.hover_range)) self.expanded.archive() LOG.info("Settings updated") def sync_status(self): self.popup.sync() self.expanded.sync() + self.hover.reposition() self.sync_menus() self.refresh_views() def scopes(self): cfg = self.settings - if cfg.tray_mode == "Consolidated": - return [ALL] - if cfg.tray_mode == "Selected remote": - return [cfg.tray_remote] if any(t.identifier == cfg.tray_remote for t in cfg.targets) else [LOCAL] - return [LOCAL] + ([t.identifier for t in cfg.targets if t.tray] if cfg.tray_mode == "Separate" else []) + if not cfg.separate_tray_icons: + return [cfg.tray_machine] + return list(dict.fromkeys((cfg.tray_machine, LOCAL, *(t.identifier for t in cfg.targets if t.tray)))) def sync_icons(self): scopes = self.scopes() @@ -184,7 +184,6 @@ class Application(QObject): icon.setContextMenu(None) icon.deleteLater() self.menus.pop(machine).deleteLater() - self.monitor_machines.pop(machine, None) for machine in scopes: if machine in self.icons: continue @@ -203,17 +202,45 @@ class Application(QObject): if not menu.isVisible(): menu.refresh() - def tray_machine(self, scope): - choices = {ALL, *self.dashboard.machines()} - chosen = self.monitor_machines.get(scope, scope) - return chosen if chosen in choices else scope if scope in choices else LOCAL + def monitor_machine(self): + choices = monitor_choices(self.settings) + return next((choice for choice in (self.settings.hover_machine, self.settings.default_machine) + if choice in choices), LOCAL) + + def restore_monitor(self): + machine = self.monitor_machine() + self.popup.set_machine(machine) + self.expanded.set_machine(machine) + with QSignalBlocker(self.popup.interval): + self.popup.interval.setCurrentIndex(self.popup.interval.findData(self.settings.hover_range)) + self.hover.reposition() + self.sync_menus() + + def monitor_selected(self, view, _index): + self.remember_monitor(machine=view.selected_machine) + + def remember_monitor(self, machine=None, span=None): + changes = {} + if machine in monitor_choices(self.settings) and machine != self.settings.hover_machine: + changes["hover_machine"] = machine + if span is not None and span != self.settings.hover_range: + changes["hover_range"] = span + if not changes: + return + updated = replace(self.settings, **changes) + try: + self.store.save(updated) + except OSError as exc: + self.restore_monitor() + QMessageBox.warning(self.popup, "Monitor selection", str(exc)) + return + # Display preferences need no collector restart or archive reset. + self.settings = self.collectors.settings = updated + self.restore_monitor() def select_machine(self, machine, scope): - self.monitor_machines[scope] = machine - self.expanded.set_machine(machine) + self.remember_monitor(machine=machine) self.hover.show(scope) - self.render() - self.sync_menus() def set_tray_display(self, mode): if mode == self.settings.mode: @@ -228,7 +255,7 @@ class Application(QObject): if reason == QSystemTrayIcon.ActivationReason.Trigger: self.toggle_pin(machine) elif reason == QSystemTrayIcon.ActivationReason.DoubleClick: - self.open_expanded(self.tray_machine(machine)) + self.open_expanded() def toggle_pin(self, machine): self.hover.pin(not self.popup.pinned or self.hover.anchor != machine, machine) @@ -241,14 +268,12 @@ class Application(QObject): def render(self): now = time() for machine, icon in self.icons.items(): - scope = self.tray_machine(machine) - members = self.dashboard.machines() if scope == ALL else (scope,) - initializing = all(self.dashboard.state(member) == Connection.CONNECTING - and member not in self.collectors.last for member in members) + initializing = (self.dashboard.state(machine) == Connection.CONNECTING + and machine not in self.collectors.last) if self.settings.mode == STATIC_TRAY_MODE or initializing: image = self.brand_icon else: - image = tray_icon(self.dashboard, scope, now) + image = tray_icon(self.dashboard, machine, now) if icon.icon().cacheKey() != image.cacheKey(): icon.setIcon(image) @@ -258,8 +283,9 @@ class Application(QObject): view.refresh() def open_expanded(self, machine=None, history=False): - if machine in self.dashboard.machines() or machine == ALL: - self.expanded.set_machine(machine) + if machine not in monitor_choices(self.settings): + machine = self.monitor_machine() + self.expanded.set_machine(machine) if history: index = self.expanded.interval.findData(3600) self.expanded.interval.setCurrentIndex(max(0, index)) @@ -271,12 +297,12 @@ class Application(QObject): if not self.storage: return kind, device = selection - signature = (scope, span, selection) + machines = self.dashboard.monitored() if scope == ALL else [scope] + signature = (scope, span, selection, tuple(machines)) if signature == self.archive_signature: return self.archive_signature = signature self.archive_token += 1 - machines = self.dashboard.machines() if scope == ALL else [scope] keys = {(machine, device, metric) for machine in machines for metric in METRIC_NAMES} if kind: keys.update((machine, TOTAL, metric) for machine in machines for metric in METRIC_NAMES) @@ -286,7 +312,7 @@ class Application(QObject): if token != self.archive_token: return self.dashboard.archived = results - if self.expanded.isVisible(): + if self.expanded.monitor_visible: self.expanded.refresh() def report_history_error(self, message): @@ -504,7 +530,7 @@ def main(): try: controller = Application(app, root) if not controller.settings.minimized: - controller.open_expanded(controller.settings.default_machine) + controller.open_expanded() return app.exec() finally: if controller is not None: diff --git a/arm/config.py b/arm/config.py index b82f8db..e18909f 100644 --- a/arm/config.py +++ b/arm/config.py @@ -6,12 +6,13 @@ from pathlib import Path from dataclasses import asdict, dataclass, field, fields from uuid import uuid4 -from .model import ALL, DISK_MODES, INTERVALS, LOCAL, RANGES, RESOURCES +from .model import ALL, DISK_MODES, INTERVALS, LOCAL, NETWORK, RANGES, RESOURCES LOG = logging.getLogger(__name__) APP_DIR = "Adaptive Resource Monitor" STATIC_TRAY_MODE = "Application Icon" TRAY_MODES = ("Overlay", "Stacked", "Composite", STATIC_TRAY_MODE) +LEGACY_PEAK = "@peak" def data_path(): @@ -57,7 +58,7 @@ class Target: @classmethod def from_dict(cls, source): cfg = cls(**existing_values(cls, source)) - if not isinstance(cfg.identifier, str) or not cfg.identifier or cfg.identifier in (LOCAL, ALL): + if not isinstance(cfg.identifier, str) or not cfg.identifier or cfg.identifier in (LOCAL, ALL, LEGACY_PEAK): cfg.identifier = str(uuid4()) for key in ("name", "host", "username", "key_file", "credential"): if not isinstance(getattr(cfg, key), str): @@ -79,10 +80,11 @@ class Settings: theme: str = "System" default_machine: str = LOCAL mode: str = "Overlay" - tray_mode: str = "Local" - tray_remote: str = "" + tray_machine: str = LOCAL + separate_tray_icons: bool = False resources: list[str] = field(default_factory=lambda: list(RESOURCES)) colors: dict[str, str] = field(default_factory=lambda: {r: info[1] for r, info in RESOURCES.items()}) + network_colors: dict[str, str] = field(default_factory=lambda: {key: value[1] for key, value in NETWORK.items()}) background: str = "#171a22" transparent: bool = False tray_refresh: float = 1 @@ -96,6 +98,7 @@ class Settings: popup_height: int = 330 popup_columns: int = 2 hover_range: int = 60 + hover_machine: str = "" hover_resources: list[str] = field(default_factory=lambda: list(RESOURCES)) local_interval: float = 1 remote_interval: float = 2 @@ -123,14 +126,13 @@ class Settings: for key, choices, fallback in ( ("theme", ("System", "Light", "Dark"), "System"), ("mode", TRAY_MODES, "Overlay"), - ("tray_mode", ("Local", "Selected remote", "Separate", "Consolidated"), "Local"), ("disk_mode", DISK_MODES, "disk.total"), ("log_level", ("DEBUG", "INFO", "WARNING", "ERROR"), "INFO"), ): value = getattr(cfg, key) if not isinstance(value, str) or value not in choices: setattr(cfg, key, fallback) - for key in ("default_machine", "tray_remote", "history_file"): + for key in ("default_machine", "history_file", "hover_machine"): if not isinstance(getattr(cfg, key), str): setattr(cfg, key, getattr(cls(), key)) for key in ("resources", "hover_resources", "gpus", "disks", "interfaces"): @@ -146,12 +148,42 @@ class Settings: setattr(cfg, key, number(getattr(cfg, key), 0, 0, 2**50)) colors = cfg.colors if isinstance(cfg.colors, dict) else {} cfg.colors = {r: valid_color(colors.get(r), info[1]) for r, info in RESOURCES.items()} + network_colors = cfg.network_colors if isinstance(cfg.network_colors, dict) else {} + cfg.network_colors = {key: valid_color(network_colors.get(key), value[1]) + for key, value in NETWORK.items()} cfg.background = valid_color(cfg.background, "#171a22") cfg.targets = [Target.from_dict(item) for item in cfg.targets if isinstance(item, dict)] if isinstance(cfg.targets, list) else [] cfg.targets = list({target.identifier: target for target in cfg.targets}.values()) + legacy_tray = source.get("tray_mode") + if "tray_machine" not in source and legacy_tray == "Selected remote": + cfg.tray_machine = source.get("tray_remote") + if not isinstance(cfg.tray_machine, str) or cfg.tray_machine not in machine_ids(cfg): + cfg.tray_machine = LOCAL + if "separate_tray_icons" not in source: + cfg.separate_tray_icons = legacy_tray == "Separate" + elif not isinstance(cfg.separate_tray_icons, bool): + cfg.separate_tray_icons = False + if cfg.default_machine == LEGACY_PEAK: + cfg.default_machine = ALL + if cfg.hover_machine == LEGACY_PEAK: + cfg.hover_machine = ALL + if cfg.hover_machine not in monitor_choices(cfg): + cfg.hover_machine = "" + # The old consolidated setting selected the all-machine view implicitly + # when neither a saved monitor nor an explicit non-local default existed. + if legacy_tray == "Consolidated" and not cfg.hover_machine and cfg.default_machine == LOCAL: + cfg.hover_machine = ALL return cfg +def machine_ids(settings): + return {LOCAL, *(target.identifier for target in settings.targets)} + + +def monitor_choices(settings): + return machine_ids(settings) | {ALL} + + def valid_color(value, default): if isinstance(value, str) and len(value) == 7 and value.startswith("#"): if all(char in "0123456789abcdef" for char in value[1:].lower()): diff --git a/arm/dialogs.py b/arm/dialogs.py index f5c3da1..c669c63 100644 --- a/arm/dialogs.py +++ b/arm/dialogs.py @@ -11,7 +11,7 @@ from PySide6.QtWidgets import ( ) from .config import TRAY_MODES -from .model import DISK_MODES, LOCAL, RANGES, RESOURCES, Connection +from .model import DISK_MODES, LOCAL, NETWORK, RANGES, RESOURCES, Connection from .views import fill, interval_choices, machine_choices, plain @@ -102,6 +102,7 @@ class SettingsDialog(QDialog): self.controls = {} self.tabs = QTabWidget() self.colors = dict(self.cfg.colors) + self.network_colors = dict(self.cfg.network_colors) self.background = self.cfg.background layout = QVBoxLayout(self) layout.addWidget(self.tabs) @@ -163,10 +164,9 @@ class SettingsDialog(QDialog): def tray(self): form = self.section("Tray Icon") self.select(form, "Visualization", "mode", [(v, v) for v in TRAY_MODES]) - self.select(form, "Machine icons", "tray_mode", - [(v, v) for v in ("Local", "Selected remote", "Separate", "Consolidated")]) - self.select(form, "Selected remote machine", "tray_remote", - [("Choose a target", "")] + [(t.name, t.identifier) for t in self.cfg.targets]) + self.select(form, "Tray icon machine", "tray_machine", + [("Local Machine", LOCAL)] + [(t.name, t.identifier) for t in self.cfg.targets]) + self.check(form, "Separate machine icons", "separate_tray_icons") self.select(form, "Refresh", "tray_refresh", interval_choices()) self.select(form, "History range", "tray_range", [(v, k) for k, v in RANGES.items() if k <= 3600]) self.select(form, "Disk graph", "disk_mode", [(v, k) for k, v in DISK_MODES.items()]) @@ -176,7 +176,9 @@ class SettingsDialog(QDialog): self.resource_choices(form, "Visible resources", "resources") self.check(form, "Transparent background", "transparent") for key, title, color in [("background", "Background", self.background)] + [ - (key, info[0], self.colors[key]) for key, info in RESOURCES.items() + (key, info[0], self.colors[key]) for key, info in RESOURCES.items() if key != "net" + ] + [ + (key, f"Network {direction}", self.network_colors[key]) for key, (direction, _) in NETWORK.items() ]: button = QPushButton(color) button.clicked.connect(lambda _, key=key, button=button: self.choose_color(key, button)) @@ -188,6 +190,8 @@ class SettingsDialog(QDialog): button.setText(color.name()) if key == "background": self.background = color.name() + elif key in NETWORK: + self.network_colors[key] = color.name() else: self.colors[key] = color.name() @@ -247,7 +251,8 @@ class SettingsDialog(QDialog): def save(self): updates = {key: getter() for key, getter in self.controls.items()} - cfg = replace(self.app.settings, **updates, background=self.background, colors=self.colors) + cfg = replace(self.app.settings, **updates, background=self.background, colors=self.colors, + network_colors=self.network_colors) try: self.app.apply(cfg) if self.startup.isChecked() != self.app.startup_enabled(): diff --git a/arm/graphs.py b/arm/graphs.py index 40ad2ef..8a51682 100644 --- a/arm/graphs.py +++ b/arm/graphs.py @@ -5,7 +5,7 @@ from PySide6.QtCore import QPointF, QRectF, QSize, Qt from PySide6.QtGui import QColor, QIcon, QPainter, QPainterPath, QPen, QPixmap from PySide6.QtWidgets import QSizePolicy, QWidget -from .model import ALL, Connection, LOCAL, RESOURCES, TOTAL, current_reading, graph_scale, normalized +from .model import ALL, Connection, LOCAL, NETWORK, RESOURCES, TOTAL, current_reading, graph_scale, normalized METRICS = {kind: d[2] for kind, d in RESOURCES.items()} @@ -14,6 +14,12 @@ def metric_for(kind, settings): return settings.disk_mode if kind == "disk" else METRICS[kind] +def resource_series(kind, settings): + if kind == "net": + return tuple(settings.network_colors.items()) + return ((metric_for(kind, settings), settings.colors[kind]),) + + def selected_resource(machine, kind, settings): return machine == LOCAL or any(target.identifier == machine and kind in target.resources for target in settings.targets) @@ -47,8 +53,8 @@ def bucket_peaks(points, now, span, columns): return result -def across_series(series, now, span, gap, columns): - """Peak per time bin, with identity attached to the winning observation.""" +def composite_samples(series, now, span, gap, columns): + """Pick the strongest resource trace within each time bin of one machine.""" step = max(span / columns, min(gap, span) / 3) size = max(1, int(span / step)) bins = {} @@ -108,9 +114,8 @@ class Dashboard: def machines(self): return [LOCAL] + [target.identifier for target in self.settings.targets] - def members(self, scope, kind): - machines = self.machines() if scope == ALL else [scope] - return [machine for machine in machines if selected_resource(machine, kind, self.settings)] + def monitored(self): + return [LOCAL] + [target.identifier for target in self.settings.targets if target.enabled] def state(self, machine): status = self.collectors.statuses.get(machine) @@ -138,26 +143,24 @@ class Dashboard: candidate = self.collectors.history.last_valid.get(key, candidate) return current_reading(candidate, status, self.interval(machine), now) - def get(self, scope, kind, metric, device, span, now, columns, archive=False): - machines = self.members(scope, kind) - rows = {machine: self.history((machine, device, metric), now - span, archive) - for machine in machines} - scale = plot_scale(metric, self.settings, (value for values in rows.values() for value in values)) - points = {machine: [(item.timestamp, normalized(item, scale)) for item in values] - for machine, values in rows.items()} - gap = max((max(2, self.interval(machine) * 3) for machine in machines), default=3) + def series(self, machine, kind, metrics, device, span, now, archive=False): + """Normalize one machine's resource traces against a shared reference.""" + enabled = selected_resource(machine, kind, self.settings) + histories = { + metric: self.history((machine, device, metric), now - span, archive) if enabled else [] + for metric in metrics + } + scale = plot_scale(metrics[0], self.settings, + (item for values in histories.values() for item in values)) + gap = max(2, self.interval(machine) * 3) if archive: gap = max(gap, span / 1200) - actual = {machine: self.observation(machine, kind, device, metric, now) for machine in machines} - if scope == ALL: - chosen = max((m for m, r in actual.items() if r and r.valid), key=lambda m: actual[m].value, - default=None) - peak = across_series(points, now, span, gap, columns) - chart = [(stamp, value) for stamp, value, _ in peak] - else: - chosen = scope - chart = points.get(scope, []) - return chart, scale, gap, actual.get(chosen), chosen, rows + result = {} + for metric, values in histories.items(): + points = [(item.timestamp, normalized(item, scale)) for item in values] + current = self.observation(machine, kind, device, metric, now) if enabled else None + result[metric] = points, current + return result, scale, gap def paint_tray(painter, size, data, settings, period, now, status): @@ -167,34 +170,41 @@ def paint_tray(painter, size, data, settings, period, now, status): rect = QRectF(1, 1, size - 2, size - 3) if settings.mode == "Stacked" and data: height = rect.height() / len(data) - for index, (kind, points, gap) in enumerate(data): + for index, (traces, gap) in enumerate(data): band = QRectF(rect.x(), rect.y() + height * index, rect.width(), max(1, height - .35)) - shade = QColor(settings.colors[kind]) + shade = QColor(traces[0][2]) shade.setAlpha(63) painter.setPen(QPen(shade, .6)) painter.drawLine(band.bottomLeft(), band.bottomRight()) - stroke(painter, band, points, now, period, gap, settings.colors[kind], .8) + for _, points, color in traces: + stroke(painter, band, points, now, period, gap, color, .8) elif settings.mode == "Composite" and data: - gap = max(gap for _, _, gap in data) - combined = across_series({kind: points for kind, points, _ in data}, now, period, gap, size) + gap = max(gap for _, gap in data) + points = {metric: values for traces, _ in data for metric, values, _ in traces} + colors = {metric: color for traces, _ in data for metric, _, color in traces} + for metric in NETWORK: + if metric in points: + stroke(painter, rect, points[metric], now, period, gap, colors[metric], .7) + combined = composite_samples(points, now, period, gap, size) for left, right in zip(combined, combined[1:]): if left[1] is not None and right[1] is not None and right[0] - left[0] <= gap: stroke(painter, rect, [(left[0], left[1]), (right[0], right[1])], now, period, gap, - settings.colors[right[2]], 1.4) + colors[right[2]], 1.4) isolated = [point for index, point in enumerate(combined) if point[1] is not None and (index == 0 or combined[index - 1][1] is None or point[0] - combined[index - 1][0] > gap)] for stamp, value, kind in isolated: - stroke(painter, rect, [(stamp, value)], now, period, gap, settings.colors[kind], 1.4) + stroke(painter, rect, [(stamp, value)], now, period, gap, colors[kind], 1.4) else: - for kind, points, gap in data: - stroke(painter, rect, points, now, period, gap, settings.colors[kind]) + for traces, gap in data: + for _, points, color in traces: + stroke(painter, rect, points, now, period, gap, color) if status: painter.setPen(QPen(QColor("#151820"), 1)) painter.setBrush(QColor("#ffd06c")) painter.drawEllipse(QRectF(size - 5.5, .5, 5, 5)) -def tray_icon(dashboard, scope, now=None): +def tray_icon(dashboard, machine, now=None): settings = dashboard.settings now = time() if now is None else now period = settings.tray_range @@ -202,13 +212,11 @@ def tray_icon(dashboard, scope, now=None): for kind in RESOURCES: if kind not in settings.resources: continue - chart, _, gap, *_ = dashboard.get(scope, kind, metric_for(kind, settings), TOTAL, period, now, 40) - data.append((kind, chart, gap)) - machines = dashboard.machines() if scope == ALL else [scope] - status = any(dashboard.state(machine) != Connection.ONLINE for machine in machines) - if scope == LOCAL and dashboard.settings.tray_mode == "Local": - status |= any(dashboard.state(machine) in (Connection.RETRYING, Connection.ERROR, Connection.TRUST) - for machine in dashboard.machines() if machine != LOCAL) + series = resource_series(kind, settings) + plots, _, gap = dashboard.series(machine, kind, tuple(metric for metric, _ in series), + TOTAL, period, now) + data.append(([(metric, plots[metric][0], color) for metric, color in series], gap)) + status = dashboard.state(machine) != Connection.ONLINE icon = QIcon() for size in (16, 20, 24, 32, 40, 48): pixmap = QPixmap(size, size) diff --git a/arm/model.py b/arm/model.py index 2d0e039..5c0814a 100644 --- a/arm/model.py +++ b/arm/model.py @@ -7,6 +7,7 @@ from time import time LOCAL = "local" ALL = "@all" TOTAL = "@total" +NETWORK = {"net.receive": ("IN", "#65df79"), "net.transmit": ("OUT", "#ff686b")} INTERVALS = (0.5, 1, 2, 5, 10) RANGES = {30: "30 seconds", 60: "60 seconds", 300: "5 minutes", 900: "15 minutes", 1800: "30 minutes", 3600: "1 hour", 21600: "6 hours", 86400: "1 day", diff --git a/arm/providers/linux_probe.sh b/arm/providers/linux_probe.sh index c1e5eaf..f65f996 100644 --- a/arm/providers/linux_probe.sh +++ b/arm/providers/linux_probe.sh @@ -50,11 +50,12 @@ sample() { dev=${dev//[[:space:]]/} path=/sys/class/net/$dev [[ -d $path ]] || continue - speed= state= physical=0 + speed= state= index= physical=0 [[ ! -e $path/device ]] || physical=1 [[ ! -r $path/operstate ]] || read -r state < "$path/operstate" + [[ ! -r $path/ifindex ]] || read -r index < "$path/ifindex" { [[ ! -r $path/speed ]] || read -r speed < "$path/speed"; } 2>/dev/null - printf 'net\t%s\t%s\t%s\t%s\t%s\n' "$dev" "$physical" "$state" "$speed" "$rest" + printf 'net\t%s\t%s\t%s\t%s\t%s\t%s\n' "$dev" "$physical" "$state" "$speed" "$rest" "$index" done < /proc/net/dev for path in /sys/class/drm/card[0-9]*; do [[ ${path##*/} =~ ^card[0-9]+$ && -r $path/device/vendor ]] || continue diff --git a/arm/providers/native.py b/arm/providers/native.py index 9abc0ad..d74f901 100644 --- a/arm/providers/native.py +++ b/arm/providers/native.py @@ -261,6 +261,6 @@ def interface_info(): count = w.ULONG.from_address(table.value).value rows = (_InterfaceRow * count).from_address(table.value + ct.alignment(_InterfaceRow)) return {row.alias: (bool(row.flags & 1) and row.type in (6, 71), - row.transmit, row.receive) for row in rows} + row.transmit, row.receive, bytes(row.guid)) for row in rows} finally: free(table) diff --git a/arm/providers/ssh.py b/arm/providers/ssh.py index 58833e3..67edd69 100644 --- a/arm/providers/ssh.py +++ b/arm/providers/ssh.py @@ -328,10 +328,10 @@ class LinuxParser: selected("disk", key, key, disk_metrics(read, write, reads, writes, min(100, active / 10) if active is not None else None), not self.target.disks or key in self.target.disks) - for key, physical, state, speed, row in (row for row in sections["net"] if len(row) == 5): + for key, physical, state, speed, row, *identity in (row for row in sections["net"] if len(row) in (5, 6)): v = integers(row, 16) if v: - receive, transmit = counters("net:" + key, (v[0], v[8])) + receive, transmit = counters(("net", key, state, *identity), (v[0], v[8])) link = num(speed) up = state == "up" if state in ("up", "down", "lowerlayerdown", "dormant") else None link = link if link and link > 0 and up else None diff --git a/arm/providers/windows.py b/arm/providers/windows.py index 69f60d6..bd88aba 100644 --- a/arm/providers/windows.py +++ b/arm/providers/windows.py @@ -170,26 +170,34 @@ class Network(Counters): def __init__(self, settings): super().__init__(settings) self.selected = settings.interfaces + self.identities = {} def sample(self): stamp, now = time(), monotonic() rows = psutil.net_io_counters(pernic=True, nowrap=False) or {} stats = psutil.net_if_stats() native = interface_info() - selected = self.selected or [key for key in rows if native.get(key, (False, 0, 0))[0]] + absent = (False, 0, 0, None) + selected = self.selected or [key for key in rows if native.get(key, absent)[0]] + identities = {key: (native.get(key, absent)[3], stats[key].isup if key in stats else None) + for key in rows} def convert(key, row, previous, elapsed): + if self.identities.get(key) != identities[key]: + previous = None values = deltas(row, previous, ("bytes_recv", "bytes_sent"), elapsed, self.interval) stat = stats.get(key) up = stat.isup if stat else None - _, tx_link, rx_link = native.get(key, (False, 0, 0)) + _, tx_link, rx_link, _ = native.get(key, absent) if tx_link in (0, 2**64 - 1): tx_link = (stat.speed * 1e6) if stat and stat.speed > 0 else 0 if rx_link in (0, 2**64 - 1): rx_link = (stat.speed * 1e6) if stat and stat.speed > 0 else 0 return net_metrics(*values, up, rx_link / 1e6 if up else None, tx_link / 1e6 if up else None) - return self.measure(stamp, now, rows, selected, convert) + sample = self.measure(stamp, now, rows, selected, convert) + self.identities = identities + return sample def os_name(): diff --git a/arm/tray.py b/arm/tray.py index c24bb8d..09184da 100644 --- a/arm/tray.py +++ b/arm/tray.py @@ -73,12 +73,12 @@ class HoverState: class HoverMonitor: - def __init__(self, popup, dashboard, icons, monitor_scope): + def __init__(self, popup, dashboard, icons): self.popup, self.dashboard, self.icons = popup, dashboard, icons - self.monitor_scope = monitor_scope self.cursor = NativeCursor() self.state = HoverState() self.anchor = None + self.location = None def tick(self): raw, cursor = self.cursor.raw(), QCursor.pos() @@ -109,7 +109,6 @@ class HoverMonitor: screen = QGuiApplication.screenAt(QCursor.pos()) or QGuiApplication.primaryScreen() if screen is None: return - cfg = self.dashboard.settings screen_rect = screen.geometry() raw, qt = self.cursor.raw(), QCursor.pos() if raw is not None and not raw_rect.isEmpty(): @@ -120,11 +119,17 @@ class HoverMonitor: else: rect = QRect(qt if screen_rect.contains(qt) else screen_rect.center(), QSize(1, 1)) self.anchor = machine - self.popup.set_machine(self.monitor_scope(machine)) - position = place_popup(screen.availableGeometry(), rect, QSize(cfg.popup_width, cfg.popup_height)) - self.popup.setGeometry(position) + self.location = screen, rect + self.reposition() self.popup.show() self.popup.refresh() + self.reposition() + + def reposition(self): + if self.location is not None: + screen, rect = self.location + position = place_popup(screen.availableGeometry(), rect, self.popup.popup_size()) + self.popup.setGeometry(position) def pin(self, value, machine=None): self.popup.pinned = value @@ -132,4 +137,4 @@ class HoverMonitor: self.popup.pin.setChecked(value) self.popup.pin.setText("Unpin" if value else "Pin") if value and (not self.popup.isVisible() or machine is not None): - self.show(machine or self.popup.selected_machine) + self.show(machine or self.anchor or next(iter(self.icons), None)) diff --git a/arm/tray_menu.py b/arm/tray_menu.py index 8399493..67529f0 100644 --- a/arm/tray_menu.py +++ b/arm/tray_menu.py @@ -19,7 +19,7 @@ class TrayMenu(QMenu): self.add_header() self.addSeparator() open_monitor = self.action(self, "Open Resource Monitor", SP.SP_ComputerIcon, - lambda: app.open_expanded(app.tray_machine(scope))) + app.open_expanded) self.setDefaultAction(open_monitor) self.pin = self.action(self, "Pin Resource Monitor", None, lambda: app.toggle_pin(scope)) self.pin.setCheckable(True) @@ -44,7 +44,7 @@ class TrayMenu(QMenu): mode_group.addAction(action) self.modes[mode] = action self.action(self, "Resource History", SP.SP_FileDialogListView, - lambda: app.open_expanded(app.tray_machine(scope), True)) + lambda: app.open_expanded(history=True)) self.addSeparator() targets = self.submenu("Remote Targets", SP.SP_DriveNetIcon) @@ -113,7 +113,7 @@ class TrayMenu(QMenu): } self.remote.menuAction().setVisible(bool(targets)) choices = {LOCAL: self.local, ALL: self.all, **self.remote_entries} - choices[app.tray_machine(self.scope)].setChecked(True) + choices[app.monitor_machine()].setChecked(True) self.modes[app.settings.mode].setChecked(True) self.pin.setChecked(app.popup.pinned and app.hover.anchor == self.scope) self.start.setChecked(app.startup_enabled()) diff --git a/arm/version.py b/arm/version.py index a91450f..944196f 100644 --- a/arm/version.py +++ b/arm/version.py @@ -1,2 +1,2 @@ -VERSION = "v0.2.0.0_alpha" +VERSION = "v0.4.1.1_alpha" NAME = "Adaptive Resource Monitor" diff --git a/arm/views.py b/arm/views.py index eec6e37..c931882 100644 --- a/arm/views.py +++ b/arm/views.py @@ -1,13 +1,14 @@ from time import time, strftime, localtime -from PySide6.QtCore import Qt, QSignalBlocker, QTimer +from PySide6.QtCore import QSize, Qt, QSignalBlocker, QTimer +from PySide6.QtGui import QColor, QPalette from PySide6.QtWidgets import ( QAbstractItemView, QComboBox, QFrame, QGridLayout, QHeaderView, QHBoxLayout, QLabel, - QPushButton, QTableWidget, QTableWidgetItem, QTabWidget, QVBoxLayout, QWidget, + QPushButton, QScrollArea, QSizePolicy, QTableWidget, QTableWidgetItem, QTabWidget, QVBoxLayout, QWidget, ) -from .graphs import Plot, metric_for -from .model import ALL, LOCAL, TOTAL, Connection, INTERVALS, RANGES, RESOURCES, format_value +from .graphs import Plot, resource_series, selected_resource +from .model import ALL, LOCAL, NETWORK, TOTAL, Connection, INTERVALS, RANGES, RESOURCES, format_value METRIC_NAMES = { "cpu.util": "CPU utilization", "cpu.frequency": "Frequency", "cpu.temperature": "CPU temperature", @@ -40,7 +41,7 @@ def fill(combo, values, selected=None): def machine_choices(dashboard): - return [(dashboard.name(machine), machine) for machine in dashboard.machines()] + [("All Systems", ALL)] + return [(dashboard.name(machine), machine) for machine in (*dashboard.machines(), ALL)] def interval_choices(): @@ -74,24 +75,83 @@ def display_value(item): class Card(QFrame): - def __init__(self, resource, detailed): + def __init__(self, resource, detailed, compact=False): super().__init__() self.title = heading(QLabel(RESOURCES[resource][0])) self.value = plain() self.plot = Plot() + self.plot.setAccessibleName(f"{RESOURCES[resource][0]} history") self.footer = plain() self.footer.setWordWrap(True) layout = QVBoxLayout(self) - layout.setContentsMargins(6, 3, 6, 4) - layout.setSpacing(3) + margins = (5, 1, 5, 2) if compact else (6, 3, 6, 4) + layout.setContentsMargins(*margins) + layout.setSpacing(1 if compact else 3) row = QHBoxLayout() row.addWidget(self.title, 0) row.addStretch() - row.addWidget(self.value) - layout.addLayout(row) + self.direction_labels = {} + if resource == "net": + layout.addLayout(row) + self.direction_labels = {metric: plain() for metric in NETWORK} + for label in self.direction_labels.values(): + layout.addWidget(label) + elif compact: + layout.addLayout(row) + layout.addWidget(self.value) + else: + row.addWidget(self.value) + layout.addLayout(row) layout.addWidget(self.plot, 1) layout.addWidget(self.footer) - self.footer.setVisible(detailed) + self.footer.setVisible(detailed and not compact) + if compact: + self.setMinimumWidth(124) + self.plot.setFixedHeight(34 if detailed else 30) + + +def measurements_table(): + table = QTableWidget(0, 6) + table.setHorizontalHeaderLabels(("Metric", "Current", "Minimum", "Maximum", "Average", "Machine / device")) + table.verticalHeader().setVisible(False) + table.setAlternatingRowColors(True) + table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers) + header = table.horizontalHeader() + header.setSectionResizeMode(QHeaderView.ResizeMode.Stretch) + header.setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents) + return table + + +class MachineSection(QFrame): + def __init__(self, expanded, refresh): + super().__init__() + self.setFrameShape(QFrame.Shape.StyledPanel) + self.setSizePolicy(QSizePolicy.Policy.Preferred, QSizePolicy.Policy.Fixed) + self.title = heading(plain()) + self.title.setWordWrap(True) + layout = QVBoxLayout(self) + layout.setContentsMargins(5, 4, 5, 4) + layout.setSpacing(2) + header = QHBoxLayout() + header.addWidget(self.title, 1) + layout.addLayout(header) + self.cards = {kind: Card(kind, detailed=expanded, compact=True) for kind in RESOURCES} + grid = QGridLayout() + grid.setSpacing(3) + for column, card in enumerate(self.cards.values()): + grid.addWidget(card, 0, column) + grid.setColumnStretch(column, 1) + layout.addLayout(grid) + self.table = measurements_table() if expanded else None + if self.table is not None: + self.table.setFixedHeight(185) + layout.addWidget(self.table) + self.table.hide() + details = QPushButton("Measurements") + details.setCheckable(True) + details.toggled.connect(self.table.setVisible) + details.toggled.connect(refresh) + header.addWidget(details) class Monitor(QWidget): @@ -147,17 +207,25 @@ class Monitor(QWidget): layout.setSpacing(4) layout.addLayout(top) layout.addWidget(self.header) - layout.addLayout(self.grid, 3) + self.single = QWidget() + single_layout = QVBoxLayout(self.single) + single_layout.setContentsMargins(0, 0, 0, 0) + single_layout.addLayout(self.grid, 3) + layout.addWidget(self.single, 1) + self.simultaneous = QScrollArea() + self.simultaneous.setWidgetResizable(True) + self.simultaneous.setAccessibleName("Individual machine histories") + groups = QWidget() + self.group_rows = QVBoxLayout(groups) + self.group_rows.setContentsMargins(1, 1, 1, 1) + self.group_rows.setSpacing(4) + self.group_rows.setAlignment(Qt.AlignmentFlag.AlignTop) + self.simultaneous.setWidget(groups) + layout.addWidget(self.simultaneous, 1) + self.sections = {} if expanded: - self.table = QTableWidget(0, 6) - self.table.setHorizontalHeaderLabels(("Metric", "Current", "Minimum", "Maximum", "Average", "Machine / device")) - self.table.verticalHeader().setVisible(False) - self.table.setAlternatingRowColors(True) - self.table.setEditTriggers(QAbstractItemView.EditTrigger.NoEditTriggers) - header = self.table.horizontalHeader() - header.setSectionResizeMode(QHeaderView.ResizeMode.Stretch) - header.setSectionResizeMode(0, QHeaderView.ResizeMode.ResizeToContents) - layout.addWidget(self.table, 2) + self.table = measurements_table() + single_layout.addWidget(self.table, 2) self.resize(900, 690) self.machine.currentIndexChanged.connect(self.sync_devices) self.device.currentIndexChanged.connect(self.selection_changed) @@ -207,10 +275,20 @@ class Monitor(QWidget): def span(self): return self.interval.currentData() or 60 + def popup_size(self): + cfg = self.dashboard.settings + if self.selected_machine != ALL: + return QSize(cfg.popup_width, cfg.popup_height) + # Cap in HoverMonitor against the work area. The scroll area keeps + # six columns together even on a narrow monitor. + rows_height = sum(max(138, section.sizeHint().height()) for section in self.sections.values()) + return QSize(max(cfg.popup_width, 875), max(cfg.popup_height, rows_height + 72)) + def sync_devices(self): if not self.expanded: return machine = self.selected_machine + self.device.setVisible(machine != ALL) devices = self.dashboard.collectors.devices.get(machine, {}) kinds = {"cpu": "CPU", "gpu": "GPU", "disk": "Disk", "net": "Network"} values = [("Selected devices · aggregate", ("", TOTAL))] + [ @@ -223,11 +301,11 @@ class Monitor(QWidget): def sync(self): settings = self.dashboard.settings - fill(self.machine, machine_choices(self.dashboard), self.machine.currentData() or settings.default_machine) + fill(self.machine, machine_choices(self.dashboard), + self.machine.currentData() or settings.hover_machine or settings.default_machine) ranges = [(label, span) for span, label in RANGES.items() if span <= 3600 or (self.expanded and settings.persistent and span <= settings.retention_days * 86400)] - fill(self.interval, ranges, (self.interval.currentData() or - (60 if self.expanded else settings.hover_range))) + fill(self.interval, ranges, (self.interval.currentData() or 60) if self.expanded else settings.hover_range) self.sync_devices() columns = 2 if self.expanded else settings.popup_columns kinds = tuple(self.cards) if self.expanded else tuple( @@ -237,16 +315,38 @@ class Monitor(QWidget): card.setVisible(resource in kinds) for index, kind in enumerate(kinds): self.grid.addWidget(self.cards[kind], index // columns, index % columns) - if not self.expanded: - self.resize(settings.popup_width, settings.popup_height) + self.sync_sections() def set_machine(self, machine): index = self.machine.findData(machine) if index >= 0: - self.machine.setCurrentIndex(index) - self.refresh() + with QSignalBlocker(self.machine): + self.machine.setCurrentIndex(index) + self.sync_devices() + self.sync_sections() + if self.monitor_visible: + self.selection_changed() + + def sync_sections(self): + both = self.selected_machine == ALL + self.single.setVisible(not both) + self.simultaneous.setVisible(both) + if not both: + return + machines = self.dashboard.monitored() + for machine in self.sections.keys() - set(machines): + section = self.sections.pop(machine) + self.group_rows.removeWidget(section) + section.hide() + section.deleteLater() + for index, machine in enumerate(machines): + if machine not in self.sections: + section = MachineSection(self.expanded, self.refresh) + self.sections[machine] = section + self.group_rows.insertWidget(index, section) def selection_changed(self): + self.sync_sections() if self.monitor_visible: self.refresh() self.archive_due.start() @@ -258,81 +358,109 @@ class Monitor(QWidget): def refresh(self): self.sync_devices() now, span, scope = time(), self.span, self.selected_machine - collectors = self.dashboard.collectors cfg = self.dashboard.settings + archive = self.expanded and cfg.persistent if scope == ALL: - online = sum(self.dashboard.state(machine) == Connection.ONLINE for machine in self.dashboard.machines()) - text = f"{online}/{len(self.dashboard.machines())} connected · Peak per resource" - else: - status = collectors.statuses.get(scope) - os_label = collectors.systems.get(scope) or next( - (t.os_type for t in cfg.targets if t.identifier == scope), "") - last = collectors.last.get(scope) - last_text = f" · Last sample {strftime('%H:%M:%S', localtime(last))}" if self.expanded and last else "" - text = f"{os_label} · {self.dashboard.state(scope)} · Sample {self.dashboard.interval(scope):g} s{last_text}" - if status and status.detail: - text += f" · {status.detail}" - if self.expanded: - cpu_name = next((d.name for d in collectors.devices[scope].values() if d.kind == "cpu-info"), "") - if cpu_name: - text += f" · {cpu_name}" + self.sync_sections() + self.refresh_sections(now, span, archive) + return + text = self.scope_status(scope) set_label(self.header, text + f" · Tray {cfg.tray_refresh:g} s") device_kind, selected = self.selection - archive = self.expanded and cfg.persistent for kind, card in self.cards.items(): if not self.expanded and kind not in cfg.hover_resources: continue - metric = metric_for(kind, cfg) selected_device = selected if kind == device_kind or (kind == "vram" and device_kind == "gpu") else TOTAL - chart, scale, gap, current, machine, _ = self.dashboard.get( - scope, kind, metric, selected_device, span, now, max(20, card.plot.width()), archive) - label = display_value(current) - if machine and scope == ALL: - label += f" · {self.dashboard.name(machine)}" - if kind in ("ram", "vram") and scope != ALL: - key = "ram.used" if kind == "ram" else "gpu.vram_used" - actual = collectors.history.latest(scope, selected_device, key) - if actual and actual.valid: - label += f" · {format_value(actual.value, actual.unit)}" - set_label(card.value, label) - card.plot.set_data([(chart, cfg.colors[kind])], now, span, gap) - if self.expanded: - if metric in ("disk.total", "disk.read", "disk.write", "net.total"): - set_label(card.footer, f"Scale {format_value(scale, 'B/s')}") - else: - set_label(card.footer, "0–100%") + self.refresh_card(card, scope, kind, selected_device, now, span, archive) if self.expanded: - self.refresh_table(scope, selected, now, span, archive) + self.refresh_table(self.table, scope, selected, now, span, archive) - def refresh_table(self, scope, device, now, span, archive): + def scope_status(self, scope, concise=False): + collectors = self.dashboard.collectors + cfg = self.dashboard.settings + status = collectors.statuses.get(scope) + os_label = collectors.systems.get(scope) or next( + (t.os_type for t in cfg.targets if t.identifier == scope), "") + last = collectors.last.get(scope) + last_text = f" · Last sample {strftime('%H:%M:%S', localtime(last))}" if self.expanded and last else "" + text = f"{os_label} · {self.dashboard.state(scope)} · Sample {self.dashboard.interval(scope):g} s{last_text}" + if status and status.detail: + text += f" · {status.detail}" + if self.expanded and not concise: + cpu_name = next((d.name for d in collectors.devices[scope].values() if d.kind == "cpu-info"), "") + if cpu_name: + text += f" · {cpu_name}" + return text + + def refresh_sections(self, now, span, archive): + machines = self.dashboard.monitored() + online = sum(self.dashboard.state(machine) == Connection.ONLINE for machine in machines) + set_label(self.header, f"{online}/{len(machines)} connected · Individual machine histories") + for machine in machines: + section = self.sections[machine] + set_label(section.title, f"{self.dashboard.name(machine)} · {self.scope_status(machine, concise=True)}") + for kind, card in section.cards.items(): + self.refresh_card(card, machine, kind, TOTAL, now, span, archive, compact=True) + if section.table is not None and section.table.isVisible(): + self.refresh_table(section.table, machine, TOTAL, now, span, archive) + + def refresh_card(self, card, scope, kind, device, now, span, archive, compact=False): + spec = resource_series(kind, self.dashboard.settings) + plots, scale, gap = self.dashboard.series(scope, kind, tuple(metric for metric, _ in spec), + device, span, now, archive) + lines = [] + for metric, color in spec: + chart, current = plots[metric] + value = display_value(current) + if kind in ("ram", "vram") and not compact: + key = "ram.used" if kind == "ram" else "gpu.vram_used" + extra = self.dashboard.collectors.history.latest(scope, device, key) + if extra and extra.valid: + value += f" · {format_value(extra.value, extra.unit)}" + if kind == "net": + label = card.direction_labels[metric] + set_label(label, f"{NETWORK[metric][0]}: {value}") + foreground = QColor(color) + if card.palette().color(QPalette.ColorRole.Window).lightness() > 150: + foreground = foreground.darker(180) + style = f"color: {foreground.name()};" + if style != label.styleSheet(): + label.setStyleSheet(style) + else: + set_label(card.value, value) + lines.append((chart, color)) + card.plot.set_data(lines, now, span, gap) + rate_plot = kind == "net" or (kind == "disk" and spec[0][0] != "disk.active") + scale_text = f"Scale {format_value(scale, 'B/s')}" if rate_plot else "0–100%" + set_label(card.footer, scale_text) + if card.plot.toolTip() != scale_text: + card.plot.setToolTip(scale_text) + + def refresh_table(self, table, machine, device, now, span, archive): data = [] collectors = self.dashboard.collectors - machines = self.dashboard.machines() if scope == ALL else [scope] - for machine in machines: - device_info = collectors.devices.get(machine, {}).get(device) - label = self.dashboard.name(machine) + (f" · {device_info.name}" if device_info else "") - if scope == ALL: - label += f" · {self.dashboard.state(machine)}" - for metric, title in METRIC_NAMES.items(): - archive_key = (machine, device, metric) - resource = ("vram" if metric.startswith("gpu.vram") else metric.split(".")[0]) - current = self.dashboard.observation(machine, resource, device, metric, now) - if current is None and archive_key not in self.dashboard.archived: - continue - if machine not in self.dashboard.members(scope, resource): - continue - rows = self.dashboard.history(archive_key, now - span, archive) - values = [item.value for item in rows if item.valid] - current_value = display_value(current) - stats = [format_value(value, rows[-1].unit) if values else "—" - for value in ((min(values), max(values), sum(values) / len(values)) if values else (None,) * 3)] - data.append((title, current_value, *stats, label)) - if self.table.rowCount() != len(data): - self.table.setRowCount(len(data)) + device_info = collectors.devices.get(machine, {}).get(device) + label = self.dashboard.name(machine) + (f" · {device_info.name}" if device_info else "") + for metric, title in METRIC_NAMES.items(): + resource = "vram" if metric.startswith("gpu.vram") else metric.split(".")[0] + if not selected_resource(machine, resource, self.dashboard.settings): + continue + archive_key = (machine, device, metric) + current = self.dashboard.observation(machine, resource, device, metric, now) + if current is None and (not archive or archive_key not in self.dashboard.archived): + continue + rows = self.dashboard.history(archive_key, now - span, archive) + values = [item.value for item in rows if item.valid] + current_value = display_value(current) + stats = ([format_value(value, rows[-1].unit) for value in (min(values), max(values), sum(values) / len(values))] + if values else ["—"] * 3) + data.append((title, current_value, *stats, label)) + if table.rowCount() != len(data): + table.setRowCount(len(data)) for row, columns in enumerate(data): for column, value in enumerate(columns): - item = self.table.item(row, column) + item = table.item(row, column) if item is None: - self.table.setItem(row, column, QTableWidgetItem(value)) + table.setItem(row, column, QTableWidgetItem(value)) elif item.text() != value: item.setText(value) diff --git a/tests/ssh_fixture.py b/tests/ssh_fixture.py index 6ac4075..94a94de 100644 --- a/tests/ssh_fixture.py +++ b/tests/ssh_fixture.py @@ -51,9 +51,10 @@ class Auth(paramiko.ServerInterface): class Fixture: - def __init__(self, *, key=None, drop_first=False, public=None): + def __init__(self, *, key=None, drop_first=False, public=None, gate=None): self.key = key or paramiko.RSAKey.generate(2048) self.drop_first, self.public = drop_first, public + self.gate = gate self.listener = socket.socket() self.listener.bind(("127.0.0.1", 0)) self.listener.listen() @@ -115,6 +116,11 @@ class Fixture: if self.drop_first and self.samples == 1: transport.close() break + if self.gate is not None: + while not self.stop.is_set() and not self.gate.wait(.05): + pass + if self.stop.is_set(): + 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): diff --git a/tests/test_model.py b/tests/test_model.py index ce65cdb..f3fc5ef 100644 --- a/tests/test_model.py +++ b/tests/test_model.py @@ -1,12 +1,13 @@ +import json import tempfile from pathlib import Path from types import SimpleNamespace import unittest -from arm.config import ConfigStore, Settings, Target +from arm.config import ConfigStore, Settings, Target, monitor_choices from arm.credentials import CredentialStore -from arm.graphs import Dashboard, across_series -from arm.model import (ALL, LOCAL, TOTAL, Availability, Connection, History, Status, +from arm.graphs import Dashboard, composite_samples +from arm.model import (ALL, LOCAL, NETWORK, 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 @@ -49,22 +50,29 @@ class ModelTests(unittest.TestCase): 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): + def test_composite_picks_the_strongest_resource_sample(self): + series = {"ram": [(15, 80), (29, None)], "cpu": [(15, 10), (29, 90)]} + self.assertEqual(composite_samples(series, 30, 30, 3, 25), + [(15, 80, "ram"), (29, 90, "cpu")]) + + def test_network_directions_share_scale_within_each_machine(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)}, + settings = Settings(targets=[target]) + coll = SimpleNamespace(settings=settings, history=History(), + statuses={m: Status(m, Connection.ONLINE) for m in (LOCAL, target.identifier)}, 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")) + for machine, rx, tx in ((LOCAL, 6144, 1024), (target.identifier, 2048, 4096)): + coll.history.add(readings(machine, 28, TOTAL, {"net.total": (2**30, "B/s")})) + coll.history.add(readings(machine, 29, TOTAL, + {"net.receive": (rx, "B/s"), "net.transmit": (tx, "B/s")})) + for machine, expected in ((LOCAL, (75, 12.5)), (target.identifier, (50, 100))): + directions, scale, _ = view.series(machine, "net", tuple(NETWORK), TOTAL, 30, 30) + self.assertEqual(tuple(directions[key][0][0][1] for key in NETWORK), expected) + self.assertEqual(scale, 4096 if machine == target.identifier else 8192) + self.assertTrue(all(directions[key][1].machine == machine for key in NETWORK)) + settings.net_scale = 16384 + self.assertEqual(view.series(target.identifier, "net", tuple(NETWORK), TOTAL, 30, 30)[1], 16384) def test_hover_and_taskbar_edges(self): state = HoverState() @@ -89,10 +97,51 @@ class ModelTests(unittest.TestCase): store.save(cfg) self.assertEqual(store.load(), cfg) cfg.mode = "Application Icon" + cfg.hover_range = 300 + cfg.hover_machine = cfg.targets[0].identifier + cfg.network_colors["net.receive"] = "#008801" store.save(cfg) self.assertEqual(store.load(), cfg) + cfg.tray_machine = cfg.targets[0].identifier + cfg.separate_tray_icons = True + for selection in (ALL, LOCAL, cfg.targets[0].identifier): + cfg.hover_machine = selection + store.save(cfg) + self.assertEqual(store.load(), cfg) + cfg.hover_machine = "removed-host" + store.save(cfg) + self.assertEqual(store.load().hover_machine, "") self.assertNotIn('"password":', path.read_text(encoding="utf-8").lower()) + def test_legacy_machine_preferences_migrate(self): + source = { + "default_machine": "@peak", "hover_machine": "@peak", "hover_range": 300, + "tray_mode": "Selected remote", "tray_remote": "remote-1", "mode": "Composite", + "persistent": True, "network_colors": {"net.receive": "#008801"}, + "targets": [{"identifier": "remote-1", "name": "Test host", "credential": "test-reference"}], + } + with tempfile.TemporaryDirectory(prefix="arm-config-test-") as root: + path = Path(root) / "settings.json" + path.write_text(json.dumps(source), encoding="utf-8") + store = ConfigStore(path) + cfg = store.load() + self.assertEqual((cfg.default_machine, cfg.hover_machine, cfg.hover_range), (ALL, ALL, 300)) + self.assertEqual((cfg.tray_machine, cfg.separate_tray_icons, cfg.mode), ("remote-1", False, "Composite")) + self.assertEqual(monitor_choices(cfg), {LOCAL, ALL, "remote-1"}) + self.assertEqual(cfg.targets[0].credential, "test-reference") + self.assertEqual(cfg.network_colors["net.receive"], "#008801") + self.assertTrue(cfg.persistent) + store.save(cfg) + saved = json.loads(path.read_text(encoding="utf-8")) + self.assertTrue({"tray_mode", "tray_remote"}.isdisjoint(saved)) + self.assertEqual(store.load(), cfg) + for legacy_tray, monitor, separate in (("Consolidated", ALL, False), ("Separate", "", True)): + cfg = Settings.from_dict({"tray_mode": legacy_tray}) + self.assertEqual((cfg.tray_machine, cfg.hover_machine, cfg.separate_tray_icons), + (LOCAL, monitor, separate)) + for invalid_source in (ALL, "@peak", "removed-host", []): + self.assertEqual(Settings.from_dict({"tray_machine": invalid_source}).tray_machine, LOCAL) + def test_real_credential_namespace_and_roundtrip(self): vault = CredentialStore() ref = vault.save("ARM unit test", "Test-only µ password") diff --git a/tests/test_providers.py b/tests/test_providers.py index 82e428e..5bff248 100644 --- a/tests/test_providers.py +++ b/tests/test_providers.py @@ -1,15 +1,20 @@ from pathlib import Path +from contextlib import ExitStack from queue import Queue from tempfile import TemporaryDirectory -from time import sleep, time +from threading import Event +from time import monotonic, sleep, time +from types import SimpleNamespace import unittest +from unittest.mock import patch import paramiko +from PySide6.QtCore import QCoreApplication -from arm.collect import Worker, problem +from arm.collect import Collectors, 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.model import Connection, LOCAL, NETWORK, 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 @@ -51,6 +56,68 @@ class Providers(unittest.TestCase): reset, _ = parser.parse(FRAME.format(boot=2, busy=400), 12, 12) self.assertIsNone(reading(reset, "disk.read").value) + def test_directional_deltas_skip_reboot_reset_and_interface_replacement(self): + def frame(boot, rx, tx, index): + lines = FRAME.format(boot=boot, busy=300).splitlines() + return "\n".join(f"net\teth0\t1\tup\t10000\t{rx} 0 0 0 0 0 0 0 {tx} 0 0 0 0 0 0 0\t{index}" + if line.startswith("net\teth0\t") else line for line in lines) + + parser = LinuxParser(Target(interval=1)) + for stamp, counters, expected in ( + (1, (1, 100, 200, 2), (None, None)), + (2, (1, 130, 275, 2), (30, 75)), + (3, (1, 20, 280, 2), (None, 5)), + (4, (1, 19000, 81000, 5), (None, None)), + (5, (1, 19010, 81005, 5), (10, 5)), + (6, (2, 40000, 82000, 5), (None, None)), + ): + sample, _ = parser.parse(frame(*counters), stamp, stamp) + self.assertEqual(tuple(reading(sample, metric, "eth0").value for metric in NETWORK), expected) + + def test_windows_directional_deltas_rebaseline_replaced_interface(self): + sampler = Network(Settings(local_interval=1, interfaces=["Ethernet"])) + samples = [{"Ethernet": SimpleNamespace(bytes_recv=rx, bytes_sent=tx)} + for rx, tx in ((100, 200), (150, 215), (90000, 100000), (90010, 100040))] + adapters = [{"Ethernet": (True, 1_000_000, 1_000_000, guid)} for guid in (b"a", b"a", b"b", b"b")] + with patch("arm.providers.windows.psutil.net_io_counters", side_effect=samples), \ + patch("arm.providers.windows.psutil.net_if_stats", return_value={"Ethernet": SimpleNamespace(isup=True)}), \ + patch("arm.providers.windows.interface_info", side_effect=adapters), \ + patch("arm.providers.windows.monotonic", side_effect=(1, 2, 3, 4)): + for expected in ((None, None), (50, 15), (None, None), (10, 40)): + packet = sampler.sample() + for device in (TOTAL, "Ethernet"): + self.assertEqual(tuple(reading(packet, metric, device).value for metric in NETWORK), expected) + + def test_collectors_sample_independently_while_another_machine_is_stalled(self): + app = QCoreApplication.instance() or QCoreApplication([]) + gate = Event() + with TemporaryDirectory(prefix="arm-ssh-test-") as root, ExitStack() as stack: + slow = stack.enter_context(Fixture(gate=gate)) + fast = stack.enter_context(Fixture()) + path = Path(root) / "known_hosts" + targets = [] + for server, interval in ((slow, 1), (fast, .5)): + targets.append(Target(host="127.0.0.1", port=server.port, username="tester", + timeout=8, interval=interval)) + update_host_key(path, f"[127.0.0.1]:{server.port}", server.key) + collectors = Collectors(Settings(targets=targets), Secret(), path) + try: + with patch("arm.collect.LOCAL_PROVIDERS", ()): + collectors.start() + deadline = monotonic() + 5 + while monotonic() < deadline and (fast.samples < 3 or not slow.samples): + app.processEvents() + sleep(.025) + app.processEvents() + self.assertGreaterEqual(fast.samples, 3) + self.assertGreaterEqual(slow.samples, 1) + self.assertNotIn(targets[0].identifier, collectors.last) + self.assertIn(targets[1].identifier, collectors.last) + self.assertEqual([collectors.intervals[t.identifier] for t in targets], [1, .5]) + finally: + collectors.close() + gate.set() + 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" @@ -129,14 +196,19 @@ class Providers(unittest.TestCase): stamp = time() replies, errors = Queue(), Queue() key = (LOCAL, TOTAL, "cpu.util") + legacy = (LOCAL, TOTAL, "net.total") + directions = [(LOCAL, TOTAL, metric) for metric in NETWORK] 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.record(readings(LOCAL, stamp, TOTAL, {"cpu.util": (31, "%"), "net.total": (800, "B/s")})) 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.request(1, [key, legacy, *directions], stamp - 1) + records = replies.get(timeout=5)[1] + self.assertEqual(records[key][0].value, 31) + self.assertEqual(records[legacy][0].value, 800) + self.assertTrue(all(not records[direction] for direction in directions)) next_db.send("clear", 2) self.assertEqual(replies.get(timeout=5), (2, {})) next_db.request(3, [key], stamp - 1) diff --git a/tests/windows_gui.py b/tests/windows_gui.py index 394e24d..91ec5f4 100644 --- a/tests/windows_gui.py +++ b/tests/windows_gui.py @@ -234,7 +234,7 @@ def run_installer_wizard(args, result, captures=None): return code -def validate_packages(release, work, result, upgrade_from=None, captures=None): +def validate_packages(release, work, result, upgrade_from=None, captures=None, portable_only=False): from arm.about import UNINSTALL_KEY from arm.branding import BUNDLED_ASSETS, PUBLISHER, SUPPORT_URL, WEBSITE, asset from arm.config import ConfigStore, Settings, Target @@ -263,6 +263,8 @@ def validate_packages(release, work, result, upgrade_from=None, captures=None): verify_executable(payload / exe, VERSION) result["verified_pe_icons_and_company_metadata"] = True run_frozen(payload / exe, work / "portable-profile", result) + if portable_only: + return import winreg key = UNINSTALL_KEY @@ -435,7 +437,7 @@ def evaluate_app(work, results, short=False, captures=None): 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.model import ALL, LOCAL, NETWORK, TOTAL, Connection, RESOURCES from arm.providers.ssh import update_host_key from ssh_fixture import Fixture, SECRET from contextlib import ExitStack @@ -547,7 +549,7 @@ def evaluate_app(work, results, short=False, captures=None): prefs.deleteLater() connections.deleteLater() with ExitStack() as stack: - servers = [stack.enter_context(Fixture()) for _ in range(1 if short else 2)] + servers = [stack.enter_context(Fixture()) for _ in range(2)] targets = [] for i, server in enumerate(servers, 1): target = Target(name=f"Loopback {i}", host="127.0.0.1", port=server.port, @@ -562,30 +564,79 @@ def evaluate_app(work, results, short=False, captures=None): 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 + menu.remote_entries[target.identifier].trigger() assert session.popup.selected_machine == target.identifier + assert session.scopes() == [LOCAL] 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)) + from arm.graphs import tray_icon + primary, other = (target.identifier for target in targets) + prefs = SettingsDialog(session) + tray_machine = prefs.controls["tray_machine"].__self__ + assert [tray_machine.itemData(i) for i in range(tray_machine.count())] == [LOCAL, primary, other] + tray_machine.setCurrentIndex(tray_machine.findData(primary)) + prefs.save() + prefs.deleteLater() + assert session.scopes() == [primary] and session.popup.selected_machine == LOCAL + menu = session.menus[primary] + for select, expected in ((menu.all, ALL), (menu.remote_entries[other], other), (menu.local, LOCAL)): + select.trigger() + with patch("arm.application.tray_icon", wraps=tray_icon) as draw: + session.render() + assert [call.args[1] for call in draw.call_args_list] == [primary] + assert session.popup.selected_machine == session.expanded.selected_machine == expected + assert select.isChecked() + if expected == ALL: + for view in (session.popup, session.expanded): + assert set(view.sections) == {LOCAL, primary, other} + assert all(set(section.cards) == set(RESOURCES) for section in view.sections.values()) + menu.all.trigger() + history = session.collectors.history + wait_for(lambda: all( + (reading := history.latest(machine, TOTAL, direction)) and reading.valid and reading.value > 0 + for machine in (primary, other) for direction in NETWORK + )) + session.popup.refresh() + for machine in (primary, other): + card = session.popup.sections[machine].cards["net"] + for direction, (points, _) in zip(NETWORK, card.plot.data[0]): + latest = history.latest(machine, TOTAL, direction) + assert any(stamp == latest.timestamp and value > 0 for stamp, value in points if value is not None) + assert card.direction_labels[direction].text().startswith(NETWORK[direction][0] + ":") + results["independent_network_directions"] = True + session.popup.interval.setCurrentIndex(session.popup.interval.findData(300)) + session.popup.hide() + menu.defaultAction().trigger() + assert session.expanded.selected_machine == ALL + session.expanded.close() + session.hover.show(primary) + assert session.popup.selected_machine == ALL and session.popup.span == 300 + saved = ConfigStore(root / "settings.json").load() + assert (saved.hover_machine, saved.hover_range, saved.tray_machine) == (ALL, 300, primary) + session.popup.hide() + session.apply(replace(session.settings, separate_tray_icons=True, persistent=True)) assert set(session.icons) == {LOCAL, *(target.identifier for target in targets)} + with patch("arm.application.tray_icon", wraps=tray_icon) as draw: + session.render() + assert {call.args[1] for call in draw.call_args_list} == {LOCAL, primary, other} + assert draw.call_count == 3 + results["independent_tray_and_monitor"] = "Local plus two SSH targets, six graphs each, three independent icon sources" 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)) + assert session.popup.selected_machine == ALL + session.apply(replace(session.settings, separate_tray_icons=False, persistent=False)) if not short: measure("disconnected_remotes") - session.apply(replace(session.settings, tray_mode="Consolidated")) - assert len(session.icons) == 1 + assert set(session.icons) == {primary} for target in list(session.settings.targets): session.remove_target(target) + assert set(session.icons) == {LOCAL} and session.popup.selected_machine == ALL 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) @@ -597,13 +648,32 @@ def evaluate_app(work, results, short=False, captures=None): 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 + restart_root = work / "restart" + store = ConfigStore(restart_root / "settings.json") + stored_targets = [replace(target, enabled=False, credential="test-reference") for target in saved.targets] + store.save(replace(saved, targets=stored_targets)) + for legacy in (False, True): + if legacy: + source = json.loads(store.path.read_text(encoding="utf-8")) + source.update(hover_machine="@peak", default_machine="@peak") + store.path.write_text(json.dumps(source), encoding="utf-8") + reopened = Application(app, restart_root) + try: + assert reopened.scopes() == [primary] + assert reopened.popup.selected_machine == reopened.expanded.selected_machine == ALL + assert reopened.popup.span == 300 and not reopened.popup.pinned + assert reopened.settings.targets == stored_targets + finally: + reopened.close() + app.processEvents() + results["restored_monitor_and_tray"] = "New and legacy settings restored All Systems at five minutes with a separate tray source" 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) + validate_packages(args.package, args.work, result, args.upgrade_from, args.captures, args.portable_only) else: evaluate_app(args.work, result, args.short, args.captures) except Exception: @@ -629,6 +699,8 @@ def parent(args): command = [sys.executable, str(Path(__file__).resolve()), "--desktop", desktop, "--work", str(work)] if args.package: command.extend(("--package", str(args.package.resolve()))) + if args.portable_only: + command.append("--portable-only") if args.upgrade_from: command.extend(("--upgrade-from", str(args.upgrade_from.resolve()))) if args.captures: @@ -651,6 +723,7 @@ if __name__ == "__main__": parser.add_argument("--desktop") parser.add_argument("--work", type=Path) parser.add_argument("--package", type=Path) + parser.add_argument("--portable-only", action="store_true") parser.add_argument("--upgrade-from", type=Path) parser.add_argument("--captures", type=Path) parser.add_argument("--short", action="store_true") diff --git a/tests/windows_simultaneous.py b/tests/windows_simultaneous.py new file mode 100644 index 0000000..7336b7f --- /dev/null +++ b/tests/windows_simultaneous.py @@ -0,0 +1,262 @@ +"""Run ARM against a private copy of authorized settings on a Windows desktop.""" +import argparse +from dataclasses import replace +from hashlib import sha256 +import json +from pathlib import Path +import shutil +import sys +from tempfile import TemporaryDirectory +from time import monotonic, time +from types import SimpleNamespace +from unittest.mock import patch +from uuid import uuid4 + +from windows_gui import start_isolated, verify_desktop + + +def evaluate(root, captures, restart, result): + import psutil + from PySide6.QtCore import QEventLoop, QPoint, QTimer + from PySide6.QtWidgets import QApplication + from arm.application import Application + from arm.branding import set_windows_identity + from arm.config import ConfigStore + from arm.graphs import resource_series, tray_icon + from arm.model import ALL, LOCAL, NETWORK, RESOURCES, TOTAL, Connection + + assert set_windows_identity() == 0 + app = QApplication([]) + assert app.platformName() == "windows" + app.setQuitOnLastWindowClosed(False) + session = Application(app, root) + proc = psutil.Process() + + def wait(seconds, condition=None): + if condition and condition(): + return + loop = QEventLoop() + timer = QTimer() + timer.setInterval(100) + if condition: + timer.timeout.connect(lambda: loop.quit() if condition() else None) + timer.start() + QTimer.singleShot(round(seconds * 1000), loop.quit) + loop.exec() + timer.stop() + if condition and not condition(): + state = {session.dashboard.name(m): str(session.dashboard.state(m)) + for m in session.dashboard.monitored()} + raise AssertionError(f"Readings not ready: {state}") + + def choose(value): + index = session.popup.machine.findData(value) + assert index >= 0 + session.popup.machine.setCurrentIndex(index) + + def measure(name, seconds=12): + before, start = proc.cpu_times(), monotonic() + wait(seconds) + after, duration = proc.cpu_times(), monotonic() - start + percent = (after.user + after.system - before.user - before.system) / duration * 100 + result.setdefault("overhead", {})[name] = { + "seconds": round(duration, 2), "cpu_one_thread_pct": round(percent, 3), + "cpu_workstation_pct": round(percent / psutil.cpu_count(), 3), + "working_set_mib": round(proc.memory_info().rss / 2**20, 2), + } + + def capture(widget, filename): + app.processEvents() + if captures: + assert widget.grab().save(str(captures / (filename + ".png"))) + + try: + primary = session.scopes()[0] + machines = session.dashboard.monitored() + assert len(machines) == 4 + if restart: + assert session.settings.hover_machine == ALL and session.settings.hover_range == 300 + session.hover.show(primary) + assert session.popup.selected_machine == ALL and session.popup.span == 300 + assert not session.popup.pinned + wait(30, lambda: all(session.dashboard.state(m) == Connection.ONLINE for m in machines)) + history = session.collectors.history + key = lambda m, metric: history.since(m, TOTAL, metric, time() - 60) + wait(17, lambda: all(sum(r.valid for r in key(m, "ram.util")) >= 3 for m in machines)) + result["machines"] = { + session.dashboard.name(m): { + "interval": session.dashboard.interval(m), + "ram_observations": len(key(m, "ram.util")), + "network_rx_observations": len(key(m, "net.receive")), + "network_tx_observations": len(key(m, "net.transmit")), + } for m in machines + } + assert len({session.collectors.workers[m, "Linux SSH"].ident for m in machines if m != LOCAL}) == 3 + if restart: + assert len(session.popup.sections) == 4 + capture(session.popup, "06-restored-selection") + result["restored_selection"] = "All Systems, 5 minutes, unpinned" + return + + measure("tray, four connected machines") + session.hover.show(primary) + choose(LOCAL) + session.popup.refresh() + assert session.popup.single.isVisible() + assert all(card.isVisible() for card in session.popup.cards.values()) + assert [(session.popup.grid.getItemPosition(i)[0], session.popup.grid.getItemPosition(i)[1]) + for i in range(6)] == [(0, 0), (0, 1), (1, 0), (1, 1), (2, 0), (2, 1)] + capture(session.popup, "01-individual-hover") + + menu = session.menus[primary] + icon_count = len(session.icons) + menu.all.trigger() + assert menu.all.isChecked() and len(session.icons) == icon_count + with patch("arm.application.tray_icon", wraps=tray_icon) as draw: + session.render() + assert {call.args[1] for call in draw.call_args_list} == set(session.icons) + section_keys = set(session.popup.sections) + assert section_keys == set(machines) + for machine, section in session.popup.sections.items(): + assert session.dashboard.name(machine) in section.title.text() + assert "Connected" in section.title.text() and set(section.cards) == set(RESOURCES) + cpu_plot = section.cards["cpu"].plot.data[0][0][0] + cpu_samples = key(machine, "cpu.util") + valid = {r.timestamp for r in cpu_samples if r.valid} + assert set(t for t, v in cpu_plot if v is not None) <= valid + assert app.primaryScreen().availableGeometry().contains(session.popup.frameGeometry()) + capture(session.popup, "02-all-systems-hover") + assert session.popup.simultaneous.verticalScrollBar().maximum() == 0 + geometry = session.popup.geometry() + session.popup.resize(680, 280) + app.processEvents() + assert session.popup.simultaneous.verticalScrollBar().maximum() > 0 + assert session.popup.simultaneous.horizontalScrollBar().maximum() > 0 + session.popup.setGeometry(geometry) + measure("All Systems hover, four connected machines") + + session.popup.hide() + session.open_expanded() + assert session.expanded.selected_machine == ALL and set(session.expanded.sections) == set(machines) + capture(session.expanded, "04-all-systems-expanded") + assert session.expanded.simultaneous.horizontalScrollBar().maximum() == 0 + assert session.expanded.simultaneous.verticalScrollBar().maximum() == 0 + section = session.expanded.sections[LOCAL] + section.table.show() + session.expanded.refresh() + assert section.table.rowCount() > 20 + section.table.hide() + measure("All Systems expanded, four connected machines") + session.expanded.showMinimized() + session.expanded.showNormal() + assert session.expanded.selected_machine == ALL + session.expanded.close() + + session.hover.show(primary) + def directional_sources(): + return [machine for machine in machines if all( + any(r.valid and r.value > 0 for r in key(machine, metric)) + and len({r.value for r in key(machine, metric) if r.valid}) > 1 + for metric in NETWORK)] + + wait(20, directional_sources) + available = directional_sources() + loaded = [machine for machine in available if all((r := history.latest(machine, TOTAL, metric)) + and r.valid and r.value > 0 for metric in NETWORK)] + source = (loaded or available)[-1] + choose(source) + session.popup.refresh() + net = session.popup.cards["net"] + assert [color for _, color in net.plot.data[0]] == [color for _, color in resource_series("net", session.settings)] + assert all(any(value is not None and value > 0 for _, value in points) + for points, _ in net.plot.data[0]) + result["directional_activity_machine"] = session.dashboard.name(source) + result["directional_activity"] = { + metric: {"nonzero_samples": sum(r.valid and r.value > 0 for r in key(source, metric)), + "distinct_rates": len({r.value for r in key(source, metric) if r.valid})} + for metric in NETWORK + } + capture(session.popup, "05-network-in-out") + + chosen = machines[1] + choose(chosen) + session.collectors.disconnect(chosen) + assert session.popup.selected_machine == chosen and "Disconnected" in session.popup.header.text() + assert ConfigStore(root / "settings.json").load().hover_machine == chosen + session.collectors.reconnect(chosen) + wait(25, lambda: session.dashboard.state(chosen) == Connection.ONLINE) + assert session.popup.selected_machine == chosen + choose(ALL) + session.popup.interval.setCurrentIndex(session.popup.interval.findData(300)) + session.set_pin(True) + session.set_pin(False) + outside = QPoint(-20000, -20000) + # Exercise the production dismissal handler. Explorer has no icon + # rectangle on the private desktop. + with patch("arm.tray.QCursor", SimpleNamespace(pos=lambda: outside)), \ + patch.object(session.hover.cursor, "raw", return_value=outside), \ + patch("arm.tray.monotonic", side_effect=[100, 120]): + session.hover.state.left = None + session.hover.tick() + session.hover.tick() + assert session.popup.isHidden() + session.hover.show(primary) + assert session.popup.selected_machine == ALL and session.popup.span == 300 + assert session.expanded.selected_machine == ALL + saved = ConfigStore(root / "settings.json").load() + assert saved.hover_machine == ALL and saved.hover_range == 300 + result["retained_dismissal_pin_disconnect"] = True + finally: + session.close() + + +def main(args): + if args.desktop: + result = {"desktop": verify_desktop(args.desktop)} + try: + evaluate(args.work, args.captures, args.restart, result) + except Exception: + import traceback + result["traceback"] = traceback.format_exc() + return 1 + finally: + (args.work / "result.json").write_text(json.dumps(result, indent=2), encoding="utf-8") + return 0 + names = ("settings.json", "known_hosts") + sources = [args.profile_dir / name for name in names] + hash_inputs = lambda: [sha256(path.read_bytes()).digest() for path in sources] + initial = hash_inputs() + with TemporaryDirectory(prefix="arm-desktop-test-") as directory: + work = Path(directory) + for source in sources: + shutil.copyfile(source, work / source.name) + from arm.config import ConfigStore + store = ConfigStore(work / "settings.json") + original = store.load() + store.save(replace(original, persistent=False, history_file="")) + for restart in (False, True): + desktop = f"ARM_Validation_{uuid4().hex[:10]}" + command = [sys.executable, str(Path(__file__).resolve()), "--desktop", desktop, "--work", str(work)] + if args.captures: + command.extend(("--captures", str(args.captures.resolve(strict=True)))) + if restart: + command.append("--restart") + code = start_isolated(command, desktop) + print((work / "result.json").read_text(encoding="utf-8")) + if code: + break + assert store.load().targets == original.targets + assert hash_inputs() == initial, "Production profile files changed" + removed = sum(path.stat().st_size for path in work.rglob("*") if path.is_file()) + print(f"Private profile test exit {code}. Removed {removed:,} bytes; original profiles and SSH trust files verified.") + return code + + +if __name__ == "__main__": + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("--profile-dir", type=Path) + parser.add_argument("--captures", type=Path) + parser.add_argument("--desktop") + parser.add_argument("--work", type=Path) + parser.add_argument("--restart", action="store_true") + raise SystemExit(main(parser.parse_args()))