Add independent per-machine monitoring

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

View File

@@ -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):

View File

@@ -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")

View File

@@ -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)

View File

@@ -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")

View File

@@ -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()))