mchuca commited on
Commit
bad179a
·
1 Parent(s): 05802ed

Server Monitor: six editions (C++/Qt, Python, web for Linux and Windows), requirements and developer kit

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
Files changed (50) hide show
  1. .gitattributes +3 -0
  2. README.md +105 -0
  3. Server Monitor(cqt-linux)/.gitignore +2 -0
  4. Server Monitor(cqt-linux)/CMakeLists.txt +9 -0
  5. Server Monitor(cqt-linux)/README.md +61 -0
  6. Server Monitor(cqt-linux)/ServerMonitor.pro +6 -0
  7. Server Monitor(cqt-linux)/build.sh +35 -0
  8. Server Monitor(cqt-linux)/deploy/server-monitor.desktop +8 -0
  9. Server Monitor(cqt-linux)/src/core/History.cpp +367 -0
  10. Server Monitor(cqt-linux)/src/core/History.h +87 -0
  11. Server Monitor(cqt-linux)/src/core/Model.cpp +128 -0
  12. Server Monitor(cqt-linux)/src/core/Model.h +118 -0
  13. Server Monitor(cqt-linux)/src/core/Platform.cpp +371 -0
  14. Server Monitor(cqt-linux)/src/core/Platform.h +25 -0
  15. Server Monitor(cqt-linux)/src/core/Session.cpp +448 -0
  16. Server Monitor(cqt-linux)/src/core/Session.h +137 -0
  17. Server Monitor(cqt-linux)/src/main.cpp +31 -0
  18. Server Monitor(cqt-linux)/src/ui/Tabs.cpp +884 -0
  19. Server Monitor(cqt-linux)/src/ui/Widgets.cpp +485 -0
  20. Server Monitor(cqt-linux)/src/ui/Widgets.h +150 -0
  21. Server Monitor(cqt-linux)/src/ui/Windows.cpp +614 -0
  22. Server Monitor(cqt-linux)/src/ui/Windows.h +22 -0
  23. Server Monitor(cqt-window)/.gitignore +2 -0
  24. Server Monitor(cqt-window)/CMakeLists.txt +12 -0
  25. Server Monitor(cqt-window)/README.md +47 -0
  26. Server Monitor(cqt-window)/ServerMonitor.pro +7 -0
  27. Server Monitor(cqt-window)/build.bat +18 -0
  28. Server Monitor(cqt-window)/src/core/History.cpp +367 -0
  29. Server Monitor(cqt-window)/src/core/History.h +87 -0
  30. Server Monitor(cqt-window)/src/core/Model.cpp +128 -0
  31. Server Monitor(cqt-window)/src/core/Model.h +118 -0
  32. Server Monitor(cqt-window)/src/core/Platform.cpp +377 -0
  33. Server Monitor(cqt-window)/src/core/Platform.h +25 -0
  34. Server Monitor(cqt-window)/src/core/Session.cpp +448 -0
  35. Server Monitor(cqt-window)/src/core/Session.h +137 -0
  36. Server Monitor(cqt-window)/src/main.cpp +31 -0
  37. Server Monitor(cqt-window)/src/ui/Tabs.cpp +884 -0
  38. Server Monitor(cqt-window)/src/ui/Widgets.cpp +485 -0
  39. Server Monitor(cqt-window)/src/ui/Widgets.h +150 -0
  40. Server Monitor(cqt-window)/src/ui/Windows.cpp +614 -0
  41. Server Monitor(cqt-window)/src/ui/Windows.h +22 -0
  42. Server Monitor(python-linux)/README.md +58 -0
  43. Server Monitor(python-linux)/history.py +331 -0
  44. Server Monitor(python-linux)/main.py +13 -0
  45. Server Monitor(python-linux)/metrics.py +84 -0
  46. Server Monitor(python-linux)/model.py +117 -0
  47. Server Monitor(python-linux)/plat.py +295 -0
  48. Server Monitor(python-linux)/run.sh +3 -0
  49. Server Monitor(python-linux)/session.py +411 -0
  50. Server Monitor(python-linux)/tabs.py +654 -0
.gitattributes CHANGED
@@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
 
 
 
 
33
  *.zip filter=lfs diff=lfs merge=lfs -text
34
  *.zst filter=lfs diff=lfs merge=lfs -text
35
  *tfevents* filter=lfs diff=lfs merge=lfs -text
36
+ *.msi filter=lfs diff=lfs merge=lfs -text
37
+ *.exe filter=lfs diff=lfs merge=lfs -text
38
+ *.deb filter=lfs diff=lfs merge=lfs -text
README.md ADDED
@@ -0,0 +1,105 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ tags:
3
+ - monitoring
4
+ - server
5
+ - qt
6
+ - python
7
+ - nodejs
8
+ ---
9
+
10
+ # ServerMonitor
11
+
12
+ A server status monitor in six stand-alone editions: three languages, each for Linux and for Windows.
13
+ It watches machines in detail (CPU, memory, disks, network, processes, services, temperatures, GPUs), keeps their
14
+ history from seconds to years, analyzes that history with plain statistics (no AI, nothing installed on the servers),
15
+ and keeps machines working with alert rules and an autopilot that can also run in "dry run" (report only).
16
+
17
+ | Folder | Language / UI | Runs on and monitors | Code lines |
18
+ |---|---|---|---|
19
+ | `Server Monitor(cqt-linux)` | C++17, Qt 5 Widgets | Linux | 3,867 |
20
+ | `Server Monitor(cqt-window)` | C++17, Qt 5 Widgets | Windows | 3,873 |
21
+ | `Server Monitor(python-linux)` | Python 3, standard library only (tkinter) | Linux | 3,090 |
22
+ | `Server Monitor(python-window)` | Python 3, standard library only (tkinter) | Windows | 3,096 |
23
+ | `Server Monitor(web-linux)` | Node.js built-ins + plain browser JavaScript | Linux | 2,225 |
24
+ | `Server Monitor(web-window)` | Node.js built-ins + plain browser JavaScript | Windows | 2,214 |
25
+
26
+ No third-party libraries are used: only Qt, the Python standard library, and Node's built-in modules.
27
+ Each edition monitors the machine it runs on and remote machines of the same OS over the system `ssh` client.
28
+ Within a language, the Linux and Windows editions are the same files except for one platform file
29
+ (`src/core/Platform.cpp`, `plat.py`, `core/platform.js` + collector script).
30
+
31
+ All editions use the same `servers.json` and the same binary history files, so data can be copied between them.
32
+
33
+ ## Quick start
34
+
35
+ | Edition | Start |
36
+ |---|---|
37
+ | `cqt-linux` | `./build.sh run` (needs Qt 5.15 development files and g++) |
38
+ | `cqt-window` | Qt command prompt: `build.bat`, then `build\release\ServerMonitor.exe` |
39
+ | `python-linux` | `./run.sh` (needs `python3-tk`) |
40
+ | `python-window` | `run.bat` |
41
+ | `web-linux` | `./run.sh`, then open `http://127.0.0.1:8765` |
42
+ | `web-window` | `run.bat`, then open `http://127.0.0.1:8765` |
43
+
44
+ Each folder has its own README with details. Installers and packages for offline installation are in
45
+ [`requirements/`](requirements/README.md): Qt 5 for Ubuntu and for Windows (with compiler), Python with tkinter, Node.js.
46
+
47
+ ## What every edition does
48
+
49
+ - **Servers:** add, edit, remove, reorder; "This computer" or SSH (key or password); test connection.
50
+ - **Dashboard:** a live card per server with gauges, sparkline, health grade and alert count; totals; recent events.
51
+ - **Server page:** Overview, CPU (per core, temperatures, GPUs), Memory, Storage, Network, Processes (end, kill,
52
+ priority), Services (start, stop, restart, enable, disable, logs), History, Insights & Autopilot, Alert rules, Console.
53
+ - **History:** every sample for 6 hours, minutes for 30 days, hours for 2 years, days for 20 years; downtime included;
54
+ min / average / 95th percentile / peak; CSV export.
55
+ - **Analysis every minute:** disk-full forecast, memory growth, leaking and runaway processes, failed or flapping
56
+ services, overload, swap thrashing, anomalies against the same weekday and hour, availability, capacity advice,
57
+ a health score with grade, and a weekly busy-hours heatmap.
58
+ - **Autopilot:** restarts failed services (with an hourly limit, never ones that were already failed when monitoring
59
+ started), lowers or ends runaway processes, optional disk cleanup; every action has a cooldown and is logged.
60
+ - **Alert rules:** "metric above/below a value for N seconds → severity → action", with events and `alerts.log`.
61
+
62
+ ## Test status
63
+
64
+ Tested on Ubuntu 26.04 (x86-64). Tests never changed the test machine: scratch settings, autopilot in dry run,
65
+ no kill / restart / cleanup / reboot command was run for real.
66
+
67
+ | Check | cqt | python | web |
68
+ |---|---|---|---|
69
+ | Linux edition against the real machine + an unreachable SSH host: scripted click-through of every page, dialogs, console, rules, autopilot form, test connection | 38 / 38 | 47 / 47 | 36 / 36 (browser) + 59 / 59 (API) |
70
+ | Windows edition, same click-through, fed with simulated Windows data | 34 / 34 | 47 / 47 | 36 / 36 + API all passed |
71
+ | Analysis on a synthetic 3-day history: same findings, same numbers, same autopilot decisions in all editions | yes | yes | yes |
72
+ | History files written by the C++ edition load in the other editions | — | yes | yes |
73
+ | No child process survives the app (normal stop and forced kill) | yes | yes | yes |
74
+ | Web only: wrong `Host` / `Origin`, missing header, path traversal, HTML injection through server data | — | — | all rejected |
75
+
76
+ Each pair was also reviewed independently after it was written; the defects found (among them: a process selection
77
+ that could slide to another process, history buckets lost at restart, understated downtime) were fixed in all
78
+ editions and are covered by the tests above.
79
+
80
+ **Not tested: real Windows.** No Windows machine was available. The Windows editions were run on Linux with a
81
+ stand-in for PowerShell, which exercises the parser, analysis and the whole UI, but **not** the PowerShell collector
82
+ script and not the Windows control commands; those were checked by careful reading only. Before relying on a Windows
83
+ edition, run the self-test on a Windows PC from this folder:
84
+
85
+ ```
86
+ powershell -ExecutionPolicy Bypass -File windows-selftest.ps1
87
+ ```
88
+
89
+ It runs the collector once exactly the way the apps start it, checks every section of its output and the command
90
+ wrapper, changes nothing on the machine, and prints PASS / FAIL per check.
91
+
92
+ Also not tested: a successful SSH session to a remote server (only a refused connection), `sudo` actions, GPUs and
93
+ temperature sensors (the test machine has none), runs longer than about 12 minutes, browsers other than Chrome.
94
+
95
+ ## Security notes
96
+
97
+ - Saved SSH passwords are only lightly disguised in `servers.json` (file mode 600), not encrypted. Prefer keys.
98
+ - The web editions listen on `127.0.0.1` only and reject requests from other sites; the page can run commands on
99
+ your servers, so do not expose the port to a network.
100
+ - Control actions run as the user the app (or the SSH login) runs as.
101
+
102
+ ## For developers
103
+
104
+ [`dev/`](dev/README.md) holds the shared specification all six editions follow, the two collector scripts, a stand-in
105
+ PowerShell for running the Windows editions on Linux, and the test scripts used above.
Server Monitor(cqt-linux)/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ build/
2
+ *.user
Server Monitor(cqt-linux)/CMakeLists.txt ADDED
@@ -0,0 +1,9 @@
 
 
 
 
 
 
 
 
 
 
1
+ cmake_minimum_required(VERSION 3.16)
2
+ project(ServerMonitor LANGUAGES CXX)
3
+ set(CMAKE_CXX_STANDARD 17)
4
+ set(CMAKE_AUTOMOC ON)
5
+ find_package(Qt5 5.15 REQUIRED COMPONENTS Widgets)
6
+ file(GLOB_RECURSE SRC CONFIGURE_DEPENDS src/*.cpp src/*.h)
7
+ add_executable(ServerMonitor ${SRC})
8
+ target_include_directories(ServerMonitor PRIVATE src)
9
+ target_link_libraries(ServerMonitor PRIVATE Qt5::Widgets)
Server Monitor(cqt-linux)/README.md ADDED
@@ -0,0 +1,61 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Server Monitor
2
+
3
+ A Qt 5 / C++17 desktop program for Linux that watches Linux servers in detail, keeps their history from seconds to years, analyzes that history with plain statistics (no AI), and fixes common problems automatically. It uses only Qt plus the system `ssh` program. All charts and gauges are drawn by hand with `QPainter`.
4
+
5
+ ## Build and run
6
+
7
+ ```bash
8
+ ./build.sh run # build, then start (./build.sh = build only, ./build.sh clean)
9
+ ```
10
+
11
+ Qt 5.15 is needed. The script uses the system Qt 5 headers if installed (`qtbase5-dev`); otherwise it uses a local copy in `~/.local/share/qt5-sdk/root`, which needs no root access. `cmake` and `ServerMonitor.pro` (Qt Creator) also work.
12
+
13
+ ## Servers
14
+
15
+ Add or remove servers from the sidebar or the dashboard. There are two ways to connect:
16
+
17
+ - **This machine:** no setup.
18
+ - **SSH:** nothing to install on the server. The app uses your system `ssh` client. Keys are recommended (`ssh-copy-id user@host`); a password also works, and the app answers ssh's password prompt itself.
19
+
20
+ A small POSIX `sh` script (in `src/core/Platform.cpp`) reads `/proc` and `/sys` on the server. All calculations happen in the app.
21
+
22
+ Control actions run as the login user. To allow privileged actions (restarting services, killing other users' processes, cleanup), tick **sudo -n** for that server; this needs passwordless sudo.
23
+
24
+ ## Features
25
+
26
+ - **Dashboard:** a live card per server (gauges, sparklines, health grade), totals across servers, and recent events.
27
+ - **Server tabs:**
28
+ - Overview, CPU (per core, temperatures, GPUs), Memory.
29
+ - Storage (usage, read/write speed, how busy each disk is), Network (per interface, TCP states).
30
+ - Processes (terminate, kill, suspend, resume, change priority), Services (start, stop, restart, enable, disable, logs).
31
+ - History, Insights & Autopilot, Alert rules, and a Console with quick checks, reboot and shut down.
32
+ - **History:** stored per server in `~/.config/ServerMonitor/ServerMonitor/history/`.
33
+ - Every sample kept 6 h; 1-minute averages and peaks kept 30 days; hourly kept 2 years; daily kept 20 years.
34
+ - Downtime is stored too, so availability is known.
35
+ - The History tab shows 1 h up to all time, with min / average / 95th percentile / peak and CSV export.
36
+ - **Analysis:** runs every minute using regression, means, standard deviations and percentiles.
37
+ - Disk-full forecast, steady memory growth, per-process leaks, runaway processes, failing or flapping services, overload, swap thrashing.
38
+ - Anomalies compared with the same weekday and hour over the last 8 weeks; availability; capacity advice.
39
+ - A health score (0–100, grade A–F) and a weekly busy-hours heatmap.
40
+ - **Autopilot:** acts on the findings, each type with its own setting.
41
+ - Restarts failed services, with a per-hour limit. Services already failed when monitoring started are left alone.
42
+ - Renices or terminates runaway processes, and handles leaking processes.
43
+ - Optional disk cleanup (off by default) and anomaly alerts.
44
+ - Every action has a cooldown and is logged; **dry run** only reports what it would do.
45
+ - **Alert rules:** for example, "CPU > 90 % for 60 s → warning → restart a service". Events go to the Events page, to desktop notifications and to `alerts.log`.
46
+
47
+ ## Code
48
+
49
+ ```
50
+ src/core/Platform.* everything Linux-specific: collector script, its parser, control commands
51
+ src/core/Model.* config, rules, metrics, formatting
52
+ src/core/History.* history store + analyzer
53
+ src/core/Session.* ssh/local link, per-server session (rules, autopilot), manager
54
+ src/ui/Widgets.* theme, hand-painted widgets, small UI builders
55
+ src/ui/Tabs.cpp server detail tabs
56
+ src/ui/Windows.* dashboard, detail page, add/edit dialog, main window
57
+ ```
58
+
59
+ The Windows edition (`Server Monitor(cqt-window)`) is the same code with a different `Platform.cpp`.
60
+
61
+ Settings are in `~/.config/ServerMonitor/ServerMonitor/servers.json` (file mode 600). Saved SSH passwords are only lightly disguised, not encrypted, so prefer keys.
Server Monitor(cqt-linux)/ServerMonitor.pro ADDED
@@ -0,0 +1,6 @@
 
 
 
 
 
 
 
1
+ # Qt Creator / qmake project
2
+ QT += widgets
3
+ CONFIG += c++17
4
+ INCLUDEPATH += src
5
+ SOURCES += $$files(src/*.cpp, true)
6
+ HEADERS += $$files(src/*.h, true)
Server Monitor(cqt-linux)/build.sh ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #!/usr/bin/env bash
2
+ # Build Server Monitor with Qt 5: ./build.sh [run|clean]
3
+ # Uses system Qt 5 dev files (pkg-config Qt5Widgets) or a local SDK unpacked from
4
+ # the Ubuntu qtbase5-dev packages into ~/.local/share/qt5-sdk/root (no root needed).
5
+ set -euo pipefail
6
+ HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; B="$HERE/build"
7
+ [[ "${1:-}" == clean ]] && { rm -rf "$B"; echo cleaned; exit 0; }
8
+
9
+ if pkg-config --exists Qt5Widgets 2>/dev/null; then
10
+ read -r -a QTF <<<"$(pkg-config --cflags Qt5Widgets)"; read -r -a QTL <<<"$(pkg-config --libs Qt5Widgets)"
11
+ MOC="$(pkg-config --variable=host_bins Qt5Core)/moc"
12
+ else
13
+ SDK="${QT5_SDK:-$HOME/.local/share/qt5-sdk/root}"; I="$SDK/usr/include/x86_64-linux-gnu/qt5"
14
+ [[ -d "$I/QtWidgets" ]] || { echo "Qt 5 headers missing. Install qtbase5-dev, or: mkdir -p ~/.local/share/qt5-sdk && cd ~/.local/share/qt5-sdk &&
15
+ apt-get download qtbase5-dev qtbase5-dev-tools libgl-dev libglx-dev libopengl-dev libvulkan-dev && for f in *.deb; do dpkg -x \$f root; done" >&2; exit 1; }
16
+ QTF=(-I"$I" -I"$I/QtCore" -I"$I/QtGui" -I"$I/QtWidgets" -I"$SDK/usr/include" -I"$SDK/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++")
17
+ QTL=(-L/usr/lib/x86_64-linux-gnu -l:libQt5Widgets.so.5 -l:libQt5Gui.so.5 -l:libQt5Core.so.5)
18
+ MOC="$SDK/usr/lib/qt5/bin/moc"
19
+ fi
20
+ FLAGS=(-std=c++17 -O2 -fPIC -Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -DQT_NO_DEBUG "${QTF[@]}" -I"$HERE/src")
21
+ mkdir -p "$B/obj"
22
+ mapfile -t SRCS < <(find "$HERE/src" -name '*.cpp' | sort)
23
+ mapfile -t MOCH < <(grep -l Q_OBJECT -r "$HERE/src" --include='*.h')
24
+ for h in "${MOCH[@]}"; do # moc only what needs it
25
+ m="$B/obj/moc_$(basename "${h%.h}").cpp"; [[ "$m" -nt "$h" ]] || "$MOC" "$h" -o "$m"; SRCS+=("$m")
26
+ done
27
+ NEWEST_H=$(find "$HERE/src" -name '*.h' -printf '%T@\n' | sort -n | tail -1)
28
+ OBJS=()
29
+ for s in "${SRCS[@]}"; do
30
+ o="$B/obj/$(basename "${s%.cpp}").o"; OBJS+=("$o")
31
+ if [[ ! -f "$o" || "$s" -nt "$o" || $(stat -c %Y "$o") < ${NEWEST_H%.*} ]]; then echo " CXX ${s#$HERE/}"; g++ "${FLAGS[@]}" -c "$s" -o "$o" & fi
32
+ done
33
+ wait
34
+ g++ -o "$B/ServerMonitor" "${OBJS[@]}" "${QTL[@]}" -lpthread && echo "Done: $B/ServerMonitor"
35
+ [[ "${1:-}" == run ]] && exec "$B/ServerMonitor"; true
Server Monitor(cqt-linux)/deploy/server-monitor.desktop ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ [Desktop Entry]
2
+ Type=Application
3
+ Name=Server Monitor
4
+ Comment=Monitor, analyze and control Linux servers
5
+ # Put the full path of the built program here, e.g. /opt/ServerMonitor/ServerMonitor
6
+ Exec=ServerMonitor
7
+ Terminal=false
8
+ Categories=System;Monitor;
Server Monitor(cqt-linux)/src/core/History.cpp ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "History.h"
2
+ #include <QDateTime>
3
+ #include <QDir>
4
+ #include <QFile>
5
+ #include <QSaveFile>
6
+ #include <algorithm>
7
+ #include <cstring>
8
+
9
+ const char *const hKeys[H_COUNT] = {"cpu", "iowait", "load", "mem", "swap", "disk", "diskio", "rx", "tx", "rd", "wr", "temp", "procs", "gpu", "failed"};
10
+ const char *const hNames[H_COUNT] = {"CPU", "I/O wait", "Load (1m)", "Memory", "Swap", "Disk usage", "Disk busy", "Net download",
11
+ "Net upload", "Disk read", "Disk write", "Temperature", "Processes", "GPU", "Failed services"};
12
+ QString tierName(Tier t) { return QStringList{"every sample", "1 minute", "1 hour", "1 day"}.value(int(t)); }
13
+ static const QByteArray kHeader = QByteArray("SMH1") + char(H_COUNT) + char(0) + char(sizeof(HPoint) & 0xff) + char(sizeof(HPoint) >> 8);
14
+
15
+ // ---- accumulator ----------------------------------------------------------------
16
+ HistoryStore::Acc::Acc(qint64 b) : bucket(b) { std::fill(mx, mx + H_COUNT, NAN); }
17
+ void HistoryStore::Acc::add(const HPoint &p)
18
+ {
19
+ n += p.n, nUp += p.nUp;
20
+ if (p.nUp)
21
+ for (int i = 0; i < H_COUNT; ++i)
22
+ if (!std::isnan(p.avg[i])) {
23
+ sum[i] += double(p.avg[i]) * p.nUp, cnt[i] += p.nUp;
24
+ if (std::isnan(mx[i]) || p.max[i] > mx[i]) mx[i] = p.max[i];
25
+ }
26
+ }
27
+ HPoint HistoryStore::Acc::point() const
28
+ {
29
+ HPoint p;
30
+ p.ts = bucket, p.n = n, p.nUp = nUp;
31
+ for (int i = 0; i < H_COUNT; ++i) p.avg[i] = cnt[i] ? float(sum[i] / cnt[i]) : NAN, p.max[i] = mx[i];
32
+ return p;
33
+ }
34
+
35
+ // ---- store ----------------------------------------------------------------------
36
+ QString HistoryStore::file(int t) const { return m_dir + "/" + QStringList{"raw", "minute", "hour", "day"}[t] + ".bin"; }
37
+ qint64 HistoryStore::bucketOf(int t, qint64 ts) const { return t == 3 ? (ts + m_tz) / 86400 * 86400 - m_tz : ts / step[t] * step[t]; } // days at local midnight
38
+
39
+ HistoryStore::HistoryStore(const QString &dir) : m_dir(dir), m_tz(QDateTime::currentDateTime().offsetFromUtc())
40
+ {
41
+ QDir().mkpath(dir);
42
+ const qint64 now = QDateTime::currentSecsSinceEpoch();
43
+ for (int t = 0; t < 4; ++t) {
44
+ QFile f(file(t));
45
+ if (!f.open(QIODevice::ReadOnly)) continue;
46
+ const QByteArray d = f.readAll();
47
+ if (!d.startsWith(kHeader)) { f.close(), QFile::remove(f.fileName() + ".old"), f.rename(f.fileName() + ".old"); continue; }
48
+ int bad = int((d.size() - kHeader.size()) % sizeof(HPoint)); // a cut-off record would misalign everything appended after it
49
+ for (int off = kHeader.size(); off + int(sizeof(HPoint)) <= d.size(); off += sizeof(HPoint)) {
50
+ HPoint p;
51
+ std::memcpy(&p, d.constData() + off, sizeof p);
52
+ if (p.ts < now - keep[t] || p.ts > now + 86400 || (!m_t[t].isEmpty() && p.ts <= m_t[t].last().ts)) ++bad;
53
+ else m_t[t] << p;
54
+ }
55
+ if (bad) rewrite(t);
56
+ }
57
+ for (int t = 1; t < 4; ++t) { // rebuild from finer data what is not stored yet: buckets the last run left open, and the current one
58
+ const qint64 stored = m_t[t].isEmpty() ? -1 : m_t[t].last().ts;
59
+ auto feed = [&](const HPoint &p) {
60
+ const qint64 b = bucketOf(t, p.ts);
61
+ if (b <= stored) return;
62
+ if (b != m_acc[t].bucket) {
63
+ if (m_acc[t].n) append(t, m_acc[t].point());
64
+ m_acc[t] = Acc(b);
65
+ }
66
+ m_acc[t].add(p);
67
+ };
68
+ for (const HPoint &p : qAsConst(m_t[t - 1])) feed(p);
69
+ if (m_acc[t - 1].n) feed(m_acc[t - 1].point());
70
+ }
71
+ }
72
+
73
+ void HistoryStore::rewrite(int t)
74
+ {
75
+ QSaveFile f(file(t));
76
+ if (!f.open(QIODevice::WriteOnly)) return;
77
+ f.write(kHeader);
78
+ f.write(reinterpret_cast<const char *>(m_t[t].constData()), qint64(m_t[t].size()) * sizeof(HPoint));
79
+ f.commit();
80
+ }
81
+
82
+ void HistoryStore::append(int t, const HPoint &p)
83
+ {
84
+ auto &v = m_t[t];
85
+ if (!v.isEmpty() && p.ts <= v.last().ts) return;
86
+ v << p;
87
+ QFile f(file(t));
88
+ if (f.open(QIODevice::Append)) {
89
+ if (f.size() < kHeader.size()) f.resize(0), f.write(kHeader);
90
+ f.write(reinterpret_cast<const char *>(&p), sizeof p);
91
+ }
92
+ if (++m_appends[t] % 500) return; // trim expired points now and then
93
+ const auto it = std::find_if(v.begin(), v.end(), [&](const HPoint &x) { return x.ts >= p.ts - keep[t]; });
94
+ if (it != v.begin()) v.erase(v.begin(), it), rewrite(t);
95
+ }
96
+
97
+ void HistoryStore::add(qint64 ts, const float *val, bool up)
98
+ {
99
+ HPoint raw;
100
+ raw.ts = ts, raw.n = 1, raw.nUp = up;
101
+ for (int i = 0; i < H_COUNT; ++i) raw.avg[i] = raw.max[i] = up ? val[i] : NAN;
102
+ append(0, raw);
103
+ for (int t = 1; t < 4; ++t) { // every coarser tier accumulates every raw sample
104
+ const qint64 b = bucketOf(t, ts);
105
+ if (m_acc[t].bucket != b) {
106
+ if (m_acc[t].n && m_acc[t].bucket < b) append(t, m_acc[t].point());
107
+ m_acc[t] = Acc(b);
108
+ }
109
+ m_acc[t].add(raw);
110
+ }
111
+ }
112
+
113
+ QVector<HPoint> HistoryStore::range(qint64 from, qint64 to, Tier tier) const
114
+ {
115
+ const int t = int(tier);
116
+ const auto &v = m_t[t];
117
+ auto it = std::lower_bound(v.begin(), v.end(), from, [](const HPoint &p, qint64 x) { return p.ts < x; });
118
+ QVector<HPoint> out;
119
+ for (; it != v.end() && it->ts <= to; ++it) out << *it;
120
+ const Acc &a = m_acc[t];
121
+ if (t && a.n && a.bucket >= from && a.bucket <= to && (out.isEmpty() || out.last().ts < a.bucket)) out << a.point();
122
+ return out;
123
+ }
124
+
125
+ QVector<HPoint> HistoryStore::range(qint64 from, qint64 to, Tier *used) const
126
+ {
127
+ const qint64 now = QDateTime::currentSecsSinceEpoch(), maxSpan[3] = {6 * 3600, 8 * 86400, 400 * 86400};
128
+ int t = 0;
129
+ while (t < 3 && (from < now - keep[t] || to - from > maxSpan[t])) ++t;
130
+ if (used) *used = Tier(t);
131
+ return range(from, to, Tier(t));
132
+ }
133
+
134
+ void HistoryStore::removeFiles() { QDir(m_dir).removeRecursively(), *this = HistoryStore(m_dir); }
135
+ qint64 HistoryStore::firstTs() const
136
+ {
137
+ qint64 f = 0;
138
+ for (const auto &v : m_t)
139
+ if (!v.isEmpty() && (!f || v[0].ts < f)) f = v[0].ts;
140
+ return f;
141
+ }
142
+ qint64 HistoryStore::diskBytes() const
143
+ {
144
+ qint64 b = 0;
145
+ for (int t = 0; t < 4; ++t) b += QFileInfo(file(t)).size();
146
+ return b;
147
+ }
148
+
149
+ Stats stats(const QVector<HPoint> &pts, int m)
150
+ {
151
+ Stats s;
152
+ QVector<double> v;
153
+ double sum = 0, w = 0;
154
+ for (const HPoint &p : pts) {
155
+ if (!p.nUp || std::isnan(p.avg[m])) continue;
156
+ v << p.avg[m], sum += double(p.avg[m]) * p.nUp, w += p.nUp;
157
+ if (std::isnan(s.max) || p.max[m] > s.max) s.max = p.max[m];
158
+ }
159
+ if (v.isEmpty()) return s;
160
+ std::sort(v.begin(), v.end());
161
+ s.count = v.size(), s.avg = sum / w, s.min = v[0], s.p95 = v[qMin(v.size() - 1, int(v.size() * 0.95))];
162
+ return s;
163
+ }
164
+
165
+ QString fmtMetric(int m, double v)
166
+ {
167
+ if (std::isnan(v)) return "—";
168
+ switch (m) {
169
+ case H_RX: case H_TX: case H_RD: case H_WR: return Fmt::rate(v);
170
+ case H_LOAD: return QString::number(v, 'f', 2);
171
+ case H_TEMP: return Fmt::temp(v);
172
+ case H_PROCS: case H_FAILED: return QString::number(v, 'f', 0);
173
+ default: return Fmt::pct(v);
174
+ }
175
+ }
176
+
177
+ // ---- analysis -------------------------------------------------------------------
178
+ Analysis::Analysis() { std::fill(&heat[0][0][0], &heat[0][0][0] + 336, NAN); }
179
+
180
+ double regression(const QVector<HPoint> &pts, int m, double *r2)
181
+ {
182
+ double n = 0, sx = 0, sy = 0, sxx = 0, sxy = 0, syy = 0, x0 = pts.isEmpty() ? 0 : pts[0].ts;
183
+ for (const HPoint &p : pts)
184
+ if (p.nUp && !std::isnan(p.avg[m])) {
185
+ const double x = p.ts - x0, y = p.avg[m];
186
+ n++, sx += x, sy += y, sxx += x * x, sxy += x * y, syy += y * y;
187
+ }
188
+ const double den = n * sxx - sx * sx, num = n * sxy - sx * sy, vy = n * syy - sy * sy;
189
+ *r2 = n >= 3 && den > 0 && vy > 1e-9 ? num * num / (den * vy) : 0; // squared correlation
190
+ return n >= 3 && den > 0 ? num / den : 0;
191
+ }
192
+
193
+ Analysis analyze(const HistoryStore &st, const Metrics &m, const AutopilotConfig &ap, const QVector<ProcTrend> &procs,
194
+ const QVector<ServiceTrend> &svcs, bool online)
195
+ {
196
+ Analysis a;
197
+ const qint64 now = a.when = QDateTime::currentSecsSinceEpoch();
198
+ const auto &minute = st.tier(Tier::Minute), &hour = st.tier(Tier::Hour);
199
+ auto add = [&](QString key, QString sev, QString cat, QString title, QString detail, QString advice, QString action = {},
200
+ QString arg = {}, QString label = {}, bool autoOk = false) {
201
+ a.findings << Finding{key, sev, cat, title, detail, advice, action, arg, label, autoOk};
202
+ };
203
+ auto sev = [](bool crit, bool warn) { return crit ? "critical" : warn ? "warning" : "info"; };
204
+
205
+ // availability
206
+ const qint64 spans[3] = {86400, 7 * 86400, 30 * 86400};
207
+ for (int i = 0; i < 3; ++i) {
208
+ double n = 0, up = 0;
209
+ for (const HPoint &p : st.range(now - spans[i], now)) n += p.n, up += p.nUp;
210
+ a.up[i] = n ? up * 100 / n : NAN;
211
+ a.down[i] = n ? (n - up) / n * qMin(spans[i], now - st.firstTs()) : 0; // share of the monitored part of the window
212
+ }
213
+ if (a.up[0] < 99)
214
+ add("avail24", sev(a.up[0] < 95, true), "Availability", QString("Availability last 24 h is %1").arg(Fmt::pct(a.up[0], 2)),
215
+ QString("The server could not be reached for about %1 in the last day.").arg(Fmt::duration(a.down[0])),
216
+ "Check network stability, power and whether the machine rebooted (uptime).");
217
+ const auto w30 = st.range(now - spans[2], now, Tier::Hour), w7 = st.range(now - spans[1], now, Tier::Minute);
218
+ a.cpu30 = stats(w30.size() >= 24 ? w30 : w7, H_CPU), a.mem30 = stats(w30.size() >= 24 ? w30 : w7, H_MEM);
219
+
220
+ // disk forecast: regression over 7 d of hours, or 24 h of minutes, whichever fits better
221
+ double r2 = 0, r2b = 0, slope = 0;
222
+ const auto week = st.range(now - spans[1], now, Tier::Hour), day = st.range(now - 86400, now, Tier::Minute);
223
+ if (week.size() >= 48) slope = regression(week, H_DISK, &r2), a.diskBasis = "hourly averages, last 7 days";
224
+ if (day.size() >= 120) {
225
+ const double s2 = regression(day, H_DISK, &r2b);
226
+ if (week.size() < 48 || r2b > r2) slope = s2, r2 = r2b, a.diskBasis = "minute averages, last 24 hours";
227
+ }
228
+ a.diskSlopePerDay = slope * 86400;
229
+ if (a.diskSlopePerDay > 0.05 && r2 >= 0.3 && m.maxDiskPct > 0) a.diskFullDays = (100 - m.maxDiskPct) / a.diskSlopePerDay;
230
+ if (a.diskFullDays >= 0 && a.diskFullDays < 30)
231
+ add("diskfull", sev(a.diskFullDays < ap.diskForecastDays, a.diskFullDays < 14), "Disk",
232
+ QString("Disk %1 will be full in %2").arg(m.fullestMount, Fmt::duration(a.diskFullDays * 86400)),
233
+ QString("Usage %1, growing %2 points/day (trend from %3, fit R² %4).").arg(Fmt::pct(m.maxDiskPct)).arg(a.diskSlopePerDay, 0, 'f', 2).arg(a.diskBasis).arg(r2, 0, 'f', 2),
234
+ "Clean logs/caches, rotate or move data, or grow the volume.", "disk_cleanup", "", "Run cleanup", ap.diskCleanup && a.diskFullDays < ap.diskForecastDays);
235
+ if (m.maxDiskPct >= ap.diskCleanupAt)
236
+ add("diskhigh", sev(m.maxDiskPct >= 97, true), "Disk", QString("Disk %1 is %2 full").arg(m.fullestMount, Fmt::pct(m.maxDiskPct)),
237
+ QString("Above the cleanup threshold of %1.").arg(Fmt::pct(ap.diskCleanupAt, 0)), "Free space soon: services fail when the disk is full.",
238
+ "disk_cleanup", "", "Run cleanup", ap.diskCleanup);
239
+
240
+ // whole-machine memory trend over 6 h
241
+ const auto six = st.range(now - 6 * 3600, now, Tier::Minute);
242
+ if (six.size() >= 90) {
243
+ a.memSlopePerHour = regression(six, H_MEM, &a.memTrendR2) * 3600;
244
+ const double left = (100 - m.memPct) / qMax(0.01, a.memSlopePerHour);
245
+ if (a.memSlopePerHour > 1 && a.memTrendR2 > 0.8 && m.memPct > 40)
246
+ add("memtrend", sev(false, left < 12), "Memory", QString("Memory keeps growing (+%1 points/hour)").arg(a.memSlopePerHour, 0, 'f', 1),
247
+ QString("Steady growth over 6 h (R² %1). At this rate memory is exhausted in about %2.").arg(a.memTrendR2, 0, 'f', 2).arg(Fmt::duration(left * 3600)),
248
+ "Look for a leaking process (Processes tab, sort by RSS).");
249
+ }
250
+
251
+ // processes: leaks and runaways
252
+ for (const ProcTrend &p : procs) {
253
+ if (p.kernel) continue;
254
+ const QString who = QString("%1 (PID %2)").arg(p.name).arg(p.pid), pid = QString::number(p.pid);
255
+ if (p.minutesTracked >= 30 && p.rssGrowthPct >= 25 && p.rssGrowth >= 100e6 && p.rssMonotonic >= 0.8)
256
+ add("leak:" + pid, sev(m.memPct >= ap.leakMemPressure, true), "Process", "Possible memory leak: " + who,
257
+ QString("RSS grew %1 (+%2) in %3 min and rose in %4% of the minutes; now %5.").arg(Fmt::bytes(p.rssGrowth), Fmt::pct(p.rssGrowthPct, 0))
258
+ .arg(p.minutesTracked).arg(qRound(p.rssMonotonic * 100)).arg(Fmt::bytes(p.rssNow)),
259
+ "Restart the program/service at a quiet time and report the leak upstream.", "kill_pid", pid, "Terminate",
260
+ ap.leakMode == "terminate" && m.memPct >= ap.leakMemPressure);
261
+ if (p.highCpuMinutes >= ap.runawayMinutes) {
262
+ const bool term = ap.runawayMode == "terminate";
263
+ add("runaway:" + pid, "warning", "Process", "Runaway process: " + who,
264
+ QString("Above %1 CPU for %2 min (now %3, user %4).").arg(Fmt::pct(ap.runawayCpu, 0)).arg(qRound(p.highCpuMinutes)).arg(Fmt::pct(p.cpuNow), p.user),
265
+ "Lower its priority (renice) or stop it if it is stuck.", term ? "kill_pid" : "renice", pid, term ? "Terminate" : "Renice to 19", ap.runawayMode != "none");
266
+ }
267
+ }
268
+
269
+ // services: failures and flapping
270
+ for (const ServiceTrend &s : svcs) {
271
+ const bool flap = s.failsLastHour >= 3 || s.autoRestartsLastHour >= ap.maxRestartsPerHour;
272
+ if (s.failedNow)
273
+ add("svc:" + s.unit, sev(flap, true), "Service", QString(flap ? "Service %1 keeps failing" : "Service %1 has failed").arg(s.unit),
274
+ s.preexisting ? "It was already failed when monitoring started, so the autopilot leaves it alone (it may be failed on purpose)."
275
+ : QString("Failed %1× in the last hour; autopilot restarted it %2×.").arg(s.failsLastHour).arg(s.autoRestartsLastHour),
276
+ flap ? "Automatic restarts were stopped. Read the logs (Services tab → Logs) and fix the cause." : "Restart it and check the logs.",
277
+ "restart_service", s.unit, "Restart", ap.restartFailed && !s.preexisting && s.autoRestartsLastHour < ap.maxRestartsPerHour);
278
+ else if (s.failsLastHour >= 3)
279
+ add("flap:" + s.unit, "warning", "Service", QString("Service %1 is unstable").arg(s.unit),
280
+ QString("It failed %1 times within the last hour.").arg(s.failsLastHour), "Inspect its logs and resource limits.");
281
+ }
282
+
283
+ // overload and swap thrashing
284
+ const auto last15 = st.range(now - 900, now, Tier::Minute);
285
+ const double load15 = stats(last15, H_LOAD).avg, io15 = stats(last15, H_IOWAIT).avg, cpu15 = stats(last15, H_CPU).avg, busy15 = stats(last15, H_DISKIO).avg;
286
+ if (online && load15 / m.cpuCount > 1.5)
287
+ add("load", sev(load15 / m.cpuCount > 3, true), "CPU", QString("CPU is overloaded (load %1 on %2 cores)").arg(load15, 0, 'f', 1).arg(m.cpuCount),
288
+ QString("15-minute average load is %1× the number of cores; tasks are waiting for CPU.").arg(load15 / m.cpuCount, 0, 'f', 1),
289
+ "Find the busiest processes, spread work over time, or add CPU.");
290
+ if (online && m.swapPct > 50 && (P::posixCpu ? io15 > 20 : m.memPct > 90 && busy15 > 50)) // no I/O wait counter on Windows: full memory + busy disks
291
+ add("thrash", "critical", "Memory", "Swap thrashing", P::posixCpu ? QString("Swap %1 used and CPU waits on I/O %2 of the time.").arg(Fmt::pct(m.swapPct), Fmt::pct(io15))
292
+ : QString("Swap %1 used, memory %2 full and disks %3 busy.").arg(Fmt::pct(m.swapPct), Fmt::pct(m.memPct), Fmt::pct(busy15)),
293
+ "Stop memory-hungry processes or add RAM.");
294
+
295
+ // anomalies: last 10 min vs same weekday+hour over 8 weeks (fallback: last 24 h)
296
+ const auto raw = st.range(now - 600, now, Tier::Raw);
297
+ const QDateTime lt = QDateTime::fromSecsSinceEpoch(now);
298
+ if (online && raw.size() >= 10)
299
+ for (auto [hm, floor, down] : {std::tuple{H_CPU, 5.0, false}, {H_MEM, 3.0, false}, {H_LOAD, 0.25 * qMax(1, m.cpuCount), false},
300
+ {H_IOWAIT, 3.0, false}, {H_RX, 256e3, true}, {H_TX, 256e3, true}}) {
301
+ if (hm == H_IOWAIT && !P::posixCpu) continue;
302
+ const double cur = stats(raw, hm).avg;
303
+ QVector<double> v;
304
+ for (const HPoint &p : hour) {
305
+ const QDateTime t = QDateTime::fromSecsSinceEpoch(p.ts);
306
+ if (p.nUp && !std::isnan(p.avg[hm]) && now - p.ts < 56 * 86400 && now - p.ts > 3600 && t.date().dayOfWeek() == lt.date().dayOfWeek() && t.time().hour() == lt.time().hour())
307
+ v << p.avg[hm];
308
+ }
309
+ QString basis = "same weekday & hour, last 8 weeks";
310
+ if (v.size() < 3) {
311
+ v.clear(), basis = "last 24 hours";
312
+ for (const HPoint &p : minute)
313
+ if (p.nUp && !std::isnan(p.avg[hm]) && now - p.ts <= 86400 && now - p.ts > 900) v << p.avg[hm];
314
+ if (v.size() < 360) continue;
315
+ }
316
+ double mean = 0, var = 0;
317
+ for (double x : v) mean += x / v.size();
318
+ for (double x : v) var += (x - mean) * (x - mean) / v.size();
319
+ const double sd = std::sqrt(var), z = (cur - mean) / qMax(sd, floor);
320
+ a.anomalies << Anomaly{hNames[hm], basis, hm, cur, mean, sd, z};
321
+ const bool hi = z >= ap.anomalyZ, lo = down && mean > 1e6 && cur < mean * 0.1;
322
+ if (ap.anomalyAlerts && (hi || lo))
323
+ add(QString("anomaly:") + hKeys[hm], sev(false, z >= ap.anomalyZ * 2), "Anomaly", QString(hi ? "Unusually high %1" : "Unusually low %1").arg(QString(hNames[hm]).toLower()),
324
+ QString("Last 10 min %1, usually %2 ± %3 (%4); %5σ.").arg(fmtMetric(hm, cur), fmtMetric(hm, mean), fmtMetric(hm, sd), basis).arg(z, 0, 'f', 1),
325
+ hi ? "Check what changed: deploys, cron jobs, traffic, attacks." : "Traffic dropped sharply - check the service is still serving.");
326
+ }
327
+
328
+ // weekly heatmaps from 4 weeks of hours
329
+ double sum[2][7][24] = {};
330
+ for (const HPoint &p : hour) {
331
+ if (now - p.ts > 28 * 86400 || !p.nUp || std::isnan(p.avg[H_CPU])) continue;
332
+ const QDateTime t = QDateTime::fromSecsSinceEpoch(p.ts);
333
+ const int d = t.date().dayOfWeek() - 1, h = t.time().hour(), n = ++a.heatN[d][h];
334
+ sum[0][d][h] += p.avg[H_CPU], sum[1][d][h] += std::isnan(p.avg[H_MEM]) ? 0 : p.avg[H_MEM];
335
+ a.heat[0][d][h] = sum[0][d][h] / n, a.heat[1][d][h] = sum[1][d][h] / n;
336
+ }
337
+
338
+ // capacity advice
339
+ for (auto [s, name, lo, hi, loTxt, hiTxt] : {std::tuple{a.cpu30, "CPU", 15.0, 80.0, "is mostly idle", "is often saturated - add cores or move work away"},
340
+ {a.mem30, "Memory", 30.0, 85.0, "is under-used", "is tight - add RAM or reduce caches/limits"}})
341
+ if (s.count >= 60)
342
+ a.capacity << QString("%1 %2 (p95 %3).").arg(name, s.p95 < lo ? loTxt : s.p95 > hi ? hiTxt : "headroom is healthy", Fmt::pct(s.p95));
343
+ if (a.diskFullDays >= 0) a.capacity << QString("Disk grows %1 points/day - full in about %2.").arg(a.diskSlopePerDay, 0, 'f', 2).arg(Fmt::duration(a.diskFullDays * 86400));
344
+ else if (!a.diskBasis.isEmpty()) a.capacity << "Disk usage is stable.";
345
+ if (a.capacity.isEmpty()) a.capacity << "Collecting history - capacity advice appears after about an hour of data.";
346
+
347
+ // health score
348
+ double score = 100, fp = 0;
349
+ auto pen = [&](bool when, double p, const QString &why) {
350
+ if (when && p > 0.5) score -= p, a.healthReasons << QString("−%1 %2").arg(qRound(p)).arg(why);
351
+ };
352
+ const double cpu = std::isnan(cpu15) ? m.cpuUsage : cpu15;
353
+ for (const Finding &f : a.findings) fp += f.category == "Availability" ? 0 : f.severity == "critical" ? 15 : f.severity == "warning" ? 7 : 2;
354
+ pen(!online, 60, "server unreachable");
355
+ pen(cpu > 70, qMin(24.0, (cpu - 70) * 0.8), "CPU busy (" + Fmt::pct(cpu) + ")");
356
+ pen(m.memPct > 80, qMin(30.0, (m.memPct - 80) * 1.5), "memory high (" + Fmt::pct(m.memPct) + ")");
357
+ pen(m.maxDiskPct > 80, qMin(40.0, (m.maxDiskPct - 80) * 2), "disk high (" + Fmt::pct(m.maxDiskPct) + ")");
358
+ pen(m.swapPct > 50, 10, "heavy swap use");
359
+ pen(m.maxTemp > 80, qMin(20.0, (m.maxTemp - 80) * 2), "hot (" + Fmt::temp(m.maxTemp) + ")");
360
+ pen(a.up[0] < 100, qMin(30.0, (100 - a.up[0]) * 5), "downtime in last 24 h");
361
+ pen(true, qMin(50.0, fp), QString("%1 finding(s)").arg(a.findings.size()));
362
+ a.health = qBound(0, qRound(score), 100);
363
+ a.grade = QString("FDCBA").at(a.health >= 90 ? 4 : a.health >= 75 ? 3 : a.health >= 60 ? 2 : a.health >= 40 ? 1 : 0);
364
+ auto rank = [](const QString &s) { return s == "critical" ? 0 : s == "warning" ? 1 : 2; };
365
+ std::stable_sort(a.findings.begin(), a.findings.end(), [&](const Finding &x, const Finding &y) { return rank(x.severity) < rank(y.severity); });
366
+ return a;
367
+ }
Server Monitor(cqt-linux)/src/core/History.h ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Persistent multi-resolution history (raw 6 h, minute 30 d, hour 2 y, day 20 y)
2
+ // and the statistics-only analyzer that feeds the autopilot.
3
+ #pragma once
4
+ #include "Model.h"
5
+ #include <cmath>
6
+
7
+ enum HMetric { H_CPU, H_IOWAIT, H_LOAD, H_MEM, H_SWAP, H_DISK, H_DISKIO, H_RX, H_TX, H_RD, H_WR, H_TEMP, H_PROCS, H_GPU, H_FAILED, H_COUNT };
8
+ extern const char *const hKeys[H_COUNT], *const hNames[H_COUNT];
9
+ enum class Tier { Raw, Minute, Hour, Day };
10
+ QString tierName(Tier t);
11
+
12
+ #pragma pack(push, 1)
13
+ struct HPoint {
14
+ qint64 ts = 0; // seconds; bucket start for aggregates
15
+ quint32 n = 0, nUp = 0; // samples / online samples
16
+ float avg[H_COUNT], max[H_COUNT];
17
+ double uptimePct() const { return n ? nUp * 100.0 / n : 0; }
18
+ };
19
+ #pragma pack(pop)
20
+
21
+ class HistoryStore {
22
+ public:
23
+ static constexpr qint64 step[4] = {1, 60, 3600, 86400}, keep[4] = {6 * 3600, 30 * 86400, 732 * 86400, 7320LL * 86400};
24
+ explicit HistoryStore(const QString &dir);
25
+ void add(qint64 ts, const float *v, bool up); // up=false records downtime only
26
+ const QVector<HPoint> &tier(Tier t) const { return m_t[int(t)]; }
27
+ QVector<HPoint> range(qint64 from, qint64 to, Tier t) const; // includes the open bucket
28
+ QVector<HPoint> range(qint64 from, qint64 to, Tier *used = nullptr) const; // finest tier covering it
29
+ void removeFiles();
30
+ qint64 firstTs() const;
31
+ qint64 diskBytes() const;
32
+
33
+ private:
34
+ struct Acc {
35
+ qint64 bucket = -1;
36
+ quint32 n = 0, nUp = 0, cnt[H_COUNT] = {};
37
+ double sum[H_COUNT] = {};
38
+ float mx[H_COUNT];
39
+ Acc(qint64 b = -1);
40
+ void add(const HPoint &p);
41
+ HPoint point() const;
42
+ };
43
+ qint64 bucketOf(int t, qint64 ts) const;
44
+ void append(int t, const HPoint &p);
45
+ void rewrite(int t);
46
+ QString file(int t) const;
47
+ QString m_dir;
48
+ QVector<HPoint> m_t[4];
49
+ Acc m_acc[4];
50
+ qint64 m_tz;
51
+ int m_appends[4] = {};
52
+ };
53
+
54
+ struct Stats { double min = NAN, avg = NAN, p95 = NAN, max = NAN; int count = 0; }; // max = peak of max[]
55
+ Stats stats(const QVector<HPoint> &pts, int metric);
56
+
57
+ // ---- analysis -------------------------------------------------------------------
58
+ struct Finding {
59
+ QString key, severity, category, title, detail, advice, action, actionArg, actionLabel; // action: disk_cleanup|restart_service|renice|kill_pid
60
+ bool autoEligible = false;
61
+ };
62
+ struct ProcTrend {
63
+ int pid = 0, minutesTracked = 0;
64
+ QString name, user;
65
+ double cpuNow = 0, highCpuMinutes = 0, rssNow = 0, rssGrowth = 0, rssGrowthPct = 0, rssMonotonic = 0;
66
+ bool kernel = false;
67
+ };
68
+ struct ServiceTrend { QString unit; bool failedNow = false, preexisting = false; int failsLastHour = 0, autoRestartsLastHour = 0; };
69
+ struct Anomaly { QString metric, baseline; int hm = 0; double now = 0, mean = 0, sd = 0, z = 0; };
70
+ struct Analysis {
71
+ qint64 when = 0;
72
+ int health = 100;
73
+ QString grade = "A", diskBasis;
74
+ QStringList healthReasons, capacity;
75
+ QVector<Finding> findings;
76
+ QVector<Anomaly> anomalies;
77
+ double diskFullDays = -1, diskSlopePerDay = 0, memSlopePerHour = 0, memTrendR2 = 0;
78
+ double up[3] = {NAN, NAN, NAN}, down[3] = {}; // 24 h, 7 d, 30 d: availability %, seconds offline
79
+ Stats cpu30, mem30;
80
+ double heat[2][7][24]; // weekly pattern: 0 = CPU, 1 = memory
81
+ int heatN[7][24] = {};
82
+ Analysis();
83
+ };
84
+ Analysis analyze(const HistoryStore &st, const Metrics &m, const AutopilotConfig &ap, const QVector<ProcTrend> &procs,
85
+ const QVector<ServiceTrend> &svcs, bool online);
86
+ double regression(const QVector<HPoint> &pts, int metric, double *r2); // slope per second
87
+ QString fmtMetric(int metric, double v);
Server Monitor(cqt-linux)/src/core/Model.cpp ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "Model.h"
2
+ #include <QJsonArray>
3
+ #include <QUuid>
4
+ #include <QVariant>
5
+ #include <type_traits>
6
+
7
+ // ---- formatting -------------------------------------------------------------
8
+ QString Fmt::bytes(double b, int prec)
9
+ {
10
+ static const char *u[] = {"B", "KB", "MB", "GB", "TB", "PB"};
11
+ int i = 0;
12
+ for (; qAbs(b) >= 1024 && i < 5; ++i) b /= 1024;
13
+ return QString::number(b, 'f', i ? prec : 0) + " " + u[i];
14
+ }
15
+ QString Fmt::count(double v)
16
+ {
17
+ const double a = qAbs(v);
18
+ return a >= 1e9 ? QString::number(v / 1e9, 'f', 1) + "G" : a >= 1e6 ? QString::number(v / 1e6, 'f', 1) + "M" : a >= 1e4 ? QString::number(v / 1e3, 'f', 1) + "K" : QString::number(v, 'f', 0);
19
+ }
20
+ QString Fmt::duration(double sec)
21
+ {
22
+ qint64 s = qint64(sec), d = s / 86400, h = s % 86400 / 3600, m = s % 3600 / 60;
23
+ return d ? QString("%1d %2h %3m").arg(d).arg(h).arg(m) : h ? QString("%1h %2m").arg(h).arg(m) : m ? QString("%1m %2s").arg(m).arg(s % 60) : QString("%1s").arg(s);
24
+ }
25
+
26
+ // ---- catalogues -------------------------------------------------------------
27
+ const QVector<Def> &ruleMetrics()
28
+ {
29
+ static const QVector<Def> d = {{"cpu", "CPU usage", "%"}, {"iowait", "CPU I/O wait", "%"}, {"load", "Load (1 min) per core", "%"},
30
+ {"mem", "Memory usage", "%"}, {"swap", "Swap usage", "%"}, {"disk", "Fullest disk usage", "%"}, {"diskio", "Busiest disk utilisation", "%"},
31
+ {"temp", "Hottest sensor", "°C"}, {"rx", "Network download", "MB/s"}, {"tx", "Network upload", "MB/s"}, {"failed", "Failed services", ""},
32
+ {"procs", "Process count", ""}, {"gpu", "GPU usage (max)", "%"}, {"gputemp", "GPU temperature (max)", "°C"}};
33
+ static const QVector<Def> noWait = d.mid(0, 1) + d.mid(2);
34
+ return P::posixCpu ? d : noWait;
35
+ }
36
+ QString defLabel(const QVector<Def> &d, const QString &k, bool unit)
37
+ {
38
+ for (const Def &x : d)
39
+ if (x.key == k) return unit ? x.unit : x.label;
40
+ return unit ? QString() : k;
41
+ }
42
+
43
+ QString Rule::conditionText() const
44
+ {
45
+ const QString u = defLabel(ruleMetrics(), metric, true);
46
+ return QString("%1 %2 %3%4").arg(defLabel(ruleMetrics(), metric), op).arg(value).arg(u.isEmpty() ? "" : " " + u) + (duration ? QString(" for %1 s").arg(duration) : "");
47
+ }
48
+ QString Rule::actionText() const { return defLabel(P::ruleActions(), action) + (arg.isEmpty() ? "" : ": " + arg); }
49
+
50
+ // ---- JSON: one field list per struct drives both saving and loading ---------------------------
51
+ #define F(f) v(#f, x.f);
52
+ template <class V> static void each(Rule &x, V v) { F(id) F(metric) F(op) F(action) F(arg) F(severity) F(enabled) F(value) F(duration) F(cooldown) }
53
+ template <class V> static void each(ServerConfig &x, V v) { F(id) F(name) F(group) F(host) F(user) F(keyFile) F(notes) F(port) F(interval) F(useSudo) F(enabled) }
54
+ template <class V> static void each(AutopilotConfig &x, V v)
55
+ {
56
+ F(enabled) F(dryRun) F(restartFailed) F(diskCleanup) F(anomalyAlerts) F(maxRestartsPerHour) F(runawayMinutes) F(diskForecastDays)
57
+ F(runawayCpu) F(diskCleanupAt) F(leakMemPressure) F(anomalyZ) F(runawayMode) F(leakMode) F(diskCleanupCommand)
58
+ }
59
+ #undef F
60
+ template <class T> static QJsonObject save(const T &c)
61
+ {
62
+ QJsonObject o;
63
+ each(const_cast<T &>(c), [&](const char *k, const auto &f) { o[k] = QJsonValue::fromVariant(QVariant::fromValue(f)); });
64
+ return o;
65
+ }
66
+ template <class T> static T load(const QJsonObject &o)
67
+ {
68
+ T c;
69
+ each(c, [&](const char *k, auto &f) { if (o.contains(k)) f = o[k].toVariant().value<std::decay_t<decltype(f)>>(); });
70
+ return c;
71
+ }
72
+
73
+ static QString xorB64(const QString &s, bool enc) // light obfuscation of secrets (NOT encryption)
74
+ {
75
+ static const QByteArray k = "ServerMonitor/obfuscation/v1";
76
+ QByteArray b = enc ? s.toUtf8() : QByteArray::fromBase64(s.toLatin1());
77
+ for (int i = 0; i < b.size(); ++i) b[i] = char(b[i] ^ k[i % k.size()]);
78
+ return enc ? QString(b.toBase64()) : QString::fromUtf8(b);
79
+ }
80
+
81
+ QJsonObject ServerConfig::toJson() const
82
+ {
83
+ QJsonObject o = save(*this);
84
+ QJsonArray rs;
85
+ for (const Rule &r : rules) rs << save(r);
86
+ o["transport"] = int(transport), o["password"] = xorB64(password, true), o["rules"] = rs, o["autopilot"] = save(autopilot);
87
+ return o;
88
+ }
89
+
90
+ ServerConfig ServerConfig::fromJson(const QJsonObject &o)
91
+ {
92
+ ServerConfig c = load<ServerConfig>(o);
93
+ c.autopilot = load<AutopilotConfig>(o["autopilot"].toObject());
94
+ if (o.contains("rules")) c.rules.clear();
95
+ for (const auto &v : o["rules"].toArray()) c.rules << load<Rule>(v.toObject());
96
+ for (Rule &r : c.rules)
97
+ if (r.id.isEmpty()) r.id = newId();
98
+ c.transport = o["transport"].toInt(1) == 0 ? Transport::Local : Transport::SSH;
99
+ c.password = xorB64(o["password"].toString(), false);
100
+ c.interval = qBound(1, c.interval, 300);
101
+ if (c.id.isEmpty()) c.id = newId();
102
+ return c;
103
+ }
104
+
105
+ QVector<Rule> ServerConfig::defaultRules()
106
+ {
107
+ QVector<Rule> rs;
108
+ for (auto [m, v, d, s] : {std::tuple{"cpu", 90, 60, "warning"}, {"mem", 90, 60, "warning"}, {"swap", 80, 120, "warning"},
109
+ {"disk", 90, 0, "critical"}, {"temp", 85, 30, "critical"}, {"load", 150, 120, "warning"}, {"failed", 0, 0, "warning"}}) {
110
+ Rule r;
111
+ r.id = newId(), r.metric = m, r.value = v, r.duration = d, r.severity = s;
112
+ rs << r;
113
+ }
114
+ return rs;
115
+ }
116
+ QString ServerConfig::newId() { return QUuid::createUuid().toString(QUuid::WithoutBraces).left(12); }
117
+ QString ServerConfig::address() const
118
+ {
119
+ if (transport == Transport::Local) return "this machine";
120
+ return (user.isEmpty() ? "" : user + "@") + host + (port != 22 ? QString(":%1").arg(port) : "");
121
+ }
122
+
123
+ double Metrics::gpuMax(bool t) const
124
+ {
125
+ double v = 0;
126
+ for (const GpuInfo &g : gpus) v = qMax(v, t ? g.temp : g.util);
127
+ return v;
128
+ }
Server Monitor(cqt-linux)/src/core/Model.h ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Data model: server config, rules, autopilot policy, parsed metrics, formatting.
2
+ #pragma once
3
+ #include "Platform.h"
4
+ #include <QHash>
5
+ #include <QJsonObject>
6
+ #include <QMap>
7
+ #include <QStringList>
8
+ #include <QVector>
9
+
10
+ namespace Fmt {
11
+ QString bytes(double b, int prec = 1);
12
+ inline QString rate(double b) { return bytes(b) + "/s"; }
13
+ inline QString pct(double p, int prec = 1) { return QString::number(p, 'f', prec) + "%"; }
14
+ inline QString temp(double c) { return QString::number(c, 'f', 0) + " °C"; }
15
+ QString count(double v);
16
+ QString duration(double s);
17
+ }
18
+
19
+ enum class Transport { Local, SSH };
20
+ inline QString transportName(Transport t) { return t == Transport::Local ? "Local" : "SSH"; }
21
+
22
+ const QVector<Def> &ruleMetrics();
23
+ QString defLabel(const QVector<Def> &d, const QString &k, bool unit = false);
24
+
25
+ // "When <metric> <op> <value> for <duration> s -> <action>(<arg>)"
26
+ struct Rule {
27
+ QString id, metric = "cpu", op = ">", action = "notify", arg, severity = "warning";
28
+ bool enabled = true;
29
+ double value = 90;
30
+ int duration = 60, cooldown = 300;
31
+ QString conditionText() const;
32
+ QString actionText() const;
33
+ };
34
+
35
+ // History-driven automatic control (evaluated by the Analyzer every minute).
36
+ struct AutopilotConfig {
37
+ bool enabled = true, dryRun = false, restartFailed = true, diskCleanup = false, anomalyAlerts = true;
38
+ int maxRestartsPerHour = 3, runawayMinutes = 10, diskForecastDays = 3;
39
+ double runawayCpu = 90, diskCleanupAt = 92, leakMemPressure = 90, anomalyZ = 3;
40
+ QString runawayMode = "renice", leakMode = "notify"; // none|renice|terminate, none|notify|terminate
41
+ QString diskCleanupCommand = P::cleanup;
42
+ };
43
+
44
+ struct ServerConfig {
45
+ QString id, name, group, host, user, keyFile, password, notes;
46
+ Transport transport = Transport::SSH;
47
+ int port = 22, interval = P::interval;
48
+ bool useSudo = false, enabled = true;
49
+ QVector<Rule> rules = defaultRules();
50
+ AutopilotConfig autopilot;
51
+ QString address() const;
52
+ QJsonObject toJson() const;
53
+ static ServerConfig fromJson(const QJsonObject &o);
54
+ static QVector<Rule> defaultRules();
55
+ static QString newId();
56
+ };
57
+
58
+ // ---- one parsed sample ------------------------------------------------------
59
+ struct CoreStat { double usage = 0, mhz = 0; };
60
+ struct MountInfo { QString device, type, mount; double total = 0, used = 0, avail = 0, pct = 0; };
61
+ struct DiskIO { QString name; double readBps = 0, writeBps = 0, readIops = 0, writeIops = 0, util = 0, totalRead = 0, totalWritten = 0; };
62
+ struct NetIf {
63
+ QString name, state;
64
+ int speed = -1;
65
+ bool virt = false;
66
+ double rxBps = 0, txBps = 0, rxPps = 0, txPps = 0, rxBytes = 0, txBytes = 0, errors = 0, drops = 0;
67
+ };
68
+ struct ProcInfo {
69
+ int pid = 0, ppid = 0, threads = 0, nice = 0;
70
+ QString name, user;
71
+ QChar state;
72
+ double cpu = 0, memPct = 0, rss = 0, vsz = 0, age = 0; // cpu: % of one core
73
+ };
74
+ struct ServiceInfo { QString unit, load, active, sub, description; };
75
+ struct TempSensor { QString name; double celsius = 0; };
76
+ struct GpuInfo { int index = 0; QString name; double util = 0, memUsed = 0, memTotal = 0, temp = 0, power = 0, fan = 0; };
77
+
78
+ struct Metrics {
79
+ bool valid = false;
80
+ qint64 timestamp = 0;
81
+ QString hostname, os, kernel, arch, cpuModel, virt;
82
+ int cpuCount = 0, loggedUsers = 0, procsRunning = 0, procsBlocked = 0, threadsTotal = 0, socketsUsed = 0;
83
+ int servicesFailed = 0, servicesRunning = 0;
84
+ double uptime = 0, load1 = 0, load5 = 0, load15 = 0;
85
+ double cpuUsage = 0, cpuUser = 0, cpuSystem = 0, cpuIowait = 0, cpuSteal = 0, cpuIrq = 0;
86
+ double ctxtPerSec = 0, intrPerSec = 0, forksPerSec = 0, avgMhz = 0;
87
+ double memTotal = 0, memFree = 0, memAvailable = 0, memUsed = 0, buffers = 0, cached = 0, shared = 0, slab = 0, dirty = 0;
88
+ double swapTotal = 0, swapUsed = 0, memPct = 0, swapPct = 0;
89
+ double diskReadBps = 0, diskWriteBps = 0, maxDiskPct = 0, maxDiskUtil = 0, netRxBps = 0, netTxBps = 0, maxTemp = 0;
90
+ QString fullestMount, busiestDisk;
91
+ QVector<CoreStat> cores;
92
+ QVector<MountInfo> mounts;
93
+ QVector<DiskIO> disks;
94
+ QVector<NetIf> nets;
95
+ QMap<QString, int> tcp; // ESTABLISHED -> n
96
+ QVector<ProcInfo> procs;
97
+ QVector<ServiceInfo> services;
98
+ QVector<TempSensor> temps;
99
+ QVector<GpuInfo> gpus;
100
+ double gpuMax(bool temp) const;
101
+ };
102
+
103
+ // Turns raw collector frames into Metrics; keeps counters for rates. process() is in Platform.cpp.
104
+ class MetricsEngine {
105
+ public:
106
+ Metrics process(const QByteArray &raw, qint64 nowMs);
107
+ void reset() { *this = MetricsEngine(); }
108
+
109
+ private:
110
+ double m_upt = 0;
111
+ QVector<QVector<double>> m_cpu;
112
+ QHash<QString, QVector<double>> m_ctr; // misc counters: "stat", "disk:sda", "net:eth0"
113
+ QHash<int, double> m_ticks;
114
+ QHash<QString, QString> m_info;
115
+ QHash<int, QString> m_users;
116
+ QVector<ServiceInfo> m_services;
117
+ QVector<GpuInfo> m_gpus;
118
+ };
Server Monitor(cqt-linux)/src/core/Platform.cpp ADDED
@@ -0,0 +1,371 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Linux: POSIX sh collector (reads /proc and /sys), its parser, and the control commands.
2
+ #include "Model.h"
3
+ #include <QRegularExpression>
4
+ #include <QSet>
5
+ #include <algorithm>
6
+
7
+ // One frame per interval: "@@SNAP_BEGIN", "@@S <section>" + raw lines, "@@SNAP_END". All maths happens in the parser.
8
+ static const char *const kCollector = R"SMSCRIPT(
9
+ sm_main() {
10
+ iv="${1:-2}" once="${2:-0}" n=0
11
+ export LC_ALL=C
12
+ while :; do
13
+ echo "@@SNAP_BEGIN"
14
+ if [ $((n % 15)) -eq 0 ]; then
15
+ echo "@@S info"
16
+ echo "hostname=$(cat /proc/sys/kernel/hostname 2>/dev/null)"
17
+ echo "kernel=$(uname -r 2>/dev/null)"
18
+ echo "arch=$(uname -m 2>/dev/null)"
19
+ echo "os=$(sed -n 's/^PRETTY_NAME=//p' /etc/os-release 2>/dev/null | tr -d '"')"
20
+ echo "cpumodel=$(grep -m1 -E '^(model name|Hardware|Processor|cpu model)' /proc/cpuinfo 2>/dev/null | cut -d: -f2- | sed 's/^ *//')"
21
+ echo "clk=$(getconf CLK_TCK 2>/dev/null || echo 100)"
22
+ echo "page=$(getconf PAGESIZE 2>/dev/null || echo 4096)"
23
+ echo "virt=$(systemd-detect-virt 2>/dev/null || echo unknown)"
24
+ echo "@@S passwd"; cut -d: -f1,3 /etc/passwd 2>/dev/null
25
+ fi
26
+ echo "@@S uptime"; cat /proc/uptime
27
+ echo "@@S loadavg"; cat /proc/loadavg
28
+ echo "@@S stat"
29
+ grep -E '^(cpu|ctxt|processes|procs_)' /proc/stat
30
+ awk '/^intr/ {print "intr", $2}' /proc/stat
31
+ echo "@@S meminfo"; cat /proc/meminfo
32
+ echo "@@S netdev"; cat /proc/net/dev
33
+ echo "@@S netstate"
34
+ for i in /sys/class/net/*; do
35
+ [ -e "$i" ] || continue
36
+ echo "${i##*/} $(cat "$i/operstate" 2>/dev/null || echo unknown) $(cat "$i/speed" 2>/dev/null || echo -1)"
37
+ done
38
+ echo "@@S diskstats"; cat /proc/diskstats
39
+ echo "@@S df"; df -P -T -k 2>/dev/null || df -P -k 2>/dev/null
40
+ echo "@@S sockstat"; cat /proc/net/sockstat 2>/dev/null
41
+ echo "@@S tcp"
42
+ cat /proc/net/tcp /proc/net/tcp6 2>/dev/null | awk '$4 ~ /^[0-9A-F][0-9A-F]$/ {c[$4]++} END {for (k in c) print k, c[k]}'
43
+ echo "@@S thermal"
44
+ for z in /sys/class/thermal/thermal_zone*; do
45
+ [ -r "$z/temp" ] && echo "$(cat "$z/type" 2>/dev/null)|$(cat "$z/temp" 2>/dev/null)"
46
+ done
47
+ for h in /sys/class/hwmon/hwmon*; do
48
+ [ -d "$h" ] || continue
49
+ hn=$(cat "$h/name" 2>/dev/null)
50
+ for t in "$h"/temp*_input; do
51
+ [ -r "$t" ] || continue
52
+ l=$(cat "${t%_input}_label" 2>/dev/null)
53
+ echo "$hn ${l:-${t##*/}}|$(cat "$t" 2>/dev/null)"
54
+ done
55
+ done
56
+ echo "@@S freq"
57
+ for c in /sys/devices/system/cpu/cpu[0-9]*; do
58
+ f=$(cat "$c/cpufreq/scaling_cur_freq" 2>/dev/null) && echo "${c##*/cpu} $f"
59
+ done
60
+ echo "@@S procs"
61
+ cat /proc/[0-9]*/stat 2>/dev/null | awk '{
62
+ if (!match($0, /\(.*\)/)) next
63
+ comm = substr($0, RSTART + 1, RLENGTH - 2)
64
+ rest = substr($0, RSTART + RLENGTH + 1)
65
+ k = split(rest, r, " ")
66
+ if (k < 22) next
67
+ print $1, r[1], r[2], r[12] + r[13], r[17], r[18], r[20], r[21], r[22], comm
68
+ }'
69
+ echo "@@S uids"; ls -ln /proc 2>/dev/null | awk '$NF ~ /^[0-9]+$/ {print $NF, $3}'
70
+ if [ $((n % 5)) -eq 0 ]; then
71
+ echo "@@S services"
72
+ systemctl list-units --type=service --all --no-legend --no-pager --plain 2>/dev/null | head -n 600
73
+ fi
74
+ if [ $((n % 3)) -eq 0 ] && command -v nvidia-smi >/dev/null 2>&1; then
75
+ echo "@@S gpu"
76
+ nvidia-smi --query-gpu=index,name,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw,fan.speed --format=csv,noheader,nounits 2>/dev/null
77
+ fi
78
+ echo "@@S users"; who 2>/dev/null | wc -l
79
+ echo "@@SNAP_END" || exit 0
80
+ [ "$once" = "once" ] && break
81
+ n=$((n + 1))
82
+ sleep "$iv"
83
+ done
84
+ }
85
+ sm_main "$@"
86
+ )SMSCRIPT";
87
+ static const char *const kRestartFailed = "for u in $(systemctl list-units --type=service --state=failed --no-legend --plain | awk '{print $1}'); do echo restart $u; systemctl restart $u; done";
88
+
89
+ namespace P {
90
+ const char *const prioLabel = "Nice", *const kernelPrefix = "Linux ",
91
+ *const sshHint = "Uses your system <b>ssh</b> client; nothing is installed on the server. Set up key login once with <code>ssh-copy-id user@host</code>.",
92
+ *const cleanup = "journalctl --vacuum-time=7d 2>/dev/null; apt-get clean 2>/dev/null; dnf clean all 2>/dev/null; "
93
+ "find /tmp /var/tmp -xdev -type f -atime +7 -delete 2>/dev/null; true";
94
+ const bool sudo = true, posixCpu = true;
95
+ const int interval = 2, normalPrio = 0;
96
+
97
+ QStringList shell(int iv) { return iv ? QStringList{"sh", "-s", "--", QString::number(iv)} : QStringList{"sh", "-s"}; }
98
+ QByteArray collector(int) { return kCollector; }
99
+ QByteArray wrap(const QString &cmd, bool sudo) { return (sudo ? "sudo -n sh -c " + quote(cmd) : cmd).toUtf8() + "\n"; }
100
+ QString quote(QString s) { return "'" + s.replace("'", "'\\''") + "'"; }
101
+ QString command(const QString &action, const QString &arg)
102
+ {
103
+ const QString n = QString::number(arg.toInt());
104
+ return QHash<QString, QString>{{"kill_pid", "kill -TERM " + n}, {"renice", "renice -n 19 -p " + n}, {"drop_caches", "sync && echo 3 > /proc/sys/vm/drop_caches"},
105
+ {"restart_service", QString("systemctl reset-failed %1 2>/dev/null; systemctl restart %1").arg(quote(arg))}, {"restart_failed", kRestartFailed}}.value(action);
106
+ }
107
+ QString serviceLogs(const QString &unit, int lines)
108
+ {
109
+ return QString("systemctl status --no-pager -l %1 2>&1 | head -n 15; echo; echo '==== journal ===='; journalctl -u %1 -n %2 --no-pager 2>&1").arg(quote(unit)).arg(lines);
110
+ }
111
+ QString power(bool reboot) { return QString("(sleep 2; systemctl %1) >/dev/null 2>&1 &").arg(reboot ? "reboot" : "poweroff"); }
112
+ bool isProtected(int pid, int ppid, double rss, const QString &name) { return pid <= 2 || ppid == 2 || rss <= 0 || name == "sshd" || name == "systemd"; } // init, kernel threads, ssh
113
+
114
+ const QVector<Def> &ruleActions()
115
+ {
116
+ static const QVector<Def> d = {{"notify", "Notify only", ""}, {"restart_failed", "Restart failed services", ""},
117
+ {"restart_service", "Restart a service", "nginx.service"}, {"kill_top_cpu", "Terminate top CPU process", ""},
118
+ {"kill_top_mem", "Terminate top memory process", ""}, {"drop_caches", "Sync + drop page cache", ""},
119
+ {"command", "Run a command", "find /tmp -mtime +7 -delete"}};
120
+ return d;
121
+ }
122
+ const QVector<Cmd> &procActions()
123
+ {
124
+ static const QVector<Cmd> d = {{"Terminate", "kill -TERM %1"}, {"Kill", "kill -KILL %1", true}, {"Hang up", "kill -HUP %1", false, true, false},
125
+ {"Suspend", "kill -STOP %1"}, {"Resume", "kill -CONT %1", false, false}};
126
+ return d;
127
+ }
128
+ const QVector<Cmd> &priorities()
129
+ {
130
+ static const QVector<Cmd> d = {{"-20 (highest)", "renice -n -20 -p %1"}, {"-10", "renice -n -10 -p %1"}, {"0 (normal)", "renice -n 0 -p %1"},
131
+ {"10", "renice -n 10 -p %1"}, {"19 (lowest)", "renice -n 19 -p %1"}};
132
+ return d;
133
+ }
134
+ const QVector<Cmd> &serviceActions()
135
+ {
136
+ static const QVector<Cmd> d = {{"Start", "systemctl start %1", false, false}, {"Stop", "systemctl stop %1", true}, {"Restart", "systemctl restart %1"},
137
+ {"Reload", "systemctl reload %1", false, false}, {"Enable", "systemctl enable %1", false, false}, {"Disable", "systemctl disable %1", true}};
138
+ return d;
139
+ }
140
+ const QVector<Cmd> &diagnostics()
141
+ {
142
+ static const QVector<Cmd> d = {{"Disk usage", "df -hT -x tmpfs -x devtmpfs -x squashfs -x overlay"}, {"Largest dirs in /var", "du -xh --max-depth=2 /var 2>/dev/null | sort -rh | head -n 20"},
143
+ {"Memory", "free -h; echo; vmstat 1 3"}, {"Top CPU processes", "ps -eo pid,user,pcpu,pmem,rss,etime,comm --sort=-pcpu | head -n 20"},
144
+ {"Listening ports", "ss -tulpn 2>/dev/null || netstat -tulpn"}, {"Kernel messages", "dmesg -T 2>/dev/null | tail -n 40 || journalctl -k -n 40 --no-pager"},
145
+ {"Errors in journal", "journalctl -p err -n 60 --no-pager"}, {"Failed services", "systemctl --failed --no-pager"},
146
+ {"Logged-in users", "w"}, {"Last reboots", "last -x reboot shutdown 2>/dev/null | head -n 15"}};
147
+ return d;
148
+ }
149
+ const QVector<Cmd> &systemActions()
150
+ {
151
+ static const QVector<Cmd> d = {{"Sync + drop page cache", "sync && echo 3 > /proc/sys/vm/drop_caches && echo done"}, {"Vacuum journal to 200 MB", "journalctl --vacuum-size=200M"},
152
+ {"Clean package cache", "(apt-get clean || dnf clean all || yum clean all) 2>&1"}, {"Restart failed services", QString(kRestartFailed) + "; echo done"},
153
+ {"Reboot", "(sleep 2; systemctl reboot) >/dev/null 2>&1 & echo 'reboot scheduled'", true},
154
+ {"Shut down", "(sleep 2; systemctl poweroff) >/dev/null 2>&1 & echo 'shutdown scheduled'", true}};
155
+ return d;
156
+ }
157
+ } // namespace P
158
+
159
+ // ---- collector frame parser ----------------------------------------------------------------
160
+ Metrics MetricsEngine::process(const QByteArray &raw, qint64 now)
161
+ {
162
+ QHash<QString, QList<QByteArray>> sec;
163
+ QList<QByteArray> *cur = nullptr;
164
+ for (const QByteArray &l : raw.split('\n')) {
165
+ if (l.startsWith("@@S ")) cur = &sec[QString(l.mid(4).trimmed())];
166
+ else if (cur && !l.startsWith("@@")) cur->append(l);
167
+ }
168
+ auto F = [](const QByteArray &l) { return l.simplified().split(' '); };
169
+ auto L = [&](const char *k) { return sec.value(k); };
170
+ auto first = [&](const char *k) { const auto v = L(k); return v.isEmpty() ? QList<QByteArray>() : F(v[0]); };
171
+ Metrics m;
172
+ m.timestamp = now;
173
+ for (const auto &l : L("info")) {
174
+ const int e = l.indexOf('=');
175
+ if (e > 0) m_info[l.left(e)] = QString::fromUtf8(l.mid(e + 1)).trimmed();
176
+ }
177
+ if (sec.contains("passwd")) {
178
+ m_users.clear();
179
+ for (const auto &l : L("passwd")) {
180
+ const int c = l.lastIndexOf(':');
181
+ if (c > 0) m_users[l.mid(c + 1).toInt()] = l.left(c);
182
+ }
183
+ }
184
+ m.hostname = m_info["hostname"], m.os = m_info["os"], m.kernel = m_info["kernel"], m.arch = m_info["arch"];
185
+ m.cpuModel = m_info["cpumodel"], m.virt = m_info["virt"];
186
+ const int clk = qMax(1, m_info.value("clk", "100").toInt()), page = qMax(512, m_info.value("page", "4096").toInt());
187
+ const auto la = first("loadavg");
188
+ m.load1 = la.value(0).toDouble(), m.load5 = la.value(1).toDouble(), m.load15 = la.value(2).toDouble();
189
+ m.uptime = first("uptime").value(0).toDouble();
190
+ if (m.uptime <= 0) return m;
191
+ const double dt = m_upt > 0 ? m.uptime - m_upt : 0;
192
+ const bool rates = dt > 0.05;
193
+ QHash<QString, QVector<double>> next;
194
+ auto delta = [&](const QString &key, const QVector<double> &v) { // per-second rates of a counter vector
195
+ QVector<double> d(v.size(), 0.0);
196
+ const auto p = m_ctr.value(key);
197
+ if (rates && p.size() == v.size())
198
+ for (int i = 0; i < v.size(); ++i) d[i] = qMax(0.0, (v[i] - p[i]) / dt);
199
+ next[key] = v;
200
+ return d;
201
+ };
202
+
203
+ // CPU
204
+ QVector<QVector<double>> cpu;
205
+ QVector<double> st(3);
206
+ for (const auto &l : L("stat")) {
207
+ const auto f = F(l);
208
+ if (f[0].startsWith("cpu")) {
209
+ QVector<double> t;
210
+ for (int i = 1; i <= 8; ++i) t << f.value(i).toDouble();
211
+ cpu << t;
212
+ } else if (f[0] == "ctxt") st[0] = f.value(1).toDouble();
213
+ else if (f[0] == "intr") st[1] = f.value(1).toDouble();
214
+ else if (f[0] == "processes") st[2] = f.value(1).toDouble();
215
+ else if (f[0] == "procs_running") m.procsRunning = f.value(1).toInt();
216
+ else if (f[0] == "procs_blocked") m.procsBlocked = f.value(1).toInt();
217
+ }
218
+ m.cpuCount = qMax(1, cpu.size() - 1);
219
+ m.cores.resize(m.cpuCount);
220
+ double jiffies = 0;
221
+ if (rates && m_cpu.size() == cpu.size())
222
+ for (int i = 0; i < cpu.size(); ++i) {
223
+ double d[8], tot = 0;
224
+ for (int k = 0; k < 8; ++k) tot += d[k] = cpu[i][k] - m_cpu[i][k];
225
+ if (tot <= 0) continue;
226
+ auto p = [&](int k) { return qBound(0.0, d[k] * 100 / tot, 100.0); }; // user nice system idle iowait irq softirq steal
227
+ const double use = qBound(0.0, 100 - p(3) - p(4), 100.0);
228
+ if (i) m.cores[i - 1].usage = use;
229
+ else jiffies = tot, m.cpuUsage = use, m.cpuUser = p(0) + p(1), m.cpuSystem = p(2), m.cpuIowait = p(4), m.cpuIrq = p(5) + p(6), m.cpuSteal = p(7);
230
+ }
231
+ m_cpu = cpu;
232
+ const auto sd = delta("stat", st);
233
+ m.ctxtPerSec = sd[0], m.intrPerSec = sd[1], m.forksPerSec = sd[2];
234
+ int nf = 0;
235
+ for (const auto &l : L("freq")) {
236
+ const auto f = F(l);
237
+ const int i = f.value(0).toInt();
238
+ if (i >= 0 && i < m.cores.size()) m.avgMhz += m.cores[i].mhz = f.value(1).toDouble() / 1000, ++nf;
239
+ }
240
+ m.avgMhz = nf ? m.avgMhz / nf : 0;
241
+
242
+ // memory
243
+ QHash<QByteArray, double> mi;
244
+ for (const auto &l : L("meminfo")) {
245
+ const int c = l.indexOf(':');
246
+ if (c > 0) mi[l.left(c)] = F(l.mid(c + 1)).value(0).toDouble() * 1024;
247
+ }
248
+ m.memTotal = mi["MemTotal"], m.memFree = mi["MemFree"], m.buffers = mi["Buffers"], m.cached = mi["Cached"] + mi["SReclaimable"];
249
+ m.memAvailable = mi.contains("MemAvailable") ? mi["MemAvailable"] : m.memFree + m.buffers + m.cached;
250
+ m.shared = mi["Shmem"], m.slab = mi["Slab"], m.dirty = mi["Dirty"], m.swapTotal = mi["SwapTotal"];
251
+ m.memUsed = qMax(0.0, m.memTotal - m.memAvailable), m.swapUsed = qMax(0.0, m.swapTotal - mi["SwapFree"]);
252
+ m.memPct = m.memTotal > 0 ? m.memUsed * 100 / m.memTotal : 0;
253
+ m.swapPct = m.swapTotal > 0 ? m.swapUsed * 100 / m.swapTotal : 0;
254
+
255
+ // network
256
+ static const QRegularExpression virt("^(lo|veth|docker|br-|virbr|cni|flannel|cali|vxlan|kube|tun|tap)");
257
+ QHash<QString, QList<QByteArray>> state;
258
+ for (const auto &l : L("netstate")) state[F(l)[0]] = F(l);
259
+ for (const auto &l : L("netdev")) {
260
+ const int c = l.indexOf(':');
261
+ const auto f = F(l.mid(c + 1));
262
+ if (c <= 0 || f.size() < 16) continue;
263
+ NetIf n;
264
+ n.name = l.left(c).trimmed();
265
+ n.virt = virt.match(n.name).hasMatch();
266
+ n.state = state[n.name].value(1, "unknown"), n.speed = state[n.name].value(2, "-1").toInt();
267
+ n.rxBytes = f[0].toDouble(), n.txBytes = f[8].toDouble();
268
+ n.errors = f[2].toDouble() + f[10].toDouble(), n.drops = f[3].toDouble() + f[11].toDouble();
269
+ const auto d = delta("net:" + n.name, {n.rxBytes, n.txBytes, f[1].toDouble(), f[9].toDouble()});
270
+ n.rxBps = d[0], n.txBps = d[1], n.rxPps = d[2], n.txPps = d[3];
271
+ if (!n.virt) m.netRxBps += n.rxBps, m.netTxBps += n.txBps;
272
+ m.nets << n;
273
+ }
274
+ std::sort(m.nets.begin(), m.nets.end(), [](const NetIf &a, const NetIf &b) { return a.virt != b.virt ? !a.virt : a.name < b.name; });
275
+ static const QStringList tcpNames = {"", "ESTABLISHED", "SYN_SENT", "SYN_RECV", "FIN_WAIT1", "FIN_WAIT2", "TIME_WAIT", "CLOSE", "CLOSE_WAIT", "LAST_ACK", "LISTEN", "CLOSING"};
276
+ for (const auto &l : L("tcp")) m.tcp[tcpNames.value(F(l)[0].toInt(nullptr, 16), "?")] += F(l).value(1).toInt();
277
+ for (const auto &l : L("sockstat"))
278
+ if (l.startsWith("sockets:")) m.socketsUsed = F(l).value(2).toInt();
279
+
280
+ // disks: whole devices + device-mapper; totals over physical disks only
281
+ static const QRegularExpression whole("^(sd[a-z]+|vd[a-z]+|xvd[a-z]+|hd[a-z]+|nvme\\d+n\\d+|mmcblk\\d+|md\\d+)$");
282
+ for (const auto &l : L("diskstats")) {
283
+ const auto f = F(l);
284
+ if (f.size() < 14) continue;
285
+ DiskIO d;
286
+ d.name = f[2];
287
+ const bool w = whole.match(d.name).hasMatch();
288
+ if (!w && !d.name.startsWith("dm-")) continue;
289
+ d.totalRead = f[5].toDouble() * 512, d.totalWritten = f[9].toDouble() * 512;
290
+ const auto r = delta("disk:" + d.name, {f[3].toDouble(), d.totalRead, f[7].toDouble(), d.totalWritten, f[12].toDouble()});
291
+ d.readIops = r[0], d.readBps = r[1], d.writeIops = r[2], d.writeBps = r[3], d.util = qMin(100.0, r[4] / 10);
292
+ if (w && !d.name.startsWith("md")) {
293
+ m.diskReadBps += d.readBps, m.diskWriteBps += d.writeBps;
294
+ if (d.util >= m.maxDiskUtil) m.maxDiskUtil = d.util, m.busiestDisk = d.name;
295
+ }
296
+ m.disks << d;
297
+ }
298
+ static const QSet<QString> skipFs = {"tmpfs", "devtmpfs", "squashfs", "overlay", "efivarfs", "ramfs", "proc", "sysfs", "autofs",
299
+ "nsfs", "devfs", "cgroup", "cgroup2", "fuse.snapfuse", "fuse.portal"};
300
+ const auto df = L("df");
301
+ const int b = !df.isEmpty() && df[0].contains("Type") ? 1 : 0;
302
+ QSet<QString> seen;
303
+ for (int i = 1; i < df.size(); ++i) {
304
+ const auto f = F(df[i]);
305
+ if (f.size() < 6 + b) continue;
306
+ MountInfo mt;
307
+ mt.device = f[0], mt.type = b ? f[1] : QByteArray();
308
+ mt.total = f[1 + b].toDouble() * 1024, mt.used = f[2 + b].toDouble() * 1024, mt.avail = f[3 + b].toDouble() * 1024;
309
+ mt.mount = f.mid(5 + b).join(' ');
310
+ const QString key = mt.device + QString::number(mt.total);
311
+ if (skipFs.contains(b ? mt.type : mt.device) || mt.total <= 0 || mt.mount.startsWith("/snap/") || (mt.device.startsWith('/') && seen.contains(key))) continue;
312
+ seen << key;
313
+ mt.pct = mt.used + mt.avail > 0 ? mt.used * 100 / (mt.used + mt.avail) : 0;
314
+ if (mt.pct >= m.maxDiskPct) m.maxDiskPct = mt.pct, m.fullestMount = mt.mount;
315
+ m.mounts << mt;
316
+ }
317
+
318
+ // processes: "pid state ppid ticks nice threads start vsize rss comm..."
319
+ QHash<int, int> uid;
320
+ for (const auto &l : L("uids")) uid[F(l)[0].toInt()] = F(l).value(1).toInt();
321
+ QHash<int, double> ticks;
322
+ const double perCore = jiffies > 0 ? jiffies / m.cpuCount : rates ? dt * clk : 0;
323
+ for (const auto &l : L("procs")) {
324
+ const auto f = l.split(' ');
325
+ ProcInfo p;
326
+ if (f.size() < 10 || (p.pid = f[0].toInt()) <= 0) continue;
327
+ p.state = f[1].isEmpty() ? '?' : f[1][0];
328
+ p.ppid = f[2].toInt(), p.nice = f[4].toInt(), p.threads = f[5].toInt();
329
+ p.age = qMax(0.0, m.uptime - f[6].toDouble() / clk), p.vsz = f[7].toDouble(), p.rss = f[8].toDouble() * page;
330
+ p.name = QString::fromUtf8(f.mid(9).join(' '));
331
+ ticks[p.pid] = f[3].toDouble();
332
+ if (perCore > 0 && m_ticks.contains(p.pid)) p.cpu = qBound(0.0, (ticks[p.pid] - m_ticks[p.pid]) * 100 / perCore, 100.0 * m.cpuCount);
333
+ p.memPct = m.memTotal > 0 ? p.rss * 100 / m.memTotal : 0;
334
+ p.user = uid.contains(p.pid) ? m_users.value(uid[p.pid], QString::number(uid[p.pid])) : "?";
335
+ m.threadsTotal += p.threads;
336
+ m.procs << p;
337
+ }
338
+ std::sort(m.procs.begin(), m.procs.end(), [](const ProcInfo &a, const ProcInfo &b) { return a.cpu != b.cpu ? a.cpu > b.cpu : a.rss > b.rss; });
339
+
340
+ // services / GPUs arrive every few samples: keep the last list
341
+ if (sec.contains("services")) {
342
+ m_services.clear();
343
+ for (const auto &l : L("services")) {
344
+ const auto f = F(l);
345
+ if (f.size() >= 4 && f[0].endsWith(".service")) m_services << ServiceInfo{f[0], f[1], f[2], f[3], QString::fromUtf8(f.mid(4).join(' '))};
346
+ }
347
+ }
348
+ m.services = m_services;
349
+ for (const auto &s : m.services) m.servicesFailed += s.active == "failed", m.servicesRunning += s.sub == "running";
350
+ if (sec.contains("gpu")) {
351
+ m_gpus.clear();
352
+ for (const auto &l : L("gpu")) {
353
+ const auto f = l.split(',');
354
+ auto n = [&](int i) { return f[i].trimmed().toDouble(); };
355
+ if (f.size() >= 8) m_gpus << GpuInfo{int(n(0)), f[1].trimmed(), n(2), n(3), n(4), n(5), n(6), n(7)};
356
+ }
357
+ }
358
+ m.gpus = m_gpus;
359
+ QSet<QString> tn;
360
+ for (const auto &l : L("thermal")) {
361
+ const int bar = l.lastIndexOf('|');
362
+ TempSensor t{QString::fromUtf8(l.left(bar)).trimmed(), l.mid(bar + 1).toDouble() / 1000};
363
+ if (bar <= 0 || t.celsius <= 0 || t.celsius > 150 || tn.contains(t.name)) continue;
364
+ tn << t.name, m.temps << t, m.maxTemp = qMax(m.maxTemp, t.celsius);
365
+ }
366
+ m.loggedUsers = first("users").value(0).toInt();
367
+
368
+ m_ctr = next, m_ticks = ticks, m_upt = m.uptime;
369
+ m.valid = rates; // the first sample has no rates yet
370
+ return m;
371
+ }
Server Monitor(cqt-linux)/src/core/Platform.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Everything that depends on the operating system of the monitored machines: how to start a shell, the
2
+ // collector script with its parser (MetricsEngine::process), and the control commands. Linux and Windows
3
+ // editions differ only in Platform.cpp.
4
+ #pragma once
5
+ #include <QStringList>
6
+ #include <QVector>
7
+
8
+ struct Def { QString key, label, unit; }; // rule metric / action catalogue
9
+ struct Cmd { QString label, cmd; bool danger = false, confirm = true, button = true; }; // cmd: %1 = pid or quoted name
10
+
11
+ namespace P {
12
+ extern const char *const prioLabel, *const kernelPrefix, *const sshHint, *const cleanup; // cleanup: default disk cleanup command
13
+ extern const bool sudo, posixCpu; // "sudo -n" exists; CPU time has I/O wait + steal
14
+ extern const int interval, normalPrio; // default sample interval (s); priority value of an ordinary process
15
+ QStringList shell(int interval = 0); // argv of a shell that runs a script from stdin (interval > 0: collector arguments)
16
+ QByteArray collector(int interval); // stdin for the collector
17
+ QByteArray wrap(const QString &cmd, bool sudo); // stdin for a one-shot command
18
+ QString quote(QString s); // shell quoting
19
+ QString command(const QString &action, const QString &arg); // kill_pid | renice | restart_service | restart_failed | drop_caches
20
+ QString serviceLogs(const QString &unit, int lines);
21
+ QString power(bool reboot);
22
+ bool isProtected(int pid, int ppid, double rss, const QString &name); // never killed automatically, no leak / runaway findings
23
+ const QVector<Def> &ruleActions(); // unit = argument hint ("" = none)
24
+ const QVector<Cmd> &procActions(), &priorities(), &serviceActions(), &diagnostics(), &systemActions();
25
+ }
Server Monitor(cqt-linux)/src/core/Session.cpp ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "Session.h"
2
+ #include <QCoreApplication>
3
+ #include <QDir>
4
+ #include <QFile>
5
+ #include <QJsonArray>
6
+ #include <QJsonDocument>
7
+ #include <QSaveFile>
8
+ #include <QStandardPaths>
9
+ #include <QTextStream>
10
+ #include <utility>
11
+
12
+ // ---- Link ---------------------------------------------------------------------------------
13
+ Link::Link(const ServerConfig &c, QObject *parent) : QObject(parent), m_c(c) {}
14
+ Link::~Link()
15
+ {
16
+ for (QProcess *p : findChildren<QProcess *>()) {
17
+ p->disconnect(this);
18
+ if (p->state() != QProcess::NotRunning) p->kill(), p->waitForFinished(500);
19
+ }
20
+ }
21
+
22
+ QProcess *Link::spawn(const QStringList &shell)
23
+ {
24
+ auto *p = new QProcess(this);
25
+ QStringList a;
26
+ if (m_c.transport == Transport::Local) {
27
+ p->setProgram(shell[0]), p->setArguments(shell.mid(1));
28
+ } else {
29
+ for (const char *o : {"ConnectTimeout=10", "ServerAliveInterval=10", "ServerAliveCountMax=3", "StrictHostKeyChecking=accept-new", "LogLevel=ERROR"}) a << "-o" << o;
30
+ auto env = QProcessEnvironment::systemEnvironment();
31
+ if (m_c.password.isEmpty()) a << "-o" << "BatchMode=yes";
32
+ else { // our own executable answers ssh's password prompt (see main.cpp)
33
+ a << "-o" << "NumberOfPasswordPrompts=1";
34
+ env.insert("SSH_ASKPASS", QDir::toNativeSeparators(QCoreApplication::applicationFilePath()));
35
+ env.insert("SSH_ASKPASS_REQUIRE", "force");
36
+ env.insert("SERVERMONITOR_ASKPASS", m_c.password);
37
+ if (!env.contains("DISPLAY")) env.insert("DISPLAY", ":0");
38
+ }
39
+ p->setProcessEnvironment(env);
40
+ if (!m_c.keyFile.isEmpty()) a << "-i" << (m_c.keyFile.startsWith("~/") ? QDir::homePath() + m_c.keyFile.mid(1) : m_c.keyFile);
41
+ if (m_c.port != 22) a << "-p" << QString::number(m_c.port);
42
+ p->setProgram("ssh"), p->setArguments(a << "-T" << (m_c.user.isEmpty() ? m_c.host : m_c.user + "@" + m_c.host) << shell.join(' '));
43
+ }
44
+ return p;
45
+ }
46
+ // Started only after the signals are connected: on Windows a failed start is reported inside start().
47
+ static void feed(QProcess *p, const QByteArray &input)
48
+ {
49
+ p->start();
50
+ if (p->state() != QProcess::NotRunning) p->write(input), p->closeWriteChannel();
51
+ }
52
+
53
+ void Link::start()
54
+ {
55
+ QProcess *p = spawn(P::shell(m_c.interval));
56
+ connect(p, &QProcess::readyReadStandardOutput, this, [this, p] {
57
+ m_buf += p->readAllStandardOutput();
58
+ for (int end; (end = m_buf.indexOf("@@SNAP_END")) >= 0;) {
59
+ const int begin = m_buf.lastIndexOf("@@SNAP_BEGIN", end);
60
+ if (begin >= 0) emit snapshot(m_buf.mid(begin, end - begin));
61
+ m_buf.remove(0, end + 10);
62
+ }
63
+ if (m_buf.size() > 8 << 20) m_buf.clear();
64
+ });
65
+ connect(p, &QProcess::readyReadStandardError, this, [this, p] { m_err = (m_err + p->readAllStandardError()).right(4096); });
66
+ connect(p, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, [this](int code) {
67
+ const QStringList l = QString(m_err).split('\n', Qt::SkipEmptyParts);
68
+ emit disconnected(l.isEmpty() ? QString("connection closed (exit code %1)").arg(code) : l.last());
69
+ });
70
+ connect(p, &QProcess::errorOccurred, this, [this, p](QProcess::ProcessError e) {
71
+ if (e == QProcess::FailedToStart) emit disconnected("cannot start " + p->program() + ": " + p->errorString());
72
+ });
73
+ feed(p, P::collector(m_c.interval));
74
+ }
75
+
76
+ int Link::exec(const QByteArray &input, int timeoutMs)
77
+ {
78
+ const int id = m_next++;
79
+ QProcess *p = spawn(P::shell());
80
+ p->setProcessChannelMode(QProcess::MergedChannels);
81
+ QTimer::singleShot(timeoutMs, p, [p] { p->kill(); });
82
+ connect(p, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, [this, p, id](int code, QProcess::ExitStatus st) {
83
+ emit execFinished(id, st == QProcess::CrashExit ? -1 : code, p->readAll() + (st == QProcess::CrashExit ? "\n[killed or timed out]" : ""));
84
+ p->deleteLater();
85
+ });
86
+ connect(p, &QProcess::errorOccurred, this, [this, p, id](QProcess::ProcessError e) {
87
+ if (e == QProcess::FailedToStart) emit execFinished(id, -1, p->errorString()), p->deleteLater();
88
+ }, Qt::QueuedConnection); // queued: the caller has to learn the id first
89
+ feed(p, input);
90
+ return id;
91
+ }
92
+
93
+ // ---- live history -----------------------------------------------------------------------
94
+ QString statusName(Status s) { return QStringList{"Disabled", "Connecting", "Online", "Offline"}.value(int(s)); }
95
+
96
+ void Live::push(const Metrics &m)
97
+ {
98
+ const int cap = 1800, n = t.size() + 1;
99
+ auto add = [&](QVector<double> &v, double x) {
100
+ if (v.size() < n - 1) v.insert(0, n - 1 - v.size(), 0.0); // align series that appeared later
101
+ v << x;
102
+ if (v.size() > cap) v.remove(0, v.size() - cap);
103
+ };
104
+ t << m.timestamp;
105
+ if (t.size() > cap) t.remove(0, t.size() - cap);
106
+ const double vals[N] = {m.cpuUsage, m.cpuUser, m.cpuSystem + m.cpuIrq, m.cpuIowait, m.cpuSteal, m.memPct,
107
+ m.memTotal > 0 ? (m.cached + m.buffers) * 100 / m.memTotal : 0, m.swapPct, m.netRxBps, m.netTxBps,
108
+ m.diskReadBps, m.diskWriteBps, m.load1};
109
+ for (int i = 0; i < N; ++i) add(s[i], vals[i]);
110
+ for (const NetIf &i : m.nets) add(ifRx[i.name], i.rxBps), add(ifTx[i.name], i.txBps);
111
+ }
112
+
113
+ // ---- session ----------------------------------------------------------------------------
114
+ ServerSession::ServerSession(const ServerConfig &c, QObject *parent) : QObject(parent), m_cfg(c), m_store(ServerManager::configDir() + "/history/" + c.id)
115
+ {
116
+ m_retry.setSingleShot(true), m_watchdog.setSingleShot(true);
117
+ connect(&m_retry, &QTimer::timeout, this, &ServerSession::start);
118
+ connect(&m_watchdog, &QTimer::timeout, this, [this] { onLost("no data received (timeout)"); });
119
+ connect(&m_analysisTimer, &QTimer::timeout, this, &ServerSession::analyzeNow);
120
+ connect(&m_offlineTick, &QTimer::timeout, this, [this] { // downtime -> availability: one sample per interval, like uptime
121
+ if (m_status == Status::Offline || (m_status == Status::Connecting && m_retries)) record(false);
122
+ });
123
+ m_analysisTimer.start(60000), m_offlineTick.start(c.interval * 1000);
124
+ QTimer::singleShot(3000, this, &ServerSession::analyzeNow);
125
+ }
126
+ ServerSession::~ServerSession() { stop(); }
127
+
128
+ void ServerSession::setConfig(const ServerConfig &c)
129
+ {
130
+ const bool reconnect = c.transport != m_cfg.transport || c.host != m_cfg.host || c.port != m_cfg.port || c.user != m_cfg.user ||
131
+ c.keyFile != m_cfg.keyFile || c.password != m_cfg.password || c.interval != m_cfg.interval || c.enabled != m_cfg.enabled;
132
+ m_cfg = c, m_offlineTick.setInterval(c.interval * 1000);
133
+ if (reconnect) m_live = Live(), m_m = Metrics(), m_procs.clear(), m_svcs.clear(), c.enabled ? start() : stop(); // may be another machine now
134
+ emit updated();
135
+ }
136
+
137
+ void ServerSession::drop(const QString &why)
138
+ {
139
+ if (m_link) m_link->disconnect(this), m_link->deleteLater();
140
+ m_link = nullptr;
141
+ for (const Done &d : std::exchange(m_pending, {})) d(-1, why);
142
+ }
143
+
144
+ void ServerSession::start()
145
+ {
146
+ drop("connection restarted");
147
+ m_retry.stop();
148
+ if (!m_cfg.enabled) return setStatus(Status::Disabled);
149
+ m_engine.reset(), m_m.valid = false; // online() only again with a fresh sample
150
+ m_link = new Link(m_cfg, this);
151
+ connect(m_link, &Link::snapshot, this, &ServerSession::onFrame);
152
+ connect(m_link, &Link::disconnected, this, &ServerSession::onLost);
153
+ connect(m_link, &Link::execFinished, this, [this](int id, int code, const QString &out) { if (Done d = m_pending.take(id)) d(code, out); });
154
+ setStatus(Status::Connecting), m_watchdog.start(25000), m_link->start();
155
+ }
156
+
157
+ void ServerSession::stop()
158
+ {
159
+ m_retry.stop(), m_watchdog.stop(), drop("connection stopped");
160
+ setStatus(m_cfg.enabled ? Status::Offline : Status::Disabled);
161
+ }
162
+
163
+ void ServerSession::setStatus(Status s, const QString &err)
164
+ {
165
+ if (!err.isEmpty() || s == Status::Online) m_err = err;
166
+ if (s != m_status) m_status = s, emit updated();
167
+ }
168
+
169
+ void ServerSession::onFrame(const QByteArray &raw)
170
+ {
171
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
172
+ m_watchdog.start(qMax(15, m_cfg.interval * 5 + 10) * 1000);
173
+ Metrics m = m_engine.process(raw, now);
174
+ if (m.uptime <= 0) return;
175
+ if (m_status != Status::Online) {
176
+ m_retries = 0;
177
+ if (std::exchange(m_offlineAlerted, false)) raise("resolved", "Server is back online");
178
+ setStatus(Status::Online);
179
+ }
180
+ if (!m.valid || m_paused) return; // first sample has no rates yet
181
+ if (m.uptime < m_m.uptime) m_procs.clear(); // rebooted: PIDs start again, old trends would be blamed on new processes
182
+ const bool first = !m_m.valid; // first sample of this connection: analyze at once, the last analysis saw "unreachable"
183
+ m_m = m, m_live.push(m), record(true), track(now), evaluateRules();
184
+ if (first) analyzeNow();
185
+ emit updated();
186
+ }
187
+
188
+ void ServerSession::onLost(const QString &why)
189
+ {
190
+ m_watchdog.stop(), drop("connection lost: " + why);
191
+ const bool was = m_status == Status::Online;
192
+ setStatus(Status::Offline, why);
193
+ if ((was || m_retries == 1) && !m_offlineAlerted) raise("critical", "Server is unreachable: " + why), m_offlineAlerted = true;
194
+ if (m_cfg.enabled) m_retry.start(QVector<int>{3, 5, 10, 20, 30, 60}[qMin(m_retries++, 5)] * 1000); // back-off
195
+ }
196
+
197
+ void ServerSession::exec(const QString &cmd, bool privileged, Done done, int timeoutMs)
198
+ {
199
+ if (!m_link || m_status != Status::Online) {
200
+ if (done) QTimer::singleShot(0, this, [done] { done(-1, "server is not connected"); });
201
+ return;
202
+ }
203
+ const int id = m_link->exec(P::wrap(cmd, privileged && m_cfg.useSudo), timeoutMs);
204
+ if (done) m_pending[id] = done;
205
+ }
206
+
207
+ double ServerSession::metricValue(const QString &k) const
208
+ {
209
+ const Metrics &m = m_m;
210
+ const QHash<QString, double> v = {{"cpu", m.cpuUsage}, {"iowait", m.cpuIowait}, {"load", m.load1 * 100 / qMax(1, m.cpuCount)},
211
+ {"mem", m.memPct}, {"swap", m.swapPct}, {"disk", m.maxDiskPct}, {"diskio", m.maxDiskUtil}, {"temp", m.maxTemp},
212
+ {"rx", m.netRxBps / 1e6}, {"tx", m.netTxBps / 1e6}, {"failed", double(m.servicesFailed)}, {"procs", double(m.procs.size())},
213
+ {"gpu", m.gpuMax(false)}, {"gputemp", m.gpuMax(true)}};
214
+ return v.value(k);
215
+ }
216
+
217
+ QStringList ServerSession::activeAlerts() const
218
+ {
219
+ QStringList out;
220
+ if (m_status == Status::Offline) out << "Unreachable: " + m_err;
221
+ for (const Rule &r : m_cfg.rules)
222
+ if (m_rules.value(r.id).active) out << r.conditionText();
223
+ return out;
224
+ }
225
+
226
+ void ServerSession::raise(const QString &sev, const QString &msg) { emit alertRaised({QDateTime::currentDateTime(), m_cfg.name, sev, msg}); }
227
+
228
+ void ServerSession::record(bool up)
229
+ {
230
+ const Metrics &m = m_m;
231
+ const float v[H_COUNT] = {float(m.cpuUsage), float(m.cpuIowait), float(m.load1), float(m.memPct), m.swapTotal > 0 ? float(m.swapPct) : NAN,
232
+ m.mounts.isEmpty() ? NAN : float(m.maxDiskPct), float(m.maxDiskUtil), float(m.netRxBps), float(m.netTxBps),
233
+ float(m.diskReadBps), float(m.diskWriteBps), m.temps.isEmpty() ? NAN : float(m.maxTemp), float(m.procs.size()),
234
+ m.gpus.isEmpty() ? NAN : float(m.gpuMax(false)), float(m.servicesFailed)};
235
+ m_store.add(QDateTime::currentSecsSinceEpoch(), v, up);
236
+ }
237
+
238
+ // per-process CPU streaks + RSS per minute; service failure transitions
239
+ void ServerSession::track(qint64 now)
240
+ {
241
+ QHash<int, ProcTrack> procs;
242
+ for (const ProcInfo &p : qAsConst(m_m.procs)) {
243
+ ProcTrack t = m_procs.value(p.pid);
244
+ if (t.name != p.name) t = ProcTrack{p.name}; // new or pid reused
245
+ t.kernel = P::isProtected(p.pid, p.ppid, p.rss, p.name);
246
+ t.highSince = p.cpu < m_cfg.autopilot.runawayCpu ? 0 : t.highSince ? t.highSince : now;
247
+ if (now - t.lastMinute >= 60000) t.lastMinute = now, t.rss << p.rss;
248
+ if (t.rss.size() > 60) t.rss.removeFirst();
249
+ procs[p.pid] = t;
250
+ }
251
+ m_procs = procs;
252
+ QHash<QString, SvcTrack> svcs;
253
+ for (const ServiceInfo &s : qAsConst(m_m.services)) {
254
+ SvcTrack &t = svcs[s.unit] = m_svcs.value(s.unit);
255
+ const bool failed = s.active == "failed";
256
+ if (t.last.isEmpty()) t.preexisting = failed; // failed before monitoring started: leave it alone
257
+ else if (failed && t.last != "failed") t.fails << now, t.preexisting = false;
258
+ else if (!failed) t.preexisting = false;
259
+ t.last = s.active;
260
+ for (auto *v : {&t.fails, &t.restarts})
261
+ while (!v->isEmpty() && now - v->first() > 3600000) v->removeFirst();
262
+ }
263
+ if (!svcs.isEmpty()) m_svcs = svcs; // forgets removed services; a sample without a service list changes nothing
264
+ }
265
+
266
+ void ServerSession::evaluateRules()
267
+ {
268
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
269
+ for (const Rule &r : qAsConst(m_cfg.rules)) {
270
+ RuleState &st = m_rules[r.id];
271
+ if (!r.enabled || ((r.metric == "gpu" || r.metric == "gputemp") && m_m.gpus.isEmpty()) || (r.metric == "temp" && m_m.temps.isEmpty())) {
272
+ st = {};
273
+ continue;
274
+ }
275
+ const double v = metricValue(r.metric);
276
+ const QString now1 = QString::number(v, 'f', 1);
277
+ if (r.op == "<" ? v >= r.value : v <= r.value) {
278
+ if (st.active) raise("resolved", QString("Recovered: %1 (now %2)").arg(r.conditionText(), now1));
279
+ st = {};
280
+ continue;
281
+ }
282
+ if (!st.since) st.since = now;
283
+ if (now - st.since < r.duration * 1000LL) continue;
284
+ if (st.active && (r.action == "notify" || now - st.lastFire < r.cooldown * 1000LL)) continue;
285
+ const QString unit = defLabel(ruleMetrics(), r.metric, true);
286
+ if (!st.active) raise(r.severity, QString("%1 (now %2%3)").arg(r.conditionText(), now1, unit.isEmpty() ? "" : " " + unit));
287
+ st.active = true, st.lastFire = now;
288
+ if (r.action == "notify") continue;
289
+ QString action = r.action, arg = r.arg;
290
+ if (action.startsWith("kill_top")) { // heaviest user process, never a protected one
291
+ const ProcInfo *best = nullptr;
292
+ for (const ProcInfo &p : m_m.procs)
293
+ if (!P::isProtected(p.pid, p.ppid, p.rss, p.name) && (!best || (action == "kill_top_mem" ? p.rss > best->rss : p.cpu > best->cpu))) best = &p;
294
+ if (!best) continue;
295
+ action = "kill_pid", arg = QString::number(best->pid);
296
+ }
297
+ run(action, arg, QString("Automation \"%1\": %2").arg(r.conditionText(), r.actionText()));
298
+ }
299
+ }
300
+
301
+ void ServerSession::run(const QString &action, const QString &arg, const QString &what, Done done)
302
+ {
303
+ const QString cmd = action == "command" ? arg : action == "disk_cleanup" ? m_cfg.autopilot.diskCleanupCommand : P::command(action, arg);
304
+ if (cmd.isEmpty()) return done ? done(-1, "nothing to do") : void();
305
+ exec(cmd, true, [=](int code, const QString &out) {
306
+ const QString tail = out.simplified().right(300); // one line: events are lines in alerts.log
307
+ raise("action", what + " -> " + (code ? QString("failed (%1)").arg(code) : "OK") + (tail.isEmpty() ? "" : " | " + tail));
308
+ if (done) done(code, out);
309
+ }, 300000);
310
+ }
311
+
312
+ void ServerSession::runFinding(const Finding &f, bool automatic, Done done)
313
+ {
314
+ if (automatic && f.action == "restart_service") m_svcs[f.actionArg].restarts << QDateTime::currentMSecsSinceEpoch();
315
+ run(f.action, f.action == "disk_cleanup" ? QString() : f.actionArg, (automatic ? "Autopilot: " : "Manual fix: ") + f.actionLabel + " (" + f.title + ")", done);
316
+ }
317
+
318
+ void ServerSession::analyzeNow()
319
+ {
320
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
321
+ QVector<ProcTrend> procs;
322
+ for (const ProcInfo &p : qAsConst(m_m.procs)) {
323
+ const ProcTrack t = m_procs.value(p.pid);
324
+ ProcTrend pt{p.pid, int(t.rss.size()), p.name, p.user, p.cpu, t.highSince ? (now - t.highSince) / 60000.0 : 0, p.rss};
325
+ pt.kernel = t.kernel;
326
+ if (t.rss.size() >= 2) {
327
+ int grew = 0;
328
+ for (int i = 1; i < t.rss.size(); ++i) grew += t.rss[i] > t.rss[i - 1];
329
+ pt.rssGrowth = t.rss.last() - t.rss[0], pt.rssGrowthPct = t.rss[0] > 0 ? pt.rssGrowth * 100 / t.rss[0] : 0;
330
+ pt.rssMonotonic = double(grew) / (t.rss.size() - 1);
331
+ }
332
+ if (pt.highCpuMinutes > 0 || pt.minutesTracked >= 30) procs << pt;
333
+ }
334
+ QVector<ServiceTrend> svcs;
335
+ for (auto it = m_svcs.cbegin(); it != m_svcs.cend(); ++it)
336
+ if (it->last == "failed" || !it->fails.isEmpty()) svcs << ServiceTrend{it.key(), it->last == "failed", it->preexisting, int(it->fails.size()), int(it->restarts.size())};
337
+ m_an = analyze(m_store, m_m, m_cfg.autopilot, procs, svcs, online());
338
+
339
+ QSet<QString> keys; // announce each new finding once
340
+ for (const Finding &f : qAsConst(m_an.findings))
341
+ if (keys << f.key, !m_reported.contains(f.key) && f.category != "Availability") raise(f.severity, "Insight: " + f.title + " - " + f.detail);
342
+ m_reported = keys;
343
+
344
+ const AutopilotConfig &ap = m_cfg.autopilot; // act on eligible findings, with cooldowns; a dry run says once what it would do
345
+ QSet<QString> dry;
346
+ if (ap.enabled && online())
347
+ for (const Finding &f : qAsConst(m_an.findings)) {
348
+ const qint64 cd = f.action == "disk_cleanup" ? 6 * 3600000LL : f.action == "restart_service" ? 120000 : 900000;
349
+ if (!f.autoEligible) continue;
350
+ if (ap.dryRun) {
351
+ if (dry << f.key, !m_dry.contains(f.key)) raise("action", "Autopilot (dry run) would: " + f.actionLabel + " - " + f.title);
352
+ } else if (now - m_cooldown.value(f.key) >= cd) m_cooldown[f.key] = now, runFinding(f, true);
353
+ }
354
+ m_dry = dry;
355
+ emit analysisUpdated();
356
+ }
357
+
358
+ void ServerSession::deleteHistory()
359
+ {
360
+ m_store.removeFiles(), m_an = Analysis();
361
+ emit analysisUpdated();
362
+ }
363
+
364
+ // ---- manager ----------------------------------------------------------------------------
365
+ QString ServerManager::configDir()
366
+ {
367
+ static const QString d = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
368
+ QDir().mkpath(d);
369
+ return d;
370
+ }
371
+
372
+ ServerSession *ServerManager::session(const QString &id) const
373
+ {
374
+ for (ServerSession *s : m_s)
375
+ if (s->config().id == id) return s;
376
+ return nullptr;
377
+ }
378
+
379
+ ServerSession *ServerManager::attach(const ServerConfig &c)
380
+ {
381
+ auto *s = new ServerSession(c, this);
382
+ connect(s, &ServerSession::alertRaised, this, [this](const AlertEvent &e) {
383
+ m_alerts.prepend(e);
384
+ m_alerts.resize(qMin(m_alerts.size(), 2000));
385
+ QFile f(configDir() + "/alerts.log");
386
+ if (f.size() > 5 << 20) f.resize(0);
387
+ if (f.open(QIODevice::Append | QIODevice::Text))
388
+ QTextStream(&f) << e.time.toString(Qt::ISODate) << '\t' << e.severity << '\t' << e.serverName << '\t' << e.message << '\n';
389
+ emit alertRaised(e);
390
+ });
391
+ m_s << s;
392
+ return s;
393
+ }
394
+
395
+ void ServerManager::load()
396
+ {
397
+ QFile f(configDir() + "/servers.json");
398
+ if (f.open(QIODevice::ReadOnly))
399
+ for (const auto &v : QJsonDocument::fromJson(f.readAll())["servers"].toArray()) attach(ServerConfig::fromJson(v.toObject()));
400
+ else { // first start: monitor this machine
401
+ ServerConfig c;
402
+ c.id = ServerConfig::newId(), c.name = "This computer", c.group = "Local", c.transport = Transport::Local;
403
+ attach(c);
404
+ save();
405
+ }
406
+ for (ServerSession *s : qAsConst(m_s)) s->start();
407
+ emit listChanged();
408
+ }
409
+
410
+ void ServerManager::save() const
411
+ {
412
+ QJsonArray a;
413
+ for (const ServerSession *s : m_s) a << s->config().toJson();
414
+ QSaveFile f(configDir() + "/servers.json");
415
+ if (f.open(QIODevice::WriteOnly)) f.write(QJsonDocument(QJsonObject{{"version", 1}, {"servers", a}}).toJson()), f.commit();
416
+ QFile::setPermissions(f.fileName(), QFileDevice::ReadOwner | QFileDevice::WriteOwner);
417
+ }
418
+
419
+ ServerSession *ServerManager::add(const ServerConfig &c)
420
+ {
421
+ ServerSession *s = attach(c);
422
+ save(), s->start();
423
+ emit listChanged();
424
+ return s;
425
+ }
426
+
427
+ void ServerManager::update(const ServerConfig &c)
428
+ {
429
+ if (ServerSession *s = session(c.id)) s->setConfig(c), save(), emit listChanged();
430
+ }
431
+
432
+ void ServerManager::remove(const QString &id, bool deleteHistory)
433
+ {
434
+ ServerSession *s = session(id);
435
+ if (!s) return;
436
+ m_s.removeOne(s);
437
+ s->disconnect(this), s->stop();
438
+ if (deleteHistory) s->deleteHistory(), QDir(configDir() + "/history").rmdir(id); // the store keeps an empty folder
439
+ s->deleteLater();
440
+ save();
441
+ emit listChanged();
442
+ }
443
+
444
+ void ServerManager::move(const QString &id, int d)
445
+ {
446
+ const int i = m_s.indexOf(session(id)), j = qBound(0, i + d, m_s.size() - 1);
447
+ if (i >= 0 && i != j) m_s.move(i, j), save(), emit listChanged();
448
+ }
Server Monitor(cqt-linux)/src/core/Session.h ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Connection to one machine (local sh or system ssh), the per-server session
2
+ // (metrics, live history, rules, autopilot) and the manager of all sessions.
3
+ #pragma once
4
+ #include "History.h"
5
+ #include <QDateTime>
6
+ #include <QElapsedTimer>
7
+ #include <QPointer>
8
+ #include <QProcess>
9
+ #include <QSet>
10
+ #include <QTimer>
11
+ #include <functional>
12
+
13
+ using Done = std::function<void(int code, QString output)>;
14
+
15
+ // Streams collector frames and runs one-shot commands. Deleting it kills everything.
16
+ class Link : public QObject {
17
+ Q_OBJECT
18
+ public:
19
+ Link(const ServerConfig &c, QObject *parent);
20
+ ~Link() override;
21
+ void start();
22
+ int exec(const QByteArray &input, int timeoutMs);
23
+ signals:
24
+ void snapshot(const QByteArray &frame);
25
+ void disconnected(const QString &reason);
26
+ void execFinished(int id, int code, const QString &out);
27
+
28
+ private:
29
+ QProcess *spawn(const QStringList &shell); // not started yet
30
+ ServerConfig m_c;
31
+ QByteArray m_buf, m_err;
32
+ int m_next = 1;
33
+ };
34
+
35
+ enum class Status { Disabled, Connecting, Online, Offline };
36
+ QString statusName(Status s);
37
+ struct AlertEvent { QDateTime time; QString serverName, severity, message; }; // severity: info|warning|critical|resolved|action
38
+
39
+ struct Live { // last hour in memory for the live charts
40
+ enum { CPU, USER, SYS, IOWAIT, STEAL, MEM, CACHE, SWAP, RX, TX, RD, WR, LOAD, N };
41
+ QVector<qint64> t;
42
+ QVector<double> s[N];
43
+ QHash<QString, QVector<double>> ifRx, ifTx;
44
+ void push(const Metrics &m);
45
+ };
46
+
47
+ class ServerSession : public QObject {
48
+ Q_OBJECT
49
+ public:
50
+ ServerSession(const ServerConfig &c, QObject *parent);
51
+ ~ServerSession() override;
52
+ const ServerConfig &config() const { return m_cfg; }
53
+ void setConfig(const ServerConfig &c);
54
+ Status status() const { return m_status; }
55
+ QString lastError() const { return m_err; }
56
+ const Metrics &metrics() const { return m_m; }
57
+ const Live &live() const { return m_live; }
58
+ bool online() const { return m_status == Status::Online && m_m.valid; }
59
+ bool isPaused() const { return m_paused; }
60
+ void setPaused(bool p) { m_paused = p, emit updated(); }
61
+ void start();
62
+ void stop();
63
+ void reconnect() { m_retries = 0, m_paused = false, start(); }
64
+ // privileged + "useSudo" wraps the command in sudo -n
65
+ void exec(const QString &cmd, bool privileged, Done done = {}, int timeoutMs = 60000);
66
+ double metricValue(const QString &key) const;
67
+ QStringList activeAlerts() const;
68
+ const HistoryStore &store() const { return m_store; }
69
+ const Analysis &analysis() const { return m_an; }
70
+ void analyzeNow();
71
+ void runFinding(const Finding &f, bool automatic, Done done = {});
72
+ void deleteHistory();
73
+ signals:
74
+ void updated();
75
+ void analysisUpdated();
76
+ void alertRaised(const AlertEvent &e);
77
+
78
+ private:
79
+ void setStatus(Status s, const QString &err = {});
80
+ void drop(const QString &why); // closes the link and fails the commands that wait for it
81
+ void onFrame(const QByteArray &raw);
82
+ void onLost(const QString &why);
83
+ void record(bool up);
84
+ void track(qint64 now);
85
+ void evaluateRules();
86
+ void run(const QString &action, const QString &arg, const QString &what, Done done = {});
87
+ void raise(const QString &sev, const QString &msg);
88
+
89
+ ServerConfig m_cfg;
90
+ Status m_status = Status::Disabled;
91
+ QString m_err;
92
+ QPointer<Link> m_link;
93
+ MetricsEngine m_engine;
94
+ Metrics m_m;
95
+ Live m_live;
96
+ QTimer m_retry, m_watchdog, m_analysisTimer, m_offlineTick;
97
+ int m_retries = 0;
98
+ bool m_paused = false, m_offlineAlerted = false;
99
+ QHash<int, Done> m_pending;
100
+ HistoryStore m_store;
101
+ Analysis m_an;
102
+ QSet<QString> m_reported, m_dry;
103
+ QHash<QString, qint64> m_cooldown;
104
+ struct RuleState { qint64 since = 0, lastFire = 0; bool active = false; };
105
+ QHash<QString, RuleState> m_rules;
106
+ struct ProcTrack { QString name; qint64 highSince = 0, lastMinute = 0; QVector<double> rss; bool kernel = false; };
107
+ QHash<int, ProcTrack> m_procs;
108
+ struct SvcTrack { QString last; bool preexisting = false; QVector<qint64> fails, restarts; };
109
+ QHash<QString, SvcTrack> m_svcs;
110
+ };
111
+
112
+ class ServerManager : public QObject {
113
+ Q_OBJECT
114
+ public:
115
+ using QObject::QObject;
116
+ ~ServerManager() override { qDeleteAll(m_s); }
117
+ static QString configDir();
118
+ void load();
119
+ void save() const;
120
+ const QVector<ServerSession *> &sessions() const { return m_s; }
121
+ ServerSession *session(const QString &id) const;
122
+ ServerSession *add(const ServerConfig &c);
123
+ void update(const ServerConfig &c);
124
+ void remove(const QString &id, bool deleteHistory);
125
+ void move(const QString &id, int delta);
126
+ const QVector<AlertEvent> &alerts() const { return m_alerts; }
127
+ void clearAlerts() { m_alerts.clear(), emit alertsCleared(); }
128
+ signals:
129
+ void listChanged();
130
+ void alertRaised(const AlertEvent &e);
131
+ void alertsCleared();
132
+
133
+ private:
134
+ ServerSession *attach(const ServerConfig &c);
135
+ QVector<ServerSession *> m_s;
136
+ QVector<AlertEvent> m_alerts;
137
+ };
Server Monitor(cqt-linux)/src/main.cpp ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Server Monitor - entry point.
2
+ #include "ui/Widgets.h"
3
+ #include "ui/Windows.h"
4
+ #include <QApplication>
5
+ #include <QStyleFactory>
6
+ #include <cstdio>
7
+
8
+ int main(int argc, char *argv[])
9
+ {
10
+ // ssh runs this executable as SSH_ASKPASS when a password is configured
11
+ if (const QByteArray pw = qEnvironmentVariable("SERVERMONITOR_ASKPASS").toUtf8(); !pw.isEmpty()) return std::puts(pw.constData()) < 0;
12
+ QApplication::setAttribute(Qt::AA_EnableHighDpiScaling), QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
13
+ QApplication app(argc, argv);
14
+ QApplication::setApplicationName("ServerMonitor"), QApplication::setOrganizationName("ServerMonitor"), QApplication::setQuitOnLastWindowClosed(false);
15
+ app.setStyle(QStyleFactory::create("Fusion"));
16
+ QPalette pal;
17
+ for (auto [role, color] : {std::pair{QPalette::Window, C::bg}, {QPalette::WindowText, C::text}, {QPalette::Base, QColor(0x111727)}, {QPalette::AlternateBase, C::panel},
18
+ {QPalette::Text, C::text}, {QPalette::Button, C::card}, {QPalette::ButtonText, C::text}, {QPalette::Highlight, QColor(0x17304a)},
19
+ {QPalette::HighlightedText, C::text}, {QPalette::ToolTipBase, C::card}, {QPalette::ToolTipText, C::text}, {QPalette::PlaceholderText, C::faint}})
20
+ pal.setColor(role, color);
21
+ pal.setColor(QPalette::Disabled, QPalette::Text, C::faint), pal.setColor(QPalette::Disabled, QPalette::ButtonText, C::faint);
22
+ app.setPalette(pal), app.setWindowIcon(C::appIcon()), app.setStyleSheet(C::styleSheet());
23
+
24
+ ServerManager mgr;
25
+ MainWindow w(&mgr);
26
+ mgr.load();
27
+ w.show();
28
+ if (const QString dir = qEnvironmentVariable("SERVERMONITOR_SNAPSHOT"); !dir.isEmpty()) // developer aid
29
+ QTimer::singleShot(qMax(1, qEnvironmentVariableIntValue("SERVERMONITOR_SNAPSHOT_DELAY")) * 1000, &w, [&w, dir] { w.saveSnapshots(dir), qApp->quit(); });
30
+ return app.exec();
31
+ }
Server Monitor(cqt-linux)/src/ui/Tabs.cpp ADDED
@@ -0,0 +1,884 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Detail-page tabs: each one shows an aspect of the bound server session.
2
+ #include "Widgets.h"
3
+ #include "Windows.h"
4
+ #include <QBoxLayout>
5
+ #include <QButtonGroup>
6
+ #include <QCheckBox>
7
+ #include <QComboBox>
8
+ #include <QDialogButtonBox>
9
+ #include <QDoubleSpinBox>
10
+ #include <QFileDialog>
11
+ #include <QFormLayout>
12
+ #include <QInputDialog>
13
+ #include <QKeyEvent>
14
+ #include <QLineEdit>
15
+ #include <QMenu>
16
+ #include <QPlainTextEdit>
17
+ #include <QScrollArea>
18
+ #include <QScrollBar>
19
+ #include <QSpinBox>
20
+ #include <QTextStream>
21
+ #include <memory>
22
+ #include <type_traits>
23
+
24
+ // ---- helpers ----------------------------------------------------------------------------
25
+ static QVBoxLayout *scrollRoot(QWidget *tab)
26
+ {
27
+ auto *outer = new QVBoxLayout(tab);
28
+ auto *sa = new QScrollArea;
29
+ auto *l = new QVBoxLayout(new QWidget);
30
+ outer->setContentsMargins(0, 0, 0, 0), outer->addWidget(sa);
31
+ sa->setWidgetResizable(true), sa->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff), sa->setWidget(l->parentWidget());
32
+ l->setContentsMargins(4, 16, 10, 16), l->setSpacing(16);
33
+ return l;
34
+ }
35
+ static QVBoxLayout *plainRoot(QWidget *tab)
36
+ {
37
+ auto *l = new QVBoxLayout(tab);
38
+ l->setContentsMargins(4, 16, 4, 12), l->setSpacing(10);
39
+ return l;
40
+ }
41
+ template <class L> static L *sub(QBoxLayout *parent, int stretch = 0) // nested layout with the standard spacing
42
+ {
43
+ auto *l = new L;
44
+ l->setSpacing(14), parent->addLayout(l, stretch);
45
+ return l;
46
+ }
47
+ static QGridLayout *grid(QBoxLayout *parent, int stretch = 0) { return sub<QGridLayout>(parent, stretch); }
48
+ static QHBoxLayout *row(QBoxLayout *parent, int stretch = 0) { return sub<QHBoxLayout>(parent, stretch); }
49
+ static QVBoxLayout *lay(QFrame *f) { return static_cast<QVBoxLayout *>(f->layout()); }
50
+ static QString kv(const QVector<QPair<QString, QString>> &rows)
51
+ {
52
+ QString h = "<table>";
53
+ for (const auto &r : rows) h += QString("<tr><td style='color:#8b95ab;padding:3px 18px 3px 0'>%1</td><td>%2</td></tr>").arg(r.first, r.second.toHtmlEscaped());
54
+ return h + "</table>";
55
+ }
56
+ static QVector<Series> cpuSeries(const Live &h, bool steal)
57
+ {
58
+ QVector<Series> s = {{"User", C::accent, h.s[Live::USER]}, {"System", C::violet, h.s[Live::SYS]}};
59
+ if (P::posixCpu) s << Series{"I/O wait", C::amber, h.s[Live::IOWAIT]};
60
+ if (P::posixCpu && steal) s << Series{"Steal", C::red, h.s[Live::STEAL]};
61
+ return s;
62
+ }
63
+ // run a command and show the result in a status label
64
+ static void runReport(ServerSession *s, QLabel *status, const QString &cmd)
65
+ {
66
+ status->setText("Running: " + cmd);
67
+ s->exec(cmd, true, [st = QPointer<QLabel>(status), cmd](int code, const QString &out) {
68
+ if (!st) return;
69
+ st->setText(code ? "✗ " + cmd + ": " + out.trimmed().left(300) : "✓ " + cmd);
70
+ st->setStyleSheet(QString("color: %1;").arg((code ? C::red : C::green).name()));
71
+ });
72
+ }
73
+
74
+ // ============================================================================ Overview
75
+ struct OverviewTab : Tab {
76
+ QVector<RingGauge *> g;
77
+ QVector<StatTile *> t;
78
+ TimeChart *cpu = new TimeChart("CPU", pctFmt, 100), *mem = new TimeChart("Memory", pctFmt, 100), *net = new TimeChart("Network", rateFmt),
79
+ *io = new TimeChart("Disk I/O", rateFmt);
80
+ QLabel *info = label({}, nullptr, true);
81
+
82
+ OverviewTab()
83
+ {
84
+ auto *l = scrollRoot(this);
85
+ auto *gp = panel(), *ip = panel("System", {info, nullptr});
86
+ auto *gl = new QHBoxLayout;
87
+ for (const char *n : {"CPU", "Memory", "Fullest disk", "Swap", "Temperature", "Health"}) g << new RingGauge(n), gl->addWidget(g.last());
88
+ g[4]->crit = 85;
89
+ lay(gp)->addLayout(gl), gp->setMinimumHeight(220), l->addWidget(gp);
90
+ t = addTiles(grid(l), {{"Load average", C::accent}, {"Processes", C::violet}, {"TCP connections", C::teal}, {"Services", C::green}, {"Uptime", C::amber}});
91
+ auto *mid = row(l);
92
+ auto *charts = grid(mid, 1);
93
+ cpu->stacked = true;
94
+ for (auto *c : {cpu, mem, net, io}) c->setMinimumHeight(220), charts->addWidget(c, charts->count() / 2, charts->count() % 2);
95
+ ip->setFixedWidth(330), mid->addWidget(ip), l->addStretch();
96
+ }
97
+ void refresh() override
98
+ {
99
+ const Metrics &m = s->metrics();
100
+ const Live &h = s->live();
101
+ const Analysis &a = s->analysis();
102
+ const ServerConfig &c = s->config();
103
+ g[0]->setValue(m.cpuUsage, {}, QString("%1 cores").arg(m.cpuCount));
104
+ g[1]->setValue(m.memPct, {}, Fmt::bytes(m.memUsed) + " / " + Fmt::bytes(m.memTotal));
105
+ g[2]->setValue(m.maxDiskPct, {}, m.fullestMount);
106
+ g[3]->setValue(m.swapPct, {}, m.swapTotal > 0 ? Fmt::bytes(m.swapUsed) + " / " + Fmt::bytes(m.swapTotal) : "no swap");
107
+ g[4]->setValue(qMin(100.0, m.maxTemp), m.temps.isEmpty() ? "—" : Fmt::temp(m.maxTemp), m.temps.isEmpty() ? "no sensors" : QString("%1 sensors").arg(m.temps.size()));
108
+ g[5]->setValue(a.health, QString::number(a.health), "grade " + a.grade, C::health(a.health));
109
+ t[0]->set(QString::number(m.load1, 'f', 2), QString("5m %1 · 15m %2").arg(m.load5, 0, 'f', 2).arg(m.load15, 0, 'f', 2), C::level(m.load1 * 100 / qMax(1, m.cpuCount), 80, 150));
110
+ t[1]->set(QString::number(m.procs.size()), QString("%1 threads · %2 running").arg(m.threadsTotal).arg(m.procsRunning));
111
+ t[2]->set(QString::number(m.tcp["ESTABLISHED"]), QString("%1 listening · %2 time-wait").arg(m.tcp["LISTEN"]).arg(m.tcp["TIME_WAIT"]));
112
+ t[3]->set(QString::number(m.servicesRunning), m.servicesFailed ? QString("%1 failed").arg(m.servicesFailed) : "running · none failed", m.servicesFailed ? C::red : C::text);
113
+ t[4]->set(Fmt::duration(m.uptime), QString("%1 user(s) logged in").arg(m.loggedUsers));
114
+ cpu->setData(h.t, cpuSeries(h, false), span);
115
+ mem->setData(h.t, {{"Used", C::violet, h.s[Live::MEM]}, {"Cache", C::blue, h.s[Live::CACHE], false, true}, {"Swap", C::pink, h.s[Live::SWAP], false}}, span);
116
+ net->setData(h.t, {{"Down", C::teal, h.s[Live::RX]}, {"Up", C::pink, h.s[Live::TX]}}, span);
117
+ io->setData(h.t, {{"Read", C::blue, h.s[Live::RD]}, {"Write", C::orange, h.s[Live::WR]}}, span);
118
+ info->setText(kv({{"Hostname", m.hostname}, {"OS", m.os}, {"Kernel", m.kernel + " " + m.arch}, {"CPU", m.cpuModel},
119
+ {"Cores", QString::number(m.cpuCount) + (m.avgMhz > 0 ? QString(" @ %1 GHz").arg(m.avgMhz / 1000, 0, 'f', 2) : "")},
120
+ {"Memory", Fmt::bytes(m.memTotal)}, {"Swap", m.swapTotal > 0 ? Fmt::bytes(m.swapTotal) : "none"}, {"Virtualisation", m.virt},
121
+ {"Disks", QString("%1 mounted file systems").arg(m.mounts.size())}, {"Interfaces", QString::number(m.nets.size())},
122
+ {"GPU", m.gpus.isEmpty() ? "none" : m.gpus[0].name}, {"Connection", c.address() + " (" + transportName(c.transport) + ")"},
123
+ {"Sample interval", QString("%1 s").arg(c.interval)}}));
124
+ }
125
+ };
126
+
127
+ // ============================================================================ CPU
128
+ struct CpuTab : Tab {
129
+ QLabel *model = label({}, "H2");
130
+ QVector<StatTile *> t;
131
+ TimeChart *chart = new TimeChart("CPU time breakdown", pctFmt, 100), *load = new TimeChart("Load average (1 min)", numFmt(1));
132
+ CoreGrid *cores = new CoreGrid;
133
+ QTableWidget *temps = table({"Sensor", "Temperature"}, {300}, {1}), *gpus = table({"#", "Name", "Usage", "Memory", "Temp", "Power", "Fan"}, {40, 220, 120, 160}, {2, 3});
134
+ QFrame *gpuPanel = panel("GPUs", {gpus});
135
+
136
+ CpuTab()
137
+ {
138
+ auto *l = scrollRoot(this);
139
+ l->addWidget(model);
140
+ t = addTiles(grid(l), {{"Usage", C::accent}, {"Load 1 / 5 / 15", C::violet}, {"Avg frequency", C::teal}, {P::posixCpu ? "Steal / IRQ" : "Interrupts + DPC", C::orange},
141
+ {"Context switches", C::blue}, {"Interrupts", C::pink}, {"New processes", C::green}, {"Running / blocked", C::amber}}, 4);
142
+ auto *r = row(l);
143
+ chart->stacked = true, chart->setMinimumHeight(260), temps->setMinimumHeight(220);
144
+ r->addWidget(chart, 3), r->addWidget(load, 2), l->addWidget(panel("Per core", {cores}));
145
+ auto *b = row(l);
146
+ b->addWidget(panel("Temperatures", {temps}), 1), b->addWidget(gpuPanel, 1), l->addStretch();
147
+ }
148
+ void refresh() override
149
+ {
150
+ const Metrics &m = s->metrics();
151
+ const Live &h = s->live();
152
+ model->setText(m.cpuModel.isEmpty() ? "Processor" : m.cpuModel);
153
+ t[0]->set(Fmt::pct(m.cpuUsage), QString("user %1 · system %2").arg(Fmt::pct(m.cpuUser), Fmt::pct(m.cpuSystem)) + (P::posixCpu ? " · iowait " + Fmt::pct(m.cpuIowait) : ""), C::level(m.cpuUsage));
154
+ t[1]->set(QString("%1 / %2 / %3").arg(m.load1, 0, 'f', 2).arg(m.load5, 0, 'f', 2).arg(m.load15, 0, 'f', 2), QString("%1% of %2 cores").arg(qRound(m.load1 * 100 / qMax(1, m.cpuCount))).arg(m.cpuCount));
155
+ t[2]->set(m.avgMhz > 0 ? QString("%1 GHz").arg(m.avgMhz / 1000, 0, 'f', 2) : "n/a");
156
+ if (P::posixCpu) t[3]->set(Fmt::pct(m.cpuSteal) + " / " + Fmt::pct(m.cpuIrq), "steal > 5% = noisy neighbours", m.cpuSteal > 5 ? C::amber : QColor());
157
+ else t[3]->set(Fmt::pct(m.cpuIrq), "hardware interrupts and deferred calls", m.cpuIrq > 15 ? C::amber : QColor());
158
+ t[4]->set(Fmt::count(m.ctxtPerSec) + "/s"), t[5]->set(Fmt::count(m.intrPerSec) + "/s"), t[6]->set(QString::number(m.forksPerSec, 'f', 1) + "/s");
159
+ t[7]->set(QString("%1 / %2").arg(m.procsRunning).arg(m.procsBlocked), P::posixCpu ? "blocked = waiting for I/O" : "blocked = waiting for a CPU", m.procsBlocked > m.cpuCount ? C::amber : QColor());
160
+ chart->setData(h.t, cpuSeries(h, true), span);
161
+ load->setData(h.t, {{"Load", C::violet, h.s[Live::LOAD]}, {"Cores", C::faint, QVector<double>(h.t.size(), m.cpuCount), false, true}}, span);
162
+ cores->setCores(m.cores);
163
+ temps->clearSpans();
164
+ fillRows(temps, m.temps, [](const TempSensor &x) { return Row{{x.name}, {Fmt::temp(x.celsius), {}, false, qMin(100.0, x.celsius)}}; });
165
+ if (m.temps.isEmpty()) temps->setRowCount(1), cell(temps, 0, 0, {"No temperature sensors exposed (common on VMs)", C::muted}), temps->setSpan(0, 0, 1, 2);
166
+ gpuPanel->setVisible(!m.gpus.isEmpty());
167
+ fillRows(gpus, m.gpus, [](const GpuInfo &g) {
168
+ return Row{{QString::number(g.index)}, {g.name}, {Fmt::pct(g.util, 0), {}, false, g.util},
169
+ {QString("%1 / %2 MiB").arg(g.memUsed).arg(g.memTotal), {}, false, g.memTotal > 0 ? g.memUsed * 100 / g.memTotal : 0},
170
+ {Fmt::temp(g.temp), C::level(g.temp, 75, 88)}, {QString("%1 W").arg(g.power)}, {Fmt::pct(g.fan, 0)}};
171
+ });
172
+ }
173
+ };
174
+
175
+ // ============================================================================ Memory
176
+ struct MemoryTab : Tab {
177
+ QVector<StatTile *> t;
178
+ SegmentBar *bar = new SegmentBar, *swap = new SegmentBar;
179
+ TimeChart *chart = new TimeChart("Memory usage", pctFmt, 100);
180
+ QLabel *detail = label({}, nullptr, true);
181
+ QTableWidget *top = table({"PID", "Process", "User", "RSS", "Memory %", "Virtual"}, {80, 220, 120, 110, 160}, {4});
182
+
183
+ MemoryTab()
184
+ {
185
+ auto *l = scrollRoot(this);
186
+ t = addTiles(grid(l), {{"Used", C::violet}, {"Available", C::green}, {"Cache + buffers", C::blue}, {"Swap used", C::pink}});
187
+ l->addWidget(panel("Composition", {bar, label("SWAP", "Section"), swap}));
188
+ auto *r = row(l);
189
+ auto *dp = panel("Details", {detail, nullptr});
190
+ chart->setMinimumHeight(280), dp->setFixedWidth(300), top->setMinimumHeight(360);
191
+ r->addWidget(chart, 3), r->addWidget(dp), l->addWidget(panel("Top memory consumers", {top}));
192
+ }
193
+ void refresh() override
194
+ {
195
+ const Metrics &m = s->metrics();
196
+ const Live &h = s->live();
197
+ const QColor free = C::grid.lighter(150);
198
+ t[0]->set(Fmt::bytes(m.memUsed), Fmt::pct(m.memPct) + " of " + Fmt::bytes(m.memTotal), C::level(m.memPct));
199
+ t[1]->set(Fmt::bytes(m.memAvailable), "free " + Fmt::bytes(m.memFree));
200
+ t[2]->set(Fmt::bytes(m.cached + m.buffers), "reclaimable when needed");
201
+ t[3]->set(m.swapTotal > 0 ? Fmt::bytes(m.swapUsed) : "no swap", m.swapTotal > 0 ? Fmt::pct(m.swapPct) + " of " + Fmt::bytes(m.swapTotal) : "", C::level(m.swapPct, 40, 80));
202
+ bar->setSegments({{qMax(0.0, m.memTotal - m.memFree - m.cached - m.buffers), C::violet, "Applications"}, {m.shared, C::pink, "Shared"},
203
+ {m.buffers, C::teal, "Buffers"}, {qMax(0.0, m.cached - m.shared), C::blue, "Cache"}, {m.memFree, free, "Free"}}, m.memTotal);
204
+ swap->setSegments({{m.swapUsed, C::pink, "Used"}, {m.swapTotal - m.swapUsed, free, "Free"}}, m.swapTotal);
205
+ chart->setData(h.t, {{"Used", C::violet, h.s[Live::MEM]}, {"Cache", C::blue, h.s[Live::CACHE], false, true}, {"Swap", C::pink, h.s[Live::SWAP]}}, span);
206
+ QVector<QPair<QString, QString>> d;
207
+ for (auto [k, v] : {std::pair{"Total", m.memTotal}, {"Used", m.memUsed}, {"Available", m.memAvailable}, {"Free", m.memFree}, {"Buffers", m.buffers},
208
+ {"Cached", m.cached}, {"Shared", m.shared}, {"Slab", m.slab}, {"Dirty", m.dirty}, {"Swap total", m.swapTotal}, {"Swap used", m.swapUsed}})
209
+ d << qMakePair(QString(k), Fmt::bytes(v));
210
+ detail->setText(kv(d));
211
+ QVector<ProcInfo> p = m.procs;
212
+ std::partial_sort(p.begin(), p.begin() + qMin(15, p.size()), p.end(), [](const ProcInfo &a, const ProcInfo &b) { return a.rss > b.rss; });
213
+ fillRows(top, p.mid(0, 15), [](const ProcInfo &x) {
214
+ return Row{{QString::number(x.pid), C::muted}, {x.name}, {x.user, C::muted}, {Fmt::bytes(x.rss), {}, true},
215
+ {Fmt::pct(x.memPct), {}, false, qMin(100.0, x.memPct * 2)}, {Fmt::bytes(x.vsz), C::muted, true}};
216
+ });
217
+ }
218
+ };
219
+
220
+ // ============================================================================ Storage
221
+ struct StorageTab : Tab {
222
+ QVector<StatTile *> t;
223
+ QTableWidget *mounts = table({"Mount point", "Device", "Type", "Size", "Used", "Free", "Usage"}, {260, 140, 80, 110, 110, 110}, {6}),
224
+ *disks = table({"Device", "Read/s", "Write/s", "Read IOPS", "Write IOPS", "Busy", "Total read", "Total written"}, {110, 110, 110, 100, 100, 150, 120}, {5});
225
+ TimeChart *io = new TimeChart("Disk throughput", rateFmt);
226
+
227
+ StorageTab()
228
+ {
229
+ auto *l = scrollRoot(this);
230
+ t = addTiles(grid(l), {{"Fullest file system", C::amber}, {"Read", C::blue}, {"Write", C::orange}, {"Busiest disk", C::red}});
231
+ mounts->setMinimumHeight(220), disks->setMinimumHeight(200), io->setMinimumHeight(260);
232
+ l->addWidget(panel("File systems", {mounts})), l->addWidget(io), l->addWidget(panel("Block devices", {disks}));
233
+ }
234
+ void refresh() override
235
+ {
236
+ const Metrics &m = s->metrics();
237
+ t[0]->set(Fmt::pct(m.maxDiskPct), m.fullestMount, C::level(m.maxDiskPct, 80, 90));
238
+ t[1]->set(Fmt::rate(m.diskReadBps)), t[2]->set(Fmt::rate(m.diskWriteBps)), t[3]->set(Fmt::pct(m.maxDiskUtil), m.busiestDisk, C::level(m.maxDiskUtil, 60, 90));
239
+ io->setData(s->live().t, {{"Read", C::blue, s->live().s[Live::RD]}, {"Write", C::orange, s->live().s[Live::WR]}}, span);
240
+ fillRows(mounts, m.mounts, [](const MountInfo &x) {
241
+ return Row{{x.mount}, {x.device, C::muted}, {x.type, C::muted}, {Fmt::bytes(x.total), {}, true}, {Fmt::bytes(x.used), {}, true},
242
+ {Fmt::bytes(x.avail), {}, true}, {Fmt::pct(x.pct), {}, false, x.pct}};
243
+ });
244
+ fillRows(disks, m.disks, [](const DiskIO &d) {
245
+ return Row{{d.name}, {Fmt::rate(d.readBps), C::blue, true}, {Fmt::rate(d.writeBps), C::orange, true}, {QString::number(d.readIops, 'f', 0), {}, true},
246
+ {QString::number(d.writeIops, 'f', 0), {}, true}, {Fmt::pct(d.util, 0), {}, false, d.util}, {Fmt::bytes(d.totalRead), C::muted, true},
247
+ {Fmt::bytes(d.totalWritten), C::muted, true}};
248
+ });
249
+ }
250
+ };
251
+
252
+ // ============================================================================ Network
253
+ struct NetworkTab : Tab {
254
+ QVector<StatTile *> t;
255
+ QComboBox *iface = new QComboBox;
256
+ QStringList shown;
257
+ TimeChart *chart = new TimeChart("Traffic", rateFmt);
258
+ QTableWidget *tbl = table({"Interface", "State", "Speed", "Down/s", "Up/s", "Pkts in/s", "Pkts out/s", "Received", "Sent", "Errors", "Drops"}, {160, 80, 90, 110, 110, 90, 90, 110, 110, 70});
259
+
260
+ NetworkTab()
261
+ {
262
+ auto *l = scrollRoot(this);
263
+ t = addTiles(grid(l), {{"Download", C::teal}, {"Upload", C::pink}, {"Established", C::accent}, {"Listening", C::green}, {"Time-wait / close-wait", C::amber}, {"Sockets in use", C::violet}});
264
+ auto *r = row(l);
265
+ r->addWidget(label("Interface", "Muted")), r->addWidget(iface), r->addStretch();
266
+ iface->setMinimumWidth(200), chart->setMinimumHeight(280), tbl->setMinimumHeight(240);
267
+ l->addWidget(chart), l->addWidget(panel("Interfaces", {tbl}));
268
+ connect(iface, QOverload<int>::of(&QComboBox::activated), this, [this] { refresh(); });
269
+ }
270
+ void refresh() override
271
+ {
272
+ const Metrics &m = s->metrics();
273
+ const Live &h = s->live();
274
+ t[0]->set(Fmt::rate(m.netRxBps), "physical interfaces"), t[1]->set(Fmt::rate(m.netTxBps));
275
+ t[2]->set(QString::number(m.tcp["ESTABLISHED"]), "TCP"), t[3]->set(QString::number(m.tcp["LISTEN"]), "open TCP ports");
276
+ t[4]->set(QString("%1 / %2").arg(m.tcp["TIME_WAIT"]).arg(m.tcp["CLOSE_WAIT"]), "many close-wait = app not closing sockets", m.tcp["CLOSE_WAIT"] > 100 ? C::amber : QColor());
277
+ t[5]->set(QString::number(m.socketsUsed));
278
+ QStringList names{"All physical (total)"};
279
+ for (const NetIf &n : m.nets) names << n.name;
280
+ if (names != shown) {
281
+ const QString cur = iface->currentText();
282
+ iface->clear(), iface->addItems(shown = names), iface->setCurrentIndex(qMax(0, names.indexOf(cur)));
283
+ }
284
+ const QString n = iface->currentText();
285
+ const bool all = iface->currentIndex() <= 0;
286
+ chart->title = "Traffic — " + (all ? "all physical interfaces" : n);
287
+ chart->setData(h.t, {{"Down", C::teal, all ? h.s[Live::RX] : h.ifRx.value(n)}, {"Up", C::pink, all ? h.s[Live::TX] : h.ifTx.value(n)}}, span);
288
+ fillRows(tbl, m.nets, [](const NetIf &x) {
289
+ const QColor dim = x.virt ? C::muted : QColor();
290
+ return Row{{x.name + (x.virt ? " (virtual)" : ""), dim}, {x.state, x.state == "up" ? C::green : x.state == "down" ? C::red : C::muted},
291
+ {x.speed > 0 ? QString("%1 Mb/s").arg(x.speed) : "—", C::muted}, {Fmt::rate(x.rxBps), C::teal, true}, {Fmt::rate(x.txBps), C::pink, true},
292
+ {QString::number(x.rxPps, 'f', 0), dim, true}, {QString::number(x.txPps, 'f', 0), dim, true}, {Fmt::bytes(x.rxBytes), dim, true},
293
+ {Fmt::bytes(x.txBytes), dim, true}, {QString::number(x.errors), x.errors ? C::amber : dim, true}, {QString::number(x.drops), x.drops ? C::amber : dim, true}};
294
+ });
295
+ }
296
+ };
297
+
298
+ // ============================================================================ list tabs (processes, services)
299
+ using Act = QPair<QString, std::function<void()>>; // context-menu entry; empty text = separator
300
+
301
+ struct ListTab : Tab { // filterable, sortable table that keeps selection and scroll position across refreshes
302
+ QLineEdit *filter = new QLineEdit;
303
+ QLabel *summary = label({}, "Muted"), *status = label({}, "Muted");
304
+ QTableWidget *tbl;
305
+ QHBoxLayout *bar;
306
+
307
+ ListTab(const QStringList &headers, const QVector<int> &widths, const QVector<int> &bars, const QString &hint)
308
+ {
309
+ auto *l = plainRoot(this);
310
+ bar = row(l), tbl = table(headers, widths, bars);
311
+ tbl->setSortingEnabled(true), tbl->setContextMenuPolicy(Qt::CustomContextMenu);
312
+ filter->setClearButtonEnabled(true), filter->setMaximumWidth(300), filter->setPlaceholderText(hint);
313
+ bar->addWidget(filter), bar->addWidget(summary), bar->addStretch();
314
+ l->addWidget(tbl, 1), l->addWidget(status);
315
+ connect(filter, &QLineEdit::textChanged, this, [this] { applyFilter(); });
316
+ }
317
+ QString selectedKey() const
318
+ {
319
+ const int r = tbl->currentRow();
320
+ return r >= 0 && !tbl->isRowHidden(r) && tbl->item(r, 0) ? tbl->item(r, 0)->text() : QString();
321
+ }
322
+ virtual bool accept(int r) const
323
+ {
324
+ for (int c = 0; c < tbl->columnCount(); ++c)
325
+ if (tbl->item(r, c) && tbl->item(r, c)->text().contains(filter->text(), Qt::CaseInsensitive)) return true;
326
+ return false;
327
+ }
328
+ void applyFilter()
329
+ {
330
+ for (int r = 0; r < tbl->rowCount(); ++r) tbl->setRowHidden(r, !accept(r));
331
+ }
332
+ template <class V, class F> void fill(const V &items, F rowOf)
333
+ {
334
+ const QString sel = selectedKey();
335
+ const int scroll = tbl->verticalScrollBar()->value(), col = qMax(0, tbl->currentColumn());
336
+ int row = -1; // rows are reused: when the selected entry is gone the selection must go too, not pass to another entry
337
+ tbl->setSortingEnabled(false), fillRows(tbl, items, rowOf), tbl->setSortingEnabled(true);
338
+ for (int r = 0; r < tbl->rowCount() && row < 0 && !sel.isEmpty(); ++r)
339
+ if (tbl->item(r, 0)->text() == sel) row = r;
340
+ tbl->setCurrentCell(row, col), applyFilter(), tbl->verticalScrollBar()->setValue(scroll);
341
+ }
342
+ void addMenu(const QVector<Act> &items)
343
+ {
344
+ connect(tbl, &QWidget::customContextMenuRequested, this, [this, items](const QPoint &p) {
345
+ if (selectedKey().isEmpty()) return;
346
+ QMenu m;
347
+ for (const Act &a : items) a.first.isEmpty() ? (void)m.addSeparator() : (void)m.addAction(a.first, a.second);
348
+ m.exec(tbl->viewport()->mapToGlobal(p));
349
+ });
350
+ }
351
+ };
352
+
353
+ struct ProcessTab : ListTab {
354
+ QCheckBox *freeze = new QCheckBox("Freeze list");
355
+
356
+ ProcessTab() : ListTab({"PID", "Name", "User", "State", "CPU", "Memory", "RSS", "Threads", P::prioLabel, "Running for"}, {80, 230, 120, 100, 130, 130, 100, 80, 70}, {4, 5}, "Filter by name, user or PID…")
357
+ {
358
+ freeze->setToolTip("Stop refreshing so rows don't move while you pick one");
359
+ bar->insertWidget(1, freeze), tbl->sortByColumn(4, Qt::DescendingOrder);
360
+ QVector<Act> menu;
361
+ for (const Cmd &c : P::procActions()) {
362
+ menu << Act{c.label, [this, c] { run(c); }};
363
+ if (c.button) bar->addWidget(button(c.label, c.danger ? "Danger" : nullptr, menu.last().second));
364
+ }
365
+ bar->addWidget(button("Priority…", nullptr, [this] { renice(); }));
366
+ addMenu(menu << Act{} << Act{"Change priority…", [this] { renice(); }});
367
+ }
368
+ void bind(ServerSession *x) override
369
+ {
370
+ if (x != s) freeze->setChecked(false); // a frozen list would show the other server's PIDs
371
+ Tab::bind(x);
372
+ }
373
+ void refresh() override
374
+ {
375
+ if (freeze->isChecked()) return;
376
+ const Metrics &m = s->metrics();
377
+ static const QHash<QChar, QPair<QString, QColor>> states = {{'R', {"Running", C::green}}, {'S', {"Sleeping", C::muted}}, {'D', {"Disk wait", C::amber}},
378
+ {'Z', {"Zombie", C::red}}, {'T', {"Stopped", C::red}}, {'I', {"Idle", C::muted}}};
379
+ int running = 0;
380
+ fill(m.procs, [&](const ProcInfo &p) {
381
+ const auto st = states.value(p.state, {QString(p.state), C::muted});
382
+ running += p.state == 'R';
383
+ return Row{{QString::number(p.pid), C::muted, true, -1, p.pid}, {p.name}, {p.user, C::muted}, {st.first, st.second},
384
+ {Fmt::pct(p.cpu), {}, false, qMin(100.0, p.cpu), p.cpu}, {Fmt::pct(p.memPct), {}, false, p.memPct, p.memPct},
385
+ {Fmt::bytes(p.rss), {}, true, -1, p.rss}, {QString::number(p.threads), {}, true, -1, p.threads},
386
+ {QString::number(p.nice), p.nice == P::normalPrio ? C::text : C::teal, true, -1, p.nice}, {Fmt::duration(p.age), C::muted, true, -1, p.age}};
387
+ });
388
+ summary->setText(QString("%1 processes · %2 running · %3 threads").arg(m.procs.size()).arg(running).arg(m.threadsTotal));
389
+ }
390
+ QString pidName() const { return tbl->item(tbl->currentRow(), 1)->text() + " (" + selectedKey() + ")"; }
391
+ void run(const Cmd &c)
392
+ {
393
+ const int pid = selectedKey().toInt(); // read before the question: the list keeps refreshing behind it
394
+ if (!pid) return status->setText("Select a process first.");
395
+ if (!c.confirm || ask(this, c.label, QString("%1 %2 on %3?").arg(c.label, pidName(), s->config().name))) runReport(s, status, c.cmd.arg(pid));
396
+ }
397
+ void renice()
398
+ {
399
+ const int pid = selectedKey().toInt();
400
+ if (!pid) return status->setText("Select a process first.");
401
+ QStringList labels;
402
+ for (const Cmd &c : P::priorities()) labels << c.label;
403
+ bool ok = false;
404
+ const int i = labels.indexOf(QInputDialog::getItem(this, "Change priority", "Priority for " + pidName() + ":", labels, labels.size() / 2, false, &ok));
405
+ if (ok && i >= 0) runReport(s, status, P::priorities()[i].cmd.arg(pid));
406
+ }
407
+ };
408
+
409
+ struct ServiceTab : ListTab {
410
+ QComboBox *state = new QComboBox;
411
+ QString sig = "?"; // not a possible signature: the first refresh always fills
412
+
413
+ ServiceTab() : ListTab({"Service", "Active", "State", "Load", "Description"}, {300, 100, 100, 90}, {}, "Filter services…")
414
+ {
415
+ state->addItems({"All", "Running", "Failed", "Not running"});
416
+ bar->insertWidget(1, state), tbl->sortByColumn(0, Qt::AscendingOrder);
417
+ connect(state, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this] { applyFilter(); });
418
+ connect(tbl, &QTableWidget::cellDoubleClicked, this, [this] { showLogs(); });
419
+ QVector<Act> menu;
420
+ for (const Cmd &c : P::serviceActions()) {
421
+ menu << Act{c.label, [this, c] { act(c); }};
422
+ bar->addWidget(button(c.label, c.danger ? "Danger" : nullptr, menu.last().second));
423
+ }
424
+ bar->addWidget(button("Logs", "Primary", [this] { showLogs(); }));
425
+ addMenu(menu << Act{} << Act{"Show logs", [this] { showLogs(); }});
426
+ }
427
+ bool accept(int r) const override
428
+ {
429
+ const QString active = tbl->item(r, 1)->text(), sub = tbl->item(r, 2)->text();
430
+ const int st = state->currentIndex();
431
+ return (st == 0 || (st == 1 && sub == "running") || (st == 2 && active == "failed") || (st == 3 && sub != "running" && active != "failed")) && ListTab::accept(r);
432
+ }
433
+ void refresh() override
434
+ {
435
+ const Metrics &m = s->metrics();
436
+ QString sg;
437
+ for (const ServiceInfo &x : m.services) sg += x.unit + x.active + x.sub;
438
+ if (sg == sig) return; // unchanged: keep the list still
439
+ sig = sg;
440
+ fill(m.services, [](const ServiceInfo &x) {
441
+ const QColor c = x.active == "failed" ? C::red : x.sub == "running" ? C::green : x.active == "active" ? C::teal : C::muted;
442
+ return Row{{x.unit}, {x.active, c}, {x.sub, c}, {x.load, C::muted}, {x.description, C::muted}};
443
+ });
444
+ summary->setText(m.services.isEmpty() ? "No services reported by this machine" : QString("%1 services · %2 running · %3 failed").arg(m.services.size()).arg(m.servicesRunning).arg(m.servicesFailed));
445
+ }
446
+ void act(const Cmd &c)
447
+ {
448
+ const QString unit = selectedKey();
449
+ if (unit.isEmpty()) return status->setText("Select a service first.");
450
+ if (!c.confirm || ask(this, "Confirm", QString("%1 %2 on %3?").arg(c.label, unit, s->config().name))) runReport(s, status, c.cmd.arg(P::quote(unit)));
451
+ }
452
+ void showLogs()
453
+ {
454
+ const QString unit = selectedKey();
455
+ if (unit.isEmpty()) return;
456
+ auto *dlg = new QDialog(this);
457
+ auto *l = new QVBoxLayout(dlg);
458
+ auto *b = new QHBoxLayout;
459
+ auto *txt = new QPlainTextEdit("Loading…");
460
+ auto *n = new QSpinBox;
461
+ dlg->setAttribute(Qt::WA_DeleteOnClose), dlg->setWindowTitle("Logs — " + unit + " — " + s->config().name), dlg->resize(1000, 640);
462
+ txt->setReadOnly(true), txt->setFont(QFont(C::mono(), 10)), txt->setLineWrapMode(QPlainTextEdit::NoWrap);
463
+ n->setRange(50, 5000), n->setValue(300), n->setSuffix(" lines");
464
+ auto load = [ss = s, t = QPointer<QPlainTextEdit>(txt), n, unit] {
465
+ if (ss) ss->exec(P::serviceLogs(unit, n->value()), true, [t](int, const QString &out) { if (t) t->setPlainText(out), t->verticalScrollBar()->setValue(t->verticalScrollBar()->maximum()); });
466
+ };
467
+ l->addWidget(txt), l->addLayout(b);
468
+ b->addWidget(n), b->addWidget(button("Reload", nullptr, load)), b->addStretch(), b->addWidget(button("Close", nullptr, [dlg] { dlg->close(); }));
469
+ load(), dlg->show();
470
+ }
471
+ };
472
+
473
+ // ============================================================================ Console
474
+ struct ConsoleTab : Tab {
475
+ QPlainTextEdit *out = new QPlainTextEdit;
476
+ QLineEdit *in = new QLineEdit;
477
+ QCheckBox *priv = new QCheckBox("privileged");
478
+ QStringList hist;
479
+ int pos = 0;
480
+
481
+ ConsoleTab()
482
+ {
483
+ auto *l = new QHBoxLayout(this);
484
+ auto *left = new QVBoxLayout, *side = new QVBoxLayout;
485
+ auto *r = new QHBoxLayout;
486
+ auto *prompt = label("$");
487
+ auto *run = button("Run", "Primary", [this] {
488
+ const QString c = in->text().trimmed();
489
+ if (c.isEmpty()) return;
490
+ if (hist.isEmpty() || hist.last() != c) hist << c;
491
+ pos = hist.size(), in->clear(), exec(c, priv->isChecked());
492
+ });
493
+ l->setContentsMargins(4, 16, 4, 12), l->setSpacing(14), l->addLayout(left, 1), l->addLayout(side);
494
+ out->setReadOnly(true), out->setFont(QFont(C::mono(), 10)), out->setMaximumBlockCount(20000);
495
+ out->setStyleSheet("QPlainTextEdit { background: #080b12; border-radius: 10px; padding: 10px; color: #cfe3ff; }");
496
+ in->setFont(QFont(C::mono(), 11)), in->setPlaceholderText("Type a shell command and press Enter (↑/↓ history)"), in->installEventFilter(this);
497
+ priv->setToolTip("Wrap in sudo -n when the server has 'Run control commands with sudo' enabled"), priv->setVisible(P::sudo);
498
+ prompt->setStyleSheet("color: #38bdf8; font-weight: 700; font-size: 15px;");
499
+ r->addWidget(prompt), r->addWidget(in, 1), r->addWidget(priv), r->addWidget(run), r->addWidget(button("Clear", nullptr, [this] { out->clear(); }));
500
+ left->addWidget(out, 1), left->addLayout(r);
501
+ connect(in, &QLineEdit::returnPressed, run, &QPushButton::click);
502
+ auto addGroup = [&](const QString &title, const QVector<Cmd> &items, bool system) {
503
+ auto *p = panel(title);
504
+ p->setFixedWidth(270), side->addWidget(p);
505
+ for (const Cmd &q : items) {
506
+ auto *b = button(q.label, q.danger ? "Danger" : "Side", [this, q, system] {
507
+ if (!system || ask(this, q.label, QString("%1 on %2?%3").arg(q.label, s->config().name, q.danger ? "\n\nThe machine will be unavailable until it comes back." : ""))) exec(q.cmd, system);
508
+ });
509
+ b->setToolTip(q.cmd), lay(p)->addWidget(b);
510
+ }
511
+ };
512
+ addGroup("Quick diagnostics", P::diagnostics(), false), addGroup("System actions", P::systemActions(), true);
513
+ side->addStretch();
514
+ }
515
+ void bind(ServerSession *x) override
516
+ {
517
+ if (x == s) return;
518
+ out->clear(), Tab::bind(x);
519
+ if (x) out->appendHtml(QString("<span style='color:#8b95ab'>Console for <b>%1</b> (%2). Commands run non-interactively with a 120 s timeout.</span>").arg(x->config().name.toHtmlEscaped(), x->config().address()));
520
+ }
521
+ bool eventFilter(QObject *o, QEvent *e) override
522
+ {
523
+ const int k = e->type() == QEvent::KeyPress ? static_cast<QKeyEvent *>(e)->key() : 0;
524
+ if (o != in || hist.isEmpty() || (k != Qt::Key_Up && k != Qt::Key_Down)) return Tab::eventFilter(o, e);
525
+ return pos = qBound(0, pos + (k == Qt::Key_Up ? -1 : 1), hist.size()), in->setText(hist.value(pos)), true;
526
+ }
527
+ void exec(const QString &cmd, bool privileged)
528
+ {
529
+ out->appendHtml(QString("<br><span style='color:#38bdf8'><b>%1 $</b></span> %2").arg(QTime::currentTime().toString("HH:mm:ss"), cmd.toHtmlEscaped()));
530
+ auto clock = std::make_shared<QElapsedTimer>();
531
+ clock->start();
532
+ s->exec(cmd, privileged, [o = QPointer<QPlainTextEdit>(out), clock](int code, const QString &text) {
533
+ if (!o) return;
534
+ if (!text.isEmpty()) o->appendPlainText(text.endsWith('\n') ? text.chopped(1) : text);
535
+ o->appendHtml(QString("<span style='color:%1'>[exit %2 · %3 ms]</span>").arg(code ? "#ef4444" : "#22c55e").arg(code).arg(clock->elapsed()));
536
+ o->verticalScrollBar()->setValue(o->verticalScrollBar()->maximum());
537
+ }, 120000);
538
+ }
539
+ };
540
+
541
+ // ============================================================================ Alert rules
542
+ struct RulesTab : Tab {
543
+ QTableWidget *rules = table({"On", "Condition", "Severity", "Action", "Cooldown", "Live value"}, {50, 380, 100, 330, 100}), *live = table({"Active problems"});
544
+
545
+ RulesTab()
546
+ {
547
+ auto *l = plainRoot(this);
548
+ l->addWidget(label("Threshold rules are checked on every sample. When a condition holds for its duration an alert is raised and the action runs; "
549
+ "if it is still true after the cooldown the action runs again. History-based automation lives in the Insights tab.", "Muted", true));
550
+ auto *b = row(l);
551
+ b->addWidget(button("+ Add rule", "Primary", [this] { editRule(-1); })), b->addWidget(button("Edit", nullptr, [this] { editRule(rules->currentRow()); }));
552
+ b->addWidget(button("Delete", "Danger", [this] {
553
+ auto rs = s->config().rules;
554
+ if (rules->currentRow() >= 0 && rules->currentRow() < rs.size()) rs.remove(rules->currentRow()), store(rs);
555
+ }));
556
+ b->addStretch();
557
+ b->addWidget(button("Reset to defaults", nullptr, [this] {
558
+ if (ask(this, "Reset rules", "Replace all rules with the defaults?")) store(ServerConfig::defaultRules());
559
+ }));
560
+ live->setMaximumHeight(160), l->addWidget(rules, 2), l->addWidget(live, 1);
561
+ connect(rules, &QTableWidget::cellDoubleClicked, this, [this](int r) { editRule(r); });
562
+ connect(rules, &QTableWidget::itemChanged, this, [this](QTableWidgetItem *it) { // the "On" checkbox
563
+ auto rs = s->config().rules;
564
+ const bool on = it->checkState() == Qt::Checked;
565
+ if (it->column() == 0 && it->row() < rs.size() && rs[it->row()].enabled != on) rs[it->row()].enabled = on, store(rs);
566
+ });
567
+ }
568
+ void bind(ServerSession *x) override { Tab::bind(x), reload(); }
569
+ void store(const QVector<Rule> &rs)
570
+ {
571
+ ServerConfig c = s->config();
572
+ c.rules = rs, save(c), reload();
573
+ }
574
+ void reload()
575
+ {
576
+ if (!s) return;
577
+ QSignalBlocker block(rules);
578
+ fillRows(rules, s->config().rules, [](const Rule &r) {
579
+ return Row{{}, {r.conditionText(), r.enabled ? QColor() : C::faint}, {r.severity, C::severity(r.severity)},
580
+ {r.actionText(), r.action == "notify" ? C::muted : C::violet}, {QString("%1 s").arg(r.cooldown), C::muted}};
581
+ });
582
+ for (int i = 0; i < rules->rowCount(); ++i) rules->item(i, 0)->setCheckState(s->config().rules[i].enabled ? Qt::Checked : Qt::Unchecked);
583
+ refresh();
584
+ }
585
+ void refresh() override
586
+ {
587
+ const auto &rs = s->config().rules;
588
+ const QStringList act = s->activeAlerts();
589
+ QSignalBlocker block(rules);
590
+ for (int i = 0; i < rs.size() && i < rules->rowCount(); ++i) {
591
+ const double v = s->metricValue(rs[i].metric);
592
+ cell(rules, i, 5, {QString::number(v, 'f', 1) + " " + defLabel(ruleMetrics(), rs[i].metric, true), (rs[i].op == "<" ? v < rs[i].value : v > rs[i].value) ? C::red : C::green});
593
+ }
594
+ fillRows(live, act, [](const QString &a) { return Row{{"⚠ " + a, C::red}}; });
595
+ if (act.isEmpty()) live->setRowCount(1), cell(live, 0, 0, {"✓ No rule is currently triggered", C::green});
596
+ }
597
+ void editRule(int idx)
598
+ {
599
+ auto rs = s->config().rules;
600
+ Rule r;
601
+ r.id = ServerConfig::newId();
602
+ if (idx >= 0 && idx < rs.size()) r = rs[idx];
603
+ else idx = -1;
604
+ QDialog dlg(this);
605
+ dlg.setWindowTitle(idx < 0 ? "New rule" : "Edit rule");
606
+ auto *f = new QFormLayout(&dlg);
607
+ auto *metric = new QComboBox, *op = new QComboBox, *sev = new QComboBox, *action = new QComboBox;
608
+ auto *value = new QDoubleSpinBox;
609
+ auto *dur = new QSpinBox, *cool = new QSpinBox;
610
+ auto *arg = new QLineEdit(r.arg);
611
+ auto *en = new QCheckBox("Enabled");
612
+ auto *cond = new QHBoxLayout;
613
+ auto *bb = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
614
+ for (const Def &d : ruleMetrics()) metric->addItem(d.label + (d.unit.isEmpty() ? "" : " (" + d.unit + ")"), d.key);
615
+ for (const Def &d : P::ruleActions()) action->addItem(d.label, d.key);
616
+ op->addItems({">", "<"}), sev->addItems({"info", "warning", "critical"});
617
+ metric->setCurrentIndex(qMax(0, metric->findData(r.metric))), action->setCurrentIndex(qMax(0, action->findData(r.action)));
618
+ op->setCurrentText(r.op), sev->setCurrentText(r.severity), en->setChecked(r.enabled);
619
+ value->setRange(-1e9, 1e9), value->setValue(r.value);
620
+ dur->setRange(0, 86400), dur->setSuffix(" s"), dur->setValue(r.duration);
621
+ cool->setRange(10, 86400), cool->setSuffix(" s"), cool->setValue(r.cooldown);
622
+ auto sync = [action, arg] {
623
+ const QString hint = defLabel(P::ruleActions(), action->currentData().toString(), true);
624
+ arg->setEnabled(!hint.isEmpty()), arg->setPlaceholderText(hint);
625
+ };
626
+ connect(action, QOverload<int>::of(&QComboBox::currentIndexChanged), &dlg, sync);
627
+ connect(bb, &QDialogButtonBox::accepted, &dlg, &QDialog::accept), connect(bb, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
628
+ cond->addWidget(op), cond->addWidget(value, 1), sync();
629
+ f->addRow("When", metric), f->addRow("is", cond), f->addRow("for at least", dur), f->addRow("Severity", sev), f->addRow("Then", action);
630
+ f->addRow("Argument", arg), f->addRow("Repeat after", cool), f->addRow("", en), f->addRow(bb);
631
+ if (dlg.exec() != QDialog::Accepted) return;
632
+ r.metric = metric->currentData().toString(), r.op = op->currentText(), r.value = value->value(), r.duration = dur->value(), r.severity = sev->currentText();
633
+ r.action = action->currentData().toString(), r.arg = arg->isEnabled() ? arg->text().trimmed() : "", r.cooldown = cool->value(), r.enabled = en->isChecked();
634
+ idx < 0 ? (void)(rs << r) : (void)(rs[idx] = r);
635
+ store(rs);
636
+ }
637
+ };
638
+
639
+ // ============================================================================ History
640
+ struct HistoryTab : Tab {
641
+ qint64 range = 86400, lastLoad = 0;
642
+ QLabel *res = label({}, "Muted");
643
+ QVector<TimeChart *> charts;
644
+ QTableWidget *st = table({"Metric", "Minimum", "Average", "95th percentile", "Peak", "Points"}, {200, 150, 150, 150, 150});
645
+ QVector<HPoint> pts;
646
+
647
+ HistoryTab()
648
+ {
649
+ auto *l = scrollRoot(this);
650
+ auto *b = row(l);
651
+ auto *group = new QButtonGroup(this);
652
+ b->setSpacing(6);
653
+ for (auto [text, sec] : {std::pair{"1 h", 3600}, {"6 h", 21600}, {"24 h", 86400}, {"7 d", 604800}, {"30 d", 2592000}, {"90 d", 7776000}, {"1 y", 31536000}, {"All", 0}}) {
654
+ auto *btn = button(text);
655
+ btn->setCheckable(true), btn->setChecked(sec == 86400), group->addButton(btn, sec / 60), b->addWidget(btn);
656
+ }
657
+ b->addSpacing(14), b->addWidget(res), b->addStretch(), b->addWidget(button("Export CSV…", nullptr, [this] { exportCsv(); }));
658
+ connect(group, &QButtonGroup::idClicked, this, [this](int id) { range = id * 60LL, reload(); });
659
+ auto *g = grid(l);
660
+ for (auto [title, fmt, max] : {std::tuple{"CPU", pctFmt, 100.0}, {"Memory & swap", pctFmt, 100.0}, {"Disk usage (fullest)", pctFmt, 100.0},
661
+ {"Disk throughput", rateFmt, 0.0}, {"Network", rateFmt, 0.0}, {"Load average", numFmt(1), 0.0},
662
+ {"Temperature", FmtFn([](double v) { return QString::number(v, 'f', 0) + "°"; }), 0.0}, {"Availability", pctFmt, 100.0}}) {
663
+ charts << new TimeChart(title, fmt, max);
664
+ charts.last()->setMinimumHeight(240), charts.last()->empty = "No history for this range yet", g->addWidget(charts.last(), (charts.size() - 1) / 2, (charts.size() - 1) % 2);
665
+ }
666
+ st->setMinimumHeight(14 * 30 + 40), l->addWidget(panel("Statistics for the selected range", {st}));
667
+ }
668
+ void bind(ServerSession *x) override { Tab::bind(x), lastLoad = 0; }
669
+ void refresh() override
670
+ {
671
+ if (QDateTime::currentMSecsSinceEpoch() - lastLoad >= (range && range <= 21600 ? 5000 : 60000)) reload();
672
+ }
673
+ void reload()
674
+ {
675
+ lastLoad = QDateTime::currentMSecsSinceEpoch();
676
+ const qint64 now = QDateTime::currentSecsSinceEpoch(), from = range ? now - range : qMax<qint64>(1, s->store().firstTs());
677
+ Tier tier;
678
+ pts = s->store().range(from, now, &tier);
679
+ const qint64 step = qMax<qint64>(HistoryStore::step[int(tier)], s->config().interval);
680
+ QVector<qint64> t;
681
+ enum { CPU, CPUMAX, MEM, SWAP, DISK, RD, WR, RX, TX, RXMAX, LOAD, TEMP, TEMPMAX, AVAIL, N };
682
+ QVector<double> v[N];
683
+ double n = 0, up = 0;
684
+ auto push = [&](qint64 ts, const HPoint *p) { // p = nullptr inserts a gap
685
+ t << ts * 1000;
686
+ const int src[N] = {H_CPU, H_CPU, H_MEM, H_SWAP, H_DISK, H_RD, H_WR, H_RX, H_TX, H_RX, H_LOAD, H_TEMP, H_TEMP, -1};
687
+ for (int i = 0; i < N; ++i)
688
+ v[i] << (!p ? NAN : i == AVAIL ? p->uptimePct() : !p->nUp ? NAN : (i == CPUMAX || i == RXMAX || i == TEMPMAX) ? p->max[src[i]] : p->avg[src[i]]);
689
+ };
690
+ for (const HPoint &p : qAsConst(pts)) {
691
+ if (!t.isEmpty() && p.ts * 1000 - t.last() > step * 3000) push(t.last() / 1000 + step, nullptr); // app was not running
692
+ push(p.ts, &p), n += p.n, up += p.nUp;
693
+ }
694
+ if (!t.isEmpty() && now * 1000 - t.last() > step * 3000) push(now, nullptr);
695
+ const bool agg = tier != Tier::Raw;
696
+ auto peak = [&](QVector<Series> s, const QString &name, const QColor &c, const QVector<double> &d) { if (agg) s << Series{name, c, d, false, true}; return s; };
697
+ const QVector<QVector<Series>> data = {peak({{"Average", C::accent, v[CPU]}}, "Peak", C::red, v[CPUMAX]),
698
+ {{"Memory", C::violet, v[MEM]}, {"Swap", C::pink, v[SWAP], false}}, {{"Usage", C::amber, v[DISK]}},
699
+ {{"Read", C::blue, v[RD]}, {"Write", C::orange, v[WR]}},
700
+ peak({{"Down", C::teal, v[RX]}, {"Up", C::pink, v[TX]}}, "Peak down", C::teal.lighter(140), v[RXMAX]),
701
+ {{"Load", C::violet, v[LOAD]}}, peak({{"Average", C::orange, v[TEMP]}}, "Peak", C::red, v[TEMPMAX]),
702
+ {{"Online", C::green, v[AVAIL]}}};
703
+ for (int i = 0; i < charts.size(); ++i) charts[i]->subtitle = agg ? "avg per " + tierName(tier) : "", charts[i]->setData(t, data[i], (now - from) * 1000);
704
+ res->setText(QString("Resolution: %1 · %2 points · availability %3 · stored %4").arg(tierName(tier)).arg(pts.size()).arg(n ? Fmt::pct(up * 100 / n, 2) : "—", Fmt::bytes(s->store().diskBytes())));
705
+ QVector<int> ms = {H_CPU, H_IOWAIT, H_LOAD, H_MEM, H_SWAP, H_DISK, H_DISKIO, H_RX, H_TX, H_RD, H_WR, H_TEMP, H_PROCS, H_GPU};
706
+ if (!P::posixCpu) ms.remove(1);
707
+ fillRows(st, ms, [&](int m) {
708
+ const Stats x = stats(pts, m);
709
+ return Row{{hNames[m]}, {fmtMetric(m, x.min), C::muted, true}, {fmtMetric(m, x.avg), {}, true}, {fmtMetric(m, x.p95), C::amber, true},
710
+ {fmtMetric(m, x.max), C::red, true}, {QString::number(x.count), C::muted, true}};
711
+ });
712
+ }
713
+ void exportCsv()
714
+ {
715
+ const QString fn = QFileDialog::getSaveFileName(this, "Export history", s->config().name + "-history.csv", "CSV (*.csv)");
716
+ QFile f(fn);
717
+ if (fn.isEmpty() || !f.open(QIODevice::WriteOnly | QIODevice::Text)) return;
718
+ QTextStream ts(&f);
719
+ ts << "time,samples,online_pct";
720
+ for (const char *k : hKeys) ts << ',' << k << "_avg," << k << "_max";
721
+ auto num = [](float x) { return std::isnan(x) ? QString() : QString::number(x, 'f', 3); };
722
+ for (const HPoint &p : qAsConst(pts)) {
723
+ ts << '\n' << QDateTime::fromSecsSinceEpoch(p.ts).toString(Qt::ISODate) << ',' << p.n << ',' << p.uptimePct();
724
+ for (int m = 0; m < H_COUNT; ++m) ts << ',' << num(p.avg[m]) << ',' << num(p.max[m]);
725
+ }
726
+ }
727
+ };
728
+
729
+ // ============================================================================ Insights & Autopilot
730
+ struct InsightsTab : Tab {
731
+ RingGauge *health = new RingGauge("Health score");
732
+ QLabel *reasons = label({}, "Muted", true), *capacity = label({}, nullptr, true);
733
+ QVector<StatTile *> t;
734
+ QVBoxLayout *findings = new QVBoxLayout;
735
+ WeekHeatmap *heat = new WeekHeatmap;
736
+ QComboBox *heatMetric = new QComboBox;
737
+ QTableWidget *anomalies = table({"Metric", "Last 10 min", "Usual", "Deviation", "Baseline"}, {110, 110, 160, 90});
738
+ QVector<std::function<void(AutopilotConfig &, bool load)>> binds; // autopilot form <-> config
739
+ bool loading = false;
740
+
741
+ // form-field builders bound to AutopilotConfig members
742
+ QWidget *chk(const QString &text, bool AutopilotConfig::*f)
743
+ {
744
+ auto *w = new QCheckBox(text);
745
+ binds << [w, f](AutopilotConfig &a, bool ld) { ld ? w->setChecked(a.*f) : void(a.*f = w->isChecked()); };
746
+ connect(w, &QCheckBox::toggled, this, [this] { store(); });
747
+ return w;
748
+ }
749
+ template <class T, class W> QWidget *spin(T AutopilotConfig::*f, double lo, double hi, const QString &pre, const QString &suf)
750
+ {
751
+ auto *w = new W;
752
+ w->setRange(lo, hi), w->setPrefix(pre), w->setSuffix(suf);
753
+ if constexpr (std::is_same_v<W, QDoubleSpinBox>) w->setDecimals(f == &AutopilotConfig::anomalyZ ? 1 : 0), w->setSingleStep(f == &AutopilotConfig::anomalyZ ? 0.5 : 1);
754
+ binds << [w, f](AutopilotConfig &a, bool ld) { ld ? w->setValue(a.*f) : void(a.*f = w->value()); };
755
+ connect(w, QOverload<T>::of(&W::valueChanged), this, [this] { store(); });
756
+ return w;
757
+ }
758
+ QWidget *combo(QString AutopilotConfig::*f, const QStringList &keys, const QStringList &labels)
759
+ {
760
+ auto *w = new QComboBox;
761
+ for (int i = 0; i < keys.size(); ++i) w->addItem(labels[i], keys[i]);
762
+ binds << [w, f](AutopilotConfig &a, bool ld) { ld ? w->setCurrentIndex(qMax(0, w->findData(a.*f))) : void(a.*f = w->currentData().toString()); };
763
+ connect(w, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this] { store(); });
764
+ return w;
765
+ }
766
+
767
+ InsightsTab()
768
+ {
769
+ using A = AutopilotConfig;
770
+ using DS = QDoubleSpinBox;
771
+ auto *l = scrollRoot(this);
772
+ auto *top = row(l);
773
+ auto *hp = panel("Health", {health, reasons, button("Analyze now", nullptr, [this] { s->analyzeNow(); })});
774
+ hp->setFixedWidth(330), health->setMinimumHeight(190), top->addWidget(hp);
775
+ auto *right = sub<QVBoxLayout>(top, 1);
776
+ t = addTiles(grid(right), {{"Disk full forecast", C::amber}, {"Memory trend (6 h)", C::violet}, {"CPU / memory p95 (30 d)", C::accent},
777
+ {"Availability 24 h", C::green}, {"Availability 7 d", C::green}, {"Availability 30 d", C::green}}, 3);
778
+ right->addWidget(panel("Capacity planning", {capacity, nullptr}));
779
+
780
+ auto *mid = row(l);
781
+ auto *fp = panel("Findings from history analysis");
782
+ auto *ap = panel("Autopilot — automatic control", {label("Acts on the findings once a minute, using statistics over the stored history. Every action is logged as an event.", "Muted", true)});
783
+ auto *form = new QFormLayout;
784
+ auto *runRow = new QHBoxLayout;
785
+ auto *cmd = new QLineEdit;
786
+ findings->setSpacing(10), lay(fp)->addLayout(findings), lay(fp)->addStretch(), mid->addWidget(fp, 1);
787
+ runRow->addWidget(spin<double, DS>(&A::runawayCpu, 10, 6400, "≥ ", " %")), runRow->addWidget(spin<int, QSpinBox>(&A::runawayMinutes, 1, 1440, "for ", " min"));
788
+ cmd->setFont(QFont(C::mono(), 9));
789
+ binds << [cmd](A &a, bool ld) { ld ? cmd->setText(a.diskCleanupCommand) : void(a.diskCleanupCommand = cmd->text().trimmed()); };
790
+ connect(cmd, &QLineEdit::editingFinished, this, [this] { store(); });
791
+ form->addRow(chk("Autopilot enabled", &A::enabled), chk("Dry run (only report)", &A::dryRun));
792
+ form->addRow(chk("Restart failed services", &A::restartFailed), spin<int, QSpinBox>(&A::maxRestartsPerHour, 1, 20, "", " / hour max"));
793
+ form->addRow("Runaway processes", combo(&A::runawayMode, {"none", "renice", "terminate"}, {"Ignore", "Lower priority (renice 19)", "Terminate"}));
794
+ form->addRow("", runRow);
795
+ form->addRow("Memory leaks", combo(&A::leakMode, {"none", "notify", "terminate"}, {"Ignore", "Notify", "Terminate under pressure"}));
796
+ form->addRow(" pressure ≥", spin<double, DS>(&A::leakMemPressure, 50, 100, "", " % memory"));
797
+ form->addRow(chk("Disk cleanup", &A::diskCleanup), spin<int, QSpinBox>(&A::diskForecastDays, 1, 60, "full in < ", " days"));
798
+ form->addRow("", spin<double, DS>(&A::diskCleanupAt, 50, 100, "or usage ≥ ", " %"));
799
+ form->addRow(" command", cmd);
800
+ form->addRow(chk("Anomaly alerts", &A::anomalyAlerts), spin<double, DS>(&A::anomalyZ, 1.5, 10, "z ≥ ", " σ"));
801
+ ap->setFixedWidth(430), lay(ap)->addLayout(form), lay(ap)->addStretch(), mid->addWidget(ap, 0, Qt::AlignTop);
802
+
803
+ auto *bot = row(l);
804
+ heatMetric->addItems({"CPU", "Memory"}), heatMetric->setFixedWidth(140), anomalies->setMinimumHeight(230);
805
+ connect(heatMetric, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this] { analysis(); });
806
+ bot->addWidget(panel("Weekly pattern (last 4 weeks, hourly averages)", {heatMetric, heat}), 3), bot->addWidget(panel("Now vs. normal (baselines)", {anomalies}), 2);
807
+ }
808
+ void bind(ServerSession *x) override
809
+ {
810
+ Tab::bind(x);
811
+ if (!x) return;
812
+ AutopilotConfig a = x->config().autopilot;
813
+ loading = true;
814
+ for (auto &b : binds) b(a, true);
815
+ loading = false, analysis();
816
+ }
817
+ void store()
818
+ {
819
+ if (loading || !s) return;
820
+ ServerConfig c = s->config();
821
+ for (auto &b : binds) b(c.autopilot, false);
822
+ save(c);
823
+ }
824
+ void analysis() override
825
+ {
826
+ const Analysis &a = s->analysis();
827
+ const int hi = heatMetric->currentIndex();
828
+ health->setValue(a.health, QString::number(a.health), "grade " + a.grade, C::health(a.health));
829
+ reasons->setText((a.healthReasons.isEmpty() ? "No deductions — everything looks healthy." : a.healthReasons.join('\n')) +
830
+ (a.when ? "\n\nAnalyzed " + QDateTime::fromSecsSinceEpoch(a.when).toString("HH:mm:ss") : ""));
831
+ if (a.diskFullDays >= 0) t[0]->set(Fmt::duration(a.diskFullDays * 86400), QString("+%1 pts/day · %2").arg(a.diskSlopePerDay, 0, 'f', 2).arg(a.diskBasis), a.diskFullDays < 7 ? C::red : a.diskFullDays < 30 ? C::amber : QColor());
832
+ else t[0]->set("Not filling", a.diskBasis.isEmpty() ? "needs ~2 h of history" : QString("trend %1 pts/day").arg(a.diskSlopePerDay, 0, 'f', 2), C::green);
833
+ if (a.memTrendR2 > 0) t[1]->set(QString("%1%2 pts/h").arg(a.memSlopePerHour >= 0 ? "+" : "").arg(a.memSlopePerHour, 0, 'f', 2), QString("fit R² %1").arg(a.memTrendR2, 0, 'f', 2), a.memSlopePerHour > 1 && a.memTrendR2 > .8 ? C::amber : QColor());
834
+ else t[1]->set("—", "needs ~90 min of history");
835
+ t[2]->set(a.cpu30.count ? Fmt::pct(a.cpu30.p95, 0) + " / " + Fmt::pct(a.mem30.p95, 0) : "—", a.cpu30.count ? "avg " + Fmt::pct(a.cpu30.avg, 0) + " / " + Fmt::pct(a.mem30.avg, 0) : "collecting");
836
+ for (int i = 0; i < 3; ++i)
837
+ std::isnan(a.up[i]) ? t[3 + i]->set("—", "no data yet")
838
+ : t[3 + i]->set(Fmt::pct(a.up[i], a.up[i] >= 99.995 ? 0 : 2), "≈ " + Fmt::duration(a.down[i]) + " offline", a.up[i] >= 99.9 ? C::green : a.up[i] >= 99 ? C::amber : C::red);
839
+ capacity->setText("<p>• " + a.capacity.join("</p><p>• ") + "</p>");
840
+ heat->setData(a.heat[hi], a.heatN, hi ? "% memory" : "% CPU", hi ? C::violet : C::accent);
841
+ fillRows(anomalies, a.anomalies, [](const Anomaly &x) {
842
+ const double az = qAbs(x.z);
843
+ return Row{{x.metric}, {fmtMetric(x.hm, x.now), {}, true}, {fmtMetric(x.hm, x.mean) + " ± " + fmtMetric(x.hm, x.sd), C::muted, true},
844
+ {QString("%1%2σ").arg(x.z >= 0 ? "+" : "").arg(x.z, 0, 'f', 1), az >= 3 ? C::red : az >= 2 ? C::amber : C::green, true}, {x.baseline, C::muted}};
845
+ });
846
+
847
+ while (QLayoutItem *it = findings->takeAt(0)) { // rebuild the finding cards
848
+ if (it->widget()) it->widget()->deleteLater();
849
+ delete it;
850
+ }
851
+ if (a.findings.isEmpty()) {
852
+ auto *ok = label("✓ No problems found in the history. The analyzer checks disk forecasts, memory trends, leaks, runaway processes, service failures, overload and anomalies every minute.", nullptr, true);
853
+ ok->setStyleSheet("color: #22c55e; padding: 10px;"), findings->addWidget(ok);
854
+ }
855
+ const AutopilotConfig &ap = s->config().autopilot;
856
+ for (const Finding &f : a.findings) {
857
+ const QColor c = C::severity(f.severity);
858
+ auto *card = new QFrame;
859
+ auto *cl = new QHBoxLayout(card);
860
+ card->setObjectName("F");
861
+ card->setStyleSheet(QString("#F { background: #1a2133; border: 1px solid #27314a; border-left: 4px solid %1; border-radius: 10px; }").arg(c.name()));
862
+ cl->addWidget(label(QString("<span style='color:%1;font-size:11px;font-weight:700'>%2 · %3</span><br><span style='font-size:14px;font-weight:600'>%4</span><br>%5<br>"
863
+ "<span style='color:#8b95ab'>→ %6</span>%7").arg(c.name(), f.severity.toUpper(), f.category.toUpper(), f.title.toHtmlEscaped(), f.detail.toHtmlEscaped(), f.advice.toHtmlEscaped(),
864
+ f.autoEligible && ap.enabled ? QString("<br><span style='color:#a78bfa;font-size:11px'>%1</span>").arg(ap.dryRun ? "Autopilot (dry run) would act on this" : "Autopilot handles this automatically") : ""),
865
+ nullptr, true), 1);
866
+ findings->addWidget(card);
867
+ if (f.action.isEmpty()) continue;
868
+ auto *b = button(f.actionLabel, f.action == "kill_pid" ? "Danger" : "Primary");
869
+ cl->addWidget(b, 0, Qt::AlignVCenter);
870
+ connect(b, &QPushButton::clicked, this, [this, f, pb = QPointer<QPushButton>(b)] { // the card may be rebuilt while the question is open
871
+ if (!ask(this, f.actionLabel, QString("%1 on %2?\n\n%3").arg(f.actionLabel, s->config().name, f.title))) return;
872
+ if (pb) pb->setEnabled(false), pb->setText("Working…");
873
+ s->runFinding(f, false, [pb](int code, const QString &) { if (pb) pb->setText(code ? "✗ Failed" : "✓ Done"); });
874
+ });
875
+ }
876
+ }
877
+ };
878
+
879
+ QVector<QPair<QString, Tab *>> makeTabs()
880
+ {
881
+ return {{"Overview", new OverviewTab}, {"CPU", new CpuTab}, {"Memory", new MemoryTab}, {"Storage", new StorageTab}, {"Network", new NetworkTab},
882
+ {"Processes", new ProcessTab}, {"Services", new ServiceTab}, {"History", new HistoryTab}, {"Insights && Autopilot", new InsightsTab},
883
+ {"Alert rules", new RulesTab}, {"Console", new ConsoleTab}};
884
+ }
Server Monitor(cqt-linux)/src/ui/Widgets.cpp ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "Widgets.h"
2
+ #include <QDateTime>
3
+ #include <QFontDatabase>
4
+ #include <QGridLayout>
5
+ #include <QHeaderView>
6
+ #include <QMessageBox>
7
+ #include <QMouseEvent>
8
+ #include <QPainterPath>
9
+ #include <QToolTip>
10
+ #include <QVBoxLayout>
11
+ #include <cmath>
12
+
13
+ // ---- theme --------------------------------------------------------------------------------
14
+ QColor C::level(double p, double w, double c) { return p >= c ? red : p >= w ? amber : green; }
15
+ QColor C::severity(const QString &s) { return s == "critical" ? red : s == "warning" ? amber : s == "resolved" ? green : s == "action" ? violet : accent; }
16
+ QColor C::health(int h) { return h >= 90 ? green : h >= 75 ? teal : h >= 60 ? amber : h >= 40 ? orange : red; }
17
+ QColor C::mix(const QColor &a, const QColor &b, double t)
18
+ {
19
+ t = qBound(0.0, t, 1.0);
20
+ return QColor::fromRgbF(a.redF() + (b.redF() - a.redF()) * t, a.greenF() + (b.greenF() - a.greenF()) * t, a.blueF() + (b.blueF() - a.blueF()) * t);
21
+ }
22
+ QString C::mono() { return QFontDatabase::systemFont(QFontDatabase::FixedFont).family(); }
23
+
24
+ QString C::styleSheet()
25
+ {
26
+ return R"(
27
+ * { color: #e6ebf5; font-size: 13px; }
28
+ QMainWindow, QDialog, #Page { background: #0d111c; }
29
+ #Sidebar { background: #10151f; border-right: 1px solid #1f2738; }
30
+ QToolTip { background: #1a2133; border: 1px solid #38bdf8; padding: 6px; border-radius: 6px; }
31
+ QLabel#H1 { font-size: 22px; font-weight: 700; } QLabel#H2 { font-size: 16px; font-weight: 600; }
32
+ QLabel#Muted { color: #8b95ab; } QLabel#Section { color: #8b95ab; font-size: 11px; font-weight: 700; letter-spacing: 1px; }
33
+ QFrame#Panel { background: #161c2b; border: 1px solid #232c41; border-radius: 12px; }
34
+ QPushButton { background: #1d2538; border: 1px solid #2c3650; border-radius: 8px; padding: 7px 14px; font-weight: 600; }
35
+ QPushButton:hover { background: #253049; border-color: #38bdf8; } QPushButton:pressed { background: #18324a; }
36
+ QPushButton:disabled { color: #5a657d; border-color: #222a3c; }
37
+ QPushButton:checked, QPushButton#Primary { background: #0e7ab8; border-color: #38bdf8; color: white; } QPushButton#Primary:hover { background: #1190d8; }
38
+ QPushButton#Danger { background: #3a1820; border-color: #7f2a36; color: #ffb4bd; } QPushButton#Danger:hover { background: #55202b; border-color: #ef4444; }
39
+ QPushButton#Nav { text-align: left; padding: 10px 14px; border: none; background: transparent; font-size: 14px; }
40
+ QPushButton#Nav:hover { background: #1a2133; } QPushButton#Nav:checked { background: #17304a; color: #7dd3fc; }
41
+ QPushButton#Flat { background: transparent; border: none; padding: 4px 8px; color: #8b95ab; } QPushButton#Flat:hover { color: #e6ebf5; }
42
+ QPushButton#Side { text-align: left; padding: 6px 12px; }
43
+ QLineEdit, QSpinBox, QDoubleSpinBox, QComboBox, QPlainTextEdit { background: #111727; border: 1px solid #2a3449; border-radius: 7px; padding: 6px 8px; selection-background-color: #0e7ab8; }
44
+ QLineEdit:focus, QSpinBox:focus, QDoubleSpinBox:focus, QComboBox:focus, QPlainTextEdit:focus { border-color: #38bdf8; }
45
+ QComboBox::drop-down { border: none; width: 22px; }
46
+ QComboBox QAbstractItemView { background: #161c2b; border: 1px solid #2a3449; selection-background-color: #17304a; }
47
+ QCheckBox::indicator { width: 16px; height: 16px; border-radius: 4px; border: 1px solid #3a4662; background: #111727; }
48
+ QCheckBox::indicator:checked { background: #0ea5e9; border-color: #38bdf8; }
49
+ QTabWidget::pane { border: none; }
50
+ QTabBar::tab { background: transparent; color: #8b95ab; padding: 10px 14px; border-bottom: 2px solid transparent; }
51
+ QTabBar::tab:hover { color: #e6ebf5; } QTabBar::tab:selected { color: #7dd3fc; border-bottom: 2px solid #38bdf8; }
52
+ QTableView, QListView { background: #131929; alternate-background-color: #161d2e; border: 1px solid #232c41; border-radius: 10px;
53
+ selection-background-color: #17304a; selection-color: #e6ebf5; outline: none; }
54
+ QTableView::item { padding: 4px; }
55
+ QHeaderView::section { background: #182033; color: #8b95ab; border: none; border-bottom: 1px solid #27314a; padding: 7px 8px; font-weight: 700; font-size: 12px; }
56
+ QScrollBar:vertical { background: transparent; width: 10px; margin: 2px; } QScrollBar:horizontal { background: transparent; height: 10px; margin: 2px; }
57
+ QScrollBar::handle { background: #2a3449; border-radius: 4px; min-height: 30px; min-width: 30px; } QScrollBar::handle:hover { background: #3b4866; }
58
+ QScrollBar::add-line, QScrollBar::sub-line { width: 0; height: 0; } QScrollBar::add-page, QScrollBar::sub-page { background: none; }
59
+ QScrollArea { border: none; background: transparent; } QScrollArea > QWidget > QWidget { background: transparent; }
60
+ QMenu { background: #161c2b; border: 1px solid #2a3449; border-radius: 8px; padding: 6px; }
61
+ QMenu::item { padding: 7px 22px; border-radius: 5px; } QMenu::item:selected { background: #17304a; }
62
+ QMenu::separator { height: 1px; background: #27314a; margin: 4px 8px; }
63
+ )";
64
+ }
65
+
66
+ QIcon C::appIcon()
67
+ {
68
+ QIcon icon;
69
+ for (int s : {16, 32, 64, 128, 256}) {
70
+ QPixmap pm(s, s);
71
+ pm.fill(Qt::transparent);
72
+ QPainter p(&pm);
73
+ p.setRenderHint(QPainter::Antialiasing);
74
+ QLinearGradient g(0, 0, s, s);
75
+ g.setColorAt(0, 0x0ea5e9), g.setColorAt(1, 0x7c3aed);
76
+ p.setBrush(g), p.setPen(Qt::NoPen);
77
+ p.drawRoundedRect(QRectF(0, 0, s, s), s * .22, s * .22);
78
+ p.setPen(QPen(Qt::white, qMax(1.5, s * .075), Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
79
+ p.drawPolyline(QPolygonF({{s * .12, s * .56}, {s * .34, s * .56}, {s * .44, s * .28}, {s * .56, s * .78}, {s * .66, s * .48}, {s * .88, s * .48}}));
80
+ icon.addPixmap(pm);
81
+ }
82
+ return icon;
83
+ }
84
+
85
+ QFont pxFont(QFont f, int px, bool bold) { return f.setPixelSize(px), f.setBold(bold), f; }
86
+ static double niceCeil(double v)
87
+ {
88
+ if (v <= 0) return 1;
89
+ const double e = std::pow(10, std::floor(std::log10(v))), f = v / e;
90
+ return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * e;
91
+ }
92
+ static void roundedPanel(QPainter &p, const QRectF &r, const QBrush &b, const QColor &border = C::border, double rad = 12)
93
+ {
94
+ p.setPen(QPen(border, 1)), p.setBrush(b);
95
+ p.drawRoundedRect(r.adjusted(.5, .5, -.5, -.5), rad, rad);
96
+ }
97
+
98
+ void paintRing(QPainter &p, const QRectF &r, double pct, const QColor &c, double t, bool glow)
99
+ {
100
+ p.save();
101
+ p.setRenderHint(QPainter::Antialiasing);
102
+ const QRectF rr = r.adjusted(t / 2, t / 2, -t / 2, -t / 2);
103
+ p.setPen(QPen(C::grid, t, Qt::SolidLine, Qt::RoundCap));
104
+ p.drawArc(rr, 225 * 16, -270 * 16);
105
+ const int span = int(-270 * 16 * qBound(0.0, pct, 100.0) / 100);
106
+ if (span < -3) {
107
+ if (glow) p.setPen(QPen(C::tint(c, 45), t * 2, Qt::SolidLine, Qt::RoundCap)), p.drawArc(rr, 225 * 16, span);
108
+ p.setPen(QPen(c, t, Qt::SolidLine, Qt::RoundCap));
109
+ p.drawArc(rr, 225 * 16, span);
110
+ }
111
+ p.restore();
112
+ }
113
+
114
+ // ---- RingGauge ------------------------------------------------------------------------------
115
+ RingGauge::RingGauge(const QString &title) : m_title(title)
116
+ {
117
+ m_anim.setDuration(450), m_anim.setEasingCurve(QEasingCurve::OutCubic);
118
+ connect(&m_anim, &QVariantAnimation::valueChanged, this, [this](const QVariant &v) { m_shown = v.toDouble(), update(); });
119
+ }
120
+ void RingGauge::setValue(double pct, const QString &center, const QString &sub, const QColor &color)
121
+ {
122
+ m_center = center, m_sub = sub, m_color = color;
123
+ pct = std::isnan(pct) ? 0 : pct;
124
+ if (qAbs(pct - m_target) > 0.05) m_anim.stop(), m_anim.setStartValue(m_shown), m_anim.setEndValue(m_target = pct), m_anim.start();
125
+ update();
126
+ }
127
+ void RingGauge::paintEvent(QPaintEvent *)
128
+ {
129
+ AA p(this);
130
+ const double s = qMin(width() - 8.0, height() - 28.0);
131
+ const QRectF r((width() - s) / 2, 4, s, s);
132
+ paintRing(p, r, m_shown, m_color.isValid() ? m_color : C::level(m_target, warn, crit), qMax(7.0, s * .085));
133
+ p.setFont(pxFont(font(), int(s * .2), true)), p.setPen(C::text);
134
+ p.drawText(QRectF(r.left(), r.top() + s * .3, s, s * .26), Qt::AlignCenter, m_center.isEmpty() ? QString::number(m_shown, 'f', 0) + "%" : m_center);
135
+ p.setFont(pxFont(font(), qMax(10, int(s * .075)))), p.setPen(C::muted);
136
+ p.drawText(QRectF(r.left() + s * .12, r.top() + s * .56, s * .76, s * .14), Qt::AlignCenter, p.fontMetrics().elidedText(m_sub, Qt::ElideRight, int(s * .76)));
137
+ p.setFont(pxFont(font(), 13, true)), p.setPen(C::text);
138
+ p.drawText(QRectF(0, r.bottom() - s * .06, width(), 22), Qt::AlignHCenter, m_title);
139
+ }
140
+
141
+ // ---- TimeChart --------------------------------------------------------------------------------
142
+ TimeChart::TimeChart(const QString &t, FmtFn fmt, double yMax) : title(t), m_fmt(fmt), m_yMax(yMax)
143
+ {
144
+ setMouseTracking(true), setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
145
+ }
146
+ void TimeChart::setData(const QVector<qint64> &t, const QVector<Series> &s, qint64 span) { m_t = t, m_s = s, m_span = span, update(); }
147
+ void TimeChart::mouseMoveEvent(QMouseEvent *e) { m_hover = e->pos().x(), update(); }
148
+
149
+ void TimeChart::paintEvent(QPaintEvent *)
150
+ {
151
+ AA p(this);
152
+ roundedPanel(p, rect(), C::panel);
153
+ p.setFont(pxFont(font(), 13, true)), p.setPen(C::text);
154
+ p.drawText(16, 10, width(), 20, Qt::AlignVCenter, title);
155
+ const int titleW = p.fontMetrics().horizontalAdvance(title);
156
+ p.setFont(pxFont(font(), 11)), p.setPen(C::muted);
157
+ p.drawText(24 + titleW, 10, width(), 20, Qt::AlignVCenter, subtitle);
158
+ double lx = width() - 16; // legend with latest values, right-aligned
159
+ for (int i = m_s.size() - 1; i >= 0; --i) {
160
+ const Series &s = m_s[i];
161
+ double last = NAN;
162
+ for (int k = s.v.size() - 1; k >= qMax(0, s.v.size() - 5) && std::isnan(last); --k) last = s.v[k];
163
+ const QString txt = s.name + (std::isnan(last) ? "" : " " + m_fmt(last));
164
+ const int w = p.fontMetrics().horizontalAdvance(txt);
165
+ if ((lx -= w) < 40 + titleW) break;
166
+ p.setPen(C::muted), p.drawText(QRectF(lx, 10, w, 20), Qt::AlignVCenter, txt);
167
+ p.setPen(Qt::NoPen), p.setBrush(s.color), p.drawRoundedRect(QRectF(lx -= 14, 16, 9, 9), 2, 2);
168
+ lx -= 14;
169
+ }
170
+ const int n = m_t.size();
171
+ int first = 0;
172
+ if (n && m_span)
173
+ while (first < n && m_t[first] < m_t.last() - m_span) ++first;
174
+ QRectF plot(56, 40, width() - 72, height() - 70);
175
+ if (n - first < 2 || plot.height() < 20) return p.setPen(C::faint), p.drawText(plot, Qt::AlignCenter, empty);
176
+
177
+ double yMax = m_yMax;
178
+ if (yMax <= 0) {
179
+ for (int i = first; i < n; ++i) {
180
+ double sum = 0;
181
+ for (const Series &s : m_s)
182
+ if (i < s.v.size() && !std::isnan(s.v[i])) sum = stacked ? sum + s.v[i] : qMax(sum, s.v[i]);
183
+ yMax = qMax(yMax, sum);
184
+ }
185
+ yMax = niceCeil(yMax * 1.12);
186
+ }
187
+ p.setFont(pxFont(font(), 10));
188
+ int lw = 0;
189
+ for (int g = 0; g <= 4; ++g) lw = qMax(lw, p.fontMetrics().horizontalAdvance(m_fmt(yMax * g / 4)));
190
+ plot.setLeft(qMax(40, lw + 18));
191
+ const qint64 t1 = m_t.last(), t0 = m_span ? t1 - m_span : m_t[first];
192
+ const double tr = qMax<qint64>(1, t1 - t0);
193
+ auto X = [&](qint64 t) { return plot.left() + (t - t0) / tr * plot.width(); };
194
+ auto Y = [&](double v) { return plot.bottom() - qBound(0.0, v, yMax) / yMax * plot.height(); };
195
+ const QString tf = tr <= 72e5 ? "HH:mm" : tr <= 2.6e8 ? "ddd HH:mm" : tr <= 3.5e10 ? "dd MMM" : "MMM yyyy";
196
+ for (int g = 0; g <= 4; ++g) { // grid, y labels, time labels
197
+ const double y = Y(yMax * g / 4), x = X(t0 + qint64(tr * g / 4));
198
+ p.setPen(QPen(C::grid, 1, g ? Qt::DashLine : Qt::SolidLine)), p.drawLine(QPointF(plot.left(), y), QPointF(plot.right(), y));
199
+ p.setPen(C::faint);
200
+ p.drawText(QRectF(0, y - 8, plot.left() - 8, 16), Qt::AlignRight | Qt::AlignVCenter, m_fmt(yMax * g / 4));
201
+ p.drawText(QRectF(g == 0 ? x : g == 4 ? x - 120 : x - 60, plot.bottom() + 6, 120, 16), (g == 0 ? Qt::AlignLeft : g == 4 ? Qt::AlignRight : Qt::AlignHCenter),
202
+ QDateTime::fromMSecsSinceEpoch(t0 + qint64(tr * g / 4)).toString(tf));
203
+ }
204
+ const int step = qMax(1, (n - first) / qMax(50, int(plot.width() * 1.5))); // ~1.5 points per pixel
205
+ QVector<double> base(n, 0.0);
206
+ p.setClipRect(plot.adjusted(-2, -4, 2, 2));
207
+ for (const Series &s : m_s) {
208
+ QVector<QPolygonF> top(1), bot(1); // runs split at gaps (NaN)
209
+ for (int i = first; i < n; i += step) {
210
+ double sum = 0, bs = 0;
211
+ int c = 0;
212
+ for (int k = i; k < qMin(n, i + step); ++k)
213
+ if (k < s.v.size() && !std::isnan(s.v[k])) sum += s.v[k], bs += base[k], ++c;
214
+ if (!c) { if (!top.last().isEmpty()) top << QPolygonF(), bot << QPolygonF(); continue; }
215
+ const double x = X(m_t[qMin(n - 1, i + step / 2)]), b = stacked ? bs / c : 0;
216
+ top.last() << QPointF(x, Y(sum / c + b)), bot.last() << QPointF(x, Y(b));
217
+ }
218
+ if (stacked)
219
+ for (int k = first; k < qMin(n, s.v.size()); ++k) base[k] += std::isnan(s.v[k]) ? 0 : s.v[k];
220
+ for (int r = 0; r < top.size(); ++r) {
221
+ if (top[r].size() < 2) continue;
222
+ if (s.fill) {
223
+ QPolygonF area = top[r];
224
+ for (int i = bot[r].size() - 1; i >= 0; --i) area << bot[r][i];
225
+ QLinearGradient g(0, plot.top(), 0, plot.bottom());
226
+ g.setColorAt(0, C::tint(s.color, stacked ? 120 : 95)), g.setColorAt(1, C::tint(s.color, stacked ? 60 : 4));
227
+ p.setPen(Qt::NoPen), p.setBrush(g), p.drawPolygon(area);
228
+ }
229
+ p.setBrush(Qt::NoBrush), p.setPen(QPen(s.color, s.dashed ? 1.3 : 2, s.dashed ? Qt::DashLine : Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
230
+ p.drawPolyline(top[r]);
231
+ }
232
+ }
233
+ p.setClipping(false);
234
+ if (m_hover < plot.left() || m_hover > plot.right()) return;
235
+ const qint64 ht = t0 + qint64((m_hover - plot.left()) / plot.width() * tr); // crosshair + tooltip
236
+ const int best = std::lower_bound(m_t.begin() + first, m_t.end(), ht) - m_t.begin() - (m_t.last() < ht);
237
+ const double x = X(m_t[best]);
238
+ p.setPen(QPen(QColor(255, 255, 255, 70), 1, Qt::DashLine)), p.drawLine(QPointF(x, plot.top()), QPointF(x, plot.bottom()));
239
+ QStringList lines{QDateTime::fromMSecsSinceEpoch(m_t[best]).toString(tr > 864e5 ? "ddd dd MMM HH:mm" : "HH:mm:ss")};
240
+ double stack = 0;
241
+ for (const Series &s : m_s) {
242
+ const double v = best < s.v.size() ? s.v[best] : NAN;
243
+ lines << s.name + ": " + (std::isnan(v) ? "—" : m_fmt(v));
244
+ if (std::isnan(v)) continue;
245
+ stack = stacked ? stack + v : v;
246
+ p.setPen(QPen(C::panel, 2)), p.setBrush(s.color), p.drawEllipse(QPointF(x, Y(stack)), 4, 4);
247
+ }
248
+ p.setFont(pxFont(font(), 11));
249
+ int tw = 0;
250
+ for (const QString &l : lines) tw = qMax(tw, p.fontMetrics().horizontalAdvance(l));
251
+ const QRectF tip(qMin(x + 12, plot.right() - tw - 20), plot.top() + 4, tw + 18, lines.size() * 16 + 10);
252
+ roundedPanel(p, tip, QColor(13, 17, 28, 235), C::border, 7);
253
+ for (int i = 0; i < lines.size(); ++i) p.setPen(i ? C::text : C::muted), p.drawText(QRectF(tip.left() + 9, tip.top() + 5 + i * 16, tw + 4, 16), Qt::AlignVCenter, lines[i]);
254
+ }
255
+
256
+ // ---- SegmentBar --------------------------------------------------------------------------------
257
+ SegmentBar::SegmentBar() { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed), setFixedHeight(58); }
258
+ void SegmentBar::setSegments(const QVector<Segment> &s, double total) { m_s = s, m_total = total > 0 ? total : 1, update(); }
259
+ void SegmentBar::paintEvent(QPaintEvent *)
260
+ {
261
+ AA p(this);
262
+ QPainterPath clip;
263
+ clip.addRoundedRect(QRectF(0, 2, width(), 14), 7, 7);
264
+ p.setClipPath(clip);
265
+ p.fillRect(rect(), C::grid);
266
+ double x = 0, lx = 0, ly = 26;
267
+ for (const Segment &s : m_s) p.fillRect(QRectF(x, 2, s.value / m_total * width(), 14), s.color), x += qMax(0.0, s.value / m_total * width());
268
+ p.setClipping(false);
269
+ p.setFont(pxFont(font(), 11));
270
+ for (const Segment &s : m_s) {
271
+ const QString t = s.label + " " + Fmt::bytes(s.value);
272
+ const int w = p.fontMetrics().horizontalAdvance(t) + 26;
273
+ if (lx + w > width()) lx = 0, ly += 18;
274
+ p.setPen(Qt::NoPen), p.setBrush(s.color), p.drawRoundedRect(QRectF(lx, ly + 3, 9, 9), 2, 2);
275
+ p.setPen(C::muted), p.drawText(QRectF(lx + 14, ly, w, 16), Qt::AlignVCenter, t);
276
+ lx += w;
277
+ }
278
+ }
279
+
280
+ // ---- StatTile ------------------------------------------------------------------------------------
281
+ StatTile::StatTile(const QString &title, const QColor &accent) : m_accent(accent)
282
+ {
283
+ auto *l = new QVBoxLayout(this);
284
+ l->setContentsMargins(16, 12, 14, 12), l->setSpacing(2);
285
+ l->addWidget(label(title.toUpper(), "Section"));
286
+ l->addWidget(m_value = new QLabel("—"));
287
+ l->addWidget(m_sub = label({}, "Muted"));
288
+ m_sub->setStyleSheet("font-size: 11px;");
289
+ setMinimumHeight(84), setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed), set("—");
290
+ }
291
+ void StatTile::set(const QString &v, const QString &sub, const QColor &c)
292
+ {
293
+ m_value->setText(v), m_sub->setText(sub), m_sub->setVisible(!sub.isEmpty());
294
+ m_value->setStyleSheet(QString("font-size: 21px; font-weight: 700; color: %1;").arg((c.isValid() ? c : C::text).name()));
295
+ }
296
+ void StatTile::paintEvent(QPaintEvent *)
297
+ {
298
+ AA p(this);
299
+ QLinearGradient g(0, 0, width(), height());
300
+ g.setColorAt(0, C::card), g.setColorAt(1, C::panel);
301
+ roundedPanel(p, rect(), g);
302
+ p.setPen(Qt::NoPen), p.setBrush(m_accent), p.drawRoundedRect(QRectF(0, 14, 4, height() - 28), 2, 2);
303
+ }
304
+ QVector<StatTile *> addTiles(QGridLayout *g, const QVector<QPair<QString, QColor>> &defs, int cols)
305
+ {
306
+ QVector<StatTile *> out;
307
+ g->setSpacing(14);
308
+ for (const auto &d : defs) out << new StatTile(d.first, d.second), g->addWidget(out.last(), (out.size() - 1) / cols, (out.size() - 1) % cols);
309
+ return out;
310
+ }
311
+
312
+ // ---- CoreGrid ---------------------------------------------------------------------------------------
313
+ CoreGrid::CoreGrid()
314
+ {
315
+ QSizePolicy sp(QSizePolicy::Expanding, QSizePolicy::Preferred);
316
+ sp.setHeightForWidth(true);
317
+ setSizePolicy(sp);
318
+ }
319
+ void CoreGrid::setCores(const QVector<CoreStat> &c)
320
+ {
321
+ if (c.size() != m_c.size()) updateGeometry();
322
+ m_c = c, update();
323
+ }
324
+ void CoreGrid::paintEvent(QPaintEvent *)
325
+ {
326
+ AA p(this);
327
+ const int cols = qMax(1, width() / 92);
328
+ const double cw = double(width()) / cols;
329
+ for (int i = 0; i < m_c.size(); ++i) {
330
+ const double u = m_c[i].usage;
331
+ const QColor c = C::level(u, 60, 85);
332
+ const QRectF r(cw * (i % cols) + 3, i / cols * 66 + 3, cw - 6, 60), bar(r.left() + 8, r.bottom() - 10, r.width() - 16, 4);
333
+ roundedPanel(p, r, C::mix(C::card, c, u / 420), C::mix(C::border, c, u / 160), 8);
334
+ p.setPen(Qt::NoPen), p.setBrush(C::grid), p.drawRoundedRect(bar, 2, 2);
335
+ p.setBrush(c), p.drawRoundedRect(QRectF(bar.left(), bar.top(), bar.width() * u / 100, 4), 2, 2);
336
+ p.setFont(pxFont(font(), 10)), p.setPen(C::muted);
337
+ p.drawText(r.adjusted(8, 5, -8, 0), Qt::AlignLeft, QString("CPU %1").arg(i));
338
+ if (m_c[i].mhz > 0) p.drawText(r.adjusted(8, 5, -8, 0), Qt::AlignRight, QString::number(m_c[i].mhz / 1000, 'f', 1) + "G");
339
+ p.setFont(pxFont(font(), 16, true)), p.setPen(C::text);
340
+ p.drawText(r.adjusted(8, 18, -8, -14), Qt::AlignVCenter, QString::number(u, 'f', 0) + "%");
341
+ }
342
+ }
343
+
344
+ // ---- WeekHeatmap ---------------------------------------------------------------------------------------
345
+ static const QStringList kDays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
346
+ WeekHeatmap::WeekHeatmap() : m_hot(C::accent)
347
+ {
348
+ std::fill(&m_v[0][0], &m_v[0][0] + 168, NAN), std::fill(&m_n[0][0], &m_n[0][0] + 168, 0);
349
+ setMouseTracking(true), setMinimumHeight(230);
350
+ }
351
+ void WeekHeatmap::setData(const double v[7][24], const int n[7][24], const QString &unit, const QColor &hot)
352
+ {
353
+ std::copy(&v[0][0], &v[0][0] + 168, &m_v[0][0]);
354
+ std::copy(&n[0][0], &n[0][0] + 168, &m_n[0][0]);
355
+ m_unit = unit, m_hot = hot, update();
356
+ }
357
+ QRectF WeekHeatmap::cell(int d, int h) const
358
+ {
359
+ const double cw = (width() - 44) / 24.0, ch = (height() - 30) / 7.0;
360
+ return QRectF(40 + h * cw + 1.5, 6 + d * ch + 1.5, cw - 3, ch - 3);
361
+ }
362
+ void WeekHeatmap::paintEvent(QPaintEvent *)
363
+ {
364
+ AA p(this);
365
+ p.setFont(pxFont(font(), 10));
366
+ bool any = false;
367
+ for (int d = 0; d < 7; ++d) {
368
+ p.setPen(C::muted), p.drawText(QRectF(0, cell(d, 0).top(), 34, cell(d, 0).height()), Qt::AlignRight | Qt::AlignVCenter, kDays[d].left(3));
369
+ for (int h = 0; h < 24; ++h) {
370
+ const double v = m_v[d][h];
371
+ any |= !std::isnan(v);
372
+ p.setPen(Qt::NoPen), p.setBrush(std::isnan(v) ? C::card : C::mix(0x1b2a44, m_hot, .15 + .85 * qBound(0.0, v / 100, 1.0)));
373
+ p.drawRoundedRect(cell(d, h), 3, 3);
374
+ }
375
+ }
376
+ p.setPen(C::faint);
377
+ for (int h = 0; h < 24; h += 3) p.drawText(QRectF(cell(6, h).left() - 4, cell(6, h).bottom() + 4, 40, 14), Qt::AlignLeft, QString("%1:00").arg(h, 2, 10, QChar('0')));
378
+ if (any) return;
379
+ const QRectF box(cell(2, 3).topLeft(), cell(4, 20).bottomRight());
380
+ p.fillRect(box, QColor(13, 17, 28, 200)), p.setPen(C::text), p.setFont(pxFont(font(), 12));
381
+ p.drawText(box, Qt::AlignCenter, "Collecting hourly history… the weekly pattern fills in over time");
382
+ }
383
+ void WeekHeatmap::mouseMoveEvent(QMouseEvent *e)
384
+ {
385
+ for (int d = 0; d < 7; ++d)
386
+ for (int h = 0; h < 24; ++h)
387
+ if (cell(d, h).contains(e->pos()))
388
+ return QToolTip::showText(e->globalPos(), std::isnan(m_v[d][h]) ? QString("%1 %2:00 — no data").arg(kDays[d]).arg(h)
389
+ : QString("%1 %2:00 — avg %3%4 (%5 samples)").arg(kDays[d]).arg(h).arg(m_v[d][h], 0, 'f', 1).arg(m_unit).arg(m_n[d][h]), this);
390
+ QToolTip::hideText();
391
+ }
392
+
393
+ // ---- table helpers --------------------------------------------------------------------------------------
394
+ void BarDelegate::paint(QPainter *p, const QStyleOptionViewItem &o, const QModelIndex &i) const
395
+ {
396
+ const QVariant pv = i.data(Qt::UserRole);
397
+ if (!pv.isValid()) return QStyledItemDelegate::paint(p, o, i);
398
+ p->save();
399
+ p->setRenderHint(QPainter::Antialiasing);
400
+ if (o.state & QStyle::State_Selected) p->fillRect(o.rect, o.palette.highlight());
401
+ const double pct = qBound(0.0, pv.toDouble(), 100.0);
402
+ const QRectF r = QRectF(o.rect).adjusted(6, o.rect.height() / 2.0 - 7, -6, -(o.rect.height() / 2.0 - 7));
403
+ const QColor c = C::level(pct);
404
+ p->setPen(Qt::NoPen), p->setBrush(C::grid), p->drawRoundedRect(r, 4, 4);
405
+ p->setBrush(C::tint(c, 200)), p->drawRoundedRect(QRectF(r.left(), r.top(), r.width() * pct / 100, r.height()), 4, 4);
406
+ p->setFont(pxFont(o.font, 11, true)), p->setPen(C::text), p->drawText(r, Qt::AlignCenter, i.data().toString());
407
+ p->restore();
408
+ }
409
+
410
+ int FlowLayout::place(const QRect &r, bool apply) const
411
+ {
412
+ if (m_items.isEmpty()) return 0;
413
+ const int sp = 16, minW = m_items[0]->minimumSize().width(), cols = qMax(1, (r.width() + sp) / (minW + sp)), w = (r.width() - (cols - 1) * sp) / cols;
414
+ int y = r.y(), rowH = 0, col = 0;
415
+ for (QLayoutItem *it : m_items) {
416
+ if (it->widget() && it->widget()->isHidden()) continue;
417
+ if (apply) it->setGeometry(QRect(r.x() + col * (w + sp), y, w, it->sizeHint().height()));
418
+ rowH = qMax(rowH, it->sizeHint().height());
419
+ if (++col == cols) col = 0, y += rowH + sp, rowH = 0;
420
+ }
421
+ return y + rowH - r.y();
422
+ }
423
+
424
+ // ---- builders ----------------------------------------------------------------------------------------
425
+ QLabel *label(const QString &text, const char *name, bool wrap)
426
+ {
427
+ auto *l = new QLabel(text);
428
+ if (name) l->setObjectName(name);
429
+ l->setWordWrap(wrap);
430
+ return l;
431
+ }
432
+ QPushButton *button(const QString &text, const char *style, std::function<void()> onClick)
433
+ {
434
+ auto *b = new QPushButton(text);
435
+ if (style) b->setObjectName(style);
436
+ if (onClick) QObject::connect(b, &QPushButton::clicked, b, onClick);
437
+ return b;
438
+ }
439
+ QFrame *panel(const QString &title, std::initializer_list<QWidget *> content)
440
+ {
441
+ auto *f = new QFrame;
442
+ f->setObjectName("Panel");
443
+ auto *l = new QVBoxLayout(f);
444
+ l->setContentsMargins(16, 14, 16, 14), l->setSpacing(10);
445
+ if (!title.isEmpty()) l->addWidget(label(title.toUpper(), "Section"));
446
+ for (QWidget *w : content) w ? l->addWidget(w) : l->addStretch();
447
+ return f;
448
+ }
449
+ bool ask(QWidget *parent, const QString &title, const QString &text) { return QMessageBox::question(parent, title, text) == QMessageBox::Yes; }
450
+
451
+ namespace {
452
+ struct SortItem : QTableWidgetItem { // sorts by Qt::UserRole+1 when set (numbers sort numerically)
453
+ bool operator<(const QTableWidgetItem &o) const override
454
+ {
455
+ const QVariant a = data(Qt::UserRole + 1), b = o.data(Qt::UserRole + 1);
456
+ if (!a.isValid() || !b.isValid()) return text() < o.text();
457
+ return a.type() == QVariant::String ? a.toString() < b.toString() : a.toDouble() < b.toDouble();
458
+ }
459
+ };
460
+ }
461
+
462
+ QTableWidget *table(const QStringList &headers, const QVector<int> &widths, const QVector<int> &bars)
463
+ {
464
+ auto *t = new QTableWidget(0, headers.size());
465
+ t->setHorizontalHeaderLabels(headers);
466
+ t->verticalHeader()->hide(), t->verticalHeader()->setDefaultSectionSize(30);
467
+ t->setAlternatingRowColors(true), t->setShowGrid(false), t->setWordWrap(false);
468
+ t->setSelectionBehavior(QAbstractItemView::SelectRows), t->setSelectionMode(QAbstractItemView::SingleSelection);
469
+ t->setEditTriggers(QAbstractItemView::NoEditTriggers), t->setFocusPolicy(Qt::NoFocus), t->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
470
+ t->horizontalHeader()->setHighlightSections(false), t->horizontalHeader()->setStretchLastSection(true);
471
+ t->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter);
472
+ for (int i = 0; i < widths.size(); ++i) t->setColumnWidth(i, widths[i]);
473
+ for (int c : bars) t->setItemDelegateForColumn(c, new BarDelegate(t));
474
+ return t;
475
+ }
476
+ void cell(QTableWidget *t, int r, int c, const Cell &x)
477
+ {
478
+ QTableWidgetItem *it = t->item(r, c);
479
+ if (!it) t->setItem(r, c, it = new SortItem);
480
+ if (it->text() != x.text) it->setText(x.text);
481
+ it->setTextAlignment(int(x.right ? Qt::AlignRight : Qt::AlignLeft) | Qt::AlignVCenter);
482
+ it->setForeground(x.color.isValid() ? x.color : C::text);
483
+ if (x.pct >= 0) it->setData(Qt::UserRole, x.pct);
484
+ if (x.key.isValid()) it->setData(Qt::UserRole + 1, x.key);
485
+ }
Server Monitor(cqt-linux)/src/ui/Widgets.h ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Theme, hand-painted widgets (gauges, time charts, bars, tiles, core grid, weekly
2
+ // heatmap), a flow layout and small builders for labels, buttons, panels and tables.
3
+ #pragma once
4
+ #include "core/Model.h"
5
+ #include <QFrame>
6
+ #include <QLabel>
7
+ #include <QLayout>
8
+ #include <QPainter>
9
+ #include <QPushButton>
10
+ #include <QStyledItemDelegate>
11
+ #include <QTableWidget>
12
+ #include <QVariantAnimation>
13
+ #include <functional>
14
+
15
+ namespace C { // palette
16
+ inline const QColor bg{0x0d111c}, panel{0x161c2b}, card{0x1a2133}, cardHover{0x20293f}, border{0x27314a}, grid{0x242d42},
17
+ text{0xe6ebf5}, muted{0x8b95ab}, faint{0x5a657d}, accent{0x38bdf8}, green{0x22c55e}, amber{0xf59e0b}, red{0xef4444},
18
+ violet{0xa78bfa}, pink{0xf472b6}, teal{0x2dd4bf}, orange{0xfb923c}, blue{0x60a5fa};
19
+ QColor level(double pct, double warn = 70, double crit = 90); // green / amber / red
20
+ QColor severity(const QString &s);
21
+ QColor health(int h);
22
+ QColor mix(const QColor &a, const QColor &b, double t);
23
+ inline QColor tint(QColor c, int alpha) { return c.setAlpha(alpha), c; }
24
+ QString styleSheet();
25
+ QIcon appIcon();
26
+ QString mono();
27
+ }
28
+
29
+ using FmtFn = std::function<QString(double)>;
30
+ inline const FmtFn pctFmt = [](double v) { return QString::number(v, 'f', 0) + "%"; }, rateFmt = Fmt::rate;
31
+ inline FmtFn numFmt(int prec) { return [prec](double v) { return QString::number(v, 'f', prec); }; }
32
+
33
+ struct AA : QPainter { // antialiased painter
34
+ explicit AA(QPaintDevice *d) : QPainter(d) { setRenderHint(Antialiasing); }
35
+ };
36
+ QFont pxFont(QFont f, int px, bool bold = false);
37
+ void paintRing(QPainter &p, const QRectF &r, double pct, const QColor &c, double thick, bool glow = true); // 270° arc
38
+
39
+ struct RingGauge : QWidget {
40
+ explicit RingGauge(const QString &title);
41
+ void setValue(double pct, const QString &center = {}, const QString &sub = {}, const QColor &color = {});
42
+ double warn = 70, crit = 90;
43
+ QSize sizeHint() const override { return {170, 190}; }
44
+ void paintEvent(QPaintEvent *) override;
45
+ QString m_title, m_center, m_sub;
46
+ QColor m_color;
47
+ double m_target = 0, m_shown = 0;
48
+ QVariantAnimation m_anim;
49
+ };
50
+
51
+ struct Series { QString name; QColor color; QVector<double> v; bool fill = true, dashed = false; };
52
+ struct TimeChart : QWidget {
53
+ explicit TimeChart(const QString &title, FmtFn fmt = pctFmt, double yMax = 0); // yMax 0 = auto
54
+ void setData(const QVector<qint64> &tMs, const QVector<Series> &s, qint64 spanMs = 0); // span 0 = all
55
+ QString title, subtitle, empty = "Waiting for data…";
56
+ bool stacked = false;
57
+ QSize sizeHint() const override { return {480, 230}; }
58
+ QSize minimumSizeHint() const override { return {260, 200}; }
59
+ void paintEvent(QPaintEvent *) override;
60
+ void mouseMoveEvent(QMouseEvent *) override;
61
+ void leaveEvent(QEvent *) override { m_hover = -1, update(); }
62
+ FmtFn m_fmt;
63
+ double m_yMax;
64
+ QVector<qint64> m_t;
65
+ QVector<Series> m_s;
66
+ qint64 m_span = 0;
67
+ int m_hover = -1;
68
+ };
69
+
70
+ struct Segment { double value; QColor color; QString label; };
71
+ struct SegmentBar : QWidget {
72
+ SegmentBar();
73
+ void setSegments(const QVector<Segment> &s, double total);
74
+ QSize sizeHint() const override { return {300, 58}; }
75
+ void paintEvent(QPaintEvent *) override;
76
+ QVector<Segment> m_s;
77
+ double m_total = 1;
78
+ };
79
+
80
+ struct StatTile : QFrame {
81
+ StatTile(const QString &title, const QColor &accent);
82
+ void set(const QString &value, const QString &sub = {}, const QColor &color = {});
83
+ void paintEvent(QPaintEvent *) override;
84
+ QLabel *m_value, *m_sub;
85
+ QColor m_accent;
86
+ };
87
+ // creates tiles in a grid (cols per row) from {title, colour} pairs
88
+ QVector<StatTile *> addTiles(class QGridLayout *g, const QVector<QPair<QString, QColor>> &defs, int cols = 99);
89
+
90
+ struct CoreGrid : QWidget {
91
+ CoreGrid();
92
+ void setCores(const QVector<CoreStat> &c);
93
+ bool hasHeightForWidth() const override { return true; }
94
+ int heightForWidth(int w) const override { return (qMax(1, m_c.size()) + qMax(1, w / 92) - 1) / qMax(1, w / 92) * 66; }
95
+ void paintEvent(QPaintEvent *) override;
96
+ QVector<CoreStat> m_c;
97
+ };
98
+
99
+ struct WeekHeatmap : QWidget {
100
+ WeekHeatmap();
101
+ void setData(const double v[7][24], const int n[7][24], const QString &unit, const QColor &hot);
102
+ QSize sizeHint() const override { return {560, 230}; }
103
+ void paintEvent(QPaintEvent *) override;
104
+ void mouseMoveEvent(QMouseEvent *) override;
105
+ QRectF cell(int d, int h) const;
106
+ double m_v[7][24];
107
+ int m_n[7][24];
108
+ QString m_unit;
109
+ QColor m_hot;
110
+ };
111
+
112
+ // table cell bar: Qt::UserRole = percent, DisplayRole = text on the bar
113
+ struct BarDelegate : QStyledItemDelegate {
114
+ using QStyledItemDelegate::QStyledItemDelegate;
115
+ void paint(QPainter *p, const QStyleOptionViewItem &o, const QModelIndex &i) const override;
116
+ };
117
+
118
+ struct FlowLayout : QLayout { // equal-width columns of cards
119
+ FlowLayout(QWidget *parent) : QLayout(parent) {}
120
+ ~FlowLayout() override { qDeleteAll(m_items); }
121
+ void addItem(QLayoutItem *i) override { m_items << i; }
122
+ int count() const override { return m_items.size(); }
123
+ QLayoutItem *itemAt(int i) const override { return m_items.value(i); }
124
+ QLayoutItem *takeAt(int i) override { return i >= 0 && i < m_items.size() ? m_items.takeAt(i) : nullptr; }
125
+ bool hasHeightForWidth() const override { return true; }
126
+ int heightForWidth(int w) const override { return place(QRect(0, 0, w, 0), false); }
127
+ void setGeometry(const QRect &r) override { QLayout::setGeometry(r), place(r, true); }
128
+ QSize sizeHint() const override { return {340, 270}; }
129
+ int place(const QRect &r, bool apply) const;
130
+ QList<QLayoutItem *> m_items;
131
+ };
132
+
133
+ // ---- small builders ----------------------------------------------------------------
134
+ QLabel *label(const QString &text, const char *objectName = nullptr, bool wrap = false);
135
+ QPushButton *button(const QString &text, const char *style = nullptr, std::function<void()> onClick = {});
136
+ QFrame *panel(const QString &title = {}, std::initializer_list<QWidget *> content = {}); // nullptr = stretch
137
+ bool ask(QWidget *parent, const QString &title, const QString &text);
138
+
139
+ struct Cell { QString text; QColor color; bool right = false; double pct = -1; QVariant key; }; // pct = bar, key = sort value
140
+ using Row = QVector<Cell>;
141
+ QTableWidget *table(const QStringList &headers, const QVector<int> &widths = {}, const QVector<int> &barColumns = {});
142
+ void cell(QTableWidget *t, int r, int c, const Cell &x);
143
+ template <class V, class F> void fillRows(QTableWidget *t, const V &items, F rowOf) // one row per item
144
+ {
145
+ t->setRowCount(items.size());
146
+ for (int r = 0; r < items.size(); ++r) {
147
+ const Row row = rowOf(items[r]);
148
+ for (int c = 0; c < row.size(); ++c) cell(t, r, c, row[c]);
149
+ }
150
+ }
Server Monitor(cqt-linux)/src/ui/Windows.cpp ADDED
@@ -0,0 +1,614 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Main window: sidebar, dashboard with server cards, server detail page, events page, tray icon.
2
+ #include "Windows.h"
3
+ #include "Widgets.h"
4
+ #include <QApplication>
5
+ #include <QBoxLayout>
6
+ #include <QCheckBox>
7
+ #include <QCloseEvent>
8
+ #include <QComboBox>
9
+ #include <QDesktopServices>
10
+ #include <QDialogButtonBox>
11
+ #include <QEventLoop>
12
+ #include <QFileDialog>
13
+ #include <QFormLayout>
14
+ #include <QLineEdit>
15
+ #include <QListWidget>
16
+ #include <QMenu>
17
+ #include <QMessageBox>
18
+ #include <QPlainTextEdit>
19
+ #include <QScrollArea>
20
+ #include <QSettings>
21
+ #include <QSpinBox>
22
+ #include <QStackedWidget>
23
+ #include <QSystemTrayIcon>
24
+ #include <QTabWidget>
25
+ #include <QUrl>
26
+ #include <memory>
27
+
28
+ struct Actions { std::function<void(const QString &)> open, edit, remove; std::function<void()> add, back; }; // set by the main window
29
+ static QColor statusColor(Status s) { return s == Status::Online ? C::green : s == Status::Connecting ? C::amber : s == Status::Offline ? C::red : C::faint; }
30
+ static QHBoxLayout *hbox()
31
+ {
32
+ auto *h = new QHBoxLayout;
33
+ h->setSpacing(10);
34
+ return h;
35
+ }
36
+ static QVBoxLayout *page(QWidget *w, int top = 22)
37
+ {
38
+ auto *l = new QVBoxLayout(w);
39
+ w->setObjectName("Page"), l->setContentsMargins(28, top, 28, 18), l->setSpacing(14);
40
+ return l;
41
+ }
42
+
43
+ // ============================================================================ dashboard cards
44
+ struct Card : QWidget {
45
+ bool hover = false;
46
+ Card() { setCursor(Qt::PointingHandCursor), setMinimumSize(320, 262); }
47
+ QSize sizeHint() const override { return {340, 262}; }
48
+ void enterEvent(QEvent *) override { hover = true, update(); }
49
+ void leaveEvent(QEvent *) override { hover = false, update(); }
50
+ };
51
+
52
+ struct ServerCard : Card {
53
+ ServerSession *s;
54
+ const Actions *act;
55
+ ServerCard(ServerSession *x, const Actions *a) : s(x), act(a)
56
+ {
57
+ connect(x, &ServerSession::updated, this, QOverload<>::of(&QWidget::update));
58
+ connect(x, &ServerSession::analysisUpdated, this, QOverload<>::of(&QWidget::update));
59
+ }
60
+ void mouseReleaseEvent(QMouseEvent *e) override { if (e->button() == Qt::LeftButton) act->open(s->config().id); }
61
+ void contextMenuEvent(QContextMenuEvent *e) override
62
+ {
63
+ const QString id = s->config().id;
64
+ QMenu m;
65
+ m.addAction("Open details", [=] { act->open(id); }), m.addAction("Reconnect", s, &ServerSession::reconnect), m.addSeparator();
66
+ m.addAction("Edit…", [=] { act->edit(id); }), m.addAction("Remove…", [=] { act->remove(id); });
67
+ m.exec(e->globalPos());
68
+ }
69
+ void paintEvent(QPaintEvent *) override
70
+ {
71
+ AA p(this);
72
+ const ServerConfig &c = s->config();
73
+ const Metrics &m = s->metrics();
74
+ const Analysis &an = s->analysis();
75
+ const bool live = s->online();
76
+ const QColor sc = statusColor(s->status()), muted = live ? C::text : C::faint;
77
+ QLinearGradient bg(0, 0, 0, height()), strip(0, 0, width(), 0);
78
+ bg.setColorAt(0, hover ? C::cardHover : C::card), bg.setColorAt(1, C::panel);
79
+ strip.setColorAt(0, sc), strip.setColorAt(.6, C::tint(sc, 0));
80
+ p.setPen(QPen(hover ? C::accent : C::border, hover ? 1.5 : 1)), p.setBrush(bg), p.drawRoundedRect(QRectF(rect()).adjusted(1, 1, -1, -1), 14, 14);
81
+ p.setPen(Qt::NoPen), p.setBrush(strip), p.drawRoundedRect(QRectF(1, 1, width() - 2, 6), 3, 3);
82
+ p.setBrush(sc), p.drawEllipse(QPointF(22, 28), 5, 5);
83
+ p.setFont(pxFont(font(), 16, true)), p.setPen(C::text);
84
+ p.drawText(QRectF(36, 16, width() - 120, 24), Qt::AlignVCenter, p.fontMetrics().elidedText(c.name, Qt::ElideRight, width() - 120));
85
+ p.setFont(pxFont(font(), 11)), p.setPen(C::muted);
86
+ p.drawText(QRectF(36, 38, width() - 60, 16), Qt::AlignVCenter, p.fontMetrics().elidedText(c.address() + (m.os.isEmpty() ? "" : " · " + m.os), Qt::ElideRight, width() - 60));
87
+ if (live) { // health badge
88
+ const QRectF hb(width() - 62, 12, 44, 44);
89
+ paintRing(p, hb, an.health, C::health(an.health), 4, false);
90
+ p.setFont(pxFont(font(), 15, true)), p.setPen(C::health(an.health)), p.drawText(hb, Qt::AlignCenter, an.grade);
91
+ } else {
92
+ p.setFont(pxFont(font(), 10, true));
93
+ const QString chip = statusName(s->status()).toUpper();
94
+ const QRectF cr(width() - p.fontMetrics().horizontalAdvance(chip) - 34, 18, p.fontMetrics().horizontalAdvance(chip) + 18, 20);
95
+ p.setPen(sc), p.setBrush(C::tint(sc, 40)), p.drawRoundedRect(cr, 10, 10), p.drawText(cr, Qt::AlignCenter, chip);
96
+ }
97
+ const bool temp = !m.temps.isEmpty(); // four gauges
98
+ const double vals[4] = {m.cpuUsage, m.memPct, m.maxDiskPct, temp ? m.maxTemp : m.swapPct}, gw = (width() - 32) / 4.0, gs = qMin(gw - 14, 70.0);
99
+ const char *names[4] = {"CPU", "Memory", "Disk", temp ? "Temp" : "Swap"};
100
+ for (int i = 0; i < 4; ++i) {
101
+ const double cx = 16 + gw * i + gw / 2;
102
+ const QRectF r(cx - gs / 2, 66, gs, gs);
103
+ paintRing(p, r, live ? qMin(100.0, vals[i]) : 0, live ? (i == 3 && temp ? C::level(vals[i], 70, 85) : C::level(vals[i])) : C::faint, 6, live);
104
+ p.setFont(pxFont(font(), 14, true)), p.setPen(muted);
105
+ p.drawText(r, Qt::AlignCenter, !live ? "—" : i == 3 && temp ? QString::number(vals[i], 'f', 0) + "°" : QString::number(vals[i], 'f', 0) + "%");
106
+ p.setFont(pxFont(font(), 11)), p.setPen(C::muted), p.drawText(QRectF(cx - gw / 2, r.bottom() - 4, gw, 16), Qt::AlignCenter, names[i]);
107
+ }
108
+ const QRectF sp(16, 166, width() - 32, 44); // CPU + memory sparkline (last 5 min)
109
+ p.setPen(Qt::NoPen), p.setBrush(QColor(0, 0, 0, 40)), p.drawRoundedRect(sp, 8, 8);
110
+ for (auto [series, color] : {std::pair{Live::MEM, C::violet}, {Live::CPU, C::accent}}) {
111
+ const QVector<double> &v = s->live().s[series];
112
+ const int n = qMin(150, v.size());
113
+ if (n < 2) continue;
114
+ QPolygonF line;
115
+ for (int i = 0; i < n; ++i) line << QPointF(sp.right() - 4 - (sp.width() - 8) * (n - 1 - i) / 149.0, sp.bottom() - 4 - qBound(0.0, v[v.size() - n + i], 100.0) / 100 * (sp.height() - 8));
116
+ QPolygonF area = line;
117
+ area << QPointF(line.last().x(), sp.bottom() - 2) << QPointF(line.first().x(), sp.bottom() - 2);
118
+ p.setPen(Qt::NoPen), p.setBrush(C::tint(color, 40)), p.drawPolygon(area);
119
+ p.setPen(QPen(color, 1.5)), p.setBrush(Qt::NoBrush), p.drawPolyline(line);
120
+ }
121
+ p.setFont(pxFont(font(), 10)), p.setPen(C::accent), p.drawText(sp.adjusted(8, 3, 0, 0), Qt::AlignLeft, "CPU");
122
+ p.setPen(C::violet), p.drawText(sp.adjusted(36, 3, 0, 0), Qt::AlignLeft, "MEM");
123
+ p.setFont(pxFont(font(), 11));
124
+ const QRectF ft(16, 218, width() - 32, 32);
125
+ if (!live) {
126
+ p.setPen(s->status() == Status::Offline ? C::red : C::muted);
127
+ return p.drawText(ft, Qt::AlignVCenter | Qt::TextWordWrap, s->status() == Status::Disabled ? "Monitoring disabled" : s->status() == Status::Offline ? "Unreachable: " + s->lastError() : "Waiting for data…");
128
+ }
129
+ p.setPen(C::teal), p.drawText(ft, Qt::AlignLeft, "↓ " + Fmt::rate(m.netRxBps));
130
+ p.setPen(C::pink), p.drawText(ft.adjusted(100, 0, 0, 0), Qt::AlignLeft, "↑ " + Fmt::rate(m.netTxBps));
131
+ p.setPen(C::muted), p.drawText(ft, Qt::AlignRight, QString("load %1 · up %2").arg(m.load1, 0, 'f', 2).arg(Fmt::duration(m.uptime)));
132
+ p.drawText(ft.adjusted(0, 16, 0, 0), Qt::AlignLeft, QString("%1 cores · %2 procs").arg(m.cpuCount).arg(m.procs.size()) + (c.autopilot.enabled ? c.autopilot.dryRun ? " · autopilot (dry run)" : " · autopilot on" : ""));
133
+ const int rules = s->activeAlerts().size(), alerts = rules + an.findings.size();
134
+ if (!alerts) return;
135
+ bool crit = rules;
136
+ for (const Finding &f : an.findings) crit |= f.severity == "critical";
137
+ const QString txt = QString("⚠ %1").arg(alerts);
138
+ const QColor ac = crit ? C::red : C::amber;
139
+ const QRectF ar(ft.right() - p.fontMetrics().horizontalAdvance(txt) - 14, ft.top() + 15, p.fontMetrics().horizontalAdvance(txt) + 14, 17);
140
+ p.setPen(Qt::NoPen), p.setBrush(C::tint(ac, 45)), p.drawRoundedRect(ar, 8, 8), p.setPen(ac), p.drawText(ar, Qt::AlignCenter, txt);
141
+ }
142
+ };
143
+
144
+ struct AddCard : Card {
145
+ const Actions *act;
146
+ explicit AddCard(const Actions *a) : act(a) {}
147
+ void mouseReleaseEvent(QMouseEvent *) override { act->add(); }
148
+ void paintEvent(QPaintEvent *) override
149
+ {
150
+ AA p(this);
151
+ const QRectF r = QRectF(rect()).adjusted(2, 2, -2, -2);
152
+ const QPointF c = r.center() - QPointF(0, 14);
153
+ p.setPen(QPen(hover ? C::accent : C::border, 1.5, Qt::DashLine)), p.setBrush(hover ? C::tint(C::accent, 18) : Qt::transparent), p.drawRoundedRect(r, 14, 14);
154
+ p.setPen(QPen(hover ? C::accent : C::muted, 3, Qt::SolidLine, Qt::RoundCap));
155
+ p.drawLine(c - QPointF(14, 0), c + QPointF(14, 0)), p.drawLine(c - QPointF(0, 14), c + QPointF(0, 14));
156
+ p.setFont(pxFont(font(), 14, true)), p.drawText(QRectF(r.left(), c.y() + 26, r.width(), 22), Qt::AlignCenter, "Add server");
157
+ p.setFont(pxFont(font(), 11)), p.setPen(C::faint), p.drawText(QRectF(r.left(), c.y() + 48, r.width(), 18), Qt::AlignCenter, "This machine · SSH");
158
+ }
159
+ };
160
+
161
+ // ============================================================================ dashboard
162
+ struct DashboardPage : QWidget {
163
+ ServerManager *mgr;
164
+ const Actions *act;
165
+ FlowLayout *flow = new FlowLayout(new QWidget);
166
+ QList<ServerCard *> cards;
167
+ AddCard *addCard;
168
+ QLineEdit *search = new QLineEdit;
169
+ QLabel *subtitle = label({}, "Muted");
170
+ QVector<StatTile *> t;
171
+ QListWidget *events = new QListWidget;
172
+
173
+ DashboardPage(ServerManager *m, const Actions *a) : mgr(m), act(a), addCard(new AddCard(a))
174
+ {
175
+ auto *l = page(this);
176
+ auto *head = hbox(), *body = hbox();
177
+ auto *titles = new QVBoxLayout;
178
+ auto *g = new QGridLayout;
179
+ auto *scroll = new QScrollArea;
180
+ auto *ev = panel("Recent events", {events});
181
+ titles->addWidget(label("Dashboard", "H1")), titles->addWidget(subtitle);
182
+ search->setPlaceholderText("Search servers…"), search->setClearButtonEnabled(true), search->setFixedWidth(240);
183
+ head->addLayout(titles), head->addStretch(), head->addWidget(search), head->addWidget(button("+ Add server", "Primary", [this] { act->add(); }));
184
+ t = addTiles(g, {{"Servers online", C::green}, {"Avg health", C::teal}, {"Active problems", C::red}, {"Avg CPU", C::accent}, {"Avg memory", C::violet}, {"Total network", C::pink}});
185
+ scroll->setWidgetResizable(true), scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff), scroll->setWidget(flow->parentWidget());
186
+ events->setStyleSheet("QListWidget { background: transparent; border: none; } QListWidget::item { padding: 6px 2px; border-bottom: 1px solid #1f2738; }");
187
+ events->setWordWrap(true), events->setSelectionMode(QAbstractItemView::NoSelection), ev->setFixedWidth(330);
188
+ body->addWidget(scroll, 1), body->addWidget(ev);
189
+ l->addLayout(head), l->addLayout(g), l->addLayout(body, 1);
190
+ connect(search, &QLineEdit::textChanged, this, [this] { filter(); });
191
+ connect(mgr, &ServerManager::listChanged, this, [this] { rebuild(); });
192
+ connect(mgr, &ServerManager::alertsCleared, events, &QListWidget::clear);
193
+ connect(mgr, &ServerManager::alertRaised, this, [this](const AlertEvent &e) {
194
+ events->insertItem(0, e.time.toString("HH:mm:ss") + " · " + e.serverName + "\n" + e.message);
195
+ events->item(0)->setForeground(C::severity(e.severity));
196
+ if (events->count() > 200) delete events->takeItem(200);
197
+ });
198
+ }
199
+ void rebuild()
200
+ {
201
+ for (ServerCard *c : qAsConst(cards)) c->hide(), c->deleteLater(); // not deleted at once: a card's own menu may have caused this
202
+ cards.clear(), flow->removeWidget(addCard);
203
+ for (ServerSession *s : mgr->sessions()) cards << new ServerCard(s, act), flow->addWidget(cards.last());
204
+ flow->addWidget(addCard), filter(), refresh();
205
+ }
206
+ void filter()
207
+ {
208
+ for (ServerCard *c : qAsConst(cards))
209
+ c->setVisible(QStringList{c->s->config().name, c->s->config().host, c->s->config().group, c->s->metrics().hostname}.join(' ').contains(search->text(), Qt::CaseInsensitive));
210
+ flow->invalidate();
211
+ }
212
+ void refresh()
213
+ {
214
+ int online = 0, total = 0, problems = 0;
215
+ double cpu = 0, mem = 0, rx = 0, tx = 0, health = 0;
216
+ for (ServerSession *s : mgr->sessions()) {
217
+ if (!s->config().enabled) continue;
218
+ ++total, problems += s->activeAlerts().size();
219
+ if (!s->online()) continue;
220
+ const Metrics &m = s->metrics();
221
+ ++online, cpu += m.cpuUsage, mem += m.memPct, rx += m.netRxBps, tx += m.netTxBps, health += s->analysis().health;
222
+ for (const Finding &f : s->analysis().findings) problems += f.severity != "info";
223
+ }
224
+ subtitle->setText(QString("%1 server(s) monitored · updated %2").arg(mgr->sessions().size()).arg(QTime::currentTime().toString("HH:mm:ss")));
225
+ t[0]->set(QString("%1 / %2").arg(online).arg(total), total > online ? QString("%1 unreachable").arg(total - online) : "all reachable", online == total ? C::green : C::amber);
226
+ t[2]->set(QString::number(problems), problems ? "alerts + insights" : "all clear", problems ? C::red : C::green);
227
+ if (!online) {
228
+ for (int i : {1, 3, 4, 5}) t[i]->set("—");
229
+ return;
230
+ }
231
+ t[1]->set(QString::number(qRound(health / online)), "score 0–100", C::health(qRound(health / online)));
232
+ t[3]->set(Fmt::pct(cpu / online), {}, C::level(cpu / online)), t[4]->set(Fmt::pct(mem / online), {}, C::level(mem / online));
233
+ t[5]->set(Fmt::rate(rx + tx), "↓ " + Fmt::rate(rx) + " ↑ " + Fmt::rate(tx));
234
+ }
235
+ };
236
+
237
+ // ============================================================================ detail page
238
+ struct DetailPage : QWidget {
239
+ ServerManager *mgr;
240
+ const Actions *act;
241
+ QPointer<ServerSession> s;
242
+ QTabWidget *tabs = new QTabWidget;
243
+ QLabel *name = label({}, "H1"), *state = new QLabel, *sub = label({}, "Muted"), *chips = label({}, nullptr, true);
244
+ QPushButton *pause = button("❚❚ Pause", nullptr, [this] { s->setPaused(!s->isPaused()); });
245
+ QComboBox *span = new QComboBox;
246
+ QList<QMetaObject::Connection> conns;
247
+
248
+ DetailPage(ServerManager *m, const Actions *a) : mgr(m), act(a)
249
+ {
250
+ auto *l = page(this, 18);
251
+ auto *head = hbox(), *nameRow = hbox();
252
+ auto *titles = new QVBoxLayout, *spanBox = new QVBoxLayout;
253
+ auto *power = button("⏻ Power", "Danger");
254
+ auto *pm = new QMenu(power);
255
+ nameRow->addWidget(name), nameRow->addWidget(state), nameRow->addStretch();
256
+ titles->addWidget(button("‹ Dashboard", "Flat", [this] { act->back(); }), 0, Qt::AlignLeft), titles->addLayout(nameRow), titles->addWidget(sub), titles->addWidget(chips);
257
+ for (auto [t, min] : {std::pair{"Last 5 minutes", 5}, {"Last 15 minutes", 15}, {"Last 30 minutes", 30}, {"Last hour", 60}}) span->addItem(t, min);
258
+ span->setCurrentIndex(1), spanBox->addWidget(label("LIVE WINDOW", "Section")), spanBox->addWidget(span);
259
+ for (bool reboot : {true, false}) {
260
+ const QString t = reboot ? "Reboot…" : "Shut down…";
261
+ pm->addAction(t, this, [this, t, reboot] {
262
+ if (QMessageBox::warning(this, t, QString("%1 %2 now?").arg(t.chopped(1), s->config().name), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) s->exec(P::power(reboot), true);
263
+ });
264
+ }
265
+ pm->addSeparator(), pm->addAction("Remove from monitor…", this, [this] { act->remove(s->config().id); }), power->setMenu(pm);
266
+ head->addLayout(titles, 1), head->addLayout(spanBox);
267
+ for (auto *b : {button("⟳ Reconnect", nullptr, [this] { s->reconnect(); }), pause, button("Edit", nullptr, [this] { act->edit(s->config().id); }), power}) head->addWidget(b, 0, Qt::AlignBottom);
268
+ tabs->setDocumentMode(true), tabs->tabBar()->setElideMode(Qt::ElideNone), tabs->tabBar()->setExpanding(false);
269
+ tabs->tabBar()->setFont(pxFont(tabs->tabBar()->font(), 13, true));
270
+ for (const auto &[title, w] : makeTabs()) w->save = [this](const ServerConfig &c) { mgr->update(c); }, tabs->addTab(w, title);
271
+ l->setSpacing(6), l->addLayout(head), l->addWidget(tabs, 1);
272
+ connect(tabs, &QTabWidget::currentChanged, this, [this] { refreshTab(true); });
273
+ connect(span, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this] { refreshTab(false); });
274
+ }
275
+ Tab *tab(int i) const { return static_cast<Tab *>(tabs->widget(i)); }
276
+ void refreshTab(bool withAnalysis)
277
+ {
278
+ Tab *t = tab(tabs->currentIndex());
279
+ if (!s) return;
280
+ t->span = span->currentData().toInt() * 60000LL, t->refresh();
281
+ if (withAnalysis) t->analysis();
282
+ }
283
+ void bind(ServerSession *x)
284
+ {
285
+ for (const auto &c : qAsConst(conns)) disconnect(c);
286
+ conns.clear(), s = x;
287
+ for (int i = 0; i < tabs->count(); ++i) tab(i)->bind(x);
288
+ if (!x) return;
289
+ conns << connect(x, &ServerSession::updated, this, [this] { header(), refreshTab(false); })
290
+ << connect(x, &ServerSession::analysisUpdated, this, [this] { header(), tab(tabs->currentIndex())->analysis(); });
291
+ header(), refreshTab(true);
292
+ }
293
+ void header()
294
+ {
295
+ const ServerConfig &c = s->config();
296
+ const Metrics &m = s->metrics();
297
+ const Analysis &a = s->analysis();
298
+ QString h;
299
+ auto chip = [&](const QString &t, const QString &color = "#b9c3d8") {
300
+ if (!t.trimmed().isEmpty()) h += QString("<span style='background:#1f2a40; color:%2; white-space:nowrap;'>&nbsp;&nbsp;%1&nbsp;&nbsp;</span>&nbsp; ").arg(t.toHtmlEscaped().replace(" ", "&nbsp;").replace("-", "&#8209;"), color);
301
+ };
302
+ name->setText(c.name);
303
+ state->setText(" ● " + (s->isPaused() ? QString("Paused") : statusName(s->status())).toUpper());
304
+ state->setStyleSheet(QString("color: %1; font-weight: 700; font-size: 12px;").arg((s->isPaused() ? C::amber : statusColor(s->status())).name()));
305
+ sub->setText(c.address() + " · " + transportName(c.transport) + (m.hostname.isEmpty() ? "" : " · host " + m.hostname) +
306
+ (s->online() ? " · up " + Fmt::duration(m.uptime) : s->status() == Status::Offline ? " · " + s->lastError() : ""));
307
+ chip(m.os), chip(m.kernel.isEmpty() ? "" : P::kernelPrefix + m.kernel), chip(m.cpuCount ? QString("%1 cores").arg(m.cpuCount) : "");
308
+ chip(m.memTotal > 0 ? Fmt::bytes(m.memTotal) + " RAM" : ""), chip(c.group, "#7dd3fc");
309
+ if (s->online()) chip(QString("health %1 (%2)").arg(a.health).arg(a.grade), C::health(a.health).name());
310
+ if (c.autopilot.enabled) chip(c.autopilot.dryRun ? "autopilot: dry run" : "autopilot: on", "#a78bfa");
311
+ chips->setText(h), pause->setText(s->isPaused() ? "▶ Resume" : "❚❚ Pause");
312
+ }
313
+ };
314
+
315
+ // ============================================================================ add / edit dialog
316
+ static bool editServer(QWidget *parent, ServerConfig &cfg, const QStringList &groups)
317
+ {
318
+ QDialog dlg(parent);
319
+ dlg.setWindowTitle(cfg.name.isEmpty() ? "Add server" : "Edit server — " + cfg.name);
320
+ dlg.setMinimumWidth(620);
321
+ auto *l = new QVBoxLayout(&dlg);
322
+ l->setContentsMargins(24, 20, 24, 20), l->setSpacing(14);
323
+ l->addWidget(label(cfg.name.isEmpty() ? "Add a server" : "Edit server", "H2"));
324
+ auto *f = new QFormLayout;
325
+ auto *name = new QLineEdit(cfg.name), *host = new QLineEdit(cfg.host), *user = new QLineEdit(cfg.user), *key = new QLineEdit(cfg.keyFile), *pass = new QLineEdit(cfg.password);
326
+ auto *group = new QComboBox, *via = new QComboBox;
327
+ auto *port = new QSpinBox, *interval = new QSpinBox;
328
+ auto *sudo = new QCheckBox("Run control commands with sudo -n (needs passwordless sudo)"), *enabled = new QCheckBox("Monitoring enabled");
329
+ auto *notes = new QPlainTextEdit(cfg.notes);
330
+ auto *browse = button("Browse…", nullptr, [&] {
331
+ const QString fn = QFileDialog::getOpenFileName(&dlg, "Private key", QDir::homePath() + "/.ssh");
332
+ if (!fn.isEmpty()) key->setText(fn);
333
+ });
334
+ auto *test = button("Test connection");
335
+ auto *hint = label({}, "Muted", true), *result = label({}, nullptr, true);
336
+ group->setEditable(true), group->addItems(groups), group->setCurrentText(cfg.group);
337
+ via->addItems({"This machine (local)", "SSH — nothing to install on the server"}), via->setCurrentIndex(int(cfg.transport));
338
+ port->setRange(1, 65535), port->setValue(cfg.port), port->setPrefix("port ");
339
+ interval->setRange(1, 300), interval->setValue(cfg.interval), interval->setSuffix(" s");
340
+ pass->setEchoMode(QLineEdit::Password), sudo->setChecked(cfg.useSudo), enabled->setChecked(cfg.enabled), notes->setMaximumHeight(70);
341
+ name->setPlaceholderText("e.g. web-01"), host->setPlaceholderText("hostname or IP address"), user->setPlaceholderText("default: your local user name");
342
+ key->setPlaceholderText("default keys / ssh-agent (~/.ssh/id_*)"), pass->setPlaceholderText("optional — keys are recommended");
343
+ auto *addr = hbox(), *keyRow = hbox(), *testRow = hbox();
344
+ addr->addWidget(host, 1), addr->addWidget(port), keyRow->addWidget(key, 1), keyRow->addWidget(browse), testRow->addWidget(test), testRow->addWidget(result, 1);
345
+ f->addRow("Name", name), f->addRow("Group", group), f->addRow("Connect via", via), f->addRow("Address", addr), f->addRow("User", user);
346
+ f->addRow("Private key", keyRow), f->addRow("Password", pass), f->addRow("Sample every", interval), f->addRow("", enabled), f->addRow("Notes", notes);
347
+ P::sudo ? f->insertRow(8, "", sudo) : (sudo->setParent(&dlg), sudo->hide());
348
+ auto *bb = new QDialogButtonBox(QDialogButtonBox::Save | QDialogButtonBox::Cancel);
349
+ l->addLayout(f), l->addWidget(hint), l->addLayout(testRow), l->addWidget(bb);
350
+ auto collect = [&] {
351
+ ServerConfig c = cfg;
352
+ c.name = name->text().trimmed(), c.group = group->currentText().trimmed(), c.transport = Transport(via->currentIndex());
353
+ c.host = c.transport == Transport::Local ? "" : host->text().trimmed(), c.port = port->value(), c.user = user->text().trimmed();
354
+ c.keyFile = key->text().trimmed(), c.password = pass->text(), c.interval = interval->value(), c.useSudo = sudo->isChecked();
355
+ c.enabled = enabled->isChecked(), c.notes = notes->toPlainText();
356
+ return c;
357
+ };
358
+ auto show = [&](const QString &text, const QColor &c) { result->setText(text), result->setStyleSheet("color: " + c.name() + ";"); };
359
+ auto sync = [&] {
360
+ const bool ssh = via->currentIndex() == 1;
361
+ for (QWidget *w : std::initializer_list<QWidget *>{host, port, user, key, browse, pass}) w->setEnabled(ssh);
362
+ hint->setText(ssh ? P::sshHint : "Monitors the computer this program runs on. No setup needed.");
363
+ if (!ssh && name->text().isEmpty()) name->setText("This computer");
364
+ };
365
+ QObject::connect(via, QOverload<int>::of(&QComboBox::currentIndexChanged), &dlg, sync);
366
+ QObject::connect(bb, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
367
+ QObject::connect(bb, &QDialogButtonBox::accepted, &dlg, [&] {
368
+ const ServerConfig c = collect();
369
+ if (c.name.isEmpty() || (c.transport == Transport::SSH && c.host.isEmpty())) return show("Please enter a name and an address.", C::red);
370
+ dlg.accept();
371
+ });
372
+ QPointer<Link> link;
373
+ QObject::connect(test, &QPushButton::clicked, &dlg, [&] { // two frames prove that data and rates work
374
+ ServerConfig c = collect();
375
+ c.interval = 1;
376
+ delete link;
377
+ link = new Link(c, &dlg);
378
+ auto engine = std::make_shared<MetricsEngine>();
379
+ auto clock = std::make_shared<QElapsedTimer>();
380
+ auto frames = std::make_shared<int>(0);
381
+ clock->start(), test->setEnabled(false), show("Connecting…", C::amber);
382
+ auto finish = [&, l = link.data()](const QString &msg, const QColor &col) { show(msg, col), test->setEnabled(true), l->disconnect(), l->deleteLater(); };
383
+ QObject::connect(link, &Link::snapshot, &dlg, [=](const QByteArray &raw) {
384
+ const Metrics m = engine->process(raw, QDateTime::currentMSecsSinceEpoch());
385
+ if (++*frames == 2)
386
+ finish(QString("✓ Connected in %1 ms — %2 · %3 · %4 cores · %5 RAM · CPU %6").arg(clock->elapsed()).arg(m.hostname, m.os).arg(m.cpuCount).arg(Fmt::bytes(m.memTotal), Fmt::pct(m.cpuUsage, 0)), C::green);
387
+ });
388
+ QObject::connect(link, &Link::disconnected, &dlg, [=](const QString &why) { finish("✗ " + why, C::red); });
389
+ QTimer::singleShot(20000, link, [=] { finish("✗ Timed out after 20 s", C::red); });
390
+ link->start();
391
+ });
392
+ sync();
393
+ if (dlg.exec() != QDialog::Accepted) return false;
394
+ cfg = collect();
395
+ return true;
396
+ }
397
+
398
+ // ============================================================================ main window
399
+ struct MainWindow::Ui {
400
+ ServerManager *mgr;
401
+ Actions act;
402
+ QStackedWidget *stack = new QStackedWidget;
403
+ DashboardPage *dash = new DashboardPage(mgr, &act);
404
+ DetailPage *detail = new DetailPage(mgr, &act);
405
+ QWidget *eventsPage = new QWidget;
406
+ QTableWidget *events = table({"Time", "Server", "Type", "Message"}, {170, 180, 100});
407
+ QComboBox *eventFilter = new QComboBox;
408
+ QListWidget *list = new QListWidget;
409
+ QPushButton *navDash = button("▦ Dashboard", "Nav"), *navEvents = button("◉ Events && alerts", "Nav");
410
+ QLabel *badge = new QLabel;
411
+ QSystemTrayIcon *tray = nullptr;
412
+ int unseen = 0;
413
+ bool quitting = false;
414
+ };
415
+
416
+ struct ServerItemDelegate : QStyledItemDelegate { // sidebar row: dot, name, alert count, mini CPU/MEM bars
417
+ ServerManager *mgr;
418
+ ServerItemDelegate(ServerManager *m, QObject *parent) : QStyledItemDelegate(parent), mgr(m) {}
419
+ QSize sizeHint(const QStyleOptionViewItem &, const QModelIndex &) const override { return {220, 58}; }
420
+ void paint(QPainter *p, const QStyleOptionViewItem &o, const QModelIndex &i) const override
421
+ {
422
+ ServerSession *s = mgr->session(i.data(Qt::UserRole).toString());
423
+ if (!s) return;
424
+ const QRectF r = QRectF(o.rect).adjusted(6, 2, -6, -2);
425
+ const Metrics &m = s->metrics();
426
+ int y = int(r.top()) + 34;
427
+ p->save();
428
+ p->setRenderHint(QPainter::Antialiasing), p->setPen(Qt::NoPen);
429
+ if (o.state & (QStyle::State_Selected | QStyle::State_MouseOver)) p->setBrush(o.state & QStyle::State_Selected ? QColor(0x17304a) : C::card), p->drawRoundedRect(r, 8, 8);
430
+ p->setBrush(statusColor(s->status())), p->drawEllipse(QPointF(r.left() + 14, r.top() + 18), 4.5, 4.5);
431
+ p->setFont(pxFont(o.font, 13, true)), p->setPen(C::text);
432
+ p->drawText(QRectF(r.left() + 26, r.top() + 8, r.width() - 70, 20), Qt::AlignVCenter, p->fontMetrics().elidedText(s->config().name, Qt::ElideRight, int(r.width() - 70)));
433
+ if (const int n = s->activeAlerts().size()) {
434
+ const QRectF b(r.right() - 26, r.top() + 10, 20, 16);
435
+ p->setFont(pxFont(o.font, 10, true)), p->setBrush(C::red), p->setPen(Qt::NoPen), p->drawRoundedRect(b, 8, 8), p->setPen(Qt::white), p->drawText(b, Qt::AlignCenter, QString::number(n));
436
+ }
437
+ for (auto [lbl, v] : {std::pair{"CPU", m.cpuUsage}, {"MEM", m.memPct}}) {
438
+ const QRectF track(r.left() + 56, y - 2, r.width() - 70, 4);
439
+ p->setFont(pxFont(o.font, 9)), p->setPen(C::faint), p->drawText(QRectF(r.left() + 26, y - 5, 30, 10), Qt::AlignVCenter, lbl);
440
+ p->setPen(Qt::NoPen), p->setBrush(C::grid), p->drawRoundedRect(track, 2, 2);
441
+ if (s->online()) p->setBrush(C::level(v)), p->drawRoundedRect(QRectF(track.left(), track.top(), track.width() * qBound(0.0, v, 100.0) / 100, 4), 2, 2);
442
+ y += 11;
443
+ }
444
+ p->restore();
445
+ }
446
+ };
447
+
448
+ MainWindow::MainWindow(ServerManager *mgr) : ui(new Ui{mgr})
449
+ {
450
+ setWindowTitle("Server Monitor"), setWindowIcon(C::appIcon()), resize(1500, 940), setMinimumSize(1100, 700);
451
+
452
+ // navigation and server actions
453
+ auto nav = [this](QWidget *pageW) {
454
+ ui->stack->setCurrentWidget(pageW);
455
+ ui->navDash->setChecked(pageW == ui->dash), ui->navEvents->setChecked(pageW == ui->eventsPage);
456
+ if (pageW != ui->detail) ui->list->clearSelection();
457
+ };
458
+ auto refreshEvents = [this] {
459
+ QVector<AlertEvent> rs;
460
+ for (const AlertEvent &e : ui->mgr->alerts())
461
+ if (!ui->eventFilter->currentIndex() || e.severity == ui->eventFilter->currentText()) rs << e;
462
+ fillRows(ui->events, rs, [](const AlertEvent &e) {
463
+ return Row{{e.time.toString("yyyy-MM-dd HH:mm:ss"), C::muted}, {e.serverName}, {e.severity.toUpper(), C::severity(e.severity)}, {e.message}};
464
+ });
465
+ };
466
+ auto showDash = [=] { nav(ui->dash), ui->dash->refresh(); };
467
+ auto showEvents = [=] { nav(ui->eventsPage), ui->unseen = 0, ui->badge->hide(), refreshEvents(); };
468
+ auto showServer = [=](const QString &id) {
469
+ if (!mgr->session(id)) return;
470
+ ui->detail->bind(mgr->session(id)), nav(ui->detail);
471
+ for (int i = 0; i < ui->list->count(); ++i)
472
+ if (ui->list->item(i)->data(Qt::UserRole) == id) ui->list->setCurrentRow(i);
473
+ };
474
+ auto groups = [mgr] {
475
+ QStringList g;
476
+ for (ServerSession *s : mgr->sessions())
477
+ if (!s->config().group.isEmpty() && !g.contains(s->config().group)) g << s->config().group;
478
+ return g;
479
+ };
480
+ auto addServer = [=] {
481
+ ServerConfig c;
482
+ c.id = ServerConfig::newId();
483
+ if (editServer(this, c, groups())) showServer(mgr->add(c)->config().id);
484
+ };
485
+ auto editSrv = [=](const QString &id) {
486
+ ServerConfig c = mgr->session(id) ? mgr->session(id)->config() : ServerConfig();
487
+ if (mgr->session(id) && editServer(this, c, groups())) mgr->update(c);
488
+ };
489
+ auto removeSrv = [=](const QString &id) {
490
+ ServerSession *s = mgr->session(id);
491
+ if (!s) return;
492
+ QMessageBox box(QMessageBox::Warning, "Remove server", QString("Stop monitoring \"%1\" and remove it from the list?").arg(s->config().name), QMessageBox::Cancel, this);
493
+ auto *withHist = box.addButton("Remove + delete history", QMessageBox::DestructiveRole), *keep = box.addButton("Remove, keep history files", QMessageBox::AcceptRole);
494
+ box.exec();
495
+ if (box.clickedButton() != withHist && box.clickedButton() != keep) return;
496
+ if (ui->detail->s == s) ui->detail->bind(nullptr), showDash();
497
+ mgr->remove(id, box.clickedButton() == withHist);
498
+ };
499
+ auto selectedId = [this] { return ui->list->currentItem() ? ui->list->currentItem()->data(Qt::UserRole).toString() : QString(); };
500
+ ui->act = {showServer, editSrv, removeSrv, addServer, showDash};
501
+
502
+ // sidebar
503
+ auto *central = new QWidget, *side = new QWidget;
504
+ auto *h = new QHBoxLayout(central);
505
+ auto *sl = new QVBoxLayout(side), *bt = new QVBoxLayout;
506
+ auto *brand = hbox(), *evRow = hbox(), *btns = hbox();
507
+ auto *logo = new QLabel, *title = label("Server Monitor");
508
+ h->setContentsMargins(0, 0, 0, 0), h->setSpacing(0), h->addWidget(side), h->addWidget(ui->stack, 1);
509
+ setCentralWidget(central);
510
+ side->setObjectName("Sidebar"), side->setFixedWidth(260);
511
+ logo->setPixmap(C::appIcon().pixmap(34, 34)), title->setStyleSheet("font-size: 16px; font-weight: 800;");
512
+ bt->setSpacing(0), bt->addWidget(title), bt->addWidget(label("monitor · analyze · control", "Muted"));
513
+ brand->addWidget(logo), brand->addLayout(bt, 1);
514
+ ui->badge->setStyleSheet("background: #ef4444; color: white; border-radius: 9px; padding: 1px 7px; font-size: 11px; font-weight: 700;"), ui->badge->hide();
515
+ evRow->addWidget(ui->navEvents, 1), evRow->addWidget(ui->badge);
516
+ ui->navDash->setCheckable(true), ui->navEvents->setCheckable(true);
517
+ ui->list->setStyleSheet("QListWidget { background: transparent; border: none; }");
518
+ ui->list->setItemDelegate(new ServerItemDelegate(mgr, ui->list)), ui->list->setMouseTracking(true), ui->list->setContextMenuPolicy(Qt::CustomContextMenu);
519
+ btns->setSpacing(6), btns->addWidget(button("+ Add", "Primary", addServer), 1);
520
+ btns->addWidget(button("Edit", nullptr, [=] { editSrv(selectedId()); }), 1), btns->addWidget(button("Remove", "Danger", [=] { removeSrv(selectedId()); }), 1);
521
+ sl->setContentsMargins(12, 18, 12, 14), sl->setSpacing(6);
522
+ sl->addLayout(brand), sl->addSpacing(14), sl->addWidget(ui->navDash), sl->addLayout(evRow), sl->addSpacing(12);
523
+ sl->addWidget(label(" SERVERS", "Section")), sl->addWidget(ui->list, 1), sl->addLayout(btns);
524
+
525
+ // events page
526
+ auto *el = page(ui->eventsPage);
527
+ auto *eh = hbox();
528
+ auto *et = new QVBoxLayout;
529
+ et->addWidget(label("Events & alerts", "H1"));
530
+ et->addWidget(label("Alerts, recoveries, insights and every automatic or manual action, newest first. Also written to alerts.log.", "Muted"));
531
+ ui->eventFilter->addItems({"All events", "critical", "warning", "info", "resolved", "action"});
532
+ eh->addLayout(et, 1), eh->addWidget(ui->eventFilter);
533
+ eh->addWidget(button("Open log folder", nullptr, [] { QDesktopServices::openUrl(QUrl::fromLocalFile(ServerManager::configDir())); }));
534
+ eh->addWidget(button("Clear list", nullptr, [mgr] { mgr->clearAlerts(); }));
535
+ el->addLayout(eh), el->addWidget(ui->events, 1);
536
+ for (QWidget *w : std::initializer_list<QWidget *>{ui->dash, ui->detail, ui->eventsPage}) ui->stack->addWidget(w);
537
+
538
+ connect(ui->navDash, &QPushButton::clicked, this, showDash);
539
+ connect(ui->navEvents, &QPushButton::clicked, this, showEvents);
540
+ connect(ui->list, &QListWidget::itemClicked, this, [=](QListWidgetItem *it) { showServer(it->data(Qt::UserRole).toString()); });
541
+ connect(ui->list, &QWidget::customContextMenuRequested, this, [=](const QPoint &pos) {
542
+ QListWidgetItem *it = ui->list->itemAt(pos);
543
+ if (!it) return;
544
+ const QString id = it->data(Qt::UserRole).toString();
545
+ QMenu m;
546
+ m.addAction("Open", [=] { showServer(id); }), m.addAction("Reconnect", [=] { mgr->session(id)->reconnect(); }), m.addSeparator();
547
+ m.addAction("Move up", [=] { mgr->move(id, -1); }), m.addAction("Move down", [=] { mgr->move(id, 1); }), m.addSeparator();
548
+ m.addAction("Edit…", [=] { editSrv(id); }), m.addAction("Remove…", [=] { removeSrv(id); });
549
+ m.exec(ui->list->viewport()->mapToGlobal(pos));
550
+ });
551
+ connect(ui->eventFilter, QOverload<int>::of(&QComboBox::currentIndexChanged), this, refreshEvents);
552
+ connect(mgr, &ServerManager::alertsCleared, this, refreshEvents);
553
+ connect(mgr, &ServerManager::listChanged, this, [=] {
554
+ const QString cur = selectedId();
555
+ ui->list->clear();
556
+ for (ServerSession *s : mgr->sessions()) {
557
+ auto *it = new QListWidgetItem(s->config().name, ui->list);
558
+ it->setData(Qt::UserRole, s->config().id);
559
+ if (s->config().id == cur) ui->list->setCurrentItem(it);
560
+ }
561
+ });
562
+ connect(mgr, &ServerManager::alertRaised, this, [=](const AlertEvent &e) {
563
+ const bool important = e.severity == "critical" || e.severity == "warning" || e.severity == "action";
564
+ if (ui->stack->currentWidget() == ui->eventsPage) refreshEvents();
565
+ else if (important) ui->badge->setText(QString::number(++ui->unseen)), ui->badge->show();
566
+ if (ui->tray && important && QSettings().value("notify", true).toBool())
567
+ ui->tray->showMessage(e.serverName + " — " + e.severity, e.message, e.severity == "critical" ? QSystemTrayIcon::Critical : e.severity == "warning" ? QSystemTrayIcon::Warning : QSystemTrayIcon::Information, 8000);
568
+ });
569
+ auto *tick = new QTimer(this); // sidebar bars + dashboard tiles
570
+ connect(tick, &QTimer::timeout, this, [this] {
571
+ ui->list->viewport()->update();
572
+ if (ui->stack->currentWidget() == ui->dash) ui->dash->refresh();
573
+ });
574
+ tick->start(1000);
575
+
576
+ if (QSystemTrayIcon::isSystemTrayAvailable()) {
577
+ ui->tray = new QSystemTrayIcon(C::appIcon(), this);
578
+ auto *menu = new QMenu(this);
579
+ menu->addAction("Show window", this, [this] { showNormal(), raise(), activateWindow(); });
580
+ for (auto [text, key] : {std::pair{"Desktop notifications", "notify"}, {"Keep running in tray when closed", "closeToTray"}}) {
581
+ QAction *a = menu->addAction(text);
582
+ a->setCheckable(true), a->setChecked(QSettings().value(key, true).toBool());
583
+ connect(a, &QAction::toggled, [k = QString(key)](bool on) { QSettings().setValue(k, on); });
584
+ }
585
+ menu->addSeparator(), menu->addAction("Quit", this, [this] { ui->quitting = true, qApp->quit(); });
586
+ ui->tray->setContextMenu(menu), ui->tray->setToolTip("Server Monitor"), ui->tray->show();
587
+ connect(ui->tray, &QSystemTrayIcon::activated, this, [this](QSystemTrayIcon::ActivationReason r) {
588
+ if (r == QSystemTrayIcon::Trigger) isVisible() && !isMinimized() ? hide() : (showNormal(), raise(), activateWindow());
589
+ });
590
+ }
591
+ restoreGeometry(QSettings().value("geometry").toByteArray());
592
+ showDash();
593
+ }
594
+
595
+ void MainWindow::closeEvent(QCloseEvent *e)
596
+ {
597
+ QSettings st;
598
+ st.setValue("geometry", saveGeometry());
599
+ if (ui->quitting || !ui->tray || !st.value("closeToTray", true).toBool()) return qApp->quit();
600
+ hide(), e->ignore();
601
+ if (!st.value("trayHintShown").toBool()) ui->tray->showMessage("Server Monitor", "Still monitoring in the background. Right-click the tray icon to quit."), st.setValue("trayHintShown", true);
602
+ }
603
+
604
+ void MainWindow::saveSnapshots(const QString &dir)
605
+ {
606
+ auto settle = [] { QEventLoop loop; QTimer::singleShot(700, &loop, &QEventLoop::quit), loop.exec(); }; // let animations finish
607
+ QTabWidget *tabs = ui->detail->tabs;
608
+ grab().save(dir + "/00-dashboard.png");
609
+ if (ui->mgr->sessions().isEmpty()) return;
610
+ ui->act.open(ui->mgr->sessions()[0]->config().id);
611
+ for (int i = 0; i < tabs->count(); ++i)
612
+ tabs->setCurrentIndex(i), settle(), grab().save(QString("%1/%2-%3.png").arg(dir).arg(i + 1, 2, 10, QChar('0')).arg(tabs->tabText(i).split(' ')[0].toLower()));
613
+ ui->navEvents->click(), settle(), grab().save(dir + "/99-events.png");
614
+ }
Server Monitor(cqt-linux)/src/ui/Windows.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Detail-page tab interface and the main window (sidebar, dashboard, server page, events, tray).
2
+ #pragma once
3
+ #include "core/Session.h"
4
+ #include <QMainWindow>
5
+
6
+ struct Tab : QWidget { // one aspect of the bound server session
7
+ QPointer<ServerSession> s;
8
+ qint64 span = 15 * 60000; // live chart window
9
+ std::function<void(const ServerConfig &)> save; // persists config edits
10
+ virtual void bind(ServerSession *x) { s = x; }
11
+ virtual void refresh() {} // new sample (only while visible)
12
+ virtual void analysis() {} // analyzer ran
13
+ };
14
+ QVector<QPair<QString, Tab *>> makeTabs();
15
+
16
+ struct MainWindow : QMainWindow {
17
+ explicit MainWindow(ServerManager *mgr);
18
+ void saveSnapshots(const QString &dir); // developer aid: PNG of every page
19
+ void closeEvent(QCloseEvent *e) override;
20
+ struct Ui;
21
+ Ui *ui;
22
+ };
Server Monitor(cqt-window)/.gitignore ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ build/
2
+ *.user
Server Monitor(cqt-window)/CMakeLists.txt ADDED
@@ -0,0 +1,12 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ cmake_minimum_required(VERSION 3.16)
2
+ project(ServerMonitor LANGUAGES CXX)
3
+ set(CMAKE_CXX_STANDARD 17)
4
+ set(CMAKE_AUTOMOC ON)
5
+ find_package(Qt5 5.15 REQUIRED COMPONENTS Widgets)
6
+ file(GLOB_RECURSE SRC CONFIGURE_DEPENDS src/*.cpp src/*.h)
7
+ add_executable(ServerMonitor WIN32 ${SRC})
8
+ if(MSVC)
9
+ target_compile_options(ServerMonitor PRIVATE /utf-8) # the sources are UTF-8
10
+ endif()
11
+ target_include_directories(ServerMonitor PRIVATE src)
12
+ target_link_libraries(ServerMonitor PRIVATE Qt5::Widgets)
Server Monitor(cqt-window)/README.md ADDED
@@ -0,0 +1,47 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Server Monitor (Windows)
2
+
3
+ A Qt 5 / C++17 desktop program for Windows that watches Windows machines in detail, keeps their history from seconds to years, analyzes that history with plain statistics (no AI), and fixes common problems automatically. It uses only Qt plus what Windows ships: PowerShell and the OpenSSH client. All charts and gauges are drawn by hand with `QPainter`.
4
+
5
+ It is the Windows edition of the Linux program in `Server Monitor(cqt-linux)`: the same code with a different `src/core/Platform.cpp`.
6
+
7
+ ## Build and run
8
+
9
+ Install Qt 5.15 (MinGW or MSVC kit), open the matching Qt command prompt in this folder and run:
10
+
11
+ ```bat
12
+ build.bat
13
+ build\release\ServerMonitor.exe
14
+ ```
15
+
16
+ `build.bat` runs `qmake`, the compiler, and `windeployqt` (which copies the Qt DLLs next to the program). Qt Creator (`ServerMonitor.pro`) and CMake (`CMakeLists.txt`) work too.
17
+
18
+ ## Servers
19
+
20
+ Add or remove servers from the sidebar or the dashboard. There are two ways to connect:
21
+
22
+ - **This machine:** no setup.
23
+ - **SSH:** the app uses the Windows `ssh` client. The server needs the *OpenSSH Server* feature; nothing else is installed on it. Keys are recommended (add your public key to the server's `authorized_keys`). A password also works if the local `ssh` is OpenSSH 8.4 or newer (check with `ssh -V`); older versions cannot take the password from a program.
24
+
25
+ A PowerShell script (in `src/core/Platform.cpp`) reads CIM classes and .NET counters on the monitored machine and prints one frame per interval. All calculations happen in the app.
26
+
27
+ Control actions run as the user the app (or the SSH login) runs as. Restarting services, ending other users' processes and cleanup need an administrator: start the app with **Run as administrator**, or log in over SSH with an administrator account.
28
+
29
+ ## Features
30
+
31
+ Same as the Linux edition: dashboard, per-server tabs (Overview, CPU, Memory, Storage, Network, Processes, Services, History, Insights & Autopilot, Alert rules, Console), history at four resolutions (6 h of samples, 30 days of minutes, 2 years of hours, 20 years of days), statistical analysis every minute, autopilot with dry run, alert rules, events and `alerts.log`.
32
+
33
+ What differs on Windows:
34
+
35
+ - **Load average** is computed the Unix way (running + waiting threads, smoothed over 1 / 5 / 15 minutes) from CPU usage and the processor queue length.
36
+ - **CPU time** is split into user, kernel and interrupts + DPC. There is no I/O wait or steal counter.
37
+ - **Swap** is the page file. Swap thrashing is reported when the page file is over half used, memory is over 90 % and the disks are over 50 % busy.
38
+ - **Failed service** means: start type Automatic, stopped, with an error exit code.
39
+ - **Processes:** End task, Kill, Kill tree, and priority classes (Idle … High). Process owners are shown only when the app runs as administrator.
40
+ - **Temperatures** appear only if the machine exposes ACPI thermal zones (many do not). GPUs need `nvidia-smi`.
41
+ - The default sample interval is 3 s.
42
+
43
+ ## Status
44
+
45
+ The shared code is tested on Linux. The Windows-specific part was tested there against simulated Windows data, so the parser and the whole UI are exercised, but **the PowerShell collector and the Windows commands have not been run on a real Windows machine yet**.
46
+
47
+ Settings are in `%LOCALAPPDATA%\ServerMonitor\ServerMonitor\servers.json`, history in the `history` folder next to it. Saved SSH passwords are only lightly disguised, not encrypted, so prefer keys.
Server Monitor(cqt-window)/ServerMonitor.pro ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ # Qt Creator / qmake project
2
+ QT += widgets
3
+ CONFIG += c++17 utf8_source
4
+ TARGET = ServerMonitor
5
+ INCLUDEPATH += src
6
+ SOURCES += $$files(src/*.cpp, true)
7
+ HEADERS += $$files(src/*.h, true)
Server Monitor(cqt-window)/build.bat ADDED
@@ -0,0 +1,18 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ @echo off
2
+ rem Build Server Monitor with Qt 5. Run from a Qt command prompt (MinGW or MSVC) so that qmake is on PATH.
3
+ setlocal
4
+ cd /d "%~dp0"
5
+ where qmake >nul 2>nul
6
+ if errorlevel 1 (
7
+ echo qmake not found. Open the Qt command prompt or add the Qt bin folder to PATH.
8
+ exit /b 1
9
+ )
10
+ if not exist build mkdir build
11
+ cd build
12
+ qmake ..\ServerMonitor.pro "CONFIG+=release"
13
+ if errorlevel 1 exit /b 1
14
+ for /f %%s in ('qmake -query QMAKE_XSPEC') do set SPEC=%%s
15
+ if "%SPEC%"=="win32-g++" (mingw32-make -j%NUMBER_OF_PROCESSORS%) else (nmake)
16
+ if errorlevel 1 exit /b 1
17
+ windeployqt release\ServerMonitor.exe
18
+ echo Done: build\release\ServerMonitor.exe
Server Monitor(cqt-window)/src/core/History.cpp ADDED
@@ -0,0 +1,367 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "History.h"
2
+ #include <QDateTime>
3
+ #include <QDir>
4
+ #include <QFile>
5
+ #include <QSaveFile>
6
+ #include <algorithm>
7
+ #include <cstring>
8
+
9
+ const char *const hKeys[H_COUNT] = {"cpu", "iowait", "load", "mem", "swap", "disk", "diskio", "rx", "tx", "rd", "wr", "temp", "procs", "gpu", "failed"};
10
+ const char *const hNames[H_COUNT] = {"CPU", "I/O wait", "Load (1m)", "Memory", "Swap", "Disk usage", "Disk busy", "Net download",
11
+ "Net upload", "Disk read", "Disk write", "Temperature", "Processes", "GPU", "Failed services"};
12
+ QString tierName(Tier t) { return QStringList{"every sample", "1 minute", "1 hour", "1 day"}.value(int(t)); }
13
+ static const QByteArray kHeader = QByteArray("SMH1") + char(H_COUNT) + char(0) + char(sizeof(HPoint) & 0xff) + char(sizeof(HPoint) >> 8);
14
+
15
+ // ---- accumulator ----------------------------------------------------------------
16
+ HistoryStore::Acc::Acc(qint64 b) : bucket(b) { std::fill(mx, mx + H_COUNT, NAN); }
17
+ void HistoryStore::Acc::add(const HPoint &p)
18
+ {
19
+ n += p.n, nUp += p.nUp;
20
+ if (p.nUp)
21
+ for (int i = 0; i < H_COUNT; ++i)
22
+ if (!std::isnan(p.avg[i])) {
23
+ sum[i] += double(p.avg[i]) * p.nUp, cnt[i] += p.nUp;
24
+ if (std::isnan(mx[i]) || p.max[i] > mx[i]) mx[i] = p.max[i];
25
+ }
26
+ }
27
+ HPoint HistoryStore::Acc::point() const
28
+ {
29
+ HPoint p;
30
+ p.ts = bucket, p.n = n, p.nUp = nUp;
31
+ for (int i = 0; i < H_COUNT; ++i) p.avg[i] = cnt[i] ? float(sum[i] / cnt[i]) : NAN, p.max[i] = mx[i];
32
+ return p;
33
+ }
34
+
35
+ // ---- store ----------------------------------------------------------------------
36
+ QString HistoryStore::file(int t) const { return m_dir + "/" + QStringList{"raw", "minute", "hour", "day"}[t] + ".bin"; }
37
+ qint64 HistoryStore::bucketOf(int t, qint64 ts) const { return t == 3 ? (ts + m_tz) / 86400 * 86400 - m_tz : ts / step[t] * step[t]; } // days at local midnight
38
+
39
+ HistoryStore::HistoryStore(const QString &dir) : m_dir(dir), m_tz(QDateTime::currentDateTime().offsetFromUtc())
40
+ {
41
+ QDir().mkpath(dir);
42
+ const qint64 now = QDateTime::currentSecsSinceEpoch();
43
+ for (int t = 0; t < 4; ++t) {
44
+ QFile f(file(t));
45
+ if (!f.open(QIODevice::ReadOnly)) continue;
46
+ const QByteArray d = f.readAll();
47
+ if (!d.startsWith(kHeader)) { f.close(), QFile::remove(f.fileName() + ".old"), f.rename(f.fileName() + ".old"); continue; }
48
+ int bad = int((d.size() - kHeader.size()) % sizeof(HPoint)); // a cut-off record would misalign everything appended after it
49
+ for (int off = kHeader.size(); off + int(sizeof(HPoint)) <= d.size(); off += sizeof(HPoint)) {
50
+ HPoint p;
51
+ std::memcpy(&p, d.constData() + off, sizeof p);
52
+ if (p.ts < now - keep[t] || p.ts > now + 86400 || (!m_t[t].isEmpty() && p.ts <= m_t[t].last().ts)) ++bad;
53
+ else m_t[t] << p;
54
+ }
55
+ if (bad) rewrite(t);
56
+ }
57
+ for (int t = 1; t < 4; ++t) { // rebuild from finer data what is not stored yet: buckets the last run left open, and the current one
58
+ const qint64 stored = m_t[t].isEmpty() ? -1 : m_t[t].last().ts;
59
+ auto feed = [&](const HPoint &p) {
60
+ const qint64 b = bucketOf(t, p.ts);
61
+ if (b <= stored) return;
62
+ if (b != m_acc[t].bucket) {
63
+ if (m_acc[t].n) append(t, m_acc[t].point());
64
+ m_acc[t] = Acc(b);
65
+ }
66
+ m_acc[t].add(p);
67
+ };
68
+ for (const HPoint &p : qAsConst(m_t[t - 1])) feed(p);
69
+ if (m_acc[t - 1].n) feed(m_acc[t - 1].point());
70
+ }
71
+ }
72
+
73
+ void HistoryStore::rewrite(int t)
74
+ {
75
+ QSaveFile f(file(t));
76
+ if (!f.open(QIODevice::WriteOnly)) return;
77
+ f.write(kHeader);
78
+ f.write(reinterpret_cast<const char *>(m_t[t].constData()), qint64(m_t[t].size()) * sizeof(HPoint));
79
+ f.commit();
80
+ }
81
+
82
+ void HistoryStore::append(int t, const HPoint &p)
83
+ {
84
+ auto &v = m_t[t];
85
+ if (!v.isEmpty() && p.ts <= v.last().ts) return;
86
+ v << p;
87
+ QFile f(file(t));
88
+ if (f.open(QIODevice::Append)) {
89
+ if (f.size() < kHeader.size()) f.resize(0), f.write(kHeader);
90
+ f.write(reinterpret_cast<const char *>(&p), sizeof p);
91
+ }
92
+ if (++m_appends[t] % 500) return; // trim expired points now and then
93
+ const auto it = std::find_if(v.begin(), v.end(), [&](const HPoint &x) { return x.ts >= p.ts - keep[t]; });
94
+ if (it != v.begin()) v.erase(v.begin(), it), rewrite(t);
95
+ }
96
+
97
+ void HistoryStore::add(qint64 ts, const float *val, bool up)
98
+ {
99
+ HPoint raw;
100
+ raw.ts = ts, raw.n = 1, raw.nUp = up;
101
+ for (int i = 0; i < H_COUNT; ++i) raw.avg[i] = raw.max[i] = up ? val[i] : NAN;
102
+ append(0, raw);
103
+ for (int t = 1; t < 4; ++t) { // every coarser tier accumulates every raw sample
104
+ const qint64 b = bucketOf(t, ts);
105
+ if (m_acc[t].bucket != b) {
106
+ if (m_acc[t].n && m_acc[t].bucket < b) append(t, m_acc[t].point());
107
+ m_acc[t] = Acc(b);
108
+ }
109
+ m_acc[t].add(raw);
110
+ }
111
+ }
112
+
113
+ QVector<HPoint> HistoryStore::range(qint64 from, qint64 to, Tier tier) const
114
+ {
115
+ const int t = int(tier);
116
+ const auto &v = m_t[t];
117
+ auto it = std::lower_bound(v.begin(), v.end(), from, [](const HPoint &p, qint64 x) { return p.ts < x; });
118
+ QVector<HPoint> out;
119
+ for (; it != v.end() && it->ts <= to; ++it) out << *it;
120
+ const Acc &a = m_acc[t];
121
+ if (t && a.n && a.bucket >= from && a.bucket <= to && (out.isEmpty() || out.last().ts < a.bucket)) out << a.point();
122
+ return out;
123
+ }
124
+
125
+ QVector<HPoint> HistoryStore::range(qint64 from, qint64 to, Tier *used) const
126
+ {
127
+ const qint64 now = QDateTime::currentSecsSinceEpoch(), maxSpan[3] = {6 * 3600, 8 * 86400, 400 * 86400};
128
+ int t = 0;
129
+ while (t < 3 && (from < now - keep[t] || to - from > maxSpan[t])) ++t;
130
+ if (used) *used = Tier(t);
131
+ return range(from, to, Tier(t));
132
+ }
133
+
134
+ void HistoryStore::removeFiles() { QDir(m_dir).removeRecursively(), *this = HistoryStore(m_dir); }
135
+ qint64 HistoryStore::firstTs() const
136
+ {
137
+ qint64 f = 0;
138
+ for (const auto &v : m_t)
139
+ if (!v.isEmpty() && (!f || v[0].ts < f)) f = v[0].ts;
140
+ return f;
141
+ }
142
+ qint64 HistoryStore::diskBytes() const
143
+ {
144
+ qint64 b = 0;
145
+ for (int t = 0; t < 4; ++t) b += QFileInfo(file(t)).size();
146
+ return b;
147
+ }
148
+
149
+ Stats stats(const QVector<HPoint> &pts, int m)
150
+ {
151
+ Stats s;
152
+ QVector<double> v;
153
+ double sum = 0, w = 0;
154
+ for (const HPoint &p : pts) {
155
+ if (!p.nUp || std::isnan(p.avg[m])) continue;
156
+ v << p.avg[m], sum += double(p.avg[m]) * p.nUp, w += p.nUp;
157
+ if (std::isnan(s.max) || p.max[m] > s.max) s.max = p.max[m];
158
+ }
159
+ if (v.isEmpty()) return s;
160
+ std::sort(v.begin(), v.end());
161
+ s.count = v.size(), s.avg = sum / w, s.min = v[0], s.p95 = v[qMin(v.size() - 1, int(v.size() * 0.95))];
162
+ return s;
163
+ }
164
+
165
+ QString fmtMetric(int m, double v)
166
+ {
167
+ if (std::isnan(v)) return "—";
168
+ switch (m) {
169
+ case H_RX: case H_TX: case H_RD: case H_WR: return Fmt::rate(v);
170
+ case H_LOAD: return QString::number(v, 'f', 2);
171
+ case H_TEMP: return Fmt::temp(v);
172
+ case H_PROCS: case H_FAILED: return QString::number(v, 'f', 0);
173
+ default: return Fmt::pct(v);
174
+ }
175
+ }
176
+
177
+ // ---- analysis -------------------------------------------------------------------
178
+ Analysis::Analysis() { std::fill(&heat[0][0][0], &heat[0][0][0] + 336, NAN); }
179
+
180
+ double regression(const QVector<HPoint> &pts, int m, double *r2)
181
+ {
182
+ double n = 0, sx = 0, sy = 0, sxx = 0, sxy = 0, syy = 0, x0 = pts.isEmpty() ? 0 : pts[0].ts;
183
+ for (const HPoint &p : pts)
184
+ if (p.nUp && !std::isnan(p.avg[m])) {
185
+ const double x = p.ts - x0, y = p.avg[m];
186
+ n++, sx += x, sy += y, sxx += x * x, sxy += x * y, syy += y * y;
187
+ }
188
+ const double den = n * sxx - sx * sx, num = n * sxy - sx * sy, vy = n * syy - sy * sy;
189
+ *r2 = n >= 3 && den > 0 && vy > 1e-9 ? num * num / (den * vy) : 0; // squared correlation
190
+ return n >= 3 && den > 0 ? num / den : 0;
191
+ }
192
+
193
+ Analysis analyze(const HistoryStore &st, const Metrics &m, const AutopilotConfig &ap, const QVector<ProcTrend> &procs,
194
+ const QVector<ServiceTrend> &svcs, bool online)
195
+ {
196
+ Analysis a;
197
+ const qint64 now = a.when = QDateTime::currentSecsSinceEpoch();
198
+ const auto &minute = st.tier(Tier::Minute), &hour = st.tier(Tier::Hour);
199
+ auto add = [&](QString key, QString sev, QString cat, QString title, QString detail, QString advice, QString action = {},
200
+ QString arg = {}, QString label = {}, bool autoOk = false) {
201
+ a.findings << Finding{key, sev, cat, title, detail, advice, action, arg, label, autoOk};
202
+ };
203
+ auto sev = [](bool crit, bool warn) { return crit ? "critical" : warn ? "warning" : "info"; };
204
+
205
+ // availability
206
+ const qint64 spans[3] = {86400, 7 * 86400, 30 * 86400};
207
+ for (int i = 0; i < 3; ++i) {
208
+ double n = 0, up = 0;
209
+ for (const HPoint &p : st.range(now - spans[i], now)) n += p.n, up += p.nUp;
210
+ a.up[i] = n ? up * 100 / n : NAN;
211
+ a.down[i] = n ? (n - up) / n * qMin(spans[i], now - st.firstTs()) : 0; // share of the monitored part of the window
212
+ }
213
+ if (a.up[0] < 99)
214
+ add("avail24", sev(a.up[0] < 95, true), "Availability", QString("Availability last 24 h is %1").arg(Fmt::pct(a.up[0], 2)),
215
+ QString("The server could not be reached for about %1 in the last day.").arg(Fmt::duration(a.down[0])),
216
+ "Check network stability, power and whether the machine rebooted (uptime).");
217
+ const auto w30 = st.range(now - spans[2], now, Tier::Hour), w7 = st.range(now - spans[1], now, Tier::Minute);
218
+ a.cpu30 = stats(w30.size() >= 24 ? w30 : w7, H_CPU), a.mem30 = stats(w30.size() >= 24 ? w30 : w7, H_MEM);
219
+
220
+ // disk forecast: regression over 7 d of hours, or 24 h of minutes, whichever fits better
221
+ double r2 = 0, r2b = 0, slope = 0;
222
+ const auto week = st.range(now - spans[1], now, Tier::Hour), day = st.range(now - 86400, now, Tier::Minute);
223
+ if (week.size() >= 48) slope = regression(week, H_DISK, &r2), a.diskBasis = "hourly averages, last 7 days";
224
+ if (day.size() >= 120) {
225
+ const double s2 = regression(day, H_DISK, &r2b);
226
+ if (week.size() < 48 || r2b > r2) slope = s2, r2 = r2b, a.diskBasis = "minute averages, last 24 hours";
227
+ }
228
+ a.diskSlopePerDay = slope * 86400;
229
+ if (a.diskSlopePerDay > 0.05 && r2 >= 0.3 && m.maxDiskPct > 0) a.diskFullDays = (100 - m.maxDiskPct) / a.diskSlopePerDay;
230
+ if (a.diskFullDays >= 0 && a.diskFullDays < 30)
231
+ add("diskfull", sev(a.diskFullDays < ap.diskForecastDays, a.diskFullDays < 14), "Disk",
232
+ QString("Disk %1 will be full in %2").arg(m.fullestMount, Fmt::duration(a.diskFullDays * 86400)),
233
+ QString("Usage %1, growing %2 points/day (trend from %3, fit R² %4).").arg(Fmt::pct(m.maxDiskPct)).arg(a.diskSlopePerDay, 0, 'f', 2).arg(a.diskBasis).arg(r2, 0, 'f', 2),
234
+ "Clean logs/caches, rotate or move data, or grow the volume.", "disk_cleanup", "", "Run cleanup", ap.diskCleanup && a.diskFullDays < ap.diskForecastDays);
235
+ if (m.maxDiskPct >= ap.diskCleanupAt)
236
+ add("diskhigh", sev(m.maxDiskPct >= 97, true), "Disk", QString("Disk %1 is %2 full").arg(m.fullestMount, Fmt::pct(m.maxDiskPct)),
237
+ QString("Above the cleanup threshold of %1.").arg(Fmt::pct(ap.diskCleanupAt, 0)), "Free space soon: services fail when the disk is full.",
238
+ "disk_cleanup", "", "Run cleanup", ap.diskCleanup);
239
+
240
+ // whole-machine memory trend over 6 h
241
+ const auto six = st.range(now - 6 * 3600, now, Tier::Minute);
242
+ if (six.size() >= 90) {
243
+ a.memSlopePerHour = regression(six, H_MEM, &a.memTrendR2) * 3600;
244
+ const double left = (100 - m.memPct) / qMax(0.01, a.memSlopePerHour);
245
+ if (a.memSlopePerHour > 1 && a.memTrendR2 > 0.8 && m.memPct > 40)
246
+ add("memtrend", sev(false, left < 12), "Memory", QString("Memory keeps growing (+%1 points/hour)").arg(a.memSlopePerHour, 0, 'f', 1),
247
+ QString("Steady growth over 6 h (R² %1). At this rate memory is exhausted in about %2.").arg(a.memTrendR2, 0, 'f', 2).arg(Fmt::duration(left * 3600)),
248
+ "Look for a leaking process (Processes tab, sort by RSS).");
249
+ }
250
+
251
+ // processes: leaks and runaways
252
+ for (const ProcTrend &p : procs) {
253
+ if (p.kernel) continue;
254
+ const QString who = QString("%1 (PID %2)").arg(p.name).arg(p.pid), pid = QString::number(p.pid);
255
+ if (p.minutesTracked >= 30 && p.rssGrowthPct >= 25 && p.rssGrowth >= 100e6 && p.rssMonotonic >= 0.8)
256
+ add("leak:" + pid, sev(m.memPct >= ap.leakMemPressure, true), "Process", "Possible memory leak: " + who,
257
+ QString("RSS grew %1 (+%2) in %3 min and rose in %4% of the minutes; now %5.").arg(Fmt::bytes(p.rssGrowth), Fmt::pct(p.rssGrowthPct, 0))
258
+ .arg(p.minutesTracked).arg(qRound(p.rssMonotonic * 100)).arg(Fmt::bytes(p.rssNow)),
259
+ "Restart the program/service at a quiet time and report the leak upstream.", "kill_pid", pid, "Terminate",
260
+ ap.leakMode == "terminate" && m.memPct >= ap.leakMemPressure);
261
+ if (p.highCpuMinutes >= ap.runawayMinutes) {
262
+ const bool term = ap.runawayMode == "terminate";
263
+ add("runaway:" + pid, "warning", "Process", "Runaway process: " + who,
264
+ QString("Above %1 CPU for %2 min (now %3, user %4).").arg(Fmt::pct(ap.runawayCpu, 0)).arg(qRound(p.highCpuMinutes)).arg(Fmt::pct(p.cpuNow), p.user),
265
+ "Lower its priority (renice) or stop it if it is stuck.", term ? "kill_pid" : "renice", pid, term ? "Terminate" : "Renice to 19", ap.runawayMode != "none");
266
+ }
267
+ }
268
+
269
+ // services: failures and flapping
270
+ for (const ServiceTrend &s : svcs) {
271
+ const bool flap = s.failsLastHour >= 3 || s.autoRestartsLastHour >= ap.maxRestartsPerHour;
272
+ if (s.failedNow)
273
+ add("svc:" + s.unit, sev(flap, true), "Service", QString(flap ? "Service %1 keeps failing" : "Service %1 has failed").arg(s.unit),
274
+ s.preexisting ? "It was already failed when monitoring started, so the autopilot leaves it alone (it may be failed on purpose)."
275
+ : QString("Failed %1× in the last hour; autopilot restarted it %2×.").arg(s.failsLastHour).arg(s.autoRestartsLastHour),
276
+ flap ? "Automatic restarts were stopped. Read the logs (Services tab → Logs) and fix the cause." : "Restart it and check the logs.",
277
+ "restart_service", s.unit, "Restart", ap.restartFailed && !s.preexisting && s.autoRestartsLastHour < ap.maxRestartsPerHour);
278
+ else if (s.failsLastHour >= 3)
279
+ add("flap:" + s.unit, "warning", "Service", QString("Service %1 is unstable").arg(s.unit),
280
+ QString("It failed %1 times within the last hour.").arg(s.failsLastHour), "Inspect its logs and resource limits.");
281
+ }
282
+
283
+ // overload and swap thrashing
284
+ const auto last15 = st.range(now - 900, now, Tier::Minute);
285
+ const double load15 = stats(last15, H_LOAD).avg, io15 = stats(last15, H_IOWAIT).avg, cpu15 = stats(last15, H_CPU).avg, busy15 = stats(last15, H_DISKIO).avg;
286
+ if (online && load15 / m.cpuCount > 1.5)
287
+ add("load", sev(load15 / m.cpuCount > 3, true), "CPU", QString("CPU is overloaded (load %1 on %2 cores)").arg(load15, 0, 'f', 1).arg(m.cpuCount),
288
+ QString("15-minute average load is %1× the number of cores; tasks are waiting for CPU.").arg(load15 / m.cpuCount, 0, 'f', 1),
289
+ "Find the busiest processes, spread work over time, or add CPU.");
290
+ if (online && m.swapPct > 50 && (P::posixCpu ? io15 > 20 : m.memPct > 90 && busy15 > 50)) // no I/O wait counter on Windows: full memory + busy disks
291
+ add("thrash", "critical", "Memory", "Swap thrashing", P::posixCpu ? QString("Swap %1 used and CPU waits on I/O %2 of the time.").arg(Fmt::pct(m.swapPct), Fmt::pct(io15))
292
+ : QString("Swap %1 used, memory %2 full and disks %3 busy.").arg(Fmt::pct(m.swapPct), Fmt::pct(m.memPct), Fmt::pct(busy15)),
293
+ "Stop memory-hungry processes or add RAM.");
294
+
295
+ // anomalies: last 10 min vs same weekday+hour over 8 weeks (fallback: last 24 h)
296
+ const auto raw = st.range(now - 600, now, Tier::Raw);
297
+ const QDateTime lt = QDateTime::fromSecsSinceEpoch(now);
298
+ if (online && raw.size() >= 10)
299
+ for (auto [hm, floor, down] : {std::tuple{H_CPU, 5.0, false}, {H_MEM, 3.0, false}, {H_LOAD, 0.25 * qMax(1, m.cpuCount), false},
300
+ {H_IOWAIT, 3.0, false}, {H_RX, 256e3, true}, {H_TX, 256e3, true}}) {
301
+ if (hm == H_IOWAIT && !P::posixCpu) continue;
302
+ const double cur = stats(raw, hm).avg;
303
+ QVector<double> v;
304
+ for (const HPoint &p : hour) {
305
+ const QDateTime t = QDateTime::fromSecsSinceEpoch(p.ts);
306
+ if (p.nUp && !std::isnan(p.avg[hm]) && now - p.ts < 56 * 86400 && now - p.ts > 3600 && t.date().dayOfWeek() == lt.date().dayOfWeek() && t.time().hour() == lt.time().hour())
307
+ v << p.avg[hm];
308
+ }
309
+ QString basis = "same weekday & hour, last 8 weeks";
310
+ if (v.size() < 3) {
311
+ v.clear(), basis = "last 24 hours";
312
+ for (const HPoint &p : minute)
313
+ if (p.nUp && !std::isnan(p.avg[hm]) && now - p.ts <= 86400 && now - p.ts > 900) v << p.avg[hm];
314
+ if (v.size() < 360) continue;
315
+ }
316
+ double mean = 0, var = 0;
317
+ for (double x : v) mean += x / v.size();
318
+ for (double x : v) var += (x - mean) * (x - mean) / v.size();
319
+ const double sd = std::sqrt(var), z = (cur - mean) / qMax(sd, floor);
320
+ a.anomalies << Anomaly{hNames[hm], basis, hm, cur, mean, sd, z};
321
+ const bool hi = z >= ap.anomalyZ, lo = down && mean > 1e6 && cur < mean * 0.1;
322
+ if (ap.anomalyAlerts && (hi || lo))
323
+ add(QString("anomaly:") + hKeys[hm], sev(false, z >= ap.anomalyZ * 2), "Anomaly", QString(hi ? "Unusually high %1" : "Unusually low %1").arg(QString(hNames[hm]).toLower()),
324
+ QString("Last 10 min %1, usually %2 ± %3 (%4); %5σ.").arg(fmtMetric(hm, cur), fmtMetric(hm, mean), fmtMetric(hm, sd), basis).arg(z, 0, 'f', 1),
325
+ hi ? "Check what changed: deploys, cron jobs, traffic, attacks." : "Traffic dropped sharply - check the service is still serving.");
326
+ }
327
+
328
+ // weekly heatmaps from 4 weeks of hours
329
+ double sum[2][7][24] = {};
330
+ for (const HPoint &p : hour) {
331
+ if (now - p.ts > 28 * 86400 || !p.nUp || std::isnan(p.avg[H_CPU])) continue;
332
+ const QDateTime t = QDateTime::fromSecsSinceEpoch(p.ts);
333
+ const int d = t.date().dayOfWeek() - 1, h = t.time().hour(), n = ++a.heatN[d][h];
334
+ sum[0][d][h] += p.avg[H_CPU], sum[1][d][h] += std::isnan(p.avg[H_MEM]) ? 0 : p.avg[H_MEM];
335
+ a.heat[0][d][h] = sum[0][d][h] / n, a.heat[1][d][h] = sum[1][d][h] / n;
336
+ }
337
+
338
+ // capacity advice
339
+ for (auto [s, name, lo, hi, loTxt, hiTxt] : {std::tuple{a.cpu30, "CPU", 15.0, 80.0, "is mostly idle", "is often saturated - add cores or move work away"},
340
+ {a.mem30, "Memory", 30.0, 85.0, "is under-used", "is tight - add RAM or reduce caches/limits"}})
341
+ if (s.count >= 60)
342
+ a.capacity << QString("%1 %2 (p95 %3).").arg(name, s.p95 < lo ? loTxt : s.p95 > hi ? hiTxt : "headroom is healthy", Fmt::pct(s.p95));
343
+ if (a.diskFullDays >= 0) a.capacity << QString("Disk grows %1 points/day - full in about %2.").arg(a.diskSlopePerDay, 0, 'f', 2).arg(Fmt::duration(a.diskFullDays * 86400));
344
+ else if (!a.diskBasis.isEmpty()) a.capacity << "Disk usage is stable.";
345
+ if (a.capacity.isEmpty()) a.capacity << "Collecting history - capacity advice appears after about an hour of data.";
346
+
347
+ // health score
348
+ double score = 100, fp = 0;
349
+ auto pen = [&](bool when, double p, const QString &why) {
350
+ if (when && p > 0.5) score -= p, a.healthReasons << QString("−%1 %2").arg(qRound(p)).arg(why);
351
+ };
352
+ const double cpu = std::isnan(cpu15) ? m.cpuUsage : cpu15;
353
+ for (const Finding &f : a.findings) fp += f.category == "Availability" ? 0 : f.severity == "critical" ? 15 : f.severity == "warning" ? 7 : 2;
354
+ pen(!online, 60, "server unreachable");
355
+ pen(cpu > 70, qMin(24.0, (cpu - 70) * 0.8), "CPU busy (" + Fmt::pct(cpu) + ")");
356
+ pen(m.memPct > 80, qMin(30.0, (m.memPct - 80) * 1.5), "memory high (" + Fmt::pct(m.memPct) + ")");
357
+ pen(m.maxDiskPct > 80, qMin(40.0, (m.maxDiskPct - 80) * 2), "disk high (" + Fmt::pct(m.maxDiskPct) + ")");
358
+ pen(m.swapPct > 50, 10, "heavy swap use");
359
+ pen(m.maxTemp > 80, qMin(20.0, (m.maxTemp - 80) * 2), "hot (" + Fmt::temp(m.maxTemp) + ")");
360
+ pen(a.up[0] < 100, qMin(30.0, (100 - a.up[0]) * 5), "downtime in last 24 h");
361
+ pen(true, qMin(50.0, fp), QString("%1 finding(s)").arg(a.findings.size()));
362
+ a.health = qBound(0, qRound(score), 100);
363
+ a.grade = QString("FDCBA").at(a.health >= 90 ? 4 : a.health >= 75 ? 3 : a.health >= 60 ? 2 : a.health >= 40 ? 1 : 0);
364
+ auto rank = [](const QString &s) { return s == "critical" ? 0 : s == "warning" ? 1 : 2; };
365
+ std::stable_sort(a.findings.begin(), a.findings.end(), [&](const Finding &x, const Finding &y) { return rank(x.severity) < rank(y.severity); });
366
+ return a;
367
+ }
Server Monitor(cqt-window)/src/core/History.h ADDED
@@ -0,0 +1,87 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Persistent multi-resolution history (raw 6 h, minute 30 d, hour 2 y, day 20 y)
2
+ // and the statistics-only analyzer that feeds the autopilot.
3
+ #pragma once
4
+ #include "Model.h"
5
+ #include <cmath>
6
+
7
+ enum HMetric { H_CPU, H_IOWAIT, H_LOAD, H_MEM, H_SWAP, H_DISK, H_DISKIO, H_RX, H_TX, H_RD, H_WR, H_TEMP, H_PROCS, H_GPU, H_FAILED, H_COUNT };
8
+ extern const char *const hKeys[H_COUNT], *const hNames[H_COUNT];
9
+ enum class Tier { Raw, Minute, Hour, Day };
10
+ QString tierName(Tier t);
11
+
12
+ #pragma pack(push, 1)
13
+ struct HPoint {
14
+ qint64 ts = 0; // seconds; bucket start for aggregates
15
+ quint32 n = 0, nUp = 0; // samples / online samples
16
+ float avg[H_COUNT], max[H_COUNT];
17
+ double uptimePct() const { return n ? nUp * 100.0 / n : 0; }
18
+ };
19
+ #pragma pack(pop)
20
+
21
+ class HistoryStore {
22
+ public:
23
+ static constexpr qint64 step[4] = {1, 60, 3600, 86400}, keep[4] = {6 * 3600, 30 * 86400, 732 * 86400, 7320LL * 86400};
24
+ explicit HistoryStore(const QString &dir);
25
+ void add(qint64 ts, const float *v, bool up); // up=false records downtime only
26
+ const QVector<HPoint> &tier(Tier t) const { return m_t[int(t)]; }
27
+ QVector<HPoint> range(qint64 from, qint64 to, Tier t) const; // includes the open bucket
28
+ QVector<HPoint> range(qint64 from, qint64 to, Tier *used = nullptr) const; // finest tier covering it
29
+ void removeFiles();
30
+ qint64 firstTs() const;
31
+ qint64 diskBytes() const;
32
+
33
+ private:
34
+ struct Acc {
35
+ qint64 bucket = -1;
36
+ quint32 n = 0, nUp = 0, cnt[H_COUNT] = {};
37
+ double sum[H_COUNT] = {};
38
+ float mx[H_COUNT];
39
+ Acc(qint64 b = -1);
40
+ void add(const HPoint &p);
41
+ HPoint point() const;
42
+ };
43
+ qint64 bucketOf(int t, qint64 ts) const;
44
+ void append(int t, const HPoint &p);
45
+ void rewrite(int t);
46
+ QString file(int t) const;
47
+ QString m_dir;
48
+ QVector<HPoint> m_t[4];
49
+ Acc m_acc[4];
50
+ qint64 m_tz;
51
+ int m_appends[4] = {};
52
+ };
53
+
54
+ struct Stats { double min = NAN, avg = NAN, p95 = NAN, max = NAN; int count = 0; }; // max = peak of max[]
55
+ Stats stats(const QVector<HPoint> &pts, int metric);
56
+
57
+ // ---- analysis -------------------------------------------------------------------
58
+ struct Finding {
59
+ QString key, severity, category, title, detail, advice, action, actionArg, actionLabel; // action: disk_cleanup|restart_service|renice|kill_pid
60
+ bool autoEligible = false;
61
+ };
62
+ struct ProcTrend {
63
+ int pid = 0, minutesTracked = 0;
64
+ QString name, user;
65
+ double cpuNow = 0, highCpuMinutes = 0, rssNow = 0, rssGrowth = 0, rssGrowthPct = 0, rssMonotonic = 0;
66
+ bool kernel = false;
67
+ };
68
+ struct ServiceTrend { QString unit; bool failedNow = false, preexisting = false; int failsLastHour = 0, autoRestartsLastHour = 0; };
69
+ struct Anomaly { QString metric, baseline; int hm = 0; double now = 0, mean = 0, sd = 0, z = 0; };
70
+ struct Analysis {
71
+ qint64 when = 0;
72
+ int health = 100;
73
+ QString grade = "A", diskBasis;
74
+ QStringList healthReasons, capacity;
75
+ QVector<Finding> findings;
76
+ QVector<Anomaly> anomalies;
77
+ double diskFullDays = -1, diskSlopePerDay = 0, memSlopePerHour = 0, memTrendR2 = 0;
78
+ double up[3] = {NAN, NAN, NAN}, down[3] = {}; // 24 h, 7 d, 30 d: availability %, seconds offline
79
+ Stats cpu30, mem30;
80
+ double heat[2][7][24]; // weekly pattern: 0 = CPU, 1 = memory
81
+ int heatN[7][24] = {};
82
+ Analysis();
83
+ };
84
+ Analysis analyze(const HistoryStore &st, const Metrics &m, const AutopilotConfig &ap, const QVector<ProcTrend> &procs,
85
+ const QVector<ServiceTrend> &svcs, bool online);
86
+ double regression(const QVector<HPoint> &pts, int metric, double *r2); // slope per second
87
+ QString fmtMetric(int metric, double v);
Server Monitor(cqt-window)/src/core/Model.cpp ADDED
@@ -0,0 +1,128 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "Model.h"
2
+ #include <QJsonArray>
3
+ #include <QUuid>
4
+ #include <QVariant>
5
+ #include <type_traits>
6
+
7
+ // ---- formatting -------------------------------------------------------------
8
+ QString Fmt::bytes(double b, int prec)
9
+ {
10
+ static const char *u[] = {"B", "KB", "MB", "GB", "TB", "PB"};
11
+ int i = 0;
12
+ for (; qAbs(b) >= 1024 && i < 5; ++i) b /= 1024;
13
+ return QString::number(b, 'f', i ? prec : 0) + " " + u[i];
14
+ }
15
+ QString Fmt::count(double v)
16
+ {
17
+ const double a = qAbs(v);
18
+ return a >= 1e9 ? QString::number(v / 1e9, 'f', 1) + "G" : a >= 1e6 ? QString::number(v / 1e6, 'f', 1) + "M" : a >= 1e4 ? QString::number(v / 1e3, 'f', 1) + "K" : QString::number(v, 'f', 0);
19
+ }
20
+ QString Fmt::duration(double sec)
21
+ {
22
+ qint64 s = qint64(sec), d = s / 86400, h = s % 86400 / 3600, m = s % 3600 / 60;
23
+ return d ? QString("%1d %2h %3m").arg(d).arg(h).arg(m) : h ? QString("%1h %2m").arg(h).arg(m) : m ? QString("%1m %2s").arg(m).arg(s % 60) : QString("%1s").arg(s);
24
+ }
25
+
26
+ // ---- catalogues -------------------------------------------------------------
27
+ const QVector<Def> &ruleMetrics()
28
+ {
29
+ static const QVector<Def> d = {{"cpu", "CPU usage", "%"}, {"iowait", "CPU I/O wait", "%"}, {"load", "Load (1 min) per core", "%"},
30
+ {"mem", "Memory usage", "%"}, {"swap", "Swap usage", "%"}, {"disk", "Fullest disk usage", "%"}, {"diskio", "Busiest disk utilisation", "%"},
31
+ {"temp", "Hottest sensor", "°C"}, {"rx", "Network download", "MB/s"}, {"tx", "Network upload", "MB/s"}, {"failed", "Failed services", ""},
32
+ {"procs", "Process count", ""}, {"gpu", "GPU usage (max)", "%"}, {"gputemp", "GPU temperature (max)", "°C"}};
33
+ static const QVector<Def> noWait = d.mid(0, 1) + d.mid(2);
34
+ return P::posixCpu ? d : noWait;
35
+ }
36
+ QString defLabel(const QVector<Def> &d, const QString &k, bool unit)
37
+ {
38
+ for (const Def &x : d)
39
+ if (x.key == k) return unit ? x.unit : x.label;
40
+ return unit ? QString() : k;
41
+ }
42
+
43
+ QString Rule::conditionText() const
44
+ {
45
+ const QString u = defLabel(ruleMetrics(), metric, true);
46
+ return QString("%1 %2 %3%4").arg(defLabel(ruleMetrics(), metric), op).arg(value).arg(u.isEmpty() ? "" : " " + u) + (duration ? QString(" for %1 s").arg(duration) : "");
47
+ }
48
+ QString Rule::actionText() const { return defLabel(P::ruleActions(), action) + (arg.isEmpty() ? "" : ": " + arg); }
49
+
50
+ // ---- JSON: one field list per struct drives both saving and loading ---------------------------
51
+ #define F(f) v(#f, x.f);
52
+ template <class V> static void each(Rule &x, V v) { F(id) F(metric) F(op) F(action) F(arg) F(severity) F(enabled) F(value) F(duration) F(cooldown) }
53
+ template <class V> static void each(ServerConfig &x, V v) { F(id) F(name) F(group) F(host) F(user) F(keyFile) F(notes) F(port) F(interval) F(useSudo) F(enabled) }
54
+ template <class V> static void each(AutopilotConfig &x, V v)
55
+ {
56
+ F(enabled) F(dryRun) F(restartFailed) F(diskCleanup) F(anomalyAlerts) F(maxRestartsPerHour) F(runawayMinutes) F(diskForecastDays)
57
+ F(runawayCpu) F(diskCleanupAt) F(leakMemPressure) F(anomalyZ) F(runawayMode) F(leakMode) F(diskCleanupCommand)
58
+ }
59
+ #undef F
60
+ template <class T> static QJsonObject save(const T &c)
61
+ {
62
+ QJsonObject o;
63
+ each(const_cast<T &>(c), [&](const char *k, const auto &f) { o[k] = QJsonValue::fromVariant(QVariant::fromValue(f)); });
64
+ return o;
65
+ }
66
+ template <class T> static T load(const QJsonObject &o)
67
+ {
68
+ T c;
69
+ each(c, [&](const char *k, auto &f) { if (o.contains(k)) f = o[k].toVariant().value<std::decay_t<decltype(f)>>(); });
70
+ return c;
71
+ }
72
+
73
+ static QString xorB64(const QString &s, bool enc) // light obfuscation of secrets (NOT encryption)
74
+ {
75
+ static const QByteArray k = "ServerMonitor/obfuscation/v1";
76
+ QByteArray b = enc ? s.toUtf8() : QByteArray::fromBase64(s.toLatin1());
77
+ for (int i = 0; i < b.size(); ++i) b[i] = char(b[i] ^ k[i % k.size()]);
78
+ return enc ? QString(b.toBase64()) : QString::fromUtf8(b);
79
+ }
80
+
81
+ QJsonObject ServerConfig::toJson() const
82
+ {
83
+ QJsonObject o = save(*this);
84
+ QJsonArray rs;
85
+ for (const Rule &r : rules) rs << save(r);
86
+ o["transport"] = int(transport), o["password"] = xorB64(password, true), o["rules"] = rs, o["autopilot"] = save(autopilot);
87
+ return o;
88
+ }
89
+
90
+ ServerConfig ServerConfig::fromJson(const QJsonObject &o)
91
+ {
92
+ ServerConfig c = load<ServerConfig>(o);
93
+ c.autopilot = load<AutopilotConfig>(o["autopilot"].toObject());
94
+ if (o.contains("rules")) c.rules.clear();
95
+ for (const auto &v : o["rules"].toArray()) c.rules << load<Rule>(v.toObject());
96
+ for (Rule &r : c.rules)
97
+ if (r.id.isEmpty()) r.id = newId();
98
+ c.transport = o["transport"].toInt(1) == 0 ? Transport::Local : Transport::SSH;
99
+ c.password = xorB64(o["password"].toString(), false);
100
+ c.interval = qBound(1, c.interval, 300);
101
+ if (c.id.isEmpty()) c.id = newId();
102
+ return c;
103
+ }
104
+
105
+ QVector<Rule> ServerConfig::defaultRules()
106
+ {
107
+ QVector<Rule> rs;
108
+ for (auto [m, v, d, s] : {std::tuple{"cpu", 90, 60, "warning"}, {"mem", 90, 60, "warning"}, {"swap", 80, 120, "warning"},
109
+ {"disk", 90, 0, "critical"}, {"temp", 85, 30, "critical"}, {"load", 150, 120, "warning"}, {"failed", 0, 0, "warning"}}) {
110
+ Rule r;
111
+ r.id = newId(), r.metric = m, r.value = v, r.duration = d, r.severity = s;
112
+ rs << r;
113
+ }
114
+ return rs;
115
+ }
116
+ QString ServerConfig::newId() { return QUuid::createUuid().toString(QUuid::WithoutBraces).left(12); }
117
+ QString ServerConfig::address() const
118
+ {
119
+ if (transport == Transport::Local) return "this machine";
120
+ return (user.isEmpty() ? "" : user + "@") + host + (port != 22 ? QString(":%1").arg(port) : "");
121
+ }
122
+
123
+ double Metrics::gpuMax(bool t) const
124
+ {
125
+ double v = 0;
126
+ for (const GpuInfo &g : gpus) v = qMax(v, t ? g.temp : g.util);
127
+ return v;
128
+ }
Server Monitor(cqt-window)/src/core/Model.h ADDED
@@ -0,0 +1,118 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Data model: server config, rules, autopilot policy, parsed metrics, formatting.
2
+ #pragma once
3
+ #include "Platform.h"
4
+ #include <QHash>
5
+ #include <QJsonObject>
6
+ #include <QMap>
7
+ #include <QStringList>
8
+ #include <QVector>
9
+
10
+ namespace Fmt {
11
+ QString bytes(double b, int prec = 1);
12
+ inline QString rate(double b) { return bytes(b) + "/s"; }
13
+ inline QString pct(double p, int prec = 1) { return QString::number(p, 'f', prec) + "%"; }
14
+ inline QString temp(double c) { return QString::number(c, 'f', 0) + " °C"; }
15
+ QString count(double v);
16
+ QString duration(double s);
17
+ }
18
+
19
+ enum class Transport { Local, SSH };
20
+ inline QString transportName(Transport t) { return t == Transport::Local ? "Local" : "SSH"; }
21
+
22
+ const QVector<Def> &ruleMetrics();
23
+ QString defLabel(const QVector<Def> &d, const QString &k, bool unit = false);
24
+
25
+ // "When <metric> <op> <value> for <duration> s -> <action>(<arg>)"
26
+ struct Rule {
27
+ QString id, metric = "cpu", op = ">", action = "notify", arg, severity = "warning";
28
+ bool enabled = true;
29
+ double value = 90;
30
+ int duration = 60, cooldown = 300;
31
+ QString conditionText() const;
32
+ QString actionText() const;
33
+ };
34
+
35
+ // History-driven automatic control (evaluated by the Analyzer every minute).
36
+ struct AutopilotConfig {
37
+ bool enabled = true, dryRun = false, restartFailed = true, diskCleanup = false, anomalyAlerts = true;
38
+ int maxRestartsPerHour = 3, runawayMinutes = 10, diskForecastDays = 3;
39
+ double runawayCpu = 90, diskCleanupAt = 92, leakMemPressure = 90, anomalyZ = 3;
40
+ QString runawayMode = "renice", leakMode = "notify"; // none|renice|terminate, none|notify|terminate
41
+ QString diskCleanupCommand = P::cleanup;
42
+ };
43
+
44
+ struct ServerConfig {
45
+ QString id, name, group, host, user, keyFile, password, notes;
46
+ Transport transport = Transport::SSH;
47
+ int port = 22, interval = P::interval;
48
+ bool useSudo = false, enabled = true;
49
+ QVector<Rule> rules = defaultRules();
50
+ AutopilotConfig autopilot;
51
+ QString address() const;
52
+ QJsonObject toJson() const;
53
+ static ServerConfig fromJson(const QJsonObject &o);
54
+ static QVector<Rule> defaultRules();
55
+ static QString newId();
56
+ };
57
+
58
+ // ---- one parsed sample ------------------------------------------------------
59
+ struct CoreStat { double usage = 0, mhz = 0; };
60
+ struct MountInfo { QString device, type, mount; double total = 0, used = 0, avail = 0, pct = 0; };
61
+ struct DiskIO { QString name; double readBps = 0, writeBps = 0, readIops = 0, writeIops = 0, util = 0, totalRead = 0, totalWritten = 0; };
62
+ struct NetIf {
63
+ QString name, state;
64
+ int speed = -1;
65
+ bool virt = false;
66
+ double rxBps = 0, txBps = 0, rxPps = 0, txPps = 0, rxBytes = 0, txBytes = 0, errors = 0, drops = 0;
67
+ };
68
+ struct ProcInfo {
69
+ int pid = 0, ppid = 0, threads = 0, nice = 0;
70
+ QString name, user;
71
+ QChar state;
72
+ double cpu = 0, memPct = 0, rss = 0, vsz = 0, age = 0; // cpu: % of one core
73
+ };
74
+ struct ServiceInfo { QString unit, load, active, sub, description; };
75
+ struct TempSensor { QString name; double celsius = 0; };
76
+ struct GpuInfo { int index = 0; QString name; double util = 0, memUsed = 0, memTotal = 0, temp = 0, power = 0, fan = 0; };
77
+
78
+ struct Metrics {
79
+ bool valid = false;
80
+ qint64 timestamp = 0;
81
+ QString hostname, os, kernel, arch, cpuModel, virt;
82
+ int cpuCount = 0, loggedUsers = 0, procsRunning = 0, procsBlocked = 0, threadsTotal = 0, socketsUsed = 0;
83
+ int servicesFailed = 0, servicesRunning = 0;
84
+ double uptime = 0, load1 = 0, load5 = 0, load15 = 0;
85
+ double cpuUsage = 0, cpuUser = 0, cpuSystem = 0, cpuIowait = 0, cpuSteal = 0, cpuIrq = 0;
86
+ double ctxtPerSec = 0, intrPerSec = 0, forksPerSec = 0, avgMhz = 0;
87
+ double memTotal = 0, memFree = 0, memAvailable = 0, memUsed = 0, buffers = 0, cached = 0, shared = 0, slab = 0, dirty = 0;
88
+ double swapTotal = 0, swapUsed = 0, memPct = 0, swapPct = 0;
89
+ double diskReadBps = 0, diskWriteBps = 0, maxDiskPct = 0, maxDiskUtil = 0, netRxBps = 0, netTxBps = 0, maxTemp = 0;
90
+ QString fullestMount, busiestDisk;
91
+ QVector<CoreStat> cores;
92
+ QVector<MountInfo> mounts;
93
+ QVector<DiskIO> disks;
94
+ QVector<NetIf> nets;
95
+ QMap<QString, int> tcp; // ESTABLISHED -> n
96
+ QVector<ProcInfo> procs;
97
+ QVector<ServiceInfo> services;
98
+ QVector<TempSensor> temps;
99
+ QVector<GpuInfo> gpus;
100
+ double gpuMax(bool temp) const;
101
+ };
102
+
103
+ // Turns raw collector frames into Metrics; keeps counters for rates. process() is in Platform.cpp.
104
+ class MetricsEngine {
105
+ public:
106
+ Metrics process(const QByteArray &raw, qint64 nowMs);
107
+ void reset() { *this = MetricsEngine(); }
108
+
109
+ private:
110
+ double m_upt = 0;
111
+ QVector<QVector<double>> m_cpu;
112
+ QHash<QString, QVector<double>> m_ctr; // misc counters: "stat", "disk:sda", "net:eth0"
113
+ QHash<int, double> m_ticks;
114
+ QHash<QString, QString> m_info;
115
+ QHash<int, QString> m_users;
116
+ QVector<ServiceInfo> m_services;
117
+ QVector<GpuInfo> m_gpus;
118
+ };
Server Monitor(cqt-window)/src/core/Platform.cpp ADDED
@@ -0,0 +1,377 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Windows: PowerShell collector (CIM classes + .NET), its parser, and the control commands.
2
+ #include "Model.h"
3
+ #include <QRegularExpression>
4
+ #include <QSet>
5
+ #include <algorithm>
6
+ #include <cmath>
7
+
8
+ static const char *const kCollector = R"SMSCRIPT(
9
+ # Server Monitor collector for Windows (PowerShell 5.1+, ASCII only).
10
+ # The caller prepends "$iv = <seconds>; $once = $false". One frame per interval:
11
+ # "@@SNAP_BEGIN", "@@S <section>" + rows (key=value or |-separated), "@@SNAP_END".
12
+ $ErrorActionPreference = 'SilentlyContinue'
13
+ $ProgressPreference = 'SilentlyContinue'
14
+ [Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false
15
+ function Cim($class, $ns = 'root/cimv2') { Get-CimInstance -ClassName $class -Namespace $ns }
16
+ function Clean($s) { ("$s" -replace '[|\r\n]', ' ').Trim() }
17
+ $epoch = [DateTime]'1970-01-01'
18
+ $smi = Get-Command nvidia-smi.exe | Select-Object -First 1 -ExpandProperty Path
19
+ # Console.Out reports no error when the pipe is closed, so the collector also ends when its parent process is gone.
20
+ $parent = Get-Process -Id (Get-CimInstance Win32_Process -Filter "ProcessId = $PID").ParentProcessId
21
+ $n = 0
22
+ while ($true) {
23
+ $t0 = Get-Date
24
+ $out = New-Object System.Collections.Generic.List[string]
25
+ $out.Add('@@SNAP_BEGIN')
26
+ $os = Cim Win32_OperatingSystem
27
+ if ($n % 15 -eq 0) {
28
+ $cs = Cim Win32_ComputerSystem
29
+ $cpu = @(Cim Win32_Processor)[0]
30
+ $virt = Clean ($cs.Manufacturer + ' ' + $cs.Model)
31
+ $admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator)
32
+ $out.Add('@@S info')
33
+ $out.Add("hostname=$($cs.Name)")
34
+ $out.Add("os=$(Clean $os.Caption)")
35
+ $out.Add("kernel=$($os.Version)")
36
+ $out.Add("arch=$($os.OSArchitecture)")
37
+ $out.Add("cpumodel=$(Clean $cpu.Name)")
38
+ $out.Add("mhz=$($cpu.MaxClockSpeed)")
39
+ $out.Add("virt=$virt")
40
+ $out.Add("admin=$([int]$admin)")
41
+ if ($admin) {
42
+ $out.Add('@@S users')
43
+ Get-Process -IncludeUserName | ForEach-Object { $out.Add("$($_.Id)|$($_.UserName)") }
44
+ }
45
+ }
46
+ $out.Add('@@S os')
47
+ $out.Add("ts=$([long](([DateTime]::UtcNow - $epoch).TotalMilliseconds))")
48
+ $out.Add("uptime=$([long](((Get-Date) - $os.LastBootUpTime).TotalSeconds))")
49
+ $out.Add("memtotal=$([long]$os.TotalVisibleMemorySize * 1024)")
50
+ $out.Add("swaptotal=$([long]$os.SizeStoredInPagingFiles * 1024)")
51
+ $out.Add("swapfree=$([long]$os.FreeSpaceInPagingFiles * 1024)")
52
+ $out.Add('@@S cpu')
53
+ Cim Win32_PerfFormattedData_PerfOS_Processor | ForEach-Object {
54
+ $out.Add("$($_.Name)|$($_.PercentProcessorTime)|$($_.PercentUserTime)|$($_.PercentPrivilegedTime)|$([long]$_.PercentInterruptTime + [long]$_.PercentDPCTime)|$($_.InterruptsPersec)")
55
+ }
56
+ $sys = Cim Win32_PerfFormattedData_PerfOS_System
57
+ $out.Add('@@S sys')
58
+ $out.Add("queue=$($sys.ProcessorQueueLength)")
59
+ $out.Add("ctxt=$($sys.ContextSwitchesPersec)")
60
+ $out.Add("threads=$($sys.Threads)")
61
+ $pm = Cim Win32_PerfFormattedData_PerfOS_Memory
62
+ $out.Add('@@S mem')
63
+ $out.Add("avail=$($pm.AvailableBytes)")
64
+ $out.Add("free=$($pm.FreeAndZeroPageListBytes)")
65
+ $out.Add("standby=$([long]$pm.StandbyCacheCoreBytes + [long]$pm.StandbyCacheNormalPriorityBytes + [long]$pm.StandbyCacheReserveBytes)")
66
+ $out.Add("syscache=$($pm.CacheBytes)")
67
+ $out.Add("modified=$($pm.ModifiedPageListBytes)")
68
+ $out.Add("pool=$([long]$pm.PoolPagedBytes + [long]$pm.PoolNonpagedBytes)")
69
+ $out.Add("commit=$($pm.CommittedBytes)")
70
+ $out.Add("commitlimit=$($pm.CommitLimit)")
71
+ $out.Add("pages=$($pm.PagesPersec)")
72
+ $out.Add('@@S net')
73
+ [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | ForEach-Object {
74
+ $s = $null
75
+ $s = $_.GetIPStatistics()
76
+ if ($s) { $out.Add("$(Clean $_.Name)|$($_.OperationalStatus)|$([long]($_.Speed / 1000000))|$($_.NetworkInterfaceType)|$($s.BytesReceived)|$($s.BytesSent)|$($s.UnicastPacketsReceived)|$($s.UnicastPacketsSent)|$([long]$s.IncomingPacketsWithErrors + [long]$s.OutgoingPacketsWithErrors)|$([long]$s.IncomingPacketsDiscarded + [long]$s.OutgoingPacketsDiscarded)|$(Clean $_.Description)") }
77
+ }
78
+ $ip = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties()
79
+ $out.Add('@@S tcp')
80
+ $ip.GetActiveTcpConnections() | Group-Object State | ForEach-Object { $out.Add("$($_.Name) $($_.Count)") }
81
+ $out.Add("Listen $(@($ip.GetActiveTcpListeners()).Count)")
82
+ $out.Add('@@S disk')
83
+ Cim Win32_PerfFormattedData_PerfDisk_PhysicalDisk | Where-Object { $_.Name -ne '_Total' } | ForEach-Object {
84
+ $out.Add("$(Clean $_.Name)|$($_.DiskReadBytesPersec)|$($_.DiskWriteBytesPersec)|$($_.DiskReadsPersec)|$($_.DiskWritesPersec)|$($_.PercentIdleTime)")
85
+ }
86
+ $out.Add('@@S df')
87
+ [System.IO.DriveInfo]::GetDrives() | Where-Object { $_.IsReady -and $_.DriveType -eq 'Fixed' } | ForEach-Object {
88
+ $out.Add("$($_.Name)|$(Clean $_.VolumeLabel)|$($_.DriveFormat)|$($_.TotalSize)|$($_.AvailableFreeSpace)")
89
+ }
90
+ $sessions = @{}
91
+ $out.Add('@@S procs')
92
+ Cim Win32_Process | ForEach-Object {
93
+ $born = 0
94
+ if ($_.CreationDate) { $born = [long](($_.CreationDate.ToUniversalTime() - $epoch).TotalSeconds) }
95
+ if ($_.Name -eq 'explorer.exe') { $sessions[$_.SessionId] = 1 }
96
+ $out.Add("$($_.ProcessId)|$($_.ParentProcessId)|$([long]$_.KernelModeTime + [long]$_.UserModeTime)|$($_.Priority)|$($_.ThreadCount)|$born|$($_.VirtualSize)|$($_.WorkingSetSize)|$(Clean $_.Name)")
97
+ }
98
+ $out.Add('@@S sessions')
99
+ $out.Add("$($sessions.Count)")
100
+ if ($n % 5 -eq 0) {
101
+ $out.Add('@@S services')
102
+ Cim Win32_Service | ForEach-Object { $out.Add("$($_.Name)|$($_.State)|$($_.StartMode)|$($_.ExitCode)|$(Clean $_.DisplayName)") }
103
+ }
104
+ $out.Add('@@S thermal')
105
+ Cim MSAcpi_ThermalZoneTemperature 'root/wmi' | ForEach-Object { $out.Add("$(Clean $_.InstanceName)|$(($_.CurrentTemperature - 2732) / 10)") }
106
+ if ($smi -and $n % 3 -eq 0) {
107
+ $out.Add('@@S gpu')
108
+ & $smi '--query-gpu=index,name,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw,fan.speed' '--format=csv,noheader,nounits' | ForEach-Object { $out.Add("$_") }
109
+ }
110
+ $out.Add('@@SNAP_END')
111
+ try { [Console]::Out.Write(($out -join "`n") + "`n"); [Console]::Out.Flush() } catch { exit }
112
+ if ($once -or $parent.HasExited) { break }
113
+ $n++
114
+ $left = $iv * 1000 - ((Get-Date) - $t0).TotalMilliseconds
115
+ if ($left -gt 0) { Start-Sleep -Milliseconds ([int]$left) }
116
+ }
117
+ )SMSCRIPT";
118
+ static const char *const kFailed = "Get-CimInstance Win32_Service | Where-Object { $_.StartMode -eq 'Auto' -and $_.State -eq 'Stopped' -and $_.ExitCode -notin 0, 1077 }";
119
+ static const char *const kRestartFailed = R"PS( | ForEach-Object { "restart $($_.Name)"; Start-Service -Name $_.Name })PS";
120
+
121
+ namespace P {
122
+ const char *const prioLabel = "Priority", *const kernelPrefix = "build ",
123
+ *const sshHint = "Uses your system <b>ssh</b> client. The server needs the OpenSSH Server feature and PowerShell; nothing else is installed. "
124
+ "For key login, add your public key to the server's <code>authorized_keys</code>.",
125
+ *const cleanup = R"(Get-ChildItem $env:TEMP, "$env:windir\Temp" -Recurse -File -ErrorAction Ignore | Where-Object { $_.LastWriteTime -lt (Get-Date).AddDays(-7) } | Remove-Item -Force -ErrorAction Ignore; Clear-RecycleBin -Force -ErrorAction Ignore)";
126
+ const bool sudo = false, posixCpu = false;
127
+ const int interval = 3, normalPrio = 8;
128
+
129
+ // PowerShell runs whatever script arrives on stdin: the encoded command is iex (@($input) -join [char]10)
130
+ QStringList shell(int)
131
+ {
132
+ return {"powershell", "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-OutputFormat", "Text", "-EncodedCommand",
133
+ "aQBlAHgAIAAoAEAAKAAkAGkAbgBwAHUAdAApACAALQBqAG8AaQBuACAAWwBjAGgAYQByAF0AMQAwACkA"};
134
+ }
135
+ QByteArray collector(int iv) { return QString("$iv = %1; $once = $false\n").arg(iv).toUtf8() + kCollector; }
136
+ QByteArray wrap(const QString &cmd, bool) // no sudo on Windows: run the app elevated for privileged actions
137
+ {
138
+ return ("[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false; $ProgressPreference = 'SilentlyContinue'; $Error.Clear(); $global:LASTEXITCODE = 0\n& {\n" +
139
+ cmd + "\n} 2>&1 | Out-String -Width 250 -Stream\nif ($LASTEXITCODE) { exit $LASTEXITCODE }\n"
140
+ "if ($Error | Where-Object { $_.FullyQualifiedErrorId -notlike 'NativeCommandError*' }) { exit 1 }; exit 0\n").toUtf8(); // stderr text of a program is not a failure
141
+ }
142
+ QString quote(QString s) { return "'" + s.replace("'", "''") + "'"; }
143
+ QString command(const QString &action, const QString &arg)
144
+ {
145
+ const QString n = QString::number(arg.toInt());
146
+ return QHash<QString, QString>{{"kill_pid", "Stop-Process -Id " + n + " -Force"}, {"renice", "(Get-Process -Id " + n + ").PriorityClass = 'Idle'"},
147
+ {"restart_service", "Restart-Service -Name " + quote(arg) + " -Force"}, {"restart_failed", QString(kFailed) + kRestartFailed}}.value(action);
148
+ }
149
+ QString serviceLogs(const QString &unit, int lines)
150
+ {
151
+ return QString(R"($s = Get-CimInstance Win32_Service | Where-Object Name -eq %1; $s | Format-List Name, DisplayName, State, StartMode, ExitCode, ProcessId, PathName; )"
152
+ R"(Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Service Control Manager' } -MaxEvents 3000 -ErrorAction Ignore | )"
153
+ R"(Where-Object { $_.Message -like ('*' + $s.DisplayName + '*') } | Select-Object -First %2 | Format-Table TimeCreated, LevelDisplayName, Message -Wrap)")
154
+ .arg(quote(unit)).arg(lines);
155
+ }
156
+ QString power(bool reboot) { return reboot ? "shutdown /r /t 5" : "shutdown /s /t 5"; }
157
+ bool isProtected(int pid, int, double rss, const QString &name)
158
+ {
159
+ static const QSet<QString> system = {"System", "Registry", "Memory Compression", "smss.exe", "csrss.exe", "wininit.exe", "winlogon.exe", "services.exe",
160
+ "lsass.exe", "svchost.exe", "sshd.exe", "dwm.exe"};
161
+ return pid <= 4 || rss <= 0 || system.contains(name);
162
+ }
163
+
164
+ const QVector<Def> &ruleActions()
165
+ {
166
+ static const QVector<Def> d = {{"notify", "Notify only", ""}, {"restart_failed", "Restart failed services", ""}, {"restart_service", "Restart a service", "Spooler"},
167
+ {"kill_top_cpu", "Terminate top CPU process", ""}, {"kill_top_mem", "Terminate top memory process", ""}, {"command", "Run a command", "Clear-DnsClientCache"}};
168
+ return d;
169
+ }
170
+ const QVector<Cmd> &procActions()
171
+ {
172
+ static const QVector<Cmd> d = {{"End task", "taskkill /PID %1"}, {"Kill", "taskkill /F /PID %1", true}, {"Kill tree", "taskkill /F /T /PID %1", true}};
173
+ return d;
174
+ }
175
+ const QVector<Cmd> &priorities()
176
+ {
177
+ static const QVector<Cmd> d = [] {
178
+ QVector<Cmd> v;
179
+ for (const char *p : {"Idle", "BelowNormal", "Normal", "AboveNormal", "High"}) v << Cmd{p, QString("(Get-Process -Id %1).PriorityClass = '") + p + "'"};
180
+ return v;
181
+ }();
182
+ return d;
183
+ }
184
+ const QVector<Cmd> &serviceActions()
185
+ {
186
+ static const QVector<Cmd> d = {{"Start", "Start-Service -Name %1", false, false}, {"Stop", "Stop-Service -Name %1 -Force", true}, {"Restart", "Restart-Service -Name %1 -Force"},
187
+ {"Enable", "Set-Service -Name %1 -StartupType Automatic", false, false}, {"Disable", "Set-Service -Name %1 -StartupType Disabled", true}};
188
+ return d;
189
+ }
190
+ const QVector<Cmd> &diagnostics()
191
+ {
192
+ static const QVector<Cmd> d = {
193
+ {"Disk usage", R"(Get-PSDrive -PSProvider FileSystem | Format-Table Name, @{ n = 'Used GB'; e = { [math]::Round($_.Used / 1GB, 1) } }, @{ n = 'Free GB'; e = { [math]::Round($_.Free / 1GB, 1) } }, Root)"},
194
+ {"Largest folders in C:\\", R"(Get-ChildItem C:\ -Directory -Force -ErrorAction Ignore | ForEach-Object { [pscustomobject]@{ Folder = $_.FullName; GB = [math]::Round((Get-ChildItem $_.FullName -Recurse -File -Force -ErrorAction Ignore | Measure-Object Length -Sum).Sum / 1GB, 2) } } | Sort-Object GB -Descending | Select-Object -First 15)"},
195
+ {"Memory", "Get-CimInstance Win32_OperatingSystem | Format-List TotalVisibleMemorySize, FreePhysicalMemory, TotalVirtualMemorySize, FreeVirtualMemory"},
196
+ {"Top CPU processes", "Get-Process | Sort-Object CPU -Descending | Select-Object -First 20 Id, ProcessName, CPU, @{ n = 'MemMB'; e = { [int]($_.WorkingSet64 / 1MB) } }, StartTime"},
197
+ {"Listening ports", "Get-NetTCPConnection -State Listen | Sort-Object LocalPort | Format-Table LocalAddress, LocalPort, OwningProcess"},
198
+ {"System errors", "Get-WinEvent -FilterHashtable @{ LogName = 'System'; Level = 1, 2 } -MaxEvents 40 | Format-Table TimeCreated, ProviderName, Message -Wrap"},
199
+ {"Application errors", "Get-WinEvent -FilterHashtable @{ LogName = 'Application'; Level = 1, 2 } -MaxEvents 40 | Format-Table TimeCreated, ProviderName, Message -Wrap"},
200
+ {"Failed services", QString(kFailed) + " | Format-Table Name, ExitCode, DisplayName"},
201
+ {"Logged-in users", "quser"},
202
+ {"Last boots", "Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = 6005, 6006, 1074 } -MaxEvents 15 | Format-Table TimeCreated, Id, Message -Wrap"}};
203
+ return d;
204
+ }
205
+ const QVector<Cmd> &systemActions()
206
+ {
207
+ static const QVector<Cmd> d = {{"Clean temp files", cleanup}, {"Flush DNS cache", "Clear-DnsClientCache; 'done'"}, {"Restart failed services", QString(kFailed) + kRestartFailed},
208
+ {"Reboot", "shutdown /r /t 5", true}, {"Shut down", "shutdown /s /t 5", true}};
209
+ return d;
210
+ }
211
+ } // namespace P
212
+
213
+ // ---- collector frame parser: rows are key=value or |-separated; most values are already rates ----------
214
+ Metrics MetricsEngine::process(const QByteArray &raw, qint64 now)
215
+ {
216
+ QHash<QString, QStringList> sec;
217
+ QStringList *cur = nullptr;
218
+ for (const QByteArray &line : raw.split('\n')) {
219
+ const QString l = QString::fromUtf8(line).trimmed();
220
+ if (l.startsWith("@@S ")) cur = &sec[l.mid(4)];
221
+ else if (cur && !l.isEmpty() && !l.startsWith("@@")) cur->append(l);
222
+ }
223
+ auto kv = [&](const char *k) {
224
+ QHash<QString, QString> h;
225
+ for (const QString &l : sec.value(k))
226
+ if (const int e = l.indexOf('='); e > 0) h[l.left(e)] = l.mid(e + 1);
227
+ return h;
228
+ };
229
+ auto rows = [&](const char *k, int minFields) {
230
+ QVector<QStringList> r;
231
+ for (const QString &l : sec.value(k))
232
+ if (const QStringList f = l.split('|'); f.size() >= minFields) r << f;
233
+ return r;
234
+ };
235
+ Metrics m;
236
+ m.timestamp = now;
237
+ if (sec.contains("info")) m_info = kv("info");
238
+ if (sec.contains("users")) {
239
+ m_users.clear();
240
+ for (const auto &f : rows("users", 2))
241
+ if (!f[1].isEmpty()) m_users[f[0].toInt()] = f[1];
242
+ }
243
+ m.hostname = m_info["hostname"], m.os = m_info["os"], m.kernel = m_info["kernel"], m.arch = m_info["arch"];
244
+ m.cpuModel = m_info["cpumodel"], m.virt = m_info["virt"];
245
+ const auto os = kv("os");
246
+ const double ts = os["ts"].toDouble() / 1000; // collector clock, seconds
247
+ m.uptime = os["uptime"].toDouble();
248
+ if (m.uptime <= 0 || ts <= 0) return m;
249
+ const double dt = m_upt > 0 ? ts - m_upt : 0;
250
+ const bool rates = dt > 0.05;
251
+ QHash<QString, QVector<double>> next;
252
+ auto delta = [&](const QString &key, const QVector<double> &v) { // per-second rates of a counter vector
253
+ QVector<double> d(v.size(), 0.0);
254
+ const auto p = m_ctr.value(key);
255
+ if (rates && p.size() == v.size())
256
+ for (int i = 0; i < v.size(); ++i) d[i] = qMax(0.0, (v[i] - p[i]) / dt);
257
+ next[key] = v;
258
+ return d;
259
+ };
260
+ auto pct = [](const QString &s) { return qBound(0.0, s.toDouble(), 100.0); };
261
+
262
+ // CPU: privileged time includes interrupts + DPCs; show them apart
263
+ QMap<int, CoreStat> cores;
264
+ m.avgMhz = m_info["mhz"].toDouble();
265
+ for (const auto &f : rows("cpu", 5)) {
266
+ if (f[0] != "_Total") { cores[f[0].toInt()] = {pct(f[1]), m.avgMhz}; continue; }
267
+ m.cpuUsage = pct(f[1]), m.cpuUser = pct(f[2]), m.cpuIrq = pct(f[4]), m.cpuSystem = qMax(0.0, pct(f[3]) - m.cpuIrq), m.intrPerSec = f.value(5).toDouble();
268
+ }
269
+ m.cores = cores.values().toVector();
270
+ m.cpuCount = qMax(1, m.cores.size());
271
+
272
+ // load average with the Unix meaning: running + waiting threads, smoothed over 1 / 5 / 15 minutes
273
+ const auto sys = kv("sys");
274
+ const double queue = sys["queue"].toDouble(), inst = m.cpuUsage / 100 * m.cpuCount + queue, spans[3] = {60, 300, 900};
275
+ QVector<double> load = m_ctr.value("load", {inst, inst, inst});
276
+ for (int i = 0; i < 3; ++i) load[i] += (inst - load[i]) * (1 - std::exp(-qMax(0.0, dt) / spans[i])); // dt < 0: the clock was set back
277
+ next["load"] = load;
278
+ m.load1 = load[0], m.load5 = load[1], m.load15 = load[2];
279
+ m.ctxtPerSec = sys["ctxt"].toDouble(), m.procsRunning = qRound(m.cpuUsage / 100 * m.cpuCount), m.procsBlocked = int(queue);
280
+
281
+ // memory: standby pages are the file cache, the page file is swap
282
+ const auto mem = kv("mem");
283
+ m.memTotal = os["memtotal"].toDouble(), m.memAvailable = mem["avail"].toDouble(), m.memFree = mem["free"].toDouble();
284
+ m.cached = mem["standby"].toDouble() + mem["syscache"].toDouble(), m.slab = mem["pool"].toDouble(), m.dirty = mem["modified"].toDouble();
285
+ m.memUsed = qMax(0.0, m.memTotal - m.memAvailable), m.swapTotal = os["swaptotal"].toDouble(), m.swapUsed = qMax(0.0, m.swapTotal - os["swapfree"].toDouble());
286
+ m.memPct = m.memTotal > 0 ? m.memUsed * 100 / m.memTotal : 0;
287
+ m.swapPct = m.swapTotal > 0 ? m.swapUsed * 100 / m.swapTotal : 0;
288
+
289
+ // network: a VM's own NIC ("Microsoft Hyper-V Network Adapter") counts as physical, host-side virtual switches do not
290
+ static const QRegularExpression virt("virtual ethernet|virtualbox|vmware virtual|vethernet|loopback|pseudo|tap-|bluetooth|wan miniport|wsl|docker", QRegularExpression::CaseInsensitiveOption);
291
+ for (const auto &f : rows("net", 10)) {
292
+ NetIf n;
293
+ n.name = f[0], n.state = f[1].toLower(), n.speed = f[2].toInt() > 0 ? f[2].toInt() : -1;
294
+ n.virt = f[3] == "Loopback" || f[3] == "Tunnel" || virt.match(f[0] + " " + f.value(10)).hasMatch();
295
+ n.rxBytes = f[4].toDouble(), n.txBytes = f[5].toDouble(), n.errors = f[8].toDouble(), n.drops = f[9].toDouble();
296
+ const auto d = delta("net:" + n.name, {n.rxBytes, n.txBytes, f[6].toDouble(), f[7].toDouble()});
297
+ n.rxBps = d[0], n.txBps = d[1], n.rxPps = d[2], n.txPps = d[3];
298
+ if (!n.virt) m.netRxBps += n.rxBps, m.netTxBps += n.txBps;
299
+ m.nets << n;
300
+ }
301
+ std::sort(m.nets.begin(), m.nets.end(), [](const NetIf &a, const NetIf &b) { return a.virt != b.virt ? !a.virt : a.name < b.name; });
302
+ static const QHash<QString, QString> tcpNames = {{"Established", "ESTABLISHED"}, {"Listen", "LISTEN"}, {"TimeWait", "TIME_WAIT"}, {"CloseWait", "CLOSE_WAIT"}};
303
+ for (const QString &l : sec.value("tcp")) {
304
+ const QStringList f = l.split(' ');
305
+ m.tcp[tcpNames.value(f[0], f[0].toUpper())] += f.value(1).toInt(), m.socketsUsed += f.value(1).toInt();
306
+ }
307
+
308
+ // disks and volumes
309
+ for (const auto &f : rows("disk", 6)) {
310
+ DiskIO d;
311
+ d.name = f[0], d.readBps = f[1].toDouble(), d.writeBps = f[2].toDouble(), d.readIops = f[3].toDouble(), d.writeIops = f[4].toDouble();
312
+ d.util = f[5].isEmpty() ? 0 : 100 - pct(f[5]); // field = idle %
313
+ m.diskReadBps += d.readBps, m.diskWriteBps += d.writeBps;
314
+ if (d.util >= m.maxDiskUtil) m.maxDiskUtil = d.util, m.busiestDisk = d.name;
315
+ m.disks << d;
316
+ }
317
+ for (const auto &f : rows("df", 5)) {
318
+ MountInfo mt;
319
+ mt.mount = f[0], mt.device = f[1], mt.type = f[2], mt.total = f[3].toDouble(), mt.avail = f[4].toDouble(), mt.used = mt.total - mt.avail;
320
+ if (mt.total <= 0) continue;
321
+ mt.pct = mt.used * 100 / mt.total;
322
+ if (mt.pct >= m.maxDiskPct) m.maxDiskPct = mt.pct, m.fullestMount = mt.mount;
323
+ m.mounts << mt;
324
+ }
325
+
326
+ // processes: "pid|ppid|cpuTime (100 ns)|priority|threads|created (unix s)|vsz|rss|name"
327
+ QHash<int, double> ticks;
328
+ int fresh = 0;
329
+ for (const auto &f : rows("procs", 9)) {
330
+ ProcInfo p;
331
+ if ((p.pid = f[0].toInt()) <= 0) continue; // 0 = idle process
332
+ const double born = f[5].toDouble();
333
+ p.ppid = f[1].toInt(), p.nice = f[3].toInt(), p.threads = f[4].toInt(), p.age = born > 0 ? qMax(0.0, ts - born) : 0;
334
+ p.vsz = f[6].toDouble(), p.rss = f[7].toDouble(), p.name = f.mid(8).join('|');
335
+ ticks[p.pid] = f[2].toDouble();
336
+ if (!m_ticks.contains(p.pid)) ++fresh;
337
+ else if (rates) p.cpu = qBound(0.0, (ticks[p.pid] - m_ticks[p.pid]) / 1e7 / dt * 100, 100.0 * m.cpuCount);
338
+ p.state = p.cpu > 0.5 ? 'R' : 'S';
339
+ p.memPct = m.memTotal > 0 ? p.rss * 100 / m.memTotal : 0;
340
+ p.user = m_users.value(p.pid, "—");
341
+ m.threadsTotal += p.threads;
342
+ m.procs << p;
343
+ }
344
+ m.forksPerSec = rates ? fresh / dt : 0;
345
+ std::sort(m.procs.begin(), m.procs.end(), [](const ProcInfo &a, const ProcInfo &b) { return a.cpu != b.cpu ? a.cpu > b.cpu : a.rss > b.rss; });
346
+ m.loggedUsers = sec.value("sessions").value(0).toInt();
347
+
348
+ // services / GPUs arrive every few samples: keep the last list. "Failed" = automatic, stopped, with an error exit code
349
+ if (sec.contains("services")) {
350
+ m_services.clear();
351
+ for (const auto &f : rows("services", 5)) {
352
+ const bool failed = f[2] == "Auto" && f[1] == "Stopped" && f[3].toInt() != 0 && f[3].toInt() != 1077;
353
+ m_services << ServiceInfo{f[0], f[2], failed ? "failed" : f[1] == "Running" ? "active" : "inactive", f[1].toLower(), f.mid(4).join('|')};
354
+ }
355
+ }
356
+ m.services = m_services;
357
+ for (const auto &s : m.services) m.servicesFailed += s.active == "failed", m.servicesRunning += s.sub == "running";
358
+ if (sec.contains("gpu")) {
359
+ m_gpus.clear();
360
+ for (const QString &l : sec.value("gpu")) {
361
+ const QStringList f = l.split(',');
362
+ auto n = [&](int i) { return f[i].trimmed().toDouble(); };
363
+ if (f.size() >= 8) m_gpus << GpuInfo{int(n(0)), f[1].trimmed(), n(2), n(3), n(4), n(5), n(6), n(7)};
364
+ }
365
+ }
366
+ m.gpus = m_gpus;
367
+ QSet<QString> tn;
368
+ for (const auto &f : rows("thermal", 2)) {
369
+ TempSensor t{f[0], f[1].toDouble()};
370
+ if (t.celsius <= 0 || t.celsius > 150 || tn.contains(t.name)) continue;
371
+ tn << t.name, m.temps << t, m.maxTemp = qMax(m.maxTemp, t.celsius);
372
+ }
373
+
374
+ m_ctr = next, m_ticks = ticks, m_upt = ts;
375
+ m.valid = rates; // the first sample has no rates yet
376
+ return m;
377
+ }
Server Monitor(cqt-window)/src/core/Platform.h ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Everything that depends on the operating system of the monitored machines: how to start a shell, the
2
+ // collector script with its parser (MetricsEngine::process), and the control commands. Linux and Windows
3
+ // editions differ only in Platform.cpp.
4
+ #pragma once
5
+ #include <QStringList>
6
+ #include <QVector>
7
+
8
+ struct Def { QString key, label, unit; }; // rule metric / action catalogue
9
+ struct Cmd { QString label, cmd; bool danger = false, confirm = true, button = true; }; // cmd: %1 = pid or quoted name
10
+
11
+ namespace P {
12
+ extern const char *const prioLabel, *const kernelPrefix, *const sshHint, *const cleanup; // cleanup: default disk cleanup command
13
+ extern const bool sudo, posixCpu; // "sudo -n" exists; CPU time has I/O wait + steal
14
+ extern const int interval, normalPrio; // default sample interval (s); priority value of an ordinary process
15
+ QStringList shell(int interval = 0); // argv of a shell that runs a script from stdin (interval > 0: collector arguments)
16
+ QByteArray collector(int interval); // stdin for the collector
17
+ QByteArray wrap(const QString &cmd, bool sudo); // stdin for a one-shot command
18
+ QString quote(QString s); // shell quoting
19
+ QString command(const QString &action, const QString &arg); // kill_pid | renice | restart_service | restart_failed | drop_caches
20
+ QString serviceLogs(const QString &unit, int lines);
21
+ QString power(bool reboot);
22
+ bool isProtected(int pid, int ppid, double rss, const QString &name); // never killed automatically, no leak / runaway findings
23
+ const QVector<Def> &ruleActions(); // unit = argument hint ("" = none)
24
+ const QVector<Cmd> &procActions(), &priorities(), &serviceActions(), &diagnostics(), &systemActions();
25
+ }
Server Monitor(cqt-window)/src/core/Session.cpp ADDED
@@ -0,0 +1,448 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "Session.h"
2
+ #include <QCoreApplication>
3
+ #include <QDir>
4
+ #include <QFile>
5
+ #include <QJsonArray>
6
+ #include <QJsonDocument>
7
+ #include <QSaveFile>
8
+ #include <QStandardPaths>
9
+ #include <QTextStream>
10
+ #include <utility>
11
+
12
+ // ---- Link ---------------------------------------------------------------------------------
13
+ Link::Link(const ServerConfig &c, QObject *parent) : QObject(parent), m_c(c) {}
14
+ Link::~Link()
15
+ {
16
+ for (QProcess *p : findChildren<QProcess *>()) {
17
+ p->disconnect(this);
18
+ if (p->state() != QProcess::NotRunning) p->kill(), p->waitForFinished(500);
19
+ }
20
+ }
21
+
22
+ QProcess *Link::spawn(const QStringList &shell)
23
+ {
24
+ auto *p = new QProcess(this);
25
+ QStringList a;
26
+ if (m_c.transport == Transport::Local) {
27
+ p->setProgram(shell[0]), p->setArguments(shell.mid(1));
28
+ } else {
29
+ for (const char *o : {"ConnectTimeout=10", "ServerAliveInterval=10", "ServerAliveCountMax=3", "StrictHostKeyChecking=accept-new", "LogLevel=ERROR"}) a << "-o" << o;
30
+ auto env = QProcessEnvironment::systemEnvironment();
31
+ if (m_c.password.isEmpty()) a << "-o" << "BatchMode=yes";
32
+ else { // our own executable answers ssh's password prompt (see main.cpp)
33
+ a << "-o" << "NumberOfPasswordPrompts=1";
34
+ env.insert("SSH_ASKPASS", QDir::toNativeSeparators(QCoreApplication::applicationFilePath()));
35
+ env.insert("SSH_ASKPASS_REQUIRE", "force");
36
+ env.insert("SERVERMONITOR_ASKPASS", m_c.password);
37
+ if (!env.contains("DISPLAY")) env.insert("DISPLAY", ":0");
38
+ }
39
+ p->setProcessEnvironment(env);
40
+ if (!m_c.keyFile.isEmpty()) a << "-i" << (m_c.keyFile.startsWith("~/") ? QDir::homePath() + m_c.keyFile.mid(1) : m_c.keyFile);
41
+ if (m_c.port != 22) a << "-p" << QString::number(m_c.port);
42
+ p->setProgram("ssh"), p->setArguments(a << "-T" << (m_c.user.isEmpty() ? m_c.host : m_c.user + "@" + m_c.host) << shell.join(' '));
43
+ }
44
+ return p;
45
+ }
46
+ // Started only after the signals are connected: on Windows a failed start is reported inside start().
47
+ static void feed(QProcess *p, const QByteArray &input)
48
+ {
49
+ p->start();
50
+ if (p->state() != QProcess::NotRunning) p->write(input), p->closeWriteChannel();
51
+ }
52
+
53
+ void Link::start()
54
+ {
55
+ QProcess *p = spawn(P::shell(m_c.interval));
56
+ connect(p, &QProcess::readyReadStandardOutput, this, [this, p] {
57
+ m_buf += p->readAllStandardOutput();
58
+ for (int end; (end = m_buf.indexOf("@@SNAP_END")) >= 0;) {
59
+ const int begin = m_buf.lastIndexOf("@@SNAP_BEGIN", end);
60
+ if (begin >= 0) emit snapshot(m_buf.mid(begin, end - begin));
61
+ m_buf.remove(0, end + 10);
62
+ }
63
+ if (m_buf.size() > 8 << 20) m_buf.clear();
64
+ });
65
+ connect(p, &QProcess::readyReadStandardError, this, [this, p] { m_err = (m_err + p->readAllStandardError()).right(4096); });
66
+ connect(p, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, [this](int code) {
67
+ const QStringList l = QString(m_err).split('\n', Qt::SkipEmptyParts);
68
+ emit disconnected(l.isEmpty() ? QString("connection closed (exit code %1)").arg(code) : l.last());
69
+ });
70
+ connect(p, &QProcess::errorOccurred, this, [this, p](QProcess::ProcessError e) {
71
+ if (e == QProcess::FailedToStart) emit disconnected("cannot start " + p->program() + ": " + p->errorString());
72
+ });
73
+ feed(p, P::collector(m_c.interval));
74
+ }
75
+
76
+ int Link::exec(const QByteArray &input, int timeoutMs)
77
+ {
78
+ const int id = m_next++;
79
+ QProcess *p = spawn(P::shell());
80
+ p->setProcessChannelMode(QProcess::MergedChannels);
81
+ QTimer::singleShot(timeoutMs, p, [p] { p->kill(); });
82
+ connect(p, QOverload<int, QProcess::ExitStatus>::of(&QProcess::finished), this, [this, p, id](int code, QProcess::ExitStatus st) {
83
+ emit execFinished(id, st == QProcess::CrashExit ? -1 : code, p->readAll() + (st == QProcess::CrashExit ? "\n[killed or timed out]" : ""));
84
+ p->deleteLater();
85
+ });
86
+ connect(p, &QProcess::errorOccurred, this, [this, p, id](QProcess::ProcessError e) {
87
+ if (e == QProcess::FailedToStart) emit execFinished(id, -1, p->errorString()), p->deleteLater();
88
+ }, Qt::QueuedConnection); // queued: the caller has to learn the id first
89
+ feed(p, input);
90
+ return id;
91
+ }
92
+
93
+ // ---- live history -----------------------------------------------------------------------
94
+ QString statusName(Status s) { return QStringList{"Disabled", "Connecting", "Online", "Offline"}.value(int(s)); }
95
+
96
+ void Live::push(const Metrics &m)
97
+ {
98
+ const int cap = 1800, n = t.size() + 1;
99
+ auto add = [&](QVector<double> &v, double x) {
100
+ if (v.size() < n - 1) v.insert(0, n - 1 - v.size(), 0.0); // align series that appeared later
101
+ v << x;
102
+ if (v.size() > cap) v.remove(0, v.size() - cap);
103
+ };
104
+ t << m.timestamp;
105
+ if (t.size() > cap) t.remove(0, t.size() - cap);
106
+ const double vals[N] = {m.cpuUsage, m.cpuUser, m.cpuSystem + m.cpuIrq, m.cpuIowait, m.cpuSteal, m.memPct,
107
+ m.memTotal > 0 ? (m.cached + m.buffers) * 100 / m.memTotal : 0, m.swapPct, m.netRxBps, m.netTxBps,
108
+ m.diskReadBps, m.diskWriteBps, m.load1};
109
+ for (int i = 0; i < N; ++i) add(s[i], vals[i]);
110
+ for (const NetIf &i : m.nets) add(ifRx[i.name], i.rxBps), add(ifTx[i.name], i.txBps);
111
+ }
112
+
113
+ // ---- session ----------------------------------------------------------------------------
114
+ ServerSession::ServerSession(const ServerConfig &c, QObject *parent) : QObject(parent), m_cfg(c), m_store(ServerManager::configDir() + "/history/" + c.id)
115
+ {
116
+ m_retry.setSingleShot(true), m_watchdog.setSingleShot(true);
117
+ connect(&m_retry, &QTimer::timeout, this, &ServerSession::start);
118
+ connect(&m_watchdog, &QTimer::timeout, this, [this] { onLost("no data received (timeout)"); });
119
+ connect(&m_analysisTimer, &QTimer::timeout, this, &ServerSession::analyzeNow);
120
+ connect(&m_offlineTick, &QTimer::timeout, this, [this] { // downtime -> availability: one sample per interval, like uptime
121
+ if (m_status == Status::Offline || (m_status == Status::Connecting && m_retries)) record(false);
122
+ });
123
+ m_analysisTimer.start(60000), m_offlineTick.start(c.interval * 1000);
124
+ QTimer::singleShot(3000, this, &ServerSession::analyzeNow);
125
+ }
126
+ ServerSession::~ServerSession() { stop(); }
127
+
128
+ void ServerSession::setConfig(const ServerConfig &c)
129
+ {
130
+ const bool reconnect = c.transport != m_cfg.transport || c.host != m_cfg.host || c.port != m_cfg.port || c.user != m_cfg.user ||
131
+ c.keyFile != m_cfg.keyFile || c.password != m_cfg.password || c.interval != m_cfg.interval || c.enabled != m_cfg.enabled;
132
+ m_cfg = c, m_offlineTick.setInterval(c.interval * 1000);
133
+ if (reconnect) m_live = Live(), m_m = Metrics(), m_procs.clear(), m_svcs.clear(), c.enabled ? start() : stop(); // may be another machine now
134
+ emit updated();
135
+ }
136
+
137
+ void ServerSession::drop(const QString &why)
138
+ {
139
+ if (m_link) m_link->disconnect(this), m_link->deleteLater();
140
+ m_link = nullptr;
141
+ for (const Done &d : std::exchange(m_pending, {})) d(-1, why);
142
+ }
143
+
144
+ void ServerSession::start()
145
+ {
146
+ drop("connection restarted");
147
+ m_retry.stop();
148
+ if (!m_cfg.enabled) return setStatus(Status::Disabled);
149
+ m_engine.reset(), m_m.valid = false; // online() only again with a fresh sample
150
+ m_link = new Link(m_cfg, this);
151
+ connect(m_link, &Link::snapshot, this, &ServerSession::onFrame);
152
+ connect(m_link, &Link::disconnected, this, &ServerSession::onLost);
153
+ connect(m_link, &Link::execFinished, this, [this](int id, int code, const QString &out) { if (Done d = m_pending.take(id)) d(code, out); });
154
+ setStatus(Status::Connecting), m_watchdog.start(25000), m_link->start();
155
+ }
156
+
157
+ void ServerSession::stop()
158
+ {
159
+ m_retry.stop(), m_watchdog.stop(), drop("connection stopped");
160
+ setStatus(m_cfg.enabled ? Status::Offline : Status::Disabled);
161
+ }
162
+
163
+ void ServerSession::setStatus(Status s, const QString &err)
164
+ {
165
+ if (!err.isEmpty() || s == Status::Online) m_err = err;
166
+ if (s != m_status) m_status = s, emit updated();
167
+ }
168
+
169
+ void ServerSession::onFrame(const QByteArray &raw)
170
+ {
171
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
172
+ m_watchdog.start(qMax(15, m_cfg.interval * 5 + 10) * 1000);
173
+ Metrics m = m_engine.process(raw, now);
174
+ if (m.uptime <= 0) return;
175
+ if (m_status != Status::Online) {
176
+ m_retries = 0;
177
+ if (std::exchange(m_offlineAlerted, false)) raise("resolved", "Server is back online");
178
+ setStatus(Status::Online);
179
+ }
180
+ if (!m.valid || m_paused) return; // first sample has no rates yet
181
+ if (m.uptime < m_m.uptime) m_procs.clear(); // rebooted: PIDs start again, old trends would be blamed on new processes
182
+ const bool first = !m_m.valid; // first sample of this connection: analyze at once, the last analysis saw "unreachable"
183
+ m_m = m, m_live.push(m), record(true), track(now), evaluateRules();
184
+ if (first) analyzeNow();
185
+ emit updated();
186
+ }
187
+
188
+ void ServerSession::onLost(const QString &why)
189
+ {
190
+ m_watchdog.stop(), drop("connection lost: " + why);
191
+ const bool was = m_status == Status::Online;
192
+ setStatus(Status::Offline, why);
193
+ if ((was || m_retries == 1) && !m_offlineAlerted) raise("critical", "Server is unreachable: " + why), m_offlineAlerted = true;
194
+ if (m_cfg.enabled) m_retry.start(QVector<int>{3, 5, 10, 20, 30, 60}[qMin(m_retries++, 5)] * 1000); // back-off
195
+ }
196
+
197
+ void ServerSession::exec(const QString &cmd, bool privileged, Done done, int timeoutMs)
198
+ {
199
+ if (!m_link || m_status != Status::Online) {
200
+ if (done) QTimer::singleShot(0, this, [done] { done(-1, "server is not connected"); });
201
+ return;
202
+ }
203
+ const int id = m_link->exec(P::wrap(cmd, privileged && m_cfg.useSudo), timeoutMs);
204
+ if (done) m_pending[id] = done;
205
+ }
206
+
207
+ double ServerSession::metricValue(const QString &k) const
208
+ {
209
+ const Metrics &m = m_m;
210
+ const QHash<QString, double> v = {{"cpu", m.cpuUsage}, {"iowait", m.cpuIowait}, {"load", m.load1 * 100 / qMax(1, m.cpuCount)},
211
+ {"mem", m.memPct}, {"swap", m.swapPct}, {"disk", m.maxDiskPct}, {"diskio", m.maxDiskUtil}, {"temp", m.maxTemp},
212
+ {"rx", m.netRxBps / 1e6}, {"tx", m.netTxBps / 1e6}, {"failed", double(m.servicesFailed)}, {"procs", double(m.procs.size())},
213
+ {"gpu", m.gpuMax(false)}, {"gputemp", m.gpuMax(true)}};
214
+ return v.value(k);
215
+ }
216
+
217
+ QStringList ServerSession::activeAlerts() const
218
+ {
219
+ QStringList out;
220
+ if (m_status == Status::Offline) out << "Unreachable: " + m_err;
221
+ for (const Rule &r : m_cfg.rules)
222
+ if (m_rules.value(r.id).active) out << r.conditionText();
223
+ return out;
224
+ }
225
+
226
+ void ServerSession::raise(const QString &sev, const QString &msg) { emit alertRaised({QDateTime::currentDateTime(), m_cfg.name, sev, msg}); }
227
+
228
+ void ServerSession::record(bool up)
229
+ {
230
+ const Metrics &m = m_m;
231
+ const float v[H_COUNT] = {float(m.cpuUsage), float(m.cpuIowait), float(m.load1), float(m.memPct), m.swapTotal > 0 ? float(m.swapPct) : NAN,
232
+ m.mounts.isEmpty() ? NAN : float(m.maxDiskPct), float(m.maxDiskUtil), float(m.netRxBps), float(m.netTxBps),
233
+ float(m.diskReadBps), float(m.diskWriteBps), m.temps.isEmpty() ? NAN : float(m.maxTemp), float(m.procs.size()),
234
+ m.gpus.isEmpty() ? NAN : float(m.gpuMax(false)), float(m.servicesFailed)};
235
+ m_store.add(QDateTime::currentSecsSinceEpoch(), v, up);
236
+ }
237
+
238
+ // per-process CPU streaks + RSS per minute; service failure transitions
239
+ void ServerSession::track(qint64 now)
240
+ {
241
+ QHash<int, ProcTrack> procs;
242
+ for (const ProcInfo &p : qAsConst(m_m.procs)) {
243
+ ProcTrack t = m_procs.value(p.pid);
244
+ if (t.name != p.name) t = ProcTrack{p.name}; // new or pid reused
245
+ t.kernel = P::isProtected(p.pid, p.ppid, p.rss, p.name);
246
+ t.highSince = p.cpu < m_cfg.autopilot.runawayCpu ? 0 : t.highSince ? t.highSince : now;
247
+ if (now - t.lastMinute >= 60000) t.lastMinute = now, t.rss << p.rss;
248
+ if (t.rss.size() > 60) t.rss.removeFirst();
249
+ procs[p.pid] = t;
250
+ }
251
+ m_procs = procs;
252
+ QHash<QString, SvcTrack> svcs;
253
+ for (const ServiceInfo &s : qAsConst(m_m.services)) {
254
+ SvcTrack &t = svcs[s.unit] = m_svcs.value(s.unit);
255
+ const bool failed = s.active == "failed";
256
+ if (t.last.isEmpty()) t.preexisting = failed; // failed before monitoring started: leave it alone
257
+ else if (failed && t.last != "failed") t.fails << now, t.preexisting = false;
258
+ else if (!failed) t.preexisting = false;
259
+ t.last = s.active;
260
+ for (auto *v : {&t.fails, &t.restarts})
261
+ while (!v->isEmpty() && now - v->first() > 3600000) v->removeFirst();
262
+ }
263
+ if (!svcs.isEmpty()) m_svcs = svcs; // forgets removed services; a sample without a service list changes nothing
264
+ }
265
+
266
+ void ServerSession::evaluateRules()
267
+ {
268
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
269
+ for (const Rule &r : qAsConst(m_cfg.rules)) {
270
+ RuleState &st = m_rules[r.id];
271
+ if (!r.enabled || ((r.metric == "gpu" || r.metric == "gputemp") && m_m.gpus.isEmpty()) || (r.metric == "temp" && m_m.temps.isEmpty())) {
272
+ st = {};
273
+ continue;
274
+ }
275
+ const double v = metricValue(r.metric);
276
+ const QString now1 = QString::number(v, 'f', 1);
277
+ if (r.op == "<" ? v >= r.value : v <= r.value) {
278
+ if (st.active) raise("resolved", QString("Recovered: %1 (now %2)").arg(r.conditionText(), now1));
279
+ st = {};
280
+ continue;
281
+ }
282
+ if (!st.since) st.since = now;
283
+ if (now - st.since < r.duration * 1000LL) continue;
284
+ if (st.active && (r.action == "notify" || now - st.lastFire < r.cooldown * 1000LL)) continue;
285
+ const QString unit = defLabel(ruleMetrics(), r.metric, true);
286
+ if (!st.active) raise(r.severity, QString("%1 (now %2%3)").arg(r.conditionText(), now1, unit.isEmpty() ? "" : " " + unit));
287
+ st.active = true, st.lastFire = now;
288
+ if (r.action == "notify") continue;
289
+ QString action = r.action, arg = r.arg;
290
+ if (action.startsWith("kill_top")) { // heaviest user process, never a protected one
291
+ const ProcInfo *best = nullptr;
292
+ for (const ProcInfo &p : m_m.procs)
293
+ if (!P::isProtected(p.pid, p.ppid, p.rss, p.name) && (!best || (action == "kill_top_mem" ? p.rss > best->rss : p.cpu > best->cpu))) best = &p;
294
+ if (!best) continue;
295
+ action = "kill_pid", arg = QString::number(best->pid);
296
+ }
297
+ run(action, arg, QString("Automation \"%1\": %2").arg(r.conditionText(), r.actionText()));
298
+ }
299
+ }
300
+
301
+ void ServerSession::run(const QString &action, const QString &arg, const QString &what, Done done)
302
+ {
303
+ const QString cmd = action == "command" ? arg : action == "disk_cleanup" ? m_cfg.autopilot.diskCleanupCommand : P::command(action, arg);
304
+ if (cmd.isEmpty()) return done ? done(-1, "nothing to do") : void();
305
+ exec(cmd, true, [=](int code, const QString &out) {
306
+ const QString tail = out.simplified().right(300); // one line: events are lines in alerts.log
307
+ raise("action", what + " -> " + (code ? QString("failed (%1)").arg(code) : "OK") + (tail.isEmpty() ? "" : " | " + tail));
308
+ if (done) done(code, out);
309
+ }, 300000);
310
+ }
311
+
312
+ void ServerSession::runFinding(const Finding &f, bool automatic, Done done)
313
+ {
314
+ if (automatic && f.action == "restart_service") m_svcs[f.actionArg].restarts << QDateTime::currentMSecsSinceEpoch();
315
+ run(f.action, f.action == "disk_cleanup" ? QString() : f.actionArg, (automatic ? "Autopilot: " : "Manual fix: ") + f.actionLabel + " (" + f.title + ")", done);
316
+ }
317
+
318
+ void ServerSession::analyzeNow()
319
+ {
320
+ const qint64 now = QDateTime::currentMSecsSinceEpoch();
321
+ QVector<ProcTrend> procs;
322
+ for (const ProcInfo &p : qAsConst(m_m.procs)) {
323
+ const ProcTrack t = m_procs.value(p.pid);
324
+ ProcTrend pt{p.pid, int(t.rss.size()), p.name, p.user, p.cpu, t.highSince ? (now - t.highSince) / 60000.0 : 0, p.rss};
325
+ pt.kernel = t.kernel;
326
+ if (t.rss.size() >= 2) {
327
+ int grew = 0;
328
+ for (int i = 1; i < t.rss.size(); ++i) grew += t.rss[i] > t.rss[i - 1];
329
+ pt.rssGrowth = t.rss.last() - t.rss[0], pt.rssGrowthPct = t.rss[0] > 0 ? pt.rssGrowth * 100 / t.rss[0] : 0;
330
+ pt.rssMonotonic = double(grew) / (t.rss.size() - 1);
331
+ }
332
+ if (pt.highCpuMinutes > 0 || pt.minutesTracked >= 30) procs << pt;
333
+ }
334
+ QVector<ServiceTrend> svcs;
335
+ for (auto it = m_svcs.cbegin(); it != m_svcs.cend(); ++it)
336
+ if (it->last == "failed" || !it->fails.isEmpty()) svcs << ServiceTrend{it.key(), it->last == "failed", it->preexisting, int(it->fails.size()), int(it->restarts.size())};
337
+ m_an = analyze(m_store, m_m, m_cfg.autopilot, procs, svcs, online());
338
+
339
+ QSet<QString> keys; // announce each new finding once
340
+ for (const Finding &f : qAsConst(m_an.findings))
341
+ if (keys << f.key, !m_reported.contains(f.key) && f.category != "Availability") raise(f.severity, "Insight: " + f.title + " - " + f.detail);
342
+ m_reported = keys;
343
+
344
+ const AutopilotConfig &ap = m_cfg.autopilot; // act on eligible findings, with cooldowns; a dry run says once what it would do
345
+ QSet<QString> dry;
346
+ if (ap.enabled && online())
347
+ for (const Finding &f : qAsConst(m_an.findings)) {
348
+ const qint64 cd = f.action == "disk_cleanup" ? 6 * 3600000LL : f.action == "restart_service" ? 120000 : 900000;
349
+ if (!f.autoEligible) continue;
350
+ if (ap.dryRun) {
351
+ if (dry << f.key, !m_dry.contains(f.key)) raise("action", "Autopilot (dry run) would: " + f.actionLabel + " - " + f.title);
352
+ } else if (now - m_cooldown.value(f.key) >= cd) m_cooldown[f.key] = now, runFinding(f, true);
353
+ }
354
+ m_dry = dry;
355
+ emit analysisUpdated();
356
+ }
357
+
358
+ void ServerSession::deleteHistory()
359
+ {
360
+ m_store.removeFiles(), m_an = Analysis();
361
+ emit analysisUpdated();
362
+ }
363
+
364
+ // ---- manager ----------------------------------------------------------------------------
365
+ QString ServerManager::configDir()
366
+ {
367
+ static const QString d = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation);
368
+ QDir().mkpath(d);
369
+ return d;
370
+ }
371
+
372
+ ServerSession *ServerManager::session(const QString &id) const
373
+ {
374
+ for (ServerSession *s : m_s)
375
+ if (s->config().id == id) return s;
376
+ return nullptr;
377
+ }
378
+
379
+ ServerSession *ServerManager::attach(const ServerConfig &c)
380
+ {
381
+ auto *s = new ServerSession(c, this);
382
+ connect(s, &ServerSession::alertRaised, this, [this](const AlertEvent &e) {
383
+ m_alerts.prepend(e);
384
+ m_alerts.resize(qMin(m_alerts.size(), 2000));
385
+ QFile f(configDir() + "/alerts.log");
386
+ if (f.size() > 5 << 20) f.resize(0);
387
+ if (f.open(QIODevice::Append | QIODevice::Text))
388
+ QTextStream(&f) << e.time.toString(Qt::ISODate) << '\t' << e.severity << '\t' << e.serverName << '\t' << e.message << '\n';
389
+ emit alertRaised(e);
390
+ });
391
+ m_s << s;
392
+ return s;
393
+ }
394
+
395
+ void ServerManager::load()
396
+ {
397
+ QFile f(configDir() + "/servers.json");
398
+ if (f.open(QIODevice::ReadOnly))
399
+ for (const auto &v : QJsonDocument::fromJson(f.readAll())["servers"].toArray()) attach(ServerConfig::fromJson(v.toObject()));
400
+ else { // first start: monitor this machine
401
+ ServerConfig c;
402
+ c.id = ServerConfig::newId(), c.name = "This computer", c.group = "Local", c.transport = Transport::Local;
403
+ attach(c);
404
+ save();
405
+ }
406
+ for (ServerSession *s : qAsConst(m_s)) s->start();
407
+ emit listChanged();
408
+ }
409
+
410
+ void ServerManager::save() const
411
+ {
412
+ QJsonArray a;
413
+ for (const ServerSession *s : m_s) a << s->config().toJson();
414
+ QSaveFile f(configDir() + "/servers.json");
415
+ if (f.open(QIODevice::WriteOnly)) f.write(QJsonDocument(QJsonObject{{"version", 1}, {"servers", a}}).toJson()), f.commit();
416
+ QFile::setPermissions(f.fileName(), QFileDevice::ReadOwner | QFileDevice::WriteOwner);
417
+ }
418
+
419
+ ServerSession *ServerManager::add(const ServerConfig &c)
420
+ {
421
+ ServerSession *s = attach(c);
422
+ save(), s->start();
423
+ emit listChanged();
424
+ return s;
425
+ }
426
+
427
+ void ServerManager::update(const ServerConfig &c)
428
+ {
429
+ if (ServerSession *s = session(c.id)) s->setConfig(c), save(), emit listChanged();
430
+ }
431
+
432
+ void ServerManager::remove(const QString &id, bool deleteHistory)
433
+ {
434
+ ServerSession *s = session(id);
435
+ if (!s) return;
436
+ m_s.removeOne(s);
437
+ s->disconnect(this), s->stop();
438
+ if (deleteHistory) s->deleteHistory(), QDir(configDir() + "/history").rmdir(id); // the store keeps an empty folder
439
+ s->deleteLater();
440
+ save();
441
+ emit listChanged();
442
+ }
443
+
444
+ void ServerManager::move(const QString &id, int d)
445
+ {
446
+ const int i = m_s.indexOf(session(id)), j = qBound(0, i + d, m_s.size() - 1);
447
+ if (i >= 0 && i != j) m_s.move(i, j), save(), emit listChanged();
448
+ }
Server Monitor(cqt-window)/src/core/Session.h ADDED
@@ -0,0 +1,137 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Connection to one machine (local sh or system ssh), the per-server session
2
+ // (metrics, live history, rules, autopilot) and the manager of all sessions.
3
+ #pragma once
4
+ #include "History.h"
5
+ #include <QDateTime>
6
+ #include <QElapsedTimer>
7
+ #include <QPointer>
8
+ #include <QProcess>
9
+ #include <QSet>
10
+ #include <QTimer>
11
+ #include <functional>
12
+
13
+ using Done = std::function<void(int code, QString output)>;
14
+
15
+ // Streams collector frames and runs one-shot commands. Deleting it kills everything.
16
+ class Link : public QObject {
17
+ Q_OBJECT
18
+ public:
19
+ Link(const ServerConfig &c, QObject *parent);
20
+ ~Link() override;
21
+ void start();
22
+ int exec(const QByteArray &input, int timeoutMs);
23
+ signals:
24
+ void snapshot(const QByteArray &frame);
25
+ void disconnected(const QString &reason);
26
+ void execFinished(int id, int code, const QString &out);
27
+
28
+ private:
29
+ QProcess *spawn(const QStringList &shell); // not started yet
30
+ ServerConfig m_c;
31
+ QByteArray m_buf, m_err;
32
+ int m_next = 1;
33
+ };
34
+
35
+ enum class Status { Disabled, Connecting, Online, Offline };
36
+ QString statusName(Status s);
37
+ struct AlertEvent { QDateTime time; QString serverName, severity, message; }; // severity: info|warning|critical|resolved|action
38
+
39
+ struct Live { // last hour in memory for the live charts
40
+ enum { CPU, USER, SYS, IOWAIT, STEAL, MEM, CACHE, SWAP, RX, TX, RD, WR, LOAD, N };
41
+ QVector<qint64> t;
42
+ QVector<double> s[N];
43
+ QHash<QString, QVector<double>> ifRx, ifTx;
44
+ void push(const Metrics &m);
45
+ };
46
+
47
+ class ServerSession : public QObject {
48
+ Q_OBJECT
49
+ public:
50
+ ServerSession(const ServerConfig &c, QObject *parent);
51
+ ~ServerSession() override;
52
+ const ServerConfig &config() const { return m_cfg; }
53
+ void setConfig(const ServerConfig &c);
54
+ Status status() const { return m_status; }
55
+ QString lastError() const { return m_err; }
56
+ const Metrics &metrics() const { return m_m; }
57
+ const Live &live() const { return m_live; }
58
+ bool online() const { return m_status == Status::Online && m_m.valid; }
59
+ bool isPaused() const { return m_paused; }
60
+ void setPaused(bool p) { m_paused = p, emit updated(); }
61
+ void start();
62
+ void stop();
63
+ void reconnect() { m_retries = 0, m_paused = false, start(); }
64
+ // privileged + "useSudo" wraps the command in sudo -n
65
+ void exec(const QString &cmd, bool privileged, Done done = {}, int timeoutMs = 60000);
66
+ double metricValue(const QString &key) const;
67
+ QStringList activeAlerts() const;
68
+ const HistoryStore &store() const { return m_store; }
69
+ const Analysis &analysis() const { return m_an; }
70
+ void analyzeNow();
71
+ void runFinding(const Finding &f, bool automatic, Done done = {});
72
+ void deleteHistory();
73
+ signals:
74
+ void updated();
75
+ void analysisUpdated();
76
+ void alertRaised(const AlertEvent &e);
77
+
78
+ private:
79
+ void setStatus(Status s, const QString &err = {});
80
+ void drop(const QString &why); // closes the link and fails the commands that wait for it
81
+ void onFrame(const QByteArray &raw);
82
+ void onLost(const QString &why);
83
+ void record(bool up);
84
+ void track(qint64 now);
85
+ void evaluateRules();
86
+ void run(const QString &action, const QString &arg, const QString &what, Done done = {});
87
+ void raise(const QString &sev, const QString &msg);
88
+
89
+ ServerConfig m_cfg;
90
+ Status m_status = Status::Disabled;
91
+ QString m_err;
92
+ QPointer<Link> m_link;
93
+ MetricsEngine m_engine;
94
+ Metrics m_m;
95
+ Live m_live;
96
+ QTimer m_retry, m_watchdog, m_analysisTimer, m_offlineTick;
97
+ int m_retries = 0;
98
+ bool m_paused = false, m_offlineAlerted = false;
99
+ QHash<int, Done> m_pending;
100
+ HistoryStore m_store;
101
+ Analysis m_an;
102
+ QSet<QString> m_reported, m_dry;
103
+ QHash<QString, qint64> m_cooldown;
104
+ struct RuleState { qint64 since = 0, lastFire = 0; bool active = false; };
105
+ QHash<QString, RuleState> m_rules;
106
+ struct ProcTrack { QString name; qint64 highSince = 0, lastMinute = 0; QVector<double> rss; bool kernel = false; };
107
+ QHash<int, ProcTrack> m_procs;
108
+ struct SvcTrack { QString last; bool preexisting = false; QVector<qint64> fails, restarts; };
109
+ QHash<QString, SvcTrack> m_svcs;
110
+ };
111
+
112
+ class ServerManager : public QObject {
113
+ Q_OBJECT
114
+ public:
115
+ using QObject::QObject;
116
+ ~ServerManager() override { qDeleteAll(m_s); }
117
+ static QString configDir();
118
+ void load();
119
+ void save() const;
120
+ const QVector<ServerSession *> &sessions() const { return m_s; }
121
+ ServerSession *session(const QString &id) const;
122
+ ServerSession *add(const ServerConfig &c);
123
+ void update(const ServerConfig &c);
124
+ void remove(const QString &id, bool deleteHistory);
125
+ void move(const QString &id, int delta);
126
+ const QVector<AlertEvent> &alerts() const { return m_alerts; }
127
+ void clearAlerts() { m_alerts.clear(), emit alertsCleared(); }
128
+ signals:
129
+ void listChanged();
130
+ void alertRaised(const AlertEvent &e);
131
+ void alertsCleared();
132
+
133
+ private:
134
+ ServerSession *attach(const ServerConfig &c);
135
+ QVector<ServerSession *> m_s;
136
+ QVector<AlertEvent> m_alerts;
137
+ };
Server Monitor(cqt-window)/src/main.cpp ADDED
@@ -0,0 +1,31 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Server Monitor - entry point.
2
+ #include "ui/Widgets.h"
3
+ #include "ui/Windows.h"
4
+ #include <QApplication>
5
+ #include <QStyleFactory>
6
+ #include <cstdio>
7
+
8
+ int main(int argc, char *argv[])
9
+ {
10
+ // ssh runs this executable as SSH_ASKPASS when a password is configured
11
+ if (const QByteArray pw = qEnvironmentVariable("SERVERMONITOR_ASKPASS").toUtf8(); !pw.isEmpty()) return std::puts(pw.constData()) < 0;
12
+ QApplication::setAttribute(Qt::AA_EnableHighDpiScaling), QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps);
13
+ QApplication app(argc, argv);
14
+ QApplication::setApplicationName("ServerMonitor"), QApplication::setOrganizationName("ServerMonitor"), QApplication::setQuitOnLastWindowClosed(false);
15
+ app.setStyle(QStyleFactory::create("Fusion"));
16
+ QPalette pal;
17
+ for (auto [role, color] : {std::pair{QPalette::Window, C::bg}, {QPalette::WindowText, C::text}, {QPalette::Base, QColor(0x111727)}, {QPalette::AlternateBase, C::panel},
18
+ {QPalette::Text, C::text}, {QPalette::Button, C::card}, {QPalette::ButtonText, C::text}, {QPalette::Highlight, QColor(0x17304a)},
19
+ {QPalette::HighlightedText, C::text}, {QPalette::ToolTipBase, C::card}, {QPalette::ToolTipText, C::text}, {QPalette::PlaceholderText, C::faint}})
20
+ pal.setColor(role, color);
21
+ pal.setColor(QPalette::Disabled, QPalette::Text, C::faint), pal.setColor(QPalette::Disabled, QPalette::ButtonText, C::faint);
22
+ app.setPalette(pal), app.setWindowIcon(C::appIcon()), app.setStyleSheet(C::styleSheet());
23
+
24
+ ServerManager mgr;
25
+ MainWindow w(&mgr);
26
+ mgr.load();
27
+ w.show();
28
+ if (const QString dir = qEnvironmentVariable("SERVERMONITOR_SNAPSHOT"); !dir.isEmpty()) // developer aid
29
+ QTimer::singleShot(qMax(1, qEnvironmentVariableIntValue("SERVERMONITOR_SNAPSHOT_DELAY")) * 1000, &w, [&w, dir] { w.saveSnapshots(dir), qApp->quit(); });
30
+ return app.exec();
31
+ }
Server Monitor(cqt-window)/src/ui/Tabs.cpp ADDED
@@ -0,0 +1,884 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Detail-page tabs: each one shows an aspect of the bound server session.
2
+ #include "Widgets.h"
3
+ #include "Windows.h"
4
+ #include <QBoxLayout>
5
+ #include <QButtonGroup>
6
+ #include <QCheckBox>
7
+ #include <QComboBox>
8
+ #include <QDialogButtonBox>
9
+ #include <QDoubleSpinBox>
10
+ #include <QFileDialog>
11
+ #include <QFormLayout>
12
+ #include <QInputDialog>
13
+ #include <QKeyEvent>
14
+ #include <QLineEdit>
15
+ #include <QMenu>
16
+ #include <QPlainTextEdit>
17
+ #include <QScrollArea>
18
+ #include <QScrollBar>
19
+ #include <QSpinBox>
20
+ #include <QTextStream>
21
+ #include <memory>
22
+ #include <type_traits>
23
+
24
+ // ---- helpers ----------------------------------------------------------------------------
25
+ static QVBoxLayout *scrollRoot(QWidget *tab)
26
+ {
27
+ auto *outer = new QVBoxLayout(tab);
28
+ auto *sa = new QScrollArea;
29
+ auto *l = new QVBoxLayout(new QWidget);
30
+ outer->setContentsMargins(0, 0, 0, 0), outer->addWidget(sa);
31
+ sa->setWidgetResizable(true), sa->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff), sa->setWidget(l->parentWidget());
32
+ l->setContentsMargins(4, 16, 10, 16), l->setSpacing(16);
33
+ return l;
34
+ }
35
+ static QVBoxLayout *plainRoot(QWidget *tab)
36
+ {
37
+ auto *l = new QVBoxLayout(tab);
38
+ l->setContentsMargins(4, 16, 4, 12), l->setSpacing(10);
39
+ return l;
40
+ }
41
+ template <class L> static L *sub(QBoxLayout *parent, int stretch = 0) // nested layout with the standard spacing
42
+ {
43
+ auto *l = new L;
44
+ l->setSpacing(14), parent->addLayout(l, stretch);
45
+ return l;
46
+ }
47
+ static QGridLayout *grid(QBoxLayout *parent, int stretch = 0) { return sub<QGridLayout>(parent, stretch); }
48
+ static QHBoxLayout *row(QBoxLayout *parent, int stretch = 0) { return sub<QHBoxLayout>(parent, stretch); }
49
+ static QVBoxLayout *lay(QFrame *f) { return static_cast<QVBoxLayout *>(f->layout()); }
50
+ static QString kv(const QVector<QPair<QString, QString>> &rows)
51
+ {
52
+ QString h = "<table>";
53
+ for (const auto &r : rows) h += QString("<tr><td style='color:#8b95ab;padding:3px 18px 3px 0'>%1</td><td>%2</td></tr>").arg(r.first, r.second.toHtmlEscaped());
54
+ return h + "</table>";
55
+ }
56
+ static QVector<Series> cpuSeries(const Live &h, bool steal)
57
+ {
58
+ QVector<Series> s = {{"User", C::accent, h.s[Live::USER]}, {"System", C::violet, h.s[Live::SYS]}};
59
+ if (P::posixCpu) s << Series{"I/O wait", C::amber, h.s[Live::IOWAIT]};
60
+ if (P::posixCpu && steal) s << Series{"Steal", C::red, h.s[Live::STEAL]};
61
+ return s;
62
+ }
63
+ // run a command and show the result in a status label
64
+ static void runReport(ServerSession *s, QLabel *status, const QString &cmd)
65
+ {
66
+ status->setText("Running: " + cmd);
67
+ s->exec(cmd, true, [st = QPointer<QLabel>(status), cmd](int code, const QString &out) {
68
+ if (!st) return;
69
+ st->setText(code ? "✗ " + cmd + ": " + out.trimmed().left(300) : "✓ " + cmd);
70
+ st->setStyleSheet(QString("color: %1;").arg((code ? C::red : C::green).name()));
71
+ });
72
+ }
73
+
74
+ // ============================================================================ Overview
75
+ struct OverviewTab : Tab {
76
+ QVector<RingGauge *> g;
77
+ QVector<StatTile *> t;
78
+ TimeChart *cpu = new TimeChart("CPU", pctFmt, 100), *mem = new TimeChart("Memory", pctFmt, 100), *net = new TimeChart("Network", rateFmt),
79
+ *io = new TimeChart("Disk I/O", rateFmt);
80
+ QLabel *info = label({}, nullptr, true);
81
+
82
+ OverviewTab()
83
+ {
84
+ auto *l = scrollRoot(this);
85
+ auto *gp = panel(), *ip = panel("System", {info, nullptr});
86
+ auto *gl = new QHBoxLayout;
87
+ for (const char *n : {"CPU", "Memory", "Fullest disk", "Swap", "Temperature", "Health"}) g << new RingGauge(n), gl->addWidget(g.last());
88
+ g[4]->crit = 85;
89
+ lay(gp)->addLayout(gl), gp->setMinimumHeight(220), l->addWidget(gp);
90
+ t = addTiles(grid(l), {{"Load average", C::accent}, {"Processes", C::violet}, {"TCP connections", C::teal}, {"Services", C::green}, {"Uptime", C::amber}});
91
+ auto *mid = row(l);
92
+ auto *charts = grid(mid, 1);
93
+ cpu->stacked = true;
94
+ for (auto *c : {cpu, mem, net, io}) c->setMinimumHeight(220), charts->addWidget(c, charts->count() / 2, charts->count() % 2);
95
+ ip->setFixedWidth(330), mid->addWidget(ip), l->addStretch();
96
+ }
97
+ void refresh() override
98
+ {
99
+ const Metrics &m = s->metrics();
100
+ const Live &h = s->live();
101
+ const Analysis &a = s->analysis();
102
+ const ServerConfig &c = s->config();
103
+ g[0]->setValue(m.cpuUsage, {}, QString("%1 cores").arg(m.cpuCount));
104
+ g[1]->setValue(m.memPct, {}, Fmt::bytes(m.memUsed) + " / " + Fmt::bytes(m.memTotal));
105
+ g[2]->setValue(m.maxDiskPct, {}, m.fullestMount);
106
+ g[3]->setValue(m.swapPct, {}, m.swapTotal > 0 ? Fmt::bytes(m.swapUsed) + " / " + Fmt::bytes(m.swapTotal) : "no swap");
107
+ g[4]->setValue(qMin(100.0, m.maxTemp), m.temps.isEmpty() ? "—" : Fmt::temp(m.maxTemp), m.temps.isEmpty() ? "no sensors" : QString("%1 sensors").arg(m.temps.size()));
108
+ g[5]->setValue(a.health, QString::number(a.health), "grade " + a.grade, C::health(a.health));
109
+ t[0]->set(QString::number(m.load1, 'f', 2), QString("5m %1 · 15m %2").arg(m.load5, 0, 'f', 2).arg(m.load15, 0, 'f', 2), C::level(m.load1 * 100 / qMax(1, m.cpuCount), 80, 150));
110
+ t[1]->set(QString::number(m.procs.size()), QString("%1 threads · %2 running").arg(m.threadsTotal).arg(m.procsRunning));
111
+ t[2]->set(QString::number(m.tcp["ESTABLISHED"]), QString("%1 listening · %2 time-wait").arg(m.tcp["LISTEN"]).arg(m.tcp["TIME_WAIT"]));
112
+ t[3]->set(QString::number(m.servicesRunning), m.servicesFailed ? QString("%1 failed").arg(m.servicesFailed) : "running · none failed", m.servicesFailed ? C::red : C::text);
113
+ t[4]->set(Fmt::duration(m.uptime), QString("%1 user(s) logged in").arg(m.loggedUsers));
114
+ cpu->setData(h.t, cpuSeries(h, false), span);
115
+ mem->setData(h.t, {{"Used", C::violet, h.s[Live::MEM]}, {"Cache", C::blue, h.s[Live::CACHE], false, true}, {"Swap", C::pink, h.s[Live::SWAP], false}}, span);
116
+ net->setData(h.t, {{"Down", C::teal, h.s[Live::RX]}, {"Up", C::pink, h.s[Live::TX]}}, span);
117
+ io->setData(h.t, {{"Read", C::blue, h.s[Live::RD]}, {"Write", C::orange, h.s[Live::WR]}}, span);
118
+ info->setText(kv({{"Hostname", m.hostname}, {"OS", m.os}, {"Kernel", m.kernel + " " + m.arch}, {"CPU", m.cpuModel},
119
+ {"Cores", QString::number(m.cpuCount) + (m.avgMhz > 0 ? QString(" @ %1 GHz").arg(m.avgMhz / 1000, 0, 'f', 2) : "")},
120
+ {"Memory", Fmt::bytes(m.memTotal)}, {"Swap", m.swapTotal > 0 ? Fmt::bytes(m.swapTotal) : "none"}, {"Virtualisation", m.virt},
121
+ {"Disks", QString("%1 mounted file systems").arg(m.mounts.size())}, {"Interfaces", QString::number(m.nets.size())},
122
+ {"GPU", m.gpus.isEmpty() ? "none" : m.gpus[0].name}, {"Connection", c.address() + " (" + transportName(c.transport) + ")"},
123
+ {"Sample interval", QString("%1 s").arg(c.interval)}}));
124
+ }
125
+ };
126
+
127
+ // ============================================================================ CPU
128
+ struct CpuTab : Tab {
129
+ QLabel *model = label({}, "H2");
130
+ QVector<StatTile *> t;
131
+ TimeChart *chart = new TimeChart("CPU time breakdown", pctFmt, 100), *load = new TimeChart("Load average (1 min)", numFmt(1));
132
+ CoreGrid *cores = new CoreGrid;
133
+ QTableWidget *temps = table({"Sensor", "Temperature"}, {300}, {1}), *gpus = table({"#", "Name", "Usage", "Memory", "Temp", "Power", "Fan"}, {40, 220, 120, 160}, {2, 3});
134
+ QFrame *gpuPanel = panel("GPUs", {gpus});
135
+
136
+ CpuTab()
137
+ {
138
+ auto *l = scrollRoot(this);
139
+ l->addWidget(model);
140
+ t = addTiles(grid(l), {{"Usage", C::accent}, {"Load 1 / 5 / 15", C::violet}, {"Avg frequency", C::teal}, {P::posixCpu ? "Steal / IRQ" : "Interrupts + DPC", C::orange},
141
+ {"Context switches", C::blue}, {"Interrupts", C::pink}, {"New processes", C::green}, {"Running / blocked", C::amber}}, 4);
142
+ auto *r = row(l);
143
+ chart->stacked = true, chart->setMinimumHeight(260), temps->setMinimumHeight(220);
144
+ r->addWidget(chart, 3), r->addWidget(load, 2), l->addWidget(panel("Per core", {cores}));
145
+ auto *b = row(l);
146
+ b->addWidget(panel("Temperatures", {temps}), 1), b->addWidget(gpuPanel, 1), l->addStretch();
147
+ }
148
+ void refresh() override
149
+ {
150
+ const Metrics &m = s->metrics();
151
+ const Live &h = s->live();
152
+ model->setText(m.cpuModel.isEmpty() ? "Processor" : m.cpuModel);
153
+ t[0]->set(Fmt::pct(m.cpuUsage), QString("user %1 · system %2").arg(Fmt::pct(m.cpuUser), Fmt::pct(m.cpuSystem)) + (P::posixCpu ? " · iowait " + Fmt::pct(m.cpuIowait) : ""), C::level(m.cpuUsage));
154
+ t[1]->set(QString("%1 / %2 / %3").arg(m.load1, 0, 'f', 2).arg(m.load5, 0, 'f', 2).arg(m.load15, 0, 'f', 2), QString("%1% of %2 cores").arg(qRound(m.load1 * 100 / qMax(1, m.cpuCount))).arg(m.cpuCount));
155
+ t[2]->set(m.avgMhz > 0 ? QString("%1 GHz").arg(m.avgMhz / 1000, 0, 'f', 2) : "n/a");
156
+ if (P::posixCpu) t[3]->set(Fmt::pct(m.cpuSteal) + " / " + Fmt::pct(m.cpuIrq), "steal > 5% = noisy neighbours", m.cpuSteal > 5 ? C::amber : QColor());
157
+ else t[3]->set(Fmt::pct(m.cpuIrq), "hardware interrupts and deferred calls", m.cpuIrq > 15 ? C::amber : QColor());
158
+ t[4]->set(Fmt::count(m.ctxtPerSec) + "/s"), t[5]->set(Fmt::count(m.intrPerSec) + "/s"), t[6]->set(QString::number(m.forksPerSec, 'f', 1) + "/s");
159
+ t[7]->set(QString("%1 / %2").arg(m.procsRunning).arg(m.procsBlocked), P::posixCpu ? "blocked = waiting for I/O" : "blocked = waiting for a CPU", m.procsBlocked > m.cpuCount ? C::amber : QColor());
160
+ chart->setData(h.t, cpuSeries(h, true), span);
161
+ load->setData(h.t, {{"Load", C::violet, h.s[Live::LOAD]}, {"Cores", C::faint, QVector<double>(h.t.size(), m.cpuCount), false, true}}, span);
162
+ cores->setCores(m.cores);
163
+ temps->clearSpans();
164
+ fillRows(temps, m.temps, [](const TempSensor &x) { return Row{{x.name}, {Fmt::temp(x.celsius), {}, false, qMin(100.0, x.celsius)}}; });
165
+ if (m.temps.isEmpty()) temps->setRowCount(1), cell(temps, 0, 0, {"No temperature sensors exposed (common on VMs)", C::muted}), temps->setSpan(0, 0, 1, 2);
166
+ gpuPanel->setVisible(!m.gpus.isEmpty());
167
+ fillRows(gpus, m.gpus, [](const GpuInfo &g) {
168
+ return Row{{QString::number(g.index)}, {g.name}, {Fmt::pct(g.util, 0), {}, false, g.util},
169
+ {QString("%1 / %2 MiB").arg(g.memUsed).arg(g.memTotal), {}, false, g.memTotal > 0 ? g.memUsed * 100 / g.memTotal : 0},
170
+ {Fmt::temp(g.temp), C::level(g.temp, 75, 88)}, {QString("%1 W").arg(g.power)}, {Fmt::pct(g.fan, 0)}};
171
+ });
172
+ }
173
+ };
174
+
175
+ // ============================================================================ Memory
176
+ struct MemoryTab : Tab {
177
+ QVector<StatTile *> t;
178
+ SegmentBar *bar = new SegmentBar, *swap = new SegmentBar;
179
+ TimeChart *chart = new TimeChart("Memory usage", pctFmt, 100);
180
+ QLabel *detail = label({}, nullptr, true);
181
+ QTableWidget *top = table({"PID", "Process", "User", "RSS", "Memory %", "Virtual"}, {80, 220, 120, 110, 160}, {4});
182
+
183
+ MemoryTab()
184
+ {
185
+ auto *l = scrollRoot(this);
186
+ t = addTiles(grid(l), {{"Used", C::violet}, {"Available", C::green}, {"Cache + buffers", C::blue}, {"Swap used", C::pink}});
187
+ l->addWidget(panel("Composition", {bar, label("SWAP", "Section"), swap}));
188
+ auto *r = row(l);
189
+ auto *dp = panel("Details", {detail, nullptr});
190
+ chart->setMinimumHeight(280), dp->setFixedWidth(300), top->setMinimumHeight(360);
191
+ r->addWidget(chart, 3), r->addWidget(dp), l->addWidget(panel("Top memory consumers", {top}));
192
+ }
193
+ void refresh() override
194
+ {
195
+ const Metrics &m = s->metrics();
196
+ const Live &h = s->live();
197
+ const QColor free = C::grid.lighter(150);
198
+ t[0]->set(Fmt::bytes(m.memUsed), Fmt::pct(m.memPct) + " of " + Fmt::bytes(m.memTotal), C::level(m.memPct));
199
+ t[1]->set(Fmt::bytes(m.memAvailable), "free " + Fmt::bytes(m.memFree));
200
+ t[2]->set(Fmt::bytes(m.cached + m.buffers), "reclaimable when needed");
201
+ t[3]->set(m.swapTotal > 0 ? Fmt::bytes(m.swapUsed) : "no swap", m.swapTotal > 0 ? Fmt::pct(m.swapPct) + " of " + Fmt::bytes(m.swapTotal) : "", C::level(m.swapPct, 40, 80));
202
+ bar->setSegments({{qMax(0.0, m.memTotal - m.memFree - m.cached - m.buffers), C::violet, "Applications"}, {m.shared, C::pink, "Shared"},
203
+ {m.buffers, C::teal, "Buffers"}, {qMax(0.0, m.cached - m.shared), C::blue, "Cache"}, {m.memFree, free, "Free"}}, m.memTotal);
204
+ swap->setSegments({{m.swapUsed, C::pink, "Used"}, {m.swapTotal - m.swapUsed, free, "Free"}}, m.swapTotal);
205
+ chart->setData(h.t, {{"Used", C::violet, h.s[Live::MEM]}, {"Cache", C::blue, h.s[Live::CACHE], false, true}, {"Swap", C::pink, h.s[Live::SWAP]}}, span);
206
+ QVector<QPair<QString, QString>> d;
207
+ for (auto [k, v] : {std::pair{"Total", m.memTotal}, {"Used", m.memUsed}, {"Available", m.memAvailable}, {"Free", m.memFree}, {"Buffers", m.buffers},
208
+ {"Cached", m.cached}, {"Shared", m.shared}, {"Slab", m.slab}, {"Dirty", m.dirty}, {"Swap total", m.swapTotal}, {"Swap used", m.swapUsed}})
209
+ d << qMakePair(QString(k), Fmt::bytes(v));
210
+ detail->setText(kv(d));
211
+ QVector<ProcInfo> p = m.procs;
212
+ std::partial_sort(p.begin(), p.begin() + qMin(15, p.size()), p.end(), [](const ProcInfo &a, const ProcInfo &b) { return a.rss > b.rss; });
213
+ fillRows(top, p.mid(0, 15), [](const ProcInfo &x) {
214
+ return Row{{QString::number(x.pid), C::muted}, {x.name}, {x.user, C::muted}, {Fmt::bytes(x.rss), {}, true},
215
+ {Fmt::pct(x.memPct), {}, false, qMin(100.0, x.memPct * 2)}, {Fmt::bytes(x.vsz), C::muted, true}};
216
+ });
217
+ }
218
+ };
219
+
220
+ // ============================================================================ Storage
221
+ struct StorageTab : Tab {
222
+ QVector<StatTile *> t;
223
+ QTableWidget *mounts = table({"Mount point", "Device", "Type", "Size", "Used", "Free", "Usage"}, {260, 140, 80, 110, 110, 110}, {6}),
224
+ *disks = table({"Device", "Read/s", "Write/s", "Read IOPS", "Write IOPS", "Busy", "Total read", "Total written"}, {110, 110, 110, 100, 100, 150, 120}, {5});
225
+ TimeChart *io = new TimeChart("Disk throughput", rateFmt);
226
+
227
+ StorageTab()
228
+ {
229
+ auto *l = scrollRoot(this);
230
+ t = addTiles(grid(l), {{"Fullest file system", C::amber}, {"Read", C::blue}, {"Write", C::orange}, {"Busiest disk", C::red}});
231
+ mounts->setMinimumHeight(220), disks->setMinimumHeight(200), io->setMinimumHeight(260);
232
+ l->addWidget(panel("File systems", {mounts})), l->addWidget(io), l->addWidget(panel("Block devices", {disks}));
233
+ }
234
+ void refresh() override
235
+ {
236
+ const Metrics &m = s->metrics();
237
+ t[0]->set(Fmt::pct(m.maxDiskPct), m.fullestMount, C::level(m.maxDiskPct, 80, 90));
238
+ t[1]->set(Fmt::rate(m.diskReadBps)), t[2]->set(Fmt::rate(m.diskWriteBps)), t[3]->set(Fmt::pct(m.maxDiskUtil), m.busiestDisk, C::level(m.maxDiskUtil, 60, 90));
239
+ io->setData(s->live().t, {{"Read", C::blue, s->live().s[Live::RD]}, {"Write", C::orange, s->live().s[Live::WR]}}, span);
240
+ fillRows(mounts, m.mounts, [](const MountInfo &x) {
241
+ return Row{{x.mount}, {x.device, C::muted}, {x.type, C::muted}, {Fmt::bytes(x.total), {}, true}, {Fmt::bytes(x.used), {}, true},
242
+ {Fmt::bytes(x.avail), {}, true}, {Fmt::pct(x.pct), {}, false, x.pct}};
243
+ });
244
+ fillRows(disks, m.disks, [](const DiskIO &d) {
245
+ return Row{{d.name}, {Fmt::rate(d.readBps), C::blue, true}, {Fmt::rate(d.writeBps), C::orange, true}, {QString::number(d.readIops, 'f', 0), {}, true},
246
+ {QString::number(d.writeIops, 'f', 0), {}, true}, {Fmt::pct(d.util, 0), {}, false, d.util}, {Fmt::bytes(d.totalRead), C::muted, true},
247
+ {Fmt::bytes(d.totalWritten), C::muted, true}};
248
+ });
249
+ }
250
+ };
251
+
252
+ // ============================================================================ Network
253
+ struct NetworkTab : Tab {
254
+ QVector<StatTile *> t;
255
+ QComboBox *iface = new QComboBox;
256
+ QStringList shown;
257
+ TimeChart *chart = new TimeChart("Traffic", rateFmt);
258
+ QTableWidget *tbl = table({"Interface", "State", "Speed", "Down/s", "Up/s", "Pkts in/s", "Pkts out/s", "Received", "Sent", "Errors", "Drops"}, {160, 80, 90, 110, 110, 90, 90, 110, 110, 70});
259
+
260
+ NetworkTab()
261
+ {
262
+ auto *l = scrollRoot(this);
263
+ t = addTiles(grid(l), {{"Download", C::teal}, {"Upload", C::pink}, {"Established", C::accent}, {"Listening", C::green}, {"Time-wait / close-wait", C::amber}, {"Sockets in use", C::violet}});
264
+ auto *r = row(l);
265
+ r->addWidget(label("Interface", "Muted")), r->addWidget(iface), r->addStretch();
266
+ iface->setMinimumWidth(200), chart->setMinimumHeight(280), tbl->setMinimumHeight(240);
267
+ l->addWidget(chart), l->addWidget(panel("Interfaces", {tbl}));
268
+ connect(iface, QOverload<int>::of(&QComboBox::activated), this, [this] { refresh(); });
269
+ }
270
+ void refresh() override
271
+ {
272
+ const Metrics &m = s->metrics();
273
+ const Live &h = s->live();
274
+ t[0]->set(Fmt::rate(m.netRxBps), "physical interfaces"), t[1]->set(Fmt::rate(m.netTxBps));
275
+ t[2]->set(QString::number(m.tcp["ESTABLISHED"]), "TCP"), t[3]->set(QString::number(m.tcp["LISTEN"]), "open TCP ports");
276
+ t[4]->set(QString("%1 / %2").arg(m.tcp["TIME_WAIT"]).arg(m.tcp["CLOSE_WAIT"]), "many close-wait = app not closing sockets", m.tcp["CLOSE_WAIT"] > 100 ? C::amber : QColor());
277
+ t[5]->set(QString::number(m.socketsUsed));
278
+ QStringList names{"All physical (total)"};
279
+ for (const NetIf &n : m.nets) names << n.name;
280
+ if (names != shown) {
281
+ const QString cur = iface->currentText();
282
+ iface->clear(), iface->addItems(shown = names), iface->setCurrentIndex(qMax(0, names.indexOf(cur)));
283
+ }
284
+ const QString n = iface->currentText();
285
+ const bool all = iface->currentIndex() <= 0;
286
+ chart->title = "Traffic — " + (all ? "all physical interfaces" : n);
287
+ chart->setData(h.t, {{"Down", C::teal, all ? h.s[Live::RX] : h.ifRx.value(n)}, {"Up", C::pink, all ? h.s[Live::TX] : h.ifTx.value(n)}}, span);
288
+ fillRows(tbl, m.nets, [](const NetIf &x) {
289
+ const QColor dim = x.virt ? C::muted : QColor();
290
+ return Row{{x.name + (x.virt ? " (virtual)" : ""), dim}, {x.state, x.state == "up" ? C::green : x.state == "down" ? C::red : C::muted},
291
+ {x.speed > 0 ? QString("%1 Mb/s").arg(x.speed) : "—", C::muted}, {Fmt::rate(x.rxBps), C::teal, true}, {Fmt::rate(x.txBps), C::pink, true},
292
+ {QString::number(x.rxPps, 'f', 0), dim, true}, {QString::number(x.txPps, 'f', 0), dim, true}, {Fmt::bytes(x.rxBytes), dim, true},
293
+ {Fmt::bytes(x.txBytes), dim, true}, {QString::number(x.errors), x.errors ? C::amber : dim, true}, {QString::number(x.drops), x.drops ? C::amber : dim, true}};
294
+ });
295
+ }
296
+ };
297
+
298
+ // ============================================================================ list tabs (processes, services)
299
+ using Act = QPair<QString, std::function<void()>>; // context-menu entry; empty text = separator
300
+
301
+ struct ListTab : Tab { // filterable, sortable table that keeps selection and scroll position across refreshes
302
+ QLineEdit *filter = new QLineEdit;
303
+ QLabel *summary = label({}, "Muted"), *status = label({}, "Muted");
304
+ QTableWidget *tbl;
305
+ QHBoxLayout *bar;
306
+
307
+ ListTab(const QStringList &headers, const QVector<int> &widths, const QVector<int> &bars, const QString &hint)
308
+ {
309
+ auto *l = plainRoot(this);
310
+ bar = row(l), tbl = table(headers, widths, bars);
311
+ tbl->setSortingEnabled(true), tbl->setContextMenuPolicy(Qt::CustomContextMenu);
312
+ filter->setClearButtonEnabled(true), filter->setMaximumWidth(300), filter->setPlaceholderText(hint);
313
+ bar->addWidget(filter), bar->addWidget(summary), bar->addStretch();
314
+ l->addWidget(tbl, 1), l->addWidget(status);
315
+ connect(filter, &QLineEdit::textChanged, this, [this] { applyFilter(); });
316
+ }
317
+ QString selectedKey() const
318
+ {
319
+ const int r = tbl->currentRow();
320
+ return r >= 0 && !tbl->isRowHidden(r) && tbl->item(r, 0) ? tbl->item(r, 0)->text() : QString();
321
+ }
322
+ virtual bool accept(int r) const
323
+ {
324
+ for (int c = 0; c < tbl->columnCount(); ++c)
325
+ if (tbl->item(r, c) && tbl->item(r, c)->text().contains(filter->text(), Qt::CaseInsensitive)) return true;
326
+ return false;
327
+ }
328
+ void applyFilter()
329
+ {
330
+ for (int r = 0; r < tbl->rowCount(); ++r) tbl->setRowHidden(r, !accept(r));
331
+ }
332
+ template <class V, class F> void fill(const V &items, F rowOf)
333
+ {
334
+ const QString sel = selectedKey();
335
+ const int scroll = tbl->verticalScrollBar()->value(), col = qMax(0, tbl->currentColumn());
336
+ int row = -1; // rows are reused: when the selected entry is gone the selection must go too, not pass to another entry
337
+ tbl->setSortingEnabled(false), fillRows(tbl, items, rowOf), tbl->setSortingEnabled(true);
338
+ for (int r = 0; r < tbl->rowCount() && row < 0 && !sel.isEmpty(); ++r)
339
+ if (tbl->item(r, 0)->text() == sel) row = r;
340
+ tbl->setCurrentCell(row, col), applyFilter(), tbl->verticalScrollBar()->setValue(scroll);
341
+ }
342
+ void addMenu(const QVector<Act> &items)
343
+ {
344
+ connect(tbl, &QWidget::customContextMenuRequested, this, [this, items](const QPoint &p) {
345
+ if (selectedKey().isEmpty()) return;
346
+ QMenu m;
347
+ for (const Act &a : items) a.first.isEmpty() ? (void)m.addSeparator() : (void)m.addAction(a.first, a.second);
348
+ m.exec(tbl->viewport()->mapToGlobal(p));
349
+ });
350
+ }
351
+ };
352
+
353
+ struct ProcessTab : ListTab {
354
+ QCheckBox *freeze = new QCheckBox("Freeze list");
355
+
356
+ ProcessTab() : ListTab({"PID", "Name", "User", "State", "CPU", "Memory", "RSS", "Threads", P::prioLabel, "Running for"}, {80, 230, 120, 100, 130, 130, 100, 80, 70}, {4, 5}, "Filter by name, user or PID…")
357
+ {
358
+ freeze->setToolTip("Stop refreshing so rows don't move while you pick one");
359
+ bar->insertWidget(1, freeze), tbl->sortByColumn(4, Qt::DescendingOrder);
360
+ QVector<Act> menu;
361
+ for (const Cmd &c : P::procActions()) {
362
+ menu << Act{c.label, [this, c] { run(c); }};
363
+ if (c.button) bar->addWidget(button(c.label, c.danger ? "Danger" : nullptr, menu.last().second));
364
+ }
365
+ bar->addWidget(button("Priority…", nullptr, [this] { renice(); }));
366
+ addMenu(menu << Act{} << Act{"Change priority…", [this] { renice(); }});
367
+ }
368
+ void bind(ServerSession *x) override
369
+ {
370
+ if (x != s) freeze->setChecked(false); // a frozen list would show the other server's PIDs
371
+ Tab::bind(x);
372
+ }
373
+ void refresh() override
374
+ {
375
+ if (freeze->isChecked()) return;
376
+ const Metrics &m = s->metrics();
377
+ static const QHash<QChar, QPair<QString, QColor>> states = {{'R', {"Running", C::green}}, {'S', {"Sleeping", C::muted}}, {'D', {"Disk wait", C::amber}},
378
+ {'Z', {"Zombie", C::red}}, {'T', {"Stopped", C::red}}, {'I', {"Idle", C::muted}}};
379
+ int running = 0;
380
+ fill(m.procs, [&](const ProcInfo &p) {
381
+ const auto st = states.value(p.state, {QString(p.state), C::muted});
382
+ running += p.state == 'R';
383
+ return Row{{QString::number(p.pid), C::muted, true, -1, p.pid}, {p.name}, {p.user, C::muted}, {st.first, st.second},
384
+ {Fmt::pct(p.cpu), {}, false, qMin(100.0, p.cpu), p.cpu}, {Fmt::pct(p.memPct), {}, false, p.memPct, p.memPct},
385
+ {Fmt::bytes(p.rss), {}, true, -1, p.rss}, {QString::number(p.threads), {}, true, -1, p.threads},
386
+ {QString::number(p.nice), p.nice == P::normalPrio ? C::text : C::teal, true, -1, p.nice}, {Fmt::duration(p.age), C::muted, true, -1, p.age}};
387
+ });
388
+ summary->setText(QString("%1 processes · %2 running · %3 threads").arg(m.procs.size()).arg(running).arg(m.threadsTotal));
389
+ }
390
+ QString pidName() const { return tbl->item(tbl->currentRow(), 1)->text() + " (" + selectedKey() + ")"; }
391
+ void run(const Cmd &c)
392
+ {
393
+ const int pid = selectedKey().toInt(); // read before the question: the list keeps refreshing behind it
394
+ if (!pid) return status->setText("Select a process first.");
395
+ if (!c.confirm || ask(this, c.label, QString("%1 %2 on %3?").arg(c.label, pidName(), s->config().name))) runReport(s, status, c.cmd.arg(pid));
396
+ }
397
+ void renice()
398
+ {
399
+ const int pid = selectedKey().toInt();
400
+ if (!pid) return status->setText("Select a process first.");
401
+ QStringList labels;
402
+ for (const Cmd &c : P::priorities()) labels << c.label;
403
+ bool ok = false;
404
+ const int i = labels.indexOf(QInputDialog::getItem(this, "Change priority", "Priority for " + pidName() + ":", labels, labels.size() / 2, false, &ok));
405
+ if (ok && i >= 0) runReport(s, status, P::priorities()[i].cmd.arg(pid));
406
+ }
407
+ };
408
+
409
+ struct ServiceTab : ListTab {
410
+ QComboBox *state = new QComboBox;
411
+ QString sig = "?"; // not a possible signature: the first refresh always fills
412
+
413
+ ServiceTab() : ListTab({"Service", "Active", "State", "Load", "Description"}, {300, 100, 100, 90}, {}, "Filter services…")
414
+ {
415
+ state->addItems({"All", "Running", "Failed", "Not running"});
416
+ bar->insertWidget(1, state), tbl->sortByColumn(0, Qt::AscendingOrder);
417
+ connect(state, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this] { applyFilter(); });
418
+ connect(tbl, &QTableWidget::cellDoubleClicked, this, [this] { showLogs(); });
419
+ QVector<Act> menu;
420
+ for (const Cmd &c : P::serviceActions()) {
421
+ menu << Act{c.label, [this, c] { act(c); }};
422
+ bar->addWidget(button(c.label, c.danger ? "Danger" : nullptr, menu.last().second));
423
+ }
424
+ bar->addWidget(button("Logs", "Primary", [this] { showLogs(); }));
425
+ addMenu(menu << Act{} << Act{"Show logs", [this] { showLogs(); }});
426
+ }
427
+ bool accept(int r) const override
428
+ {
429
+ const QString active = tbl->item(r, 1)->text(), sub = tbl->item(r, 2)->text();
430
+ const int st = state->currentIndex();
431
+ return (st == 0 || (st == 1 && sub == "running") || (st == 2 && active == "failed") || (st == 3 && sub != "running" && active != "failed")) && ListTab::accept(r);
432
+ }
433
+ void refresh() override
434
+ {
435
+ const Metrics &m = s->metrics();
436
+ QString sg;
437
+ for (const ServiceInfo &x : m.services) sg += x.unit + x.active + x.sub;
438
+ if (sg == sig) return; // unchanged: keep the list still
439
+ sig = sg;
440
+ fill(m.services, [](const ServiceInfo &x) {
441
+ const QColor c = x.active == "failed" ? C::red : x.sub == "running" ? C::green : x.active == "active" ? C::teal : C::muted;
442
+ return Row{{x.unit}, {x.active, c}, {x.sub, c}, {x.load, C::muted}, {x.description, C::muted}};
443
+ });
444
+ summary->setText(m.services.isEmpty() ? "No services reported by this machine" : QString("%1 services · %2 running · %3 failed").arg(m.services.size()).arg(m.servicesRunning).arg(m.servicesFailed));
445
+ }
446
+ void act(const Cmd &c)
447
+ {
448
+ const QString unit = selectedKey();
449
+ if (unit.isEmpty()) return status->setText("Select a service first.");
450
+ if (!c.confirm || ask(this, "Confirm", QString("%1 %2 on %3?").arg(c.label, unit, s->config().name))) runReport(s, status, c.cmd.arg(P::quote(unit)));
451
+ }
452
+ void showLogs()
453
+ {
454
+ const QString unit = selectedKey();
455
+ if (unit.isEmpty()) return;
456
+ auto *dlg = new QDialog(this);
457
+ auto *l = new QVBoxLayout(dlg);
458
+ auto *b = new QHBoxLayout;
459
+ auto *txt = new QPlainTextEdit("Loading…");
460
+ auto *n = new QSpinBox;
461
+ dlg->setAttribute(Qt::WA_DeleteOnClose), dlg->setWindowTitle("Logs — " + unit + " — " + s->config().name), dlg->resize(1000, 640);
462
+ txt->setReadOnly(true), txt->setFont(QFont(C::mono(), 10)), txt->setLineWrapMode(QPlainTextEdit::NoWrap);
463
+ n->setRange(50, 5000), n->setValue(300), n->setSuffix(" lines");
464
+ auto load = [ss = s, t = QPointer<QPlainTextEdit>(txt), n, unit] {
465
+ if (ss) ss->exec(P::serviceLogs(unit, n->value()), true, [t](int, const QString &out) { if (t) t->setPlainText(out), t->verticalScrollBar()->setValue(t->verticalScrollBar()->maximum()); });
466
+ };
467
+ l->addWidget(txt), l->addLayout(b);
468
+ b->addWidget(n), b->addWidget(button("Reload", nullptr, load)), b->addStretch(), b->addWidget(button("Close", nullptr, [dlg] { dlg->close(); }));
469
+ load(), dlg->show();
470
+ }
471
+ };
472
+
473
+ // ============================================================================ Console
474
+ struct ConsoleTab : Tab {
475
+ QPlainTextEdit *out = new QPlainTextEdit;
476
+ QLineEdit *in = new QLineEdit;
477
+ QCheckBox *priv = new QCheckBox("privileged");
478
+ QStringList hist;
479
+ int pos = 0;
480
+
481
+ ConsoleTab()
482
+ {
483
+ auto *l = new QHBoxLayout(this);
484
+ auto *left = new QVBoxLayout, *side = new QVBoxLayout;
485
+ auto *r = new QHBoxLayout;
486
+ auto *prompt = label("$");
487
+ auto *run = button("Run", "Primary", [this] {
488
+ const QString c = in->text().trimmed();
489
+ if (c.isEmpty()) return;
490
+ if (hist.isEmpty() || hist.last() != c) hist << c;
491
+ pos = hist.size(), in->clear(), exec(c, priv->isChecked());
492
+ });
493
+ l->setContentsMargins(4, 16, 4, 12), l->setSpacing(14), l->addLayout(left, 1), l->addLayout(side);
494
+ out->setReadOnly(true), out->setFont(QFont(C::mono(), 10)), out->setMaximumBlockCount(20000);
495
+ out->setStyleSheet("QPlainTextEdit { background: #080b12; border-radius: 10px; padding: 10px; color: #cfe3ff; }");
496
+ in->setFont(QFont(C::mono(), 11)), in->setPlaceholderText("Type a shell command and press Enter (↑/↓ history)"), in->installEventFilter(this);
497
+ priv->setToolTip("Wrap in sudo -n when the server has 'Run control commands with sudo' enabled"), priv->setVisible(P::sudo);
498
+ prompt->setStyleSheet("color: #38bdf8; font-weight: 700; font-size: 15px;");
499
+ r->addWidget(prompt), r->addWidget(in, 1), r->addWidget(priv), r->addWidget(run), r->addWidget(button("Clear", nullptr, [this] { out->clear(); }));
500
+ left->addWidget(out, 1), left->addLayout(r);
501
+ connect(in, &QLineEdit::returnPressed, run, &QPushButton::click);
502
+ auto addGroup = [&](const QString &title, const QVector<Cmd> &items, bool system) {
503
+ auto *p = panel(title);
504
+ p->setFixedWidth(270), side->addWidget(p);
505
+ for (const Cmd &q : items) {
506
+ auto *b = button(q.label, q.danger ? "Danger" : "Side", [this, q, system] {
507
+ if (!system || ask(this, q.label, QString("%1 on %2?%3").arg(q.label, s->config().name, q.danger ? "\n\nThe machine will be unavailable until it comes back." : ""))) exec(q.cmd, system);
508
+ });
509
+ b->setToolTip(q.cmd), lay(p)->addWidget(b);
510
+ }
511
+ };
512
+ addGroup("Quick diagnostics", P::diagnostics(), false), addGroup("System actions", P::systemActions(), true);
513
+ side->addStretch();
514
+ }
515
+ void bind(ServerSession *x) override
516
+ {
517
+ if (x == s) return;
518
+ out->clear(), Tab::bind(x);
519
+ if (x) out->appendHtml(QString("<span style='color:#8b95ab'>Console for <b>%1</b> (%2). Commands run non-interactively with a 120 s timeout.</span>").arg(x->config().name.toHtmlEscaped(), x->config().address()));
520
+ }
521
+ bool eventFilter(QObject *o, QEvent *e) override
522
+ {
523
+ const int k = e->type() == QEvent::KeyPress ? static_cast<QKeyEvent *>(e)->key() : 0;
524
+ if (o != in || hist.isEmpty() || (k != Qt::Key_Up && k != Qt::Key_Down)) return Tab::eventFilter(o, e);
525
+ return pos = qBound(0, pos + (k == Qt::Key_Up ? -1 : 1), hist.size()), in->setText(hist.value(pos)), true;
526
+ }
527
+ void exec(const QString &cmd, bool privileged)
528
+ {
529
+ out->appendHtml(QString("<br><span style='color:#38bdf8'><b>%1 $</b></span> %2").arg(QTime::currentTime().toString("HH:mm:ss"), cmd.toHtmlEscaped()));
530
+ auto clock = std::make_shared<QElapsedTimer>();
531
+ clock->start();
532
+ s->exec(cmd, privileged, [o = QPointer<QPlainTextEdit>(out), clock](int code, const QString &text) {
533
+ if (!o) return;
534
+ if (!text.isEmpty()) o->appendPlainText(text.endsWith('\n') ? text.chopped(1) : text);
535
+ o->appendHtml(QString("<span style='color:%1'>[exit %2 · %3 ms]</span>").arg(code ? "#ef4444" : "#22c55e").arg(code).arg(clock->elapsed()));
536
+ o->verticalScrollBar()->setValue(o->verticalScrollBar()->maximum());
537
+ }, 120000);
538
+ }
539
+ };
540
+
541
+ // ============================================================================ Alert rules
542
+ struct RulesTab : Tab {
543
+ QTableWidget *rules = table({"On", "Condition", "Severity", "Action", "Cooldown", "Live value"}, {50, 380, 100, 330, 100}), *live = table({"Active problems"});
544
+
545
+ RulesTab()
546
+ {
547
+ auto *l = plainRoot(this);
548
+ l->addWidget(label("Threshold rules are checked on every sample. When a condition holds for its duration an alert is raised and the action runs; "
549
+ "if it is still true after the cooldown the action runs again. History-based automation lives in the Insights tab.", "Muted", true));
550
+ auto *b = row(l);
551
+ b->addWidget(button("+ Add rule", "Primary", [this] { editRule(-1); })), b->addWidget(button("Edit", nullptr, [this] { editRule(rules->currentRow()); }));
552
+ b->addWidget(button("Delete", "Danger", [this] {
553
+ auto rs = s->config().rules;
554
+ if (rules->currentRow() >= 0 && rules->currentRow() < rs.size()) rs.remove(rules->currentRow()), store(rs);
555
+ }));
556
+ b->addStretch();
557
+ b->addWidget(button("Reset to defaults", nullptr, [this] {
558
+ if (ask(this, "Reset rules", "Replace all rules with the defaults?")) store(ServerConfig::defaultRules());
559
+ }));
560
+ live->setMaximumHeight(160), l->addWidget(rules, 2), l->addWidget(live, 1);
561
+ connect(rules, &QTableWidget::cellDoubleClicked, this, [this](int r) { editRule(r); });
562
+ connect(rules, &QTableWidget::itemChanged, this, [this](QTableWidgetItem *it) { // the "On" checkbox
563
+ auto rs = s->config().rules;
564
+ const bool on = it->checkState() == Qt::Checked;
565
+ if (it->column() == 0 && it->row() < rs.size() && rs[it->row()].enabled != on) rs[it->row()].enabled = on, store(rs);
566
+ });
567
+ }
568
+ void bind(ServerSession *x) override { Tab::bind(x), reload(); }
569
+ void store(const QVector<Rule> &rs)
570
+ {
571
+ ServerConfig c = s->config();
572
+ c.rules = rs, save(c), reload();
573
+ }
574
+ void reload()
575
+ {
576
+ if (!s) return;
577
+ QSignalBlocker block(rules);
578
+ fillRows(rules, s->config().rules, [](const Rule &r) {
579
+ return Row{{}, {r.conditionText(), r.enabled ? QColor() : C::faint}, {r.severity, C::severity(r.severity)},
580
+ {r.actionText(), r.action == "notify" ? C::muted : C::violet}, {QString("%1 s").arg(r.cooldown), C::muted}};
581
+ });
582
+ for (int i = 0; i < rules->rowCount(); ++i) rules->item(i, 0)->setCheckState(s->config().rules[i].enabled ? Qt::Checked : Qt::Unchecked);
583
+ refresh();
584
+ }
585
+ void refresh() override
586
+ {
587
+ const auto &rs = s->config().rules;
588
+ const QStringList act = s->activeAlerts();
589
+ QSignalBlocker block(rules);
590
+ for (int i = 0; i < rs.size() && i < rules->rowCount(); ++i) {
591
+ const double v = s->metricValue(rs[i].metric);
592
+ cell(rules, i, 5, {QString::number(v, 'f', 1) + " " + defLabel(ruleMetrics(), rs[i].metric, true), (rs[i].op == "<" ? v < rs[i].value : v > rs[i].value) ? C::red : C::green});
593
+ }
594
+ fillRows(live, act, [](const QString &a) { return Row{{"⚠ " + a, C::red}}; });
595
+ if (act.isEmpty()) live->setRowCount(1), cell(live, 0, 0, {"✓ No rule is currently triggered", C::green});
596
+ }
597
+ void editRule(int idx)
598
+ {
599
+ auto rs = s->config().rules;
600
+ Rule r;
601
+ r.id = ServerConfig::newId();
602
+ if (idx >= 0 && idx < rs.size()) r = rs[idx];
603
+ else idx = -1;
604
+ QDialog dlg(this);
605
+ dlg.setWindowTitle(idx < 0 ? "New rule" : "Edit rule");
606
+ auto *f = new QFormLayout(&dlg);
607
+ auto *metric = new QComboBox, *op = new QComboBox, *sev = new QComboBox, *action = new QComboBox;
608
+ auto *value = new QDoubleSpinBox;
609
+ auto *dur = new QSpinBox, *cool = new QSpinBox;
610
+ auto *arg = new QLineEdit(r.arg);
611
+ auto *en = new QCheckBox("Enabled");
612
+ auto *cond = new QHBoxLayout;
613
+ auto *bb = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel);
614
+ for (const Def &d : ruleMetrics()) metric->addItem(d.label + (d.unit.isEmpty() ? "" : " (" + d.unit + ")"), d.key);
615
+ for (const Def &d : P::ruleActions()) action->addItem(d.label, d.key);
616
+ op->addItems({">", "<"}), sev->addItems({"info", "warning", "critical"});
617
+ metric->setCurrentIndex(qMax(0, metric->findData(r.metric))), action->setCurrentIndex(qMax(0, action->findData(r.action)));
618
+ op->setCurrentText(r.op), sev->setCurrentText(r.severity), en->setChecked(r.enabled);
619
+ value->setRange(-1e9, 1e9), value->setValue(r.value);
620
+ dur->setRange(0, 86400), dur->setSuffix(" s"), dur->setValue(r.duration);
621
+ cool->setRange(10, 86400), cool->setSuffix(" s"), cool->setValue(r.cooldown);
622
+ auto sync = [action, arg] {
623
+ const QString hint = defLabel(P::ruleActions(), action->currentData().toString(), true);
624
+ arg->setEnabled(!hint.isEmpty()), arg->setPlaceholderText(hint);
625
+ };
626
+ connect(action, QOverload<int>::of(&QComboBox::currentIndexChanged), &dlg, sync);
627
+ connect(bb, &QDialogButtonBox::accepted, &dlg, &QDialog::accept), connect(bb, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
628
+ cond->addWidget(op), cond->addWidget(value, 1), sync();
629
+ f->addRow("When", metric), f->addRow("is", cond), f->addRow("for at least", dur), f->addRow("Severity", sev), f->addRow("Then", action);
630
+ f->addRow("Argument", arg), f->addRow("Repeat after", cool), f->addRow("", en), f->addRow(bb);
631
+ if (dlg.exec() != QDialog::Accepted) return;
632
+ r.metric = metric->currentData().toString(), r.op = op->currentText(), r.value = value->value(), r.duration = dur->value(), r.severity = sev->currentText();
633
+ r.action = action->currentData().toString(), r.arg = arg->isEnabled() ? arg->text().trimmed() : "", r.cooldown = cool->value(), r.enabled = en->isChecked();
634
+ idx < 0 ? (void)(rs << r) : (void)(rs[idx] = r);
635
+ store(rs);
636
+ }
637
+ };
638
+
639
+ // ============================================================================ History
640
+ struct HistoryTab : Tab {
641
+ qint64 range = 86400, lastLoad = 0;
642
+ QLabel *res = label({}, "Muted");
643
+ QVector<TimeChart *> charts;
644
+ QTableWidget *st = table({"Metric", "Minimum", "Average", "95th percentile", "Peak", "Points"}, {200, 150, 150, 150, 150});
645
+ QVector<HPoint> pts;
646
+
647
+ HistoryTab()
648
+ {
649
+ auto *l = scrollRoot(this);
650
+ auto *b = row(l);
651
+ auto *group = new QButtonGroup(this);
652
+ b->setSpacing(6);
653
+ for (auto [text, sec] : {std::pair{"1 h", 3600}, {"6 h", 21600}, {"24 h", 86400}, {"7 d", 604800}, {"30 d", 2592000}, {"90 d", 7776000}, {"1 y", 31536000}, {"All", 0}}) {
654
+ auto *btn = button(text);
655
+ btn->setCheckable(true), btn->setChecked(sec == 86400), group->addButton(btn, sec / 60), b->addWidget(btn);
656
+ }
657
+ b->addSpacing(14), b->addWidget(res), b->addStretch(), b->addWidget(button("Export CSV…", nullptr, [this] { exportCsv(); }));
658
+ connect(group, &QButtonGroup::idClicked, this, [this](int id) { range = id * 60LL, reload(); });
659
+ auto *g = grid(l);
660
+ for (auto [title, fmt, max] : {std::tuple{"CPU", pctFmt, 100.0}, {"Memory & swap", pctFmt, 100.0}, {"Disk usage (fullest)", pctFmt, 100.0},
661
+ {"Disk throughput", rateFmt, 0.0}, {"Network", rateFmt, 0.0}, {"Load average", numFmt(1), 0.0},
662
+ {"Temperature", FmtFn([](double v) { return QString::number(v, 'f', 0) + "°"; }), 0.0}, {"Availability", pctFmt, 100.0}}) {
663
+ charts << new TimeChart(title, fmt, max);
664
+ charts.last()->setMinimumHeight(240), charts.last()->empty = "No history for this range yet", g->addWidget(charts.last(), (charts.size() - 1) / 2, (charts.size() - 1) % 2);
665
+ }
666
+ st->setMinimumHeight(14 * 30 + 40), l->addWidget(panel("Statistics for the selected range", {st}));
667
+ }
668
+ void bind(ServerSession *x) override { Tab::bind(x), lastLoad = 0; }
669
+ void refresh() override
670
+ {
671
+ if (QDateTime::currentMSecsSinceEpoch() - lastLoad >= (range && range <= 21600 ? 5000 : 60000)) reload();
672
+ }
673
+ void reload()
674
+ {
675
+ lastLoad = QDateTime::currentMSecsSinceEpoch();
676
+ const qint64 now = QDateTime::currentSecsSinceEpoch(), from = range ? now - range : qMax<qint64>(1, s->store().firstTs());
677
+ Tier tier;
678
+ pts = s->store().range(from, now, &tier);
679
+ const qint64 step = qMax<qint64>(HistoryStore::step[int(tier)], s->config().interval);
680
+ QVector<qint64> t;
681
+ enum { CPU, CPUMAX, MEM, SWAP, DISK, RD, WR, RX, TX, RXMAX, LOAD, TEMP, TEMPMAX, AVAIL, N };
682
+ QVector<double> v[N];
683
+ double n = 0, up = 0;
684
+ auto push = [&](qint64 ts, const HPoint *p) { // p = nullptr inserts a gap
685
+ t << ts * 1000;
686
+ const int src[N] = {H_CPU, H_CPU, H_MEM, H_SWAP, H_DISK, H_RD, H_WR, H_RX, H_TX, H_RX, H_LOAD, H_TEMP, H_TEMP, -1};
687
+ for (int i = 0; i < N; ++i)
688
+ v[i] << (!p ? NAN : i == AVAIL ? p->uptimePct() : !p->nUp ? NAN : (i == CPUMAX || i == RXMAX || i == TEMPMAX) ? p->max[src[i]] : p->avg[src[i]]);
689
+ };
690
+ for (const HPoint &p : qAsConst(pts)) {
691
+ if (!t.isEmpty() && p.ts * 1000 - t.last() > step * 3000) push(t.last() / 1000 + step, nullptr); // app was not running
692
+ push(p.ts, &p), n += p.n, up += p.nUp;
693
+ }
694
+ if (!t.isEmpty() && now * 1000 - t.last() > step * 3000) push(now, nullptr);
695
+ const bool agg = tier != Tier::Raw;
696
+ auto peak = [&](QVector<Series> s, const QString &name, const QColor &c, const QVector<double> &d) { if (agg) s << Series{name, c, d, false, true}; return s; };
697
+ const QVector<QVector<Series>> data = {peak({{"Average", C::accent, v[CPU]}}, "Peak", C::red, v[CPUMAX]),
698
+ {{"Memory", C::violet, v[MEM]}, {"Swap", C::pink, v[SWAP], false}}, {{"Usage", C::amber, v[DISK]}},
699
+ {{"Read", C::blue, v[RD]}, {"Write", C::orange, v[WR]}},
700
+ peak({{"Down", C::teal, v[RX]}, {"Up", C::pink, v[TX]}}, "Peak down", C::teal.lighter(140), v[RXMAX]),
701
+ {{"Load", C::violet, v[LOAD]}}, peak({{"Average", C::orange, v[TEMP]}}, "Peak", C::red, v[TEMPMAX]),
702
+ {{"Online", C::green, v[AVAIL]}}};
703
+ for (int i = 0; i < charts.size(); ++i) charts[i]->subtitle = agg ? "avg per " + tierName(tier) : "", charts[i]->setData(t, data[i], (now - from) * 1000);
704
+ res->setText(QString("Resolution: %1 · %2 points · availability %3 · stored %4").arg(tierName(tier)).arg(pts.size()).arg(n ? Fmt::pct(up * 100 / n, 2) : "—", Fmt::bytes(s->store().diskBytes())));
705
+ QVector<int> ms = {H_CPU, H_IOWAIT, H_LOAD, H_MEM, H_SWAP, H_DISK, H_DISKIO, H_RX, H_TX, H_RD, H_WR, H_TEMP, H_PROCS, H_GPU};
706
+ if (!P::posixCpu) ms.remove(1);
707
+ fillRows(st, ms, [&](int m) {
708
+ const Stats x = stats(pts, m);
709
+ return Row{{hNames[m]}, {fmtMetric(m, x.min), C::muted, true}, {fmtMetric(m, x.avg), {}, true}, {fmtMetric(m, x.p95), C::amber, true},
710
+ {fmtMetric(m, x.max), C::red, true}, {QString::number(x.count), C::muted, true}};
711
+ });
712
+ }
713
+ void exportCsv()
714
+ {
715
+ const QString fn = QFileDialog::getSaveFileName(this, "Export history", s->config().name + "-history.csv", "CSV (*.csv)");
716
+ QFile f(fn);
717
+ if (fn.isEmpty() || !f.open(QIODevice::WriteOnly | QIODevice::Text)) return;
718
+ QTextStream ts(&f);
719
+ ts << "time,samples,online_pct";
720
+ for (const char *k : hKeys) ts << ',' << k << "_avg," << k << "_max";
721
+ auto num = [](float x) { return std::isnan(x) ? QString() : QString::number(x, 'f', 3); };
722
+ for (const HPoint &p : qAsConst(pts)) {
723
+ ts << '\n' << QDateTime::fromSecsSinceEpoch(p.ts).toString(Qt::ISODate) << ',' << p.n << ',' << p.uptimePct();
724
+ for (int m = 0; m < H_COUNT; ++m) ts << ',' << num(p.avg[m]) << ',' << num(p.max[m]);
725
+ }
726
+ }
727
+ };
728
+
729
+ // ============================================================================ Insights & Autopilot
730
+ struct InsightsTab : Tab {
731
+ RingGauge *health = new RingGauge("Health score");
732
+ QLabel *reasons = label({}, "Muted", true), *capacity = label({}, nullptr, true);
733
+ QVector<StatTile *> t;
734
+ QVBoxLayout *findings = new QVBoxLayout;
735
+ WeekHeatmap *heat = new WeekHeatmap;
736
+ QComboBox *heatMetric = new QComboBox;
737
+ QTableWidget *anomalies = table({"Metric", "Last 10 min", "Usual", "Deviation", "Baseline"}, {110, 110, 160, 90});
738
+ QVector<std::function<void(AutopilotConfig &, bool load)>> binds; // autopilot form <-> config
739
+ bool loading = false;
740
+
741
+ // form-field builders bound to AutopilotConfig members
742
+ QWidget *chk(const QString &text, bool AutopilotConfig::*f)
743
+ {
744
+ auto *w = new QCheckBox(text);
745
+ binds << [w, f](AutopilotConfig &a, bool ld) { ld ? w->setChecked(a.*f) : void(a.*f = w->isChecked()); };
746
+ connect(w, &QCheckBox::toggled, this, [this] { store(); });
747
+ return w;
748
+ }
749
+ template <class T, class W> QWidget *spin(T AutopilotConfig::*f, double lo, double hi, const QString &pre, const QString &suf)
750
+ {
751
+ auto *w = new W;
752
+ w->setRange(lo, hi), w->setPrefix(pre), w->setSuffix(suf);
753
+ if constexpr (std::is_same_v<W, QDoubleSpinBox>) w->setDecimals(f == &AutopilotConfig::anomalyZ ? 1 : 0), w->setSingleStep(f == &AutopilotConfig::anomalyZ ? 0.5 : 1);
754
+ binds << [w, f](AutopilotConfig &a, bool ld) { ld ? w->setValue(a.*f) : void(a.*f = w->value()); };
755
+ connect(w, QOverload<T>::of(&W::valueChanged), this, [this] { store(); });
756
+ return w;
757
+ }
758
+ QWidget *combo(QString AutopilotConfig::*f, const QStringList &keys, const QStringList &labels)
759
+ {
760
+ auto *w = new QComboBox;
761
+ for (int i = 0; i < keys.size(); ++i) w->addItem(labels[i], keys[i]);
762
+ binds << [w, f](AutopilotConfig &a, bool ld) { ld ? w->setCurrentIndex(qMax(0, w->findData(a.*f))) : void(a.*f = w->currentData().toString()); };
763
+ connect(w, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this] { store(); });
764
+ return w;
765
+ }
766
+
767
+ InsightsTab()
768
+ {
769
+ using A = AutopilotConfig;
770
+ using DS = QDoubleSpinBox;
771
+ auto *l = scrollRoot(this);
772
+ auto *top = row(l);
773
+ auto *hp = panel("Health", {health, reasons, button("Analyze now", nullptr, [this] { s->analyzeNow(); })});
774
+ hp->setFixedWidth(330), health->setMinimumHeight(190), top->addWidget(hp);
775
+ auto *right = sub<QVBoxLayout>(top, 1);
776
+ t = addTiles(grid(right), {{"Disk full forecast", C::amber}, {"Memory trend (6 h)", C::violet}, {"CPU / memory p95 (30 d)", C::accent},
777
+ {"Availability 24 h", C::green}, {"Availability 7 d", C::green}, {"Availability 30 d", C::green}}, 3);
778
+ right->addWidget(panel("Capacity planning", {capacity, nullptr}));
779
+
780
+ auto *mid = row(l);
781
+ auto *fp = panel("Findings from history analysis");
782
+ auto *ap = panel("Autopilot — automatic control", {label("Acts on the findings once a minute, using statistics over the stored history. Every action is logged as an event.", "Muted", true)});
783
+ auto *form = new QFormLayout;
784
+ auto *runRow = new QHBoxLayout;
785
+ auto *cmd = new QLineEdit;
786
+ findings->setSpacing(10), lay(fp)->addLayout(findings), lay(fp)->addStretch(), mid->addWidget(fp, 1);
787
+ runRow->addWidget(spin<double, DS>(&A::runawayCpu, 10, 6400, "≥ ", " %")), runRow->addWidget(spin<int, QSpinBox>(&A::runawayMinutes, 1, 1440, "for ", " min"));
788
+ cmd->setFont(QFont(C::mono(), 9));
789
+ binds << [cmd](A &a, bool ld) { ld ? cmd->setText(a.diskCleanupCommand) : void(a.diskCleanupCommand = cmd->text().trimmed()); };
790
+ connect(cmd, &QLineEdit::editingFinished, this, [this] { store(); });
791
+ form->addRow(chk("Autopilot enabled", &A::enabled), chk("Dry run (only report)", &A::dryRun));
792
+ form->addRow(chk("Restart failed services", &A::restartFailed), spin<int, QSpinBox>(&A::maxRestartsPerHour, 1, 20, "", " / hour max"));
793
+ form->addRow("Runaway processes", combo(&A::runawayMode, {"none", "renice", "terminate"}, {"Ignore", "Lower priority (renice 19)", "Terminate"}));
794
+ form->addRow("", runRow);
795
+ form->addRow("Memory leaks", combo(&A::leakMode, {"none", "notify", "terminate"}, {"Ignore", "Notify", "Terminate under pressure"}));
796
+ form->addRow(" pressure ≥", spin<double, DS>(&A::leakMemPressure, 50, 100, "", " % memory"));
797
+ form->addRow(chk("Disk cleanup", &A::diskCleanup), spin<int, QSpinBox>(&A::diskForecastDays, 1, 60, "full in < ", " days"));
798
+ form->addRow("", spin<double, DS>(&A::diskCleanupAt, 50, 100, "or usage ≥ ", " %"));
799
+ form->addRow(" command", cmd);
800
+ form->addRow(chk("Anomaly alerts", &A::anomalyAlerts), spin<double, DS>(&A::anomalyZ, 1.5, 10, "z ≥ ", " σ"));
801
+ ap->setFixedWidth(430), lay(ap)->addLayout(form), lay(ap)->addStretch(), mid->addWidget(ap, 0, Qt::AlignTop);
802
+
803
+ auto *bot = row(l);
804
+ heatMetric->addItems({"CPU", "Memory"}), heatMetric->setFixedWidth(140), anomalies->setMinimumHeight(230);
805
+ connect(heatMetric, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this] { analysis(); });
806
+ bot->addWidget(panel("Weekly pattern (last 4 weeks, hourly averages)", {heatMetric, heat}), 3), bot->addWidget(panel("Now vs. normal (baselines)", {anomalies}), 2);
807
+ }
808
+ void bind(ServerSession *x) override
809
+ {
810
+ Tab::bind(x);
811
+ if (!x) return;
812
+ AutopilotConfig a = x->config().autopilot;
813
+ loading = true;
814
+ for (auto &b : binds) b(a, true);
815
+ loading = false, analysis();
816
+ }
817
+ void store()
818
+ {
819
+ if (loading || !s) return;
820
+ ServerConfig c = s->config();
821
+ for (auto &b : binds) b(c.autopilot, false);
822
+ save(c);
823
+ }
824
+ void analysis() override
825
+ {
826
+ const Analysis &a = s->analysis();
827
+ const int hi = heatMetric->currentIndex();
828
+ health->setValue(a.health, QString::number(a.health), "grade " + a.grade, C::health(a.health));
829
+ reasons->setText((a.healthReasons.isEmpty() ? "No deductions — everything looks healthy." : a.healthReasons.join('\n')) +
830
+ (a.when ? "\n\nAnalyzed " + QDateTime::fromSecsSinceEpoch(a.when).toString("HH:mm:ss") : ""));
831
+ if (a.diskFullDays >= 0) t[0]->set(Fmt::duration(a.diskFullDays * 86400), QString("+%1 pts/day · %2").arg(a.diskSlopePerDay, 0, 'f', 2).arg(a.diskBasis), a.diskFullDays < 7 ? C::red : a.diskFullDays < 30 ? C::amber : QColor());
832
+ else t[0]->set("Not filling", a.diskBasis.isEmpty() ? "needs ~2 h of history" : QString("trend %1 pts/day").arg(a.diskSlopePerDay, 0, 'f', 2), C::green);
833
+ if (a.memTrendR2 > 0) t[1]->set(QString("%1%2 pts/h").arg(a.memSlopePerHour >= 0 ? "+" : "").arg(a.memSlopePerHour, 0, 'f', 2), QString("fit R² %1").arg(a.memTrendR2, 0, 'f', 2), a.memSlopePerHour > 1 && a.memTrendR2 > .8 ? C::amber : QColor());
834
+ else t[1]->set("—", "needs ~90 min of history");
835
+ t[2]->set(a.cpu30.count ? Fmt::pct(a.cpu30.p95, 0) + " / " + Fmt::pct(a.mem30.p95, 0) : "—", a.cpu30.count ? "avg " + Fmt::pct(a.cpu30.avg, 0) + " / " + Fmt::pct(a.mem30.avg, 0) : "collecting");
836
+ for (int i = 0; i < 3; ++i)
837
+ std::isnan(a.up[i]) ? t[3 + i]->set("—", "no data yet")
838
+ : t[3 + i]->set(Fmt::pct(a.up[i], a.up[i] >= 99.995 ? 0 : 2), "≈ " + Fmt::duration(a.down[i]) + " offline", a.up[i] >= 99.9 ? C::green : a.up[i] >= 99 ? C::amber : C::red);
839
+ capacity->setText("<p>• " + a.capacity.join("</p><p>• ") + "</p>");
840
+ heat->setData(a.heat[hi], a.heatN, hi ? "% memory" : "% CPU", hi ? C::violet : C::accent);
841
+ fillRows(anomalies, a.anomalies, [](const Anomaly &x) {
842
+ const double az = qAbs(x.z);
843
+ return Row{{x.metric}, {fmtMetric(x.hm, x.now), {}, true}, {fmtMetric(x.hm, x.mean) + " ± " + fmtMetric(x.hm, x.sd), C::muted, true},
844
+ {QString("%1%2σ").arg(x.z >= 0 ? "+" : "").arg(x.z, 0, 'f', 1), az >= 3 ? C::red : az >= 2 ? C::amber : C::green, true}, {x.baseline, C::muted}};
845
+ });
846
+
847
+ while (QLayoutItem *it = findings->takeAt(0)) { // rebuild the finding cards
848
+ if (it->widget()) it->widget()->deleteLater();
849
+ delete it;
850
+ }
851
+ if (a.findings.isEmpty()) {
852
+ auto *ok = label("✓ No problems found in the history. The analyzer checks disk forecasts, memory trends, leaks, runaway processes, service failures, overload and anomalies every minute.", nullptr, true);
853
+ ok->setStyleSheet("color: #22c55e; padding: 10px;"), findings->addWidget(ok);
854
+ }
855
+ const AutopilotConfig &ap = s->config().autopilot;
856
+ for (const Finding &f : a.findings) {
857
+ const QColor c = C::severity(f.severity);
858
+ auto *card = new QFrame;
859
+ auto *cl = new QHBoxLayout(card);
860
+ card->setObjectName("F");
861
+ card->setStyleSheet(QString("#F { background: #1a2133; border: 1px solid #27314a; border-left: 4px solid %1; border-radius: 10px; }").arg(c.name()));
862
+ cl->addWidget(label(QString("<span style='color:%1;font-size:11px;font-weight:700'>%2 · %3</span><br><span style='font-size:14px;font-weight:600'>%4</span><br>%5<br>"
863
+ "<span style='color:#8b95ab'>→ %6</span>%7").arg(c.name(), f.severity.toUpper(), f.category.toUpper(), f.title.toHtmlEscaped(), f.detail.toHtmlEscaped(), f.advice.toHtmlEscaped(),
864
+ f.autoEligible && ap.enabled ? QString("<br><span style='color:#a78bfa;font-size:11px'>%1</span>").arg(ap.dryRun ? "Autopilot (dry run) would act on this" : "Autopilot handles this automatically") : ""),
865
+ nullptr, true), 1);
866
+ findings->addWidget(card);
867
+ if (f.action.isEmpty()) continue;
868
+ auto *b = button(f.actionLabel, f.action == "kill_pid" ? "Danger" : "Primary");
869
+ cl->addWidget(b, 0, Qt::AlignVCenter);
870
+ connect(b, &QPushButton::clicked, this, [this, f, pb = QPointer<QPushButton>(b)] { // the card may be rebuilt while the question is open
871
+ if (!ask(this, f.actionLabel, QString("%1 on %2?\n\n%3").arg(f.actionLabel, s->config().name, f.title))) return;
872
+ if (pb) pb->setEnabled(false), pb->setText("Working…");
873
+ s->runFinding(f, false, [pb](int code, const QString &) { if (pb) pb->setText(code ? "✗ Failed" : "✓ Done"); });
874
+ });
875
+ }
876
+ }
877
+ };
878
+
879
+ QVector<QPair<QString, Tab *>> makeTabs()
880
+ {
881
+ return {{"Overview", new OverviewTab}, {"CPU", new CpuTab}, {"Memory", new MemoryTab}, {"Storage", new StorageTab}, {"Network", new NetworkTab},
882
+ {"Processes", new ProcessTab}, {"Services", new ServiceTab}, {"History", new HistoryTab}, {"Insights && Autopilot", new InsightsTab},
883
+ {"Alert rules", new RulesTab}, {"Console", new ConsoleTab}};
884
+ }
Server Monitor(cqt-window)/src/ui/Widgets.cpp ADDED
@@ -0,0 +1,485 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #include "Widgets.h"
2
+ #include <QDateTime>
3
+ #include <QFontDatabase>
4
+ #include <QGridLayout>
5
+ #include <QHeaderView>
6
+ #include <QMessageBox>
7
+ #include <QMouseEvent>
8
+ #include <QPainterPath>
9
+ #include <QToolTip>
10
+ #include <QVBoxLayout>
11
+ #include <cmath>
12
+
13
+ // ---- theme --------------------------------------------------------------------------------
14
+ QColor C::level(double p, double w, double c) { return p >= c ? red : p >= w ? amber : green; }
15
+ QColor C::severity(const QString &s) { return s == "critical" ? red : s == "warning" ? amber : s == "resolved" ? green : s == "action" ? violet : accent; }
16
+ QColor C::health(int h) { return h >= 90 ? green : h >= 75 ? teal : h >= 60 ? amber : h >= 40 ? orange : red; }
17
+ QColor C::mix(const QColor &a, const QColor &b, double t)
18
+ {
19
+ t = qBound(0.0, t, 1.0);
20
+ return QColor::fromRgbF(a.redF() + (b.redF() - a.redF()) * t, a.greenF() + (b.greenF() - a.greenF()) * t, a.blueF() + (b.blueF() - a.blueF()) * t);
21
+ }
22
+ QString C::mono() { return QFontDatabase::systemFont(QFontDatabase::FixedFont).family(); }
23
+
24
+ QString C::styleSheet()
25
+ {
26
+ return R"(
27
+ * { color: #e6ebf5; font-size: 13px; }
28
+ QMainWindow, QDialog, #Page { background: #0d111c; }
29
+ #Sidebar { background: #10151f; border-right: 1px solid #1f2738; }
30
+ QToolTip { background: #1a2133; border: 1px solid #38bdf8; padding: 6px; border-radius: 6px; }
31
+ QLabel#H1 { font-size: 22px; font-weight: 700; } QLabel#H2 { font-size: 16px; font-weight: 600; }
32
+ QLabel#Muted { color: #8b95ab; } QLabel#Section { color: #8b95ab; font-size: 11px; font-weight: 700; letter-spacing: 1px; }
33
+ QFrame#Panel { background: #161c2b; border: 1px solid #232c41; border-radius: 12px; }
34
+ QPushButton { background: #1d2538; border: 1px solid #2c3650; border-radius: 8px; padding: 7px 14px; font-weight: 600; }
35
+ QPushButton:hover { background: #253049; border-color: #38bdf8; } QPushButton:pressed { background: #18324a; }
36
+ QPushButton:disabled { color: #5a657d; border-color: #222a3c; }
37
+ QPushButton:checked, QPushButton#Primary { background: #0e7ab8; border-color: #38bdf8; color: white; } QPushButton#Primary:hover { background: #1190d8; }
38
+ QPushButton#Danger { background: #3a1820; border-color: #7f2a36; color: #ffb4bd; } QPushButton#Danger:hover { background: #55202b; border-color: #ef4444; }
39
+ QPushButton#Nav { text-align: left; padding: 10px 14px; border: none; background: transparent; font-size: 14px; }
40
+ QPushButton#Nav:hover { background: #1a2133; } QPushButton#Nav:checked { background: #17304a; color: #7dd3fc; }
41
+ QPushButton#Flat { background: transparent; border: none; padding: 4px 8px; color: #8b95ab; } QPushButton#Flat:hover { color: #e6ebf5; }
42
+ QPushButton#Side { text-align: left; padding: 6px 12px; }
43
+ QLineEdit, QSpinBox, QDoubleSpinBox, QComboBox, QPlainTextEdit { background: #111727; border: 1px solid #2a3449; border-radius: 7px; padding: 6px 8px; selection-background-color: #0e7ab8; }
44
+ QLineEdit:focus, QSpinBox:focus, QDoubleSpinBox:focus, QComboBox:focus, QPlainTextEdit:focus { border-color: #38bdf8; }
45
+ QComboBox::drop-down { border: none; width: 22px; }
46
+ QComboBox QAbstractItemView { background: #161c2b; border: 1px solid #2a3449; selection-background-color: #17304a; }
47
+ QCheckBox::indicator { width: 16px; height: 16px; border-radius: 4px; border: 1px solid #3a4662; background: #111727; }
48
+ QCheckBox::indicator:checked { background: #0ea5e9; border-color: #38bdf8; }
49
+ QTabWidget::pane { border: none; }
50
+ QTabBar::tab { background: transparent; color: #8b95ab; padding: 10px 14px; border-bottom: 2px solid transparent; }
51
+ QTabBar::tab:hover { color: #e6ebf5; } QTabBar::tab:selected { color: #7dd3fc; border-bottom: 2px solid #38bdf8; }
52
+ QTableView, QListView { background: #131929; alternate-background-color: #161d2e; border: 1px solid #232c41; border-radius: 10px;
53
+ selection-background-color: #17304a; selection-color: #e6ebf5; outline: none; }
54
+ QTableView::item { padding: 4px; }
55
+ QHeaderView::section { background: #182033; color: #8b95ab; border: none; border-bottom: 1px solid #27314a; padding: 7px 8px; font-weight: 700; font-size: 12px; }
56
+ QScrollBar:vertical { background: transparent; width: 10px; margin: 2px; } QScrollBar:horizontal { background: transparent; height: 10px; margin: 2px; }
57
+ QScrollBar::handle { background: #2a3449; border-radius: 4px; min-height: 30px; min-width: 30px; } QScrollBar::handle:hover { background: #3b4866; }
58
+ QScrollBar::add-line, QScrollBar::sub-line { width: 0; height: 0; } QScrollBar::add-page, QScrollBar::sub-page { background: none; }
59
+ QScrollArea { border: none; background: transparent; } QScrollArea > QWidget > QWidget { background: transparent; }
60
+ QMenu { background: #161c2b; border: 1px solid #2a3449; border-radius: 8px; padding: 6px; }
61
+ QMenu::item { padding: 7px 22px; border-radius: 5px; } QMenu::item:selected { background: #17304a; }
62
+ QMenu::separator { height: 1px; background: #27314a; margin: 4px 8px; }
63
+ )";
64
+ }
65
+
66
+ QIcon C::appIcon()
67
+ {
68
+ QIcon icon;
69
+ for (int s : {16, 32, 64, 128, 256}) {
70
+ QPixmap pm(s, s);
71
+ pm.fill(Qt::transparent);
72
+ QPainter p(&pm);
73
+ p.setRenderHint(QPainter::Antialiasing);
74
+ QLinearGradient g(0, 0, s, s);
75
+ g.setColorAt(0, 0x0ea5e9), g.setColorAt(1, 0x7c3aed);
76
+ p.setBrush(g), p.setPen(Qt::NoPen);
77
+ p.drawRoundedRect(QRectF(0, 0, s, s), s * .22, s * .22);
78
+ p.setPen(QPen(Qt::white, qMax(1.5, s * .075), Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
79
+ p.drawPolyline(QPolygonF({{s * .12, s * .56}, {s * .34, s * .56}, {s * .44, s * .28}, {s * .56, s * .78}, {s * .66, s * .48}, {s * .88, s * .48}}));
80
+ icon.addPixmap(pm);
81
+ }
82
+ return icon;
83
+ }
84
+
85
+ QFont pxFont(QFont f, int px, bool bold) { return f.setPixelSize(px), f.setBold(bold), f; }
86
+ static double niceCeil(double v)
87
+ {
88
+ if (v <= 0) return 1;
89
+ const double e = std::pow(10, std::floor(std::log10(v))), f = v / e;
90
+ return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * e;
91
+ }
92
+ static void roundedPanel(QPainter &p, const QRectF &r, const QBrush &b, const QColor &border = C::border, double rad = 12)
93
+ {
94
+ p.setPen(QPen(border, 1)), p.setBrush(b);
95
+ p.drawRoundedRect(r.adjusted(.5, .5, -.5, -.5), rad, rad);
96
+ }
97
+
98
+ void paintRing(QPainter &p, const QRectF &r, double pct, const QColor &c, double t, bool glow)
99
+ {
100
+ p.save();
101
+ p.setRenderHint(QPainter::Antialiasing);
102
+ const QRectF rr = r.adjusted(t / 2, t / 2, -t / 2, -t / 2);
103
+ p.setPen(QPen(C::grid, t, Qt::SolidLine, Qt::RoundCap));
104
+ p.drawArc(rr, 225 * 16, -270 * 16);
105
+ const int span = int(-270 * 16 * qBound(0.0, pct, 100.0) / 100);
106
+ if (span < -3) {
107
+ if (glow) p.setPen(QPen(C::tint(c, 45), t * 2, Qt::SolidLine, Qt::RoundCap)), p.drawArc(rr, 225 * 16, span);
108
+ p.setPen(QPen(c, t, Qt::SolidLine, Qt::RoundCap));
109
+ p.drawArc(rr, 225 * 16, span);
110
+ }
111
+ p.restore();
112
+ }
113
+
114
+ // ---- RingGauge ------------------------------------------------------------------------------
115
+ RingGauge::RingGauge(const QString &title) : m_title(title)
116
+ {
117
+ m_anim.setDuration(450), m_anim.setEasingCurve(QEasingCurve::OutCubic);
118
+ connect(&m_anim, &QVariantAnimation::valueChanged, this, [this](const QVariant &v) { m_shown = v.toDouble(), update(); });
119
+ }
120
+ void RingGauge::setValue(double pct, const QString &center, const QString &sub, const QColor &color)
121
+ {
122
+ m_center = center, m_sub = sub, m_color = color;
123
+ pct = std::isnan(pct) ? 0 : pct;
124
+ if (qAbs(pct - m_target) > 0.05) m_anim.stop(), m_anim.setStartValue(m_shown), m_anim.setEndValue(m_target = pct), m_anim.start();
125
+ update();
126
+ }
127
+ void RingGauge::paintEvent(QPaintEvent *)
128
+ {
129
+ AA p(this);
130
+ const double s = qMin(width() - 8.0, height() - 28.0);
131
+ const QRectF r((width() - s) / 2, 4, s, s);
132
+ paintRing(p, r, m_shown, m_color.isValid() ? m_color : C::level(m_target, warn, crit), qMax(7.0, s * .085));
133
+ p.setFont(pxFont(font(), int(s * .2), true)), p.setPen(C::text);
134
+ p.drawText(QRectF(r.left(), r.top() + s * .3, s, s * .26), Qt::AlignCenter, m_center.isEmpty() ? QString::number(m_shown, 'f', 0) + "%" : m_center);
135
+ p.setFont(pxFont(font(), qMax(10, int(s * .075)))), p.setPen(C::muted);
136
+ p.drawText(QRectF(r.left() + s * .12, r.top() + s * .56, s * .76, s * .14), Qt::AlignCenter, p.fontMetrics().elidedText(m_sub, Qt::ElideRight, int(s * .76)));
137
+ p.setFont(pxFont(font(), 13, true)), p.setPen(C::text);
138
+ p.drawText(QRectF(0, r.bottom() - s * .06, width(), 22), Qt::AlignHCenter, m_title);
139
+ }
140
+
141
+ // ---- TimeChart --------------------------------------------------------------------------------
142
+ TimeChart::TimeChart(const QString &t, FmtFn fmt, double yMax) : title(t), m_fmt(fmt), m_yMax(yMax)
143
+ {
144
+ setMouseTracking(true), setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding);
145
+ }
146
+ void TimeChart::setData(const QVector<qint64> &t, const QVector<Series> &s, qint64 span) { m_t = t, m_s = s, m_span = span, update(); }
147
+ void TimeChart::mouseMoveEvent(QMouseEvent *e) { m_hover = e->pos().x(), update(); }
148
+
149
+ void TimeChart::paintEvent(QPaintEvent *)
150
+ {
151
+ AA p(this);
152
+ roundedPanel(p, rect(), C::panel);
153
+ p.setFont(pxFont(font(), 13, true)), p.setPen(C::text);
154
+ p.drawText(16, 10, width(), 20, Qt::AlignVCenter, title);
155
+ const int titleW = p.fontMetrics().horizontalAdvance(title);
156
+ p.setFont(pxFont(font(), 11)), p.setPen(C::muted);
157
+ p.drawText(24 + titleW, 10, width(), 20, Qt::AlignVCenter, subtitle);
158
+ double lx = width() - 16; // legend with latest values, right-aligned
159
+ for (int i = m_s.size() - 1; i >= 0; --i) {
160
+ const Series &s = m_s[i];
161
+ double last = NAN;
162
+ for (int k = s.v.size() - 1; k >= qMax(0, s.v.size() - 5) && std::isnan(last); --k) last = s.v[k];
163
+ const QString txt = s.name + (std::isnan(last) ? "" : " " + m_fmt(last));
164
+ const int w = p.fontMetrics().horizontalAdvance(txt);
165
+ if ((lx -= w) < 40 + titleW) break;
166
+ p.setPen(C::muted), p.drawText(QRectF(lx, 10, w, 20), Qt::AlignVCenter, txt);
167
+ p.setPen(Qt::NoPen), p.setBrush(s.color), p.drawRoundedRect(QRectF(lx -= 14, 16, 9, 9), 2, 2);
168
+ lx -= 14;
169
+ }
170
+ const int n = m_t.size();
171
+ int first = 0;
172
+ if (n && m_span)
173
+ while (first < n && m_t[first] < m_t.last() - m_span) ++first;
174
+ QRectF plot(56, 40, width() - 72, height() - 70);
175
+ if (n - first < 2 || plot.height() < 20) return p.setPen(C::faint), p.drawText(plot, Qt::AlignCenter, empty);
176
+
177
+ double yMax = m_yMax;
178
+ if (yMax <= 0) {
179
+ for (int i = first; i < n; ++i) {
180
+ double sum = 0;
181
+ for (const Series &s : m_s)
182
+ if (i < s.v.size() && !std::isnan(s.v[i])) sum = stacked ? sum + s.v[i] : qMax(sum, s.v[i]);
183
+ yMax = qMax(yMax, sum);
184
+ }
185
+ yMax = niceCeil(yMax * 1.12);
186
+ }
187
+ p.setFont(pxFont(font(), 10));
188
+ int lw = 0;
189
+ for (int g = 0; g <= 4; ++g) lw = qMax(lw, p.fontMetrics().horizontalAdvance(m_fmt(yMax * g / 4)));
190
+ plot.setLeft(qMax(40, lw + 18));
191
+ const qint64 t1 = m_t.last(), t0 = m_span ? t1 - m_span : m_t[first];
192
+ const double tr = qMax<qint64>(1, t1 - t0);
193
+ auto X = [&](qint64 t) { return plot.left() + (t - t0) / tr * plot.width(); };
194
+ auto Y = [&](double v) { return plot.bottom() - qBound(0.0, v, yMax) / yMax * plot.height(); };
195
+ const QString tf = tr <= 72e5 ? "HH:mm" : tr <= 2.6e8 ? "ddd HH:mm" : tr <= 3.5e10 ? "dd MMM" : "MMM yyyy";
196
+ for (int g = 0; g <= 4; ++g) { // grid, y labels, time labels
197
+ const double y = Y(yMax * g / 4), x = X(t0 + qint64(tr * g / 4));
198
+ p.setPen(QPen(C::grid, 1, g ? Qt::DashLine : Qt::SolidLine)), p.drawLine(QPointF(plot.left(), y), QPointF(plot.right(), y));
199
+ p.setPen(C::faint);
200
+ p.drawText(QRectF(0, y - 8, plot.left() - 8, 16), Qt::AlignRight | Qt::AlignVCenter, m_fmt(yMax * g / 4));
201
+ p.drawText(QRectF(g == 0 ? x : g == 4 ? x - 120 : x - 60, plot.bottom() + 6, 120, 16), (g == 0 ? Qt::AlignLeft : g == 4 ? Qt::AlignRight : Qt::AlignHCenter),
202
+ QDateTime::fromMSecsSinceEpoch(t0 + qint64(tr * g / 4)).toString(tf));
203
+ }
204
+ const int step = qMax(1, (n - first) / qMax(50, int(plot.width() * 1.5))); // ~1.5 points per pixel
205
+ QVector<double> base(n, 0.0);
206
+ p.setClipRect(plot.adjusted(-2, -4, 2, 2));
207
+ for (const Series &s : m_s) {
208
+ QVector<QPolygonF> top(1), bot(1); // runs split at gaps (NaN)
209
+ for (int i = first; i < n; i += step) {
210
+ double sum = 0, bs = 0;
211
+ int c = 0;
212
+ for (int k = i; k < qMin(n, i + step); ++k)
213
+ if (k < s.v.size() && !std::isnan(s.v[k])) sum += s.v[k], bs += base[k], ++c;
214
+ if (!c) { if (!top.last().isEmpty()) top << QPolygonF(), bot << QPolygonF(); continue; }
215
+ const double x = X(m_t[qMin(n - 1, i + step / 2)]), b = stacked ? bs / c : 0;
216
+ top.last() << QPointF(x, Y(sum / c + b)), bot.last() << QPointF(x, Y(b));
217
+ }
218
+ if (stacked)
219
+ for (int k = first; k < qMin(n, s.v.size()); ++k) base[k] += std::isnan(s.v[k]) ? 0 : s.v[k];
220
+ for (int r = 0; r < top.size(); ++r) {
221
+ if (top[r].size() < 2) continue;
222
+ if (s.fill) {
223
+ QPolygonF area = top[r];
224
+ for (int i = bot[r].size() - 1; i >= 0; --i) area << bot[r][i];
225
+ QLinearGradient g(0, plot.top(), 0, plot.bottom());
226
+ g.setColorAt(0, C::tint(s.color, stacked ? 120 : 95)), g.setColorAt(1, C::tint(s.color, stacked ? 60 : 4));
227
+ p.setPen(Qt::NoPen), p.setBrush(g), p.drawPolygon(area);
228
+ }
229
+ p.setBrush(Qt::NoBrush), p.setPen(QPen(s.color, s.dashed ? 1.3 : 2, s.dashed ? Qt::DashLine : Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin));
230
+ p.drawPolyline(top[r]);
231
+ }
232
+ }
233
+ p.setClipping(false);
234
+ if (m_hover < plot.left() || m_hover > plot.right()) return;
235
+ const qint64 ht = t0 + qint64((m_hover - plot.left()) / plot.width() * tr); // crosshair + tooltip
236
+ const int best = std::lower_bound(m_t.begin() + first, m_t.end(), ht) - m_t.begin() - (m_t.last() < ht);
237
+ const double x = X(m_t[best]);
238
+ p.setPen(QPen(QColor(255, 255, 255, 70), 1, Qt::DashLine)), p.drawLine(QPointF(x, plot.top()), QPointF(x, plot.bottom()));
239
+ QStringList lines{QDateTime::fromMSecsSinceEpoch(m_t[best]).toString(tr > 864e5 ? "ddd dd MMM HH:mm" : "HH:mm:ss")};
240
+ double stack = 0;
241
+ for (const Series &s : m_s) {
242
+ const double v = best < s.v.size() ? s.v[best] : NAN;
243
+ lines << s.name + ": " + (std::isnan(v) ? "—" : m_fmt(v));
244
+ if (std::isnan(v)) continue;
245
+ stack = stacked ? stack + v : v;
246
+ p.setPen(QPen(C::panel, 2)), p.setBrush(s.color), p.drawEllipse(QPointF(x, Y(stack)), 4, 4);
247
+ }
248
+ p.setFont(pxFont(font(), 11));
249
+ int tw = 0;
250
+ for (const QString &l : lines) tw = qMax(tw, p.fontMetrics().horizontalAdvance(l));
251
+ const QRectF tip(qMin(x + 12, plot.right() - tw - 20), plot.top() + 4, tw + 18, lines.size() * 16 + 10);
252
+ roundedPanel(p, tip, QColor(13, 17, 28, 235), C::border, 7);
253
+ for (int i = 0; i < lines.size(); ++i) p.setPen(i ? C::text : C::muted), p.drawText(QRectF(tip.left() + 9, tip.top() + 5 + i * 16, tw + 4, 16), Qt::AlignVCenter, lines[i]);
254
+ }
255
+
256
+ // ---- SegmentBar --------------------------------------------------------------------------------
257
+ SegmentBar::SegmentBar() { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed), setFixedHeight(58); }
258
+ void SegmentBar::setSegments(const QVector<Segment> &s, double total) { m_s = s, m_total = total > 0 ? total : 1, update(); }
259
+ void SegmentBar::paintEvent(QPaintEvent *)
260
+ {
261
+ AA p(this);
262
+ QPainterPath clip;
263
+ clip.addRoundedRect(QRectF(0, 2, width(), 14), 7, 7);
264
+ p.setClipPath(clip);
265
+ p.fillRect(rect(), C::grid);
266
+ double x = 0, lx = 0, ly = 26;
267
+ for (const Segment &s : m_s) p.fillRect(QRectF(x, 2, s.value / m_total * width(), 14), s.color), x += qMax(0.0, s.value / m_total * width());
268
+ p.setClipping(false);
269
+ p.setFont(pxFont(font(), 11));
270
+ for (const Segment &s : m_s) {
271
+ const QString t = s.label + " " + Fmt::bytes(s.value);
272
+ const int w = p.fontMetrics().horizontalAdvance(t) + 26;
273
+ if (lx + w > width()) lx = 0, ly += 18;
274
+ p.setPen(Qt::NoPen), p.setBrush(s.color), p.drawRoundedRect(QRectF(lx, ly + 3, 9, 9), 2, 2);
275
+ p.setPen(C::muted), p.drawText(QRectF(lx + 14, ly, w, 16), Qt::AlignVCenter, t);
276
+ lx += w;
277
+ }
278
+ }
279
+
280
+ // ---- StatTile ------------------------------------------------------------------------------------
281
+ StatTile::StatTile(const QString &title, const QColor &accent) : m_accent(accent)
282
+ {
283
+ auto *l = new QVBoxLayout(this);
284
+ l->setContentsMargins(16, 12, 14, 12), l->setSpacing(2);
285
+ l->addWidget(label(title.toUpper(), "Section"));
286
+ l->addWidget(m_value = new QLabel("—"));
287
+ l->addWidget(m_sub = label({}, "Muted"));
288
+ m_sub->setStyleSheet("font-size: 11px;");
289
+ setMinimumHeight(84), setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed), set("—");
290
+ }
291
+ void StatTile::set(const QString &v, const QString &sub, const QColor &c)
292
+ {
293
+ m_value->setText(v), m_sub->setText(sub), m_sub->setVisible(!sub.isEmpty());
294
+ m_value->setStyleSheet(QString("font-size: 21px; font-weight: 700; color: %1;").arg((c.isValid() ? c : C::text).name()));
295
+ }
296
+ void StatTile::paintEvent(QPaintEvent *)
297
+ {
298
+ AA p(this);
299
+ QLinearGradient g(0, 0, width(), height());
300
+ g.setColorAt(0, C::card), g.setColorAt(1, C::panel);
301
+ roundedPanel(p, rect(), g);
302
+ p.setPen(Qt::NoPen), p.setBrush(m_accent), p.drawRoundedRect(QRectF(0, 14, 4, height() - 28), 2, 2);
303
+ }
304
+ QVector<StatTile *> addTiles(QGridLayout *g, const QVector<QPair<QString, QColor>> &defs, int cols)
305
+ {
306
+ QVector<StatTile *> out;
307
+ g->setSpacing(14);
308
+ for (const auto &d : defs) out << new StatTile(d.first, d.second), g->addWidget(out.last(), (out.size() - 1) / cols, (out.size() - 1) % cols);
309
+ return out;
310
+ }
311
+
312
+ // ---- CoreGrid ---------------------------------------------------------------------------------------
313
+ CoreGrid::CoreGrid()
314
+ {
315
+ QSizePolicy sp(QSizePolicy::Expanding, QSizePolicy::Preferred);
316
+ sp.setHeightForWidth(true);
317
+ setSizePolicy(sp);
318
+ }
319
+ void CoreGrid::setCores(const QVector<CoreStat> &c)
320
+ {
321
+ if (c.size() != m_c.size()) updateGeometry();
322
+ m_c = c, update();
323
+ }
324
+ void CoreGrid::paintEvent(QPaintEvent *)
325
+ {
326
+ AA p(this);
327
+ const int cols = qMax(1, width() / 92);
328
+ const double cw = double(width()) / cols;
329
+ for (int i = 0; i < m_c.size(); ++i) {
330
+ const double u = m_c[i].usage;
331
+ const QColor c = C::level(u, 60, 85);
332
+ const QRectF r(cw * (i % cols) + 3, i / cols * 66 + 3, cw - 6, 60), bar(r.left() + 8, r.bottom() - 10, r.width() - 16, 4);
333
+ roundedPanel(p, r, C::mix(C::card, c, u / 420), C::mix(C::border, c, u / 160), 8);
334
+ p.setPen(Qt::NoPen), p.setBrush(C::grid), p.drawRoundedRect(bar, 2, 2);
335
+ p.setBrush(c), p.drawRoundedRect(QRectF(bar.left(), bar.top(), bar.width() * u / 100, 4), 2, 2);
336
+ p.setFont(pxFont(font(), 10)), p.setPen(C::muted);
337
+ p.drawText(r.adjusted(8, 5, -8, 0), Qt::AlignLeft, QString("CPU %1").arg(i));
338
+ if (m_c[i].mhz > 0) p.drawText(r.adjusted(8, 5, -8, 0), Qt::AlignRight, QString::number(m_c[i].mhz / 1000, 'f', 1) + "G");
339
+ p.setFont(pxFont(font(), 16, true)), p.setPen(C::text);
340
+ p.drawText(r.adjusted(8, 18, -8, -14), Qt::AlignVCenter, QString::number(u, 'f', 0) + "%");
341
+ }
342
+ }
343
+
344
+ // ---- WeekHeatmap ---------------------------------------------------------------------------------------
345
+ static const QStringList kDays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"};
346
+ WeekHeatmap::WeekHeatmap() : m_hot(C::accent)
347
+ {
348
+ std::fill(&m_v[0][0], &m_v[0][0] + 168, NAN), std::fill(&m_n[0][0], &m_n[0][0] + 168, 0);
349
+ setMouseTracking(true), setMinimumHeight(230);
350
+ }
351
+ void WeekHeatmap::setData(const double v[7][24], const int n[7][24], const QString &unit, const QColor &hot)
352
+ {
353
+ std::copy(&v[0][0], &v[0][0] + 168, &m_v[0][0]);
354
+ std::copy(&n[0][0], &n[0][0] + 168, &m_n[0][0]);
355
+ m_unit = unit, m_hot = hot, update();
356
+ }
357
+ QRectF WeekHeatmap::cell(int d, int h) const
358
+ {
359
+ const double cw = (width() - 44) / 24.0, ch = (height() - 30) / 7.0;
360
+ return QRectF(40 + h * cw + 1.5, 6 + d * ch + 1.5, cw - 3, ch - 3);
361
+ }
362
+ void WeekHeatmap::paintEvent(QPaintEvent *)
363
+ {
364
+ AA p(this);
365
+ p.setFont(pxFont(font(), 10));
366
+ bool any = false;
367
+ for (int d = 0; d < 7; ++d) {
368
+ p.setPen(C::muted), p.drawText(QRectF(0, cell(d, 0).top(), 34, cell(d, 0).height()), Qt::AlignRight | Qt::AlignVCenter, kDays[d].left(3));
369
+ for (int h = 0; h < 24; ++h) {
370
+ const double v = m_v[d][h];
371
+ any |= !std::isnan(v);
372
+ p.setPen(Qt::NoPen), p.setBrush(std::isnan(v) ? C::card : C::mix(0x1b2a44, m_hot, .15 + .85 * qBound(0.0, v / 100, 1.0)));
373
+ p.drawRoundedRect(cell(d, h), 3, 3);
374
+ }
375
+ }
376
+ p.setPen(C::faint);
377
+ for (int h = 0; h < 24; h += 3) p.drawText(QRectF(cell(6, h).left() - 4, cell(6, h).bottom() + 4, 40, 14), Qt::AlignLeft, QString("%1:00").arg(h, 2, 10, QChar('0')));
378
+ if (any) return;
379
+ const QRectF box(cell(2, 3).topLeft(), cell(4, 20).bottomRight());
380
+ p.fillRect(box, QColor(13, 17, 28, 200)), p.setPen(C::text), p.setFont(pxFont(font(), 12));
381
+ p.drawText(box, Qt::AlignCenter, "Collecting hourly history… the weekly pattern fills in over time");
382
+ }
383
+ void WeekHeatmap::mouseMoveEvent(QMouseEvent *e)
384
+ {
385
+ for (int d = 0; d < 7; ++d)
386
+ for (int h = 0; h < 24; ++h)
387
+ if (cell(d, h).contains(e->pos()))
388
+ return QToolTip::showText(e->globalPos(), std::isnan(m_v[d][h]) ? QString("%1 %2:00 — no data").arg(kDays[d]).arg(h)
389
+ : QString("%1 %2:00 — avg %3%4 (%5 samples)").arg(kDays[d]).arg(h).arg(m_v[d][h], 0, 'f', 1).arg(m_unit).arg(m_n[d][h]), this);
390
+ QToolTip::hideText();
391
+ }
392
+
393
+ // ---- table helpers --------------------------------------------------------------------------------------
394
+ void BarDelegate::paint(QPainter *p, const QStyleOptionViewItem &o, const QModelIndex &i) const
395
+ {
396
+ const QVariant pv = i.data(Qt::UserRole);
397
+ if (!pv.isValid()) return QStyledItemDelegate::paint(p, o, i);
398
+ p->save();
399
+ p->setRenderHint(QPainter::Antialiasing);
400
+ if (o.state & QStyle::State_Selected) p->fillRect(o.rect, o.palette.highlight());
401
+ const double pct = qBound(0.0, pv.toDouble(), 100.0);
402
+ const QRectF r = QRectF(o.rect).adjusted(6, o.rect.height() / 2.0 - 7, -6, -(o.rect.height() / 2.0 - 7));
403
+ const QColor c = C::level(pct);
404
+ p->setPen(Qt::NoPen), p->setBrush(C::grid), p->drawRoundedRect(r, 4, 4);
405
+ p->setBrush(C::tint(c, 200)), p->drawRoundedRect(QRectF(r.left(), r.top(), r.width() * pct / 100, r.height()), 4, 4);
406
+ p->setFont(pxFont(o.font, 11, true)), p->setPen(C::text), p->drawText(r, Qt::AlignCenter, i.data().toString());
407
+ p->restore();
408
+ }
409
+
410
+ int FlowLayout::place(const QRect &r, bool apply) const
411
+ {
412
+ if (m_items.isEmpty()) return 0;
413
+ const int sp = 16, minW = m_items[0]->minimumSize().width(), cols = qMax(1, (r.width() + sp) / (minW + sp)), w = (r.width() - (cols - 1) * sp) / cols;
414
+ int y = r.y(), rowH = 0, col = 0;
415
+ for (QLayoutItem *it : m_items) {
416
+ if (it->widget() && it->widget()->isHidden()) continue;
417
+ if (apply) it->setGeometry(QRect(r.x() + col * (w + sp), y, w, it->sizeHint().height()));
418
+ rowH = qMax(rowH, it->sizeHint().height());
419
+ if (++col == cols) col = 0, y += rowH + sp, rowH = 0;
420
+ }
421
+ return y + rowH - r.y();
422
+ }
423
+
424
+ // ---- builders ----------------------------------------------------------------------------------------
425
+ QLabel *label(const QString &text, const char *name, bool wrap)
426
+ {
427
+ auto *l = new QLabel(text);
428
+ if (name) l->setObjectName(name);
429
+ l->setWordWrap(wrap);
430
+ return l;
431
+ }
432
+ QPushButton *button(const QString &text, const char *style, std::function<void()> onClick)
433
+ {
434
+ auto *b = new QPushButton(text);
435
+ if (style) b->setObjectName(style);
436
+ if (onClick) QObject::connect(b, &QPushButton::clicked, b, onClick);
437
+ return b;
438
+ }
439
+ QFrame *panel(const QString &title, std::initializer_list<QWidget *> content)
440
+ {
441
+ auto *f = new QFrame;
442
+ f->setObjectName("Panel");
443
+ auto *l = new QVBoxLayout(f);
444
+ l->setContentsMargins(16, 14, 16, 14), l->setSpacing(10);
445
+ if (!title.isEmpty()) l->addWidget(label(title.toUpper(), "Section"));
446
+ for (QWidget *w : content) w ? l->addWidget(w) : l->addStretch();
447
+ return f;
448
+ }
449
+ bool ask(QWidget *parent, const QString &title, const QString &text) { return QMessageBox::question(parent, title, text) == QMessageBox::Yes; }
450
+
451
+ namespace {
452
+ struct SortItem : QTableWidgetItem { // sorts by Qt::UserRole+1 when set (numbers sort numerically)
453
+ bool operator<(const QTableWidgetItem &o) const override
454
+ {
455
+ const QVariant a = data(Qt::UserRole + 1), b = o.data(Qt::UserRole + 1);
456
+ if (!a.isValid() || !b.isValid()) return text() < o.text();
457
+ return a.type() == QVariant::String ? a.toString() < b.toString() : a.toDouble() < b.toDouble();
458
+ }
459
+ };
460
+ }
461
+
462
+ QTableWidget *table(const QStringList &headers, const QVector<int> &widths, const QVector<int> &bars)
463
+ {
464
+ auto *t = new QTableWidget(0, headers.size());
465
+ t->setHorizontalHeaderLabels(headers);
466
+ t->verticalHeader()->hide(), t->verticalHeader()->setDefaultSectionSize(30);
467
+ t->setAlternatingRowColors(true), t->setShowGrid(false), t->setWordWrap(false);
468
+ t->setSelectionBehavior(QAbstractItemView::SelectRows), t->setSelectionMode(QAbstractItemView::SingleSelection);
469
+ t->setEditTriggers(QAbstractItemView::NoEditTriggers), t->setFocusPolicy(Qt::NoFocus), t->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel);
470
+ t->horizontalHeader()->setHighlightSections(false), t->horizontalHeader()->setStretchLastSection(true);
471
+ t->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter);
472
+ for (int i = 0; i < widths.size(); ++i) t->setColumnWidth(i, widths[i]);
473
+ for (int c : bars) t->setItemDelegateForColumn(c, new BarDelegate(t));
474
+ return t;
475
+ }
476
+ void cell(QTableWidget *t, int r, int c, const Cell &x)
477
+ {
478
+ QTableWidgetItem *it = t->item(r, c);
479
+ if (!it) t->setItem(r, c, it = new SortItem);
480
+ if (it->text() != x.text) it->setText(x.text);
481
+ it->setTextAlignment(int(x.right ? Qt::AlignRight : Qt::AlignLeft) | Qt::AlignVCenter);
482
+ it->setForeground(x.color.isValid() ? x.color : C::text);
483
+ if (x.pct >= 0) it->setData(Qt::UserRole, x.pct);
484
+ if (x.key.isValid()) it->setData(Qt::UserRole + 1, x.key);
485
+ }
Server Monitor(cqt-window)/src/ui/Widgets.h ADDED
@@ -0,0 +1,150 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Theme, hand-painted widgets (gauges, time charts, bars, tiles, core grid, weekly
2
+ // heatmap), a flow layout and small builders for labels, buttons, panels and tables.
3
+ #pragma once
4
+ #include "core/Model.h"
5
+ #include <QFrame>
6
+ #include <QLabel>
7
+ #include <QLayout>
8
+ #include <QPainter>
9
+ #include <QPushButton>
10
+ #include <QStyledItemDelegate>
11
+ #include <QTableWidget>
12
+ #include <QVariantAnimation>
13
+ #include <functional>
14
+
15
+ namespace C { // palette
16
+ inline const QColor bg{0x0d111c}, panel{0x161c2b}, card{0x1a2133}, cardHover{0x20293f}, border{0x27314a}, grid{0x242d42},
17
+ text{0xe6ebf5}, muted{0x8b95ab}, faint{0x5a657d}, accent{0x38bdf8}, green{0x22c55e}, amber{0xf59e0b}, red{0xef4444},
18
+ violet{0xa78bfa}, pink{0xf472b6}, teal{0x2dd4bf}, orange{0xfb923c}, blue{0x60a5fa};
19
+ QColor level(double pct, double warn = 70, double crit = 90); // green / amber / red
20
+ QColor severity(const QString &s);
21
+ QColor health(int h);
22
+ QColor mix(const QColor &a, const QColor &b, double t);
23
+ inline QColor tint(QColor c, int alpha) { return c.setAlpha(alpha), c; }
24
+ QString styleSheet();
25
+ QIcon appIcon();
26
+ QString mono();
27
+ }
28
+
29
+ using FmtFn = std::function<QString(double)>;
30
+ inline const FmtFn pctFmt = [](double v) { return QString::number(v, 'f', 0) + "%"; }, rateFmt = Fmt::rate;
31
+ inline FmtFn numFmt(int prec) { return [prec](double v) { return QString::number(v, 'f', prec); }; }
32
+
33
+ struct AA : QPainter { // antialiased painter
34
+ explicit AA(QPaintDevice *d) : QPainter(d) { setRenderHint(Antialiasing); }
35
+ };
36
+ QFont pxFont(QFont f, int px, bool bold = false);
37
+ void paintRing(QPainter &p, const QRectF &r, double pct, const QColor &c, double thick, bool glow = true); // 270° arc
38
+
39
+ struct RingGauge : QWidget {
40
+ explicit RingGauge(const QString &title);
41
+ void setValue(double pct, const QString &center = {}, const QString &sub = {}, const QColor &color = {});
42
+ double warn = 70, crit = 90;
43
+ QSize sizeHint() const override { return {170, 190}; }
44
+ void paintEvent(QPaintEvent *) override;
45
+ QString m_title, m_center, m_sub;
46
+ QColor m_color;
47
+ double m_target = 0, m_shown = 0;
48
+ QVariantAnimation m_anim;
49
+ };
50
+
51
+ struct Series { QString name; QColor color; QVector<double> v; bool fill = true, dashed = false; };
52
+ struct TimeChart : QWidget {
53
+ explicit TimeChart(const QString &title, FmtFn fmt = pctFmt, double yMax = 0); // yMax 0 = auto
54
+ void setData(const QVector<qint64> &tMs, const QVector<Series> &s, qint64 spanMs = 0); // span 0 = all
55
+ QString title, subtitle, empty = "Waiting for data…";
56
+ bool stacked = false;
57
+ QSize sizeHint() const override { return {480, 230}; }
58
+ QSize minimumSizeHint() const override { return {260, 200}; }
59
+ void paintEvent(QPaintEvent *) override;
60
+ void mouseMoveEvent(QMouseEvent *) override;
61
+ void leaveEvent(QEvent *) override { m_hover = -1, update(); }
62
+ FmtFn m_fmt;
63
+ double m_yMax;
64
+ QVector<qint64> m_t;
65
+ QVector<Series> m_s;
66
+ qint64 m_span = 0;
67
+ int m_hover = -1;
68
+ };
69
+
70
+ struct Segment { double value; QColor color; QString label; };
71
+ struct SegmentBar : QWidget {
72
+ SegmentBar();
73
+ void setSegments(const QVector<Segment> &s, double total);
74
+ QSize sizeHint() const override { return {300, 58}; }
75
+ void paintEvent(QPaintEvent *) override;
76
+ QVector<Segment> m_s;
77
+ double m_total = 1;
78
+ };
79
+
80
+ struct StatTile : QFrame {
81
+ StatTile(const QString &title, const QColor &accent);
82
+ void set(const QString &value, const QString &sub = {}, const QColor &color = {});
83
+ void paintEvent(QPaintEvent *) override;
84
+ QLabel *m_value, *m_sub;
85
+ QColor m_accent;
86
+ };
87
+ // creates tiles in a grid (cols per row) from {title, colour} pairs
88
+ QVector<StatTile *> addTiles(class QGridLayout *g, const QVector<QPair<QString, QColor>> &defs, int cols = 99);
89
+
90
+ struct CoreGrid : QWidget {
91
+ CoreGrid();
92
+ void setCores(const QVector<CoreStat> &c);
93
+ bool hasHeightForWidth() const override { return true; }
94
+ int heightForWidth(int w) const override { return (qMax(1, m_c.size()) + qMax(1, w / 92) - 1) / qMax(1, w / 92) * 66; }
95
+ void paintEvent(QPaintEvent *) override;
96
+ QVector<CoreStat> m_c;
97
+ };
98
+
99
+ struct WeekHeatmap : QWidget {
100
+ WeekHeatmap();
101
+ void setData(const double v[7][24], const int n[7][24], const QString &unit, const QColor &hot);
102
+ QSize sizeHint() const override { return {560, 230}; }
103
+ void paintEvent(QPaintEvent *) override;
104
+ void mouseMoveEvent(QMouseEvent *) override;
105
+ QRectF cell(int d, int h) const;
106
+ double m_v[7][24];
107
+ int m_n[7][24];
108
+ QString m_unit;
109
+ QColor m_hot;
110
+ };
111
+
112
+ // table cell bar: Qt::UserRole = percent, DisplayRole = text on the bar
113
+ struct BarDelegate : QStyledItemDelegate {
114
+ using QStyledItemDelegate::QStyledItemDelegate;
115
+ void paint(QPainter *p, const QStyleOptionViewItem &o, const QModelIndex &i) const override;
116
+ };
117
+
118
+ struct FlowLayout : QLayout { // equal-width columns of cards
119
+ FlowLayout(QWidget *parent) : QLayout(parent) {}
120
+ ~FlowLayout() override { qDeleteAll(m_items); }
121
+ void addItem(QLayoutItem *i) override { m_items << i; }
122
+ int count() const override { return m_items.size(); }
123
+ QLayoutItem *itemAt(int i) const override { return m_items.value(i); }
124
+ QLayoutItem *takeAt(int i) override { return i >= 0 && i < m_items.size() ? m_items.takeAt(i) : nullptr; }
125
+ bool hasHeightForWidth() const override { return true; }
126
+ int heightForWidth(int w) const override { return place(QRect(0, 0, w, 0), false); }
127
+ void setGeometry(const QRect &r) override { QLayout::setGeometry(r), place(r, true); }
128
+ QSize sizeHint() const override { return {340, 270}; }
129
+ int place(const QRect &r, bool apply) const;
130
+ QList<QLayoutItem *> m_items;
131
+ };
132
+
133
+ // ---- small builders ----------------------------------------------------------------
134
+ QLabel *label(const QString &text, const char *objectName = nullptr, bool wrap = false);
135
+ QPushButton *button(const QString &text, const char *style = nullptr, std::function<void()> onClick = {});
136
+ QFrame *panel(const QString &title = {}, std::initializer_list<QWidget *> content = {}); // nullptr = stretch
137
+ bool ask(QWidget *parent, const QString &title, const QString &text);
138
+
139
+ struct Cell { QString text; QColor color; bool right = false; double pct = -1; QVariant key; }; // pct = bar, key = sort value
140
+ using Row = QVector<Cell>;
141
+ QTableWidget *table(const QStringList &headers, const QVector<int> &widths = {}, const QVector<int> &barColumns = {});
142
+ void cell(QTableWidget *t, int r, int c, const Cell &x);
143
+ template <class V, class F> void fillRows(QTableWidget *t, const V &items, F rowOf) // one row per item
144
+ {
145
+ t->setRowCount(items.size());
146
+ for (int r = 0; r < items.size(); ++r) {
147
+ const Row row = rowOf(items[r]);
148
+ for (int c = 0; c < row.size(); ++c) cell(t, r, c, row[c]);
149
+ }
150
+ }
Server Monitor(cqt-window)/src/ui/Windows.cpp ADDED
@@ -0,0 +1,614 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Main window: sidebar, dashboard with server cards, server detail page, events page, tray icon.
2
+ #include "Windows.h"
3
+ #include "Widgets.h"
4
+ #include <QApplication>
5
+ #include <QBoxLayout>
6
+ #include <QCheckBox>
7
+ #include <QCloseEvent>
8
+ #include <QComboBox>
9
+ #include <QDesktopServices>
10
+ #include <QDialogButtonBox>
11
+ #include <QEventLoop>
12
+ #include <QFileDialog>
13
+ #include <QFormLayout>
14
+ #include <QLineEdit>
15
+ #include <QListWidget>
16
+ #include <QMenu>
17
+ #include <QMessageBox>
18
+ #include <QPlainTextEdit>
19
+ #include <QScrollArea>
20
+ #include <QSettings>
21
+ #include <QSpinBox>
22
+ #include <QStackedWidget>
23
+ #include <QSystemTrayIcon>
24
+ #include <QTabWidget>
25
+ #include <QUrl>
26
+ #include <memory>
27
+
28
+ struct Actions { std::function<void(const QString &)> open, edit, remove; std::function<void()> add, back; }; // set by the main window
29
+ static QColor statusColor(Status s) { return s == Status::Online ? C::green : s == Status::Connecting ? C::amber : s == Status::Offline ? C::red : C::faint; }
30
+ static QHBoxLayout *hbox()
31
+ {
32
+ auto *h = new QHBoxLayout;
33
+ h->setSpacing(10);
34
+ return h;
35
+ }
36
+ static QVBoxLayout *page(QWidget *w, int top = 22)
37
+ {
38
+ auto *l = new QVBoxLayout(w);
39
+ w->setObjectName("Page"), l->setContentsMargins(28, top, 28, 18), l->setSpacing(14);
40
+ return l;
41
+ }
42
+
43
+ // ============================================================================ dashboard cards
44
+ struct Card : QWidget {
45
+ bool hover = false;
46
+ Card() { setCursor(Qt::PointingHandCursor), setMinimumSize(320, 262); }
47
+ QSize sizeHint() const override { return {340, 262}; }
48
+ void enterEvent(QEvent *) override { hover = true, update(); }
49
+ void leaveEvent(QEvent *) override { hover = false, update(); }
50
+ };
51
+
52
+ struct ServerCard : Card {
53
+ ServerSession *s;
54
+ const Actions *act;
55
+ ServerCard(ServerSession *x, const Actions *a) : s(x), act(a)
56
+ {
57
+ connect(x, &ServerSession::updated, this, QOverload<>::of(&QWidget::update));
58
+ connect(x, &ServerSession::analysisUpdated, this, QOverload<>::of(&QWidget::update));
59
+ }
60
+ void mouseReleaseEvent(QMouseEvent *e) override { if (e->button() == Qt::LeftButton) act->open(s->config().id); }
61
+ void contextMenuEvent(QContextMenuEvent *e) override
62
+ {
63
+ const QString id = s->config().id;
64
+ QMenu m;
65
+ m.addAction("Open details", [=] { act->open(id); }), m.addAction("Reconnect", s, &ServerSession::reconnect), m.addSeparator();
66
+ m.addAction("Edit…", [=] { act->edit(id); }), m.addAction("Remove…", [=] { act->remove(id); });
67
+ m.exec(e->globalPos());
68
+ }
69
+ void paintEvent(QPaintEvent *) override
70
+ {
71
+ AA p(this);
72
+ const ServerConfig &c = s->config();
73
+ const Metrics &m = s->metrics();
74
+ const Analysis &an = s->analysis();
75
+ const bool live = s->online();
76
+ const QColor sc = statusColor(s->status()), muted = live ? C::text : C::faint;
77
+ QLinearGradient bg(0, 0, 0, height()), strip(0, 0, width(), 0);
78
+ bg.setColorAt(0, hover ? C::cardHover : C::card), bg.setColorAt(1, C::panel);
79
+ strip.setColorAt(0, sc), strip.setColorAt(.6, C::tint(sc, 0));
80
+ p.setPen(QPen(hover ? C::accent : C::border, hover ? 1.5 : 1)), p.setBrush(bg), p.drawRoundedRect(QRectF(rect()).adjusted(1, 1, -1, -1), 14, 14);
81
+ p.setPen(Qt::NoPen), p.setBrush(strip), p.drawRoundedRect(QRectF(1, 1, width() - 2, 6), 3, 3);
82
+ p.setBrush(sc), p.drawEllipse(QPointF(22, 28), 5, 5);
83
+ p.setFont(pxFont(font(), 16, true)), p.setPen(C::text);
84
+ p.drawText(QRectF(36, 16, width() - 120, 24), Qt::AlignVCenter, p.fontMetrics().elidedText(c.name, Qt::ElideRight, width() - 120));
85
+ p.setFont(pxFont(font(), 11)), p.setPen(C::muted);
86
+ p.drawText(QRectF(36, 38, width() - 60, 16), Qt::AlignVCenter, p.fontMetrics().elidedText(c.address() + (m.os.isEmpty() ? "" : " · " + m.os), Qt::ElideRight, width() - 60));
87
+ if (live) { // health badge
88
+ const QRectF hb(width() - 62, 12, 44, 44);
89
+ paintRing(p, hb, an.health, C::health(an.health), 4, false);
90
+ p.setFont(pxFont(font(), 15, true)), p.setPen(C::health(an.health)), p.drawText(hb, Qt::AlignCenter, an.grade);
91
+ } else {
92
+ p.setFont(pxFont(font(), 10, true));
93
+ const QString chip = statusName(s->status()).toUpper();
94
+ const QRectF cr(width() - p.fontMetrics().horizontalAdvance(chip) - 34, 18, p.fontMetrics().horizontalAdvance(chip) + 18, 20);
95
+ p.setPen(sc), p.setBrush(C::tint(sc, 40)), p.drawRoundedRect(cr, 10, 10), p.drawText(cr, Qt::AlignCenter, chip);
96
+ }
97
+ const bool temp = !m.temps.isEmpty(); // four gauges
98
+ const double vals[4] = {m.cpuUsage, m.memPct, m.maxDiskPct, temp ? m.maxTemp : m.swapPct}, gw = (width() - 32) / 4.0, gs = qMin(gw - 14, 70.0);
99
+ const char *names[4] = {"CPU", "Memory", "Disk", temp ? "Temp" : "Swap"};
100
+ for (int i = 0; i < 4; ++i) {
101
+ const double cx = 16 + gw * i + gw / 2;
102
+ const QRectF r(cx - gs / 2, 66, gs, gs);
103
+ paintRing(p, r, live ? qMin(100.0, vals[i]) : 0, live ? (i == 3 && temp ? C::level(vals[i], 70, 85) : C::level(vals[i])) : C::faint, 6, live);
104
+ p.setFont(pxFont(font(), 14, true)), p.setPen(muted);
105
+ p.drawText(r, Qt::AlignCenter, !live ? "—" : i == 3 && temp ? QString::number(vals[i], 'f', 0) + "°" : QString::number(vals[i], 'f', 0) + "%");
106
+ p.setFont(pxFont(font(), 11)), p.setPen(C::muted), p.drawText(QRectF(cx - gw / 2, r.bottom() - 4, gw, 16), Qt::AlignCenter, names[i]);
107
+ }
108
+ const QRectF sp(16, 166, width() - 32, 44); // CPU + memory sparkline (last 5 min)
109
+ p.setPen(Qt::NoPen), p.setBrush(QColor(0, 0, 0, 40)), p.drawRoundedRect(sp, 8, 8);
110
+ for (auto [series, color] : {std::pair{Live::MEM, C::violet}, {Live::CPU, C::accent}}) {
111
+ const QVector<double> &v = s->live().s[series];
112
+ const int n = qMin(150, v.size());
113
+ if (n < 2) continue;
114
+ QPolygonF line;
115
+ for (int i = 0; i < n; ++i) line << QPointF(sp.right() - 4 - (sp.width() - 8) * (n - 1 - i) / 149.0, sp.bottom() - 4 - qBound(0.0, v[v.size() - n + i], 100.0) / 100 * (sp.height() - 8));
116
+ QPolygonF area = line;
117
+ area << QPointF(line.last().x(), sp.bottom() - 2) << QPointF(line.first().x(), sp.bottom() - 2);
118
+ p.setPen(Qt::NoPen), p.setBrush(C::tint(color, 40)), p.drawPolygon(area);
119
+ p.setPen(QPen(color, 1.5)), p.setBrush(Qt::NoBrush), p.drawPolyline(line);
120
+ }
121
+ p.setFont(pxFont(font(), 10)), p.setPen(C::accent), p.drawText(sp.adjusted(8, 3, 0, 0), Qt::AlignLeft, "CPU");
122
+ p.setPen(C::violet), p.drawText(sp.adjusted(36, 3, 0, 0), Qt::AlignLeft, "MEM");
123
+ p.setFont(pxFont(font(), 11));
124
+ const QRectF ft(16, 218, width() - 32, 32);
125
+ if (!live) {
126
+ p.setPen(s->status() == Status::Offline ? C::red : C::muted);
127
+ return p.drawText(ft, Qt::AlignVCenter | Qt::TextWordWrap, s->status() == Status::Disabled ? "Monitoring disabled" : s->status() == Status::Offline ? "Unreachable: " + s->lastError() : "Waiting for data…");
128
+ }
129
+ p.setPen(C::teal), p.drawText(ft, Qt::AlignLeft, "↓ " + Fmt::rate(m.netRxBps));
130
+ p.setPen(C::pink), p.drawText(ft.adjusted(100, 0, 0, 0), Qt::AlignLeft, "↑ " + Fmt::rate(m.netTxBps));
131
+ p.setPen(C::muted), p.drawText(ft, Qt::AlignRight, QString("load %1 · up %2").arg(m.load1, 0, 'f', 2).arg(Fmt::duration(m.uptime)));
132
+ p.drawText(ft.adjusted(0, 16, 0, 0), Qt::AlignLeft, QString("%1 cores · %2 procs").arg(m.cpuCount).arg(m.procs.size()) + (c.autopilot.enabled ? c.autopilot.dryRun ? " · autopilot (dry run)" : " · autopilot on" : ""));
133
+ const int rules = s->activeAlerts().size(), alerts = rules + an.findings.size();
134
+ if (!alerts) return;
135
+ bool crit = rules;
136
+ for (const Finding &f : an.findings) crit |= f.severity == "critical";
137
+ const QString txt = QString("⚠ %1").arg(alerts);
138
+ const QColor ac = crit ? C::red : C::amber;
139
+ const QRectF ar(ft.right() - p.fontMetrics().horizontalAdvance(txt) - 14, ft.top() + 15, p.fontMetrics().horizontalAdvance(txt) + 14, 17);
140
+ p.setPen(Qt::NoPen), p.setBrush(C::tint(ac, 45)), p.drawRoundedRect(ar, 8, 8), p.setPen(ac), p.drawText(ar, Qt::AlignCenter, txt);
141
+ }
142
+ };
143
+
144
+ struct AddCard : Card {
145
+ const Actions *act;
146
+ explicit AddCard(const Actions *a) : act(a) {}
147
+ void mouseReleaseEvent(QMouseEvent *) override { act->add(); }
148
+ void paintEvent(QPaintEvent *) override
149
+ {
150
+ AA p(this);
151
+ const QRectF r = QRectF(rect()).adjusted(2, 2, -2, -2);
152
+ const QPointF c = r.center() - QPointF(0, 14);
153
+ p.setPen(QPen(hover ? C::accent : C::border, 1.5, Qt::DashLine)), p.setBrush(hover ? C::tint(C::accent, 18) : Qt::transparent), p.drawRoundedRect(r, 14, 14);
154
+ p.setPen(QPen(hover ? C::accent : C::muted, 3, Qt::SolidLine, Qt::RoundCap));
155
+ p.drawLine(c - QPointF(14, 0), c + QPointF(14, 0)), p.drawLine(c - QPointF(0, 14), c + QPointF(0, 14));
156
+ p.setFont(pxFont(font(), 14, true)), p.drawText(QRectF(r.left(), c.y() + 26, r.width(), 22), Qt::AlignCenter, "Add server");
157
+ p.setFont(pxFont(font(), 11)), p.setPen(C::faint), p.drawText(QRectF(r.left(), c.y() + 48, r.width(), 18), Qt::AlignCenter, "This machine · SSH");
158
+ }
159
+ };
160
+
161
+ // ============================================================================ dashboard
162
+ struct DashboardPage : QWidget {
163
+ ServerManager *mgr;
164
+ const Actions *act;
165
+ FlowLayout *flow = new FlowLayout(new QWidget);
166
+ QList<ServerCard *> cards;
167
+ AddCard *addCard;
168
+ QLineEdit *search = new QLineEdit;
169
+ QLabel *subtitle = label({}, "Muted");
170
+ QVector<StatTile *> t;
171
+ QListWidget *events = new QListWidget;
172
+
173
+ DashboardPage(ServerManager *m, const Actions *a) : mgr(m), act(a), addCard(new AddCard(a))
174
+ {
175
+ auto *l = page(this);
176
+ auto *head = hbox(), *body = hbox();
177
+ auto *titles = new QVBoxLayout;
178
+ auto *g = new QGridLayout;
179
+ auto *scroll = new QScrollArea;
180
+ auto *ev = panel("Recent events", {events});
181
+ titles->addWidget(label("Dashboard", "H1")), titles->addWidget(subtitle);
182
+ search->setPlaceholderText("Search servers…"), search->setClearButtonEnabled(true), search->setFixedWidth(240);
183
+ head->addLayout(titles), head->addStretch(), head->addWidget(search), head->addWidget(button("+ Add server", "Primary", [this] { act->add(); }));
184
+ t = addTiles(g, {{"Servers online", C::green}, {"Avg health", C::teal}, {"Active problems", C::red}, {"Avg CPU", C::accent}, {"Avg memory", C::violet}, {"Total network", C::pink}});
185
+ scroll->setWidgetResizable(true), scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff), scroll->setWidget(flow->parentWidget());
186
+ events->setStyleSheet("QListWidget { background: transparent; border: none; } QListWidget::item { padding: 6px 2px; border-bottom: 1px solid #1f2738; }");
187
+ events->setWordWrap(true), events->setSelectionMode(QAbstractItemView::NoSelection), ev->setFixedWidth(330);
188
+ body->addWidget(scroll, 1), body->addWidget(ev);
189
+ l->addLayout(head), l->addLayout(g), l->addLayout(body, 1);
190
+ connect(search, &QLineEdit::textChanged, this, [this] { filter(); });
191
+ connect(mgr, &ServerManager::listChanged, this, [this] { rebuild(); });
192
+ connect(mgr, &ServerManager::alertsCleared, events, &QListWidget::clear);
193
+ connect(mgr, &ServerManager::alertRaised, this, [this](const AlertEvent &e) {
194
+ events->insertItem(0, e.time.toString("HH:mm:ss") + " · " + e.serverName + "\n" + e.message);
195
+ events->item(0)->setForeground(C::severity(e.severity));
196
+ if (events->count() > 200) delete events->takeItem(200);
197
+ });
198
+ }
199
+ void rebuild()
200
+ {
201
+ for (ServerCard *c : qAsConst(cards)) c->hide(), c->deleteLater(); // not deleted at once: a card's own menu may have caused this
202
+ cards.clear(), flow->removeWidget(addCard);
203
+ for (ServerSession *s : mgr->sessions()) cards << new ServerCard(s, act), flow->addWidget(cards.last());
204
+ flow->addWidget(addCard), filter(), refresh();
205
+ }
206
+ void filter()
207
+ {
208
+ for (ServerCard *c : qAsConst(cards))
209
+ c->setVisible(QStringList{c->s->config().name, c->s->config().host, c->s->config().group, c->s->metrics().hostname}.join(' ').contains(search->text(), Qt::CaseInsensitive));
210
+ flow->invalidate();
211
+ }
212
+ void refresh()
213
+ {
214
+ int online = 0, total = 0, problems = 0;
215
+ double cpu = 0, mem = 0, rx = 0, tx = 0, health = 0;
216
+ for (ServerSession *s : mgr->sessions()) {
217
+ if (!s->config().enabled) continue;
218
+ ++total, problems += s->activeAlerts().size();
219
+ if (!s->online()) continue;
220
+ const Metrics &m = s->metrics();
221
+ ++online, cpu += m.cpuUsage, mem += m.memPct, rx += m.netRxBps, tx += m.netTxBps, health += s->analysis().health;
222
+ for (const Finding &f : s->analysis().findings) problems += f.severity != "info";
223
+ }
224
+ subtitle->setText(QString("%1 server(s) monitored · updated %2").arg(mgr->sessions().size()).arg(QTime::currentTime().toString("HH:mm:ss")));
225
+ t[0]->set(QString("%1 / %2").arg(online).arg(total), total > online ? QString("%1 unreachable").arg(total - online) : "all reachable", online == total ? C::green : C::amber);
226
+ t[2]->set(QString::number(problems), problems ? "alerts + insights" : "all clear", problems ? C::red : C::green);
227
+ if (!online) {
228
+ for (int i : {1, 3, 4, 5}) t[i]->set("—");
229
+ return;
230
+ }
231
+ t[1]->set(QString::number(qRound(health / online)), "score 0–100", C::health(qRound(health / online)));
232
+ t[3]->set(Fmt::pct(cpu / online), {}, C::level(cpu / online)), t[4]->set(Fmt::pct(mem / online), {}, C::level(mem / online));
233
+ t[5]->set(Fmt::rate(rx + tx), "↓ " + Fmt::rate(rx) + " ↑ " + Fmt::rate(tx));
234
+ }
235
+ };
236
+
237
+ // ============================================================================ detail page
238
+ struct DetailPage : QWidget {
239
+ ServerManager *mgr;
240
+ const Actions *act;
241
+ QPointer<ServerSession> s;
242
+ QTabWidget *tabs = new QTabWidget;
243
+ QLabel *name = label({}, "H1"), *state = new QLabel, *sub = label({}, "Muted"), *chips = label({}, nullptr, true);
244
+ QPushButton *pause = button("❚❚ Pause", nullptr, [this] { s->setPaused(!s->isPaused()); });
245
+ QComboBox *span = new QComboBox;
246
+ QList<QMetaObject::Connection> conns;
247
+
248
+ DetailPage(ServerManager *m, const Actions *a) : mgr(m), act(a)
249
+ {
250
+ auto *l = page(this, 18);
251
+ auto *head = hbox(), *nameRow = hbox();
252
+ auto *titles = new QVBoxLayout, *spanBox = new QVBoxLayout;
253
+ auto *power = button("⏻ Power", "Danger");
254
+ auto *pm = new QMenu(power);
255
+ nameRow->addWidget(name), nameRow->addWidget(state), nameRow->addStretch();
256
+ titles->addWidget(button("‹ Dashboard", "Flat", [this] { act->back(); }), 0, Qt::AlignLeft), titles->addLayout(nameRow), titles->addWidget(sub), titles->addWidget(chips);
257
+ for (auto [t, min] : {std::pair{"Last 5 minutes", 5}, {"Last 15 minutes", 15}, {"Last 30 minutes", 30}, {"Last hour", 60}}) span->addItem(t, min);
258
+ span->setCurrentIndex(1), spanBox->addWidget(label("LIVE WINDOW", "Section")), spanBox->addWidget(span);
259
+ for (bool reboot : {true, false}) {
260
+ const QString t = reboot ? "Reboot…" : "Shut down…";
261
+ pm->addAction(t, this, [this, t, reboot] {
262
+ if (QMessageBox::warning(this, t, QString("%1 %2 now?").arg(t.chopped(1), s->config().name), QMessageBox::Yes | QMessageBox::No) == QMessageBox::Yes) s->exec(P::power(reboot), true);
263
+ });
264
+ }
265
+ pm->addSeparator(), pm->addAction("Remove from monitor…", this, [this] { act->remove(s->config().id); }), power->setMenu(pm);
266
+ head->addLayout(titles, 1), head->addLayout(spanBox);
267
+ for (auto *b : {button("⟳ Reconnect", nullptr, [this] { s->reconnect(); }), pause, button("Edit", nullptr, [this] { act->edit(s->config().id); }), power}) head->addWidget(b, 0, Qt::AlignBottom);
268
+ tabs->setDocumentMode(true), tabs->tabBar()->setElideMode(Qt::ElideNone), tabs->tabBar()->setExpanding(false);
269
+ tabs->tabBar()->setFont(pxFont(tabs->tabBar()->font(), 13, true));
270
+ for (const auto &[title, w] : makeTabs()) w->save = [this](const ServerConfig &c) { mgr->update(c); }, tabs->addTab(w, title);
271
+ l->setSpacing(6), l->addLayout(head), l->addWidget(tabs, 1);
272
+ connect(tabs, &QTabWidget::currentChanged, this, [this] { refreshTab(true); });
273
+ connect(span, QOverload<int>::of(&QComboBox::currentIndexChanged), this, [this] { refreshTab(false); });
274
+ }
275
+ Tab *tab(int i) const { return static_cast<Tab *>(tabs->widget(i)); }
276
+ void refreshTab(bool withAnalysis)
277
+ {
278
+ Tab *t = tab(tabs->currentIndex());
279
+ if (!s) return;
280
+ t->span = span->currentData().toInt() * 60000LL, t->refresh();
281
+ if (withAnalysis) t->analysis();
282
+ }
283
+ void bind(ServerSession *x)
284
+ {
285
+ for (const auto &c : qAsConst(conns)) disconnect(c);
286
+ conns.clear(), s = x;
287
+ for (int i = 0; i < tabs->count(); ++i) tab(i)->bind(x);
288
+ if (!x) return;
289
+ conns << connect(x, &ServerSession::updated, this, [this] { header(), refreshTab(false); })
290
+ << connect(x, &ServerSession::analysisUpdated, this, [this] { header(), tab(tabs->currentIndex())->analysis(); });
291
+ header(), refreshTab(true);
292
+ }
293
+ void header()
294
+ {
295
+ const ServerConfig &c = s->config();
296
+ const Metrics &m = s->metrics();
297
+ const Analysis &a = s->analysis();
298
+ QString h;
299
+ auto chip = [&](const QString &t, const QString &color = "#b9c3d8") {
300
+ if (!t.trimmed().isEmpty()) h += QString("<span style='background:#1f2a40; color:%2; white-space:nowrap;'>&nbsp;&nbsp;%1&nbsp;&nbsp;</span>&nbsp; ").arg(t.toHtmlEscaped().replace(" ", "&nbsp;").replace("-", "&#8209;"), color);
301
+ };
302
+ name->setText(c.name);
303
+ state->setText(" ● " + (s->isPaused() ? QString("Paused") : statusName(s->status())).toUpper());
304
+ state->setStyleSheet(QString("color: %1; font-weight: 700; font-size: 12px;").arg((s->isPaused() ? C::amber : statusColor(s->status())).name()));
305
+ sub->setText(c.address() + " · " + transportName(c.transport) + (m.hostname.isEmpty() ? "" : " · host " + m.hostname) +
306
+ (s->online() ? " · up " + Fmt::duration(m.uptime) : s->status() == Status::Offline ? " · " + s->lastError() : ""));
307
+ chip(m.os), chip(m.kernel.isEmpty() ? "" : P::kernelPrefix + m.kernel), chip(m.cpuCount ? QString("%1 cores").arg(m.cpuCount) : "");
308
+ chip(m.memTotal > 0 ? Fmt::bytes(m.memTotal) + " RAM" : ""), chip(c.group, "#7dd3fc");
309
+ if (s->online()) chip(QString("health %1 (%2)").arg(a.health).arg(a.grade), C::health(a.health).name());
310
+ if (c.autopilot.enabled) chip(c.autopilot.dryRun ? "autopilot: dry run" : "autopilot: on", "#a78bfa");
311
+ chips->setText(h), pause->setText(s->isPaused() ? "▶ Resume" : "❚❚ Pause");
312
+ }
313
+ };
314
+
315
+ // ============================================================================ add / edit dialog
316
+ static bool editServer(QWidget *parent, ServerConfig &cfg, const QStringList &groups)
317
+ {
318
+ QDialog dlg(parent);
319
+ dlg.setWindowTitle(cfg.name.isEmpty() ? "Add server" : "Edit server — " + cfg.name);
320
+ dlg.setMinimumWidth(620);
321
+ auto *l = new QVBoxLayout(&dlg);
322
+ l->setContentsMargins(24, 20, 24, 20), l->setSpacing(14);
323
+ l->addWidget(label(cfg.name.isEmpty() ? "Add a server" : "Edit server", "H2"));
324
+ auto *f = new QFormLayout;
325
+ auto *name = new QLineEdit(cfg.name), *host = new QLineEdit(cfg.host), *user = new QLineEdit(cfg.user), *key = new QLineEdit(cfg.keyFile), *pass = new QLineEdit(cfg.password);
326
+ auto *group = new QComboBox, *via = new QComboBox;
327
+ auto *port = new QSpinBox, *interval = new QSpinBox;
328
+ auto *sudo = new QCheckBox("Run control commands with sudo -n (needs passwordless sudo)"), *enabled = new QCheckBox("Monitoring enabled");
329
+ auto *notes = new QPlainTextEdit(cfg.notes);
330
+ auto *browse = button("Browse…", nullptr, [&] {
331
+ const QString fn = QFileDialog::getOpenFileName(&dlg, "Private key", QDir::homePath() + "/.ssh");
332
+ if (!fn.isEmpty()) key->setText(fn);
333
+ });
334
+ auto *test = button("Test connection");
335
+ auto *hint = label({}, "Muted", true), *result = label({}, nullptr, true);
336
+ group->setEditable(true), group->addItems(groups), group->setCurrentText(cfg.group);
337
+ via->addItems({"This machine (local)", "SSH — nothing to install on the server"}), via->setCurrentIndex(int(cfg.transport));
338
+ port->setRange(1, 65535), port->setValue(cfg.port), port->setPrefix("port ");
339
+ interval->setRange(1, 300), interval->setValue(cfg.interval), interval->setSuffix(" s");
340
+ pass->setEchoMode(QLineEdit::Password), sudo->setChecked(cfg.useSudo), enabled->setChecked(cfg.enabled), notes->setMaximumHeight(70);
341
+ name->setPlaceholderText("e.g. web-01"), host->setPlaceholderText("hostname or IP address"), user->setPlaceholderText("default: your local user name");
342
+ key->setPlaceholderText("default keys / ssh-agent (~/.ssh/id_*)"), pass->setPlaceholderText("optional — keys are recommended");
343
+ auto *addr = hbox(), *keyRow = hbox(), *testRow = hbox();
344
+ addr->addWidget(host, 1), addr->addWidget(port), keyRow->addWidget(key, 1), keyRow->addWidget(browse), testRow->addWidget(test), testRow->addWidget(result, 1);
345
+ f->addRow("Name", name), f->addRow("Group", group), f->addRow("Connect via", via), f->addRow("Address", addr), f->addRow("User", user);
346
+ f->addRow("Private key", keyRow), f->addRow("Password", pass), f->addRow("Sample every", interval), f->addRow("", enabled), f->addRow("Notes", notes);
347
+ P::sudo ? f->insertRow(8, "", sudo) : (sudo->setParent(&dlg), sudo->hide());
348
+ auto *bb = new QDialogButtonBox(QDialogButtonBox::Save | QDialogButtonBox::Cancel);
349
+ l->addLayout(f), l->addWidget(hint), l->addLayout(testRow), l->addWidget(bb);
350
+ auto collect = [&] {
351
+ ServerConfig c = cfg;
352
+ c.name = name->text().trimmed(), c.group = group->currentText().trimmed(), c.transport = Transport(via->currentIndex());
353
+ c.host = c.transport == Transport::Local ? "" : host->text().trimmed(), c.port = port->value(), c.user = user->text().trimmed();
354
+ c.keyFile = key->text().trimmed(), c.password = pass->text(), c.interval = interval->value(), c.useSudo = sudo->isChecked();
355
+ c.enabled = enabled->isChecked(), c.notes = notes->toPlainText();
356
+ return c;
357
+ };
358
+ auto show = [&](const QString &text, const QColor &c) { result->setText(text), result->setStyleSheet("color: " + c.name() + ";"); };
359
+ auto sync = [&] {
360
+ const bool ssh = via->currentIndex() == 1;
361
+ for (QWidget *w : std::initializer_list<QWidget *>{host, port, user, key, browse, pass}) w->setEnabled(ssh);
362
+ hint->setText(ssh ? P::sshHint : "Monitors the computer this program runs on. No setup needed.");
363
+ if (!ssh && name->text().isEmpty()) name->setText("This computer");
364
+ };
365
+ QObject::connect(via, QOverload<int>::of(&QComboBox::currentIndexChanged), &dlg, sync);
366
+ QObject::connect(bb, &QDialogButtonBox::rejected, &dlg, &QDialog::reject);
367
+ QObject::connect(bb, &QDialogButtonBox::accepted, &dlg, [&] {
368
+ const ServerConfig c = collect();
369
+ if (c.name.isEmpty() || (c.transport == Transport::SSH && c.host.isEmpty())) return show("Please enter a name and an address.", C::red);
370
+ dlg.accept();
371
+ });
372
+ QPointer<Link> link;
373
+ QObject::connect(test, &QPushButton::clicked, &dlg, [&] { // two frames prove that data and rates work
374
+ ServerConfig c = collect();
375
+ c.interval = 1;
376
+ delete link;
377
+ link = new Link(c, &dlg);
378
+ auto engine = std::make_shared<MetricsEngine>();
379
+ auto clock = std::make_shared<QElapsedTimer>();
380
+ auto frames = std::make_shared<int>(0);
381
+ clock->start(), test->setEnabled(false), show("Connecting…", C::amber);
382
+ auto finish = [&, l = link.data()](const QString &msg, const QColor &col) { show(msg, col), test->setEnabled(true), l->disconnect(), l->deleteLater(); };
383
+ QObject::connect(link, &Link::snapshot, &dlg, [=](const QByteArray &raw) {
384
+ const Metrics m = engine->process(raw, QDateTime::currentMSecsSinceEpoch());
385
+ if (++*frames == 2)
386
+ finish(QString("✓ Connected in %1 ms — %2 · %3 · %4 cores · %5 RAM · CPU %6").arg(clock->elapsed()).arg(m.hostname, m.os).arg(m.cpuCount).arg(Fmt::bytes(m.memTotal), Fmt::pct(m.cpuUsage, 0)), C::green);
387
+ });
388
+ QObject::connect(link, &Link::disconnected, &dlg, [=](const QString &why) { finish("✗ " + why, C::red); });
389
+ QTimer::singleShot(20000, link, [=] { finish("✗ Timed out after 20 s", C::red); });
390
+ link->start();
391
+ });
392
+ sync();
393
+ if (dlg.exec() != QDialog::Accepted) return false;
394
+ cfg = collect();
395
+ return true;
396
+ }
397
+
398
+ // ============================================================================ main window
399
+ struct MainWindow::Ui {
400
+ ServerManager *mgr;
401
+ Actions act;
402
+ QStackedWidget *stack = new QStackedWidget;
403
+ DashboardPage *dash = new DashboardPage(mgr, &act);
404
+ DetailPage *detail = new DetailPage(mgr, &act);
405
+ QWidget *eventsPage = new QWidget;
406
+ QTableWidget *events = table({"Time", "Server", "Type", "Message"}, {170, 180, 100});
407
+ QComboBox *eventFilter = new QComboBox;
408
+ QListWidget *list = new QListWidget;
409
+ QPushButton *navDash = button("▦ Dashboard", "Nav"), *navEvents = button("◉ Events && alerts", "Nav");
410
+ QLabel *badge = new QLabel;
411
+ QSystemTrayIcon *tray = nullptr;
412
+ int unseen = 0;
413
+ bool quitting = false;
414
+ };
415
+
416
+ struct ServerItemDelegate : QStyledItemDelegate { // sidebar row: dot, name, alert count, mini CPU/MEM bars
417
+ ServerManager *mgr;
418
+ ServerItemDelegate(ServerManager *m, QObject *parent) : QStyledItemDelegate(parent), mgr(m) {}
419
+ QSize sizeHint(const QStyleOptionViewItem &, const QModelIndex &) const override { return {220, 58}; }
420
+ void paint(QPainter *p, const QStyleOptionViewItem &o, const QModelIndex &i) const override
421
+ {
422
+ ServerSession *s = mgr->session(i.data(Qt::UserRole).toString());
423
+ if (!s) return;
424
+ const QRectF r = QRectF(o.rect).adjusted(6, 2, -6, -2);
425
+ const Metrics &m = s->metrics();
426
+ int y = int(r.top()) + 34;
427
+ p->save();
428
+ p->setRenderHint(QPainter::Antialiasing), p->setPen(Qt::NoPen);
429
+ if (o.state & (QStyle::State_Selected | QStyle::State_MouseOver)) p->setBrush(o.state & QStyle::State_Selected ? QColor(0x17304a) : C::card), p->drawRoundedRect(r, 8, 8);
430
+ p->setBrush(statusColor(s->status())), p->drawEllipse(QPointF(r.left() + 14, r.top() + 18), 4.5, 4.5);
431
+ p->setFont(pxFont(o.font, 13, true)), p->setPen(C::text);
432
+ p->drawText(QRectF(r.left() + 26, r.top() + 8, r.width() - 70, 20), Qt::AlignVCenter, p->fontMetrics().elidedText(s->config().name, Qt::ElideRight, int(r.width() - 70)));
433
+ if (const int n = s->activeAlerts().size()) {
434
+ const QRectF b(r.right() - 26, r.top() + 10, 20, 16);
435
+ p->setFont(pxFont(o.font, 10, true)), p->setBrush(C::red), p->setPen(Qt::NoPen), p->drawRoundedRect(b, 8, 8), p->setPen(Qt::white), p->drawText(b, Qt::AlignCenter, QString::number(n));
436
+ }
437
+ for (auto [lbl, v] : {std::pair{"CPU", m.cpuUsage}, {"MEM", m.memPct}}) {
438
+ const QRectF track(r.left() + 56, y - 2, r.width() - 70, 4);
439
+ p->setFont(pxFont(o.font, 9)), p->setPen(C::faint), p->drawText(QRectF(r.left() + 26, y - 5, 30, 10), Qt::AlignVCenter, lbl);
440
+ p->setPen(Qt::NoPen), p->setBrush(C::grid), p->drawRoundedRect(track, 2, 2);
441
+ if (s->online()) p->setBrush(C::level(v)), p->drawRoundedRect(QRectF(track.left(), track.top(), track.width() * qBound(0.0, v, 100.0) / 100, 4), 2, 2);
442
+ y += 11;
443
+ }
444
+ p->restore();
445
+ }
446
+ };
447
+
448
+ MainWindow::MainWindow(ServerManager *mgr) : ui(new Ui{mgr})
449
+ {
450
+ setWindowTitle("Server Monitor"), setWindowIcon(C::appIcon()), resize(1500, 940), setMinimumSize(1100, 700);
451
+
452
+ // navigation and server actions
453
+ auto nav = [this](QWidget *pageW) {
454
+ ui->stack->setCurrentWidget(pageW);
455
+ ui->navDash->setChecked(pageW == ui->dash), ui->navEvents->setChecked(pageW == ui->eventsPage);
456
+ if (pageW != ui->detail) ui->list->clearSelection();
457
+ };
458
+ auto refreshEvents = [this] {
459
+ QVector<AlertEvent> rs;
460
+ for (const AlertEvent &e : ui->mgr->alerts())
461
+ if (!ui->eventFilter->currentIndex() || e.severity == ui->eventFilter->currentText()) rs << e;
462
+ fillRows(ui->events, rs, [](const AlertEvent &e) {
463
+ return Row{{e.time.toString("yyyy-MM-dd HH:mm:ss"), C::muted}, {e.serverName}, {e.severity.toUpper(), C::severity(e.severity)}, {e.message}};
464
+ });
465
+ };
466
+ auto showDash = [=] { nav(ui->dash), ui->dash->refresh(); };
467
+ auto showEvents = [=] { nav(ui->eventsPage), ui->unseen = 0, ui->badge->hide(), refreshEvents(); };
468
+ auto showServer = [=](const QString &id) {
469
+ if (!mgr->session(id)) return;
470
+ ui->detail->bind(mgr->session(id)), nav(ui->detail);
471
+ for (int i = 0; i < ui->list->count(); ++i)
472
+ if (ui->list->item(i)->data(Qt::UserRole) == id) ui->list->setCurrentRow(i);
473
+ };
474
+ auto groups = [mgr] {
475
+ QStringList g;
476
+ for (ServerSession *s : mgr->sessions())
477
+ if (!s->config().group.isEmpty() && !g.contains(s->config().group)) g << s->config().group;
478
+ return g;
479
+ };
480
+ auto addServer = [=] {
481
+ ServerConfig c;
482
+ c.id = ServerConfig::newId();
483
+ if (editServer(this, c, groups())) showServer(mgr->add(c)->config().id);
484
+ };
485
+ auto editSrv = [=](const QString &id) {
486
+ ServerConfig c = mgr->session(id) ? mgr->session(id)->config() : ServerConfig();
487
+ if (mgr->session(id) && editServer(this, c, groups())) mgr->update(c);
488
+ };
489
+ auto removeSrv = [=](const QString &id) {
490
+ ServerSession *s = mgr->session(id);
491
+ if (!s) return;
492
+ QMessageBox box(QMessageBox::Warning, "Remove server", QString("Stop monitoring \"%1\" and remove it from the list?").arg(s->config().name), QMessageBox::Cancel, this);
493
+ auto *withHist = box.addButton("Remove + delete history", QMessageBox::DestructiveRole), *keep = box.addButton("Remove, keep history files", QMessageBox::AcceptRole);
494
+ box.exec();
495
+ if (box.clickedButton() != withHist && box.clickedButton() != keep) return;
496
+ if (ui->detail->s == s) ui->detail->bind(nullptr), showDash();
497
+ mgr->remove(id, box.clickedButton() == withHist);
498
+ };
499
+ auto selectedId = [this] { return ui->list->currentItem() ? ui->list->currentItem()->data(Qt::UserRole).toString() : QString(); };
500
+ ui->act = {showServer, editSrv, removeSrv, addServer, showDash};
501
+
502
+ // sidebar
503
+ auto *central = new QWidget, *side = new QWidget;
504
+ auto *h = new QHBoxLayout(central);
505
+ auto *sl = new QVBoxLayout(side), *bt = new QVBoxLayout;
506
+ auto *brand = hbox(), *evRow = hbox(), *btns = hbox();
507
+ auto *logo = new QLabel, *title = label("Server Monitor");
508
+ h->setContentsMargins(0, 0, 0, 0), h->setSpacing(0), h->addWidget(side), h->addWidget(ui->stack, 1);
509
+ setCentralWidget(central);
510
+ side->setObjectName("Sidebar"), side->setFixedWidth(260);
511
+ logo->setPixmap(C::appIcon().pixmap(34, 34)), title->setStyleSheet("font-size: 16px; font-weight: 800;");
512
+ bt->setSpacing(0), bt->addWidget(title), bt->addWidget(label("monitor · analyze · control", "Muted"));
513
+ brand->addWidget(logo), brand->addLayout(bt, 1);
514
+ ui->badge->setStyleSheet("background: #ef4444; color: white; border-radius: 9px; padding: 1px 7px; font-size: 11px; font-weight: 700;"), ui->badge->hide();
515
+ evRow->addWidget(ui->navEvents, 1), evRow->addWidget(ui->badge);
516
+ ui->navDash->setCheckable(true), ui->navEvents->setCheckable(true);
517
+ ui->list->setStyleSheet("QListWidget { background: transparent; border: none; }");
518
+ ui->list->setItemDelegate(new ServerItemDelegate(mgr, ui->list)), ui->list->setMouseTracking(true), ui->list->setContextMenuPolicy(Qt::CustomContextMenu);
519
+ btns->setSpacing(6), btns->addWidget(button("+ Add", "Primary", addServer), 1);
520
+ btns->addWidget(button("Edit", nullptr, [=] { editSrv(selectedId()); }), 1), btns->addWidget(button("Remove", "Danger", [=] { removeSrv(selectedId()); }), 1);
521
+ sl->setContentsMargins(12, 18, 12, 14), sl->setSpacing(6);
522
+ sl->addLayout(brand), sl->addSpacing(14), sl->addWidget(ui->navDash), sl->addLayout(evRow), sl->addSpacing(12);
523
+ sl->addWidget(label(" SERVERS", "Section")), sl->addWidget(ui->list, 1), sl->addLayout(btns);
524
+
525
+ // events page
526
+ auto *el = page(ui->eventsPage);
527
+ auto *eh = hbox();
528
+ auto *et = new QVBoxLayout;
529
+ et->addWidget(label("Events & alerts", "H1"));
530
+ et->addWidget(label("Alerts, recoveries, insights and every automatic or manual action, newest first. Also written to alerts.log.", "Muted"));
531
+ ui->eventFilter->addItems({"All events", "critical", "warning", "info", "resolved", "action"});
532
+ eh->addLayout(et, 1), eh->addWidget(ui->eventFilter);
533
+ eh->addWidget(button("Open log folder", nullptr, [] { QDesktopServices::openUrl(QUrl::fromLocalFile(ServerManager::configDir())); }));
534
+ eh->addWidget(button("Clear list", nullptr, [mgr] { mgr->clearAlerts(); }));
535
+ el->addLayout(eh), el->addWidget(ui->events, 1);
536
+ for (QWidget *w : std::initializer_list<QWidget *>{ui->dash, ui->detail, ui->eventsPage}) ui->stack->addWidget(w);
537
+
538
+ connect(ui->navDash, &QPushButton::clicked, this, showDash);
539
+ connect(ui->navEvents, &QPushButton::clicked, this, showEvents);
540
+ connect(ui->list, &QListWidget::itemClicked, this, [=](QListWidgetItem *it) { showServer(it->data(Qt::UserRole).toString()); });
541
+ connect(ui->list, &QWidget::customContextMenuRequested, this, [=](const QPoint &pos) {
542
+ QListWidgetItem *it = ui->list->itemAt(pos);
543
+ if (!it) return;
544
+ const QString id = it->data(Qt::UserRole).toString();
545
+ QMenu m;
546
+ m.addAction("Open", [=] { showServer(id); }), m.addAction("Reconnect", [=] { mgr->session(id)->reconnect(); }), m.addSeparator();
547
+ m.addAction("Move up", [=] { mgr->move(id, -1); }), m.addAction("Move down", [=] { mgr->move(id, 1); }), m.addSeparator();
548
+ m.addAction("Edit…", [=] { editSrv(id); }), m.addAction("Remove…", [=] { removeSrv(id); });
549
+ m.exec(ui->list->viewport()->mapToGlobal(pos));
550
+ });
551
+ connect(ui->eventFilter, QOverload<int>::of(&QComboBox::currentIndexChanged), this, refreshEvents);
552
+ connect(mgr, &ServerManager::alertsCleared, this, refreshEvents);
553
+ connect(mgr, &ServerManager::listChanged, this, [=] {
554
+ const QString cur = selectedId();
555
+ ui->list->clear();
556
+ for (ServerSession *s : mgr->sessions()) {
557
+ auto *it = new QListWidgetItem(s->config().name, ui->list);
558
+ it->setData(Qt::UserRole, s->config().id);
559
+ if (s->config().id == cur) ui->list->setCurrentItem(it);
560
+ }
561
+ });
562
+ connect(mgr, &ServerManager::alertRaised, this, [=](const AlertEvent &e) {
563
+ const bool important = e.severity == "critical" || e.severity == "warning" || e.severity == "action";
564
+ if (ui->stack->currentWidget() == ui->eventsPage) refreshEvents();
565
+ else if (important) ui->badge->setText(QString::number(++ui->unseen)), ui->badge->show();
566
+ if (ui->tray && important && QSettings().value("notify", true).toBool())
567
+ ui->tray->showMessage(e.serverName + " — " + e.severity, e.message, e.severity == "critical" ? QSystemTrayIcon::Critical : e.severity == "warning" ? QSystemTrayIcon::Warning : QSystemTrayIcon::Information, 8000);
568
+ });
569
+ auto *tick = new QTimer(this); // sidebar bars + dashboard tiles
570
+ connect(tick, &QTimer::timeout, this, [this] {
571
+ ui->list->viewport()->update();
572
+ if (ui->stack->currentWidget() == ui->dash) ui->dash->refresh();
573
+ });
574
+ tick->start(1000);
575
+
576
+ if (QSystemTrayIcon::isSystemTrayAvailable()) {
577
+ ui->tray = new QSystemTrayIcon(C::appIcon(), this);
578
+ auto *menu = new QMenu(this);
579
+ menu->addAction("Show window", this, [this] { showNormal(), raise(), activateWindow(); });
580
+ for (auto [text, key] : {std::pair{"Desktop notifications", "notify"}, {"Keep running in tray when closed", "closeToTray"}}) {
581
+ QAction *a = menu->addAction(text);
582
+ a->setCheckable(true), a->setChecked(QSettings().value(key, true).toBool());
583
+ connect(a, &QAction::toggled, [k = QString(key)](bool on) { QSettings().setValue(k, on); });
584
+ }
585
+ menu->addSeparator(), menu->addAction("Quit", this, [this] { ui->quitting = true, qApp->quit(); });
586
+ ui->tray->setContextMenu(menu), ui->tray->setToolTip("Server Monitor"), ui->tray->show();
587
+ connect(ui->tray, &QSystemTrayIcon::activated, this, [this](QSystemTrayIcon::ActivationReason r) {
588
+ if (r == QSystemTrayIcon::Trigger) isVisible() && !isMinimized() ? hide() : (showNormal(), raise(), activateWindow());
589
+ });
590
+ }
591
+ restoreGeometry(QSettings().value("geometry").toByteArray());
592
+ showDash();
593
+ }
594
+
595
+ void MainWindow::closeEvent(QCloseEvent *e)
596
+ {
597
+ QSettings st;
598
+ st.setValue("geometry", saveGeometry());
599
+ if (ui->quitting || !ui->tray || !st.value("closeToTray", true).toBool()) return qApp->quit();
600
+ hide(), e->ignore();
601
+ if (!st.value("trayHintShown").toBool()) ui->tray->showMessage("Server Monitor", "Still monitoring in the background. Right-click the tray icon to quit."), st.setValue("trayHintShown", true);
602
+ }
603
+
604
+ void MainWindow::saveSnapshots(const QString &dir)
605
+ {
606
+ auto settle = [] { QEventLoop loop; QTimer::singleShot(700, &loop, &QEventLoop::quit), loop.exec(); }; // let animations finish
607
+ QTabWidget *tabs = ui->detail->tabs;
608
+ grab().save(dir + "/00-dashboard.png");
609
+ if (ui->mgr->sessions().isEmpty()) return;
610
+ ui->act.open(ui->mgr->sessions()[0]->config().id);
611
+ for (int i = 0; i < tabs->count(); ++i)
612
+ tabs->setCurrentIndex(i), settle(), grab().save(QString("%1/%2-%3.png").arg(dir).arg(i + 1, 2, 10, QChar('0')).arg(tabs->tabText(i).split(' ')[0].toLower()));
613
+ ui->navEvents->click(), settle(), grab().save(dir + "/99-events.png");
614
+ }
Server Monitor(cqt-window)/src/ui/Windows.h ADDED
@@ -0,0 +1,22 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ // Detail-page tab interface and the main window (sidebar, dashboard, server page, events, tray).
2
+ #pragma once
3
+ #include "core/Session.h"
4
+ #include <QMainWindow>
5
+
6
+ struct Tab : QWidget { // one aspect of the bound server session
7
+ QPointer<ServerSession> s;
8
+ qint64 span = 15 * 60000; // live chart window
9
+ std::function<void(const ServerConfig &)> save; // persists config edits
10
+ virtual void bind(ServerSession *x) { s = x; }
11
+ virtual void refresh() {} // new sample (only while visible)
12
+ virtual void analysis() {} // analyzer ran
13
+ };
14
+ QVector<QPair<QString, Tab *>> makeTabs();
15
+
16
+ struct MainWindow : QMainWindow {
17
+ explicit MainWindow(ServerManager *mgr);
18
+ void saveSnapshots(const QString &dir); // developer aid: PNG of every page
19
+ void closeEvent(QCloseEvent *e) override;
20
+ struct Ui;
21
+ Ui *ui;
22
+ };
Server Monitor(python-linux)/README.md ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Server Monitor (Python, Linux)
2
+
3
+ A desktop program that watches Linux machines in detail, keeps their history from seconds to years, analyzes that history with plain statistics (no AI), and fixes common problems automatically. It is a port of the C++/Qt edition to the Python 3 standard library only: the interface is tkinter, and every gauge, chart, tile and table is drawn by hand on a canvas.
4
+
5
+ ## Requirements
6
+
7
+ - Linux, Python 3.8 or newer with tkinter (`sudo apt install python3-tk` on Debian/Ubuntu). No pip packages.
8
+ - The system `ssh` client, only for remote servers.
9
+
10
+ ## Run
11
+
12
+ ```bash
13
+ ./run.sh # or: python3 main.py
14
+ ```
15
+
16
+ The first start adds "This computer". Closing the window ends the program (there is no tray icon).
17
+
18
+ ## How it connects
19
+
20
+ - **This machine:** no setup. A small POSIX `sh` script (embedded in `plat.py`) reads `/proc` and `/sys`.
21
+ - **SSH:** nothing to install on the server. The same script is sent over your `ssh` client. Keys are recommended (`ssh-copy-id user@host`); a password also works, and a small temporary helper script answers ssh's password prompt.
22
+
23
+ All calculations happen in the app. Control actions run as the login user; tick **sudo -n** for a server to allow privileged actions (needs passwordless sudo).
24
+
25
+ ## Features
26
+
27
+ - **Dashboard:** a live card per server (gauges, sparkline, health grade), totals, recent events, search.
28
+ - **Server tabs:** Overview, CPU (per core, temperatures, GPUs), Memory, Storage, Network, Processes (signals, priority), Services (start/stop/restart/enable/disable, logs), History, Insights & Autopilot, Alert rules, Console.
29
+ - **History:** every sample kept 6 h, 1-minute averages and peaks 30 days, hourly 2 years, daily 20 years; downtime is stored too. Ranges from 1 h to all time, min / average / 95th percentile / peak, CSV export.
30
+ - **Analysis (every minute):** disk-full forecast, memory trend, per-process leaks and runaways, failed or flapping services, overload, swap thrashing, anomalies against the same weekday and hour, availability, capacity advice, health score with grade, weekly heatmap.
31
+ - **Autopilot:** acts on the findings with cooldowns and a restart limit; **dry run** only reports. Services that were already failed when monitoring started are left alone.
32
+ - **Alert rules:** "CPU > 90 % for 60 s → warning → restart a service"; events go to the Events page and to `alerts.log`.
33
+
34
+ ## Data
35
+
36
+ Everything is stored in `~/.config/ServerMonitorPy` (or `$XDG_CONFIG_HOME/ServerMonitorPy`):
37
+
38
+ - `servers.json` (mode 600): servers, rules and autopilot settings. Saved SSH passwords are only lightly disguised, not encrypted, so prefer keys.
39
+ - `history/<server id>/{raw,minute,hour,day}.bin`: the history tiers.
40
+ - `alerts.log`: every alert and action.
41
+
42
+ The file formats are the same as in the other Server Monitor editions, so files can be copied between them.
43
+
44
+ ## Code
45
+
46
+ ```
47
+ main.py entry point
48
+ plat.py everything Linux-specific: collector script, spawning, frame parser, command tables
49
+ metrics.py one parsed sample + helpers shared by the platform parsers
50
+ model.py configuration, rules, formatting
51
+ history.py history store + analyzer
52
+ session.py ssh/local link, per-server session (rules, autopilot), manager
53
+ widgets.py theme, hand-drawn widgets, small UI builders
54
+ tabs.py server detail tabs
55
+ ui.py dashboard, detail page, add/edit dialog, main window
56
+ ```
57
+
58
+ Only `plat.py` differs from the Windows edition.
Server Monitor(python-linux)/history.py ADDED
@@ -0,0 +1,331 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Persistent multi-resolution history (raw 6 h, minute 30 d, hour 2 y, day 20 y)
2
+ and the statistics-only analyzer that feeds the autopilot."""
3
+ import math, os, struct, time
4
+ from array import array
5
+ from bisect import bisect_left, bisect_right
6
+ from collections import namedtuple
7
+
8
+ import plat
9
+ from model import duration, fmt_bytes, pct, rate, rnd, temp
10
+
11
+ KEYS = 'cpu iowait load mem swap disk diskio rx tx rd wr temp procs gpu failed'.split()
12
+ NAMES = ['CPU', 'I/O wait', 'Load (1m)', 'Memory', 'Swap', 'Disk usage', 'Disk busy', 'Net download', 'Net upload', 'Disk read',
13
+ 'Disk write', 'Temperature', 'Processes', 'GPU', 'Failed services']
14
+ CPU, IOWAIT, LOAD, MEM, SWAP, DISK, DISKIO, RX, TX, RD, WR, TEMP, PROCS, GPU, FAILED = range(15)
15
+ H_COUNT, NAN = len(KEYS), math.nan
16
+ TIERS, TIER_NAMES = ('raw', 'minute', 'hour', 'day'), ('every sample', '1 minute', '1 hour', '1 day')
17
+ STEP, KEEP, MAX_SPAN = (1, 60, 3600, 86400), (6 * 3600, 30 * 86400, 732 * 86400, 7320 * 86400), (6 * 3600, 8 * 86400, 400 * 86400)
18
+ REC = struct.Struct('<qII15f15f') # ts (bucket start for aggregates), samples, online samples, avg[15], max[15]
19
+ HEADER = b'SMH1' + bytes([H_COUNT, 0]) + struct.pack('<H', REC.size)
20
+
21
+ class Points:
22
+ """Column store of history records: ts, n (samples), up (online samples), avg[metric], max[metric]."""
23
+ def __init__(self, rows=(), cols=None):
24
+ self.c = cols or [array(t, c) for t, c in zip('qII' + 'f' * 30, zip(*rows) if rows else [()] * 33)]
25
+ (self.ts, self.n, self.up), self.avg, self.max = self.c[:3], self.c[3:3 + H_COUNT], self.c[3 + H_COUNT:]
26
+ def __len__(self): return len(self.ts)
27
+ def add(self, row):
28
+ for c, v in zip(self.c, row): c.append(v)
29
+ def cut(self, i, j=None): return Points(cols=[c[i:j] for c in self.c])
30
+ def rows(self): return zip(*self.c)
31
+
32
+ class Acc:
33
+ """Running aggregate of one open bucket."""
34
+ def __init__(self, bucket=-1):
35
+ self.bucket, self.n, self.up = bucket, 0, 0
36
+ self.cnt, self.sum, self.max = [0] * H_COUNT, [0.0] * H_COUNT, [NAN] * H_COUNT
37
+ def add(self, r):
38
+ self.n, self.up = self.n + r[1], self.up + r[2]
39
+ for i in range(H_COUNT if r[2] else 0):
40
+ avg, mx = r[3 + i], r[3 + H_COUNT + i]
41
+ if avg == avg:
42
+ self.sum[i] += avg * r[2]
43
+ self.cnt[i] += r[2]
44
+ if self.max[i] != self.max[i] or mx > self.max[i]: self.max[i] = mx
45
+ def row(self): # through the record format, so the values are float32 like the stored ones
46
+ return REC.unpack(REC.pack(self.bucket, self.n, self.up, *(s / c if c else NAN for s, c in zip(self.sum, self.cnt)), *self.max))
47
+
48
+ class Store:
49
+ def __init__(self, path):
50
+ self.dir, self.tz, self.appends = path, time.localtime().tm_gmtoff, [0] * 4
51
+ os.makedirs(path, exist_ok=True)
52
+ now = int(time.time())
53
+ self.tiers, self.acc = [Points() for _ in TIERS], [Acc() for _ in TIERS]
54
+ for t in range(4): self.load(t, now)
55
+ for t in (1, 2, 3): # rebuild from finer data what is not stored yet: buckets the last run left open, and the current one
56
+ finer, stored = self.tiers[t - 1], self.tiers[t].ts[-1] if len(self.tiers[t]) else -1
57
+ for r in [*finer.cut(bisect_right(finer.ts, stored)).rows(), *([self.acc[t - 1].row()] if self.acc[t - 1].n else [])]:
58
+ b, a = self.bucket(t, r[0]), self.acc[t]
59
+ if b <= stored: continue
60
+ if b != a.bucket:
61
+ if a.n: self.append(t, a.row())
62
+ a = self.acc[t] = Acc(b)
63
+ a.add(r)
64
+ def file(self, t): return os.path.join(self.dir, TIERS[t] + '.bin')
65
+ def bucket(self, t, ts): return (ts + self.tz) // 86400 * 86400 - self.tz if t == 3 else ts // STEP[t] * STEP[t] # days start at local midnight
66
+ def load(self, t, now):
67
+ try:
68
+ with open(self.file(t), 'rb') as f: data = f.read()
69
+ except OSError:
70
+ return
71
+ if not data.startswith(HEADER): return os.replace(self.file(t), self.file(t) + '.old')
72
+ rows, last = [], -1
73
+ for r in REC.iter_unpack(data[len(HEADER):len(data) - (len(data) - len(HEADER)) % REC.size]):
74
+ if now - KEEP[t] <= r[0] <= now + 86400 and r[0] > last:
75
+ rows.append(r)
76
+ last = r[0]
77
+ self.tiers[t] = Points(rows)
78
+ if len(HEADER) + len(rows) * REC.size != len(data): # expired or damaged records, or a cut-off one that would misalign what is appended
79
+ self.rewrite(t)
80
+ def rewrite(self, t):
81
+ try:
82
+ with open(self.file(t) + '.tmp', 'wb') as f: f.write(HEADER + b''.join(REC.pack(*r) for r in self.tiers[t].rows()))
83
+ os.replace(self.file(t) + '.tmp', self.file(t))
84
+ except OSError:
85
+ pass # history stays in memory when the disk is full or read-only
86
+ def append(self, t, row):
87
+ p = self.tiers[t]
88
+ if len(p) and row[0] <= p.ts[-1]: return
89
+ p.add(row)
90
+ try:
91
+ with open(self.file(t), 'ab') as f:
92
+ if f.tell() < len(HEADER):
93
+ f.truncate(0)
94
+ f.write(HEADER)
95
+ f.write(REC.pack(*row))
96
+ except OSError:
97
+ pass
98
+ self.appends[t] += 1
99
+ if self.appends[t] % 500 == 0: # trim expired points now and then
100
+ k = bisect_left(p.ts, row[0] - KEEP[t])
101
+ if k:
102
+ self.tiers[t] = p.cut(k)
103
+ self.rewrite(t)
104
+ def add(self, ts, values, up):
105
+ """Records one sample; up=False records downtime only."""
106
+ v = values if up else [NAN] * H_COUNT
107
+ raw = REC.unpack(REC.pack(ts, 1, int(up), *v, *v))
108
+ self.append(0, raw)
109
+ for t in (1, 2, 3): # every coarser tier accumulates every raw sample
110
+ b, a = self.bucket(t, ts), self.acc[t]
111
+ if a.bucket != b:
112
+ if a.n and a.bucket < b: self.append(t, a.row())
113
+ a = self.acc[t] = Acc(b)
114
+ a.add(raw)
115
+ def range(self, frm, to, t):
116
+ """Points of tier t in [frm, to], including the open bucket."""
117
+ p, a = self.tiers[t], self.acc[t]
118
+ out = p.cut(bisect_left(p.ts, frm), bisect_right(p.ts, to))
119
+ if t and a.n and frm <= a.bucket <= to and (not len(out) or out.ts[-1] < a.bucket): out.add(a.row())
120
+ return out
121
+ def span(self, frm, to):
122
+ """(points, tier) from the finest tier that covers the range."""
123
+ now, t = int(time.time()), 0
124
+ while t < 3 and (frm < now - KEEP[t] or to - frm > MAX_SPAN[t]): t += 1
125
+ return self.range(frm, to, t), t
126
+ def first_ts(self): return min((p.ts[0] for p in self.tiers if len(p)), default=0)
127
+ def disk_bytes(self): return sum(os.path.getsize(self.file(t)) for t in range(4) if os.path.exists(self.file(t)))
128
+
129
+ Stats = namedtuple('Stats', 'min avg p95 max count', defaults=(NAN, NAN, NAN, NAN, 0)) # max = peak of max[]
130
+
131
+ def stats(p, m):
132
+ v = [(a, x, u) for a, x, u in zip(p.avg[m], p.max[m], p.up) if u and a == a]
133
+ if not v: return Stats()
134
+ a = sorted(r[0] for r in v)
135
+ return Stats(a[0], sum(r[0] * r[2] for r in v) / sum(r[2] for r in v), a[min(len(a) - 1, int(len(a) * 0.95))], max(r[1] for r in v), len(a))
136
+
137
+ def regression(p, m):
138
+ """Least-squares (slope per second, squared correlation) of a metric over time."""
139
+ xy = [(t - p.ts[0], y) for t, y, u in zip(p.ts, p.avg[m], p.up) if u and y == y]
140
+ n, sx, sy = len(xy), sum(x for x, _ in xy), sum(y for _, y in xy)
141
+ den, num, vy = n * sum(x * x for x, _ in xy) - sx * sx, n * sum(x * y for x, y in xy) - sx * sy, n * sum(y * y for _, y in xy) - sy * sy
142
+ if n < 3 or den <= 0: return 0.0, 0.0
143
+ return num / den, num * num / (den * vy) if vy > 1e-9 else 0.0
144
+
145
+ def slot(ts):
146
+ """(weekday, hour) of a timestamp in local time; Monday = 0."""
147
+ t = time.localtime(ts)
148
+ return t.tm_wday, t.tm_hour
149
+
150
+ def fmt_metric(m, v):
151
+ if v != v: return '—'
152
+ return rate(v) if m in (RX, TX, RD, WR) else f'{v:.2f}' if m == LOAD else temp(v) if m == TEMP else f'{v:.0f}' if m in (PROCS, FAILED) else pct(v)
153
+
154
+ # ---- analysis -------------------------------------------------------------------
155
+ # action: disk_cleanup | restart_service | renice | kill_pid
156
+ Finding = namedtuple('Finding', 'key severity category title detail advice action arg label auto')
157
+ ProcTrend = namedtuple('ProcTrend', 'pid minutes name user cpu_now high_cpu_minutes rss_now rss_growth rss_growth_pct rss_monotonic protected',
158
+ defaults=(0, 0, '', '', 0, 0, 0, 0, 0, 0, False))
159
+ ServiceTrend = namedtuple('ServiceTrend', 'unit failed_now preexisting fails_last_hour auto_restarts_last_hour')
160
+ Anomaly = namedtuple('Anomaly', 'metric baseline hm now mean sd z')
161
+
162
+ class Analysis:
163
+ def __init__(self):
164
+ self.when, self.health, self.grade, self.disk_basis = 0, 100, 'A', ''
165
+ self.reasons, self.capacity, self.findings, self.anomalies = [], [], [], []
166
+ self.disk_full_days, self.disk_slope_per_day, self.mem_slope_per_hour, self.mem_trend_r2 = -1, 0, 0, 0
167
+ self.up, self.down, self.cpu30, self.mem30 = [NAN] * 3, [0] * 3, Stats(), Stats() # 24 h, 7 d, 30 d: availability %, seconds offline
168
+ self.heat = [[[NAN] * 24 for _ in range(7)] for _ in range(2)] # weekly pattern: 0 = CPU, 1 = memory
169
+ self.heat_n = [[0] * 24 for _ in range(7)]
170
+
171
+ def analyze(st, m, ap, procs, svcs, online):
172
+ a = Analysis()
173
+ now = a.when = int(time.time())
174
+ minute, hour, cores = st.tiers[1], st.tiers[2], max(1, m.cpu_count)
175
+
176
+ def add(key, sev, cat, title, detail, advice, action='', arg='', label='', auto=False):
177
+ a.findings.append(Finding(key, sev, cat, title, detail, advice, action, arg, label, bool(auto)))
178
+
179
+ def sev(crit, warn): return 'critical' if crit else 'warning' if warn else 'info'
180
+
181
+ # availability
182
+ spans = (86400, 7 * 86400, 30 * 86400)
183
+ for i, span in enumerate(spans):
184
+ p = st.span(now - span, now)[0]
185
+ n, up = sum(p.n), sum(p.up)
186
+ if n: a.up[i], a.down[i] = up * 100 / n, (n - up) / n * min(span, now - st.first_ts()) # share of the monitored part of the window
187
+ if a.up[0] < 99:
188
+ add('avail24', sev(a.up[0] < 95, True), 'Availability', f'Availability last 24 h is {pct(a.up[0], 2)}',
189
+ f'The server could not be reached for about {duration(a.down[0])} in the last day.',
190
+ 'Check network stability, power and whether the machine rebooted (uptime).')
191
+ w30, w7 = st.range(now - spans[2], now, 2), st.range(now - spans[1], now, 1)
192
+ a.cpu30, a.mem30 = (stats(w30 if len(w30) >= 24 else w7, k) for k in (CPU, MEM))
193
+
194
+ # disk forecast: regression over 7 d of hours, or 24 h of minutes, whichever fits better
195
+ slope = r2 = 0.0
196
+ week, day = st.range(now - spans[1], now, 2), st.range(now - 86400, now, 1)
197
+ if len(week) >= 48: (slope, r2), a.disk_basis = regression(week, DISK), 'hourly averages, last 7 days'
198
+ if len(day) >= 120:
199
+ s2, r2b = regression(day, DISK)
200
+ if len(week) < 48 or r2b > r2: slope, r2, a.disk_basis = s2, r2b, 'minute averages, last 24 hours'
201
+ a.disk_slope_per_day = slope * 86400
202
+ if a.disk_slope_per_day > 0.05 and r2 >= 0.3 and m.max_disk_pct > 0: a.disk_full_days = (100 - m.max_disk_pct) / a.disk_slope_per_day
203
+ if 0 <= a.disk_full_days < 30:
204
+ add('diskfull', sev(a.disk_full_days < ap.diskForecastDays, a.disk_full_days < 14), 'Disk',
205
+ f'Disk {m.fullest_mount} will be full in {duration(a.disk_full_days * 86400)}',
206
+ f'Usage {pct(m.max_disk_pct)}, growing {a.disk_slope_per_day:.2f} points/day (trend from {a.disk_basis}, fit R² {r2:.2f}).',
207
+ 'Clean logs/caches, rotate or move data, or grow the volume.', 'disk_cleanup', '', 'Run cleanup',
208
+ ap.diskCleanup and a.disk_full_days < ap.diskForecastDays)
209
+ if m.max_disk_pct >= ap.diskCleanupAt:
210
+ add('diskhigh', sev(m.max_disk_pct >= 97, True), 'Disk', f'Disk {m.fullest_mount} is {pct(m.max_disk_pct)} full',
211
+ f'Above the cleanup threshold of {pct(ap.diskCleanupAt, 0)}.', 'Free space soon: services fail when the disk is full.',
212
+ 'disk_cleanup', '', 'Run cleanup', ap.diskCleanup)
213
+
214
+ # whole-machine memory trend over 6 h
215
+ six = st.range(now - 6 * 3600, now, 1)
216
+ if len(six) >= 90:
217
+ slope, a.mem_trend_r2 = regression(six, MEM)
218
+ a.mem_slope_per_hour = slope * 3600
219
+ left = (100 - m.mem_pct) / max(0.01, a.mem_slope_per_hour)
220
+ if a.mem_slope_per_hour > 1 and a.mem_trend_r2 > 0.8 and m.mem_pct > 40:
221
+ add('memtrend', sev(False, left < 12), 'Memory', f'Memory keeps growing (+{a.mem_slope_per_hour:.1f} points/hour)',
222
+ f'Steady growth over 6 h (R² {a.mem_trend_r2:.2f}). At this rate memory is exhausted in about {duration(left * 3600)}.',
223
+ 'Look for a leaking process (Processes tab, sort by RSS).')
224
+
225
+ # processes: leaks and runaways
226
+ for p in procs:
227
+ if p.protected: continue
228
+ who = f'{p.name} (PID {p.pid})'
229
+ if p.minutes >= 30 and p.rss_growth_pct >= 25 and p.rss_growth >= 100e6 and p.rss_monotonic >= 0.8:
230
+ add(f'leak:{p.pid}', sev(m.mem_pct >= ap.leakMemPressure, True), 'Process', 'Possible memory leak: ' + who,
231
+ f'RSS grew {fmt_bytes(p.rss_growth)} (+{pct(p.rss_growth_pct, 0)}) in {p.minutes} min and rose in '
232
+ f'{rnd(p.rss_monotonic * 100)}% of the minutes; now {fmt_bytes(p.rss_now)}.',
233
+ 'Restart the program/service at a quiet time and report the leak upstream.', 'kill_pid', str(p.pid), 'Terminate',
234
+ ap.leakMode == 'terminate' and m.mem_pct >= ap.leakMemPressure)
235
+ if p.high_cpu_minutes >= ap.runawayMinutes:
236
+ term = ap.runawayMode == 'terminate'
237
+ add(f'runaway:{p.pid}', 'warning', 'Process', 'Runaway process: ' + who,
238
+ f'Above {pct(ap.runawayCpu, 0)} CPU for {rnd(p.high_cpu_minutes)} min (now {pct(p.cpu_now)}, user {p.user}).',
239
+ plat.TEXT['renice_advice'], 'kill_pid' if term else 'renice', str(p.pid), 'Terminate' if term else plat.TEXT['renice'],
240
+ ap.runawayMode != 'none')
241
+
242
+ # services: failures and flapping
243
+ for s in svcs:
244
+ flap = s.fails_last_hour >= 3 or s.auto_restarts_last_hour >= ap.maxRestartsPerHour
245
+ if s.failed_now:
246
+ add('svc:' + s.unit, sev(flap, True), 'Service', f'Service {s.unit} ' + ('keeps failing' if flap else 'has failed'),
247
+ 'It was already failed when monitoring started, so the autopilot leaves it alone (it may be failed on purpose).' if s.preexisting
248
+ else f'Failed {s.fails_last_hour}× in the last hour; autopilot restarted it {s.auto_restarts_last_hour}×.',
249
+ 'Automatic restarts were stopped. Read the logs (Services tab → Logs) and fix the cause.' if flap else 'Restart it and check the logs.',
250
+ 'restart_service', s.unit, 'Restart', ap.restartFailed and not s.preexisting and s.auto_restarts_last_hour < ap.maxRestartsPerHour)
251
+ elif s.fails_last_hour >= 3:
252
+ add('flap:' + s.unit, 'warning', 'Service', f'Service {s.unit} is unstable',
253
+ f'It failed {s.fails_last_hour} times within the last hour.', 'Inspect its logs and resource limits.')
254
+
255
+ # overload and swap thrashing
256
+ last15 = st.range(now - 900, now, 1)
257
+ load15, io15, cpu15, busy15 = (stats(last15, k).avg for k in (LOAD, IOWAIT, CPU, DISKIO))
258
+ if online and load15 / cores > 1.5:
259
+ add('load', sev(load15 / cores > 3, True), 'CPU', f'CPU is overloaded (load {load15:.1f} on {cores} cores)',
260
+ f'15-minute average load is {load15 / cores:.1f}× the number of cores; tasks are waiting for CPU.',
261
+ 'Find the busiest processes, spread work over time, or add CPU.')
262
+ thrash = plat.thrashing(io15, m.mem_pct, busy15)
263
+ if online and m.swap_pct > 50 and thrash:
264
+ add('thrash', 'critical', 'Memory', 'Swap thrashing', f'Swap {pct(m.swap_pct)} used{thrash}.', 'Stop memory-hungry processes or add RAM.')
265
+
266
+ # anomalies: last 10 min vs same weekday+hour over 8 weeks (fallback: last 24 h)
267
+ raw = st.range(now - 600, now, 0)
268
+ same = [i for i in range(bisect_right(hour.ts, now - 56 * 86400), bisect_left(hour.ts, now - 3600)) if slot(hour.ts[i]) == slot(now)]
269
+ recent = range(bisect_left(minute.ts, now - 86400), bisect_left(minute.ts, now - 900))
270
+ checks = [(CPU, 5.0, False), (MEM, 3.0, False), (LOAD, 0.25 * cores, False), (IOWAIT, 3.0, False), (RX, 256e3, True), (TX, 256e3, True)]
271
+ for hm, floor, down in checks if online and len(raw) >= 10 else (): # (metric, smallest deviation unit, alert on drops)
272
+ if hm == IOWAIT and not plat.POSIX_CPU: continue
273
+ cur, basis = stats(raw, hm).avg, 'same weekday & hour, last 8 weeks'
274
+ v = [hour.avg[hm][i] for i in same if hour.up[i] and hour.avg[hm][i] == hour.avg[hm][i]]
275
+ if len(v) < 3:
276
+ v, basis = [minute.avg[hm][i] for i in recent if minute.up[i] and minute.avg[hm][i] == minute.avg[hm][i]], 'last 24 hours'
277
+ if len(v) < 360: continue
278
+ mean = sum(v) / len(v)
279
+ sd = math.sqrt(sum((x - mean) ** 2 for x in v) / len(v))
280
+ z = (cur - mean) / max(sd, floor)
281
+ a.anomalies.append(Anomaly(NAMES[hm], basis, hm, cur, mean, sd, z))
282
+ hi, lo = z >= ap.anomalyZ, down and mean > 1e6 and cur < mean * 0.1
283
+ if ap.anomalyAlerts and (hi or lo):
284
+ add('anomaly:' + KEYS[hm], sev(False, z >= ap.anomalyZ * 2), 'Anomaly', f'Unusually {"high" if hi else "low"} {NAMES[hm].lower()}',
285
+ f'Last 10 min {fmt_metric(hm, cur)}, usually {fmt_metric(hm, mean)} ± {fmt_metric(hm, sd)} ({basis}); {z:.1f}σ.',
286
+ 'Check what changed: deploys, cron jobs, traffic, attacks.' if hi else 'Traffic dropped sharply - check the service is still serving.')
287
+
288
+ # weekly heatmaps from 4 weeks of hours
289
+ total = [[[0.0] * 24 for _ in range(7)] for _ in range(2)]
290
+ for i in range(bisect_left(hour.ts, now - 28 * 86400), len(hour)):
291
+ cpu, mem = hour.avg[CPU][i], hour.avg[MEM][i]
292
+ if not hour.up[i] or cpu != cpu: continue
293
+ d, h = slot(hour.ts[i])
294
+ a.heat_n[d][h] += 1
295
+ for k, v in enumerate((cpu, mem if mem == mem else 0)):
296
+ total[k][d][h] += v
297
+ a.heat[k][d][h] = total[k][d][h] / a.heat_n[d][h]
298
+
299
+ # capacity advice
300
+ for s, name, lo, hi, lo_txt, hi_txt in ((a.cpu30, 'CPU', 15, 80, 'is mostly idle', 'is often saturated - add cores or move work away'),
301
+ (a.mem30, 'Memory', 30, 85, 'is under-used', 'is tight - add RAM or reduce caches/limits')):
302
+ if s.count >= 60: a.capacity.append(f'{name} {lo_txt if s.p95 < lo else hi_txt if s.p95 > hi else "headroom is healthy"} (p95 {pct(s.p95)}).')
303
+ if a.disk_full_days >= 0:
304
+ a.capacity.append(f'Disk grows {a.disk_slope_per_day:.2f} points/day - full in about {duration(a.disk_full_days * 86400)}.')
305
+ elif a.disk_basis:
306
+ a.capacity.append('Disk usage is stable.')
307
+ if not a.capacity: a.capacity.append('Collecting history - capacity advice appears after about an hour of data.')
308
+
309
+ # health score
310
+ score = 100.0
311
+
312
+ def pen(when, p, why):
313
+ nonlocal score
314
+ if when and p > 0.5:
315
+ score -= p
316
+ a.reasons.append(f'−{rnd(p)} {why}')
317
+
318
+ cpu = m.cpu_usage if cpu15 != cpu15 else cpu15
319
+ pen(not online, 60, 'server unreachable')
320
+ pen(cpu > 70, min(24, (cpu - 70) * 0.8), f'CPU busy ({pct(cpu)})')
321
+ pen(m.mem_pct > 80, min(30, (m.mem_pct - 80) * 1.5), f'memory high ({pct(m.mem_pct)})')
322
+ pen(m.max_disk_pct > 80, min(40, (m.max_disk_pct - 80) * 2), f'disk high ({pct(m.max_disk_pct)})')
323
+ pen(m.swap_pct > 50, 10, 'heavy swap use')
324
+ pen(m.max_temp > 80, min(20, (m.max_temp - 80) * 2), f'hot ({temp(m.max_temp)})')
325
+ pen(a.up[0] < 100, min(30, (100 - a.up[0]) * 5), 'downtime in last 24 h')
326
+ pen(True, min(50, sum(0 if f.category == 'Availability' else {'critical': 15, 'warning': 7}.get(f.severity, 2) for f in a.findings)),
327
+ f'{len(a.findings)} finding(s)')
328
+ a.health = min(max(rnd(score), 0), 100)
329
+ a.grade = 'FDCBA'[sum(a.health >= x for x in (40, 60, 75, 90))]
330
+ a.findings.sort(key=lambda f: {'critical': 0, 'warning': 1}.get(f.severity, 2))
331
+ return a
Server Monitor(python-linux)/main.py ADDED
@@ -0,0 +1,13 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Server Monitor - entry point."""
2
+ import tkinter as tk
3
+
4
+ from session import Manager
5
+ from ui import MainWindow
6
+
7
+ def main():
8
+ root, mgr = tk.Tk(), Manager()
9
+ MainWindow(root, mgr)
10
+ mgr.load()
11
+ root.mainloop()
12
+
13
+ if __name__ == '__main__': main()
Server Monitor(python-linux)/metrics.py ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """One parsed sample (Metrics) and the frame helpers shared by the platform parsers."""
2
+ from collections import namedtuple
3
+
4
+ Core = namedtuple('Core', 'usage mhz')
5
+ Mount = namedtuple('Mount', 'device type mount total used avail pct')
6
+ Disk = namedtuple('Disk', 'name read_bps write_bps read_iops write_iops util total_read total_written')
7
+ Net = namedtuple('Net', 'name state speed virt rx_bps tx_bps rx_pps tx_pps rx_bytes tx_bytes errors drops')
8
+ Proc = namedtuple('Proc', 'pid ppid threads nice name user state cpu mem_pct rss vsz age') # cpu: % of one core
9
+ Service = namedtuple('Service', 'unit load active sub description')
10
+ Temp = namedtuple('Temp', 'name celsius')
11
+ Gpu = namedtuple('Gpu', 'index name util mem_used mem_total temp power fan')
12
+
13
+ class Metrics:
14
+ TEXTS = 'hostname os kernel arch cpu_model virt fullest_mount busiest_disk'
15
+ NUMBERS = ('cpu_count logged_users procs_running procs_blocked threads_total sockets_used services_failed services_running '
16
+ 'uptime load1 load5 load15 cpu_usage cpu_user cpu_system cpu_iowait cpu_steal cpu_irq ctxt_per_sec intr_per_sec '
17
+ 'forks_per_sec avg_mhz mem_total mem_free mem_available mem_used buffers cached shared slab dirty swap_total '
18
+ 'swap_used mem_pct swap_pct disk_read_bps disk_write_bps max_disk_pct max_disk_util net_rx_bps net_tx_bps max_temp')
19
+ LISTS = 'cores mounts disks nets procs services temps gpus'
20
+ def __init__(self, timestamp=0):
21
+ self.valid, self.timestamp, self.tcp = False, timestamp, {} # tcp: state name -> connections
22
+ for names, value in ((self.TEXTS, ''), (self.NUMBERS, 0)):
23
+ for k in names.split(): setattr(self, k, value)
24
+ for k in self.LISTS.split(): setattr(self, k, [])
25
+ def gpu_max(self, temp=False): return max((g.temp if temp else g.util for g in self.gpus), default=0)
26
+
27
+ def num(s):
28
+ """Number from text; 0 when missing or malformed."""
29
+ try: return float(s)
30
+ except (TypeError, ValueError): return 0.0
31
+
32
+ def to_int(s, base=10):
33
+ try: return int(str(s).strip(), base)
34
+ except ValueError: return 0
35
+
36
+ def sections(frame):
37
+ """Splits a collector frame into {section name: lines}."""
38
+ sec, cur = {}, None
39
+ for line in frame.replace('\r', '').split('\n'):
40
+ if line.startswith('@@S '): cur = sec.setdefault(line[4:].strip(), [])
41
+ elif cur is not None and not line.startswith('@@'): cur.append(line)
42
+ return sec
43
+
44
+ def rates(state, dt):
45
+ """Returns delta(key, counters) -> per-second rates against the previous frame; remembers the new counters."""
46
+ prev, state['counters'] = state.get('counters', {}), {}
47
+
48
+ def delta(key, v):
49
+ p = prev.get(key, ())
50
+ state['counters'][key] = v
51
+ return [max(0.0, (a - b) / dt) for a, b in zip(v, p)] if dt > 0.05 and len(p) == len(v) else [0.0] * len(v)
52
+ return delta
53
+
54
+ def add_disk(m, d, physical=True):
55
+ """Lists a disk; physical ones count towards the totals and the busiest-disk figure."""
56
+ m.disks.append(d)
57
+ if physical:
58
+ m.disk_read_bps += d.read_bps
59
+ m.disk_write_bps += d.write_bps
60
+ if d.util >= m.max_disk_util: m.max_disk_util, m.busiest_disk = d.util, d.name
61
+
62
+ def add_mount(m, mt):
63
+ m.mounts.append(mt)
64
+ if mt.pct >= m.max_disk_pct: m.max_disk_pct, m.fullest_mount = mt.pct, mt.mount
65
+
66
+ def finish(m, sec, state, temp_unit):
67
+ """What every platform shares: percentages, totals, sensors (value / temp_unit = Celsius), cached GPUs and services, ordering."""
68
+ m.mem_pct = m.mem_used * 100 / m.mem_total if m.mem_total > 0 else 0
69
+ m.swap_pct = m.swap_used * 100 / m.swap_total if m.swap_total > 0 else 0
70
+ m.net_rx_bps, m.net_tx_bps = (sum(getattr(n, k) for n in m.nets if not n.virt) for k in ('rx_bps', 'tx_bps'))
71
+ m.threads_total = sum(p.threads for p in m.procs)
72
+ if 'gpu' in sec: # nvidia-smi CSV; like the services it arrives every few samples: keep the last list
73
+ state['gpus'] = [Gpu(int(num(f[0])), f[1].strip(), *map(num, f[2:8])) for f in (l.split(',') for l in sec['gpu']) if len(f) >= 8]
74
+ m.gpus, m.services = state.get('gpus', []), state.get('services', [])
75
+ m.services_failed = sum(s.active == 'failed' for s in m.services)
76
+ m.services_running = sum(s.sub == 'running' for s in m.services)
77
+ for line in sec.get('thermal', ()):
78
+ name, _, value = line.rpartition('|')
79
+ t = Temp(name.strip(), num(value) / temp_unit)
80
+ if name and 0 < t.celsius <= 150 and all(t.name != x.name for x in m.temps): m.temps.append(t)
81
+ m.max_temp = max((t.celsius for t in m.temps), default=0)
82
+ m.nets.sort(key=lambda n: (n.virt, n.name))
83
+ m.procs.sort(key=lambda p: (-p.cpu, -p.rss))
84
+ return m
Server Monitor(python-linux)/model.py ADDED
@@ -0,0 +1,117 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Server configuration, alert rules, autopilot policy and text formatting."""
2
+ import base64, binascii, math, uuid
3
+ from dataclasses import asdict, dataclass, field, fields
4
+
5
+ import plat
6
+ from metrics import to_int
7
+
8
+ # ---- formatting -------------------------------------------------------------
9
+ def fmt_bytes(b, prec=1):
10
+ i = 0
11
+ while abs(b) >= 1024 and i < 5: b, i = b / 1024, i + 1
12
+ return f'{b:.{prec if i else 0}f} ' + 'B KB MB GB TB PB'.split()[i]
13
+
14
+ def rate(b): return fmt_bytes(b) + '/s'
15
+ def pct(p, prec=1): return f'{p:.{prec}f}%'
16
+ def temp(c): return f'{c:.0f} °C'
17
+
18
+ def count(v):
19
+ a = abs(v)
20
+ return f'{v / 1e9:.1f}G' if a >= 1e9 else f'{v / 1e6:.1f}M' if a >= 1e6 else f'{v / 1e3:.1f}K' if a >= 1e4 else f'{v:.0f}'
21
+
22
+ def duration(sec):
23
+ s = int(sec)
24
+ d, h, m = s // 86400, s % 86400 // 3600, s % 3600 // 60
25
+ return f'{d}d {h}h {m}m' if d else f'{h}h {m}m' if h else f'{m}m {s % 60}s' if m else f'{s}s'
26
+
27
+ def rnd(x):
28
+ """Rounds half up (Python's round() rounds half to even)."""
29
+ return math.floor(x + 0.5)
30
+
31
+ def command(template, q='', n=None):
32
+ """Fills a platform command template: {q} = quoted argument, {n} = integer argument (default: q as a number)."""
33
+ return template.replace('{q}', plat.quote(str(q))).replace('{n}', str(to_int(q if n is None else n)))
34
+
35
+ # ---- catalogues: (key, label, unit) and (key, label, argument hint) ------------
36
+ RULE_METRICS = [d for d in (
37
+ ('cpu', 'CPU usage', '%'), ('iowait', 'CPU I/O wait', '%'), ('load', 'Load (1 min) per core', '%'), ('mem', 'Memory usage', '%'),
38
+ ('swap', 'Swap usage', '%'), ('disk', 'Fullest disk usage', '%'), ('diskio', 'Busiest disk utilisation', '%'),
39
+ ('temp', 'Hottest sensor', '°C'), ('rx', 'Network download', 'MB/s'), ('tx', 'Network upload', 'MB/s'), ('failed', 'Failed services', ''),
40
+ ('procs', 'Process count', ''), ('gpu', 'GPU usage (max)', '%'), ('gputemp', 'GPU temperature (max)', '°C')) if plat.POSIX_CPU or d[0] != 'iowait']
41
+ RULE_ACTIONS = [(k, text, plat.HINTS.get(k, '')) for k, text in (
42
+ ('notify', 'Notify only'), ('restart_failed', 'Restart failed services'), ('restart_service', 'Restart a service'),
43
+ ('kill_top_cpu', 'Terminate top CPU process'), ('kill_top_mem', 'Terminate top memory process'),
44
+ ('drop_caches', 'Sync + drop page cache'), ('command', 'Run a command')) if k != 'drop_caches' or k in plat.CMD]
45
+
46
+ def catalogue(defs, key, col=1):
47
+ """Label (col 1) or unit / hint (col 2) of a rule metric or action."""
48
+ return next((d[col] for d in defs if d[0] == key), key if col == 1 else '')
49
+
50
+ # ---- configuration (field names = servers.json keys) ---------------------------
51
+ @dataclass
52
+ class Rule:
53
+ """When <metric> <op> <value> for <duration> s -> <action>(<arg>), again after <cooldown> s."""
54
+ id: str = ''; metric: str = 'cpu'; op: str = '>'; action: str = 'notify'; arg: str = ''; severity: str = 'warning'
55
+ enabled: bool = True; value: float = 90.0; duration: int = 60; cooldown: int = 300
56
+ def condition(self):
57
+ unit = catalogue(RULE_METRICS, self.metric, 2)
58
+ return (f'{catalogue(RULE_METRICS, self.metric)} {self.op} {self.value:g}' + (f' {unit}' if unit else '')
59
+ + (f' for {self.duration} s' if self.duration else ''))
60
+ def action_text(self): return catalogue(RULE_ACTIONS, self.action) + (f': {self.arg}' if self.arg else '')
61
+
62
+ @dataclass
63
+ class AutopilotConfig:
64
+ """History-driven automatic control (evaluated by the analyzer every minute)."""
65
+ enabled: bool = True; dryRun: bool = False; restartFailed: bool = True; diskCleanup: bool = False; anomalyAlerts: bool = True
66
+ maxRestartsPerHour: int = 3; runawayMinutes: int = 10; diskForecastDays: int = 3
67
+ runawayCpu: float = 90.0; diskCleanupAt: float = 92.0; leakMemPressure: float = 90.0; anomalyZ: float = 3.0
68
+ runawayMode: str = 'renice'; leakMode: str = 'notify' # none|renice|terminate, none|notify|terminate
69
+ diskCleanupCommand: str = plat.CLEANUP
70
+
71
+ def new_id(): return str(uuid.uuid4())[:12]
72
+
73
+ def default_rules():
74
+ return [Rule(new_id(), m, value=float(v), duration=d, severity=s) for m, v, d, s in (
75
+ ('cpu', 90, 60, 'warning'), ('mem', 90, 60, 'warning'), ('swap', 80, 120, 'warning'), ('disk', 90, 0, 'critical'),
76
+ ('temp', 85, 30, 'critical'), ('load', 150, 120, 'warning'), ('failed', 0, 0, 'warning'))]
77
+
78
+ def load(cls, o):
79
+ """Dataclass from a JSON object: known scalar fields only, converted to the declared type."""
80
+ c = cls()
81
+ for f in fields(cls):
82
+ if f.type in (str, int, float, bool) and o.get(f.name) is not None:
83
+ try: setattr(c, f.name, f.type(o[f.name]))
84
+ except (TypeError, ValueError): pass
85
+ return c
86
+
87
+ def xor_b64(s, encode):
88
+ """Light obfuscation of saved passwords (NOT encryption)."""
89
+ key = b'ServerMonitor/obfuscation/v1'
90
+ try: b = s.encode() if encode else base64.b64decode(s)
91
+ except binascii.Error: return ''
92
+ b = bytes(x ^ key[i % len(key)] for i, x in enumerate(b))
93
+ return base64.b64encode(b).decode() if encode else b.decode('utf-8', 'replace')
94
+
95
+ @dataclass
96
+ class ServerConfig:
97
+ id: str = ''; name: str = ''; group: str = ''; host: str = ''; user: str = ''; keyFile: str = ''; password: str = ''; notes: str = ''
98
+ transport: int = 1; port: int = 22; interval: int = plat.INTERVAL; useSudo: bool = False; enabled: bool = True # transport: 0 Local, 1 SSH
99
+ rules: list = field(default_factory=default_rules)
100
+ autopilot: AutopilotConfig = field(default_factory=AutopilotConfig)
101
+ def address(self):
102
+ if not self.transport: return 'this machine'
103
+ return (f'{self.user}@' if self.user else '') + self.host + (f':{self.port}' if self.port != 22 else '')
104
+ def to_json(self): return {**asdict(self), 'password': xor_b64(self.password, True)}
105
+ @classmethod
106
+ def from_json(cls, o):
107
+ c = load(cls, o)
108
+ c.autopilot = load(AutopilotConfig, o.get('autopilot', {}))
109
+ if 'rules' in o: c.rules = [load(Rule, r) for r in o['rules']]
110
+ for r in c.rules: r.id = r.id or new_id()
111
+ c.transport = 0 if o.get('transport', 1) == 0 else 1
112
+ c.password = xor_b64(o.get('password', ''), False)
113
+ c.interval = min(max(c.interval, 1), 300)
114
+ c.id = c.id or new_id()
115
+ return c
116
+
117
+ TRANSPORTS = ('Local', 'SSH')
Server Monitor(python-linux)/plat.py ADDED
@@ -0,0 +1,295 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Platform module (Linux): everything OS-specific - collector script, process spawning, frame parser,
2
+ command tables and the texts that differ between the editions."""
3
+ import atexit, functools, os, re, signal, subprocess, tempfile
4
+
5
+ from metrics import Core, Disk, Metrics, Mount, Net, Proc, Service, add_disk, add_mount, finish, num, rates, sections, to_int
6
+
7
+ NAME, HAS_SUDO, POSIX_CPU, INTERVAL = 'Linux', True, True, 2 # POSIX_CPU: I/O wait and steal exist; INTERVAL: default sample seconds
8
+ SPAWN = {'start_new_session': True} # extra subprocess.Popen arguments: own process group, so that kill() reaches what the shell started
9
+
10
+ def config_dir(): return os.path.join(os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'ServerMonitorPy')
11
+ def open_folder(path): subprocess.Popen(['xdg-open', path])
12
+
13
+ def shell(interval=None):
14
+ """Command line that runs the script arriving on stdin (locally, or joined by spaces as the ssh remote command)."""
15
+ return ['sh', '-s'] + (['--', str(interval)] if interval else [])
16
+
17
+ def collector(interval):
18
+ """Stdin for the collector process (the interval travels on the command line)."""
19
+ return COLLECTOR
20
+
21
+ def kill(p):
22
+ """Ends a child process with everything it started (a shell's sleep or pipeline would keep its output pipe open)."""
23
+ try: p.poll() is None and os.killpg(p.pid, signal.SIGKILL)
24
+ except OSError: pass
25
+
26
+ def quote(s): return "'" + s.replace("'", "'\\''") + "'"
27
+
28
+ def wrap(cmd, privileged, sudo):
29
+ """Stdin for a one-shot command."""
30
+ return (f'sudo -n sh -c {quote(cmd)}' if privileged and sudo else cmd) + '\n'
31
+
32
+ @functools.lru_cache(None)
33
+ def askpass():
34
+ """Helper script that answers ssh's password prompt from $SERVERMONITOR_ASKPASS; removed on exit."""
35
+ fd, path = tempfile.mkstemp(prefix='servermonitor-askpass-', suffix='.sh')
36
+ os.write(fd, b'#!/bin/sh\nprintf \'%s\\n\' "$SERVERMONITOR_ASKPASS"\n')
37
+ os.close(fd)
38
+ os.chmod(path, 0o700)
39
+ atexit.register(os.remove, path)
40
+ return path
41
+
42
+ def protected(p):
43
+ """Processes that are never killed automatically and get no leak / runaway findings."""
44
+ return p.pid <= 2 or p.ppid == 2 or p.rss <= 0 or p.name in ('sshd', 'systemd')
45
+
46
+ def thrashing(iowait, mem, disk_busy):
47
+ """Rest of the sentence "Swap … used" when heavy swap use is thrashing ('' = it is not); iowait and disk_busy are 15-minute averages."""
48
+ return f' and CPU waits on I/O {iowait:.1f}% of the time' if iowait > 20 else ''
49
+
50
+ def priority_level(nice):
51
+ """How the priority column value compares with normal: > 0 raised, < 0 lowered."""
52
+ return -nice
53
+
54
+ def cpu_tile(m):
55
+ """(value, sub text, warn) of the CPU tab tile TEXT['cpu_tile']."""
56
+ return f'{m.cpu_steal:.1f}% / {m.cpu_irq:.1f}%', 'steal > 5% = noisy neighbours', m.cpu_steal > 5
57
+
58
+ # ---- command tables: {q} = quoted argument, {n} = integer argument ---------------------------
59
+ CMD = {
60
+ 'kill_pid': 'kill -TERM {n}', 'renice': 'renice -n 19 -p {n}', 'drop_caches': 'sync && echo 3 > /proc/sys/vm/drop_caches',
61
+ 'restart_service': 'systemctl reset-failed {q} 2>/dev/null; systemctl restart {q}',
62
+ 'restart_failed': "for u in $(systemctl list-units --type=service --state=failed --no-legend --plain | awk '{print $1}'); "
63
+ "do echo restart $u; systemctl restart $u; done"}
64
+ CLEANUP = ('journalctl --vacuum-time=7d 2>/dev/null; apt-get clean 2>/dev/null; dnf clean all 2>/dev/null; '
65
+ 'find /tmp /var/tmp -xdev -type f -atime +7 -delete 2>/dev/null; true')
66
+ HINTS = {'restart_service': 'nginx.service', 'command': 'find /tmp -mtime +7 -delete'} # rule-argument placeholders
67
+ POWER = {'Reboot': '(sleep 2; systemctl reboot) >/dev/null 2>&1 &', 'Shut down': '(sleep 2; systemctl poweroff) >/dev/null 2>&1 &'}
68
+ # (label, command, flags): b = toolbar button, c = ask first, d = dangerous
69
+ PROC_ACTIONS = [('Terminate', 'kill -TERM {n}', 'bc'), ('Kill', 'kill -KILL {n}', 'bcd'), ('Hang up', 'kill -HUP {n}', 'c'),
70
+ ('Suspend', 'kill -STOP {n}', 'bc'), ('Resume', 'kill -CONT {n}', 'b')]
71
+ PRIORITIES = {'-20 (highest)': -20, '-10': -10, '0 (normal)': 0, '10': 10, '19 (lowest)': 19}
72
+ PRIORITY_CMD = 'renice -n {v} -p {n}'
73
+ SERVICE_VERBS = {v: f'systemctl {v} {{q}}' for v in ('start', 'stop', 'restart', 'reload', 'enable', 'disable')}
74
+ SERVICE_LOGS = "systemctl status --no-pager -l {q} 2>&1 | head -n 15; echo; echo '==== journal ===='; journalctl -u {q} -n {n} --no-pager 2>&1"
75
+ QUICK = [ # console: quick diagnostics
76
+ ('Disk usage', 'df -hT -x tmpfs -x devtmpfs -x squashfs -x overlay'),
77
+ ('Largest dirs in /var', 'du -xh --max-depth=2 /var 2>/dev/null | sort -rh | head -n 20'),
78
+ ('Memory', 'free -h; echo; vmstat 1 3'),
79
+ ('Top CPU processes', 'ps -eo pid,user,pcpu,pmem,rss,etime,comm --sort=-pcpu | head -n 20'),
80
+ ('Listening ports', 'ss -tulpn 2>/dev/null || netstat -tulpn'),
81
+ ('Kernel messages', 'dmesg -T 2>/dev/null | tail -n 40 || journalctl -k -n 40 --no-pager'),
82
+ ('Errors in journal', 'journalctl -p err -n 60 --no-pager'),
83
+ ('Failed services', 'systemctl --failed --no-pager'),
84
+ ('Logged-in users', 'w'),
85
+ ('Last reboots', 'last -x reboot shutdown 2>/dev/null | head -n 15')]
86
+ ACTIONS = [ # console: system actions (confirmed, privileged); the POWER ones are shown as dangerous
87
+ ('Sync + drop page cache', CMD['drop_caches'] + ' && echo done'),
88
+ ('Vacuum journal to 200 MB', 'journalctl --vacuum-size=200M'),
89
+ ('Clean package cache', '(apt-get clean || dnf clean all || yum clean all) 2>&1'),
90
+ ('Restart failed services', CMD['restart_failed'] + '; echo done'),
91
+ ('Reboot', POWER['Reboot'] + " echo 'reboot scheduled'"),
92
+ ('Shut down', POWER['Shut down'] + " echo 'shutdown scheduled'")]
93
+ TEXT = {
94
+ 'cpu_tile': 'Steal / IRQ', 'priority': 'Nice', 'kernel': 'Linux ',
95
+ 'renice': 'Renice to 19', 'renice_mode': 'Lower priority (renice 19)', 'renice_advice': 'Lower its priority (renice) or stop it if it is stuck.',
96
+ 'ssh_hint': 'Uses your system ssh client; nothing is installed on the server. Set up key login once with: ssh-copy-id user@host',
97
+ 'key_hint': 'default keys / ssh-agent (~/.ssh/id_*)', 'sudo': 'Run control commands with sudo -n (needs passwordless sudo)',
98
+ 'console_hint': 'Type a shell command and press Enter (↑/↓ history)',
99
+ 'privileged_tip': "Wrap in sudo -n when the server has 'Run control commands with sudo' enabled"}
100
+
101
+ # ---- collector frame parser -------------------------------------------------------------------
102
+ VIRTUAL_IF = re.compile(r'lo|veth|docker|br-|virbr|cni|flannel|cali|vxlan|kube|tun|tap')
103
+ WHOLE_DISK = re.compile(r'(sd[a-z]+|vd[a-z]+|xvd[a-z]+|hd[a-z]+|nvme\d+n\d+|mmcblk\d+|md\d+)$')
104
+ TCP_STATES = ['', 'ESTABLISHED', 'SYN_SENT', 'SYN_RECV', 'FIN_WAIT1', 'FIN_WAIT2', 'TIME_WAIT', 'CLOSE', 'CLOSE_WAIT', 'LAST_ACK', 'LISTEN', 'CLOSING']
105
+ SKIP_FS = {'tmpfs', 'devtmpfs', 'squashfs', 'overlay', 'efivarfs', 'ramfs', 'proc', 'sysfs', 'autofs', 'nsfs', 'devfs', 'cgroup', 'cgroup2',
106
+ 'fuse.snapfuse', 'fuse.portal'}
107
+
108
+ def parse(frame, st, now):
109
+ """Collector frame -> Metrics; st keeps the counters of the previous frame (rates) and the slow sections."""
110
+ sec, m = sections(frame), Metrics(now)
111
+
112
+ def rows(name): # non-empty lines of a section, split into fields
113
+ return [f for f in map(str.split, sec.get(name, ())) if f]
114
+
115
+ def first(name): return (rows(name) or [['']])[0]
116
+
117
+ info = st.setdefault('info', {})
118
+ for line in sec.get('info', ()):
119
+ k, eq, v = line.partition('=')
120
+ if eq and k: info[k] = v.strip()
121
+ if 'passwd' in sec: st['users'] = {to_int(uid): name for name, _, uid in (l.rpartition(':') for l in sec['passwd']) if name}
122
+ m.hostname, m.os, m.kernel, m.arch, m.cpu_model, m.virt = (info.get(k, '') for k in ('hostname', 'os', 'kernel', 'arch', 'cpumodel', 'virt'))
123
+ clk, page = max(1, to_int(info.get('clk', 100))), max(512, to_int(info.get('page', 4096)))
124
+ m.load1, m.load5, m.load15 = (num(x) for x in (first('loadavg') + [''] * 3)[:3])
125
+ m.uptime = num(first('uptime')[0])
126
+ if m.uptime <= 0: return m
127
+ dt = m.uptime - st['uptime'] if st.get('uptime', 0) > 0 else 0
128
+ live, delta = dt > 0.05, rates(st, dt)
129
+
130
+ # CPU
131
+ cpu, counters = [], [0.0] * 3
132
+ for f in rows('stat'):
133
+ v = num(f[1]) if len(f) > 1 else 0.0
134
+ if f[0].startswith('cpu'): cpu.append([num(x) for x in (f[1:9] + [''] * 8)[:8]])
135
+ elif f[0] in ('ctxt', 'intr', 'processes'): counters[('ctxt', 'intr', 'processes').index(f[0])] = v
136
+ elif f[0] == 'procs_running': m.procs_running = int(v)
137
+ elif f[0] == 'procs_blocked': m.procs_blocked = int(v)
138
+ m.cpu_count = max(1, len(cpu) - 1)
139
+ usage, mhz, jiffies, old = [0.0] * m.cpu_count, [0.0] * m.cpu_count, 0, st.get('cpu', [])
140
+ for i, (new, was) in enumerate(zip(cpu, old) if live and len(cpu) == len(old) else ()):
141
+ d = [a - b for a, b in zip(new, was)]
142
+ total = sum(d)
143
+ if total <= 0: continue
144
+ p = [min(max(x * 100 / total, 0), 100) for x in d] # user nice system idle iowait irq softirq steal
145
+ use = min(max(100 - p[3] - p[4], 0), 100)
146
+ if i:
147
+ usage[i - 1] = use
148
+ else:
149
+ jiffies, m.cpu_usage, m.cpu_user, m.cpu_system, m.cpu_iowait, m.cpu_irq, m.cpu_steal = total, use, p[0] + p[1], p[2], p[4], p[5] + p[6], p[7]
150
+ st['cpu'] = cpu
151
+ m.ctxt_per_sec, m.intr_per_sec, m.forks_per_sec = delta('stat', counters)
152
+ freqs = [(to_int(f[0]), num(f[1]) / 1000) for f in rows('freq') if len(f) > 1 and 0 <= to_int(f[0]) < m.cpu_count]
153
+ for i, v in freqs: mhz[i] = v
154
+ m.avg_mhz = sum(v for _, v in freqs) / len(freqs) if freqs else 0
155
+ m.cores = [Core(*c) for c in zip(usage, mhz)]
156
+
157
+ # memory
158
+ mi = {k: num((v.split() or [''])[0]) * 1024 for k, _, v in (l.partition(':') for l in sec.get('meminfo', ())) if v}
159
+ m.mem_total, m.mem_free, m.buffers, m.cached = (mi.get(k, 0.0) for k in ('MemTotal', 'MemFree', 'Buffers', 'Cached'))
160
+ m.cached += mi.get('SReclaimable', 0.0)
161
+ m.mem_available = mi.get('MemAvailable', m.mem_free + m.buffers + m.cached)
162
+ m.shared, m.slab, m.dirty, m.swap_total = (mi.get(k, 0.0) for k in ('Shmem', 'Slab', 'Dirty', 'SwapTotal'))
163
+ m.mem_used, m.swap_used = max(0.0, m.mem_total - m.mem_available), max(0.0, m.swap_total - mi.get('SwapFree', 0.0))
164
+
165
+ # network
166
+ state = {f[0]: f for f in rows('netstate')}
167
+ for line in sec.get('netdev', ()):
168
+ name, _, rest = line.partition(':')
169
+ name, f = name.strip(), [num(x) for x in rest.split()]
170
+ if not name or len(f) < 16: continue
171
+ s = state.get(name, [])
172
+ m.nets.append(Net(name, s[1] if len(s) > 1 else 'unknown', to_int(s[2]) if len(s) > 2 else -1, bool(VIRTUAL_IF.match(name)),
173
+ *delta('net:' + name, [f[0], f[8], f[1], f[9]]), f[0], f[8], f[2] + f[10], f[3] + f[11]))
174
+ for f in rows('tcp'):
175
+ i = to_int(f[0], 16)
176
+ name = TCP_STATES[i] if i < len(TCP_STATES) else '?'
177
+ m.tcp[name] = m.tcp.get(name, 0) + to_int(f[-1] if len(f) > 1 else 0)
178
+ for f in rows('sockstat'):
179
+ if f[0] == 'sockets:' and len(f) > 2: m.sockets_used = to_int(f[2])
180
+
181
+ # disks: whole devices + device-mapper; totals over physical disks only
182
+ for f in rows('diskstats'):
183
+ whole = bool(WHOLE_DISK.match(f[2])) if len(f) >= 14 else False
184
+ if len(f) < 14 or not (whole or f[2].startswith('dm-')): continue
185
+ read, written = num(f[5]) * 512, num(f[9]) * 512
186
+ r = delta('disk:' + f[2], [num(f[3]), read, num(f[7]), written, num(f[12])])
187
+ add_disk(m, Disk(f[2], r[1], r[3], r[0], r[2], min(100.0, r[4] / 10), read, written), whole and not f[2].startswith('md'))
188
+ df, seen = sec.get('df', []), set()
189
+ b = int(bool(df) and 'Type' in df[0]) # 1 when df printed the file system type
190
+ for f in map(str.split, df[1:]):
191
+ if len(f) < 6 + b: continue
192
+ device, fs, mount = f[0], f[1] if b else '', ' '.join(f[5 + b:])
193
+ total, used, avail = (num(x) * 1024 for x in f[1 + b:4 + b])
194
+ if (fs if b else device) in SKIP_FS or total <= 0 or mount.startswith('/snap/') or (device.startswith('/') and (device, total) in seen):
195
+ continue
196
+ seen.add((device, total))
197
+ add_mount(m, Mount(device, fs, mount, total, used, avail, used * 100 / (used + avail) if used + avail > 0 else 0))
198
+
199
+ # processes: "pid state ppid ticks nice threads start vsize rss comm..."
200
+ uid = {to_int(f[0]): to_int(f[1]) for f in rows('uids') if len(f) > 1}
201
+ users, old, ticks = st.get('users', {}), st.get('ticks', {}), {}
202
+ per_core = jiffies / m.cpu_count if jiffies > 0 else dt * clk if live else 0
203
+ for line in sec.get('procs', ()):
204
+ f = line.split(' ', 9)
205
+ pid = to_int(f[0])
206
+ if len(f) < 10 or pid <= 0: continue
207
+ ticks[pid], rss = num(f[3]), num(f[8]) * page
208
+ cpu = min(max((ticks[pid] - old[pid]) * 100 / per_core, 0), 100.0 * m.cpu_count) if per_core > 0 and pid in old else 0.0
209
+ m.procs.append(Proc(pid, to_int(f[2]), to_int(f[5]), to_int(f[4]), f[9], users.get(uid[pid], str(uid[pid])) if pid in uid else '?',
210
+ f[1][:1] or '?', cpu, rss * 100 / m.mem_total if m.mem_total > 0 else 0, rss, num(f[7]), max(0.0, m.uptime - num(f[6]) / clk)))
211
+
212
+ if 'services' in sec: st['services'] = [Service(*f[:4], ' '.join(f[4:])) for f in rows('services') if len(f) >= 4 and f[0].endswith('.service')]
213
+ m.logged_users = to_int(first('users')[0])
214
+ st['ticks'], st['uptime'] = ticks, m.uptime
215
+ m.valid = live # the first sample has no rates yet
216
+ return finish(m, sec, st, 1000)
217
+
218
+ COLLECTOR = r'''sm_main() {
219
+ iv="${1:-2}" once="${2:-0}" n=0
220
+ export LC_ALL=C
221
+ while :; do
222
+ echo "@@SNAP_BEGIN"
223
+ if [ $((n % 15)) -eq 0 ]; then
224
+ echo "@@S info"
225
+ echo "hostname=$(cat /proc/sys/kernel/hostname 2>/dev/null)"
226
+ echo "kernel=$(uname -r 2>/dev/null)"
227
+ echo "arch=$(uname -m 2>/dev/null)"
228
+ echo "os=$(sed -n 's/^PRETTY_NAME=//p' /etc/os-release 2>/dev/null | tr -d '"')"
229
+ echo "cpumodel=$(grep -m1 -E '^(model name|Hardware|Processor|cpu model)' /proc/cpuinfo 2>/dev/null | cut -d: -f2- | sed 's/^ *//')"
230
+ echo "clk=$(getconf CLK_TCK 2>/dev/null || echo 100)"
231
+ echo "page=$(getconf PAGESIZE 2>/dev/null || echo 4096)"
232
+ echo "virt=$(systemd-detect-virt 2>/dev/null || echo unknown)"
233
+ echo "@@S passwd"; cut -d: -f1,3 /etc/passwd 2>/dev/null
234
+ fi
235
+ echo "@@S uptime"; cat /proc/uptime
236
+ echo "@@S loadavg"; cat /proc/loadavg
237
+ echo "@@S stat"
238
+ grep -E '^(cpu|ctxt|processes|procs_)' /proc/stat
239
+ awk '/^intr/ {print "intr", $2}' /proc/stat
240
+ echo "@@S meminfo"; cat /proc/meminfo
241
+ echo "@@S netdev"; cat /proc/net/dev
242
+ echo "@@S netstate"
243
+ for i in /sys/class/net/*; do
244
+ [ -e "$i" ] || continue
245
+ echo "${i##*/} $(cat "$i/operstate" 2>/dev/null || echo unknown) $(cat "$i/speed" 2>/dev/null || echo -1)"
246
+ done
247
+ echo "@@S diskstats"; cat /proc/diskstats
248
+ echo "@@S df"; df -P -T -k 2>/dev/null || df -P -k 2>/dev/null
249
+ echo "@@S sockstat"; cat /proc/net/sockstat 2>/dev/null
250
+ echo "@@S tcp"
251
+ cat /proc/net/tcp /proc/net/tcp6 2>/dev/null | awk '$4 ~ /^[0-9A-F][0-9A-F]$/ {c[$4]++} END {for (k in c) print k, c[k]}'
252
+ echo "@@S thermal"
253
+ for z in /sys/class/thermal/thermal_zone*; do
254
+ [ -r "$z/temp" ] && echo "$(cat "$z/type" 2>/dev/null)|$(cat "$z/temp" 2>/dev/null)"
255
+ done
256
+ for h in /sys/class/hwmon/hwmon*; do
257
+ [ -d "$h" ] || continue
258
+ hn=$(cat "$h/name" 2>/dev/null)
259
+ for t in "$h"/temp*_input; do
260
+ [ -r "$t" ] || continue
261
+ l=$(cat "${t%_input}_label" 2>/dev/null)
262
+ echo "$hn ${l:-${t##*/}}|$(cat "$t" 2>/dev/null)"
263
+ done
264
+ done
265
+ echo "@@S freq"
266
+ for c in /sys/devices/system/cpu/cpu[0-9]*; do
267
+ f=$(cat "$c/cpufreq/scaling_cur_freq" 2>/dev/null) && echo "${c##*/cpu} $f"
268
+ done
269
+ echo "@@S procs"
270
+ cat /proc/[0-9]*/stat 2>/dev/null | awk '{
271
+ if (!match($0, /\(.*\)/)) next
272
+ comm = substr($0, RSTART + 1, RLENGTH - 2)
273
+ rest = substr($0, RSTART + RLENGTH + 1)
274
+ k = split(rest, r, " ")
275
+ if (k < 22) next
276
+ print $1, r[1], r[2], r[12] + r[13], r[17], r[18], r[20], r[21], r[22], comm
277
+ }'
278
+ echo "@@S uids"; ls -ln /proc 2>/dev/null | awk '$NF ~ /^[0-9]+$/ {print $NF, $3}'
279
+ if [ $((n % 5)) -eq 0 ]; then
280
+ echo "@@S services"
281
+ systemctl list-units --type=service --all --no-legend --no-pager --plain 2>/dev/null | head -n 600
282
+ fi
283
+ if [ $((n % 3)) -eq 0 ] && command -v nvidia-smi >/dev/null 2>&1; then
284
+ echo "@@S gpu"
285
+ nvidia-smi --query-gpu=index,name,utilization.gpu,memory.used,memory.total,temperature.gpu,power.draw,fan.speed --format=csv,noheader,nounits 2>/dev/null
286
+ fi
287
+ echo "@@S users"; who 2>/dev/null | wc -l
288
+ echo "@@SNAP_END" || exit 0
289
+ [ "$once" = "once" ] && break
290
+ n=$((n + 1))
291
+ sleep "$iv"
292
+ done
293
+ }
294
+ sm_main "$@"
295
+ '''
Server Monitor(python-linux)/run.sh ADDED
@@ -0,0 +1,3 @@
 
 
 
 
1
+ #!/bin/sh
2
+ # Start Server Monitor (needs Python 3.8+ with tkinter).
3
+ exec python3 "$(dirname "$0")/main.py" "$@"
Server Monitor(python-linux)/session.py ADDED
@@ -0,0 +1,411 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Connection to one machine (local shell or system ssh), the per-server session
2
+ (metrics, live history, rules, autopilot) and the manager of all sessions."""
3
+ import json, os, queue, shutil, subprocess, threading, time
4
+ from collections import namedtuple
5
+ from datetime import datetime
6
+ from types import SimpleNamespace
7
+
8
+ import plat
9
+ from history import Analysis, ProcTrend, ServiceTrend, Store, analyze
10
+ from metrics import Metrics
11
+ from model import RULE_METRICS, ServerConfig, catalogue, command, new_id
12
+
13
+ PIPE = subprocess.PIPE
14
+ SSH_OPTIONS = ['ConnectTimeout=10', 'ServerAliveInterval=10', 'ServerAliveCountMax=3', 'StrictHostKeyChecking=accept-new', 'LogLevel=ERROR']
15
+ STATUS = ('Disabled', 'Connecting', 'Online', 'Offline')
16
+ DISABLED, CONNECTING, ONLINE, OFFLINE = range(4)
17
+ AlertEvent = namedtuple('AlertEvent', 'time server severity message') # severity: info|warning|critical|resolved|action
18
+
19
+ # ---- UI-thread dispatch -----------------------------------------------------------------
20
+ class Loop:
21
+ """Hands work to the UI thread: worker threads post() calls, timers are due in pump(), which the UI calls often."""
22
+ def __init__(self): self.calls, self.timers = queue.SimpleQueue(), set()
23
+ def post(self, fn, *args): self.calls.put((fn, args))
24
+ def pump(self):
25
+ while not self.calls.empty():
26
+ fn, args = self.calls.get()
27
+ fn(*args)
28
+ now = time.monotonic()
29
+ for t in [t for t in self.timers if t.due <= now]:
30
+ if t in self.timers: # not stopped by a call that ran just before
31
+ t.start() if t.every else t.stop()
32
+ t.fn()
33
+
34
+ loop = Loop()
35
+
36
+ class Timer:
37
+ """Restartable timer on the loop; with every (seconds) it repeats."""
38
+ def __init__(self, fn, every=0):
39
+ self.fn, self.every = fn, every
40
+ if every: self.start()
41
+ def start(self, seconds=None):
42
+ self.due = time.monotonic() + (seconds or self.every)
43
+ loop.timers.add(self)
44
+ def stop(self): loop.timers.discard(self)
45
+
46
+ class Signal(list):
47
+ """List of listeners; calling it calls them all."""
48
+ def __call__(self, *args):
49
+ for fn in list(self): fn(*args)
50
+
51
+ # ---- Link ---------------------------------------------------------------------------------
52
+ class Link:
53
+ """Streams collector frames and runs one-shot commands on one machine. close() kills everything."""
54
+ def __init__(self, cfg, on_frame, on_lost):
55
+ self.cfg, self.on_frame, self.on_lost, self.procs, self.pending, self.closed = cfg, on_frame, on_lost, set(), {}, False
56
+ def spawn(self, interval=None, **kw):
57
+ c, argv, env = self.cfg, plat.shell(interval), None
58
+ if c.transport:
59
+ options = SSH_OPTIONS + (['NumberOfPasswordPrompts=1'] if c.password else ['BatchMode=yes'])
60
+ if c.password: # a helper script answers ssh's password prompt
61
+ env = {'DISPLAY': ':0', **os.environ, 'SSH_ASKPASS': plat.askpass(), 'SSH_ASKPASS_REQUIRE': 'force', 'SERVERMONITOR_ASKPASS': c.password}
62
+ argv = ['ssh', *(x for o in options for x in ('-o', o)), *(['-i', os.path.expanduser(c.keyFile)] if c.keyFile else []),
63
+ *(['-p', str(c.port)] if c.port != 22 else []), '-T', f'{c.user}@{c.host}' if c.user else c.host, ' '.join(argv)]
64
+ try: p = subprocess.Popen(argv, stdin=PIPE, stdout=PIPE, env=env, **plat.SPAWN, **kw)
65
+ except OSError as e: raise OSError(f'cannot start {argv[0]}: {e.strerror}') from e
66
+ self.procs.add(p)
67
+ return p
68
+ def post(self, fn, *args): # results reach the UI thread, unless the link was closed meanwhile
69
+ loop.post(lambda: self.closed or fn(*args))
70
+ def start(self):
71
+ try: p = self.spawn(self.cfg.interval, stderr=PIPE)
72
+ except OSError as e: return self.post(self.on_lost, str(e))
73
+ threading.Thread(target=self.stream, args=(p,), daemon=True).start()
74
+ def stream(self, p): # worker thread: frames out of stdout, the last error line out of stderr
75
+ buf, err = b'', [b'']
76
+
77
+ def errors():
78
+ for chunk in iter(lambda: p.stderr.read1(4096), b''): err[0] = (err[0] + chunk)[-4096:]
79
+
80
+ reader = threading.Thread(target=errors, daemon=True)
81
+ reader.start()
82
+ try:
83
+ p.stdin.write(plat.collector(self.cfg.interval).encode())
84
+ p.stdin.close()
85
+ for chunk in iter(lambda: p.stdout.read1(1 << 16), b''):
86
+ buf += chunk
87
+ while b'@@SNAP_END' in buf:
88
+ end = buf.find(b'@@SNAP_END')
89
+ begin = buf.rfind(b'@@SNAP_BEGIN', 0, end)
90
+ if begin >= 0 and loop.calls.qsize() < 100: # a stalled UI must not pile up frames
91
+ self.post(self.on_frame, buf[begin:end].decode('utf-8', 'replace'))
92
+ buf = buf[end + 10:]
93
+ if len(buf) > 8 << 20: buf = b''
94
+ except (OSError, ValueError):
95
+ pass # killed while writing or reading
96
+ code = p.wait()
97
+ reader.join(2)
98
+ lines = err[0].decode('utf-8', 'replace').split('\n')
99
+ self.post(self.on_lost, next((l.strip() for l in reversed(lines) if l.strip()), f'connection closed (exit code {code})'))
100
+ def exec(self, script, timeout, done=None):
101
+ """Runs a script; done(code, output) is called on the UI thread (code -1: killed, timed out or not started)."""
102
+ try: p = self.spawn(stderr=subprocess.STDOUT)
103
+ except OSError as e: return done and self.post(done, -1, str(e))
104
+ self.pending[p] = done
105
+
106
+ def work():
107
+ try:
108
+ out, code = p.communicate(script.encode(), timeout)[0], p.returncode
109
+ except subprocess.TimeoutExpired:
110
+ plat.kill(p)
111
+ try: out, code = p.communicate(timeout=2)[0], -1
112
+ except subprocess.TimeoutExpired: out, code = b'', -1 # something it started still holds the pipe
113
+ self.post(self.finished, p, -1 if code < 0 else code, out.decode('utf-8', 'replace') + ('\n[killed or timed out]' if code < 0 else ''))
114
+
115
+ threading.Thread(target=work, daemon=True).start()
116
+ def finished(self, p, code, out):
117
+ self.procs.discard(p)
118
+ done = self.pending.pop(p)
119
+ if done: done(code, out)
120
+ def close(self, reason='connection stopped'):
121
+ self.closed = True
122
+ for p in self.procs: plat.kill(p)
123
+ for done in self.pending.values():
124
+ if done: done(-1, reason)
125
+
126
+ # ---- live history -----------------------------------------------------------------------
127
+ class Live:
128
+ """The last hour of samples in memory, for the live charts."""
129
+ KEYS, CAP = 'cpu user sys iowait steal mem cache swap rx tx rd wr load'.split(), 1800
130
+ def __init__(self): self.t, self.s, self.if_rx, self.if_tx = [], {k: [] for k in self.KEYS}, {}, {}
131
+ def push(self, m):
132
+ n = len(self.t)
133
+
134
+ def add(v, x):
135
+ v[:0] = [0.0] * (n - len(v)) # align series that appeared later
136
+ v.append(x)
137
+ del v[:-self.CAP]
138
+
139
+ add(self.t, m.timestamp)
140
+ values = (m.cpu_usage, m.cpu_user, m.cpu_system + m.cpu_irq, m.cpu_iowait, m.cpu_steal, m.mem_pct,
141
+ (m.cached + m.buffers) * 100 / m.mem_total if m.mem_total > 0 else 0, m.swap_pct, m.net_rx_bps, m.net_tx_bps,
142
+ m.disk_read_bps, m.disk_write_bps, m.load1)
143
+ for k, x in zip(self.KEYS, values): add(self.s[k], x)
144
+ for i in m.nets:
145
+ add(self.if_rx.setdefault(i.name, []), i.rx_bps)
146
+ add(self.if_tx.setdefault(i.name, []), i.tx_bps)
147
+
148
+ # ---- session ----------------------------------------------------------------------------
149
+ class Session:
150
+ def __init__(self, cfg):
151
+ self.cfg, self.status, self.err, self.link, self.engine = cfg, DISABLED, '', None, {}
152
+ self.m, self.live, self.an = Metrics(), Live(), Analysis()
153
+ self.store = Store(os.path.join(Manager.config_dir(), 'history', cfg.id))
154
+ self.retries, self.paused, self.offline_alerted = 0, False, False
155
+ self.reported, self.dry, self.cooldown, self.rules, self.procs, self.svcs = set(), set(), {}, {}, {}, {} # analyzer / rule / tracking state
156
+ self.updated, self.analysis_updated, self.alert = Signal(), Signal(), Signal()
157
+ self.retry, self.watchdog, first = Timer(self.start), Timer(lambda: self.lost('no data received (timeout)')), Timer(self.analyze)
158
+ self.offline = Timer(self.down, cfg.interval) # downtime -> availability: one sample per interval, like uptime
159
+ self.timers = [self.retry, self.watchdog, first, self.offline, Timer(self.analyze, 60)]
160
+ first.start(3)
161
+ def online(self): return self.status == ONLINE and self.m.valid
162
+ def down(self):
163
+ if self.status == OFFLINE or (self.status == CONNECTING and self.retries): self.record(False)
164
+ def set_config(self, c):
165
+ old, self.cfg, self.offline.every = self.cfg, c, c.interval
166
+ if any(getattr(c, k) != getattr(old, k) for k in ('transport', 'host', 'port', 'user', 'keyFile', 'password', 'interval', 'enabled')):
167
+ self.live, self.m, self.procs, self.svcs = Live(), Metrics(), {}, {} # may be another machine now
168
+ self.start() if c.enabled else self.stop()
169
+ self.updated()
170
+ def set_paused(self, paused):
171
+ self.paused = paused
172
+ self.updated()
173
+ def reconnect(self):
174
+ self.retries, self.paused = 0, False
175
+ self.start()
176
+ def drop_link(self, reason):
177
+ self.retry.stop()
178
+ self.watchdog.stop()
179
+ link, self.link = self.link, None
180
+ if link: link.close(reason)
181
+ def start(self):
182
+ self.drop_link('connection restarted')
183
+ if not self.cfg.enabled: return self.set_status(DISABLED)
184
+ self.engine, self.m.valid = {}, False # online() only again with a fresh sample
185
+ self.link = Link(self.cfg, self.frame, self.lost)
186
+ self.set_status(CONNECTING)
187
+ self.watchdog.start(25)
188
+ self.link.start()
189
+ def stop(self):
190
+ self.drop_link('connection stopped')
191
+ self.set_status(OFFLINE if self.cfg.enabled else DISABLED)
192
+ def close(self):
193
+ self.stop()
194
+ for t in self.timers: t.stop()
195
+ def set_status(self, status, err=''):
196
+ if err or status == ONLINE: self.err = err
197
+ if status != self.status:
198
+ self.status = status
199
+ self.updated()
200
+ def frame(self, raw):
201
+ now = time.time() * 1000
202
+ self.watchdog.start(max(15, self.cfg.interval * 5 + 10))
203
+ m = plat.parse(raw, self.engine, now)
204
+ if m.uptime <= 0: return
205
+ if self.status != ONLINE:
206
+ self.retries = 0
207
+ if self.offline_alerted: self.raise_alert('resolved', 'Server is back online')
208
+ self.offline_alerted = False
209
+ self.set_status(ONLINE)
210
+ if not m.valid or self.paused: # the first sample has no rates yet
211
+ return
212
+ if m.uptime < self.m.uptime: self.procs = {} # rebooted: PIDs start again, old trends would be blamed on new processes
213
+ first, self.m = not self.m.valid, m
214
+ self.live.push(m)
215
+ self.record(True)
216
+ self.track(now)
217
+ self.evaluate_rules()
218
+ if first: self.analyze() # first sample of this connection: the last analysis saw "unreachable"
219
+ self.updated()
220
+ def lost(self, why):
221
+ was = self.status == ONLINE
222
+ self.drop_link('connection lost: ' + why)
223
+ self.set_status(OFFLINE, why)
224
+ if (was or self.retries == 1) and not self.offline_alerted:
225
+ self.raise_alert('critical', 'Server is unreachable: ' + why)
226
+ self.offline_alerted = True
227
+ if self.cfg.enabled:
228
+ self.retry.start((3, 5, 10, 20, 30, 60)[min(self.retries, 5)]) # back-off
229
+ self.retries += 1
230
+ def exec(self, cmd, privileged, done=None, timeout=60):
231
+ """Runs a command on the machine; privileged ones go through sudo when the server is set up for it."""
232
+ if self.link and self.status == ONLINE: self.link.exec(plat.wrap(cmd, privileged, self.cfg.useSudo), timeout, done)
233
+ elif done: loop.post(done, -1, 'server is not connected')
234
+ def metric_value(self, key):
235
+ m = self.m
236
+ return {'cpu': m.cpu_usage, 'iowait': m.cpu_iowait, 'load': m.load1 * 100 / max(1, m.cpu_count), 'mem': m.mem_pct, 'swap': m.swap_pct,
237
+ 'disk': m.max_disk_pct, 'diskio': m.max_disk_util, 'temp': m.max_temp, 'rx': m.net_rx_bps / 1e6, 'tx': m.net_tx_bps / 1e6,
238
+ 'failed': m.services_failed, 'procs': len(m.procs), 'gpu': m.gpu_max(), 'gputemp': m.gpu_max(True)}.get(key, 0)
239
+ def active_alerts(self):
240
+ down = ['Unreachable: ' + self.err] if self.status == OFFLINE else []
241
+ return down + [r.condition() for r in self.cfg.rules if r.id in self.rules and self.rules[r.id].active]
242
+ def raise_alert(self, severity, message): self.alert(AlertEvent(datetime.now(), self.cfg.name, severity, message))
243
+ def record(self, up):
244
+ m, nan = self.m, float('nan')
245
+ self.store.add(int(time.time()), (
246
+ m.cpu_usage, m.cpu_iowait, m.load1, m.mem_pct, m.swap_pct if m.swap_total > 0 else nan, m.max_disk_pct if m.mounts else nan,
247
+ m.max_disk_util, m.net_rx_bps, m.net_tx_bps, m.disk_read_bps, m.disk_write_bps, m.max_temp if m.temps else nan, len(m.procs),
248
+ m.gpu_max() if m.gpus else nan, m.services_failed), up)
249
+ def track(self, now):
250
+ """Per-process CPU streaks and RSS per minute; service failure transitions."""
251
+ procs = {}
252
+ for p in self.m.procs:
253
+ t = self.procs.get(p.pid)
254
+ if not t or t.name != p.name: # new, or the pid was reused
255
+ t = SimpleNamespace(name=p.name, high_since=0, last_minute=0, rss=[])
256
+ t.protected = plat.protected(p)
257
+ t.high_since = 0 if p.cpu < self.cfg.autopilot.runawayCpu else t.high_since or now
258
+ if now - t.last_minute >= 60000: t.last_minute, t.rss = now, t.rss[-59:] + [p.rss]
259
+ procs[p.pid] = t
260
+ self.procs, svcs = procs, {}
261
+ for s in self.m.services:
262
+ t, failed = self.svcs.get(s.unit) or SimpleNamespace(last='', preexisting=False, fails=[], restarts=[]), s.active == 'failed'
263
+ svcs[s.unit] = t
264
+ if not t.last:
265
+ t.preexisting = failed # failed before monitoring started: leave it alone
266
+ elif failed and t.last != 'failed':
267
+ t.fails.append(now)
268
+ t.preexisting = False
269
+ elif not failed:
270
+ t.preexisting = False
271
+ t.last = s.active
272
+ t.fails, t.restarts = ([x for x in v if now - x <= 3600000] for v in (t.fails, t.restarts))
273
+ if svcs: self.svcs = svcs # forgets removed services; a sample without a service list changes nothing
274
+ def evaluate_rules(self):
275
+ now, m = time.time() * 1000, self.m
276
+ for r in self.cfg.rules:
277
+ st = self.rules.setdefault(r.id, SimpleNamespace(since=0, last_fire=0, active=False))
278
+ v = self.metric_value(r.metric)
279
+ idle = not r.enabled or (r.metric in ('gpu', 'gputemp') and not m.gpus) or (r.metric == 'temp' and not m.temps)
280
+ if idle or (v >= r.value if r.op == '<' else v <= r.value):
281
+ if st.active and not idle: self.raise_alert('resolved', f'Recovered: {r.condition()} (now {v:.1f})')
282
+ del self.rules[r.id]
283
+ continue
284
+ st.since = st.since or now
285
+ if now - st.since < r.duration * 1000 or (st.active and (r.action == 'notify' or now - st.last_fire < r.cooldown * 1000)): continue
286
+ unit = catalogue(RULE_METRICS, r.metric, 2)
287
+ if not st.active: self.raise_alert(r.severity, f'{r.condition()} (now {v:.1f}' + (f' {unit}' if unit else '') + ')')
288
+ st.active, st.last_fire = True, now
289
+ action, arg = r.action, r.arg
290
+ if action.startswith('kill_top'): # heaviest process that is not protected
291
+ best = max((p for p in m.procs if not plat.protected(p)), key=lambda p: p.rss if action == 'kill_top_mem' else p.cpu, default=None)
292
+ action, arg = ('kill_pid', str(best.pid)) if best else ('notify', '')
293
+ if action != 'notify': self.run(action, arg, f'Automation "{r.condition()}": {r.action_text()}')
294
+ def run(self, action, arg, what, done=None):
295
+ cmds = {'command': arg, 'disk_cleanup': self.cfg.autopilot.diskCleanupCommand, **{k: command(v, arg) for k, v in plat.CMD.items()}}
296
+ if not cmds.get(action): return done and done(-1, 'nothing to do')
297
+
298
+ def report(code, out):
299
+ tail = ' '.join(out.split())[-300:] # one line: events are lines in alerts.log
300
+ self.raise_alert('action', f'{what} -> ' + (f'failed ({code})' if code else 'OK') + (f' | {tail}' if tail else ''))
301
+ if done: done(code, out)
302
+
303
+ self.exec(cmds[action], True, report, 300)
304
+ def run_finding(self, f, automatic, done=None):
305
+ if automatic and f.action == 'restart_service': self.svcs[f.arg].restarts.append(time.time() * 1000)
306
+ self.run(f.action, '' if f.action == 'disk_cleanup' else f.arg, ('Autopilot: ' if automatic else 'Manual fix: ') + f'{f.label} ({f.title})', done)
307
+ def analyze(self):
308
+ now, trends, ap = time.time() * 1000, [], self.cfg.autopilot
309
+ for p in self.m.procs:
310
+ t = self.procs.get(p.pid)
311
+ rss = t.rss if t else []
312
+ growth = rss[-1] - rss[0] if len(rss) >= 2 else 0
313
+ pt = ProcTrend(p.pid, len(rss), p.name, p.user, p.cpu, (now - t.high_since) / 60000 if t and t.high_since else 0, p.rss, growth,
314
+ growth * 100 / rss[0] if growth and rss[0] > 0 else 0,
315
+ sum(b > a for a, b in zip(rss, rss[1:])) / (len(rss) - 1) if len(rss) >= 2 else 0, bool(t and t.protected))
316
+ if pt.high_cpu_minutes > 0 or pt.minutes >= 30: trends.append(pt)
317
+ svcs = [ServiceTrend(unit, t.last == 'failed', t.preexisting, len(t.fails), len(t.restarts))
318
+ for unit, t in self.svcs.items() if t.last == 'failed' or t.fails]
319
+ self.an = analyze(self.store, self.m, ap, trends, svcs, self.online())
320
+
321
+ for f in self.an.findings: # announce each new finding once
322
+ if f.key not in self.reported and f.category != 'Availability': self.raise_alert(f.severity, f'Insight: {f.title} - {f.detail}')
323
+ self.reported = {f.key for f in self.an.findings}
324
+
325
+ dry = set() # act on eligible findings, with cooldowns; a dry run says once what it would do
326
+ for f in self.an.findings if ap.enabled and self.online() else ():
327
+ if not f.auto: continue
328
+ if ap.dryRun:
329
+ dry.add(f.key)
330
+ if f.key not in self.dry: self.raise_alert('action', f'Autopilot (dry run) would: {f.label} - {f.title}')
331
+ elif now - self.cooldown.get(f.key, 0) >= {'disk_cleanup': 6 * 3600000, 'restart_service': 120000}.get(f.action, 900000):
332
+ self.cooldown[f.key] = now
333
+ self.run_finding(f, True)
334
+ self.dry = dry
335
+ self.analysis_updated()
336
+
337
+ # ---- manager ----------------------------------------------------------------------------
338
+ class Manager:
339
+ def __init__(self):
340
+ self.sessions, self.alerts = [], []
341
+ self.changed, self.alert, self.cleared = Signal(), Signal(), Signal() # server list changed, alert raised, alerts cleared
342
+ @staticmethod
343
+ def config_dir():
344
+ os.makedirs(plat.config_dir(), exist_ok=True)
345
+ return plat.config_dir()
346
+ def path(self, name): return os.path.join(self.config_dir(), name)
347
+ def session(self, server_id): return next((s for s in self.sessions if s.cfg.id == server_id), None)
348
+ def attach(self, cfg):
349
+ s = Session(cfg)
350
+ s.alert.append(self.on_alert)
351
+ self.sessions.append(s)
352
+ return s
353
+ def on_alert(self, e):
354
+ self.alerts[:0] = [e]
355
+ del self.alerts[2000:]
356
+ log = self.path('alerts.log')
357
+ try:
358
+ with open(log, 'w' if os.path.exists(log) and os.path.getsize(log) > 5 << 20 else 'a', encoding='utf-8') as f:
359
+ f.write(f'{e.time.isoformat(timespec="seconds")}\t{e.severity}\t{e.server}\t{e.message}\n')
360
+ except OSError:
361
+ pass # the event still reaches the window
362
+ self.alert(e)
363
+ def load(self):
364
+ try:
365
+ with open(self.path('servers.json'), encoding='utf-8') as f:
366
+ for o in json.load(f)['servers']: self.attach(ServerConfig.from_json(o))
367
+ except FileNotFoundError: # first start: monitor this machine
368
+ self.attach(ServerConfig(new_id(), 'This computer', 'Local', transport=0))
369
+ self.save()
370
+ except (OSError, ValueError, LookupError, TypeError, AttributeError):
371
+ pass # unreadable or damaged file: start with the servers read so far
372
+ for s in self.sessions: s.start()
373
+ self.changed()
374
+ def save(self):
375
+ tmp = self.path('servers.json.tmp')
376
+ with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), 'w', encoding='utf-8') as f:
377
+ json.dump({'version': 1, 'servers': [s.cfg.to_json() for s in self.sessions]}, f, indent=4)
378
+ os.replace(tmp, self.path('servers.json'))
379
+ def add(self, cfg):
380
+ s = self.attach(cfg)
381
+ self.save()
382
+ s.start()
383
+ self.changed()
384
+ return s
385
+ def update(self, cfg):
386
+ s = self.session(cfg.id)
387
+ if s:
388
+ s.set_config(cfg)
389
+ self.save()
390
+ self.changed()
391
+ def remove(self, server_id, delete_history):
392
+ s = self.session(server_id)
393
+ if not s: return
394
+ self.sessions.remove(s)
395
+ s.alert.clear()
396
+ s.close()
397
+ if delete_history: shutil.rmtree(s.store.dir, ignore_errors=True)
398
+ self.save()
399
+ self.changed()
400
+ def move(self, server_id, delta):
401
+ i = self.sessions.index(self.session(server_id))
402
+ j = min(max(i + delta, 0), len(self.sessions) - 1)
403
+ if i != j:
404
+ self.sessions.insert(j, self.sessions.pop(i))
405
+ self.save()
406
+ self.changed()
407
+ def clear_alerts(self):
408
+ self.alerts.clear()
409
+ self.cleared()
410
+ def close(self):
411
+ for s in self.sessions: s.close()
Server Monitor(python-linux)/tabs.py ADDED
@@ -0,0 +1,654 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ """Detail-page tabs: each one shows an aspect of the bound server session."""
2
+ import copy, math, time, tkinter as tk
3
+ from datetime import datetime
4
+ from tkinter import filedialog
5
+
6
+ import plat
7
+ from history import (CPU, DISK, DISKIO, GPU, IOWAIT, KEYS, LOAD, MEM, NAMES, PROCS, RD, RX, STEP, SWAP, TEMP, TIER_NAMES, TX, WR, fmt_metric,
8
+ stats)
9
+ from model import (RULE_ACTIONS, RULE_METRICS, TRANSPORTS, Rule, catalogue, command, count, default_rules, duration, fmt_bytes, new_id, pct, rate,
10
+ temp)
11
+ from widgets import (C, Cell as X, Chart, CoreGrid, Dialog, Entry, F, Gauge, Heatmap, KeyValues, Scroll, SegmentBar, Spin, Table, ask, box,
12
+ button, check, choose, combo, decimals, down, field, health, label, level, mix, panel, pct0, popup, press, right, severity,
13
+ spread, textbox, tiles, tip, write)
14
+
15
+ class Tab(tk.Frame):
16
+ """One aspect of the bound session s. save(config) persists config edits."""
17
+ span = 15 * 60000 # live chart window
18
+ def __init__(self, parent, save):
19
+ super().__init__(parent, bg=C.bg)
20
+ self.s, self.save = None, save
21
+ self.build()
22
+ def page(self, scroll=True):
23
+ """Padded root for the content; scrolls when the tab is taller than the window."""
24
+ if scroll: return down(box(down(Scroll(self), 0, fill='both', expand=True).body), 0, fill='both', expand=True, padx=(4, 10), pady=16)
25
+ return down(box(self), 0, fill='both', expand=True, padx=4, pady=(16, 12))
26
+ def attach(self, s): self.s = s
27
+ def refresh(self): """A new sample arrived (called only while the tab is visible)."""
28
+ def analysis(self): """The analyzer ran."""
29
+ def run(self, cmd, status):
30
+ """Runs a command and reports the result in a status label."""
31
+ status.config(text='Running: ' + cmd, fg=C.muted)
32
+ self.s.exec(cmd, True, lambda code, out: status.winfo_exists() and status.config(
33
+ text=f'✗ {cmd}: {out.strip()[:300]}' if code else f'✓ {cmd}', fg=C.red if code else C.green))
34
+
35
+ def io_wait(live): return [('I/O wait', C.amber, live.s['iowait'])] if plat.POSIX_CPU else []
36
+
37
+ # ============================================================================ Overview
38
+ class Overview(Tab):
39
+ def build(self):
40
+ b = self.page()
41
+ gauges = down(panel(b))
42
+ self.g = [Gauge(gauges, name, 85 if name == 'Temperature' else 90) for name in ('CPU', 'Memory', 'Fullest disk', 'Swap', 'Temperature', 'Health')]
43
+ spread(self.g, gap=0) # equal widths: all six stay visible in a narrow window
44
+ self.t = tiles(b, [('Load average', C.accent), ('Processes', C.violet), ('TCP connections', C.teal), ('Services', C.green), ('Uptime', C.amber)])
45
+ mid = down(box(b), 0)
46
+ system = panel(mid, 'System', 330)
47
+ system.pack(side='right', fill='y')
48
+ self.info = down(KeyValues(system))
49
+ charts = right(box(mid), 14, True)
50
+ self.cpu, self.mem = Chart(charts, 'CPU', pct0, 100, stacked=True), Chart(charts, 'Memory', pct0, 100)
51
+ self.net, self.io = Chart(charts, 'Network', rate), Chart(charts, 'Disk I/O', rate)
52
+ spread([self.cpu, self.mem, self.net, self.io], 2)
53
+ def refresh(self):
54
+ m, h, a, c, g, t, tcp = self.s.m, self.s.live, self.s.an, self.s.cfg, self.g, self.t, self.s.m.tcp
55
+ g[0].set(m.cpu_usage, sub=f'{m.cpu_count} cores')
56
+ g[1].set(m.mem_pct, sub=f'{fmt_bytes(m.mem_used)} / {fmt_bytes(m.mem_total)}')
57
+ g[2].set(m.max_disk_pct, sub=m.fullest_mount)
58
+ g[3].set(m.swap_pct, sub=f'{fmt_bytes(m.swap_used)} / {fmt_bytes(m.swap_total)}' if m.swap_total > 0 else 'no swap')
59
+ g[4].set(min(100, m.max_temp), temp(m.max_temp) if m.temps else '—', f'{len(m.temps)} sensors' if m.temps else 'no sensors')
60
+ g[5].set(a.health, str(a.health), 'grade ' + a.grade, health(a.health))
61
+ t[0].set(f'{m.load1:.2f}', f'5m {m.load5:.2f} · 15m {m.load15:.2f}', level(m.load1 * 100 / max(1, m.cpu_count), 80, 150))
62
+ t[1].set(str(len(m.procs)), f'{m.threads_total} threads · {m.procs_running} running')
63
+ t[2].set(str(tcp.get('ESTABLISHED', 0)), f'{tcp.get("LISTEN", 0)} listening · {tcp.get("TIME_WAIT", 0)} time-wait')
64
+ t[3].set(str(m.services_running), f'{m.services_failed} failed' if m.services_failed else 'running · none failed', C.red if m.services_failed else None)
65
+ t[4].set(duration(m.uptime), f'{m.logged_users} user(s) logged in')
66
+ self.cpu.set(h.t, [('User', C.accent, h.s['user']), ('System', C.violet, h.s['sys'])] + io_wait(h), self.span)
67
+ self.mem.set(h.t, [('Used', C.violet, h.s['mem']), ('Cache', C.blue, h.s['cache'], False, True), ('Swap', C.pink, h.s['swap'], False)], self.span)
68
+ self.net.set(h.t, [('Down', C.teal, h.s['rx']), ('Up', C.pink, h.s['tx'])], self.span)
69
+ self.io.set(h.t, [('Read', C.blue, h.s['rd']), ('Write', C.orange, h.s['wr'])], self.span)
70
+ self.info.set([('Hostname', m.hostname), ('OS', m.os), ('Kernel', f'{m.kernel} {m.arch}'), ('CPU', m.cpu_model),
71
+ ('Cores', str(m.cpu_count) + (f' @ {m.avg_mhz / 1000:.2f} GHz' if m.avg_mhz > 0 else '')), ('Memory', fmt_bytes(m.mem_total)),
72
+ ('Swap', fmt_bytes(m.swap_total) if m.swap_total > 0 else 'none'), ('Virtualisation', m.virt),
73
+ ('Disks', f'{len(m.mounts)} mounted file systems'), ('Interfaces', str(len(m.nets))), ('GPU', m.gpus[0].name if m.gpus else 'none'),
74
+ ('Connection', f'{c.address()} ({TRANSPORTS[c.transport]})'), ('Sample interval', f'{c.interval} s')])
75
+
76
+ # ============================================================================ CPU
77
+ class CpuTab(Tab):
78
+ def build(self):
79
+ b = self.page()
80
+ self.model = down(label(b, kind='H2'))
81
+ self.t = tiles(b, [('Usage', C.accent), ('Load 1 / 5 / 15', C.violet), ('Avg frequency', C.teal), (plat.TEXT['cpu_tile'], C.orange),
82
+ ('Context switches', C.blue), ('Interrupts', C.pink), ('New processes', C.green), ('Running / blocked', C.amber)], 4)
83
+ r = down(box(b))
84
+ self.chart, self.load = Chart(r, 'CPU time breakdown', pct0, 100, 260, True), Chart(r, 'Load average (1 min)', decimals(1), height=260)
85
+ spread([self.chart, self.load], weights=(3, 2))
86
+ self.cores = down(CoreGrid(down(panel(b, 'Per core'))), 0)
87
+ r = down(box(b), 0)
88
+ temps, self.gpu_panel = right(panel(r, 'Temperatures'), 0, True), panel(r, 'GPUs')
89
+ self.temps = down(Table(temps, ['Sensor', 'Temperature'], [300], [1]), 0)
90
+ self.gpus = down(Table(self.gpu_panel, ['#', 'Name', 'Usage', 'Memory', 'Temp', 'Power', 'Fan'], [40, 220, 120, 160], [2, 3]), 0)
91
+ def refresh(self):
92
+ m, h, t = self.s.m, self.s.live, self.t
93
+ self.model.config(text=m.cpu_model or 'Processor')
94
+ t[0].set(pct(m.cpu_usage), f'user {pct(m.cpu_user)} · system {pct(m.cpu_system)}' + (f' · iowait {pct(m.cpu_iowait)}' if plat.POSIX_CPU else ''),
95
+ level(m.cpu_usage))
96
+ t[1].set(f'{m.load1:.2f} / {m.load5:.2f} / {m.load15:.2f}', f'{m.load1 * 100 / max(1, m.cpu_count):.0f}% of {m.cpu_count} cores')
97
+ t[2].set(f'{m.avg_mhz / 1000:.2f} GHz' if m.avg_mhz > 0 else 'n/a')
98
+ value, sub, warn = plat.cpu_tile(m)
99
+ t[3].set(value, sub, C.amber if warn else None)
100
+ t[4].set(count(m.ctxt_per_sec) + '/s')
101
+ t[5].set(count(m.intr_per_sec) + '/s')
102
+ t[6].set(f'{m.forks_per_sec:.1f}/s')
103
+ t[7].set(f'{m.procs_running} / {m.procs_blocked}', 'blocked = waiting for ' + ('I/O' if plat.POSIX_CPU else 'a CPU'),
104
+ C.amber if m.procs_blocked > m.cpu_count else None)
105
+ self.chart.set(h.t, [('User', C.accent, h.s['user']), ('System', C.violet, h.s['sys'])] + io_wait(h)
106
+ + ([('Steal', C.red, h.s['steal'])] if plat.POSIX_CPU else []), self.span)
107
+ self.load.set(h.t, [('Load', C.violet, h.s['load']), ('Cores', C.faint, [m.cpu_count] * len(h.t), False, True)], self.span)
108
+ self.cores.set(m.cores)
109
+ self.temps.set([[x.name, X(temp(x.celsius), pct=min(100, x.celsius))] for x in m.temps]
110
+ or [[X('No temperature sensors exposed (common on VMs)', C.muted)]])
111
+ if bool(m.gpus) != bool(self.gpu_panel.winfo_manager()):
112
+ right(self.gpu_panel, 0, True, padx=(14, 0)) if m.gpus else self.gpu_panel.pack_forget()
113
+ self.gpus.set([[str(g.index), g.name, X(pct(g.util, 0), pct=g.util),
114
+ X(f'{g.mem_used:g} / {g.mem_total:g} MiB', pct=g.mem_used * 100 / g.mem_total if g.mem_total > 0 else 0),
115
+ X(temp(g.temp), level(g.temp, 75, 88)), f'{g.power:g} W', pct(g.fan, 0)] for g in m.gpus])
116
+
117
+ # ============================================================================ Memory
118
+ class MemoryTab(Tab):
119
+ def build(self):
120
+ b = self.page()
121
+ self.t = tiles(b, [('Used', C.violet), ('Available', C.green), ('Cache + buffers', C.blue), ('Swap used', C.pink)])
122
+ composition = down(panel(b, 'Composition'))
123
+ self.bar = down(SegmentBar(composition), 10)
124
+ down(label(composition, 'SWAP', 'Section'), 10)
125
+ self.swap = down(SegmentBar(composition), 0)
126
+ r = down(box(b))
127
+ details = panel(r, 'Details', 300)
128
+ details.pack(side='right', fill='y')
129
+ self.detail = down(KeyValues(details))
130
+ self.chart = right(Chart(r, 'Memory usage', pct0, 100, 280), 14, True)
131
+ self.top = down(Table(down(panel(b, 'Top memory consumers'), 0), ['PID', 'Process', 'User', 'RSS', 'Memory %', 'Virtual'],
132
+ [80, 220, 120, 110, 160], [4], height=360), 0)
133
+ def refresh(self):
134
+ m, h, t, free = self.s.m, self.s.live, self.t, mix(C.grid, '#ffffff', .18)
135
+ t[0].set(fmt_bytes(m.mem_used), f'{pct(m.mem_pct)} of {fmt_bytes(m.mem_total)}', level(m.mem_pct))
136
+ t[1].set(fmt_bytes(m.mem_available), 'free ' + fmt_bytes(m.mem_free))
137
+ t[2].set(fmt_bytes(m.cached + m.buffers), 'reclaimable when needed')
138
+ t[3].set(fmt_bytes(m.swap_used) if m.swap_total > 0 else 'no swap', f'{pct(m.swap_pct)} of {fmt_bytes(m.swap_total)}' if m.swap_total > 0 else '',
139
+ level(m.swap_pct, 40, 80))
140
+ self.bar.set([(max(0.0, m.mem_total - m.mem_free - m.cached - m.buffers), C.violet, 'Applications'), (m.shared, C.pink, 'Shared'),
141
+ (m.buffers, C.teal, 'Buffers'), (max(0.0, m.cached - m.shared), C.blue, 'Cache'), (m.mem_free, free, 'Free')], m.mem_total)
142
+ self.swap.set([(m.swap_used, C.pink, 'Used'), (m.swap_total - m.swap_used, free, 'Free')], m.swap_total)
143
+ self.chart.set(h.t, [('Used', C.violet, h.s['mem']), ('Cache', C.blue, h.s['cache'], False, True), ('Swap', C.pink, h.s['swap'])], self.span)
144
+ self.detail.set([(k, fmt_bytes(v)) for k, v in (
145
+ ('Total', m.mem_total), ('Used', m.mem_used), ('Available', m.mem_available), ('Free', m.mem_free), ('Buffers', m.buffers),
146
+ ('Cached', m.cached), ('Shared', m.shared), ('Slab', m.slab), ('Dirty', m.dirty), ('Swap total', m.swap_total), ('Swap used', m.swap_used))])
147
+ self.top.set([[X(str(p.pid), C.muted), p.name, X(p.user, C.muted), X(fmt_bytes(p.rss), right=True), X(pct(p.mem_pct), pct=min(100, p.mem_pct * 2)),
148
+ X(fmt_bytes(p.vsz), C.muted, True)] for p in sorted(m.procs, key=lambda p: -p.rss)[:15]])
149
+
150
+ # ============================================================================ Storage
151
+ class StorageTab(Tab):
152
+ def build(self):
153
+ b = self.page()
154
+ self.t = tiles(b, [('Fullest file system', C.amber), ('Read', C.blue), ('Write', C.orange), ('Busiest disk', C.red)])
155
+ self.mounts = down(Table(down(panel(b, 'File systems')), ['Mount point', 'Device', 'Type', 'Size', 'Used', 'Free', 'Usage'],
156
+ [260, 140, 80, 110, 110, 110], [6]), 0)
157
+ self.io = down(Chart(b, 'Disk throughput', rate, height=260))
158
+ self.disks = down(Table(down(panel(b, 'Block devices'), 0), ['Device', 'Read/s', 'Write/s', 'Read IOPS', 'Write IOPS', 'Busy', 'Total read',
159
+ 'Total written'], [110, 110, 110, 100, 100, 150, 120], [5], height=200), 0)
160
+ def refresh(self):
161
+ m, h, t = self.s.m, self.s.live, self.t
162
+ t[0].set(pct(m.max_disk_pct), m.fullest_mount, level(m.max_disk_pct, 80, 90))
163
+ t[1].set(rate(m.disk_read_bps))
164
+ t[2].set(rate(m.disk_write_bps))
165
+ t[3].set(pct(m.max_disk_util), m.busiest_disk, level(m.max_disk_util, 60, 90))
166
+ self.io.set(h.t, [('Read', C.blue, h.s['rd']), ('Write', C.orange, h.s['wr'])], self.span)
167
+ self.mounts.set([[x.mount, X(x.device, C.muted), X(x.type, C.muted), X(fmt_bytes(x.total), right=True), X(fmt_bytes(x.used), right=True),
168
+ X(fmt_bytes(x.avail), right=True), X(pct(x.pct), pct=x.pct)] for x in m.mounts])
169
+ self.disks.set([[d.name, X(rate(d.read_bps), C.blue, True), X(rate(d.write_bps), C.orange, True), X(f'{d.read_iops:.0f}', right=True),
170
+ X(f'{d.write_iops:.0f}', right=True), X(pct(d.util, 0), pct=d.util), X(fmt_bytes(d.total_read), C.muted, True),
171
+ X(fmt_bytes(d.total_written), C.muted, True)] for d in m.disks])
172
+
173
+ # ============================================================================ Network
174
+ class NetworkTab(Tab):
175
+ def build(self):
176
+ b = self.page()
177
+ self.t = tiles(b, [('Download', C.teal), ('Upload', C.pink), ('Established', C.accent), ('Listening', C.green),
178
+ ('Time-wait / close-wait', C.amber), ('Sockets in use', C.violet)])
179
+ r = down(box(b))
180
+ right(label(r, 'Interface', 'Muted'))
181
+ self.iface = right(combo(r, ['All physical (total)'], 28, self.refresh), fill='none')
182
+ self.chart = down(Chart(b, 'Traffic', rate, height=280))
183
+ self.tbl = down(Table(down(panel(b, 'Interfaces'), 0), ['Interface', 'State', 'Speed', 'Down/s', 'Up/s', 'Pkts in/s', 'Pkts out/s', 'Received',
184
+ 'Sent', 'Errors', 'Drops'], [160, 80, 90, 110, 110, 90, 90, 110, 110, 70], height=240), 0)
185
+ def refresh(self):
186
+ m, h, t, tcp = self.s.m, self.s.live, self.t, self.s.m.tcp
187
+ t[0].set(rate(m.net_rx_bps), 'physical interfaces')
188
+ t[1].set(rate(m.net_tx_bps))
189
+ t[2].set(str(tcp.get('ESTABLISHED', 0)), 'TCP')
190
+ t[3].set(str(tcp.get('LISTEN', 0)), 'open TCP ports')
191
+ t[4].set(f'{tcp.get("TIME_WAIT", 0)} / {tcp.get("CLOSE_WAIT", 0)}', 'many close-wait = app not closing sockets',
192
+ C.amber if tcp.get('CLOSE_WAIT', 0) > 100 else None)
193
+ t[5].set(str(m.sockets_used))
194
+ names = ['All physical (total)'] + [n.name for n in m.nets]
195
+ if list(self.iface['values']) != names:
196
+ current = self.iface.get()
197
+ self.iface.config(values=names)
198
+ self.iface.current(names.index(current) if current in names else 0)
199
+ name, total = self.iface.get(), self.iface.current() <= 0
200
+ self.chart.title = 'Traffic — ' + ('all physical interfaces' if total else name)
201
+ self.chart.set(h.t, [('Down', C.teal, h.s['rx'] if total else h.if_rx.get(name, [])),
202
+ ('Up', C.pink, h.s['tx'] if total else h.if_tx.get(name, []))], self.span)
203
+
204
+ def row(x):
205
+ dim = C.muted if x.virt else ''
206
+ return [X(x.name + (' (virtual)' if x.virt else ''), dim), X(x.state, {'up': C.green, 'down': C.red}.get(x.state, C.muted)),
207
+ X(f'{x.speed} Mb/s' if x.speed > 0 else '—', C.muted), X(rate(x.rx_bps), C.teal, True), X(rate(x.tx_bps), C.pink, True),
208
+ X(f'{x.rx_pps:.0f}', dim, True), X(f'{x.tx_pps:.0f}', dim, True), X(fmt_bytes(x.rx_bytes), dim, True), X(fmt_bytes(x.tx_bytes), dim, True),
209
+ X(f'{x.errors:g}', C.amber if x.errors else dim, True), X(f'{x.drops:g}', C.amber if x.drops else dim, True)]
210
+ self.tbl.set([row(x) for x in m.nets])
211
+
212
+ # ============================================================================ list tabs (processes, services)
213
+ class ListTab(Tab):
214
+ """Filterable, sortable table that keeps the selection across refreshes; rows are lists of Cell."""
215
+ def build_list(self, headers, widths, bars, hint, sort):
216
+ b = self.page(False)
217
+ self.bar, self.rows = down(box(b), 10), []
218
+ self.actions = box(self.bar) # packed first: in a narrow window the summary gives way, not the buttons
219
+ self.actions.pack(side='right')
220
+ self.filter = right(Entry(self.bar, hint=hint, width=26))
221
+ self.filter.bind('<KeyRelease>', lambda e: self.show())
222
+ self.bar.bind('<Configure>', lambda e: self.filter.config(width=26 if e.width > 1000 else 12))
223
+ self.summary = right(label(self.bar, kind='Muted'))
224
+ self.tbl = down(Table(b, headers, widths, bars, sort), 8, fill='both', expand=True)
225
+ self.status = down(label(b, kind='Muted'), 0)
226
+ def accept(self, row): return True
227
+ def show(self, rows=None):
228
+ self.rows = self.rows if rows is None else rows
229
+ needle = self.filter.text().lower()
230
+ self.tbl.set([r for r in self.rows if self.accept(r) and any(needle in c.text.lower() for c in r)])
231
+
232
+ STATES = {'R': ('Running', C.green), 'S': ('Sleeping', C.muted), 'D': ('Disk wait', C.amber), 'Z': ('Zombie', C.red), 'T': ('Stopped', C.red),
233
+ 'I': ('Idle', C.muted)}
234
+
235
+ class ProcessTab(ListTab):
236
+ def build(self):
237
+ self.build_list(['PID', 'Name', 'User', 'State', 'CPU', 'Memory', 'RSS', 'Threads', plat.TEXT['priority'], 'Running for'],
238
+ [80, 230, 120, 100, 130, 130, 100, 80, 70], [4, 5], 'Filter by name, user or PID…', (4, True))
239
+ self.freeze = check(self.bar, 'Freeze list')
240
+ tip(self.freeze, "Stop refreshing so rows don't move while you pick one").pack(side='left', after=self.filter, padx=(0, 10))
241
+ menu = []
242
+ for verb, cmd, flags in plat.PROC_ACTIONS:
243
+ menu.append((verb, lambda verb=verb, cmd=cmd, flags=flags: self.signal(verb, cmd, 'c' in flags)))
244
+ if 'b' in flags: right(button(self.actions, verb, menu[-1][1], 'Danger' if 'd' in flags else None), 6)
245
+ right(button(self.actions, 'Priority…', self.priority), 0)
246
+ self.tbl.on_menu = lambda e: popup(self, e, menu + [None, ('Change priority…', self.priority)])
247
+ def attach(self, s):
248
+ if s is not self.s: self.freeze.var.set(False) # a frozen list would show the other server's PIDs
249
+ self.s = s
250
+ def refresh(self):
251
+ if self.freeze.var.get(): return
252
+ m = self.s.m
253
+
254
+ def row(p):
255
+ state, color = STATES.get(p.state, (p.state, C.muted))
256
+ raised = plat.priority_level(p.nice)
257
+ return [X(str(p.pid), C.muted, True, key=p.pid), X(p.name), X(p.user, C.muted), X(state, color), X(pct(p.cpu), pct=min(100, p.cpu), key=p.cpu),
258
+ X(pct(p.mem_pct), pct=p.mem_pct, key=p.mem_pct), X(fmt_bytes(p.rss), right=True, key=p.rss), X(str(p.threads), right=True, key=p.threads),
259
+ X(str(p.nice), (C.orange if raised > 0 else C.teal) if raised else C.text, True, key=p.nice), X(duration(p.age), C.muted, True, key=p.age)]
260
+ self.show([row(p) for p in m.procs])
261
+ self.summary.config(text=f'{len(m.procs)} processes · {sum(p.state == "R" for p in m.procs)} running · {m.threads_total} threads')
262
+ def selected(self):
263
+ """(pid, 'name (pid)') of the selected process, or None after a hint in the status line."""
264
+ row = self.tbl.row()
265
+ if row: return row[0].text, f'{row[1].text} ({row[0].text})'
266
+ self.status.config(text='Select a process first.', fg=C.muted)
267
+ def signal(self, verb, cmd, confirm):
268
+ sel = self.selected()
269
+ if sel and (not confirm or ask(self, verb, f'{verb} {sel[1]} on {self.s.cfg.name}?')): self.run(command(cmd, sel[0]), self.status)
270
+ def priority(self):
271
+ sel = self.selected()
272
+ choice = sel and choose(self, 'Change priority', f'Priority for {sel[1]}:', [(k, None) for k in plat.PRIORITIES] + [('Cancel', 'Flat')])
273
+ if choice in plat.PRIORITIES: self.run(command(plat.PRIORITY_CMD.replace('{v}', str(plat.PRIORITIES[choice])), sel[0]), self.status)
274
+
275
+ class ServiceTab(ListTab):
276
+ def build(self):
277
+ self.build_list(['Service', 'Active', 'State', 'Load', 'Description'], [300, 100, 100, 90], [], 'Filter services…', (0, False))
278
+ self.state, self.shown = combo(self.bar, ['All', 'Running', 'Failed', 'Not running'], 12, self.show), None
279
+ self.state.pack(side='left', after=self.filter, padx=(0, 10))
280
+ menu = [(verb.capitalize(), lambda verb=verb: self.act(verb)) for verb in plat.SERVICE_VERBS]
281
+ for text, act in menu: right(button(self.actions, text, act, 'Danger' if text in ('Stop', 'Disable') else None), 6)
282
+ right(button(self.actions, 'Logs', self.logs, 'Primary'), 0)
283
+ self.tbl.on_open = self.logs
284
+ self.tbl.on_menu = lambda e: popup(self, e, menu + [None, ('Show logs', self.logs)])
285
+ def attach(self, s): self.s, self.shown = s, None
286
+ def accept(self, row):
287
+ active, sub, state = row[1].text, row[2].text, self.state.current()
288
+ return state == 0 or (state == 1 and sub == 'running') or (state == 2 and active == 'failed') or (state == 3 and sub != 'running' and active != 'failed')
289
+ def refresh(self):
290
+ m = self.s.m
291
+ shown = [(x.unit, x.active, x.sub) for x in m.services]
292
+ if shown == self.shown: # unchanged: keep the list still
293
+ return
294
+ self.shown = shown
295
+
296
+ def row(x):
297
+ c = C.red if x.active == 'failed' else C.green if x.sub == 'running' else C.teal if x.active == 'active' else C.muted
298
+ return [X(x.unit), X(x.active, c), X(x.sub, c), X(x.load, C.muted), X(x.description, C.muted)]
299
+ self.show([row(x) for x in m.services])
300
+ self.summary.config(text=f'{len(m.services)} services · {m.services_running} running · {m.services_failed} failed' if m.services
301
+ else 'No services reported by this machine')
302
+ def act(self, verb):
303
+ unit = self.tbl.row() and self.tbl.selected
304
+ if not unit: return self.status.config(text='Select a service first.', fg=C.muted)
305
+ if verb not in ('stop', 'disable', 'restart') or ask(self, 'Confirm', f'{verb.capitalize()} {unit} on {self.s.cfg.name}?'):
306
+ self.run(command(plat.SERVICE_VERBS[verb], unit), self.status)
307
+ def logs(self):
308
+ s, unit = self.s, self.tbl.row() and self.tbl.selected
309
+ if not unit: return
310
+ d = Dialog(self, f'Logs — {unit} — {s.cfg.name}')
311
+ d.geometry('1000x640')
312
+ text = textbox(d)
313
+ write(text, 'Loading…')
314
+ down(text.frame, 12, fill='both', expand=True)
315
+ r = down(box(d), 0)
316
+ lines = right(Spin(r, 50, 5000, 300), 6)
317
+ right(label(r, 'lines', 'Muted'))
318
+
319
+ def load():
320
+ s.exec(command(plat.SERVICE_LOGS, unit, lines.value()), True, lambda code, out: text.winfo_exists() and write(text, out, clear=True))
321
+ right(button(r, 'Reload', load))
322
+ button(r, 'Close', d.close).pack(side='right')
323
+ load()
324
+
325
+ # ============================================================================ Console
326
+ class ConsoleTab(Tab):
327
+ def build(self):
328
+ b = self.page(False)
329
+ side = Scroll(b) # the command lists scroll in a low window
330
+ side.cv.config(width=288)
331
+ side.pack(side='right', fill='y', padx=(14, 0))
332
+ self.out, self.history, self.pos = textbox(b), [], 0
333
+ down(self.out.frame, 10, fill='both', expand=True)
334
+ r = down(box(b), 0)
335
+ right(label(r, '$', fg=C.accent, font=F(15, True)))
336
+ self.cmd = right(Entry(r, hint=plat.TEXT['console_hint'], mono=True), grow=True)
337
+ self.privileged = check(r, 'privileged')
338
+ if plat.HAS_SUDO: right(tip(self.privileged, plat.TEXT['privileged_tip']))
339
+ right(button(r, 'Run', self.enter, 'Primary'))
340
+ right(button(r, 'Clear', lambda: write(self.out, '', clear=True)), 0)
341
+ for key, handler in (('<Return>', self.enter), ('<Up>', lambda: self.recall(-1)), ('<Down>', lambda: self.recall(1))):
342
+ self.cmd.bind(key, lambda e, handler=handler: handler())
343
+ for title, items, system in (('Quick diagnostics', plat.QUICK, False), ('System actions', plat.ACTIONS, True)):
344
+ p = down(panel(side.body, title, 270))
345
+ for text, cmd in items:
346
+ tip(down(button(p, text, lambda text=text, cmd=cmd, system=system: self.quick(text, cmd, system),
347
+ 'Danger' if text in plat.POWER else 'Side', pady=3), 6), cmd)
348
+ def attach(self, s):
349
+ if s is self.s: return
350
+ self.s = s
351
+ write(self.out, '', clear=True)
352
+ if s: write(self.out, f'Console for {s.cfg.name} ({s.cfg.address()}). Commands run non-interactively with a 120 s timeout.\n', C.muted)
353
+ def enter(self):
354
+ cmd = self.cmd.text().strip()
355
+ if cmd:
356
+ if self.history[-1:] != [cmd]: self.history.append(cmd)
357
+ self.pos = len(self.history)
358
+ self.cmd.put('')
359
+ self.exec(cmd, self.privileged.var.get())
360
+ def recall(self, step):
361
+ if self.history:
362
+ self.pos = min(max(self.pos + step, 0), len(self.history))
363
+ self.cmd.put((self.history + [''])[self.pos])
364
+ def quick(self, text, cmd, system):
365
+ danger = text in plat.POWER
366
+ question = f'{text} on {self.s.cfg.name}?' + ('\n\nThe machine will be unavailable until it comes back.' if danger else '')
367
+ if not system or ask(self, text, question, danger): self.exec(cmd, system)
368
+ def exec(self, cmd, privileged):
369
+ out, t0 = self.out, time.monotonic()
370
+ write(out, f'\n{time.strftime("%H:%M:%S")} $ ', C.accent)
371
+ write(out, cmd + '\n')
372
+
373
+ def done(code, text):
374
+ if out.winfo_exists():
375
+ write(out, text.rstrip('\n') + '\n' if text else '')
376
+ write(out, f'[exit {code} · {(time.monotonic() - t0) * 1000:.0f} ms]\n', C.red if code else C.green)
377
+ self.s.exec(cmd, privileged, done, 120)
378
+
379
+ # ============================================================================ Alert rules
380
+ class RulesTab(Tab):
381
+ def build(self):
382
+ b = self.page(False)
383
+ down(label(b, 'Threshold rules are checked on every sample. When a condition holds for its duration an alert is raised and the action runs; '
384
+ 'if it is still true after the cooldown the action runs again. History-based automation lives in the Insights tab.', 'Muted', True), 10)
385
+ r = down(box(b), 10)
386
+ right(button(r, '+ Add rule', lambda: self.edit(-1), 'Primary'))
387
+ right(button(r, 'Edit', lambda: self.edit(self.index())))
388
+ right(button(r, 'Delete', lambda: self.index() >= 0 and self.store([x for i, x in enumerate(self.s.cfg.rules) if i != self.index()]), 'Danger'))
389
+ button(r, 'Reset to defaults', lambda: ask(self, 'Reset rules', 'Replace all rules with the defaults?') and self.store(default_rules())).pack(side='right')
390
+ self.rules = down(Table(b, ['On', 'Condition', 'Severity', 'Action', 'Cooldown', 'Live value'], [50, 380, 100, 330, 100]), 10, fill='both', expand=True)
391
+ self.active = down(Table(b, ['Active problems'], height=128), 0)
392
+ self.rules.on_open = lambda: self.edit(self.index())
393
+ self.rules.on_click = lambda i, col: col == 0 and self.toggle(i)
394
+ def attach(self, s):
395
+ self.s = s
396
+ if s: self.refresh()
397
+ def index(self):
398
+ """Index of the selected rule, -1 without a selection."""
399
+ return self.rules.selected if self.rules.row() else -1
400
+ def store(self, rules):
401
+ c = copy.copy(self.s.cfg)
402
+ c.rules = rules
403
+ self.save(c)
404
+ self.refresh()
405
+ def toggle(self, i):
406
+ rules = copy.deepcopy(self.s.cfg.rules)
407
+ rules[i].enabled = not rules[i].enabled
408
+ self.store(rules)
409
+ def refresh(self):
410
+ s, rows = self.s, []
411
+ for i, r in enumerate(s.cfg.rules):
412
+ v = s.metric_value(r.metric)
413
+ hit = v < r.value if r.op == '<' else v > r.value
414
+ rows.append([X('☑' if r.enabled else '☐', C.accent if r.enabled else C.faint, key=i), X(r.condition(), '' if r.enabled else C.faint),
415
+ X(r.severity, severity(r.severity)),
416
+ X(r.action_text(), C.muted if r.action == 'notify' else C.violet), X(f'{r.cooldown} s', C.muted),
417
+ X(f'{v:.1f} {catalogue(RULE_METRICS, r.metric, 2)}', C.red if hit else C.green)])
418
+ self.rules.set(rows)
419
+ self.active.set([[X('⚠ ' + a, C.red)] for a in s.active_alerts()] or [[X('✓ No rule is currently triggered', C.green)]])
420
+ def edit(self, i):
421
+ rules = copy.deepcopy(self.s.cfg.rules)
422
+ r = rules[i] if 0 <= i < len(rules) else Rule(new_id())
423
+ d = Dialog(self, 'Edit rule' if r in rules else 'New rule')
424
+ f = down(box(d))
425
+ metric = field(f, 'When', combo(f, [m[1] + (f' ({m[2]})' if m[2] else '') for m in RULE_METRICS], 34))
426
+ condition = field(f, 'is', box(f))
427
+ op, value = right(combo(condition, ['>', '<'], 3)), right(Spin(condition, -1e9, 1e9, r.value, .5), 0, True)
428
+ hold = field(f, 'for at least (s)', Spin(f, 0, 86400, r.duration))
429
+ level_ = field(f, 'Severity', combo(f, ['info', 'warning', 'critical']))
430
+ action = field(f, 'Then', combo(f, [a[1] for a in RULE_ACTIONS], 34, lambda: sync()))
431
+ arg = field(f, 'Argument', Entry(f, r.arg))
432
+ cooldown = field(f, 'Repeat after (s)', Spin(f, 10, 86400, r.cooldown))
433
+ enabled = field(f, '', check(f, 'Enabled', r.enabled))
434
+ for w, values, current in ((metric, [m[0] for m in RULE_METRICS], r.metric), (action, [a[0] for a in RULE_ACTIONS], r.action),
435
+ (op, ['>', '<'], r.op), (level_, ['info', 'warning', 'critical'], r.severity)):
436
+ w.current(values.index(current) if current in values else 0)
437
+
438
+ def sync(): # only some actions take an argument
439
+ hint = RULE_ACTIONS[action.current()][2]
440
+ arg.config(state='normal')
441
+ arg.put(arg.text(), hint)
442
+ arg.config(state='normal' if hint else 'disabled')
443
+
444
+ def ok():
445
+ r.metric, r.op, r.severity, r.action = RULE_METRICS[metric.current()][0], op.get(), level_.get(), RULE_ACTIONS[action.current()][0]
446
+ r.value, r.duration, r.cooldown, r.enabled = float(value.value()), hold.value(), cooldown.value(), enabled.var.get()
447
+ r.arg = arg.text().strip() if RULE_ACTIONS[action.current()][2] else ''
448
+ d.close(True)
449
+
450
+ sync()
451
+ d.buttons(('Cancel', d.close), ('OK', ok, 'Primary'))
452
+ if d.run(): self.store(rules if r in rules else rules + [r])
453
+
454
+ # ============================================================================ History
455
+ RANGES = (('1 h', 3600), ('6 h', 21600), ('24 h', 86400), ('7 d', 604800), ('30 d', 2592000), ('90 d', 7776000), ('1 y', 31536000), ('All', 0))
456
+ # chart series: (metric, peak instead of average); metric -1 = availability
457
+ SERIES = ((CPU, 0), (CPU, 1), (MEM, 0), (SWAP, 0), (DISK, 0), (RD, 0), (WR, 0), (RX, 0), (TX, 0), (RX, 1), (LOAD, 0), (TEMP, 0), (TEMP, 1), (-1, 0))
458
+
459
+ class HistoryTab(Tab):
460
+ def build(self):
461
+ b = self.page()
462
+ r = down(box(b))
463
+ self.range, self.loaded, self.pts = 86400, 0, None
464
+ button(r, 'Export CSV…', self.export).pack(side='right', anchor='n') # packed first: in a narrow window the summary wraps instead
465
+ self.ranges = {sec: right(button(r, text, lambda sec=sec: self.pick(sec)), 6, fill='none', anchor='n') for text, sec in RANGES}
466
+ press(self.ranges[self.range], True)
467
+ self.res = right(label(r, kind='Muted', wrap=True), 0, True, padx=8)
468
+ g = down(box(b))
469
+ self.charts = [Chart(g, title, fmt, ymax, 240, empty='No history for this range yet') for title, fmt, ymax in (
470
+ ('CPU', pct0, 100), ('Memory & swap', pct0, 100), ('Disk usage (fullest)', pct0, 100), ('Disk throughput', rate, 0), ('Network', rate, 0),
471
+ ('Load average', decimals(1), 0), ('Temperature', lambda v: f'{v:.0f}°', 0), ('Availability', pct0, 100))]
472
+ spread(self.charts, 2)
473
+ self.stats = down(Table(down(panel(b, 'Statistics for the selected range'), 0), ['Metric', 'Minimum', 'Average', '95th percentile', 'Peak', 'Points'],
474
+ [200, 150, 150, 150, 150], height=14 * 30 + 34), 0)
475
+ def attach(self, s): self.s, self.loaded = s, 0
476
+ def pick(self, sec):
477
+ press(self.ranges[self.range], False)
478
+ self.range = sec
479
+ press(self.ranges[sec], True)
480
+ self.reload()
481
+ def refresh(self):
482
+ if time.time() - self.loaded >= (5 if 0 < self.range <= 21600 else 60): self.reload()
483
+ def reload(self):
484
+ s, self.loaded = self.s, time.time()
485
+ now = int(self.loaded)
486
+ frm = now - self.range if self.range else max(1, s.store.first_ts())
487
+ p, tier = s.store.span(frm, now)
488
+ self.pts = p
489
+ step, t, v = max(STEP[tier], s.cfg.interval), [], [[] for _ in SERIES]
490
+
491
+ def push(ts, i=None): # without a point index: a gap
492
+ t.append(ts * 1000)
493
+ for col, (m, peak) in zip(v, SERIES):
494
+ col.append(math.nan if i is None else p.up[i] * 100 / p.n[i] if m < 0 else (p.max if peak else p.avg)[m][i] if p.up[i] else math.nan)
495
+
496
+ for i, ts in enumerate(p.ts):
497
+ if t and ts * 1000 - t[-1] > step * 3000: # the app was not running
498
+ push(t[-1] // 1000 + step)
499
+ push(ts, i)
500
+ if t and now * 1000 - t[-1] > step * 3000: push(now)
501
+ cpu, cpu_max, mem, swap, disk, rd, wr, rx, tx, rx_max, load, temp_, temp_max, avail = v
502
+ peak = [('Peak', C.red, cpu_max, False, True)], [('Peak down', mix(C.teal, '#ffffff', .4), rx_max, False, True)], [('Peak', C.red, temp_max, False, True)]
503
+ cpu_peak, rx_peak, temp_peak = peak if tier else ([], [], []) # aggregated tiers also show the peaks
504
+ data = ([('Average', C.accent, cpu)] + cpu_peak, [('Memory', C.violet, mem), ('Swap', C.pink, swap, False)], [('Usage', C.amber, disk)],
505
+ [('Read', C.blue, rd), ('Write', C.orange, wr)], [('Down', C.teal, rx), ('Up', C.pink, tx)] + rx_peak, [('Load', C.violet, load)],
506
+ [('Average', C.orange, temp_)] + temp_peak, [('Online', C.green, avail)])
507
+ for chart, series in zip(self.charts, data):
508
+ chart.subtitle = f'avg per {TIER_NAMES[tier]}' if tier else ''
509
+ chart.set(t, series, (now - frm) * 1000)
510
+ n, up = sum(p.n), sum(p.up)
511
+ self.res.config(text=f'Resolution: {TIER_NAMES[tier]} · {len(p)} points · availability {pct(up * 100 / n, 2) if n else "—"}'
512
+ f' · stored {fmt_bytes(s.store.disk_bytes())}')
513
+
514
+ def row(m):
515
+ x = stats(p, m)
516
+ return [NAMES[m], X(fmt_metric(m, x.min), C.muted, True), X(fmt_metric(m, x.avg), right=True), X(fmt_metric(m, x.p95), C.amber, True),
517
+ X(fmt_metric(m, x.max), C.red, True), X(str(x.count), C.muted, True)]
518
+ self.stats.set([row(m) for m in (CPU, IOWAIT, LOAD, MEM, SWAP, DISK, DISKIO, RX, TX, RD, WR, TEMP, PROCS, GPU) if plat.POSIX_CPU or m != IOWAIT])
519
+ def export(self):
520
+ name = filedialog.asksaveasfilename(parent=self, title='Export history', initialfile=f'{self.s.cfg.name}-history.csv', filetypes=[('CSV', '*.csv')],
521
+ defaultextension='.csv')
522
+ if not name or self.pts is None: return
523
+ with open(name, 'w', encoding='utf-8', newline='\n') as f:
524
+ f.write('time,samples,online_pct' + ''.join(f',{k}_avg,{k}_max' for k in KEYS))
525
+ for ts, n, up, *values in self.pts.rows():
526
+ cells = [(values[m], values[len(KEYS) + m]) for m in range(len(KEYS))]
527
+ f.write(f'\n{datetime.fromtimestamp(ts).isoformat()},{n},{up * 100 / n if n else 0:g}'
528
+ + ''.join(',' + ','.join('' if x != x else f'{x:.3f}' for x in pair) for pair in cells))
529
+
530
+ # ============================================================================ Insights & Autopilot
531
+ class InsightsTab(Tab):
532
+ def build(self):
533
+ b, self.binds, self.loading = self.page(), [], False # binds: (config field, widget getter, widget setter)
534
+ top = down(box(b))
535
+ hp = right(panel(top, 'Health', 330), 14)
536
+ self.health = down(Gauge(hp, 'Health score'), 10)
537
+ self.reasons = down(label(hp, kind='Muted', wrap=296), 10)
538
+ down(button(hp, 'Analyze now', lambda: self.s.analyze()), 0)
539
+ side = right(box(top), 0, True)
540
+ self.t = tiles(side, [('Disk full forecast', C.amber), ('Memory trend (6 h)', C.violet), ('CPU / memory p95 (30 d)', C.accent),
541
+ ('Availability 24 h', C.green), ('Availability 7 d', C.green), ('Availability 30 d', C.green)], 3)
542
+ self.capacity = down(label(down(panel(side, 'Capacity planning'), 0, fill='both', expand=True), wrap=True), 0)
543
+
544
+ mid = down(box(b))
545
+ ap = panel(mid, 'Autopilot — automatic control', 430)
546
+ ap.pack(side='right', anchor='n')
547
+ down(label(ap, 'Acts on the findings once a minute, using statistics over the stored history. Every action is logged as an event.', 'Muted', 396), 10)
548
+ form = down(box(ap), 0)
549
+ self.findings = down(box(right(panel(mid, 'Findings from history analysis'), 14, True)), 0)
550
+
551
+ def line(*parts): # form row: the first part in the left column, the others side by side in the right one
552
+ r, cell = form.grid_size()[1], box(form)
553
+ for i, part in enumerate(parts):
554
+ w = label(cell if i else form, part, 'Muted') if isinstance(part, str) else part(cell if i else form)
555
+ right(w, 6) if i else w.grid(row=r, column=0, sticky='w', padx=(0, 10), pady=4)
556
+ cell.grid(row=r, column=1, sticky='w', pady=4)
557
+
558
+ tie = self.tie
559
+ line(tie('enabled', check, 'Autopilot enabled'), tie('dryRun', check, 'Dry run (only report)'))
560
+ line(tie('restartFailed', check, 'Restart failed services'), tie('maxRestartsPerHour', Spin, 1, 20), '/ hour max')
561
+ line('Runaway processes', tie('runawayMode', combo, ['Ignore', plat.TEXT['renice_mode'], 'Terminate'], 26, keys=['none', 'renice', 'terminate']))
562
+ line('', '≥', tie('runawayCpu', Spin, 10, 6400), '% for', tie('runawayMinutes', Spin, 1, 1440), 'min')
563
+ line('Memory leaks', tie('leakMode', combo, ['Ignore', 'Notify', 'Terminate under pressure'], 26, keys=['none', 'notify', 'terminate']))
564
+ line(' pressure ≥', tie('leakMemPressure', Spin, 50, 100), '% memory')
565
+ line(tie('diskCleanup', check, 'Disk cleanup'), 'full in <', tie('diskForecastDays', Spin, 1, 60), 'days')
566
+ line('', 'or usage ≥', tie('diskCleanupAt', Spin, 50, 100), '%')
567
+ line(' command', tie('diskCleanupCommand', Entry, width=34, mono=True))
568
+ line(tie('anomalyAlerts', check, 'Anomaly alerts'), 'z ≥', tie('anomalyZ', Spin, 1.5, 10, step=.5), 'σ')
569
+
570
+ bottom = down(box(b), 0)
571
+ weekly, usual = panel(bottom, 'Weekly pattern (last 4 weeks, hourly averages)'), panel(bottom, 'Now vs. normal (baselines)')
572
+ self.heat_metric = down(combo(weekly, ['CPU', 'Memory'], 12, self.analysis), 10, fill='none', anchor='w')
573
+ self.heat = down(Heatmap(weekly), 0, fill='both', expand=True)
574
+ self.anomalies = down(Table(usual, ['Metric', 'Last 10 min', 'Usual', 'Deviation', 'Baseline'], [110, 110, 160, 90], height=230), 0)
575
+ spread([weekly, usual], weights=(3, 2))
576
+ def tie(self, name, make, *args, keys=None, **kw):
577
+ """Factory for a form widget bound to an AutopilotConfig field; every change is stored."""
578
+ def create(parent):
579
+ if make is Entry:
580
+ w = Entry(parent, **kw)
581
+ w.bind('<FocusOut>', lambda e: self.store(), add='+')
582
+ w.bind('<Return>', lambda e: self.store())
583
+ self.binds.append((name, lambda: w.text().strip(), w.put))
584
+ else:
585
+ w = make(parent, *args, command=self.store, **kw)
586
+ self.binds.append((name, w.var.get, w.var.set) if make is check else (name, w.value, w.put) if make is Spin
587
+ else (name, lambda: keys[w.current()], lambda v: w.current(keys.index(v) if v in keys else 0)))
588
+ return w
589
+ return create
590
+ def attach(self, s):
591
+ self.s = s
592
+ if s:
593
+ self.loading = True
594
+ for name, _, put in self.binds: put(getattr(s.cfg.autopilot, name))
595
+ self.loading = False
596
+ def store(self):
597
+ if self.loading or not self.s: return
598
+ c = copy.deepcopy(self.s.cfg)
599
+ for name, get, _ in self.binds: setattr(c.autopilot, name, type(getattr(c.autopilot, name))(get()))
600
+ if c.autopilot != self.s.cfg.autopilot: self.save(c)
601
+ def analysis(self):
602
+ s, a, t, hi = self.s, self.s.an, self.t, self.heat_metric.current()
603
+ self.health.set(a.health, str(a.health), 'grade ' + a.grade, health(a.health))
604
+ self.reasons.config(text=('\n'.join(a.reasons) or 'No deductions — everything looks healthy.')
605
+ + (f'\n\nAnalyzed {time.strftime("%H:%M:%S", time.localtime(a.when))}' if a.when else ''))
606
+ if a.disk_full_days >= 0:
607
+ t[0].set(duration(a.disk_full_days * 86400), f'+{a.disk_slope_per_day:.2f} pts/day · {a.disk_basis}',
608
+ C.red if a.disk_full_days < 7 else C.amber if a.disk_full_days < 30 else None)
609
+ else:
610
+ t[0].set('Not filling', f'trend {a.disk_slope_per_day:.2f} pts/day' if a.disk_basis else 'needs ~2 h of history', C.green)
611
+ if a.mem_trend_r2 > 0:
612
+ t[1].set(f'{a.mem_slope_per_hour:+.2f} pts/h', f'fit R² {a.mem_trend_r2:.2f}', C.amber if a.mem_slope_per_hour > 1 and a.mem_trend_r2 > .8 else None)
613
+ else:
614
+ t[1].set('—', 'needs ~90 min of history')
615
+ if a.cpu30.count: t[2].set(f'{pct(a.cpu30.p95, 0)} / {pct(a.mem30.p95, 0)}', f'avg {pct(a.cpu30.avg, 0)} / {pct(a.mem30.avg, 0)}')
616
+ else: t[2].set('—', 'collecting')
617
+ for tile, up, off in zip(t[3:], a.up, a.down):
618
+ if up != up: tile.set('—', 'no data yet')
619
+ else: tile.set(pct(up, 0 if up >= 99.995 else 2), f'≈ {duration(off)} offline', C.green if up >= 99.9 else C.amber if up >= 99 else C.red)
620
+ self.capacity.config(text='\n\n'.join('• ' + c for c in a.capacity))
621
+ self.heat.set(a.heat[hi], a.heat_n, '% memory' if hi else '% CPU', C.violet if hi else C.accent)
622
+ self.anomalies.set([[x.metric, X(fmt_metric(x.hm, x.now), right=True), X(f'{fmt_metric(x.hm, x.mean)} ± {fmt_metric(x.hm, x.sd)}', C.muted, True),
623
+ X(f'{x.z:+.1f}σ', C.red if abs(x.z) >= 3 else C.amber if abs(x.z) >= 2 else C.green, True), X(x.baseline, C.muted)]
624
+ for x in a.anomalies])
625
+
626
+ for w in self.findings.winfo_children(): # rebuild the finding cards
627
+ w.destroy()
628
+ if not a.findings:
629
+ down(label(self.findings, '✓ No problems found in the history. The analyzer checks disk forecasts, memory trends, leaks, runaway processes, '
630
+ 'service failures, overload and anomalies every minute.', wrap=True, fg=C.green), 0)
631
+ ap = s.cfg.autopilot
632
+ for f in a.findings:
633
+ color = severity(f.severity)
634
+ card = down(tk.Frame(self.findings, bg=C.card, highlightthickness=1, highlightbackground=C.border), 10)
635
+ right(tk.Frame(card, bg=color, width=4), 0)
636
+ if f.action:
637
+ b = button(card, f.label, kind='Danger' if f.action == 'kill_pid' else 'Primary')
638
+ b.config(command=lambda f=f, b=b: self.fix(f, b))
639
+ b.pack(side='right', padx=12)
640
+ text = right(box(card), 0, True, padx=12, pady=10)
641
+ down(label(text, f'{f.severity.upper()} · {f.category.upper()}', fg=color, font=F(11, True)), 2)
642
+ down(label(text, f.title, wrap=True, font=F(14, True)), 2)
643
+ down(label(text, f.detail, wrap=True), 2)
644
+ down(label(text, '→ ' + f.advice, 'Muted', True), 0)
645
+ if f.auto and ap.enabled:
646
+ down(label(text, 'Autopilot (dry run) would act on this' if ap.dryRun else 'Autopilot handles this automatically', 'Small', fg=C.violet), 0)
647
+ def fix(self, f, b):
648
+ if ask(self, f.label, f'{f.label} on {self.s.cfg.name}?\n\n{f.title}', f.action == 'kill_pid'):
649
+ if b.winfo_exists(): # the card may have been rebuilt while the question was open
650
+ b.config(state='disabled', text='Working…')
651
+ self.s.run_finding(f, False, lambda code, out: b.winfo_exists() and b.config(text='✗ Failed' if code else '✓ Done'))
652
+
653
+ TABS = (('Overview', Overview), ('CPU', CpuTab), ('Memory', MemoryTab), ('Storage', StorageTab), ('Network', NetworkTab), ('Processes', ProcessTab),
654
+ ('Services', ServiceTab), ('History', HistoryTab), ('Insights & Autopilot', InsightsTab), ('Alert rules', RulesTab), ('Console', ConsoleTab))