diff --git a/.gitattributes b/.gitattributes index a6344aac8c09253b3b630fb776ae94478aa0275b..375dfaa3a3645bc4c4ae5eb90fa4aa0de2ce6984 100644 --- a/.gitattributes +++ b/.gitattributes @@ -33,3 +33,6 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text *.zip filter=lfs diff=lfs merge=lfs -text *.zst filter=lfs diff=lfs merge=lfs -text *tfevents* filter=lfs diff=lfs merge=lfs -text +*.msi filter=lfs diff=lfs merge=lfs -text +*.exe filter=lfs diff=lfs merge=lfs -text +*.deb filter=lfs diff=lfs merge=lfs -text diff --git a/README.md b/README.md new file mode 100644 index 0000000000000000000000000000000000000000..efe3ca34cb04e28a779274c3b71c7ef5d4fbaaf2 --- /dev/null +++ b/README.md @@ -0,0 +1,105 @@ +--- +tags: +- monitoring +- server +- qt +- python +- nodejs +--- + +# ServerMonitor + +A server status monitor in six stand-alone editions: three languages, each for Linux and for Windows. +It watches machines in detail (CPU, memory, disks, network, processes, services, temperatures, GPUs), keeps their +history from seconds to years, analyzes that history with plain statistics (no AI, nothing installed on the servers), +and keeps machines working with alert rules and an autopilot that can also run in "dry run" (report only). + +| Folder | Language / UI | Runs on and monitors | Code lines | +|---|---|---|---| +| `Server Monitor(cqt-linux)` | C++17, Qt 5 Widgets | Linux | 3,867 | +| `Server Monitor(cqt-window)` | C++17, Qt 5 Widgets | Windows | 3,873 | +| `Server Monitor(python-linux)` | Python 3, standard library only (tkinter) | Linux | 3,090 | +| `Server Monitor(python-window)` | Python 3, standard library only (tkinter) | Windows | 3,096 | +| `Server Monitor(web-linux)` | Node.js built-ins + plain browser JavaScript | Linux | 2,225 | +| `Server Monitor(web-window)` | Node.js built-ins + plain browser JavaScript | Windows | 2,214 | + +No third-party libraries are used: only Qt, the Python standard library, and Node's built-in modules. +Each edition monitors the machine it runs on and remote machines of the same OS over the system `ssh` client. +Within a language, the Linux and Windows editions are the same files except for one platform file +(`src/core/Platform.cpp`, `plat.py`, `core/platform.js` + collector script). + +All editions use the same `servers.json` and the same binary history files, so data can be copied between them. + +## Quick start + +| Edition | Start | +|---|---| +| `cqt-linux` | `./build.sh run` (needs Qt 5.15 development files and g++) | +| `cqt-window` | Qt command prompt: `build.bat`, then `build\release\ServerMonitor.exe` | +| `python-linux` | `./run.sh` (needs `python3-tk`) | +| `python-window` | `run.bat` | +| `web-linux` | `./run.sh`, then open `http://127.0.0.1:8765` | +| `web-window` | `run.bat`, then open `http://127.0.0.1:8765` | + +Each folder has its own README with details. Installers and packages for offline installation are in +[`requirements/`](requirements/README.md): Qt 5 for Ubuntu and for Windows (with compiler), Python with tkinter, Node.js. + +## What every edition does + +- **Servers:** add, edit, remove, reorder; "This computer" or SSH (key or password); test connection. +- **Dashboard:** a live card per server with gauges, sparkline, health grade and alert count; totals; recent events. +- **Server page:** Overview, CPU (per core, temperatures, GPUs), Memory, Storage, Network, Processes (end, kill, + priority), Services (start, stop, restart, enable, disable, logs), History, Insights & Autopilot, Alert rules, Console. +- **History:** every sample for 6 hours, minutes for 30 days, hours for 2 years, days for 20 years; downtime included; + min / average / 95th percentile / peak; CSV export. +- **Analysis every minute:** disk-full forecast, memory growth, leaking and runaway processes, failed or flapping + services, overload, swap thrashing, anomalies against the same weekday and hour, availability, capacity advice, + a health score with grade, and a weekly busy-hours heatmap. +- **Autopilot:** restarts failed services (with an hourly limit, never ones that were already failed when monitoring + started), lowers or ends runaway processes, optional disk cleanup; every action has a cooldown and is logged. +- **Alert rules:** "metric above/below a value for N seconds → severity → action", with events and `alerts.log`. + +## Test status + +Tested on Ubuntu 26.04 (x86-64). Tests never changed the test machine: scratch settings, autopilot in dry run, +no kill / restart / cleanup / reboot command was run for real. + +| Check | cqt | python | web | +|---|---|---|---| +| 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) | +| Windows edition, same click-through, fed with simulated Windows data | 34 / 34 | 47 / 47 | 36 / 36 + API all passed | +| Analysis on a synthetic 3-day history: same findings, same numbers, same autopilot decisions in all editions | yes | yes | yes | +| History files written by the C++ edition load in the other editions | — | yes | yes | +| No child process survives the app (normal stop and forced kill) | yes | yes | yes | +| Web only: wrong `Host` / `Origin`, missing header, path traversal, HTML injection through server data | — | — | all rejected | + +Each pair was also reviewed independently after it was written; the defects found (among them: a process selection +that could slide to another process, history buckets lost at restart, understated downtime) were fixed in all +editions and are covered by the tests above. + +**Not tested: real Windows.** No Windows machine was available. The Windows editions were run on Linux with a +stand-in for PowerShell, which exercises the parser, analysis and the whole UI, but **not** the PowerShell collector +script and not the Windows control commands; those were checked by careful reading only. Before relying on a Windows +edition, run the self-test on a Windows PC from this folder: + +``` +powershell -ExecutionPolicy Bypass -File windows-selftest.ps1 +``` + +It runs the collector once exactly the way the apps start it, checks every section of its output and the command +wrapper, changes nothing on the machine, and prints PASS / FAIL per check. + +Also not tested: a successful SSH session to a remote server (only a refused connection), `sudo` actions, GPUs and +temperature sensors (the test machine has none), runs longer than about 12 minutes, browsers other than Chrome. + +## Security notes + +- Saved SSH passwords are only lightly disguised in `servers.json` (file mode 600), not encrypted. Prefer keys. +- The web editions listen on `127.0.0.1` only and reject requests from other sites; the page can run commands on + your servers, so do not expose the port to a network. +- Control actions run as the user the app (or the SSH login) runs as. + +## For developers + +[`dev/`](dev/README.md) holds the shared specification all six editions follow, the two collector scripts, a stand-in +PowerShell for running the Windows editions on Linux, and the test scripts used above. diff --git a/Server Monitor(cqt-linux)/.gitignore b/Server Monitor(cqt-linux)/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..f0bb5faa29b568a9fea0a9119a999c787de9bbd1 --- /dev/null +++ b/Server Monitor(cqt-linux)/.gitignore @@ -0,0 +1,2 @@ +build/ +*.user diff --git a/Server Monitor(cqt-linux)/CMakeLists.txt b/Server Monitor(cqt-linux)/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..588c3b8a2c25295d439c14060e74442f99add1bf --- /dev/null +++ b/Server Monitor(cqt-linux)/CMakeLists.txt @@ -0,0 +1,9 @@ +cmake_minimum_required(VERSION 3.16) +project(ServerMonitor LANGUAGES CXX) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_AUTOMOC ON) +find_package(Qt5 5.15 REQUIRED COMPONENTS Widgets) +file(GLOB_RECURSE SRC CONFIGURE_DEPENDS src/*.cpp src/*.h) +add_executable(ServerMonitor ${SRC}) +target_include_directories(ServerMonitor PRIVATE src) +target_link_libraries(ServerMonitor PRIVATE Qt5::Widgets) diff --git a/Server Monitor(cqt-linux)/README.md b/Server Monitor(cqt-linux)/README.md new file mode 100644 index 0000000000000000000000000000000000000000..cbd9f2bd8e65f16763924cffbea9012290c31fc0 --- /dev/null +++ b/Server Monitor(cqt-linux)/README.md @@ -0,0 +1,61 @@ +# Server Monitor + +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`. + +## Build and run + +```bash +./build.sh run # build, then start (./build.sh = build only, ./build.sh clean) +``` + +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. + +## Servers + +Add or remove servers from the sidebar or the dashboard. There are two ways to connect: + +- **This machine:** no setup. +- **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. + +A small POSIX `sh` script (in `src/core/Platform.cpp`) reads `/proc` and `/sys` on the server. All calculations happen in the app. + +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. + +## Features + +- **Dashboard:** a live card per server (gauges, sparklines, health grade), totals across servers, and recent events. +- **Server tabs:** + - Overview, CPU (per core, temperatures, GPUs), Memory. + - Storage (usage, read/write speed, how busy each disk is), Network (per interface, TCP states). + - Processes (terminate, kill, suspend, resume, change priority), Services (start, stop, restart, enable, disable, logs). + - History, Insights & Autopilot, Alert rules, and a Console with quick checks, reboot and shut down. +- **History:** stored per server in `~/.config/ServerMonitor/ServerMonitor/history/`. + - Every sample kept 6 h; 1-minute averages and peaks kept 30 days; hourly kept 2 years; daily kept 20 years. + - Downtime is stored too, so availability is known. + - The History tab shows 1 h up to all time, with min / average / 95th percentile / peak and CSV export. +- **Analysis:** runs every minute using regression, means, standard deviations and percentiles. + - Disk-full forecast, steady memory growth, per-process leaks, runaway processes, failing or flapping services, overload, swap thrashing. + - Anomalies compared with the same weekday and hour over the last 8 weeks; availability; capacity advice. + - A health score (0–100, grade A–F) and a weekly busy-hours heatmap. +- **Autopilot:** acts on the findings, each type with its own setting. + - Restarts failed services, with a per-hour limit. Services already failed when monitoring started are left alone. + - Renices or terminates runaway processes, and handles leaking processes. + - Optional disk cleanup (off by default) and anomaly alerts. + - Every action has a cooldown and is logged; **dry run** only reports what it would do. +- **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`. + +## Code + +``` +src/core/Platform.* everything Linux-specific: collector script, its parser, control commands +src/core/Model.* config, rules, metrics, formatting +src/core/History.* history store + analyzer +src/core/Session.* ssh/local link, per-server session (rules, autopilot), manager +src/ui/Widgets.* theme, hand-painted widgets, small UI builders +src/ui/Tabs.cpp server detail tabs +src/ui/Windows.* dashboard, detail page, add/edit dialog, main window +``` + +The Windows edition (`Server Monitor(cqt-window)`) is the same code with a different `Platform.cpp`. + +Settings are in `~/.config/ServerMonitor/ServerMonitor/servers.json` (file mode 600). Saved SSH passwords are only lightly disguised, not encrypted, so prefer keys. diff --git a/Server Monitor(cqt-linux)/ServerMonitor.pro b/Server Monitor(cqt-linux)/ServerMonitor.pro new file mode 100644 index 0000000000000000000000000000000000000000..b401a6daf74a3d7abc0ecda704090525db96ae5f --- /dev/null +++ b/Server Monitor(cqt-linux)/ServerMonitor.pro @@ -0,0 +1,6 @@ +# Qt Creator / qmake project +QT += widgets +CONFIG += c++17 +INCLUDEPATH += src +SOURCES += $$files(src/*.cpp, true) +HEADERS += $$files(src/*.h, true) diff --git a/Server Monitor(cqt-linux)/build.sh b/Server Monitor(cqt-linux)/build.sh new file mode 100755 index 0000000000000000000000000000000000000000..65296d76654d71602b2fe18d4b800845d9555b13 --- /dev/null +++ b/Server Monitor(cqt-linux)/build.sh @@ -0,0 +1,35 @@ +#!/usr/bin/env bash +# Build Server Monitor with Qt 5: ./build.sh [run|clean] +# Uses system Qt 5 dev files (pkg-config Qt5Widgets) or a local SDK unpacked from +# the Ubuntu qtbase5-dev packages into ~/.local/share/qt5-sdk/root (no root needed). +set -euo pipefail +HERE="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"; B="$HERE/build" +[[ "${1:-}" == clean ]] && { rm -rf "$B"; echo cleaned; exit 0; } + +if pkg-config --exists Qt5Widgets 2>/dev/null; then + read -r -a QTF <<<"$(pkg-config --cflags Qt5Widgets)"; read -r -a QTL <<<"$(pkg-config --libs Qt5Widgets)" + MOC="$(pkg-config --variable=host_bins Qt5Core)/moc" +else + SDK="${QT5_SDK:-$HOME/.local/share/qt5-sdk/root}"; I="$SDK/usr/include/x86_64-linux-gnu/qt5" + [[ -d "$I/QtWidgets" ]] || { echo "Qt 5 headers missing. Install qtbase5-dev, or: mkdir -p ~/.local/share/qt5-sdk && cd ~/.local/share/qt5-sdk && + 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; } + 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++") + QTL=(-L/usr/lib/x86_64-linux-gnu -l:libQt5Widgets.so.5 -l:libQt5Gui.so.5 -l:libQt5Core.so.5) + MOC="$SDK/usr/lib/qt5/bin/moc" +fi +FLAGS=(-std=c++17 -O2 -fPIC -Wall -Wextra -Wno-unused-parameter -Wno-missing-field-initializers -DQT_NO_DEBUG "${QTF[@]}" -I"$HERE/src") +mkdir -p "$B/obj" +mapfile -t SRCS < <(find "$HERE/src" -name '*.cpp' | sort) +mapfile -t MOCH < <(grep -l Q_OBJECT -r "$HERE/src" --include='*.h') +for h in "${MOCH[@]}"; do # moc only what needs it + m="$B/obj/moc_$(basename "${h%.h}").cpp"; [[ "$m" -nt "$h" ]] || "$MOC" "$h" -o "$m"; SRCS+=("$m") +done +NEWEST_H=$(find "$HERE/src" -name '*.h' -printf '%T@\n' | sort -n | tail -1) +OBJS=() +for s in "${SRCS[@]}"; do + o="$B/obj/$(basename "${s%.cpp}").o"; OBJS+=("$o") + if [[ ! -f "$o" || "$s" -nt "$o" || $(stat -c %Y "$o") < ${NEWEST_H%.*} ]]; then echo " CXX ${s#$HERE/}"; g++ "${FLAGS[@]}" -c "$s" -o "$o" & fi +done +wait +g++ -o "$B/ServerMonitor" "${OBJS[@]}" "${QTL[@]}" -lpthread && echo "Done: $B/ServerMonitor" +[[ "${1:-}" == run ]] && exec "$B/ServerMonitor"; true diff --git a/Server Monitor(cqt-linux)/deploy/server-monitor.desktop b/Server Monitor(cqt-linux)/deploy/server-monitor.desktop new file mode 100644 index 0000000000000000000000000000000000000000..6ac99d72a3d9c9d2d570b8c580f0dcd001f360f8 --- /dev/null +++ b/Server Monitor(cqt-linux)/deploy/server-monitor.desktop @@ -0,0 +1,8 @@ +[Desktop Entry] +Type=Application +Name=Server Monitor +Comment=Monitor, analyze and control Linux servers +# Put the full path of the built program here, e.g. /opt/ServerMonitor/ServerMonitor +Exec=ServerMonitor +Terminal=false +Categories=System;Monitor; diff --git a/Server Monitor(cqt-linux)/src/core/History.cpp b/Server Monitor(cqt-linux)/src/core/History.cpp new file mode 100644 index 0000000000000000000000000000000000000000..900a01f6cddbf958d9ae6f930a84e9feffcfe907 --- /dev/null +++ b/Server Monitor(cqt-linux)/src/core/History.cpp @@ -0,0 +1,367 @@ +#include "History.h" +#include +#include +#include +#include +#include +#include + +const char *const hKeys[H_COUNT] = {"cpu", "iowait", "load", "mem", "swap", "disk", "diskio", "rx", "tx", "rd", "wr", "temp", "procs", "gpu", "failed"}; +const char *const hNames[H_COUNT] = {"CPU", "I/O wait", "Load (1m)", "Memory", "Swap", "Disk usage", "Disk busy", "Net download", + "Net upload", "Disk read", "Disk write", "Temperature", "Processes", "GPU", "Failed services"}; +QString tierName(Tier t) { return QStringList{"every sample", "1 minute", "1 hour", "1 day"}.value(int(t)); } +static const QByteArray kHeader = QByteArray("SMH1") + char(H_COUNT) + char(0) + char(sizeof(HPoint) & 0xff) + char(sizeof(HPoint) >> 8); + +// ---- accumulator ---------------------------------------------------------------- +HistoryStore::Acc::Acc(qint64 b) : bucket(b) { std::fill(mx, mx + H_COUNT, NAN); } +void HistoryStore::Acc::add(const HPoint &p) +{ + n += p.n, nUp += p.nUp; + if (p.nUp) + for (int i = 0; i < H_COUNT; ++i) + if (!std::isnan(p.avg[i])) { + sum[i] += double(p.avg[i]) * p.nUp, cnt[i] += p.nUp; + if (std::isnan(mx[i]) || p.max[i] > mx[i]) mx[i] = p.max[i]; + } +} +HPoint HistoryStore::Acc::point() const +{ + HPoint p; + p.ts = bucket, p.n = n, p.nUp = nUp; + for (int i = 0; i < H_COUNT; ++i) p.avg[i] = cnt[i] ? float(sum[i] / cnt[i]) : NAN, p.max[i] = mx[i]; + return p; +} + +// ---- store ---------------------------------------------------------------------- +QString HistoryStore::file(int t) const { return m_dir + "/" + QStringList{"raw", "minute", "hour", "day"}[t] + ".bin"; } +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 + +HistoryStore::HistoryStore(const QString &dir) : m_dir(dir), m_tz(QDateTime::currentDateTime().offsetFromUtc()) +{ + QDir().mkpath(dir); + const qint64 now = QDateTime::currentSecsSinceEpoch(); + for (int t = 0; t < 4; ++t) { + QFile f(file(t)); + if (!f.open(QIODevice::ReadOnly)) continue; + const QByteArray d = f.readAll(); + if (!d.startsWith(kHeader)) { f.close(), QFile::remove(f.fileName() + ".old"), f.rename(f.fileName() + ".old"); continue; } + int bad = int((d.size() - kHeader.size()) % sizeof(HPoint)); // a cut-off record would misalign everything appended after it + for (int off = kHeader.size(); off + int(sizeof(HPoint)) <= d.size(); off += sizeof(HPoint)) { + HPoint p; + std::memcpy(&p, d.constData() + off, sizeof p); + if (p.ts < now - keep[t] || p.ts > now + 86400 || (!m_t[t].isEmpty() && p.ts <= m_t[t].last().ts)) ++bad; + else m_t[t] << p; + } + if (bad) rewrite(t); + } + 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 + const qint64 stored = m_t[t].isEmpty() ? -1 : m_t[t].last().ts; + auto feed = [&](const HPoint &p) { + const qint64 b = bucketOf(t, p.ts); + if (b <= stored) return; + if (b != m_acc[t].bucket) { + if (m_acc[t].n) append(t, m_acc[t].point()); + m_acc[t] = Acc(b); + } + m_acc[t].add(p); + }; + for (const HPoint &p : qAsConst(m_t[t - 1])) feed(p); + if (m_acc[t - 1].n) feed(m_acc[t - 1].point()); + } +} + +void HistoryStore::rewrite(int t) +{ + QSaveFile f(file(t)); + if (!f.open(QIODevice::WriteOnly)) return; + f.write(kHeader); + f.write(reinterpret_cast(m_t[t].constData()), qint64(m_t[t].size()) * sizeof(HPoint)); + f.commit(); +} + +void HistoryStore::append(int t, const HPoint &p) +{ + auto &v = m_t[t]; + if (!v.isEmpty() && p.ts <= v.last().ts) return; + v << p; + QFile f(file(t)); + if (f.open(QIODevice::Append)) { + if (f.size() < kHeader.size()) f.resize(0), f.write(kHeader); + f.write(reinterpret_cast(&p), sizeof p); + } + if (++m_appends[t] % 500) return; // trim expired points now and then + const auto it = std::find_if(v.begin(), v.end(), [&](const HPoint &x) { return x.ts >= p.ts - keep[t]; }); + if (it != v.begin()) v.erase(v.begin(), it), rewrite(t); +} + +void HistoryStore::add(qint64 ts, const float *val, bool up) +{ + HPoint raw; + raw.ts = ts, raw.n = 1, raw.nUp = up; + for (int i = 0; i < H_COUNT; ++i) raw.avg[i] = raw.max[i] = up ? val[i] : NAN; + append(0, raw); + for (int t = 1; t < 4; ++t) { // every coarser tier accumulates every raw sample + const qint64 b = bucketOf(t, ts); + if (m_acc[t].bucket != b) { + if (m_acc[t].n && m_acc[t].bucket < b) append(t, m_acc[t].point()); + m_acc[t] = Acc(b); + } + m_acc[t].add(raw); + } +} + +QVector HistoryStore::range(qint64 from, qint64 to, Tier tier) const +{ + const int t = int(tier); + const auto &v = m_t[t]; + auto it = std::lower_bound(v.begin(), v.end(), from, [](const HPoint &p, qint64 x) { return p.ts < x; }); + QVector out; + for (; it != v.end() && it->ts <= to; ++it) out << *it; + const Acc &a = m_acc[t]; + if (t && a.n && a.bucket >= from && a.bucket <= to && (out.isEmpty() || out.last().ts < a.bucket)) out << a.point(); + return out; +} + +QVector HistoryStore::range(qint64 from, qint64 to, Tier *used) const +{ + const qint64 now = QDateTime::currentSecsSinceEpoch(), maxSpan[3] = {6 * 3600, 8 * 86400, 400 * 86400}; + int t = 0; + while (t < 3 && (from < now - keep[t] || to - from > maxSpan[t])) ++t; + if (used) *used = Tier(t); + return range(from, to, Tier(t)); +} + +void HistoryStore::removeFiles() { QDir(m_dir).removeRecursively(), *this = HistoryStore(m_dir); } +qint64 HistoryStore::firstTs() const +{ + qint64 f = 0; + for (const auto &v : m_t) + if (!v.isEmpty() && (!f || v[0].ts < f)) f = v[0].ts; + return f; +} +qint64 HistoryStore::diskBytes() const +{ + qint64 b = 0; + for (int t = 0; t < 4; ++t) b += QFileInfo(file(t)).size(); + return b; +} + +Stats stats(const QVector &pts, int m) +{ + Stats s; + QVector v; + double sum = 0, w = 0; + for (const HPoint &p : pts) { + if (!p.nUp || std::isnan(p.avg[m])) continue; + v << p.avg[m], sum += double(p.avg[m]) * p.nUp, w += p.nUp; + if (std::isnan(s.max) || p.max[m] > s.max) s.max = p.max[m]; + } + if (v.isEmpty()) return s; + std::sort(v.begin(), v.end()); + s.count = v.size(), s.avg = sum / w, s.min = v[0], s.p95 = v[qMin(v.size() - 1, int(v.size() * 0.95))]; + return s; +} + +QString fmtMetric(int m, double v) +{ + if (std::isnan(v)) return "—"; + switch (m) { + case H_RX: case H_TX: case H_RD: case H_WR: return Fmt::rate(v); + case H_LOAD: return QString::number(v, 'f', 2); + case H_TEMP: return Fmt::temp(v); + case H_PROCS: case H_FAILED: return QString::number(v, 'f', 0); + default: return Fmt::pct(v); + } +} + +// ---- analysis ------------------------------------------------------------------- +Analysis::Analysis() { std::fill(&heat[0][0][0], &heat[0][0][0] + 336, NAN); } + +double regression(const QVector &pts, int m, double *r2) +{ + double n = 0, sx = 0, sy = 0, sxx = 0, sxy = 0, syy = 0, x0 = pts.isEmpty() ? 0 : pts[0].ts; + for (const HPoint &p : pts) + if (p.nUp && !std::isnan(p.avg[m])) { + const double x = p.ts - x0, y = p.avg[m]; + n++, sx += x, sy += y, sxx += x * x, sxy += x * y, syy += y * y; + } + const double den = n * sxx - sx * sx, num = n * sxy - sx * sy, vy = n * syy - sy * sy; + *r2 = n >= 3 && den > 0 && vy > 1e-9 ? num * num / (den * vy) : 0; // squared correlation + return n >= 3 && den > 0 ? num / den : 0; +} + +Analysis analyze(const HistoryStore &st, const Metrics &m, const AutopilotConfig &ap, const QVector &procs, + const QVector &svcs, bool online) +{ + Analysis a; + const qint64 now = a.when = QDateTime::currentSecsSinceEpoch(); + const auto &minute = st.tier(Tier::Minute), &hour = st.tier(Tier::Hour); + auto add = [&](QString key, QString sev, QString cat, QString title, QString detail, QString advice, QString action = {}, + QString arg = {}, QString label = {}, bool autoOk = false) { + a.findings << Finding{key, sev, cat, title, detail, advice, action, arg, label, autoOk}; + }; + auto sev = [](bool crit, bool warn) { return crit ? "critical" : warn ? "warning" : "info"; }; + + // availability + const qint64 spans[3] = {86400, 7 * 86400, 30 * 86400}; + for (int i = 0; i < 3; ++i) { + double n = 0, up = 0; + for (const HPoint &p : st.range(now - spans[i], now)) n += p.n, up += p.nUp; + a.up[i] = n ? up * 100 / n : NAN; + a.down[i] = n ? (n - up) / n * qMin(spans[i], now - st.firstTs()) : 0; // share of the monitored part of the window + } + if (a.up[0] < 99) + add("avail24", sev(a.up[0] < 95, true), "Availability", QString("Availability last 24 h is %1").arg(Fmt::pct(a.up[0], 2)), + QString("The server could not be reached for about %1 in the last day.").arg(Fmt::duration(a.down[0])), + "Check network stability, power and whether the machine rebooted (uptime)."); + const auto w30 = st.range(now - spans[2], now, Tier::Hour), w7 = st.range(now - spans[1], now, Tier::Minute); + a.cpu30 = stats(w30.size() >= 24 ? w30 : w7, H_CPU), a.mem30 = stats(w30.size() >= 24 ? w30 : w7, H_MEM); + + // disk forecast: regression over 7 d of hours, or 24 h of minutes, whichever fits better + double r2 = 0, r2b = 0, slope = 0; + const auto week = st.range(now - spans[1], now, Tier::Hour), day = st.range(now - 86400, now, Tier::Minute); + if (week.size() >= 48) slope = regression(week, H_DISK, &r2), a.diskBasis = "hourly averages, last 7 days"; + if (day.size() >= 120) { + const double s2 = regression(day, H_DISK, &r2b); + if (week.size() < 48 || r2b > r2) slope = s2, r2 = r2b, a.diskBasis = "minute averages, last 24 hours"; + } + a.diskSlopePerDay = slope * 86400; + if (a.diskSlopePerDay > 0.05 && r2 >= 0.3 && m.maxDiskPct > 0) a.diskFullDays = (100 - m.maxDiskPct) / a.diskSlopePerDay; + if (a.diskFullDays >= 0 && a.diskFullDays < 30) + add("diskfull", sev(a.diskFullDays < ap.diskForecastDays, a.diskFullDays < 14), "Disk", + QString("Disk %1 will be full in %2").arg(m.fullestMount, Fmt::duration(a.diskFullDays * 86400)), + 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), + "Clean logs/caches, rotate or move data, or grow the volume.", "disk_cleanup", "", "Run cleanup", ap.diskCleanup && a.diskFullDays < ap.diskForecastDays); + if (m.maxDiskPct >= ap.diskCleanupAt) + add("diskhigh", sev(m.maxDiskPct >= 97, true), "Disk", QString("Disk %1 is %2 full").arg(m.fullestMount, Fmt::pct(m.maxDiskPct)), + QString("Above the cleanup threshold of %1.").arg(Fmt::pct(ap.diskCleanupAt, 0)), "Free space soon: services fail when the disk is full.", + "disk_cleanup", "", "Run cleanup", ap.diskCleanup); + + // whole-machine memory trend over 6 h + const auto six = st.range(now - 6 * 3600, now, Tier::Minute); + if (six.size() >= 90) { + a.memSlopePerHour = regression(six, H_MEM, &a.memTrendR2) * 3600; + const double left = (100 - m.memPct) / qMax(0.01, a.memSlopePerHour); + if (a.memSlopePerHour > 1 && a.memTrendR2 > 0.8 && m.memPct > 40) + add("memtrend", sev(false, left < 12), "Memory", QString("Memory keeps growing (+%1 points/hour)").arg(a.memSlopePerHour, 0, 'f', 1), + 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)), + "Look for a leaking process (Processes tab, sort by RSS)."); + } + + // processes: leaks and runaways + for (const ProcTrend &p : procs) { + if (p.kernel) continue; + const QString who = QString("%1 (PID %2)").arg(p.name).arg(p.pid), pid = QString::number(p.pid); + if (p.minutesTracked >= 30 && p.rssGrowthPct >= 25 && p.rssGrowth >= 100e6 && p.rssMonotonic >= 0.8) + add("leak:" + pid, sev(m.memPct >= ap.leakMemPressure, true), "Process", "Possible memory leak: " + who, + 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)) + .arg(p.minutesTracked).arg(qRound(p.rssMonotonic * 100)).arg(Fmt::bytes(p.rssNow)), + "Restart the program/service at a quiet time and report the leak upstream.", "kill_pid", pid, "Terminate", + ap.leakMode == "terminate" && m.memPct >= ap.leakMemPressure); + if (p.highCpuMinutes >= ap.runawayMinutes) { + const bool term = ap.runawayMode == "terminate"; + add("runaway:" + pid, "warning", "Process", "Runaway process: " + who, + 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), + "Lower its priority (renice) or stop it if it is stuck.", term ? "kill_pid" : "renice", pid, term ? "Terminate" : "Renice to 19", ap.runawayMode != "none"); + } + } + + // services: failures and flapping + for (const ServiceTrend &s : svcs) { + const bool flap = s.failsLastHour >= 3 || s.autoRestartsLastHour >= ap.maxRestartsPerHour; + if (s.failedNow) + add("svc:" + s.unit, sev(flap, true), "Service", QString(flap ? "Service %1 keeps failing" : "Service %1 has failed").arg(s.unit), + s.preexisting ? "It was already failed when monitoring started, so the autopilot leaves it alone (it may be failed on purpose)." + : QString("Failed %1× in the last hour; autopilot restarted it %2×.").arg(s.failsLastHour).arg(s.autoRestartsLastHour), + flap ? "Automatic restarts were stopped. Read the logs (Services tab → Logs) and fix the cause." : "Restart it and check the logs.", + "restart_service", s.unit, "Restart", ap.restartFailed && !s.preexisting && s.autoRestartsLastHour < ap.maxRestartsPerHour); + else if (s.failsLastHour >= 3) + add("flap:" + s.unit, "warning", "Service", QString("Service %1 is unstable").arg(s.unit), + QString("It failed %1 times within the last hour.").arg(s.failsLastHour), "Inspect its logs and resource limits."); + } + + // overload and swap thrashing + const auto last15 = st.range(now - 900, now, Tier::Minute); + 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; + if (online && load15 / m.cpuCount > 1.5) + 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), + QString("15-minute average load is %1× the number of cores; tasks are waiting for CPU.").arg(load15 / m.cpuCount, 0, 'f', 1), + "Find the busiest processes, spread work over time, or add CPU."); + 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 + 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)) + : QString("Swap %1 used, memory %2 full and disks %3 busy.").arg(Fmt::pct(m.swapPct), Fmt::pct(m.memPct), Fmt::pct(busy15)), + "Stop memory-hungry processes or add RAM."); + + // anomalies: last 10 min vs same weekday+hour over 8 weeks (fallback: last 24 h) + const auto raw = st.range(now - 600, now, Tier::Raw); + const QDateTime lt = QDateTime::fromSecsSinceEpoch(now); + if (online && raw.size() >= 10) + 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}, + {H_IOWAIT, 3.0, false}, {H_RX, 256e3, true}, {H_TX, 256e3, true}}) { + if (hm == H_IOWAIT && !P::posixCpu) continue; + const double cur = stats(raw, hm).avg; + QVector v; + for (const HPoint &p : hour) { + const QDateTime t = QDateTime::fromSecsSinceEpoch(p.ts); + 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()) + v << p.avg[hm]; + } + QString basis = "same weekday & hour, last 8 weeks"; + if (v.size() < 3) { + v.clear(), basis = "last 24 hours"; + for (const HPoint &p : minute) + if (p.nUp && !std::isnan(p.avg[hm]) && now - p.ts <= 86400 && now - p.ts > 900) v << p.avg[hm]; + if (v.size() < 360) continue; + } + double mean = 0, var = 0; + for (double x : v) mean += x / v.size(); + for (double x : v) var += (x - mean) * (x - mean) / v.size(); + const double sd = std::sqrt(var), z = (cur - mean) / qMax(sd, floor); + a.anomalies << Anomaly{hNames[hm], basis, hm, cur, mean, sd, z}; + const bool hi = z >= ap.anomalyZ, lo = down && mean > 1e6 && cur < mean * 0.1; + if (ap.anomalyAlerts && (hi || lo)) + 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()), + 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), + hi ? "Check what changed: deploys, cron jobs, traffic, attacks." : "Traffic dropped sharply - check the service is still serving."); + } + + // weekly heatmaps from 4 weeks of hours + double sum[2][7][24] = {}; + for (const HPoint &p : hour) { + if (now - p.ts > 28 * 86400 || !p.nUp || std::isnan(p.avg[H_CPU])) continue; + const QDateTime t = QDateTime::fromSecsSinceEpoch(p.ts); + const int d = t.date().dayOfWeek() - 1, h = t.time().hour(), n = ++a.heatN[d][h]; + sum[0][d][h] += p.avg[H_CPU], sum[1][d][h] += std::isnan(p.avg[H_MEM]) ? 0 : p.avg[H_MEM]; + a.heat[0][d][h] = sum[0][d][h] / n, a.heat[1][d][h] = sum[1][d][h] / n; + } + + // capacity advice + 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"}, + {a.mem30, "Memory", 30.0, 85.0, "is under-used", "is tight - add RAM or reduce caches/limits"}}) + if (s.count >= 60) + a.capacity << QString("%1 %2 (p95 %3).").arg(name, s.p95 < lo ? loTxt : s.p95 > hi ? hiTxt : "headroom is healthy", Fmt::pct(s.p95)); + 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)); + else if (!a.diskBasis.isEmpty()) a.capacity << "Disk usage is stable."; + if (a.capacity.isEmpty()) a.capacity << "Collecting history - capacity advice appears after about an hour of data."; + + // health score + double score = 100, fp = 0; + auto pen = [&](bool when, double p, const QString &why) { + if (when && p > 0.5) score -= p, a.healthReasons << QString("−%1 %2").arg(qRound(p)).arg(why); + }; + const double cpu = std::isnan(cpu15) ? m.cpuUsage : cpu15; + for (const Finding &f : a.findings) fp += f.category == "Availability" ? 0 : f.severity == "critical" ? 15 : f.severity == "warning" ? 7 : 2; + pen(!online, 60, "server unreachable"); + pen(cpu > 70, qMin(24.0, (cpu - 70) * 0.8), "CPU busy (" + Fmt::pct(cpu) + ")"); + pen(m.memPct > 80, qMin(30.0, (m.memPct - 80) * 1.5), "memory high (" + Fmt::pct(m.memPct) + ")"); + pen(m.maxDiskPct > 80, qMin(40.0, (m.maxDiskPct - 80) * 2), "disk high (" + Fmt::pct(m.maxDiskPct) + ")"); + pen(m.swapPct > 50, 10, "heavy swap use"); + pen(m.maxTemp > 80, qMin(20.0, (m.maxTemp - 80) * 2), "hot (" + Fmt::temp(m.maxTemp) + ")"); + pen(a.up[0] < 100, qMin(30.0, (100 - a.up[0]) * 5), "downtime in last 24 h"); + pen(true, qMin(50.0, fp), QString("%1 finding(s)").arg(a.findings.size())); + a.health = qBound(0, qRound(score), 100); + a.grade = QString("FDCBA").at(a.health >= 90 ? 4 : a.health >= 75 ? 3 : a.health >= 60 ? 2 : a.health >= 40 ? 1 : 0); + auto rank = [](const QString &s) { return s == "critical" ? 0 : s == "warning" ? 1 : 2; }; + std::stable_sort(a.findings.begin(), a.findings.end(), [&](const Finding &x, const Finding &y) { return rank(x.severity) < rank(y.severity); }); + return a; +} diff --git a/Server Monitor(cqt-linux)/src/core/History.h b/Server Monitor(cqt-linux)/src/core/History.h new file mode 100644 index 0000000000000000000000000000000000000000..ead62778fe8acfa1c2ee1b7db37e33d7b945a72d --- /dev/null +++ b/Server Monitor(cqt-linux)/src/core/History.h @@ -0,0 +1,87 @@ +// Persistent multi-resolution history (raw 6 h, minute 30 d, hour 2 y, day 20 y) +// and the statistics-only analyzer that feeds the autopilot. +#pragma once +#include "Model.h" +#include + +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 }; +extern const char *const hKeys[H_COUNT], *const hNames[H_COUNT]; +enum class Tier { Raw, Minute, Hour, Day }; +QString tierName(Tier t); + +#pragma pack(push, 1) +struct HPoint { + qint64 ts = 0; // seconds; bucket start for aggregates + quint32 n = 0, nUp = 0; // samples / online samples + float avg[H_COUNT], max[H_COUNT]; + double uptimePct() const { return n ? nUp * 100.0 / n : 0; } +}; +#pragma pack(pop) + +class HistoryStore { +public: + static constexpr qint64 step[4] = {1, 60, 3600, 86400}, keep[4] = {6 * 3600, 30 * 86400, 732 * 86400, 7320LL * 86400}; + explicit HistoryStore(const QString &dir); + void add(qint64 ts, const float *v, bool up); // up=false records downtime only + const QVector &tier(Tier t) const { return m_t[int(t)]; } + QVector range(qint64 from, qint64 to, Tier t) const; // includes the open bucket + QVector range(qint64 from, qint64 to, Tier *used = nullptr) const; // finest tier covering it + void removeFiles(); + qint64 firstTs() const; + qint64 diskBytes() const; + +private: + struct Acc { + qint64 bucket = -1; + quint32 n = 0, nUp = 0, cnt[H_COUNT] = {}; + double sum[H_COUNT] = {}; + float mx[H_COUNT]; + Acc(qint64 b = -1); + void add(const HPoint &p); + HPoint point() const; + }; + qint64 bucketOf(int t, qint64 ts) const; + void append(int t, const HPoint &p); + void rewrite(int t); + QString file(int t) const; + QString m_dir; + QVector m_t[4]; + Acc m_acc[4]; + qint64 m_tz; + int m_appends[4] = {}; +}; + +struct Stats { double min = NAN, avg = NAN, p95 = NAN, max = NAN; int count = 0; }; // max = peak of max[] +Stats stats(const QVector &pts, int metric); + +// ---- analysis ------------------------------------------------------------------- +struct Finding { + QString key, severity, category, title, detail, advice, action, actionArg, actionLabel; // action: disk_cleanup|restart_service|renice|kill_pid + bool autoEligible = false; +}; +struct ProcTrend { + int pid = 0, minutesTracked = 0; + QString name, user; + double cpuNow = 0, highCpuMinutes = 0, rssNow = 0, rssGrowth = 0, rssGrowthPct = 0, rssMonotonic = 0; + bool kernel = false; +}; +struct ServiceTrend { QString unit; bool failedNow = false, preexisting = false; int failsLastHour = 0, autoRestartsLastHour = 0; }; +struct Anomaly { QString metric, baseline; int hm = 0; double now = 0, mean = 0, sd = 0, z = 0; }; +struct Analysis { + qint64 when = 0; + int health = 100; + QString grade = "A", diskBasis; + QStringList healthReasons, capacity; + QVector findings; + QVector anomalies; + double diskFullDays = -1, diskSlopePerDay = 0, memSlopePerHour = 0, memTrendR2 = 0; + double up[3] = {NAN, NAN, NAN}, down[3] = {}; // 24 h, 7 d, 30 d: availability %, seconds offline + Stats cpu30, mem30; + double heat[2][7][24]; // weekly pattern: 0 = CPU, 1 = memory + int heatN[7][24] = {}; + Analysis(); +}; +Analysis analyze(const HistoryStore &st, const Metrics &m, const AutopilotConfig &ap, const QVector &procs, + const QVector &svcs, bool online); +double regression(const QVector &pts, int metric, double *r2); // slope per second +QString fmtMetric(int metric, double v); diff --git a/Server Monitor(cqt-linux)/src/core/Model.cpp b/Server Monitor(cqt-linux)/src/core/Model.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d124e3b054e2e77444a315998afa5b6b1f5de433 --- /dev/null +++ b/Server Monitor(cqt-linux)/src/core/Model.cpp @@ -0,0 +1,128 @@ +#include "Model.h" +#include +#include +#include +#include + +// ---- formatting ------------------------------------------------------------- +QString Fmt::bytes(double b, int prec) +{ + static const char *u[] = {"B", "KB", "MB", "GB", "TB", "PB"}; + int i = 0; + for (; qAbs(b) >= 1024 && i < 5; ++i) b /= 1024; + return QString::number(b, 'f', i ? prec : 0) + " " + u[i]; +} +QString Fmt::count(double v) +{ + const double a = qAbs(v); + 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); +} +QString Fmt::duration(double sec) +{ + qint64 s = qint64(sec), d = s / 86400, h = s % 86400 / 3600, m = s % 3600 / 60; + 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); +} + +// ---- catalogues ------------------------------------------------------------- +const QVector &ruleMetrics() +{ + static const QVector d = {{"cpu", "CPU usage", "%"}, {"iowait", "CPU I/O wait", "%"}, {"load", "Load (1 min) per core", "%"}, + {"mem", "Memory usage", "%"}, {"swap", "Swap usage", "%"}, {"disk", "Fullest disk usage", "%"}, {"diskio", "Busiest disk utilisation", "%"}, + {"temp", "Hottest sensor", "°C"}, {"rx", "Network download", "MB/s"}, {"tx", "Network upload", "MB/s"}, {"failed", "Failed services", ""}, + {"procs", "Process count", ""}, {"gpu", "GPU usage (max)", "%"}, {"gputemp", "GPU temperature (max)", "°C"}}; + static const QVector noWait = d.mid(0, 1) + d.mid(2); + return P::posixCpu ? d : noWait; +} +QString defLabel(const QVector &d, const QString &k, bool unit) +{ + for (const Def &x : d) + if (x.key == k) return unit ? x.unit : x.label; + return unit ? QString() : k; +} + +QString Rule::conditionText() const +{ + const QString u = defLabel(ruleMetrics(), metric, true); + return QString("%1 %2 %3%4").arg(defLabel(ruleMetrics(), metric), op).arg(value).arg(u.isEmpty() ? "" : " " + u) + (duration ? QString(" for %1 s").arg(duration) : ""); +} +QString Rule::actionText() const { return defLabel(P::ruleActions(), action) + (arg.isEmpty() ? "" : ": " + arg); } + +// ---- JSON: one field list per struct drives both saving and loading --------------------------- +#define F(f) v(#f, x.f); +template 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) } +template 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) } +template static void each(AutopilotConfig &x, V v) +{ + F(enabled) F(dryRun) F(restartFailed) F(diskCleanup) F(anomalyAlerts) F(maxRestartsPerHour) F(runawayMinutes) F(diskForecastDays) + F(runawayCpu) F(diskCleanupAt) F(leakMemPressure) F(anomalyZ) F(runawayMode) F(leakMode) F(diskCleanupCommand) +} +#undef F +template static QJsonObject save(const T &c) +{ + QJsonObject o; + each(const_cast(c), [&](const char *k, const auto &f) { o[k] = QJsonValue::fromVariant(QVariant::fromValue(f)); }); + return o; +} +template static T load(const QJsonObject &o) +{ + T c; + each(c, [&](const char *k, auto &f) { if (o.contains(k)) f = o[k].toVariant().value>(); }); + return c; +} + +static QString xorB64(const QString &s, bool enc) // light obfuscation of secrets (NOT encryption) +{ + static const QByteArray k = "ServerMonitor/obfuscation/v1"; + QByteArray b = enc ? s.toUtf8() : QByteArray::fromBase64(s.toLatin1()); + for (int i = 0; i < b.size(); ++i) b[i] = char(b[i] ^ k[i % k.size()]); + return enc ? QString(b.toBase64()) : QString::fromUtf8(b); +} + +QJsonObject ServerConfig::toJson() const +{ + QJsonObject o = save(*this); + QJsonArray rs; + for (const Rule &r : rules) rs << save(r); + o["transport"] = int(transport), o["password"] = xorB64(password, true), o["rules"] = rs, o["autopilot"] = save(autopilot); + return o; +} + +ServerConfig ServerConfig::fromJson(const QJsonObject &o) +{ + ServerConfig c = load(o); + c.autopilot = load(o["autopilot"].toObject()); + if (o.contains("rules")) c.rules.clear(); + for (const auto &v : o["rules"].toArray()) c.rules << load(v.toObject()); + for (Rule &r : c.rules) + if (r.id.isEmpty()) r.id = newId(); + c.transport = o["transport"].toInt(1) == 0 ? Transport::Local : Transport::SSH; + c.password = xorB64(o["password"].toString(), false); + c.interval = qBound(1, c.interval, 300); + if (c.id.isEmpty()) c.id = newId(); + return c; +} + +QVector ServerConfig::defaultRules() +{ + QVector rs; + for (auto [m, v, d, s] : {std::tuple{"cpu", 90, 60, "warning"}, {"mem", 90, 60, "warning"}, {"swap", 80, 120, "warning"}, + {"disk", 90, 0, "critical"}, {"temp", 85, 30, "critical"}, {"load", 150, 120, "warning"}, {"failed", 0, 0, "warning"}}) { + Rule r; + r.id = newId(), r.metric = m, r.value = v, r.duration = d, r.severity = s; + rs << r; + } + return rs; +} +QString ServerConfig::newId() { return QUuid::createUuid().toString(QUuid::WithoutBraces).left(12); } +QString ServerConfig::address() const +{ + if (transport == Transport::Local) return "this machine"; + return (user.isEmpty() ? "" : user + "@") + host + (port != 22 ? QString(":%1").arg(port) : ""); +} + +double Metrics::gpuMax(bool t) const +{ + double v = 0; + for (const GpuInfo &g : gpus) v = qMax(v, t ? g.temp : g.util); + return v; +} diff --git a/Server Monitor(cqt-linux)/src/core/Model.h b/Server Monitor(cqt-linux)/src/core/Model.h new file mode 100644 index 0000000000000000000000000000000000000000..1e770def6a71b41063ff737b72918444b947996f --- /dev/null +++ b/Server Monitor(cqt-linux)/src/core/Model.h @@ -0,0 +1,118 @@ +// Data model: server config, rules, autopilot policy, parsed metrics, formatting. +#pragma once +#include "Platform.h" +#include +#include +#include +#include +#include + +namespace Fmt { +QString bytes(double b, int prec = 1); +inline QString rate(double b) { return bytes(b) + "/s"; } +inline QString pct(double p, int prec = 1) { return QString::number(p, 'f', prec) + "%"; } +inline QString temp(double c) { return QString::number(c, 'f', 0) + " °C"; } +QString count(double v); +QString duration(double s); +} + +enum class Transport { Local, SSH }; +inline QString transportName(Transport t) { return t == Transport::Local ? "Local" : "SSH"; } + +const QVector &ruleMetrics(); +QString defLabel(const QVector &d, const QString &k, bool unit = false); + +// "When for s -> ()" +struct Rule { + QString id, metric = "cpu", op = ">", action = "notify", arg, severity = "warning"; + bool enabled = true; + double value = 90; + int duration = 60, cooldown = 300; + QString conditionText() const; + QString actionText() const; +}; + +// History-driven automatic control (evaluated by the Analyzer every minute). +struct AutopilotConfig { + bool enabled = true, dryRun = false, restartFailed = true, diskCleanup = false, anomalyAlerts = true; + int maxRestartsPerHour = 3, runawayMinutes = 10, diskForecastDays = 3; + double runawayCpu = 90, diskCleanupAt = 92, leakMemPressure = 90, anomalyZ = 3; + QString runawayMode = "renice", leakMode = "notify"; // none|renice|terminate, none|notify|terminate + QString diskCleanupCommand = P::cleanup; +}; + +struct ServerConfig { + QString id, name, group, host, user, keyFile, password, notes; + Transport transport = Transport::SSH; + int port = 22, interval = P::interval; + bool useSudo = false, enabled = true; + QVector rules = defaultRules(); + AutopilotConfig autopilot; + QString address() const; + QJsonObject toJson() const; + static ServerConfig fromJson(const QJsonObject &o); + static QVector defaultRules(); + static QString newId(); +}; + +// ---- one parsed sample ------------------------------------------------------ +struct CoreStat { double usage = 0, mhz = 0; }; +struct MountInfo { QString device, type, mount; double total = 0, used = 0, avail = 0, pct = 0; }; +struct DiskIO { QString name; double readBps = 0, writeBps = 0, readIops = 0, writeIops = 0, util = 0, totalRead = 0, totalWritten = 0; }; +struct NetIf { + QString name, state; + int speed = -1; + bool virt = false; + double rxBps = 0, txBps = 0, rxPps = 0, txPps = 0, rxBytes = 0, txBytes = 0, errors = 0, drops = 0; +}; +struct ProcInfo { + int pid = 0, ppid = 0, threads = 0, nice = 0; + QString name, user; + QChar state; + double cpu = 0, memPct = 0, rss = 0, vsz = 0, age = 0; // cpu: % of one core +}; +struct ServiceInfo { QString unit, load, active, sub, description; }; +struct TempSensor { QString name; double celsius = 0; }; +struct GpuInfo { int index = 0; QString name; double util = 0, memUsed = 0, memTotal = 0, temp = 0, power = 0, fan = 0; }; + +struct Metrics { + bool valid = false; + qint64 timestamp = 0; + QString hostname, os, kernel, arch, cpuModel, virt; + int cpuCount = 0, loggedUsers = 0, procsRunning = 0, procsBlocked = 0, threadsTotal = 0, socketsUsed = 0; + int servicesFailed = 0, servicesRunning = 0; + double uptime = 0, load1 = 0, load5 = 0, load15 = 0; + double cpuUsage = 0, cpuUser = 0, cpuSystem = 0, cpuIowait = 0, cpuSteal = 0, cpuIrq = 0; + double ctxtPerSec = 0, intrPerSec = 0, forksPerSec = 0, avgMhz = 0; + double memTotal = 0, memFree = 0, memAvailable = 0, memUsed = 0, buffers = 0, cached = 0, shared = 0, slab = 0, dirty = 0; + double swapTotal = 0, swapUsed = 0, memPct = 0, swapPct = 0; + double diskReadBps = 0, diskWriteBps = 0, maxDiskPct = 0, maxDiskUtil = 0, netRxBps = 0, netTxBps = 0, maxTemp = 0; + QString fullestMount, busiestDisk; + QVector cores; + QVector mounts; + QVector disks; + QVector nets; + QMap tcp; // ESTABLISHED -> n + QVector procs; + QVector services; + QVector temps; + QVector gpus; + double gpuMax(bool temp) const; +}; + +// Turns raw collector frames into Metrics; keeps counters for rates. process() is in Platform.cpp. +class MetricsEngine { +public: + Metrics process(const QByteArray &raw, qint64 nowMs); + void reset() { *this = MetricsEngine(); } + +private: + double m_upt = 0; + QVector> m_cpu; + QHash> m_ctr; // misc counters: "stat", "disk:sda", "net:eth0" + QHash m_ticks; + QHash m_info; + QHash m_users; + QVector m_services; + QVector m_gpus; +}; diff --git a/Server Monitor(cqt-linux)/src/core/Platform.cpp b/Server Monitor(cqt-linux)/src/core/Platform.cpp new file mode 100644 index 0000000000000000000000000000000000000000..ae56a869147cdccd879921a2addd440dd3eaa751 --- /dev/null +++ b/Server Monitor(cqt-linux)/src/core/Platform.cpp @@ -0,0 +1,371 @@ +// Linux: POSIX sh collector (reads /proc and /sys), its parser, and the control commands. +#include "Model.h" +#include +#include +#include + +// One frame per interval: "@@SNAP_BEGIN", "@@S
" + raw lines, "@@SNAP_END". All maths happens in the parser. +static const char *const kCollector = R"SMSCRIPT( +sm_main() { +iv="${1:-2}" once="${2:-0}" n=0 +export LC_ALL=C +while :; do + echo "@@SNAP_BEGIN" + if [ $((n % 15)) -eq 0 ]; then + echo "@@S info" + echo "hostname=$(cat /proc/sys/kernel/hostname 2>/dev/null)" + echo "kernel=$(uname -r 2>/dev/null)" + echo "arch=$(uname -m 2>/dev/null)" + echo "os=$(sed -n 's/^PRETTY_NAME=//p' /etc/os-release 2>/dev/null | tr -d '"')" + echo "cpumodel=$(grep -m1 -E '^(model name|Hardware|Processor|cpu model)' /proc/cpuinfo 2>/dev/null | cut -d: -f2- | sed 's/^ *//')" + echo "clk=$(getconf CLK_TCK 2>/dev/null || echo 100)" + echo "page=$(getconf PAGESIZE 2>/dev/null || echo 4096)" + echo "virt=$(systemd-detect-virt 2>/dev/null || echo unknown)" + echo "@@S passwd"; cut -d: -f1,3 /etc/passwd 2>/dev/null + fi + echo "@@S uptime"; cat /proc/uptime + echo "@@S loadavg"; cat /proc/loadavg + echo "@@S stat" + grep -E '^(cpu|ctxt|processes|procs_)' /proc/stat + awk '/^intr/ {print "intr", $2}' /proc/stat + echo "@@S meminfo"; cat /proc/meminfo + echo "@@S netdev"; cat /proc/net/dev + echo "@@S netstate" + for i in /sys/class/net/*; do + [ -e "$i" ] || continue + echo "${i##*/} $(cat "$i/operstate" 2>/dev/null || echo unknown) $(cat "$i/speed" 2>/dev/null || echo -1)" + done + echo "@@S diskstats"; cat /proc/diskstats + echo "@@S df"; df -P -T -k 2>/dev/null || df -P -k 2>/dev/null + echo "@@S sockstat"; cat /proc/net/sockstat 2>/dev/null + echo "@@S tcp" + 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]}' + echo "@@S thermal" + for z in /sys/class/thermal/thermal_zone*; do + [ -r "$z/temp" ] && echo "$(cat "$z/type" 2>/dev/null)|$(cat "$z/temp" 2>/dev/null)" + done + for h in /sys/class/hwmon/hwmon*; do + [ -d "$h" ] || continue + hn=$(cat "$h/name" 2>/dev/null) + for t in "$h"/temp*_input; do + [ -r "$t" ] || continue + l=$(cat "${t%_input}_label" 2>/dev/null) + echo "$hn ${l:-${t##*/}}|$(cat "$t" 2>/dev/null)" + done + done + echo "@@S freq" + for c in /sys/devices/system/cpu/cpu[0-9]*; do + f=$(cat "$c/cpufreq/scaling_cur_freq" 2>/dev/null) && echo "${c##*/cpu} $f" + done + echo "@@S procs" + cat /proc/[0-9]*/stat 2>/dev/null | awk '{ + if (!match($0, /\(.*\)/)) next + comm = substr($0, RSTART + 1, RLENGTH - 2) + rest = substr($0, RSTART + RLENGTH + 1) + k = split(rest, r, " ") + if (k < 22) next + print $1, r[1], r[2], r[12] + r[13], r[17], r[18], r[20], r[21], r[22], comm + }' + echo "@@S uids"; ls -ln /proc 2>/dev/null | awk '$NF ~ /^[0-9]+$/ {print $NF, $3}' + if [ $((n % 5)) -eq 0 ]; then + echo "@@S services" + systemctl list-units --type=service --all --no-legend --no-pager --plain 2>/dev/null | head -n 600 + fi + if [ $((n % 3)) -eq 0 ] && command -v nvidia-smi >/dev/null 2>&1; then + echo "@@S gpu" + 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 + fi + echo "@@S users"; who 2>/dev/null | wc -l + echo "@@SNAP_END" || exit 0 + [ "$once" = "once" ] && break + n=$((n + 1)) + sleep "$iv" +done +} +sm_main "$@" +)SMSCRIPT"; +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"; + +namespace P { +const char *const prioLabel = "Nice", *const kernelPrefix = "Linux ", + *const sshHint = "Uses your system ssh client; nothing is installed on the server. Set up key login once with ssh-copy-id user@host.", + *const cleanup = "journalctl --vacuum-time=7d 2>/dev/null; apt-get clean 2>/dev/null; dnf clean all 2>/dev/null; " + "find /tmp /var/tmp -xdev -type f -atime +7 -delete 2>/dev/null; true"; +const bool sudo = true, posixCpu = true; +const int interval = 2, normalPrio = 0; + +QStringList shell(int iv) { return iv ? QStringList{"sh", "-s", "--", QString::number(iv)} : QStringList{"sh", "-s"}; } +QByteArray collector(int) { return kCollector; } +QByteArray wrap(const QString &cmd, bool sudo) { return (sudo ? "sudo -n sh -c " + quote(cmd) : cmd).toUtf8() + "\n"; } +QString quote(QString s) { return "'" + s.replace("'", "'\\''") + "'"; } +QString command(const QString &action, const QString &arg) +{ + const QString n = QString::number(arg.toInt()); + return QHash{{"kill_pid", "kill -TERM " + n}, {"renice", "renice -n 19 -p " + n}, {"drop_caches", "sync && echo 3 > /proc/sys/vm/drop_caches"}, + {"restart_service", QString("systemctl reset-failed %1 2>/dev/null; systemctl restart %1").arg(quote(arg))}, {"restart_failed", kRestartFailed}}.value(action); +} +QString serviceLogs(const QString &unit, int lines) +{ + 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); +} +QString power(bool reboot) { return QString("(sleep 2; systemctl %1) >/dev/null 2>&1 &").arg(reboot ? "reboot" : "poweroff"); } +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 + +const QVector &ruleActions() +{ + static const QVector d = {{"notify", "Notify only", ""}, {"restart_failed", "Restart failed services", ""}, + {"restart_service", "Restart a service", "nginx.service"}, {"kill_top_cpu", "Terminate top CPU process", ""}, + {"kill_top_mem", "Terminate top memory process", ""}, {"drop_caches", "Sync + drop page cache", ""}, + {"command", "Run a command", "find /tmp -mtime +7 -delete"}}; + return d; +} +const QVector &procActions() +{ + static const QVector d = {{"Terminate", "kill -TERM %1"}, {"Kill", "kill -KILL %1", true}, {"Hang up", "kill -HUP %1", false, true, false}, + {"Suspend", "kill -STOP %1"}, {"Resume", "kill -CONT %1", false, false}}; + return d; +} +const QVector &priorities() +{ + static const QVector d = {{"-20 (highest)", "renice -n -20 -p %1"}, {"-10", "renice -n -10 -p %1"}, {"0 (normal)", "renice -n 0 -p %1"}, + {"10", "renice -n 10 -p %1"}, {"19 (lowest)", "renice -n 19 -p %1"}}; + return d; +} +const QVector &serviceActions() +{ + static const QVector d = {{"Start", "systemctl start %1", false, false}, {"Stop", "systemctl stop %1", true}, {"Restart", "systemctl restart %1"}, + {"Reload", "systemctl reload %1", false, false}, {"Enable", "systemctl enable %1", false, false}, {"Disable", "systemctl disable %1", true}}; + return d; +} +const QVector &diagnostics() +{ + static const QVector 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"}, + {"Memory", "free -h; echo; vmstat 1 3"}, {"Top CPU processes", "ps -eo pid,user,pcpu,pmem,rss,etime,comm --sort=-pcpu | head -n 20"}, + {"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"}, + {"Errors in journal", "journalctl -p err -n 60 --no-pager"}, {"Failed services", "systemctl --failed --no-pager"}, + {"Logged-in users", "w"}, {"Last reboots", "last -x reboot shutdown 2>/dev/null | head -n 15"}}; + return d; +} +const QVector &systemActions() +{ + static const QVector d = {{"Sync + drop page cache", "sync && echo 3 > /proc/sys/vm/drop_caches && echo done"}, {"Vacuum journal to 200 MB", "journalctl --vacuum-size=200M"}, + {"Clean package cache", "(apt-get clean || dnf clean all || yum clean all) 2>&1"}, {"Restart failed services", QString(kRestartFailed) + "; echo done"}, + {"Reboot", "(sleep 2; systemctl reboot) >/dev/null 2>&1 & echo 'reboot scheduled'", true}, + {"Shut down", "(sleep 2; systemctl poweroff) >/dev/null 2>&1 & echo 'shutdown scheduled'", true}}; + return d; +} +} // namespace P + +// ---- collector frame parser ---------------------------------------------------------------- +Metrics MetricsEngine::process(const QByteArray &raw, qint64 now) +{ + QHash> sec; + QList *cur = nullptr; + for (const QByteArray &l : raw.split('\n')) { + if (l.startsWith("@@S ")) cur = &sec[QString(l.mid(4).trimmed())]; + else if (cur && !l.startsWith("@@")) cur->append(l); + } + auto F = [](const QByteArray &l) { return l.simplified().split(' '); }; + auto L = [&](const char *k) { return sec.value(k); }; + auto first = [&](const char *k) { const auto v = L(k); return v.isEmpty() ? QList() : F(v[0]); }; + Metrics m; + m.timestamp = now; + for (const auto &l : L("info")) { + const int e = l.indexOf('='); + if (e > 0) m_info[l.left(e)] = QString::fromUtf8(l.mid(e + 1)).trimmed(); + } + if (sec.contains("passwd")) { + m_users.clear(); + for (const auto &l : L("passwd")) { + const int c = l.lastIndexOf(':'); + if (c > 0) m_users[l.mid(c + 1).toInt()] = l.left(c); + } + } + m.hostname = m_info["hostname"], m.os = m_info["os"], m.kernel = m_info["kernel"], m.arch = m_info["arch"]; + m.cpuModel = m_info["cpumodel"], m.virt = m_info["virt"]; + const int clk = qMax(1, m_info.value("clk", "100").toInt()), page = qMax(512, m_info.value("page", "4096").toInt()); + const auto la = first("loadavg"); + m.load1 = la.value(0).toDouble(), m.load5 = la.value(1).toDouble(), m.load15 = la.value(2).toDouble(); + m.uptime = first("uptime").value(0).toDouble(); + if (m.uptime <= 0) return m; + const double dt = m_upt > 0 ? m.uptime - m_upt : 0; + const bool rates = dt > 0.05; + QHash> next; + auto delta = [&](const QString &key, const QVector &v) { // per-second rates of a counter vector + QVector d(v.size(), 0.0); + const auto p = m_ctr.value(key); + if (rates && p.size() == v.size()) + for (int i = 0; i < v.size(); ++i) d[i] = qMax(0.0, (v[i] - p[i]) / dt); + next[key] = v; + return d; + }; + + // CPU + QVector> cpu; + QVector st(3); + for (const auto &l : L("stat")) { + const auto f = F(l); + if (f[0].startsWith("cpu")) { + QVector t; + for (int i = 1; i <= 8; ++i) t << f.value(i).toDouble(); + cpu << t; + } else if (f[0] == "ctxt") st[0] = f.value(1).toDouble(); + else if (f[0] == "intr") st[1] = f.value(1).toDouble(); + else if (f[0] == "processes") st[2] = f.value(1).toDouble(); + else if (f[0] == "procs_running") m.procsRunning = f.value(1).toInt(); + else if (f[0] == "procs_blocked") m.procsBlocked = f.value(1).toInt(); + } + m.cpuCount = qMax(1, cpu.size() - 1); + m.cores.resize(m.cpuCount); + double jiffies = 0; + if (rates && m_cpu.size() == cpu.size()) + for (int i = 0; i < cpu.size(); ++i) { + double d[8], tot = 0; + for (int k = 0; k < 8; ++k) tot += d[k] = cpu[i][k] - m_cpu[i][k]; + if (tot <= 0) continue; + auto p = [&](int k) { return qBound(0.0, d[k] * 100 / tot, 100.0); }; // user nice system idle iowait irq softirq steal + const double use = qBound(0.0, 100 - p(3) - p(4), 100.0); + if (i) m.cores[i - 1].usage = use; + 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); + } + m_cpu = cpu; + const auto sd = delta("stat", st); + m.ctxtPerSec = sd[0], m.intrPerSec = sd[1], m.forksPerSec = sd[2]; + int nf = 0; + for (const auto &l : L("freq")) { + const auto f = F(l); + const int i = f.value(0).toInt(); + if (i >= 0 && i < m.cores.size()) m.avgMhz += m.cores[i].mhz = f.value(1).toDouble() / 1000, ++nf; + } + m.avgMhz = nf ? m.avgMhz / nf : 0; + + // memory + QHash mi; + for (const auto &l : L("meminfo")) { + const int c = l.indexOf(':'); + if (c > 0) mi[l.left(c)] = F(l.mid(c + 1)).value(0).toDouble() * 1024; + } + m.memTotal = mi["MemTotal"], m.memFree = mi["MemFree"], m.buffers = mi["Buffers"], m.cached = mi["Cached"] + mi["SReclaimable"]; + m.memAvailable = mi.contains("MemAvailable") ? mi["MemAvailable"] : m.memFree + m.buffers + m.cached; + m.shared = mi["Shmem"], m.slab = mi["Slab"], m.dirty = mi["Dirty"], m.swapTotal = mi["SwapTotal"]; + m.memUsed = qMax(0.0, m.memTotal - m.memAvailable), m.swapUsed = qMax(0.0, m.swapTotal - mi["SwapFree"]); + m.memPct = m.memTotal > 0 ? m.memUsed * 100 / m.memTotal : 0; + m.swapPct = m.swapTotal > 0 ? m.swapUsed * 100 / m.swapTotal : 0; + + // network + static const QRegularExpression virt("^(lo|veth|docker|br-|virbr|cni|flannel|cali|vxlan|kube|tun|tap)"); + QHash> state; + for (const auto &l : L("netstate")) state[F(l)[0]] = F(l); + for (const auto &l : L("netdev")) { + const int c = l.indexOf(':'); + const auto f = F(l.mid(c + 1)); + if (c <= 0 || f.size() < 16) continue; + NetIf n; + n.name = l.left(c).trimmed(); + n.virt = virt.match(n.name).hasMatch(); + n.state = state[n.name].value(1, "unknown"), n.speed = state[n.name].value(2, "-1").toInt(); + n.rxBytes = f[0].toDouble(), n.txBytes = f[8].toDouble(); + n.errors = f[2].toDouble() + f[10].toDouble(), n.drops = f[3].toDouble() + f[11].toDouble(); + const auto d = delta("net:" + n.name, {n.rxBytes, n.txBytes, f[1].toDouble(), f[9].toDouble()}); + n.rxBps = d[0], n.txBps = d[1], n.rxPps = d[2], n.txPps = d[3]; + if (!n.virt) m.netRxBps += n.rxBps, m.netTxBps += n.txBps; + m.nets << n; + } + 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; }); + static const QStringList tcpNames = {"", "ESTABLISHED", "SYN_SENT", "SYN_RECV", "FIN_WAIT1", "FIN_WAIT2", "TIME_WAIT", "CLOSE", "CLOSE_WAIT", "LAST_ACK", "LISTEN", "CLOSING"}; + for (const auto &l : L("tcp")) m.tcp[tcpNames.value(F(l)[0].toInt(nullptr, 16), "?")] += F(l).value(1).toInt(); + for (const auto &l : L("sockstat")) + if (l.startsWith("sockets:")) m.socketsUsed = F(l).value(2).toInt(); + + // disks: whole devices + device-mapper; totals over physical disks only + static const QRegularExpression whole("^(sd[a-z]+|vd[a-z]+|xvd[a-z]+|hd[a-z]+|nvme\\d+n\\d+|mmcblk\\d+|md\\d+)$"); + for (const auto &l : L("diskstats")) { + const auto f = F(l); + if (f.size() < 14) continue; + DiskIO d; + d.name = f[2]; + const bool w = whole.match(d.name).hasMatch(); + if (!w && !d.name.startsWith("dm-")) continue; + d.totalRead = f[5].toDouble() * 512, d.totalWritten = f[9].toDouble() * 512; + const auto r = delta("disk:" + d.name, {f[3].toDouble(), d.totalRead, f[7].toDouble(), d.totalWritten, f[12].toDouble()}); + d.readIops = r[0], d.readBps = r[1], d.writeIops = r[2], d.writeBps = r[3], d.util = qMin(100.0, r[4] / 10); + if (w && !d.name.startsWith("md")) { + m.diskReadBps += d.readBps, m.diskWriteBps += d.writeBps; + if (d.util >= m.maxDiskUtil) m.maxDiskUtil = d.util, m.busiestDisk = d.name; + } + m.disks << d; + } + static const QSet skipFs = {"tmpfs", "devtmpfs", "squashfs", "overlay", "efivarfs", "ramfs", "proc", "sysfs", "autofs", + "nsfs", "devfs", "cgroup", "cgroup2", "fuse.snapfuse", "fuse.portal"}; + const auto df = L("df"); + const int b = !df.isEmpty() && df[0].contains("Type") ? 1 : 0; + QSet seen; + for (int i = 1; i < df.size(); ++i) { + const auto f = F(df[i]); + if (f.size() < 6 + b) continue; + MountInfo mt; + mt.device = f[0], mt.type = b ? f[1] : QByteArray(); + mt.total = f[1 + b].toDouble() * 1024, mt.used = f[2 + b].toDouble() * 1024, mt.avail = f[3 + b].toDouble() * 1024; + mt.mount = f.mid(5 + b).join(' '); + const QString key = mt.device + QString::number(mt.total); + if (skipFs.contains(b ? mt.type : mt.device) || mt.total <= 0 || mt.mount.startsWith("/snap/") || (mt.device.startsWith('/') && seen.contains(key))) continue; + seen << key; + mt.pct = mt.used + mt.avail > 0 ? mt.used * 100 / (mt.used + mt.avail) : 0; + if (mt.pct >= m.maxDiskPct) m.maxDiskPct = mt.pct, m.fullestMount = mt.mount; + m.mounts << mt; + } + + // processes: "pid state ppid ticks nice threads start vsize rss comm..." + QHash uid; + for (const auto &l : L("uids")) uid[F(l)[0].toInt()] = F(l).value(1).toInt(); + QHash ticks; + const double perCore = jiffies > 0 ? jiffies / m.cpuCount : rates ? dt * clk : 0; + for (const auto &l : L("procs")) { + const auto f = l.split(' '); + ProcInfo p; + if (f.size() < 10 || (p.pid = f[0].toInt()) <= 0) continue; + p.state = f[1].isEmpty() ? '?' : f[1][0]; + p.ppid = f[2].toInt(), p.nice = f[4].toInt(), p.threads = f[5].toInt(); + p.age = qMax(0.0, m.uptime - f[6].toDouble() / clk), p.vsz = f[7].toDouble(), p.rss = f[8].toDouble() * page; + p.name = QString::fromUtf8(f.mid(9).join(' ')); + ticks[p.pid] = f[3].toDouble(); + 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); + p.memPct = m.memTotal > 0 ? p.rss * 100 / m.memTotal : 0; + p.user = uid.contains(p.pid) ? m_users.value(uid[p.pid], QString::number(uid[p.pid])) : "?"; + m.threadsTotal += p.threads; + m.procs << p; + } + 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; }); + + // services / GPUs arrive every few samples: keep the last list + if (sec.contains("services")) { + m_services.clear(); + for (const auto &l : L("services")) { + const auto f = F(l); + 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(' '))}; + } + } + m.services = m_services; + for (const auto &s : m.services) m.servicesFailed += s.active == "failed", m.servicesRunning += s.sub == "running"; + if (sec.contains("gpu")) { + m_gpus.clear(); + for (const auto &l : L("gpu")) { + const auto f = l.split(','); + auto n = [&](int i) { return f[i].trimmed().toDouble(); }; + 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)}; + } + } + m.gpus = m_gpus; + QSet tn; + for (const auto &l : L("thermal")) { + const int bar = l.lastIndexOf('|'); + TempSensor t{QString::fromUtf8(l.left(bar)).trimmed(), l.mid(bar + 1).toDouble() / 1000}; + if (bar <= 0 || t.celsius <= 0 || t.celsius > 150 || tn.contains(t.name)) continue; + tn << t.name, m.temps << t, m.maxTemp = qMax(m.maxTemp, t.celsius); + } + m.loggedUsers = first("users").value(0).toInt(); + + m_ctr = next, m_ticks = ticks, m_upt = m.uptime; + m.valid = rates; // the first sample has no rates yet + return m; +} diff --git a/Server Monitor(cqt-linux)/src/core/Platform.h b/Server Monitor(cqt-linux)/src/core/Platform.h new file mode 100644 index 0000000000000000000000000000000000000000..2df02dc28a4462bcfd3d5c8eb6e8d5f1b008ec24 --- /dev/null +++ b/Server Monitor(cqt-linux)/src/core/Platform.h @@ -0,0 +1,25 @@ +// Everything that depends on the operating system of the monitored machines: how to start a shell, the +// collector script with its parser (MetricsEngine::process), and the control commands. Linux and Windows +// editions differ only in Platform.cpp. +#pragma once +#include +#include + +struct Def { QString key, label, unit; }; // rule metric / action catalogue +struct Cmd { QString label, cmd; bool danger = false, confirm = true, button = true; }; // cmd: %1 = pid or quoted name + +namespace P { +extern const char *const prioLabel, *const kernelPrefix, *const sshHint, *const cleanup; // cleanup: default disk cleanup command +extern const bool sudo, posixCpu; // "sudo -n" exists; CPU time has I/O wait + steal +extern const int interval, normalPrio; // default sample interval (s); priority value of an ordinary process +QStringList shell(int interval = 0); // argv of a shell that runs a script from stdin (interval > 0: collector arguments) +QByteArray collector(int interval); // stdin for the collector +QByteArray wrap(const QString &cmd, bool sudo); // stdin for a one-shot command +QString quote(QString s); // shell quoting +QString command(const QString &action, const QString &arg); // kill_pid | renice | restart_service | restart_failed | drop_caches +QString serviceLogs(const QString &unit, int lines); +QString power(bool reboot); +bool isProtected(int pid, int ppid, double rss, const QString &name); // never killed automatically, no leak / runaway findings +const QVector &ruleActions(); // unit = argument hint ("" = none) +const QVector &procActions(), &priorities(), &serviceActions(), &diagnostics(), &systemActions(); +} diff --git a/Server Monitor(cqt-linux)/src/core/Session.cpp b/Server Monitor(cqt-linux)/src/core/Session.cpp new file mode 100644 index 0000000000000000000000000000000000000000..afd54dd3a321f81fb876747c93c1be4bf86974b8 --- /dev/null +++ b/Server Monitor(cqt-linux)/src/core/Session.cpp @@ -0,0 +1,448 @@ +#include "Session.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// ---- Link --------------------------------------------------------------------------------- +Link::Link(const ServerConfig &c, QObject *parent) : QObject(parent), m_c(c) {} +Link::~Link() +{ + for (QProcess *p : findChildren()) { + p->disconnect(this); + if (p->state() != QProcess::NotRunning) p->kill(), p->waitForFinished(500); + } +} + +QProcess *Link::spawn(const QStringList &shell) +{ + auto *p = new QProcess(this); + QStringList a; + if (m_c.transport == Transport::Local) { + p->setProgram(shell[0]), p->setArguments(shell.mid(1)); + } else { + for (const char *o : {"ConnectTimeout=10", "ServerAliveInterval=10", "ServerAliveCountMax=3", "StrictHostKeyChecking=accept-new", "LogLevel=ERROR"}) a << "-o" << o; + auto env = QProcessEnvironment::systemEnvironment(); + if (m_c.password.isEmpty()) a << "-o" << "BatchMode=yes"; + else { // our own executable answers ssh's password prompt (see main.cpp) + a << "-o" << "NumberOfPasswordPrompts=1"; + env.insert("SSH_ASKPASS", QDir::toNativeSeparators(QCoreApplication::applicationFilePath())); + env.insert("SSH_ASKPASS_REQUIRE", "force"); + env.insert("SERVERMONITOR_ASKPASS", m_c.password); + if (!env.contains("DISPLAY")) env.insert("DISPLAY", ":0"); + } + p->setProcessEnvironment(env); + if (!m_c.keyFile.isEmpty()) a << "-i" << (m_c.keyFile.startsWith("~/") ? QDir::homePath() + m_c.keyFile.mid(1) : m_c.keyFile); + if (m_c.port != 22) a << "-p" << QString::number(m_c.port); + p->setProgram("ssh"), p->setArguments(a << "-T" << (m_c.user.isEmpty() ? m_c.host : m_c.user + "@" + m_c.host) << shell.join(' ')); + } + return p; +} +// Started only after the signals are connected: on Windows a failed start is reported inside start(). +static void feed(QProcess *p, const QByteArray &input) +{ + p->start(); + if (p->state() != QProcess::NotRunning) p->write(input), p->closeWriteChannel(); +} + +void Link::start() +{ + QProcess *p = spawn(P::shell(m_c.interval)); + connect(p, &QProcess::readyReadStandardOutput, this, [this, p] { + m_buf += p->readAllStandardOutput(); + for (int end; (end = m_buf.indexOf("@@SNAP_END")) >= 0;) { + const int begin = m_buf.lastIndexOf("@@SNAP_BEGIN", end); + if (begin >= 0) emit snapshot(m_buf.mid(begin, end - begin)); + m_buf.remove(0, end + 10); + } + if (m_buf.size() > 8 << 20) m_buf.clear(); + }); + connect(p, &QProcess::readyReadStandardError, this, [this, p] { m_err = (m_err + p->readAllStandardError()).right(4096); }); + connect(p, QOverload::of(&QProcess::finished), this, [this](int code) { + const QStringList l = QString(m_err).split('\n', Qt::SkipEmptyParts); + emit disconnected(l.isEmpty() ? QString("connection closed (exit code %1)").arg(code) : l.last()); + }); + connect(p, &QProcess::errorOccurred, this, [this, p](QProcess::ProcessError e) { + if (e == QProcess::FailedToStart) emit disconnected("cannot start " + p->program() + ": " + p->errorString()); + }); + feed(p, P::collector(m_c.interval)); +} + +int Link::exec(const QByteArray &input, int timeoutMs) +{ + const int id = m_next++; + QProcess *p = spawn(P::shell()); + p->setProcessChannelMode(QProcess::MergedChannels); + QTimer::singleShot(timeoutMs, p, [p] { p->kill(); }); + connect(p, QOverload::of(&QProcess::finished), this, [this, p, id](int code, QProcess::ExitStatus st) { + emit execFinished(id, st == QProcess::CrashExit ? -1 : code, p->readAll() + (st == QProcess::CrashExit ? "\n[killed or timed out]" : "")); + p->deleteLater(); + }); + connect(p, &QProcess::errorOccurred, this, [this, p, id](QProcess::ProcessError e) { + if (e == QProcess::FailedToStart) emit execFinished(id, -1, p->errorString()), p->deleteLater(); + }, Qt::QueuedConnection); // queued: the caller has to learn the id first + feed(p, input); + return id; +} + +// ---- live history ----------------------------------------------------------------------- +QString statusName(Status s) { return QStringList{"Disabled", "Connecting", "Online", "Offline"}.value(int(s)); } + +void Live::push(const Metrics &m) +{ + const int cap = 1800, n = t.size() + 1; + auto add = [&](QVector &v, double x) { + if (v.size() < n - 1) v.insert(0, n - 1 - v.size(), 0.0); // align series that appeared later + v << x; + if (v.size() > cap) v.remove(0, v.size() - cap); + }; + t << m.timestamp; + if (t.size() > cap) t.remove(0, t.size() - cap); + const double vals[N] = {m.cpuUsage, m.cpuUser, m.cpuSystem + m.cpuIrq, m.cpuIowait, m.cpuSteal, m.memPct, + m.memTotal > 0 ? (m.cached + m.buffers) * 100 / m.memTotal : 0, m.swapPct, m.netRxBps, m.netTxBps, + m.diskReadBps, m.diskWriteBps, m.load1}; + for (int i = 0; i < N; ++i) add(s[i], vals[i]); + for (const NetIf &i : m.nets) add(ifRx[i.name], i.rxBps), add(ifTx[i.name], i.txBps); +} + +// ---- session ---------------------------------------------------------------------------- +ServerSession::ServerSession(const ServerConfig &c, QObject *parent) : QObject(parent), m_cfg(c), m_store(ServerManager::configDir() + "/history/" + c.id) +{ + m_retry.setSingleShot(true), m_watchdog.setSingleShot(true); + connect(&m_retry, &QTimer::timeout, this, &ServerSession::start); + connect(&m_watchdog, &QTimer::timeout, this, [this] { onLost("no data received (timeout)"); }); + connect(&m_analysisTimer, &QTimer::timeout, this, &ServerSession::analyzeNow); + connect(&m_offlineTick, &QTimer::timeout, this, [this] { // downtime -> availability: one sample per interval, like uptime + if (m_status == Status::Offline || (m_status == Status::Connecting && m_retries)) record(false); + }); + m_analysisTimer.start(60000), m_offlineTick.start(c.interval * 1000); + QTimer::singleShot(3000, this, &ServerSession::analyzeNow); +} +ServerSession::~ServerSession() { stop(); } + +void ServerSession::setConfig(const ServerConfig &c) +{ + const bool reconnect = c.transport != m_cfg.transport || c.host != m_cfg.host || c.port != m_cfg.port || c.user != m_cfg.user || + c.keyFile != m_cfg.keyFile || c.password != m_cfg.password || c.interval != m_cfg.interval || c.enabled != m_cfg.enabled; + m_cfg = c, m_offlineTick.setInterval(c.interval * 1000); + if (reconnect) m_live = Live(), m_m = Metrics(), m_procs.clear(), m_svcs.clear(), c.enabled ? start() : stop(); // may be another machine now + emit updated(); +} + +void ServerSession::drop(const QString &why) +{ + if (m_link) m_link->disconnect(this), m_link->deleteLater(); + m_link = nullptr; + for (const Done &d : std::exchange(m_pending, {})) d(-1, why); +} + +void ServerSession::start() +{ + drop("connection restarted"); + m_retry.stop(); + if (!m_cfg.enabled) return setStatus(Status::Disabled); + m_engine.reset(), m_m.valid = false; // online() only again with a fresh sample + m_link = new Link(m_cfg, this); + connect(m_link, &Link::snapshot, this, &ServerSession::onFrame); + connect(m_link, &Link::disconnected, this, &ServerSession::onLost); + connect(m_link, &Link::execFinished, this, [this](int id, int code, const QString &out) { if (Done d = m_pending.take(id)) d(code, out); }); + setStatus(Status::Connecting), m_watchdog.start(25000), m_link->start(); +} + +void ServerSession::stop() +{ + m_retry.stop(), m_watchdog.stop(), drop("connection stopped"); + setStatus(m_cfg.enabled ? Status::Offline : Status::Disabled); +} + +void ServerSession::setStatus(Status s, const QString &err) +{ + if (!err.isEmpty() || s == Status::Online) m_err = err; + if (s != m_status) m_status = s, emit updated(); +} + +void ServerSession::onFrame(const QByteArray &raw) +{ + const qint64 now = QDateTime::currentMSecsSinceEpoch(); + m_watchdog.start(qMax(15, m_cfg.interval * 5 + 10) * 1000); + Metrics m = m_engine.process(raw, now); + if (m.uptime <= 0) return; + if (m_status != Status::Online) { + m_retries = 0; + if (std::exchange(m_offlineAlerted, false)) raise("resolved", "Server is back online"); + setStatus(Status::Online); + } + if (!m.valid || m_paused) return; // first sample has no rates yet + if (m.uptime < m_m.uptime) m_procs.clear(); // rebooted: PIDs start again, old trends would be blamed on new processes + const bool first = !m_m.valid; // first sample of this connection: analyze at once, the last analysis saw "unreachable" + m_m = m, m_live.push(m), record(true), track(now), evaluateRules(); + if (first) analyzeNow(); + emit updated(); +} + +void ServerSession::onLost(const QString &why) +{ + m_watchdog.stop(), drop("connection lost: " + why); + const bool was = m_status == Status::Online; + setStatus(Status::Offline, why); + if ((was || m_retries == 1) && !m_offlineAlerted) raise("critical", "Server is unreachable: " + why), m_offlineAlerted = true; + if (m_cfg.enabled) m_retry.start(QVector{3, 5, 10, 20, 30, 60}[qMin(m_retries++, 5)] * 1000); // back-off +} + +void ServerSession::exec(const QString &cmd, bool privileged, Done done, int timeoutMs) +{ + if (!m_link || m_status != Status::Online) { + if (done) QTimer::singleShot(0, this, [done] { done(-1, "server is not connected"); }); + return; + } + const int id = m_link->exec(P::wrap(cmd, privileged && m_cfg.useSudo), timeoutMs); + if (done) m_pending[id] = done; +} + +double ServerSession::metricValue(const QString &k) const +{ + const Metrics &m = m_m; + const QHash v = {{"cpu", m.cpuUsage}, {"iowait", m.cpuIowait}, {"load", m.load1 * 100 / qMax(1, m.cpuCount)}, + {"mem", m.memPct}, {"swap", m.swapPct}, {"disk", m.maxDiskPct}, {"diskio", m.maxDiskUtil}, {"temp", m.maxTemp}, + {"rx", m.netRxBps / 1e6}, {"tx", m.netTxBps / 1e6}, {"failed", double(m.servicesFailed)}, {"procs", double(m.procs.size())}, + {"gpu", m.gpuMax(false)}, {"gputemp", m.gpuMax(true)}}; + return v.value(k); +} + +QStringList ServerSession::activeAlerts() const +{ + QStringList out; + if (m_status == Status::Offline) out << "Unreachable: " + m_err; + for (const Rule &r : m_cfg.rules) + if (m_rules.value(r.id).active) out << r.conditionText(); + return out; +} + +void ServerSession::raise(const QString &sev, const QString &msg) { emit alertRaised({QDateTime::currentDateTime(), m_cfg.name, sev, msg}); } + +void ServerSession::record(bool up) +{ + const Metrics &m = m_m; + const float v[H_COUNT] = {float(m.cpuUsage), float(m.cpuIowait), float(m.load1), float(m.memPct), m.swapTotal > 0 ? float(m.swapPct) : NAN, + m.mounts.isEmpty() ? NAN : float(m.maxDiskPct), float(m.maxDiskUtil), float(m.netRxBps), float(m.netTxBps), + float(m.diskReadBps), float(m.diskWriteBps), m.temps.isEmpty() ? NAN : float(m.maxTemp), float(m.procs.size()), + m.gpus.isEmpty() ? NAN : float(m.gpuMax(false)), float(m.servicesFailed)}; + m_store.add(QDateTime::currentSecsSinceEpoch(), v, up); +} + +// per-process CPU streaks + RSS per minute; service failure transitions +void ServerSession::track(qint64 now) +{ + QHash procs; + for (const ProcInfo &p : qAsConst(m_m.procs)) { + ProcTrack t = m_procs.value(p.pid); + if (t.name != p.name) t = ProcTrack{p.name}; // new or pid reused + t.kernel = P::isProtected(p.pid, p.ppid, p.rss, p.name); + t.highSince = p.cpu < m_cfg.autopilot.runawayCpu ? 0 : t.highSince ? t.highSince : now; + if (now - t.lastMinute >= 60000) t.lastMinute = now, t.rss << p.rss; + if (t.rss.size() > 60) t.rss.removeFirst(); + procs[p.pid] = t; + } + m_procs = procs; + QHash svcs; + for (const ServiceInfo &s : qAsConst(m_m.services)) { + SvcTrack &t = svcs[s.unit] = m_svcs.value(s.unit); + const bool failed = s.active == "failed"; + if (t.last.isEmpty()) t.preexisting = failed; // failed before monitoring started: leave it alone + else if (failed && t.last != "failed") t.fails << now, t.preexisting = false; + else if (!failed) t.preexisting = false; + t.last = s.active; + for (auto *v : {&t.fails, &t.restarts}) + while (!v->isEmpty() && now - v->first() > 3600000) v->removeFirst(); + } + if (!svcs.isEmpty()) m_svcs = svcs; // forgets removed services; a sample without a service list changes nothing +} + +void ServerSession::evaluateRules() +{ + const qint64 now = QDateTime::currentMSecsSinceEpoch(); + for (const Rule &r : qAsConst(m_cfg.rules)) { + RuleState &st = m_rules[r.id]; + if (!r.enabled || ((r.metric == "gpu" || r.metric == "gputemp") && m_m.gpus.isEmpty()) || (r.metric == "temp" && m_m.temps.isEmpty())) { + st = {}; + continue; + } + const double v = metricValue(r.metric); + const QString now1 = QString::number(v, 'f', 1); + if (r.op == "<" ? v >= r.value : v <= r.value) { + if (st.active) raise("resolved", QString("Recovered: %1 (now %2)").arg(r.conditionText(), now1)); + st = {}; + continue; + } + if (!st.since) st.since = now; + if (now - st.since < r.duration * 1000LL) continue; + if (st.active && (r.action == "notify" || now - st.lastFire < r.cooldown * 1000LL)) continue; + const QString unit = defLabel(ruleMetrics(), r.metric, true); + if (!st.active) raise(r.severity, QString("%1 (now %2%3)").arg(r.conditionText(), now1, unit.isEmpty() ? "" : " " + unit)); + st.active = true, st.lastFire = now; + if (r.action == "notify") continue; + QString action = r.action, arg = r.arg; + if (action.startsWith("kill_top")) { // heaviest user process, never a protected one + const ProcInfo *best = nullptr; + for (const ProcInfo &p : m_m.procs) + 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; + if (!best) continue; + action = "kill_pid", arg = QString::number(best->pid); + } + run(action, arg, QString("Automation \"%1\": %2").arg(r.conditionText(), r.actionText())); + } +} + +void ServerSession::run(const QString &action, const QString &arg, const QString &what, Done done) +{ + const QString cmd = action == "command" ? arg : action == "disk_cleanup" ? m_cfg.autopilot.diskCleanupCommand : P::command(action, arg); + if (cmd.isEmpty()) return done ? done(-1, "nothing to do") : void(); + exec(cmd, true, [=](int code, const QString &out) { + const QString tail = out.simplified().right(300); // one line: events are lines in alerts.log + raise("action", what + " -> " + (code ? QString("failed (%1)").arg(code) : "OK") + (tail.isEmpty() ? "" : " | " + tail)); + if (done) done(code, out); + }, 300000); +} + +void ServerSession::runFinding(const Finding &f, bool automatic, Done done) +{ + if (automatic && f.action == "restart_service") m_svcs[f.actionArg].restarts << QDateTime::currentMSecsSinceEpoch(); + run(f.action, f.action == "disk_cleanup" ? QString() : f.actionArg, (automatic ? "Autopilot: " : "Manual fix: ") + f.actionLabel + " (" + f.title + ")", done); +} + +void ServerSession::analyzeNow() +{ + const qint64 now = QDateTime::currentMSecsSinceEpoch(); + QVector procs; + for (const ProcInfo &p : qAsConst(m_m.procs)) { + const ProcTrack t = m_procs.value(p.pid); + ProcTrend pt{p.pid, int(t.rss.size()), p.name, p.user, p.cpu, t.highSince ? (now - t.highSince) / 60000.0 : 0, p.rss}; + pt.kernel = t.kernel; + if (t.rss.size() >= 2) { + int grew = 0; + for (int i = 1; i < t.rss.size(); ++i) grew += t.rss[i] > t.rss[i - 1]; + pt.rssGrowth = t.rss.last() - t.rss[0], pt.rssGrowthPct = t.rss[0] > 0 ? pt.rssGrowth * 100 / t.rss[0] : 0; + pt.rssMonotonic = double(grew) / (t.rss.size() - 1); + } + if (pt.highCpuMinutes > 0 || pt.minutesTracked >= 30) procs << pt; + } + QVector svcs; + for (auto it = m_svcs.cbegin(); it != m_svcs.cend(); ++it) + if (it->last == "failed" || !it->fails.isEmpty()) svcs << ServiceTrend{it.key(), it->last == "failed", it->preexisting, int(it->fails.size()), int(it->restarts.size())}; + m_an = analyze(m_store, m_m, m_cfg.autopilot, procs, svcs, online()); + + QSet keys; // announce each new finding once + for (const Finding &f : qAsConst(m_an.findings)) + if (keys << f.key, !m_reported.contains(f.key) && f.category != "Availability") raise(f.severity, "Insight: " + f.title + " - " + f.detail); + m_reported = keys; + + const AutopilotConfig &ap = m_cfg.autopilot; // act on eligible findings, with cooldowns; a dry run says once what it would do + QSet dry; + if (ap.enabled && online()) + for (const Finding &f : qAsConst(m_an.findings)) { + const qint64 cd = f.action == "disk_cleanup" ? 6 * 3600000LL : f.action == "restart_service" ? 120000 : 900000; + if (!f.autoEligible) continue; + if (ap.dryRun) { + if (dry << f.key, !m_dry.contains(f.key)) raise("action", "Autopilot (dry run) would: " + f.actionLabel + " - " + f.title); + } else if (now - m_cooldown.value(f.key) >= cd) m_cooldown[f.key] = now, runFinding(f, true); + } + m_dry = dry; + emit analysisUpdated(); +} + +void ServerSession::deleteHistory() +{ + m_store.removeFiles(), m_an = Analysis(); + emit analysisUpdated(); +} + +// ---- manager ---------------------------------------------------------------------------- +QString ServerManager::configDir() +{ + static const QString d = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); + QDir().mkpath(d); + return d; +} + +ServerSession *ServerManager::session(const QString &id) const +{ + for (ServerSession *s : m_s) + if (s->config().id == id) return s; + return nullptr; +} + +ServerSession *ServerManager::attach(const ServerConfig &c) +{ + auto *s = new ServerSession(c, this); + connect(s, &ServerSession::alertRaised, this, [this](const AlertEvent &e) { + m_alerts.prepend(e); + m_alerts.resize(qMin(m_alerts.size(), 2000)); + QFile f(configDir() + "/alerts.log"); + if (f.size() > 5 << 20) f.resize(0); + if (f.open(QIODevice::Append | QIODevice::Text)) + QTextStream(&f) << e.time.toString(Qt::ISODate) << '\t' << e.severity << '\t' << e.serverName << '\t' << e.message << '\n'; + emit alertRaised(e); + }); + m_s << s; + return s; +} + +void ServerManager::load() +{ + QFile f(configDir() + "/servers.json"); + if (f.open(QIODevice::ReadOnly)) + for (const auto &v : QJsonDocument::fromJson(f.readAll())["servers"].toArray()) attach(ServerConfig::fromJson(v.toObject())); + else { // first start: monitor this machine + ServerConfig c; + c.id = ServerConfig::newId(), c.name = "This computer", c.group = "Local", c.transport = Transport::Local; + attach(c); + save(); + } + for (ServerSession *s : qAsConst(m_s)) s->start(); + emit listChanged(); +} + +void ServerManager::save() const +{ + QJsonArray a; + for (const ServerSession *s : m_s) a << s->config().toJson(); + QSaveFile f(configDir() + "/servers.json"); + if (f.open(QIODevice::WriteOnly)) f.write(QJsonDocument(QJsonObject{{"version", 1}, {"servers", a}}).toJson()), f.commit(); + QFile::setPermissions(f.fileName(), QFileDevice::ReadOwner | QFileDevice::WriteOwner); +} + +ServerSession *ServerManager::add(const ServerConfig &c) +{ + ServerSession *s = attach(c); + save(), s->start(); + emit listChanged(); + return s; +} + +void ServerManager::update(const ServerConfig &c) +{ + if (ServerSession *s = session(c.id)) s->setConfig(c), save(), emit listChanged(); +} + +void ServerManager::remove(const QString &id, bool deleteHistory) +{ + ServerSession *s = session(id); + if (!s) return; + m_s.removeOne(s); + s->disconnect(this), s->stop(); + if (deleteHistory) s->deleteHistory(), QDir(configDir() + "/history").rmdir(id); // the store keeps an empty folder + s->deleteLater(); + save(); + emit listChanged(); +} + +void ServerManager::move(const QString &id, int d) +{ + const int i = m_s.indexOf(session(id)), j = qBound(0, i + d, m_s.size() - 1); + if (i >= 0 && i != j) m_s.move(i, j), save(), emit listChanged(); +} diff --git a/Server Monitor(cqt-linux)/src/core/Session.h b/Server Monitor(cqt-linux)/src/core/Session.h new file mode 100644 index 0000000000000000000000000000000000000000..eb1c155289421a4ab33b7d8fd546a247618b2172 --- /dev/null +++ b/Server Monitor(cqt-linux)/src/core/Session.h @@ -0,0 +1,137 @@ +// Connection to one machine (local sh or system ssh), the per-server session +// (metrics, live history, rules, autopilot) and the manager of all sessions. +#pragma once +#include "History.h" +#include +#include +#include +#include +#include +#include +#include + +using Done = std::function; + +// Streams collector frames and runs one-shot commands. Deleting it kills everything. +class Link : public QObject { + Q_OBJECT +public: + Link(const ServerConfig &c, QObject *parent); + ~Link() override; + void start(); + int exec(const QByteArray &input, int timeoutMs); +signals: + void snapshot(const QByteArray &frame); + void disconnected(const QString &reason); + void execFinished(int id, int code, const QString &out); + +private: + QProcess *spawn(const QStringList &shell); // not started yet + ServerConfig m_c; + QByteArray m_buf, m_err; + int m_next = 1; +}; + +enum class Status { Disabled, Connecting, Online, Offline }; +QString statusName(Status s); +struct AlertEvent { QDateTime time; QString serverName, severity, message; }; // severity: info|warning|critical|resolved|action + +struct Live { // last hour in memory for the live charts + enum { CPU, USER, SYS, IOWAIT, STEAL, MEM, CACHE, SWAP, RX, TX, RD, WR, LOAD, N }; + QVector t; + QVector s[N]; + QHash> ifRx, ifTx; + void push(const Metrics &m); +}; + +class ServerSession : public QObject { + Q_OBJECT +public: + ServerSession(const ServerConfig &c, QObject *parent); + ~ServerSession() override; + const ServerConfig &config() const { return m_cfg; } + void setConfig(const ServerConfig &c); + Status status() const { return m_status; } + QString lastError() const { return m_err; } + const Metrics &metrics() const { return m_m; } + const Live &live() const { return m_live; } + bool online() const { return m_status == Status::Online && m_m.valid; } + bool isPaused() const { return m_paused; } + void setPaused(bool p) { m_paused = p, emit updated(); } + void start(); + void stop(); + void reconnect() { m_retries = 0, m_paused = false, start(); } + // privileged + "useSudo" wraps the command in sudo -n + void exec(const QString &cmd, bool privileged, Done done = {}, int timeoutMs = 60000); + double metricValue(const QString &key) const; + QStringList activeAlerts() const; + const HistoryStore &store() const { return m_store; } + const Analysis &analysis() const { return m_an; } + void analyzeNow(); + void runFinding(const Finding &f, bool automatic, Done done = {}); + void deleteHistory(); +signals: + void updated(); + void analysisUpdated(); + void alertRaised(const AlertEvent &e); + +private: + void setStatus(Status s, const QString &err = {}); + void drop(const QString &why); // closes the link and fails the commands that wait for it + void onFrame(const QByteArray &raw); + void onLost(const QString &why); + void record(bool up); + void track(qint64 now); + void evaluateRules(); + void run(const QString &action, const QString &arg, const QString &what, Done done = {}); + void raise(const QString &sev, const QString &msg); + + ServerConfig m_cfg; + Status m_status = Status::Disabled; + QString m_err; + QPointer m_link; + MetricsEngine m_engine; + Metrics m_m; + Live m_live; + QTimer m_retry, m_watchdog, m_analysisTimer, m_offlineTick; + int m_retries = 0; + bool m_paused = false, m_offlineAlerted = false; + QHash m_pending; + HistoryStore m_store; + Analysis m_an; + QSet m_reported, m_dry; + QHash m_cooldown; + struct RuleState { qint64 since = 0, lastFire = 0; bool active = false; }; + QHash m_rules; + struct ProcTrack { QString name; qint64 highSince = 0, lastMinute = 0; QVector rss; bool kernel = false; }; + QHash m_procs; + struct SvcTrack { QString last; bool preexisting = false; QVector fails, restarts; }; + QHash m_svcs; +}; + +class ServerManager : public QObject { + Q_OBJECT +public: + using QObject::QObject; + ~ServerManager() override { qDeleteAll(m_s); } + static QString configDir(); + void load(); + void save() const; + const QVector &sessions() const { return m_s; } + ServerSession *session(const QString &id) const; + ServerSession *add(const ServerConfig &c); + void update(const ServerConfig &c); + void remove(const QString &id, bool deleteHistory); + void move(const QString &id, int delta); + const QVector &alerts() const { return m_alerts; } + void clearAlerts() { m_alerts.clear(), emit alertsCleared(); } +signals: + void listChanged(); + void alertRaised(const AlertEvent &e); + void alertsCleared(); + +private: + ServerSession *attach(const ServerConfig &c); + QVector m_s; + QVector m_alerts; +}; diff --git a/Server Monitor(cqt-linux)/src/main.cpp b/Server Monitor(cqt-linux)/src/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3080d6443322bc98ba4cff8a15c90283e273470e --- /dev/null +++ b/Server Monitor(cqt-linux)/src/main.cpp @@ -0,0 +1,31 @@ +// Server Monitor - entry point. +#include "ui/Widgets.h" +#include "ui/Windows.h" +#include +#include +#include + +int main(int argc, char *argv[]) +{ + // ssh runs this executable as SSH_ASKPASS when a password is configured + if (const QByteArray pw = qEnvironmentVariable("SERVERMONITOR_ASKPASS").toUtf8(); !pw.isEmpty()) return std::puts(pw.constData()) < 0; + QApplication::setAttribute(Qt::AA_EnableHighDpiScaling), QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); + QApplication app(argc, argv); + QApplication::setApplicationName("ServerMonitor"), QApplication::setOrganizationName("ServerMonitor"), QApplication::setQuitOnLastWindowClosed(false); + app.setStyle(QStyleFactory::create("Fusion")); + QPalette pal; + for (auto [role, color] : {std::pair{QPalette::Window, C::bg}, {QPalette::WindowText, C::text}, {QPalette::Base, QColor(0x111727)}, {QPalette::AlternateBase, C::panel}, + {QPalette::Text, C::text}, {QPalette::Button, C::card}, {QPalette::ButtonText, C::text}, {QPalette::Highlight, QColor(0x17304a)}, + {QPalette::HighlightedText, C::text}, {QPalette::ToolTipBase, C::card}, {QPalette::ToolTipText, C::text}, {QPalette::PlaceholderText, C::faint}}) + pal.setColor(role, color); + pal.setColor(QPalette::Disabled, QPalette::Text, C::faint), pal.setColor(QPalette::Disabled, QPalette::ButtonText, C::faint); + app.setPalette(pal), app.setWindowIcon(C::appIcon()), app.setStyleSheet(C::styleSheet()); + + ServerManager mgr; + MainWindow w(&mgr); + mgr.load(); + w.show(); + if (const QString dir = qEnvironmentVariable("SERVERMONITOR_SNAPSHOT"); !dir.isEmpty()) // developer aid + QTimer::singleShot(qMax(1, qEnvironmentVariableIntValue("SERVERMONITOR_SNAPSHOT_DELAY")) * 1000, &w, [&w, dir] { w.saveSnapshots(dir), qApp->quit(); }); + return app.exec(); +} diff --git a/Server Monitor(cqt-linux)/src/ui/Tabs.cpp b/Server Monitor(cqt-linux)/src/ui/Tabs.cpp new file mode 100644 index 0000000000000000000000000000000000000000..82e2a49be6a95dd8fbe070cbcec88d52c2eeda57 --- /dev/null +++ b/Server Monitor(cqt-linux)/src/ui/Tabs.cpp @@ -0,0 +1,884 @@ +// Detail-page tabs: each one shows an aspect of the bound server session. +#include "Widgets.h" +#include "Windows.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// ---- helpers ---------------------------------------------------------------------------- +static QVBoxLayout *scrollRoot(QWidget *tab) +{ + auto *outer = new QVBoxLayout(tab); + auto *sa = new QScrollArea; + auto *l = new QVBoxLayout(new QWidget); + outer->setContentsMargins(0, 0, 0, 0), outer->addWidget(sa); + sa->setWidgetResizable(true), sa->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff), sa->setWidget(l->parentWidget()); + l->setContentsMargins(4, 16, 10, 16), l->setSpacing(16); + return l; +} +static QVBoxLayout *plainRoot(QWidget *tab) +{ + auto *l = new QVBoxLayout(tab); + l->setContentsMargins(4, 16, 4, 12), l->setSpacing(10); + return l; +} +template static L *sub(QBoxLayout *parent, int stretch = 0) // nested layout with the standard spacing +{ + auto *l = new L; + l->setSpacing(14), parent->addLayout(l, stretch); + return l; +} +static QGridLayout *grid(QBoxLayout *parent, int stretch = 0) { return sub(parent, stretch); } +static QHBoxLayout *row(QBoxLayout *parent, int stretch = 0) { return sub(parent, stretch); } +static QVBoxLayout *lay(QFrame *f) { return static_cast(f->layout()); } +static QString kv(const QVector> &rows) +{ + QString h = ""; + for (const auto &r : rows) h += QString("").arg(r.first, r.second.toHtmlEscaped()); + return h + "
%1%2
"; +} +static QVector cpuSeries(const Live &h, bool steal) +{ + QVector s = {{"User", C::accent, h.s[Live::USER]}, {"System", C::violet, h.s[Live::SYS]}}; + if (P::posixCpu) s << Series{"I/O wait", C::amber, h.s[Live::IOWAIT]}; + if (P::posixCpu && steal) s << Series{"Steal", C::red, h.s[Live::STEAL]}; + return s; +} +// run a command and show the result in a status label +static void runReport(ServerSession *s, QLabel *status, const QString &cmd) +{ + status->setText("Running: " + cmd); + s->exec(cmd, true, [st = QPointer(status), cmd](int code, const QString &out) { + if (!st) return; + st->setText(code ? "✗ " + cmd + ": " + out.trimmed().left(300) : "✓ " + cmd); + st->setStyleSheet(QString("color: %1;").arg((code ? C::red : C::green).name())); + }); +} + +// ============================================================================ Overview +struct OverviewTab : Tab { + QVector g; + QVector t; + TimeChart *cpu = new TimeChart("CPU", pctFmt, 100), *mem = new TimeChart("Memory", pctFmt, 100), *net = new TimeChart("Network", rateFmt), + *io = new TimeChart("Disk I/O", rateFmt); + QLabel *info = label({}, nullptr, true); + + OverviewTab() + { + auto *l = scrollRoot(this); + auto *gp = panel(), *ip = panel("System", {info, nullptr}); + auto *gl = new QHBoxLayout; + for (const char *n : {"CPU", "Memory", "Fullest disk", "Swap", "Temperature", "Health"}) g << new RingGauge(n), gl->addWidget(g.last()); + g[4]->crit = 85; + lay(gp)->addLayout(gl), gp->setMinimumHeight(220), l->addWidget(gp); + t = addTiles(grid(l), {{"Load average", C::accent}, {"Processes", C::violet}, {"TCP connections", C::teal}, {"Services", C::green}, {"Uptime", C::amber}}); + auto *mid = row(l); + auto *charts = grid(mid, 1); + cpu->stacked = true; + for (auto *c : {cpu, mem, net, io}) c->setMinimumHeight(220), charts->addWidget(c, charts->count() / 2, charts->count() % 2); + ip->setFixedWidth(330), mid->addWidget(ip), l->addStretch(); + } + void refresh() override + { + const Metrics &m = s->metrics(); + const Live &h = s->live(); + const Analysis &a = s->analysis(); + const ServerConfig &c = s->config(); + g[0]->setValue(m.cpuUsage, {}, QString("%1 cores").arg(m.cpuCount)); + g[1]->setValue(m.memPct, {}, Fmt::bytes(m.memUsed) + " / " + Fmt::bytes(m.memTotal)); + g[2]->setValue(m.maxDiskPct, {}, m.fullestMount); + g[3]->setValue(m.swapPct, {}, m.swapTotal > 0 ? Fmt::bytes(m.swapUsed) + " / " + Fmt::bytes(m.swapTotal) : "no swap"); + 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())); + g[5]->setValue(a.health, QString::number(a.health), "grade " + a.grade, C::health(a.health)); + 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)); + t[1]->set(QString::number(m.procs.size()), QString("%1 threads · %2 running").arg(m.threadsTotal).arg(m.procsRunning)); + t[2]->set(QString::number(m.tcp["ESTABLISHED"]), QString("%1 listening · %2 time-wait").arg(m.tcp["LISTEN"]).arg(m.tcp["TIME_WAIT"])); + t[3]->set(QString::number(m.servicesRunning), m.servicesFailed ? QString("%1 failed").arg(m.servicesFailed) : "running · none failed", m.servicesFailed ? C::red : C::text); + t[4]->set(Fmt::duration(m.uptime), QString("%1 user(s) logged in").arg(m.loggedUsers)); + cpu->setData(h.t, cpuSeries(h, false), span); + 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); + net->setData(h.t, {{"Down", C::teal, h.s[Live::RX]}, {"Up", C::pink, h.s[Live::TX]}}, span); + io->setData(h.t, {{"Read", C::blue, h.s[Live::RD]}, {"Write", C::orange, h.s[Live::WR]}}, span); + info->setText(kv({{"Hostname", m.hostname}, {"OS", m.os}, {"Kernel", m.kernel + " " + m.arch}, {"CPU", m.cpuModel}, + {"Cores", QString::number(m.cpuCount) + (m.avgMhz > 0 ? QString(" @ %1 GHz").arg(m.avgMhz / 1000, 0, 'f', 2) : "")}, + {"Memory", Fmt::bytes(m.memTotal)}, {"Swap", m.swapTotal > 0 ? Fmt::bytes(m.swapTotal) : "none"}, {"Virtualisation", m.virt}, + {"Disks", QString("%1 mounted file systems").arg(m.mounts.size())}, {"Interfaces", QString::number(m.nets.size())}, + {"GPU", m.gpus.isEmpty() ? "none" : m.gpus[0].name}, {"Connection", c.address() + " (" + transportName(c.transport) + ")"}, + {"Sample interval", QString("%1 s").arg(c.interval)}})); + } +}; + +// ============================================================================ CPU +struct CpuTab : Tab { + QLabel *model = label({}, "H2"); + QVector t; + TimeChart *chart = new TimeChart("CPU time breakdown", pctFmt, 100), *load = new TimeChart("Load average (1 min)", numFmt(1)); + CoreGrid *cores = new CoreGrid; + QTableWidget *temps = table({"Sensor", "Temperature"}, {300}, {1}), *gpus = table({"#", "Name", "Usage", "Memory", "Temp", "Power", "Fan"}, {40, 220, 120, 160}, {2, 3}); + QFrame *gpuPanel = panel("GPUs", {gpus}); + + CpuTab() + { + auto *l = scrollRoot(this); + l->addWidget(model); + 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}, + {"Context switches", C::blue}, {"Interrupts", C::pink}, {"New processes", C::green}, {"Running / blocked", C::amber}}, 4); + auto *r = row(l); + chart->stacked = true, chart->setMinimumHeight(260), temps->setMinimumHeight(220); + r->addWidget(chart, 3), r->addWidget(load, 2), l->addWidget(panel("Per core", {cores})); + auto *b = row(l); + b->addWidget(panel("Temperatures", {temps}), 1), b->addWidget(gpuPanel, 1), l->addStretch(); + } + void refresh() override + { + const Metrics &m = s->metrics(); + const Live &h = s->live(); + model->setText(m.cpuModel.isEmpty() ? "Processor" : m.cpuModel); + 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)); + 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)); + t[2]->set(m.avgMhz > 0 ? QString("%1 GHz").arg(m.avgMhz / 1000, 0, 'f', 2) : "n/a"); + if (P::posixCpu) t[3]->set(Fmt::pct(m.cpuSteal) + " / " + Fmt::pct(m.cpuIrq), "steal > 5% = noisy neighbours", m.cpuSteal > 5 ? C::amber : QColor()); + else t[3]->set(Fmt::pct(m.cpuIrq), "hardware interrupts and deferred calls", m.cpuIrq > 15 ? C::amber : QColor()); + 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"); + 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()); + chart->setData(h.t, cpuSeries(h, true), span); + load->setData(h.t, {{"Load", C::violet, h.s[Live::LOAD]}, {"Cores", C::faint, QVector(h.t.size(), m.cpuCount), false, true}}, span); + cores->setCores(m.cores); + temps->clearSpans(); + fillRows(temps, m.temps, [](const TempSensor &x) { return Row{{x.name}, {Fmt::temp(x.celsius), {}, false, qMin(100.0, x.celsius)}}; }); + 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); + gpuPanel->setVisible(!m.gpus.isEmpty()); + fillRows(gpus, m.gpus, [](const GpuInfo &g) { + return Row{{QString::number(g.index)}, {g.name}, {Fmt::pct(g.util, 0), {}, false, g.util}, + {QString("%1 / %2 MiB").arg(g.memUsed).arg(g.memTotal), {}, false, g.memTotal > 0 ? g.memUsed * 100 / g.memTotal : 0}, + {Fmt::temp(g.temp), C::level(g.temp, 75, 88)}, {QString("%1 W").arg(g.power)}, {Fmt::pct(g.fan, 0)}}; + }); + } +}; + +// ============================================================================ Memory +struct MemoryTab : Tab { + QVector t; + SegmentBar *bar = new SegmentBar, *swap = new SegmentBar; + TimeChart *chart = new TimeChart("Memory usage", pctFmt, 100); + QLabel *detail = label({}, nullptr, true); + QTableWidget *top = table({"PID", "Process", "User", "RSS", "Memory %", "Virtual"}, {80, 220, 120, 110, 160}, {4}); + + MemoryTab() + { + auto *l = scrollRoot(this); + t = addTiles(grid(l), {{"Used", C::violet}, {"Available", C::green}, {"Cache + buffers", C::blue}, {"Swap used", C::pink}}); + l->addWidget(panel("Composition", {bar, label("SWAP", "Section"), swap})); + auto *r = row(l); + auto *dp = panel("Details", {detail, nullptr}); + chart->setMinimumHeight(280), dp->setFixedWidth(300), top->setMinimumHeight(360); + r->addWidget(chart, 3), r->addWidget(dp), l->addWidget(panel("Top memory consumers", {top})); + } + void refresh() override + { + const Metrics &m = s->metrics(); + const Live &h = s->live(); + const QColor free = C::grid.lighter(150); + t[0]->set(Fmt::bytes(m.memUsed), Fmt::pct(m.memPct) + " of " + Fmt::bytes(m.memTotal), C::level(m.memPct)); + t[1]->set(Fmt::bytes(m.memAvailable), "free " + Fmt::bytes(m.memFree)); + t[2]->set(Fmt::bytes(m.cached + m.buffers), "reclaimable when needed"); + 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)); + bar->setSegments({{qMax(0.0, m.memTotal - m.memFree - m.cached - m.buffers), C::violet, "Applications"}, {m.shared, C::pink, "Shared"}, + {m.buffers, C::teal, "Buffers"}, {qMax(0.0, m.cached - m.shared), C::blue, "Cache"}, {m.memFree, free, "Free"}}, m.memTotal); + swap->setSegments({{m.swapUsed, C::pink, "Used"}, {m.swapTotal - m.swapUsed, free, "Free"}}, m.swapTotal); + 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); + QVector> d; + for (auto [k, v] : {std::pair{"Total", m.memTotal}, {"Used", m.memUsed}, {"Available", m.memAvailable}, {"Free", m.memFree}, {"Buffers", m.buffers}, + {"Cached", m.cached}, {"Shared", m.shared}, {"Slab", m.slab}, {"Dirty", m.dirty}, {"Swap total", m.swapTotal}, {"Swap used", m.swapUsed}}) + d << qMakePair(QString(k), Fmt::bytes(v)); + detail->setText(kv(d)); + QVector p = m.procs; + std::partial_sort(p.begin(), p.begin() + qMin(15, p.size()), p.end(), [](const ProcInfo &a, const ProcInfo &b) { return a.rss > b.rss; }); + fillRows(top, p.mid(0, 15), [](const ProcInfo &x) { + return Row{{QString::number(x.pid), C::muted}, {x.name}, {x.user, C::muted}, {Fmt::bytes(x.rss), {}, true}, + {Fmt::pct(x.memPct), {}, false, qMin(100.0, x.memPct * 2)}, {Fmt::bytes(x.vsz), C::muted, true}}; + }); + } +}; + +// ============================================================================ Storage +struct StorageTab : Tab { + QVector t; + QTableWidget *mounts = table({"Mount point", "Device", "Type", "Size", "Used", "Free", "Usage"}, {260, 140, 80, 110, 110, 110}, {6}), + *disks = table({"Device", "Read/s", "Write/s", "Read IOPS", "Write IOPS", "Busy", "Total read", "Total written"}, {110, 110, 110, 100, 100, 150, 120}, {5}); + TimeChart *io = new TimeChart("Disk throughput", rateFmt); + + StorageTab() + { + auto *l = scrollRoot(this); + t = addTiles(grid(l), {{"Fullest file system", C::amber}, {"Read", C::blue}, {"Write", C::orange}, {"Busiest disk", C::red}}); + mounts->setMinimumHeight(220), disks->setMinimumHeight(200), io->setMinimumHeight(260); + l->addWidget(panel("File systems", {mounts})), l->addWidget(io), l->addWidget(panel("Block devices", {disks})); + } + void refresh() override + { + const Metrics &m = s->metrics(); + t[0]->set(Fmt::pct(m.maxDiskPct), m.fullestMount, C::level(m.maxDiskPct, 80, 90)); + 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)); + io->setData(s->live().t, {{"Read", C::blue, s->live().s[Live::RD]}, {"Write", C::orange, s->live().s[Live::WR]}}, span); + fillRows(mounts, m.mounts, [](const MountInfo &x) { + return Row{{x.mount}, {x.device, C::muted}, {x.type, C::muted}, {Fmt::bytes(x.total), {}, true}, {Fmt::bytes(x.used), {}, true}, + {Fmt::bytes(x.avail), {}, true}, {Fmt::pct(x.pct), {}, false, x.pct}}; + }); + fillRows(disks, m.disks, [](const DiskIO &d) { + 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}, + {QString::number(d.writeIops, 'f', 0), {}, true}, {Fmt::pct(d.util, 0), {}, false, d.util}, {Fmt::bytes(d.totalRead), C::muted, true}, + {Fmt::bytes(d.totalWritten), C::muted, true}}; + }); + } +}; + +// ============================================================================ Network +struct NetworkTab : Tab { + QVector t; + QComboBox *iface = new QComboBox; + QStringList shown; + TimeChart *chart = new TimeChart("Traffic", rateFmt); + 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}); + + NetworkTab() + { + auto *l = scrollRoot(this); + 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}}); + auto *r = row(l); + r->addWidget(label("Interface", "Muted")), r->addWidget(iface), r->addStretch(); + iface->setMinimumWidth(200), chart->setMinimumHeight(280), tbl->setMinimumHeight(240); + l->addWidget(chart), l->addWidget(panel("Interfaces", {tbl})); + connect(iface, QOverload::of(&QComboBox::activated), this, [this] { refresh(); }); + } + void refresh() override + { + const Metrics &m = s->metrics(); + const Live &h = s->live(); + t[0]->set(Fmt::rate(m.netRxBps), "physical interfaces"), t[1]->set(Fmt::rate(m.netTxBps)); + t[2]->set(QString::number(m.tcp["ESTABLISHED"]), "TCP"), t[3]->set(QString::number(m.tcp["LISTEN"]), "open TCP ports"); + 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()); + t[5]->set(QString::number(m.socketsUsed)); + QStringList names{"All physical (total)"}; + for (const NetIf &n : m.nets) names << n.name; + if (names != shown) { + const QString cur = iface->currentText(); + iface->clear(), iface->addItems(shown = names), iface->setCurrentIndex(qMax(0, names.indexOf(cur))); + } + const QString n = iface->currentText(); + const bool all = iface->currentIndex() <= 0; + chart->title = "Traffic — " + (all ? "all physical interfaces" : n); + 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); + fillRows(tbl, m.nets, [](const NetIf &x) { + const QColor dim = x.virt ? C::muted : QColor(); + return Row{{x.name + (x.virt ? " (virtual)" : ""), dim}, {x.state, x.state == "up" ? C::green : x.state == "down" ? C::red : C::muted}, + {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}, + {QString::number(x.rxPps, 'f', 0), dim, true}, {QString::number(x.txPps, 'f', 0), dim, true}, {Fmt::bytes(x.rxBytes), dim, true}, + {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}}; + }); + } +}; + +// ============================================================================ list tabs (processes, services) +using Act = QPair>; // context-menu entry; empty text = separator + +struct ListTab : Tab { // filterable, sortable table that keeps selection and scroll position across refreshes + QLineEdit *filter = new QLineEdit; + QLabel *summary = label({}, "Muted"), *status = label({}, "Muted"); + QTableWidget *tbl; + QHBoxLayout *bar; + + ListTab(const QStringList &headers, const QVector &widths, const QVector &bars, const QString &hint) + { + auto *l = plainRoot(this); + bar = row(l), tbl = table(headers, widths, bars); + tbl->setSortingEnabled(true), tbl->setContextMenuPolicy(Qt::CustomContextMenu); + filter->setClearButtonEnabled(true), filter->setMaximumWidth(300), filter->setPlaceholderText(hint); + bar->addWidget(filter), bar->addWidget(summary), bar->addStretch(); + l->addWidget(tbl, 1), l->addWidget(status); + connect(filter, &QLineEdit::textChanged, this, [this] { applyFilter(); }); + } + QString selectedKey() const + { + const int r = tbl->currentRow(); + return r >= 0 && !tbl->isRowHidden(r) && tbl->item(r, 0) ? tbl->item(r, 0)->text() : QString(); + } + virtual bool accept(int r) const + { + for (int c = 0; c < tbl->columnCount(); ++c) + if (tbl->item(r, c) && tbl->item(r, c)->text().contains(filter->text(), Qt::CaseInsensitive)) return true; + return false; + } + void applyFilter() + { + for (int r = 0; r < tbl->rowCount(); ++r) tbl->setRowHidden(r, !accept(r)); + } + template void fill(const V &items, F rowOf) + { + const QString sel = selectedKey(); + const int scroll = tbl->verticalScrollBar()->value(), col = qMax(0, tbl->currentColumn()); + int row = -1; // rows are reused: when the selected entry is gone the selection must go too, not pass to another entry + tbl->setSortingEnabled(false), fillRows(tbl, items, rowOf), tbl->setSortingEnabled(true); + for (int r = 0; r < tbl->rowCount() && row < 0 && !sel.isEmpty(); ++r) + if (tbl->item(r, 0)->text() == sel) row = r; + tbl->setCurrentCell(row, col), applyFilter(), tbl->verticalScrollBar()->setValue(scroll); + } + void addMenu(const QVector &items) + { + connect(tbl, &QWidget::customContextMenuRequested, this, [this, items](const QPoint &p) { + if (selectedKey().isEmpty()) return; + QMenu m; + for (const Act &a : items) a.first.isEmpty() ? (void)m.addSeparator() : (void)m.addAction(a.first, a.second); + m.exec(tbl->viewport()->mapToGlobal(p)); + }); + } +}; + +struct ProcessTab : ListTab { + QCheckBox *freeze = new QCheckBox("Freeze list"); + + 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…") + { + freeze->setToolTip("Stop refreshing so rows don't move while you pick one"); + bar->insertWidget(1, freeze), tbl->sortByColumn(4, Qt::DescendingOrder); + QVector menu; + for (const Cmd &c : P::procActions()) { + menu << Act{c.label, [this, c] { run(c); }}; + if (c.button) bar->addWidget(button(c.label, c.danger ? "Danger" : nullptr, menu.last().second)); + } + bar->addWidget(button("Priority…", nullptr, [this] { renice(); })); + addMenu(menu << Act{} << Act{"Change priority…", [this] { renice(); }}); + } + void bind(ServerSession *x) override + { + if (x != s) freeze->setChecked(false); // a frozen list would show the other server's PIDs + Tab::bind(x); + } + void refresh() override + { + if (freeze->isChecked()) return; + const Metrics &m = s->metrics(); + static const QHash> states = {{'R', {"Running", C::green}}, {'S', {"Sleeping", C::muted}}, {'D', {"Disk wait", C::amber}}, + {'Z', {"Zombie", C::red}}, {'T', {"Stopped", C::red}}, {'I', {"Idle", C::muted}}}; + int running = 0; + fill(m.procs, [&](const ProcInfo &p) { + const auto st = states.value(p.state, {QString(p.state), C::muted}); + running += p.state == 'R'; + return Row{{QString::number(p.pid), C::muted, true, -1, p.pid}, {p.name}, {p.user, C::muted}, {st.first, st.second}, + {Fmt::pct(p.cpu), {}, false, qMin(100.0, p.cpu), p.cpu}, {Fmt::pct(p.memPct), {}, false, p.memPct, p.memPct}, + {Fmt::bytes(p.rss), {}, true, -1, p.rss}, {QString::number(p.threads), {}, true, -1, p.threads}, + {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}}; + }); + summary->setText(QString("%1 processes · %2 running · %3 threads").arg(m.procs.size()).arg(running).arg(m.threadsTotal)); + } + QString pidName() const { return tbl->item(tbl->currentRow(), 1)->text() + " (" + selectedKey() + ")"; } + void run(const Cmd &c) + { + const int pid = selectedKey().toInt(); // read before the question: the list keeps refreshing behind it + if (!pid) return status->setText("Select a process first."); + 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)); + } + void renice() + { + const int pid = selectedKey().toInt(); + if (!pid) return status->setText("Select a process first."); + QStringList labels; + for (const Cmd &c : P::priorities()) labels << c.label; + bool ok = false; + const int i = labels.indexOf(QInputDialog::getItem(this, "Change priority", "Priority for " + pidName() + ":", labels, labels.size() / 2, false, &ok)); + if (ok && i >= 0) runReport(s, status, P::priorities()[i].cmd.arg(pid)); + } +}; + +struct ServiceTab : ListTab { + QComboBox *state = new QComboBox; + QString sig = "?"; // not a possible signature: the first refresh always fills + + ServiceTab() : ListTab({"Service", "Active", "State", "Load", "Description"}, {300, 100, 100, 90}, {}, "Filter services…") + { + state->addItems({"All", "Running", "Failed", "Not running"}); + bar->insertWidget(1, state), tbl->sortByColumn(0, Qt::AscendingOrder); + connect(state, QOverload::of(&QComboBox::currentIndexChanged), this, [this] { applyFilter(); }); + connect(tbl, &QTableWidget::cellDoubleClicked, this, [this] { showLogs(); }); + QVector menu; + for (const Cmd &c : P::serviceActions()) { + menu << Act{c.label, [this, c] { act(c); }}; + bar->addWidget(button(c.label, c.danger ? "Danger" : nullptr, menu.last().second)); + } + bar->addWidget(button("Logs", "Primary", [this] { showLogs(); })); + addMenu(menu << Act{} << Act{"Show logs", [this] { showLogs(); }}); + } + bool accept(int r) const override + { + const QString active = tbl->item(r, 1)->text(), sub = tbl->item(r, 2)->text(); + const int st = state->currentIndex(); + return (st == 0 || (st == 1 && sub == "running") || (st == 2 && active == "failed") || (st == 3 && sub != "running" && active != "failed")) && ListTab::accept(r); + } + void refresh() override + { + const Metrics &m = s->metrics(); + QString sg; + for (const ServiceInfo &x : m.services) sg += x.unit + x.active + x.sub; + if (sg == sig) return; // unchanged: keep the list still + sig = sg; + fill(m.services, [](const ServiceInfo &x) { + const QColor c = x.active == "failed" ? C::red : x.sub == "running" ? C::green : x.active == "active" ? C::teal : C::muted; + return Row{{x.unit}, {x.active, c}, {x.sub, c}, {x.load, C::muted}, {x.description, C::muted}}; + }); + 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)); + } + void act(const Cmd &c) + { + const QString unit = selectedKey(); + if (unit.isEmpty()) return status->setText("Select a service first."); + 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))); + } + void showLogs() + { + const QString unit = selectedKey(); + if (unit.isEmpty()) return; + auto *dlg = new QDialog(this); + auto *l = new QVBoxLayout(dlg); + auto *b = new QHBoxLayout; + auto *txt = new QPlainTextEdit("Loading…"); + auto *n = new QSpinBox; + dlg->setAttribute(Qt::WA_DeleteOnClose), dlg->setWindowTitle("Logs — " + unit + " — " + s->config().name), dlg->resize(1000, 640); + txt->setReadOnly(true), txt->setFont(QFont(C::mono(), 10)), txt->setLineWrapMode(QPlainTextEdit::NoWrap); + n->setRange(50, 5000), n->setValue(300), n->setSuffix(" lines"); + auto load = [ss = s, t = QPointer(txt), n, unit] { + 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()); }); + }; + l->addWidget(txt), l->addLayout(b); + b->addWidget(n), b->addWidget(button("Reload", nullptr, load)), b->addStretch(), b->addWidget(button("Close", nullptr, [dlg] { dlg->close(); })); + load(), dlg->show(); + } +}; + +// ============================================================================ Console +struct ConsoleTab : Tab { + QPlainTextEdit *out = new QPlainTextEdit; + QLineEdit *in = new QLineEdit; + QCheckBox *priv = new QCheckBox("privileged"); + QStringList hist; + int pos = 0; + + ConsoleTab() + { + auto *l = new QHBoxLayout(this); + auto *left = new QVBoxLayout, *side = new QVBoxLayout; + auto *r = new QHBoxLayout; + auto *prompt = label("$"); + auto *run = button("Run", "Primary", [this] { + const QString c = in->text().trimmed(); + if (c.isEmpty()) return; + if (hist.isEmpty() || hist.last() != c) hist << c; + pos = hist.size(), in->clear(), exec(c, priv->isChecked()); + }); + l->setContentsMargins(4, 16, 4, 12), l->setSpacing(14), l->addLayout(left, 1), l->addLayout(side); + out->setReadOnly(true), out->setFont(QFont(C::mono(), 10)), out->setMaximumBlockCount(20000); + out->setStyleSheet("QPlainTextEdit { background: #080b12; border-radius: 10px; padding: 10px; color: #cfe3ff; }"); + in->setFont(QFont(C::mono(), 11)), in->setPlaceholderText("Type a shell command and press Enter (↑/↓ history)"), in->installEventFilter(this); + priv->setToolTip("Wrap in sudo -n when the server has 'Run control commands with sudo' enabled"), priv->setVisible(P::sudo); + prompt->setStyleSheet("color: #38bdf8; font-weight: 700; font-size: 15px;"); + r->addWidget(prompt), r->addWidget(in, 1), r->addWidget(priv), r->addWidget(run), r->addWidget(button("Clear", nullptr, [this] { out->clear(); })); + left->addWidget(out, 1), left->addLayout(r); + connect(in, &QLineEdit::returnPressed, run, &QPushButton::click); + auto addGroup = [&](const QString &title, const QVector &items, bool system) { + auto *p = panel(title); + p->setFixedWidth(270), side->addWidget(p); + for (const Cmd &q : items) { + auto *b = button(q.label, q.danger ? "Danger" : "Side", [this, q, system] { + 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); + }); + b->setToolTip(q.cmd), lay(p)->addWidget(b); + } + }; + addGroup("Quick diagnostics", P::diagnostics(), false), addGroup("System actions", P::systemActions(), true); + side->addStretch(); + } + void bind(ServerSession *x) override + { + if (x == s) return; + out->clear(), Tab::bind(x); + if (x) out->appendHtml(QString("Console for %1 (%2). Commands run non-interactively with a 120 s timeout.").arg(x->config().name.toHtmlEscaped(), x->config().address())); + } + bool eventFilter(QObject *o, QEvent *e) override + { + const int k = e->type() == QEvent::KeyPress ? static_cast(e)->key() : 0; + if (o != in || hist.isEmpty() || (k != Qt::Key_Up && k != Qt::Key_Down)) return Tab::eventFilter(o, e); + return pos = qBound(0, pos + (k == Qt::Key_Up ? -1 : 1), hist.size()), in->setText(hist.value(pos)), true; + } + void exec(const QString &cmd, bool privileged) + { + out->appendHtml(QString("
%1 $ %2").arg(QTime::currentTime().toString("HH:mm:ss"), cmd.toHtmlEscaped())); + auto clock = std::make_shared(); + clock->start(); + s->exec(cmd, privileged, [o = QPointer(out), clock](int code, const QString &text) { + if (!o) return; + if (!text.isEmpty()) o->appendPlainText(text.endsWith('\n') ? text.chopped(1) : text); + o->appendHtml(QString("[exit %2 · %3 ms]").arg(code ? "#ef4444" : "#22c55e").arg(code).arg(clock->elapsed())); + o->verticalScrollBar()->setValue(o->verticalScrollBar()->maximum()); + }, 120000); + } +}; + +// ============================================================================ Alert rules +struct RulesTab : Tab { + QTableWidget *rules = table({"On", "Condition", "Severity", "Action", "Cooldown", "Live value"}, {50, 380, 100, 330, 100}), *live = table({"Active problems"}); + + RulesTab() + { + auto *l = plainRoot(this); + 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; " + "if it is still true after the cooldown the action runs again. History-based automation lives in the Insights tab.", "Muted", true)); + auto *b = row(l); + b->addWidget(button("+ Add rule", "Primary", [this] { editRule(-1); })), b->addWidget(button("Edit", nullptr, [this] { editRule(rules->currentRow()); })); + b->addWidget(button("Delete", "Danger", [this] { + auto rs = s->config().rules; + if (rules->currentRow() >= 0 && rules->currentRow() < rs.size()) rs.remove(rules->currentRow()), store(rs); + })); + b->addStretch(); + b->addWidget(button("Reset to defaults", nullptr, [this] { + if (ask(this, "Reset rules", "Replace all rules with the defaults?")) store(ServerConfig::defaultRules()); + })); + live->setMaximumHeight(160), l->addWidget(rules, 2), l->addWidget(live, 1); + connect(rules, &QTableWidget::cellDoubleClicked, this, [this](int r) { editRule(r); }); + connect(rules, &QTableWidget::itemChanged, this, [this](QTableWidgetItem *it) { // the "On" checkbox + auto rs = s->config().rules; + const bool on = it->checkState() == Qt::Checked; + if (it->column() == 0 && it->row() < rs.size() && rs[it->row()].enabled != on) rs[it->row()].enabled = on, store(rs); + }); + } + void bind(ServerSession *x) override { Tab::bind(x), reload(); } + void store(const QVector &rs) + { + ServerConfig c = s->config(); + c.rules = rs, save(c), reload(); + } + void reload() + { + if (!s) return; + QSignalBlocker block(rules); + fillRows(rules, s->config().rules, [](const Rule &r) { + return Row{{}, {r.conditionText(), r.enabled ? QColor() : C::faint}, {r.severity, C::severity(r.severity)}, + {r.actionText(), r.action == "notify" ? C::muted : C::violet}, {QString("%1 s").arg(r.cooldown), C::muted}}; + }); + for (int i = 0; i < rules->rowCount(); ++i) rules->item(i, 0)->setCheckState(s->config().rules[i].enabled ? Qt::Checked : Qt::Unchecked); + refresh(); + } + void refresh() override + { + const auto &rs = s->config().rules; + const QStringList act = s->activeAlerts(); + QSignalBlocker block(rules); + for (int i = 0; i < rs.size() && i < rules->rowCount(); ++i) { + const double v = s->metricValue(rs[i].metric); + 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}); + } + fillRows(live, act, [](const QString &a) { return Row{{"⚠ " + a, C::red}}; }); + if (act.isEmpty()) live->setRowCount(1), cell(live, 0, 0, {"✓ No rule is currently triggered", C::green}); + } + void editRule(int idx) + { + auto rs = s->config().rules; + Rule r; + r.id = ServerConfig::newId(); + if (idx >= 0 && idx < rs.size()) r = rs[idx]; + else idx = -1; + QDialog dlg(this); + dlg.setWindowTitle(idx < 0 ? "New rule" : "Edit rule"); + auto *f = new QFormLayout(&dlg); + auto *metric = new QComboBox, *op = new QComboBox, *sev = new QComboBox, *action = new QComboBox; + auto *value = new QDoubleSpinBox; + auto *dur = new QSpinBox, *cool = new QSpinBox; + auto *arg = new QLineEdit(r.arg); + auto *en = new QCheckBox("Enabled"); + auto *cond = new QHBoxLayout; + auto *bb = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + for (const Def &d : ruleMetrics()) metric->addItem(d.label + (d.unit.isEmpty() ? "" : " (" + d.unit + ")"), d.key); + for (const Def &d : P::ruleActions()) action->addItem(d.label, d.key); + op->addItems({">", "<"}), sev->addItems({"info", "warning", "critical"}); + metric->setCurrentIndex(qMax(0, metric->findData(r.metric))), action->setCurrentIndex(qMax(0, action->findData(r.action))); + op->setCurrentText(r.op), sev->setCurrentText(r.severity), en->setChecked(r.enabled); + value->setRange(-1e9, 1e9), value->setValue(r.value); + dur->setRange(0, 86400), dur->setSuffix(" s"), dur->setValue(r.duration); + cool->setRange(10, 86400), cool->setSuffix(" s"), cool->setValue(r.cooldown); + auto sync = [action, arg] { + const QString hint = defLabel(P::ruleActions(), action->currentData().toString(), true); + arg->setEnabled(!hint.isEmpty()), arg->setPlaceholderText(hint); + }; + connect(action, QOverload::of(&QComboBox::currentIndexChanged), &dlg, sync); + connect(bb, &QDialogButtonBox::accepted, &dlg, &QDialog::accept), connect(bb, &QDialogButtonBox::rejected, &dlg, &QDialog::reject); + cond->addWidget(op), cond->addWidget(value, 1), sync(); + f->addRow("When", metric), f->addRow("is", cond), f->addRow("for at least", dur), f->addRow("Severity", sev), f->addRow("Then", action); + f->addRow("Argument", arg), f->addRow("Repeat after", cool), f->addRow("", en), f->addRow(bb); + if (dlg.exec() != QDialog::Accepted) return; + r.metric = metric->currentData().toString(), r.op = op->currentText(), r.value = value->value(), r.duration = dur->value(), r.severity = sev->currentText(); + r.action = action->currentData().toString(), r.arg = arg->isEnabled() ? arg->text().trimmed() : "", r.cooldown = cool->value(), r.enabled = en->isChecked(); + idx < 0 ? (void)(rs << r) : (void)(rs[idx] = r); + store(rs); + } +}; + +// ============================================================================ History +struct HistoryTab : Tab { + qint64 range = 86400, lastLoad = 0; + QLabel *res = label({}, "Muted"); + QVector charts; + QTableWidget *st = table({"Metric", "Minimum", "Average", "95th percentile", "Peak", "Points"}, {200, 150, 150, 150, 150}); + QVector pts; + + HistoryTab() + { + auto *l = scrollRoot(this); + auto *b = row(l); + auto *group = new QButtonGroup(this); + b->setSpacing(6); + 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}}) { + auto *btn = button(text); + btn->setCheckable(true), btn->setChecked(sec == 86400), group->addButton(btn, sec / 60), b->addWidget(btn); + } + b->addSpacing(14), b->addWidget(res), b->addStretch(), b->addWidget(button("Export CSV…", nullptr, [this] { exportCsv(); })); + connect(group, &QButtonGroup::idClicked, this, [this](int id) { range = id * 60LL, reload(); }); + auto *g = grid(l); + for (auto [title, fmt, max] : {std::tuple{"CPU", pctFmt, 100.0}, {"Memory & swap", pctFmt, 100.0}, {"Disk usage (fullest)", pctFmt, 100.0}, + {"Disk throughput", rateFmt, 0.0}, {"Network", rateFmt, 0.0}, {"Load average", numFmt(1), 0.0}, + {"Temperature", FmtFn([](double v) { return QString::number(v, 'f', 0) + "°"; }), 0.0}, {"Availability", pctFmt, 100.0}}) { + charts << new TimeChart(title, fmt, max); + 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); + } + st->setMinimumHeight(14 * 30 + 40), l->addWidget(panel("Statistics for the selected range", {st})); + } + void bind(ServerSession *x) override { Tab::bind(x), lastLoad = 0; } + void refresh() override + { + if (QDateTime::currentMSecsSinceEpoch() - lastLoad >= (range && range <= 21600 ? 5000 : 60000)) reload(); + } + void reload() + { + lastLoad = QDateTime::currentMSecsSinceEpoch(); + const qint64 now = QDateTime::currentSecsSinceEpoch(), from = range ? now - range : qMax(1, s->store().firstTs()); + Tier tier; + pts = s->store().range(from, now, &tier); + const qint64 step = qMax(HistoryStore::step[int(tier)], s->config().interval); + QVector t; + enum { CPU, CPUMAX, MEM, SWAP, DISK, RD, WR, RX, TX, RXMAX, LOAD, TEMP, TEMPMAX, AVAIL, N }; + QVector v[N]; + double n = 0, up = 0; + auto push = [&](qint64 ts, const HPoint *p) { // p = nullptr inserts a gap + t << ts * 1000; + 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}; + for (int i = 0; i < N; ++i) + 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]]); + }; + for (const HPoint &p : qAsConst(pts)) { + if (!t.isEmpty() && p.ts * 1000 - t.last() > step * 3000) push(t.last() / 1000 + step, nullptr); // app was not running + push(p.ts, &p), n += p.n, up += p.nUp; + } + if (!t.isEmpty() && now * 1000 - t.last() > step * 3000) push(now, nullptr); + const bool agg = tier != Tier::Raw; + auto peak = [&](QVector s, const QString &name, const QColor &c, const QVector &d) { if (agg) s << Series{name, c, d, false, true}; return s; }; + const QVector> data = {peak({{"Average", C::accent, v[CPU]}}, "Peak", C::red, v[CPUMAX]), + {{"Memory", C::violet, v[MEM]}, {"Swap", C::pink, v[SWAP], false}}, {{"Usage", C::amber, v[DISK]}}, + {{"Read", C::blue, v[RD]}, {"Write", C::orange, v[WR]}}, + peak({{"Down", C::teal, v[RX]}, {"Up", C::pink, v[TX]}}, "Peak down", C::teal.lighter(140), v[RXMAX]), + {{"Load", C::violet, v[LOAD]}}, peak({{"Average", C::orange, v[TEMP]}}, "Peak", C::red, v[TEMPMAX]), + {{"Online", C::green, v[AVAIL]}}}; + 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); + 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()))); + QVector 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}; + if (!P::posixCpu) ms.remove(1); + fillRows(st, ms, [&](int m) { + const Stats x = stats(pts, m); + return Row{{hNames[m]}, {fmtMetric(m, x.min), C::muted, true}, {fmtMetric(m, x.avg), {}, true}, {fmtMetric(m, x.p95), C::amber, true}, + {fmtMetric(m, x.max), C::red, true}, {QString::number(x.count), C::muted, true}}; + }); + } + void exportCsv() + { + const QString fn = QFileDialog::getSaveFileName(this, "Export history", s->config().name + "-history.csv", "CSV (*.csv)"); + QFile f(fn); + if (fn.isEmpty() || !f.open(QIODevice::WriteOnly | QIODevice::Text)) return; + QTextStream ts(&f); + ts << "time,samples,online_pct"; + for (const char *k : hKeys) ts << ',' << k << "_avg," << k << "_max"; + auto num = [](float x) { return std::isnan(x) ? QString() : QString::number(x, 'f', 3); }; + for (const HPoint &p : qAsConst(pts)) { + ts << '\n' << QDateTime::fromSecsSinceEpoch(p.ts).toString(Qt::ISODate) << ',' << p.n << ',' << p.uptimePct(); + for (int m = 0; m < H_COUNT; ++m) ts << ',' << num(p.avg[m]) << ',' << num(p.max[m]); + } + } +}; + +// ============================================================================ Insights & Autopilot +struct InsightsTab : Tab { + RingGauge *health = new RingGauge("Health score"); + QLabel *reasons = label({}, "Muted", true), *capacity = label({}, nullptr, true); + QVector t; + QVBoxLayout *findings = new QVBoxLayout; + WeekHeatmap *heat = new WeekHeatmap; + QComboBox *heatMetric = new QComboBox; + QTableWidget *anomalies = table({"Metric", "Last 10 min", "Usual", "Deviation", "Baseline"}, {110, 110, 160, 90}); + QVector> binds; // autopilot form <-> config + bool loading = false; + + // form-field builders bound to AutopilotConfig members + QWidget *chk(const QString &text, bool AutopilotConfig::*f) + { + auto *w = new QCheckBox(text); + binds << [w, f](AutopilotConfig &a, bool ld) { ld ? w->setChecked(a.*f) : void(a.*f = w->isChecked()); }; + connect(w, &QCheckBox::toggled, this, [this] { store(); }); + return w; + } + template QWidget *spin(T AutopilotConfig::*f, double lo, double hi, const QString &pre, const QString &suf) + { + auto *w = new W; + w->setRange(lo, hi), w->setPrefix(pre), w->setSuffix(suf); + if constexpr (std::is_same_v) w->setDecimals(f == &AutopilotConfig::anomalyZ ? 1 : 0), w->setSingleStep(f == &AutopilotConfig::anomalyZ ? 0.5 : 1); + binds << [w, f](AutopilotConfig &a, bool ld) { ld ? w->setValue(a.*f) : void(a.*f = w->value()); }; + connect(w, QOverload::of(&W::valueChanged), this, [this] { store(); }); + return w; + } + QWidget *combo(QString AutopilotConfig::*f, const QStringList &keys, const QStringList &labels) + { + auto *w = new QComboBox; + for (int i = 0; i < keys.size(); ++i) w->addItem(labels[i], keys[i]); + binds << [w, f](AutopilotConfig &a, bool ld) { ld ? w->setCurrentIndex(qMax(0, w->findData(a.*f))) : void(a.*f = w->currentData().toString()); }; + connect(w, QOverload::of(&QComboBox::currentIndexChanged), this, [this] { store(); }); + return w; + } + + InsightsTab() + { + using A = AutopilotConfig; + using DS = QDoubleSpinBox; + auto *l = scrollRoot(this); + auto *top = row(l); + auto *hp = panel("Health", {health, reasons, button("Analyze now", nullptr, [this] { s->analyzeNow(); })}); + hp->setFixedWidth(330), health->setMinimumHeight(190), top->addWidget(hp); + auto *right = sub(top, 1); + t = addTiles(grid(right), {{"Disk full forecast", C::amber}, {"Memory trend (6 h)", C::violet}, {"CPU / memory p95 (30 d)", C::accent}, + {"Availability 24 h", C::green}, {"Availability 7 d", C::green}, {"Availability 30 d", C::green}}, 3); + right->addWidget(panel("Capacity planning", {capacity, nullptr})); + + auto *mid = row(l); + auto *fp = panel("Findings from history analysis"); + 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)}); + auto *form = new QFormLayout; + auto *runRow = new QHBoxLayout; + auto *cmd = new QLineEdit; + findings->setSpacing(10), lay(fp)->addLayout(findings), lay(fp)->addStretch(), mid->addWidget(fp, 1); + runRow->addWidget(spin(&A::runawayCpu, 10, 6400, "≥ ", " %")), runRow->addWidget(spin(&A::runawayMinutes, 1, 1440, "for ", " min")); + cmd->setFont(QFont(C::mono(), 9)); + binds << [cmd](A &a, bool ld) { ld ? cmd->setText(a.diskCleanupCommand) : void(a.diskCleanupCommand = cmd->text().trimmed()); }; + connect(cmd, &QLineEdit::editingFinished, this, [this] { store(); }); + form->addRow(chk("Autopilot enabled", &A::enabled), chk("Dry run (only report)", &A::dryRun)); + form->addRow(chk("Restart failed services", &A::restartFailed), spin(&A::maxRestartsPerHour, 1, 20, "", " / hour max")); + form->addRow("Runaway processes", combo(&A::runawayMode, {"none", "renice", "terminate"}, {"Ignore", "Lower priority (renice 19)", "Terminate"})); + form->addRow("", runRow); + form->addRow("Memory leaks", combo(&A::leakMode, {"none", "notify", "terminate"}, {"Ignore", "Notify", "Terminate under pressure"})); + form->addRow(" pressure ≥", spin(&A::leakMemPressure, 50, 100, "", " % memory")); + form->addRow(chk("Disk cleanup", &A::diskCleanup), spin(&A::diskForecastDays, 1, 60, "full in < ", " days")); + form->addRow("", spin(&A::diskCleanupAt, 50, 100, "or usage ≥ ", " %")); + form->addRow(" command", cmd); + form->addRow(chk("Anomaly alerts", &A::anomalyAlerts), spin(&A::anomalyZ, 1.5, 10, "z ≥ ", " σ")); + ap->setFixedWidth(430), lay(ap)->addLayout(form), lay(ap)->addStretch(), mid->addWidget(ap, 0, Qt::AlignTop); + + auto *bot = row(l); + heatMetric->addItems({"CPU", "Memory"}), heatMetric->setFixedWidth(140), anomalies->setMinimumHeight(230); + connect(heatMetric, QOverload::of(&QComboBox::currentIndexChanged), this, [this] { analysis(); }); + bot->addWidget(panel("Weekly pattern (last 4 weeks, hourly averages)", {heatMetric, heat}), 3), bot->addWidget(panel("Now vs. normal (baselines)", {anomalies}), 2); + } + void bind(ServerSession *x) override + { + Tab::bind(x); + if (!x) return; + AutopilotConfig a = x->config().autopilot; + loading = true; + for (auto &b : binds) b(a, true); + loading = false, analysis(); + } + void store() + { + if (loading || !s) return; + ServerConfig c = s->config(); + for (auto &b : binds) b(c.autopilot, false); + save(c); + } + void analysis() override + { + const Analysis &a = s->analysis(); + const int hi = heatMetric->currentIndex(); + health->setValue(a.health, QString::number(a.health), "grade " + a.grade, C::health(a.health)); + reasons->setText((a.healthReasons.isEmpty() ? "No deductions — everything looks healthy." : a.healthReasons.join('\n')) + + (a.when ? "\n\nAnalyzed " + QDateTime::fromSecsSinceEpoch(a.when).toString("HH:mm:ss") : "")); + 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()); + 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); + 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()); + else t[1]->set("—", "needs ~90 min of history"); + 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"); + for (int i = 0; i < 3; ++i) + std::isnan(a.up[i]) ? t[3 + i]->set("—", "no data yet") + : 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); + capacity->setText("

• " + a.capacity.join("

• ") + "

"); + heat->setData(a.heat[hi], a.heatN, hi ? "% memory" : "% CPU", hi ? C::violet : C::accent); + fillRows(anomalies, a.anomalies, [](const Anomaly &x) { + const double az = qAbs(x.z); + return Row{{x.metric}, {fmtMetric(x.hm, x.now), {}, true}, {fmtMetric(x.hm, x.mean) + " ± " + fmtMetric(x.hm, x.sd), C::muted, true}, + {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}}; + }); + + while (QLayoutItem *it = findings->takeAt(0)) { // rebuild the finding cards + if (it->widget()) it->widget()->deleteLater(); + delete it; + } + if (a.findings.isEmpty()) { + 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); + ok->setStyleSheet("color: #22c55e; padding: 10px;"), findings->addWidget(ok); + } + const AutopilotConfig &ap = s->config().autopilot; + for (const Finding &f : a.findings) { + const QColor c = C::severity(f.severity); + auto *card = new QFrame; + auto *cl = new QHBoxLayout(card); + card->setObjectName("F"); + card->setStyleSheet(QString("#F { background: #1a2133; border: 1px solid #27314a; border-left: 4px solid %1; border-radius: 10px; }").arg(c.name())); + cl->addWidget(label(QString("%2 · %3
%4
%5
" + "→ %6%7").arg(c.name(), f.severity.toUpper(), f.category.toUpper(), f.title.toHtmlEscaped(), f.detail.toHtmlEscaped(), f.advice.toHtmlEscaped(), + f.autoEligible && ap.enabled ? QString("
%1").arg(ap.dryRun ? "Autopilot (dry run) would act on this" : "Autopilot handles this automatically") : ""), + nullptr, true), 1); + findings->addWidget(card); + if (f.action.isEmpty()) continue; + auto *b = button(f.actionLabel, f.action == "kill_pid" ? "Danger" : "Primary"); + cl->addWidget(b, 0, Qt::AlignVCenter); + connect(b, &QPushButton::clicked, this, [this, f, pb = QPointer(b)] { // the card may be rebuilt while the question is open + if (!ask(this, f.actionLabel, QString("%1 on %2?\n\n%3").arg(f.actionLabel, s->config().name, f.title))) return; + if (pb) pb->setEnabled(false), pb->setText("Working…"); + s->runFinding(f, false, [pb](int code, const QString &) { if (pb) pb->setText(code ? "✗ Failed" : "✓ Done"); }); + }); + } + } +}; + +QVector> makeTabs() +{ + return {{"Overview", new OverviewTab}, {"CPU", new CpuTab}, {"Memory", new MemoryTab}, {"Storage", new StorageTab}, {"Network", new NetworkTab}, + {"Processes", new ProcessTab}, {"Services", new ServiceTab}, {"History", new HistoryTab}, {"Insights && Autopilot", new InsightsTab}, + {"Alert rules", new RulesTab}, {"Console", new ConsoleTab}}; +} diff --git a/Server Monitor(cqt-linux)/src/ui/Widgets.cpp b/Server Monitor(cqt-linux)/src/ui/Widgets.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c9dccd43ba64fc5b7474517b80eb01d724757ced --- /dev/null +++ b/Server Monitor(cqt-linux)/src/ui/Widgets.cpp @@ -0,0 +1,485 @@ +#include "Widgets.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// ---- theme -------------------------------------------------------------------------------- +QColor C::level(double p, double w, double c) { return p >= c ? red : p >= w ? amber : green; } +QColor C::severity(const QString &s) { return s == "critical" ? red : s == "warning" ? amber : s == "resolved" ? green : s == "action" ? violet : accent; } +QColor C::health(int h) { return h >= 90 ? green : h >= 75 ? teal : h >= 60 ? amber : h >= 40 ? orange : red; } +QColor C::mix(const QColor &a, const QColor &b, double t) +{ + t = qBound(0.0, t, 1.0); + return QColor::fromRgbF(a.redF() + (b.redF() - a.redF()) * t, a.greenF() + (b.greenF() - a.greenF()) * t, a.blueF() + (b.blueF() - a.blueF()) * t); +} +QString C::mono() { return QFontDatabase::systemFont(QFontDatabase::FixedFont).family(); } + +QString C::styleSheet() +{ + return R"( +* { color: #e6ebf5; font-size: 13px; } +QMainWindow, QDialog, #Page { background: #0d111c; } +#Sidebar { background: #10151f; border-right: 1px solid #1f2738; } +QToolTip { background: #1a2133; border: 1px solid #38bdf8; padding: 6px; border-radius: 6px; } +QLabel#H1 { font-size: 22px; font-weight: 700; } QLabel#H2 { font-size: 16px; font-weight: 600; } +QLabel#Muted { color: #8b95ab; } QLabel#Section { color: #8b95ab; font-size: 11px; font-weight: 700; letter-spacing: 1px; } +QFrame#Panel { background: #161c2b; border: 1px solid #232c41; border-radius: 12px; } +QPushButton { background: #1d2538; border: 1px solid #2c3650; border-radius: 8px; padding: 7px 14px; font-weight: 600; } +QPushButton:hover { background: #253049; border-color: #38bdf8; } QPushButton:pressed { background: #18324a; } +QPushButton:disabled { color: #5a657d; border-color: #222a3c; } +QPushButton:checked, QPushButton#Primary { background: #0e7ab8; border-color: #38bdf8; color: white; } QPushButton#Primary:hover { background: #1190d8; } +QPushButton#Danger { background: #3a1820; border-color: #7f2a36; color: #ffb4bd; } QPushButton#Danger:hover { background: #55202b; border-color: #ef4444; } +QPushButton#Nav { text-align: left; padding: 10px 14px; border: none; background: transparent; font-size: 14px; } +QPushButton#Nav:hover { background: #1a2133; } QPushButton#Nav:checked { background: #17304a; color: #7dd3fc; } +QPushButton#Flat { background: transparent; border: none; padding: 4px 8px; color: #8b95ab; } QPushButton#Flat:hover { color: #e6ebf5; } +QPushButton#Side { text-align: left; padding: 6px 12px; } +QLineEdit, QSpinBox, QDoubleSpinBox, QComboBox, QPlainTextEdit { background: #111727; border: 1px solid #2a3449; border-radius: 7px; padding: 6px 8px; selection-background-color: #0e7ab8; } +QLineEdit:focus, QSpinBox:focus, QDoubleSpinBox:focus, QComboBox:focus, QPlainTextEdit:focus { border-color: #38bdf8; } +QComboBox::drop-down { border: none; width: 22px; } +QComboBox QAbstractItemView { background: #161c2b; border: 1px solid #2a3449; selection-background-color: #17304a; } +QCheckBox::indicator { width: 16px; height: 16px; border-radius: 4px; border: 1px solid #3a4662; background: #111727; } +QCheckBox::indicator:checked { background: #0ea5e9; border-color: #38bdf8; } +QTabWidget::pane { border: none; } +QTabBar::tab { background: transparent; color: #8b95ab; padding: 10px 14px; border-bottom: 2px solid transparent; } +QTabBar::tab:hover { color: #e6ebf5; } QTabBar::tab:selected { color: #7dd3fc; border-bottom: 2px solid #38bdf8; } +QTableView, QListView { background: #131929; alternate-background-color: #161d2e; border: 1px solid #232c41; border-radius: 10px; + selection-background-color: #17304a; selection-color: #e6ebf5; outline: none; } +QTableView::item { padding: 4px; } +QHeaderView::section { background: #182033; color: #8b95ab; border: none; border-bottom: 1px solid #27314a; padding: 7px 8px; font-weight: 700; font-size: 12px; } +QScrollBar:vertical { background: transparent; width: 10px; margin: 2px; } QScrollBar:horizontal { background: transparent; height: 10px; margin: 2px; } +QScrollBar::handle { background: #2a3449; border-radius: 4px; min-height: 30px; min-width: 30px; } QScrollBar::handle:hover { background: #3b4866; } +QScrollBar::add-line, QScrollBar::sub-line { width: 0; height: 0; } QScrollBar::add-page, QScrollBar::sub-page { background: none; } +QScrollArea { border: none; background: transparent; } QScrollArea > QWidget > QWidget { background: transparent; } +QMenu { background: #161c2b; border: 1px solid #2a3449; border-radius: 8px; padding: 6px; } +QMenu::item { padding: 7px 22px; border-radius: 5px; } QMenu::item:selected { background: #17304a; } +QMenu::separator { height: 1px; background: #27314a; margin: 4px 8px; } +)"; +} + +QIcon C::appIcon() +{ + QIcon icon; + for (int s : {16, 32, 64, 128, 256}) { + QPixmap pm(s, s); + pm.fill(Qt::transparent); + QPainter p(&pm); + p.setRenderHint(QPainter::Antialiasing); + QLinearGradient g(0, 0, s, s); + g.setColorAt(0, 0x0ea5e9), g.setColorAt(1, 0x7c3aed); + p.setBrush(g), p.setPen(Qt::NoPen); + p.drawRoundedRect(QRectF(0, 0, s, s), s * .22, s * .22); + p.setPen(QPen(Qt::white, qMax(1.5, s * .075), Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); + 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}})); + icon.addPixmap(pm); + } + return icon; +} + +QFont pxFont(QFont f, int px, bool bold) { return f.setPixelSize(px), f.setBold(bold), f; } +static double niceCeil(double v) +{ + if (v <= 0) return 1; + const double e = std::pow(10, std::floor(std::log10(v))), f = v / e; + return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * e; +} +static void roundedPanel(QPainter &p, const QRectF &r, const QBrush &b, const QColor &border = C::border, double rad = 12) +{ + p.setPen(QPen(border, 1)), p.setBrush(b); + p.drawRoundedRect(r.adjusted(.5, .5, -.5, -.5), rad, rad); +} + +void paintRing(QPainter &p, const QRectF &r, double pct, const QColor &c, double t, bool glow) +{ + p.save(); + p.setRenderHint(QPainter::Antialiasing); + const QRectF rr = r.adjusted(t / 2, t / 2, -t / 2, -t / 2); + p.setPen(QPen(C::grid, t, Qt::SolidLine, Qt::RoundCap)); + p.drawArc(rr, 225 * 16, -270 * 16); + const int span = int(-270 * 16 * qBound(0.0, pct, 100.0) / 100); + if (span < -3) { + if (glow) p.setPen(QPen(C::tint(c, 45), t * 2, Qt::SolidLine, Qt::RoundCap)), p.drawArc(rr, 225 * 16, span); + p.setPen(QPen(c, t, Qt::SolidLine, Qt::RoundCap)); + p.drawArc(rr, 225 * 16, span); + } + p.restore(); +} + +// ---- RingGauge ------------------------------------------------------------------------------ +RingGauge::RingGauge(const QString &title) : m_title(title) +{ + m_anim.setDuration(450), m_anim.setEasingCurve(QEasingCurve::OutCubic); + connect(&m_anim, &QVariantAnimation::valueChanged, this, [this](const QVariant &v) { m_shown = v.toDouble(), update(); }); +} +void RingGauge::setValue(double pct, const QString ¢er, const QString &sub, const QColor &color) +{ + m_center = center, m_sub = sub, m_color = color; + pct = std::isnan(pct) ? 0 : pct; + if (qAbs(pct - m_target) > 0.05) m_anim.stop(), m_anim.setStartValue(m_shown), m_anim.setEndValue(m_target = pct), m_anim.start(); + update(); +} +void RingGauge::paintEvent(QPaintEvent *) +{ + AA p(this); + const double s = qMin(width() - 8.0, height() - 28.0); + const QRectF r((width() - s) / 2, 4, s, s); + paintRing(p, r, m_shown, m_color.isValid() ? m_color : C::level(m_target, warn, crit), qMax(7.0, s * .085)); + p.setFont(pxFont(font(), int(s * .2), true)), p.setPen(C::text); + 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); + p.setFont(pxFont(font(), qMax(10, int(s * .075)))), p.setPen(C::muted); + 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))); + p.setFont(pxFont(font(), 13, true)), p.setPen(C::text); + p.drawText(QRectF(0, r.bottom() - s * .06, width(), 22), Qt::AlignHCenter, m_title); +} + +// ---- TimeChart -------------------------------------------------------------------------------- +TimeChart::TimeChart(const QString &t, FmtFn fmt, double yMax) : title(t), m_fmt(fmt), m_yMax(yMax) +{ + setMouseTracking(true), setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); +} +void TimeChart::setData(const QVector &t, const QVector &s, qint64 span) { m_t = t, m_s = s, m_span = span, update(); } +void TimeChart::mouseMoveEvent(QMouseEvent *e) { m_hover = e->pos().x(), update(); } + +void TimeChart::paintEvent(QPaintEvent *) +{ + AA p(this); + roundedPanel(p, rect(), C::panel); + p.setFont(pxFont(font(), 13, true)), p.setPen(C::text); + p.drawText(16, 10, width(), 20, Qt::AlignVCenter, title); + const int titleW = p.fontMetrics().horizontalAdvance(title); + p.setFont(pxFont(font(), 11)), p.setPen(C::muted); + p.drawText(24 + titleW, 10, width(), 20, Qt::AlignVCenter, subtitle); + double lx = width() - 16; // legend with latest values, right-aligned + for (int i = m_s.size() - 1; i >= 0; --i) { + const Series &s = m_s[i]; + double last = NAN; + for (int k = s.v.size() - 1; k >= qMax(0, s.v.size() - 5) && std::isnan(last); --k) last = s.v[k]; + const QString txt = s.name + (std::isnan(last) ? "" : " " + m_fmt(last)); + const int w = p.fontMetrics().horizontalAdvance(txt); + if ((lx -= w) < 40 + titleW) break; + p.setPen(C::muted), p.drawText(QRectF(lx, 10, w, 20), Qt::AlignVCenter, txt); + p.setPen(Qt::NoPen), p.setBrush(s.color), p.drawRoundedRect(QRectF(lx -= 14, 16, 9, 9), 2, 2); + lx -= 14; + } + const int n = m_t.size(); + int first = 0; + if (n && m_span) + while (first < n && m_t[first] < m_t.last() - m_span) ++first; + QRectF plot(56, 40, width() - 72, height() - 70); + if (n - first < 2 || plot.height() < 20) return p.setPen(C::faint), p.drawText(plot, Qt::AlignCenter, empty); + + double yMax = m_yMax; + if (yMax <= 0) { + for (int i = first; i < n; ++i) { + double sum = 0; + for (const Series &s : m_s) + if (i < s.v.size() && !std::isnan(s.v[i])) sum = stacked ? sum + s.v[i] : qMax(sum, s.v[i]); + yMax = qMax(yMax, sum); + } + yMax = niceCeil(yMax * 1.12); + } + p.setFont(pxFont(font(), 10)); + int lw = 0; + for (int g = 0; g <= 4; ++g) lw = qMax(lw, p.fontMetrics().horizontalAdvance(m_fmt(yMax * g / 4))); + plot.setLeft(qMax(40, lw + 18)); + const qint64 t1 = m_t.last(), t0 = m_span ? t1 - m_span : m_t[first]; + const double tr = qMax(1, t1 - t0); + auto X = [&](qint64 t) { return plot.left() + (t - t0) / tr * plot.width(); }; + auto Y = [&](double v) { return plot.bottom() - qBound(0.0, v, yMax) / yMax * plot.height(); }; + const QString tf = tr <= 72e5 ? "HH:mm" : tr <= 2.6e8 ? "ddd HH:mm" : tr <= 3.5e10 ? "dd MMM" : "MMM yyyy"; + for (int g = 0; g <= 4; ++g) { // grid, y labels, time labels + const double y = Y(yMax * g / 4), x = X(t0 + qint64(tr * g / 4)); + p.setPen(QPen(C::grid, 1, g ? Qt::DashLine : Qt::SolidLine)), p.drawLine(QPointF(plot.left(), y), QPointF(plot.right(), y)); + p.setPen(C::faint); + p.drawText(QRectF(0, y - 8, plot.left() - 8, 16), Qt::AlignRight | Qt::AlignVCenter, m_fmt(yMax * g / 4)); + 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), + QDateTime::fromMSecsSinceEpoch(t0 + qint64(tr * g / 4)).toString(tf)); + } + const int step = qMax(1, (n - first) / qMax(50, int(plot.width() * 1.5))); // ~1.5 points per pixel + QVector base(n, 0.0); + p.setClipRect(plot.adjusted(-2, -4, 2, 2)); + for (const Series &s : m_s) { + QVector top(1), bot(1); // runs split at gaps (NaN) + for (int i = first; i < n; i += step) { + double sum = 0, bs = 0; + int c = 0; + for (int k = i; k < qMin(n, i + step); ++k) + if (k < s.v.size() && !std::isnan(s.v[k])) sum += s.v[k], bs += base[k], ++c; + if (!c) { if (!top.last().isEmpty()) top << QPolygonF(), bot << QPolygonF(); continue; } + const double x = X(m_t[qMin(n - 1, i + step / 2)]), b = stacked ? bs / c : 0; + top.last() << QPointF(x, Y(sum / c + b)), bot.last() << QPointF(x, Y(b)); + } + if (stacked) + for (int k = first; k < qMin(n, s.v.size()); ++k) base[k] += std::isnan(s.v[k]) ? 0 : s.v[k]; + for (int r = 0; r < top.size(); ++r) { + if (top[r].size() < 2) continue; + if (s.fill) { + QPolygonF area = top[r]; + for (int i = bot[r].size() - 1; i >= 0; --i) area << bot[r][i]; + QLinearGradient g(0, plot.top(), 0, plot.bottom()); + g.setColorAt(0, C::tint(s.color, stacked ? 120 : 95)), g.setColorAt(1, C::tint(s.color, stacked ? 60 : 4)); + p.setPen(Qt::NoPen), p.setBrush(g), p.drawPolygon(area); + } + p.setBrush(Qt::NoBrush), p.setPen(QPen(s.color, s.dashed ? 1.3 : 2, s.dashed ? Qt::DashLine : Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); + p.drawPolyline(top[r]); + } + } + p.setClipping(false); + if (m_hover < plot.left() || m_hover > plot.right()) return; + const qint64 ht = t0 + qint64((m_hover - plot.left()) / plot.width() * tr); // crosshair + tooltip + const int best = std::lower_bound(m_t.begin() + first, m_t.end(), ht) - m_t.begin() - (m_t.last() < ht); + const double x = X(m_t[best]); + p.setPen(QPen(QColor(255, 255, 255, 70), 1, Qt::DashLine)), p.drawLine(QPointF(x, plot.top()), QPointF(x, plot.bottom())); + QStringList lines{QDateTime::fromMSecsSinceEpoch(m_t[best]).toString(tr > 864e5 ? "ddd dd MMM HH:mm" : "HH:mm:ss")}; + double stack = 0; + for (const Series &s : m_s) { + const double v = best < s.v.size() ? s.v[best] : NAN; + lines << s.name + ": " + (std::isnan(v) ? "—" : m_fmt(v)); + if (std::isnan(v)) continue; + stack = stacked ? stack + v : v; + p.setPen(QPen(C::panel, 2)), p.setBrush(s.color), p.drawEllipse(QPointF(x, Y(stack)), 4, 4); + } + p.setFont(pxFont(font(), 11)); + int tw = 0; + for (const QString &l : lines) tw = qMax(tw, p.fontMetrics().horizontalAdvance(l)); + const QRectF tip(qMin(x + 12, plot.right() - tw - 20), plot.top() + 4, tw + 18, lines.size() * 16 + 10); + roundedPanel(p, tip, QColor(13, 17, 28, 235), C::border, 7); + 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]); +} + +// ---- SegmentBar -------------------------------------------------------------------------------- +SegmentBar::SegmentBar() { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed), setFixedHeight(58); } +void SegmentBar::setSegments(const QVector &s, double total) { m_s = s, m_total = total > 0 ? total : 1, update(); } +void SegmentBar::paintEvent(QPaintEvent *) +{ + AA p(this); + QPainterPath clip; + clip.addRoundedRect(QRectF(0, 2, width(), 14), 7, 7); + p.setClipPath(clip); + p.fillRect(rect(), C::grid); + double x = 0, lx = 0, ly = 26; + 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()); + p.setClipping(false); + p.setFont(pxFont(font(), 11)); + for (const Segment &s : m_s) { + const QString t = s.label + " " + Fmt::bytes(s.value); + const int w = p.fontMetrics().horizontalAdvance(t) + 26; + if (lx + w > width()) lx = 0, ly += 18; + p.setPen(Qt::NoPen), p.setBrush(s.color), p.drawRoundedRect(QRectF(lx, ly + 3, 9, 9), 2, 2); + p.setPen(C::muted), p.drawText(QRectF(lx + 14, ly, w, 16), Qt::AlignVCenter, t); + lx += w; + } +} + +// ---- StatTile ------------------------------------------------------------------------------------ +StatTile::StatTile(const QString &title, const QColor &accent) : m_accent(accent) +{ + auto *l = new QVBoxLayout(this); + l->setContentsMargins(16, 12, 14, 12), l->setSpacing(2); + l->addWidget(label(title.toUpper(), "Section")); + l->addWidget(m_value = new QLabel("—")); + l->addWidget(m_sub = label({}, "Muted")); + m_sub->setStyleSheet("font-size: 11px;"); + setMinimumHeight(84), setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed), set("—"); +} +void StatTile::set(const QString &v, const QString &sub, const QColor &c) +{ + m_value->setText(v), m_sub->setText(sub), m_sub->setVisible(!sub.isEmpty()); + m_value->setStyleSheet(QString("font-size: 21px; font-weight: 700; color: %1;").arg((c.isValid() ? c : C::text).name())); +} +void StatTile::paintEvent(QPaintEvent *) +{ + AA p(this); + QLinearGradient g(0, 0, width(), height()); + g.setColorAt(0, C::card), g.setColorAt(1, C::panel); + roundedPanel(p, rect(), g); + p.setPen(Qt::NoPen), p.setBrush(m_accent), p.drawRoundedRect(QRectF(0, 14, 4, height() - 28), 2, 2); +} +QVector addTiles(QGridLayout *g, const QVector> &defs, int cols) +{ + QVector out; + g->setSpacing(14); + for (const auto &d : defs) out << new StatTile(d.first, d.second), g->addWidget(out.last(), (out.size() - 1) / cols, (out.size() - 1) % cols); + return out; +} + +// ---- CoreGrid --------------------------------------------------------------------------------------- +CoreGrid::CoreGrid() +{ + QSizePolicy sp(QSizePolicy::Expanding, QSizePolicy::Preferred); + sp.setHeightForWidth(true); + setSizePolicy(sp); +} +void CoreGrid::setCores(const QVector &c) +{ + if (c.size() != m_c.size()) updateGeometry(); + m_c = c, update(); +} +void CoreGrid::paintEvent(QPaintEvent *) +{ + AA p(this); + const int cols = qMax(1, width() / 92); + const double cw = double(width()) / cols; + for (int i = 0; i < m_c.size(); ++i) { + const double u = m_c[i].usage; + const QColor c = C::level(u, 60, 85); + 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); + roundedPanel(p, r, C::mix(C::card, c, u / 420), C::mix(C::border, c, u / 160), 8); + p.setPen(Qt::NoPen), p.setBrush(C::grid), p.drawRoundedRect(bar, 2, 2); + p.setBrush(c), p.drawRoundedRect(QRectF(bar.left(), bar.top(), bar.width() * u / 100, 4), 2, 2); + p.setFont(pxFont(font(), 10)), p.setPen(C::muted); + p.drawText(r.adjusted(8, 5, -8, 0), Qt::AlignLeft, QString("CPU %1").arg(i)); + 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"); + p.setFont(pxFont(font(), 16, true)), p.setPen(C::text); + p.drawText(r.adjusted(8, 18, -8, -14), Qt::AlignVCenter, QString::number(u, 'f', 0) + "%"); + } +} + +// ---- WeekHeatmap --------------------------------------------------------------------------------------- +static const QStringList kDays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; +WeekHeatmap::WeekHeatmap() : m_hot(C::accent) +{ + std::fill(&m_v[0][0], &m_v[0][0] + 168, NAN), std::fill(&m_n[0][0], &m_n[0][0] + 168, 0); + setMouseTracking(true), setMinimumHeight(230); +} +void WeekHeatmap::setData(const double v[7][24], const int n[7][24], const QString &unit, const QColor &hot) +{ + std::copy(&v[0][0], &v[0][0] + 168, &m_v[0][0]); + std::copy(&n[0][0], &n[0][0] + 168, &m_n[0][0]); + m_unit = unit, m_hot = hot, update(); +} +QRectF WeekHeatmap::cell(int d, int h) const +{ + const double cw = (width() - 44) / 24.0, ch = (height() - 30) / 7.0; + return QRectF(40 + h * cw + 1.5, 6 + d * ch + 1.5, cw - 3, ch - 3); +} +void WeekHeatmap::paintEvent(QPaintEvent *) +{ + AA p(this); + p.setFont(pxFont(font(), 10)); + bool any = false; + for (int d = 0; d < 7; ++d) { + 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)); + for (int h = 0; h < 24; ++h) { + const double v = m_v[d][h]; + any |= !std::isnan(v); + 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))); + p.drawRoundedRect(cell(d, h), 3, 3); + } + } + p.setPen(C::faint); + 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'))); + if (any) return; + const QRectF box(cell(2, 3).topLeft(), cell(4, 20).bottomRight()); + p.fillRect(box, QColor(13, 17, 28, 200)), p.setPen(C::text), p.setFont(pxFont(font(), 12)); + p.drawText(box, Qt::AlignCenter, "Collecting hourly history… the weekly pattern fills in over time"); +} +void WeekHeatmap::mouseMoveEvent(QMouseEvent *e) +{ + for (int d = 0; d < 7; ++d) + for (int h = 0; h < 24; ++h) + if (cell(d, h).contains(e->pos())) + return QToolTip::showText(e->globalPos(), std::isnan(m_v[d][h]) ? QString("%1 %2:00 — no data").arg(kDays[d]).arg(h) + : 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); + QToolTip::hideText(); +} + +// ---- table helpers -------------------------------------------------------------------------------------- +void BarDelegate::paint(QPainter *p, const QStyleOptionViewItem &o, const QModelIndex &i) const +{ + const QVariant pv = i.data(Qt::UserRole); + if (!pv.isValid()) return QStyledItemDelegate::paint(p, o, i); + p->save(); + p->setRenderHint(QPainter::Antialiasing); + if (o.state & QStyle::State_Selected) p->fillRect(o.rect, o.palette.highlight()); + const double pct = qBound(0.0, pv.toDouble(), 100.0); + const QRectF r = QRectF(o.rect).adjusted(6, o.rect.height() / 2.0 - 7, -6, -(o.rect.height() / 2.0 - 7)); + const QColor c = C::level(pct); + p->setPen(Qt::NoPen), p->setBrush(C::grid), p->drawRoundedRect(r, 4, 4); + p->setBrush(C::tint(c, 200)), p->drawRoundedRect(QRectF(r.left(), r.top(), r.width() * pct / 100, r.height()), 4, 4); + p->setFont(pxFont(o.font, 11, true)), p->setPen(C::text), p->drawText(r, Qt::AlignCenter, i.data().toString()); + p->restore(); +} + +int FlowLayout::place(const QRect &r, bool apply) const +{ + if (m_items.isEmpty()) return 0; + 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; + int y = r.y(), rowH = 0, col = 0; + for (QLayoutItem *it : m_items) { + if (it->widget() && it->widget()->isHidden()) continue; + if (apply) it->setGeometry(QRect(r.x() + col * (w + sp), y, w, it->sizeHint().height())); + rowH = qMax(rowH, it->sizeHint().height()); + if (++col == cols) col = 0, y += rowH + sp, rowH = 0; + } + return y + rowH - r.y(); +} + +// ---- builders ---------------------------------------------------------------------------------------- +QLabel *label(const QString &text, const char *name, bool wrap) +{ + auto *l = new QLabel(text); + if (name) l->setObjectName(name); + l->setWordWrap(wrap); + return l; +} +QPushButton *button(const QString &text, const char *style, std::function onClick) +{ + auto *b = new QPushButton(text); + if (style) b->setObjectName(style); + if (onClick) QObject::connect(b, &QPushButton::clicked, b, onClick); + return b; +} +QFrame *panel(const QString &title, std::initializer_list content) +{ + auto *f = new QFrame; + f->setObjectName("Panel"); + auto *l = new QVBoxLayout(f); + l->setContentsMargins(16, 14, 16, 14), l->setSpacing(10); + if (!title.isEmpty()) l->addWidget(label(title.toUpper(), "Section")); + for (QWidget *w : content) w ? l->addWidget(w) : l->addStretch(); + return f; +} +bool ask(QWidget *parent, const QString &title, const QString &text) { return QMessageBox::question(parent, title, text) == QMessageBox::Yes; } + +namespace { +struct SortItem : QTableWidgetItem { // sorts by Qt::UserRole+1 when set (numbers sort numerically) + bool operator<(const QTableWidgetItem &o) const override + { + const QVariant a = data(Qt::UserRole + 1), b = o.data(Qt::UserRole + 1); + if (!a.isValid() || !b.isValid()) return text() < o.text(); + return a.type() == QVariant::String ? a.toString() < b.toString() : a.toDouble() < b.toDouble(); + } +}; +} + +QTableWidget *table(const QStringList &headers, const QVector &widths, const QVector &bars) +{ + auto *t = new QTableWidget(0, headers.size()); + t->setHorizontalHeaderLabels(headers); + t->verticalHeader()->hide(), t->verticalHeader()->setDefaultSectionSize(30); + t->setAlternatingRowColors(true), t->setShowGrid(false), t->setWordWrap(false); + t->setSelectionBehavior(QAbstractItemView::SelectRows), t->setSelectionMode(QAbstractItemView::SingleSelection); + t->setEditTriggers(QAbstractItemView::NoEditTriggers), t->setFocusPolicy(Qt::NoFocus), t->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); + t->horizontalHeader()->setHighlightSections(false), t->horizontalHeader()->setStretchLastSection(true); + t->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter); + for (int i = 0; i < widths.size(); ++i) t->setColumnWidth(i, widths[i]); + for (int c : bars) t->setItemDelegateForColumn(c, new BarDelegate(t)); + return t; +} +void cell(QTableWidget *t, int r, int c, const Cell &x) +{ + QTableWidgetItem *it = t->item(r, c); + if (!it) t->setItem(r, c, it = new SortItem); + if (it->text() != x.text) it->setText(x.text); + it->setTextAlignment(int(x.right ? Qt::AlignRight : Qt::AlignLeft) | Qt::AlignVCenter); + it->setForeground(x.color.isValid() ? x.color : C::text); + if (x.pct >= 0) it->setData(Qt::UserRole, x.pct); + if (x.key.isValid()) it->setData(Qt::UserRole + 1, x.key); +} diff --git a/Server Monitor(cqt-linux)/src/ui/Widgets.h b/Server Monitor(cqt-linux)/src/ui/Widgets.h new file mode 100644 index 0000000000000000000000000000000000000000..916e8c4a461ff62a1c9d679e3c76e37eaaf20da4 --- /dev/null +++ b/Server Monitor(cqt-linux)/src/ui/Widgets.h @@ -0,0 +1,150 @@ +// Theme, hand-painted widgets (gauges, time charts, bars, tiles, core grid, weekly +// heatmap), a flow layout and small builders for labels, buttons, panels and tables. +#pragma once +#include "core/Model.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace C { // palette +inline const QColor bg{0x0d111c}, panel{0x161c2b}, card{0x1a2133}, cardHover{0x20293f}, border{0x27314a}, grid{0x242d42}, + text{0xe6ebf5}, muted{0x8b95ab}, faint{0x5a657d}, accent{0x38bdf8}, green{0x22c55e}, amber{0xf59e0b}, red{0xef4444}, + violet{0xa78bfa}, pink{0xf472b6}, teal{0x2dd4bf}, orange{0xfb923c}, blue{0x60a5fa}; +QColor level(double pct, double warn = 70, double crit = 90); // green / amber / red +QColor severity(const QString &s); +QColor health(int h); +QColor mix(const QColor &a, const QColor &b, double t); +inline QColor tint(QColor c, int alpha) { return c.setAlpha(alpha), c; } +QString styleSheet(); +QIcon appIcon(); +QString mono(); +} + +using FmtFn = std::function; +inline const FmtFn pctFmt = [](double v) { return QString::number(v, 'f', 0) + "%"; }, rateFmt = Fmt::rate; +inline FmtFn numFmt(int prec) { return [prec](double v) { return QString::number(v, 'f', prec); }; } + +struct AA : QPainter { // antialiased painter + explicit AA(QPaintDevice *d) : QPainter(d) { setRenderHint(Antialiasing); } +}; +QFont pxFont(QFont f, int px, bool bold = false); +void paintRing(QPainter &p, const QRectF &r, double pct, const QColor &c, double thick, bool glow = true); // 270° arc + +struct RingGauge : QWidget { + explicit RingGauge(const QString &title); + void setValue(double pct, const QString ¢er = {}, const QString &sub = {}, const QColor &color = {}); + double warn = 70, crit = 90; + QSize sizeHint() const override { return {170, 190}; } + void paintEvent(QPaintEvent *) override; + QString m_title, m_center, m_sub; + QColor m_color; + double m_target = 0, m_shown = 0; + QVariantAnimation m_anim; +}; + +struct Series { QString name; QColor color; QVector v; bool fill = true, dashed = false; }; +struct TimeChart : QWidget { + explicit TimeChart(const QString &title, FmtFn fmt = pctFmt, double yMax = 0); // yMax 0 = auto + void setData(const QVector &tMs, const QVector &s, qint64 spanMs = 0); // span 0 = all + QString title, subtitle, empty = "Waiting for data…"; + bool stacked = false; + QSize sizeHint() const override { return {480, 230}; } + QSize minimumSizeHint() const override { return {260, 200}; } + void paintEvent(QPaintEvent *) override; + void mouseMoveEvent(QMouseEvent *) override; + void leaveEvent(QEvent *) override { m_hover = -1, update(); } + FmtFn m_fmt; + double m_yMax; + QVector m_t; + QVector m_s; + qint64 m_span = 0; + int m_hover = -1; +}; + +struct Segment { double value; QColor color; QString label; }; +struct SegmentBar : QWidget { + SegmentBar(); + void setSegments(const QVector &s, double total); + QSize sizeHint() const override { return {300, 58}; } + void paintEvent(QPaintEvent *) override; + QVector m_s; + double m_total = 1; +}; + +struct StatTile : QFrame { + StatTile(const QString &title, const QColor &accent); + void set(const QString &value, const QString &sub = {}, const QColor &color = {}); + void paintEvent(QPaintEvent *) override; + QLabel *m_value, *m_sub; + QColor m_accent; +}; +// creates tiles in a grid (cols per row) from {title, colour} pairs +QVector addTiles(class QGridLayout *g, const QVector> &defs, int cols = 99); + +struct CoreGrid : QWidget { + CoreGrid(); + void setCores(const QVector &c); + bool hasHeightForWidth() const override { return true; } + int heightForWidth(int w) const override { return (qMax(1, m_c.size()) + qMax(1, w / 92) - 1) / qMax(1, w / 92) * 66; } + void paintEvent(QPaintEvent *) override; + QVector m_c; +}; + +struct WeekHeatmap : QWidget { + WeekHeatmap(); + void setData(const double v[7][24], const int n[7][24], const QString &unit, const QColor &hot); + QSize sizeHint() const override { return {560, 230}; } + void paintEvent(QPaintEvent *) override; + void mouseMoveEvent(QMouseEvent *) override; + QRectF cell(int d, int h) const; + double m_v[7][24]; + int m_n[7][24]; + QString m_unit; + QColor m_hot; +}; + +// table cell bar: Qt::UserRole = percent, DisplayRole = text on the bar +struct BarDelegate : QStyledItemDelegate { + using QStyledItemDelegate::QStyledItemDelegate; + void paint(QPainter *p, const QStyleOptionViewItem &o, const QModelIndex &i) const override; +}; + +struct FlowLayout : QLayout { // equal-width columns of cards + FlowLayout(QWidget *parent) : QLayout(parent) {} + ~FlowLayout() override { qDeleteAll(m_items); } + void addItem(QLayoutItem *i) override { m_items << i; } + int count() const override { return m_items.size(); } + QLayoutItem *itemAt(int i) const override { return m_items.value(i); } + QLayoutItem *takeAt(int i) override { return i >= 0 && i < m_items.size() ? m_items.takeAt(i) : nullptr; } + bool hasHeightForWidth() const override { return true; } + int heightForWidth(int w) const override { return place(QRect(0, 0, w, 0), false); } + void setGeometry(const QRect &r) override { QLayout::setGeometry(r), place(r, true); } + QSize sizeHint() const override { return {340, 270}; } + int place(const QRect &r, bool apply) const; + QList m_items; +}; + +// ---- small builders ---------------------------------------------------------------- +QLabel *label(const QString &text, const char *objectName = nullptr, bool wrap = false); +QPushButton *button(const QString &text, const char *style = nullptr, std::function onClick = {}); +QFrame *panel(const QString &title = {}, std::initializer_list content = {}); // nullptr = stretch +bool ask(QWidget *parent, const QString &title, const QString &text); + +struct Cell { QString text; QColor color; bool right = false; double pct = -1; QVariant key; }; // pct = bar, key = sort value +using Row = QVector; +QTableWidget *table(const QStringList &headers, const QVector &widths = {}, const QVector &barColumns = {}); +void cell(QTableWidget *t, int r, int c, const Cell &x); +template void fillRows(QTableWidget *t, const V &items, F rowOf) // one row per item +{ + t->setRowCount(items.size()); + for (int r = 0; r < items.size(); ++r) { + const Row row = rowOf(items[r]); + for (int c = 0; c < row.size(); ++c) cell(t, r, c, row[c]); + } +} diff --git a/Server Monitor(cqt-linux)/src/ui/Windows.cpp b/Server Monitor(cqt-linux)/src/ui/Windows.cpp new file mode 100644 index 0000000000000000000000000000000000000000..97fc3f5ec0f2c5348ab97d5e3b3ddc6233a675f6 --- /dev/null +++ b/Server Monitor(cqt-linux)/src/ui/Windows.cpp @@ -0,0 +1,614 @@ +// Main window: sidebar, dashboard with server cards, server detail page, events page, tray icon. +#include "Windows.h" +#include "Widgets.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct Actions { std::function open, edit, remove; std::function add, back; }; // set by the main window +static QColor statusColor(Status s) { return s == Status::Online ? C::green : s == Status::Connecting ? C::amber : s == Status::Offline ? C::red : C::faint; } +static QHBoxLayout *hbox() +{ + auto *h = new QHBoxLayout; + h->setSpacing(10); + return h; +} +static QVBoxLayout *page(QWidget *w, int top = 22) +{ + auto *l = new QVBoxLayout(w); + w->setObjectName("Page"), l->setContentsMargins(28, top, 28, 18), l->setSpacing(14); + return l; +} + +// ============================================================================ dashboard cards +struct Card : QWidget { + bool hover = false; + Card() { setCursor(Qt::PointingHandCursor), setMinimumSize(320, 262); } + QSize sizeHint() const override { return {340, 262}; } + void enterEvent(QEvent *) override { hover = true, update(); } + void leaveEvent(QEvent *) override { hover = false, update(); } +}; + +struct ServerCard : Card { + ServerSession *s; + const Actions *act; + ServerCard(ServerSession *x, const Actions *a) : s(x), act(a) + { + connect(x, &ServerSession::updated, this, QOverload<>::of(&QWidget::update)); + connect(x, &ServerSession::analysisUpdated, this, QOverload<>::of(&QWidget::update)); + } + void mouseReleaseEvent(QMouseEvent *e) override { if (e->button() == Qt::LeftButton) act->open(s->config().id); } + void contextMenuEvent(QContextMenuEvent *e) override + { + const QString id = s->config().id; + QMenu m; + m.addAction("Open details", [=] { act->open(id); }), m.addAction("Reconnect", s, &ServerSession::reconnect), m.addSeparator(); + m.addAction("Edit…", [=] { act->edit(id); }), m.addAction("Remove…", [=] { act->remove(id); }); + m.exec(e->globalPos()); + } + void paintEvent(QPaintEvent *) override + { + AA p(this); + const ServerConfig &c = s->config(); + const Metrics &m = s->metrics(); + const Analysis &an = s->analysis(); + const bool live = s->online(); + const QColor sc = statusColor(s->status()), muted = live ? C::text : C::faint; + QLinearGradient bg(0, 0, 0, height()), strip(0, 0, width(), 0); + bg.setColorAt(0, hover ? C::cardHover : C::card), bg.setColorAt(1, C::panel); + strip.setColorAt(0, sc), strip.setColorAt(.6, C::tint(sc, 0)); + 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); + p.setPen(Qt::NoPen), p.setBrush(strip), p.drawRoundedRect(QRectF(1, 1, width() - 2, 6), 3, 3); + p.setBrush(sc), p.drawEllipse(QPointF(22, 28), 5, 5); + p.setFont(pxFont(font(), 16, true)), p.setPen(C::text); + p.drawText(QRectF(36, 16, width() - 120, 24), Qt::AlignVCenter, p.fontMetrics().elidedText(c.name, Qt::ElideRight, width() - 120)); + p.setFont(pxFont(font(), 11)), p.setPen(C::muted); + p.drawText(QRectF(36, 38, width() - 60, 16), Qt::AlignVCenter, p.fontMetrics().elidedText(c.address() + (m.os.isEmpty() ? "" : " · " + m.os), Qt::ElideRight, width() - 60)); + if (live) { // health badge + const QRectF hb(width() - 62, 12, 44, 44); + paintRing(p, hb, an.health, C::health(an.health), 4, false); + p.setFont(pxFont(font(), 15, true)), p.setPen(C::health(an.health)), p.drawText(hb, Qt::AlignCenter, an.grade); + } else { + p.setFont(pxFont(font(), 10, true)); + const QString chip = statusName(s->status()).toUpper(); + const QRectF cr(width() - p.fontMetrics().horizontalAdvance(chip) - 34, 18, p.fontMetrics().horizontalAdvance(chip) + 18, 20); + p.setPen(sc), p.setBrush(C::tint(sc, 40)), p.drawRoundedRect(cr, 10, 10), p.drawText(cr, Qt::AlignCenter, chip); + } + const bool temp = !m.temps.isEmpty(); // four gauges + 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); + const char *names[4] = {"CPU", "Memory", "Disk", temp ? "Temp" : "Swap"}; + for (int i = 0; i < 4; ++i) { + const double cx = 16 + gw * i + gw / 2; + const QRectF r(cx - gs / 2, 66, gs, gs); + 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); + p.setFont(pxFont(font(), 14, true)), p.setPen(muted); + p.drawText(r, Qt::AlignCenter, !live ? "—" : i == 3 && temp ? QString::number(vals[i], 'f', 0) + "°" : QString::number(vals[i], 'f', 0) + "%"); + p.setFont(pxFont(font(), 11)), p.setPen(C::muted), p.drawText(QRectF(cx - gw / 2, r.bottom() - 4, gw, 16), Qt::AlignCenter, names[i]); + } + const QRectF sp(16, 166, width() - 32, 44); // CPU + memory sparkline (last 5 min) + p.setPen(Qt::NoPen), p.setBrush(QColor(0, 0, 0, 40)), p.drawRoundedRect(sp, 8, 8); + for (auto [series, color] : {std::pair{Live::MEM, C::violet}, {Live::CPU, C::accent}}) { + const QVector &v = s->live().s[series]; + const int n = qMin(150, v.size()); + if (n < 2) continue; + QPolygonF line; + 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)); + QPolygonF area = line; + area << QPointF(line.last().x(), sp.bottom() - 2) << QPointF(line.first().x(), sp.bottom() - 2); + p.setPen(Qt::NoPen), p.setBrush(C::tint(color, 40)), p.drawPolygon(area); + p.setPen(QPen(color, 1.5)), p.setBrush(Qt::NoBrush), p.drawPolyline(line); + } + p.setFont(pxFont(font(), 10)), p.setPen(C::accent), p.drawText(sp.adjusted(8, 3, 0, 0), Qt::AlignLeft, "CPU"); + p.setPen(C::violet), p.drawText(sp.adjusted(36, 3, 0, 0), Qt::AlignLeft, "MEM"); + p.setFont(pxFont(font(), 11)); + const QRectF ft(16, 218, width() - 32, 32); + if (!live) { + p.setPen(s->status() == Status::Offline ? C::red : C::muted); + return p.drawText(ft, Qt::AlignVCenter | Qt::TextWordWrap, s->status() == Status::Disabled ? "Monitoring disabled" : s->status() == Status::Offline ? "Unreachable: " + s->lastError() : "Waiting for data…"); + } + p.setPen(C::teal), p.drawText(ft, Qt::AlignLeft, "↓ " + Fmt::rate(m.netRxBps)); + p.setPen(C::pink), p.drawText(ft.adjusted(100, 0, 0, 0), Qt::AlignLeft, "↑ " + Fmt::rate(m.netTxBps)); + 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))); + 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" : "")); + const int rules = s->activeAlerts().size(), alerts = rules + an.findings.size(); + if (!alerts) return; + bool crit = rules; + for (const Finding &f : an.findings) crit |= f.severity == "critical"; + const QString txt = QString("⚠ %1").arg(alerts); + const QColor ac = crit ? C::red : C::amber; + const QRectF ar(ft.right() - p.fontMetrics().horizontalAdvance(txt) - 14, ft.top() + 15, p.fontMetrics().horizontalAdvance(txt) + 14, 17); + p.setPen(Qt::NoPen), p.setBrush(C::tint(ac, 45)), p.drawRoundedRect(ar, 8, 8), p.setPen(ac), p.drawText(ar, Qt::AlignCenter, txt); + } +}; + +struct AddCard : Card { + const Actions *act; + explicit AddCard(const Actions *a) : act(a) {} + void mouseReleaseEvent(QMouseEvent *) override { act->add(); } + void paintEvent(QPaintEvent *) override + { + AA p(this); + const QRectF r = QRectF(rect()).adjusted(2, 2, -2, -2); + const QPointF c = r.center() - QPointF(0, 14); + 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); + p.setPen(QPen(hover ? C::accent : C::muted, 3, Qt::SolidLine, Qt::RoundCap)); + p.drawLine(c - QPointF(14, 0), c + QPointF(14, 0)), p.drawLine(c - QPointF(0, 14), c + QPointF(0, 14)); + p.setFont(pxFont(font(), 14, true)), p.drawText(QRectF(r.left(), c.y() + 26, r.width(), 22), Qt::AlignCenter, "Add server"); + 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"); + } +}; + +// ============================================================================ dashboard +struct DashboardPage : QWidget { + ServerManager *mgr; + const Actions *act; + FlowLayout *flow = new FlowLayout(new QWidget); + QList cards; + AddCard *addCard; + QLineEdit *search = new QLineEdit; + QLabel *subtitle = label({}, "Muted"); + QVector t; + QListWidget *events = new QListWidget; + + DashboardPage(ServerManager *m, const Actions *a) : mgr(m), act(a), addCard(new AddCard(a)) + { + auto *l = page(this); + auto *head = hbox(), *body = hbox(); + auto *titles = new QVBoxLayout; + auto *g = new QGridLayout; + auto *scroll = new QScrollArea; + auto *ev = panel("Recent events", {events}); + titles->addWidget(label("Dashboard", "H1")), titles->addWidget(subtitle); + search->setPlaceholderText("Search servers…"), search->setClearButtonEnabled(true), search->setFixedWidth(240); + head->addLayout(titles), head->addStretch(), head->addWidget(search), head->addWidget(button("+ Add server", "Primary", [this] { act->add(); })); + 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}}); + scroll->setWidgetResizable(true), scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff), scroll->setWidget(flow->parentWidget()); + events->setStyleSheet("QListWidget { background: transparent; border: none; } QListWidget::item { padding: 6px 2px; border-bottom: 1px solid #1f2738; }"); + events->setWordWrap(true), events->setSelectionMode(QAbstractItemView::NoSelection), ev->setFixedWidth(330); + body->addWidget(scroll, 1), body->addWidget(ev); + l->addLayout(head), l->addLayout(g), l->addLayout(body, 1); + connect(search, &QLineEdit::textChanged, this, [this] { filter(); }); + connect(mgr, &ServerManager::listChanged, this, [this] { rebuild(); }); + connect(mgr, &ServerManager::alertsCleared, events, &QListWidget::clear); + connect(mgr, &ServerManager::alertRaised, this, [this](const AlertEvent &e) { + events->insertItem(0, e.time.toString("HH:mm:ss") + " · " + e.serverName + "\n" + e.message); + events->item(0)->setForeground(C::severity(e.severity)); + if (events->count() > 200) delete events->takeItem(200); + }); + } + void rebuild() + { + for (ServerCard *c : qAsConst(cards)) c->hide(), c->deleteLater(); // not deleted at once: a card's own menu may have caused this + cards.clear(), flow->removeWidget(addCard); + for (ServerSession *s : mgr->sessions()) cards << new ServerCard(s, act), flow->addWidget(cards.last()); + flow->addWidget(addCard), filter(), refresh(); + } + void filter() + { + for (ServerCard *c : qAsConst(cards)) + 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)); + flow->invalidate(); + } + void refresh() + { + int online = 0, total = 0, problems = 0; + double cpu = 0, mem = 0, rx = 0, tx = 0, health = 0; + for (ServerSession *s : mgr->sessions()) { + if (!s->config().enabled) continue; + ++total, problems += s->activeAlerts().size(); + if (!s->online()) continue; + const Metrics &m = s->metrics(); + ++online, cpu += m.cpuUsage, mem += m.memPct, rx += m.netRxBps, tx += m.netTxBps, health += s->analysis().health; + for (const Finding &f : s->analysis().findings) problems += f.severity != "info"; + } + subtitle->setText(QString("%1 server(s) monitored · updated %2").arg(mgr->sessions().size()).arg(QTime::currentTime().toString("HH:mm:ss"))); + 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); + t[2]->set(QString::number(problems), problems ? "alerts + insights" : "all clear", problems ? C::red : C::green); + if (!online) { + for (int i : {1, 3, 4, 5}) t[i]->set("—"); + return; + } + t[1]->set(QString::number(qRound(health / online)), "score 0–100", C::health(qRound(health / online))); + t[3]->set(Fmt::pct(cpu / online), {}, C::level(cpu / online)), t[4]->set(Fmt::pct(mem / online), {}, C::level(mem / online)); + t[5]->set(Fmt::rate(rx + tx), "↓ " + Fmt::rate(rx) + " ↑ " + Fmt::rate(tx)); + } +}; + +// ============================================================================ detail page +struct DetailPage : QWidget { + ServerManager *mgr; + const Actions *act; + QPointer s; + QTabWidget *tabs = new QTabWidget; + QLabel *name = label({}, "H1"), *state = new QLabel, *sub = label({}, "Muted"), *chips = label({}, nullptr, true); + QPushButton *pause = button("❚❚ Pause", nullptr, [this] { s->setPaused(!s->isPaused()); }); + QComboBox *span = new QComboBox; + QList conns; + + DetailPage(ServerManager *m, const Actions *a) : mgr(m), act(a) + { + auto *l = page(this, 18); + auto *head = hbox(), *nameRow = hbox(); + auto *titles = new QVBoxLayout, *spanBox = new QVBoxLayout; + auto *power = button("⏻ Power", "Danger"); + auto *pm = new QMenu(power); + nameRow->addWidget(name), nameRow->addWidget(state), nameRow->addStretch(); + titles->addWidget(button("‹ Dashboard", "Flat", [this] { act->back(); }), 0, Qt::AlignLeft), titles->addLayout(nameRow), titles->addWidget(sub), titles->addWidget(chips); + 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); + span->setCurrentIndex(1), spanBox->addWidget(label("LIVE WINDOW", "Section")), spanBox->addWidget(span); + for (bool reboot : {true, false}) { + const QString t = reboot ? "Reboot…" : "Shut down…"; + pm->addAction(t, this, [this, t, reboot] { + 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); + }); + } + pm->addSeparator(), pm->addAction("Remove from monitor…", this, [this] { act->remove(s->config().id); }), power->setMenu(pm); + head->addLayout(titles, 1), head->addLayout(spanBox); + 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); + tabs->setDocumentMode(true), tabs->tabBar()->setElideMode(Qt::ElideNone), tabs->tabBar()->setExpanding(false); + tabs->tabBar()->setFont(pxFont(tabs->tabBar()->font(), 13, true)); + for (const auto &[title, w] : makeTabs()) w->save = [this](const ServerConfig &c) { mgr->update(c); }, tabs->addTab(w, title); + l->setSpacing(6), l->addLayout(head), l->addWidget(tabs, 1); + connect(tabs, &QTabWidget::currentChanged, this, [this] { refreshTab(true); }); + connect(span, QOverload::of(&QComboBox::currentIndexChanged), this, [this] { refreshTab(false); }); + } + Tab *tab(int i) const { return static_cast(tabs->widget(i)); } + void refreshTab(bool withAnalysis) + { + Tab *t = tab(tabs->currentIndex()); + if (!s) return; + t->span = span->currentData().toInt() * 60000LL, t->refresh(); + if (withAnalysis) t->analysis(); + } + void bind(ServerSession *x) + { + for (const auto &c : qAsConst(conns)) disconnect(c); + conns.clear(), s = x; + for (int i = 0; i < tabs->count(); ++i) tab(i)->bind(x); + if (!x) return; + conns << connect(x, &ServerSession::updated, this, [this] { header(), refreshTab(false); }) + << connect(x, &ServerSession::analysisUpdated, this, [this] { header(), tab(tabs->currentIndex())->analysis(); }); + header(), refreshTab(true); + } + void header() + { + const ServerConfig &c = s->config(); + const Metrics &m = s->metrics(); + const Analysis &a = s->analysis(); + QString h; + auto chip = [&](const QString &t, const QString &color = "#b9c3d8") { + if (!t.trimmed().isEmpty()) h += QString("  %1    ").arg(t.toHtmlEscaped().replace(" ", " ").replace("-", "‑"), color); + }; + name->setText(c.name); + state->setText(" ● " + (s->isPaused() ? QString("Paused") : statusName(s->status())).toUpper()); + state->setStyleSheet(QString("color: %1; font-weight: 700; font-size: 12px;").arg((s->isPaused() ? C::amber : statusColor(s->status())).name())); + sub->setText(c.address() + " · " + transportName(c.transport) + (m.hostname.isEmpty() ? "" : " · host " + m.hostname) + + (s->online() ? " · up " + Fmt::duration(m.uptime) : s->status() == Status::Offline ? " · " + s->lastError() : "")); + chip(m.os), chip(m.kernel.isEmpty() ? "" : P::kernelPrefix + m.kernel), chip(m.cpuCount ? QString("%1 cores").arg(m.cpuCount) : ""); + chip(m.memTotal > 0 ? Fmt::bytes(m.memTotal) + " RAM" : ""), chip(c.group, "#7dd3fc"); + if (s->online()) chip(QString("health %1 (%2)").arg(a.health).arg(a.grade), C::health(a.health).name()); + if (c.autopilot.enabled) chip(c.autopilot.dryRun ? "autopilot: dry run" : "autopilot: on", "#a78bfa"); + chips->setText(h), pause->setText(s->isPaused() ? "▶ Resume" : "❚❚ Pause"); + } +}; + +// ============================================================================ add / edit dialog +static bool editServer(QWidget *parent, ServerConfig &cfg, const QStringList &groups) +{ + QDialog dlg(parent); + dlg.setWindowTitle(cfg.name.isEmpty() ? "Add server" : "Edit server — " + cfg.name); + dlg.setMinimumWidth(620); + auto *l = new QVBoxLayout(&dlg); + l->setContentsMargins(24, 20, 24, 20), l->setSpacing(14); + l->addWidget(label(cfg.name.isEmpty() ? "Add a server" : "Edit server", "H2")); + auto *f = new QFormLayout; + 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); + auto *group = new QComboBox, *via = new QComboBox; + auto *port = new QSpinBox, *interval = new QSpinBox; + auto *sudo = new QCheckBox("Run control commands with sudo -n (needs passwordless sudo)"), *enabled = new QCheckBox("Monitoring enabled"); + auto *notes = new QPlainTextEdit(cfg.notes); + auto *browse = button("Browse…", nullptr, [&] { + const QString fn = QFileDialog::getOpenFileName(&dlg, "Private key", QDir::homePath() + "/.ssh"); + if (!fn.isEmpty()) key->setText(fn); + }); + auto *test = button("Test connection"); + auto *hint = label({}, "Muted", true), *result = label({}, nullptr, true); + group->setEditable(true), group->addItems(groups), group->setCurrentText(cfg.group); + via->addItems({"This machine (local)", "SSH — nothing to install on the server"}), via->setCurrentIndex(int(cfg.transport)); + port->setRange(1, 65535), port->setValue(cfg.port), port->setPrefix("port "); + interval->setRange(1, 300), interval->setValue(cfg.interval), interval->setSuffix(" s"); + pass->setEchoMode(QLineEdit::Password), sudo->setChecked(cfg.useSudo), enabled->setChecked(cfg.enabled), notes->setMaximumHeight(70); + name->setPlaceholderText("e.g. web-01"), host->setPlaceholderText("hostname or IP address"), user->setPlaceholderText("default: your local user name"); + key->setPlaceholderText("default keys / ssh-agent (~/.ssh/id_*)"), pass->setPlaceholderText("optional — keys are recommended"); + auto *addr = hbox(), *keyRow = hbox(), *testRow = hbox(); + addr->addWidget(host, 1), addr->addWidget(port), keyRow->addWidget(key, 1), keyRow->addWidget(browse), testRow->addWidget(test), testRow->addWidget(result, 1); + f->addRow("Name", name), f->addRow("Group", group), f->addRow("Connect via", via), f->addRow("Address", addr), f->addRow("User", user); + f->addRow("Private key", keyRow), f->addRow("Password", pass), f->addRow("Sample every", interval), f->addRow("", enabled), f->addRow("Notes", notes); + P::sudo ? f->insertRow(8, "", sudo) : (sudo->setParent(&dlg), sudo->hide()); + auto *bb = new QDialogButtonBox(QDialogButtonBox::Save | QDialogButtonBox::Cancel); + l->addLayout(f), l->addWidget(hint), l->addLayout(testRow), l->addWidget(bb); + auto collect = [&] { + ServerConfig c = cfg; + c.name = name->text().trimmed(), c.group = group->currentText().trimmed(), c.transport = Transport(via->currentIndex()); + c.host = c.transport == Transport::Local ? "" : host->text().trimmed(), c.port = port->value(), c.user = user->text().trimmed(); + c.keyFile = key->text().trimmed(), c.password = pass->text(), c.interval = interval->value(), c.useSudo = sudo->isChecked(); + c.enabled = enabled->isChecked(), c.notes = notes->toPlainText(); + return c; + }; + auto show = [&](const QString &text, const QColor &c) { result->setText(text), result->setStyleSheet("color: " + c.name() + ";"); }; + auto sync = [&] { + const bool ssh = via->currentIndex() == 1; + for (QWidget *w : std::initializer_list{host, port, user, key, browse, pass}) w->setEnabled(ssh); + hint->setText(ssh ? P::sshHint : "Monitors the computer this program runs on. No setup needed."); + if (!ssh && name->text().isEmpty()) name->setText("This computer"); + }; + QObject::connect(via, QOverload::of(&QComboBox::currentIndexChanged), &dlg, sync); + QObject::connect(bb, &QDialogButtonBox::rejected, &dlg, &QDialog::reject); + QObject::connect(bb, &QDialogButtonBox::accepted, &dlg, [&] { + const ServerConfig c = collect(); + if (c.name.isEmpty() || (c.transport == Transport::SSH && c.host.isEmpty())) return show("Please enter a name and an address.", C::red); + dlg.accept(); + }); + QPointer link; + QObject::connect(test, &QPushButton::clicked, &dlg, [&] { // two frames prove that data and rates work + ServerConfig c = collect(); + c.interval = 1; + delete link; + link = new Link(c, &dlg); + auto engine = std::make_shared(); + auto clock = std::make_shared(); + auto frames = std::make_shared(0); + clock->start(), test->setEnabled(false), show("Connecting…", C::amber); + auto finish = [&, l = link.data()](const QString &msg, const QColor &col) { show(msg, col), test->setEnabled(true), l->disconnect(), l->deleteLater(); }; + QObject::connect(link, &Link::snapshot, &dlg, [=](const QByteArray &raw) { + const Metrics m = engine->process(raw, QDateTime::currentMSecsSinceEpoch()); + if (++*frames == 2) + 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); + }); + QObject::connect(link, &Link::disconnected, &dlg, [=](const QString &why) { finish("✗ " + why, C::red); }); + QTimer::singleShot(20000, link, [=] { finish("✗ Timed out after 20 s", C::red); }); + link->start(); + }); + sync(); + if (dlg.exec() != QDialog::Accepted) return false; + cfg = collect(); + return true; +} + +// ============================================================================ main window +struct MainWindow::Ui { + ServerManager *mgr; + Actions act; + QStackedWidget *stack = new QStackedWidget; + DashboardPage *dash = new DashboardPage(mgr, &act); + DetailPage *detail = new DetailPage(mgr, &act); + QWidget *eventsPage = new QWidget; + QTableWidget *events = table({"Time", "Server", "Type", "Message"}, {170, 180, 100}); + QComboBox *eventFilter = new QComboBox; + QListWidget *list = new QListWidget; + QPushButton *navDash = button("▦ Dashboard", "Nav"), *navEvents = button("◉ Events && alerts", "Nav"); + QLabel *badge = new QLabel; + QSystemTrayIcon *tray = nullptr; + int unseen = 0; + bool quitting = false; +}; + +struct ServerItemDelegate : QStyledItemDelegate { // sidebar row: dot, name, alert count, mini CPU/MEM bars + ServerManager *mgr; + ServerItemDelegate(ServerManager *m, QObject *parent) : QStyledItemDelegate(parent), mgr(m) {} + QSize sizeHint(const QStyleOptionViewItem &, const QModelIndex &) const override { return {220, 58}; } + void paint(QPainter *p, const QStyleOptionViewItem &o, const QModelIndex &i) const override + { + ServerSession *s = mgr->session(i.data(Qt::UserRole).toString()); + if (!s) return; + const QRectF r = QRectF(o.rect).adjusted(6, 2, -6, -2); + const Metrics &m = s->metrics(); + int y = int(r.top()) + 34; + p->save(); + p->setRenderHint(QPainter::Antialiasing), p->setPen(Qt::NoPen); + 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); + p->setBrush(statusColor(s->status())), p->drawEllipse(QPointF(r.left() + 14, r.top() + 18), 4.5, 4.5); + p->setFont(pxFont(o.font, 13, true)), p->setPen(C::text); + 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))); + if (const int n = s->activeAlerts().size()) { + const QRectF b(r.right() - 26, r.top() + 10, 20, 16); + 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)); + } + for (auto [lbl, v] : {std::pair{"CPU", m.cpuUsage}, {"MEM", m.memPct}}) { + const QRectF track(r.left() + 56, y - 2, r.width() - 70, 4); + p->setFont(pxFont(o.font, 9)), p->setPen(C::faint), p->drawText(QRectF(r.left() + 26, y - 5, 30, 10), Qt::AlignVCenter, lbl); + p->setPen(Qt::NoPen), p->setBrush(C::grid), p->drawRoundedRect(track, 2, 2); + 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); + y += 11; + } + p->restore(); + } +}; + +MainWindow::MainWindow(ServerManager *mgr) : ui(new Ui{mgr}) +{ + setWindowTitle("Server Monitor"), setWindowIcon(C::appIcon()), resize(1500, 940), setMinimumSize(1100, 700); + + // navigation and server actions + auto nav = [this](QWidget *pageW) { + ui->stack->setCurrentWidget(pageW); + ui->navDash->setChecked(pageW == ui->dash), ui->navEvents->setChecked(pageW == ui->eventsPage); + if (pageW != ui->detail) ui->list->clearSelection(); + }; + auto refreshEvents = [this] { + QVector rs; + for (const AlertEvent &e : ui->mgr->alerts()) + if (!ui->eventFilter->currentIndex() || e.severity == ui->eventFilter->currentText()) rs << e; + fillRows(ui->events, rs, [](const AlertEvent &e) { + return Row{{e.time.toString("yyyy-MM-dd HH:mm:ss"), C::muted}, {e.serverName}, {e.severity.toUpper(), C::severity(e.severity)}, {e.message}}; + }); + }; + auto showDash = [=] { nav(ui->dash), ui->dash->refresh(); }; + auto showEvents = [=] { nav(ui->eventsPage), ui->unseen = 0, ui->badge->hide(), refreshEvents(); }; + auto showServer = [=](const QString &id) { + if (!mgr->session(id)) return; + ui->detail->bind(mgr->session(id)), nav(ui->detail); + for (int i = 0; i < ui->list->count(); ++i) + if (ui->list->item(i)->data(Qt::UserRole) == id) ui->list->setCurrentRow(i); + }; + auto groups = [mgr] { + QStringList g; + for (ServerSession *s : mgr->sessions()) + if (!s->config().group.isEmpty() && !g.contains(s->config().group)) g << s->config().group; + return g; + }; + auto addServer = [=] { + ServerConfig c; + c.id = ServerConfig::newId(); + if (editServer(this, c, groups())) showServer(mgr->add(c)->config().id); + }; + auto editSrv = [=](const QString &id) { + ServerConfig c = mgr->session(id) ? mgr->session(id)->config() : ServerConfig(); + if (mgr->session(id) && editServer(this, c, groups())) mgr->update(c); + }; + auto removeSrv = [=](const QString &id) { + ServerSession *s = mgr->session(id); + if (!s) return; + QMessageBox box(QMessageBox::Warning, "Remove server", QString("Stop monitoring \"%1\" and remove it from the list?").arg(s->config().name), QMessageBox::Cancel, this); + auto *withHist = box.addButton("Remove + delete history", QMessageBox::DestructiveRole), *keep = box.addButton("Remove, keep history files", QMessageBox::AcceptRole); + box.exec(); + if (box.clickedButton() != withHist && box.clickedButton() != keep) return; + if (ui->detail->s == s) ui->detail->bind(nullptr), showDash(); + mgr->remove(id, box.clickedButton() == withHist); + }; + auto selectedId = [this] { return ui->list->currentItem() ? ui->list->currentItem()->data(Qt::UserRole).toString() : QString(); }; + ui->act = {showServer, editSrv, removeSrv, addServer, showDash}; + + // sidebar + auto *central = new QWidget, *side = new QWidget; + auto *h = new QHBoxLayout(central); + auto *sl = new QVBoxLayout(side), *bt = new QVBoxLayout; + auto *brand = hbox(), *evRow = hbox(), *btns = hbox(); + auto *logo = new QLabel, *title = label("Server Monitor"); + h->setContentsMargins(0, 0, 0, 0), h->setSpacing(0), h->addWidget(side), h->addWidget(ui->stack, 1); + setCentralWidget(central); + side->setObjectName("Sidebar"), side->setFixedWidth(260); + logo->setPixmap(C::appIcon().pixmap(34, 34)), title->setStyleSheet("font-size: 16px; font-weight: 800;"); + bt->setSpacing(0), bt->addWidget(title), bt->addWidget(label("monitor · analyze · control", "Muted")); + brand->addWidget(logo), brand->addLayout(bt, 1); + ui->badge->setStyleSheet("background: #ef4444; color: white; border-radius: 9px; padding: 1px 7px; font-size: 11px; font-weight: 700;"), ui->badge->hide(); + evRow->addWidget(ui->navEvents, 1), evRow->addWidget(ui->badge); + ui->navDash->setCheckable(true), ui->navEvents->setCheckable(true); + ui->list->setStyleSheet("QListWidget { background: transparent; border: none; }"); + ui->list->setItemDelegate(new ServerItemDelegate(mgr, ui->list)), ui->list->setMouseTracking(true), ui->list->setContextMenuPolicy(Qt::CustomContextMenu); + btns->setSpacing(6), btns->addWidget(button("+ Add", "Primary", addServer), 1); + btns->addWidget(button("Edit", nullptr, [=] { editSrv(selectedId()); }), 1), btns->addWidget(button("Remove", "Danger", [=] { removeSrv(selectedId()); }), 1); + sl->setContentsMargins(12, 18, 12, 14), sl->setSpacing(6); + sl->addLayout(brand), sl->addSpacing(14), sl->addWidget(ui->navDash), sl->addLayout(evRow), sl->addSpacing(12); + sl->addWidget(label(" SERVERS", "Section")), sl->addWidget(ui->list, 1), sl->addLayout(btns); + + // events page + auto *el = page(ui->eventsPage); + auto *eh = hbox(); + auto *et = new QVBoxLayout; + et->addWidget(label("Events & alerts", "H1")); + et->addWidget(label("Alerts, recoveries, insights and every automatic or manual action, newest first. Also written to alerts.log.", "Muted")); + ui->eventFilter->addItems({"All events", "critical", "warning", "info", "resolved", "action"}); + eh->addLayout(et, 1), eh->addWidget(ui->eventFilter); + eh->addWidget(button("Open log folder", nullptr, [] { QDesktopServices::openUrl(QUrl::fromLocalFile(ServerManager::configDir())); })); + eh->addWidget(button("Clear list", nullptr, [mgr] { mgr->clearAlerts(); })); + el->addLayout(eh), el->addWidget(ui->events, 1); + for (QWidget *w : std::initializer_list{ui->dash, ui->detail, ui->eventsPage}) ui->stack->addWidget(w); + + connect(ui->navDash, &QPushButton::clicked, this, showDash); + connect(ui->navEvents, &QPushButton::clicked, this, showEvents); + connect(ui->list, &QListWidget::itemClicked, this, [=](QListWidgetItem *it) { showServer(it->data(Qt::UserRole).toString()); }); + connect(ui->list, &QWidget::customContextMenuRequested, this, [=](const QPoint &pos) { + QListWidgetItem *it = ui->list->itemAt(pos); + if (!it) return; + const QString id = it->data(Qt::UserRole).toString(); + QMenu m; + m.addAction("Open", [=] { showServer(id); }), m.addAction("Reconnect", [=] { mgr->session(id)->reconnect(); }), m.addSeparator(); + m.addAction("Move up", [=] { mgr->move(id, -1); }), m.addAction("Move down", [=] { mgr->move(id, 1); }), m.addSeparator(); + m.addAction("Edit…", [=] { editSrv(id); }), m.addAction("Remove…", [=] { removeSrv(id); }); + m.exec(ui->list->viewport()->mapToGlobal(pos)); + }); + connect(ui->eventFilter, QOverload::of(&QComboBox::currentIndexChanged), this, refreshEvents); + connect(mgr, &ServerManager::alertsCleared, this, refreshEvents); + connect(mgr, &ServerManager::listChanged, this, [=] { + const QString cur = selectedId(); + ui->list->clear(); + for (ServerSession *s : mgr->sessions()) { + auto *it = new QListWidgetItem(s->config().name, ui->list); + it->setData(Qt::UserRole, s->config().id); + if (s->config().id == cur) ui->list->setCurrentItem(it); + } + }); + connect(mgr, &ServerManager::alertRaised, this, [=](const AlertEvent &e) { + const bool important = e.severity == "critical" || e.severity == "warning" || e.severity == "action"; + if (ui->stack->currentWidget() == ui->eventsPage) refreshEvents(); + else if (important) ui->badge->setText(QString::number(++ui->unseen)), ui->badge->show(); + if (ui->tray && important && QSettings().value("notify", true).toBool()) + ui->tray->showMessage(e.serverName + " — " + e.severity, e.message, e.severity == "critical" ? QSystemTrayIcon::Critical : e.severity == "warning" ? QSystemTrayIcon::Warning : QSystemTrayIcon::Information, 8000); + }); + auto *tick = new QTimer(this); // sidebar bars + dashboard tiles + connect(tick, &QTimer::timeout, this, [this] { + ui->list->viewport()->update(); + if (ui->stack->currentWidget() == ui->dash) ui->dash->refresh(); + }); + tick->start(1000); + + if (QSystemTrayIcon::isSystemTrayAvailable()) { + ui->tray = new QSystemTrayIcon(C::appIcon(), this); + auto *menu = new QMenu(this); + menu->addAction("Show window", this, [this] { showNormal(), raise(), activateWindow(); }); + for (auto [text, key] : {std::pair{"Desktop notifications", "notify"}, {"Keep running in tray when closed", "closeToTray"}}) { + QAction *a = menu->addAction(text); + a->setCheckable(true), a->setChecked(QSettings().value(key, true).toBool()); + connect(a, &QAction::toggled, [k = QString(key)](bool on) { QSettings().setValue(k, on); }); + } + menu->addSeparator(), menu->addAction("Quit", this, [this] { ui->quitting = true, qApp->quit(); }); + ui->tray->setContextMenu(menu), ui->tray->setToolTip("Server Monitor"), ui->tray->show(); + connect(ui->tray, &QSystemTrayIcon::activated, this, [this](QSystemTrayIcon::ActivationReason r) { + if (r == QSystemTrayIcon::Trigger) isVisible() && !isMinimized() ? hide() : (showNormal(), raise(), activateWindow()); + }); + } + restoreGeometry(QSettings().value("geometry").toByteArray()); + showDash(); +} + +void MainWindow::closeEvent(QCloseEvent *e) +{ + QSettings st; + st.setValue("geometry", saveGeometry()); + if (ui->quitting || !ui->tray || !st.value("closeToTray", true).toBool()) return qApp->quit(); + hide(), e->ignore(); + 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); +} + +void MainWindow::saveSnapshots(const QString &dir) +{ + auto settle = [] { QEventLoop loop; QTimer::singleShot(700, &loop, &QEventLoop::quit), loop.exec(); }; // let animations finish + QTabWidget *tabs = ui->detail->tabs; + grab().save(dir + "/00-dashboard.png"); + if (ui->mgr->sessions().isEmpty()) return; + ui->act.open(ui->mgr->sessions()[0]->config().id); + for (int i = 0; i < tabs->count(); ++i) + 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())); + ui->navEvents->click(), settle(), grab().save(dir + "/99-events.png"); +} diff --git a/Server Monitor(cqt-linux)/src/ui/Windows.h b/Server Monitor(cqt-linux)/src/ui/Windows.h new file mode 100644 index 0000000000000000000000000000000000000000..71bc26fbd4c8a818eb3631f899c05804d62a840e --- /dev/null +++ b/Server Monitor(cqt-linux)/src/ui/Windows.h @@ -0,0 +1,22 @@ +// Detail-page tab interface and the main window (sidebar, dashboard, server page, events, tray). +#pragma once +#include "core/Session.h" +#include + +struct Tab : QWidget { // one aspect of the bound server session + QPointer s; + qint64 span = 15 * 60000; // live chart window + std::function save; // persists config edits + virtual void bind(ServerSession *x) { s = x; } + virtual void refresh() {} // new sample (only while visible) + virtual void analysis() {} // analyzer ran +}; +QVector> makeTabs(); + +struct MainWindow : QMainWindow { + explicit MainWindow(ServerManager *mgr); + void saveSnapshots(const QString &dir); // developer aid: PNG of every page + void closeEvent(QCloseEvent *e) override; + struct Ui; + Ui *ui; +}; diff --git a/Server Monitor(cqt-window)/.gitignore b/Server Monitor(cqt-window)/.gitignore new file mode 100644 index 0000000000000000000000000000000000000000..f0bb5faa29b568a9fea0a9119a999c787de9bbd1 --- /dev/null +++ b/Server Monitor(cqt-window)/.gitignore @@ -0,0 +1,2 @@ +build/ +*.user diff --git a/Server Monitor(cqt-window)/CMakeLists.txt b/Server Monitor(cqt-window)/CMakeLists.txt new file mode 100644 index 0000000000000000000000000000000000000000..445ddba37d3aabaa89b3026c93a793151e0fcf83 --- /dev/null +++ b/Server Monitor(cqt-window)/CMakeLists.txt @@ -0,0 +1,12 @@ +cmake_minimum_required(VERSION 3.16) +project(ServerMonitor LANGUAGES CXX) +set(CMAKE_CXX_STANDARD 17) +set(CMAKE_AUTOMOC ON) +find_package(Qt5 5.15 REQUIRED COMPONENTS Widgets) +file(GLOB_RECURSE SRC CONFIGURE_DEPENDS src/*.cpp src/*.h) +add_executable(ServerMonitor WIN32 ${SRC}) +if(MSVC) + target_compile_options(ServerMonitor PRIVATE /utf-8) # the sources are UTF-8 +endif() +target_include_directories(ServerMonitor PRIVATE src) +target_link_libraries(ServerMonitor PRIVATE Qt5::Widgets) diff --git a/Server Monitor(cqt-window)/README.md b/Server Monitor(cqt-window)/README.md new file mode 100644 index 0000000000000000000000000000000000000000..e8cd0a3fa145d6e447b0022b9e02df8e8d871bf4 --- /dev/null +++ b/Server Monitor(cqt-window)/README.md @@ -0,0 +1,47 @@ +# Server Monitor (Windows) + +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`. + +It is the Windows edition of the Linux program in `Server Monitor(cqt-linux)`: the same code with a different `src/core/Platform.cpp`. + +## Build and run + +Install Qt 5.15 (MinGW or MSVC kit), open the matching Qt command prompt in this folder and run: + +```bat +build.bat +build\release\ServerMonitor.exe +``` + +`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. + +## Servers + +Add or remove servers from the sidebar or the dashboard. There are two ways to connect: + +- **This machine:** no setup. +- **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. + +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. + +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. + +## Features + +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`. + +What differs on Windows: + +- **Load average** is computed the Unix way (running + waiting threads, smoothed over 1 / 5 / 15 minutes) from CPU usage and the processor queue length. +- **CPU time** is split into user, kernel and interrupts + DPC. There is no I/O wait or steal counter. +- **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. +- **Failed service** means: start type Automatic, stopped, with an error exit code. +- **Processes:** End task, Kill, Kill tree, and priority classes (Idle … High). Process owners are shown only when the app runs as administrator. +- **Temperatures** appear only if the machine exposes ACPI thermal zones (many do not). GPUs need `nvidia-smi`. +- The default sample interval is 3 s. + +## Status + +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**. + +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. diff --git a/Server Monitor(cqt-window)/ServerMonitor.pro b/Server Monitor(cqt-window)/ServerMonitor.pro new file mode 100644 index 0000000000000000000000000000000000000000..962d24b9adbfc4cbd6402dceffc862e8349c5a99 --- /dev/null +++ b/Server Monitor(cqt-window)/ServerMonitor.pro @@ -0,0 +1,7 @@ +# Qt Creator / qmake project +QT += widgets +CONFIG += c++17 utf8_source +TARGET = ServerMonitor +INCLUDEPATH += src +SOURCES += $$files(src/*.cpp, true) +HEADERS += $$files(src/*.h, true) diff --git a/Server Monitor(cqt-window)/build.bat b/Server Monitor(cqt-window)/build.bat new file mode 100644 index 0000000000000000000000000000000000000000..b90bee9da3591e4db59d481305c41486a52f5bac --- /dev/null +++ b/Server Monitor(cqt-window)/build.bat @@ -0,0 +1,18 @@ +@echo off +rem Build Server Monitor with Qt 5. Run from a Qt command prompt (MinGW or MSVC) so that qmake is on PATH. +setlocal +cd /d "%~dp0" +where qmake >nul 2>nul +if errorlevel 1 ( + echo qmake not found. Open the Qt command prompt or add the Qt bin folder to PATH. + exit /b 1 +) +if not exist build mkdir build +cd build +qmake ..\ServerMonitor.pro "CONFIG+=release" +if errorlevel 1 exit /b 1 +for /f %%s in ('qmake -query QMAKE_XSPEC') do set SPEC=%%s +if "%SPEC%"=="win32-g++" (mingw32-make -j%NUMBER_OF_PROCESSORS%) else (nmake) +if errorlevel 1 exit /b 1 +windeployqt release\ServerMonitor.exe +echo Done: build\release\ServerMonitor.exe diff --git a/Server Monitor(cqt-window)/src/core/History.cpp b/Server Monitor(cqt-window)/src/core/History.cpp new file mode 100644 index 0000000000000000000000000000000000000000..900a01f6cddbf958d9ae6f930a84e9feffcfe907 --- /dev/null +++ b/Server Monitor(cqt-window)/src/core/History.cpp @@ -0,0 +1,367 @@ +#include "History.h" +#include +#include +#include +#include +#include +#include + +const char *const hKeys[H_COUNT] = {"cpu", "iowait", "load", "mem", "swap", "disk", "diskio", "rx", "tx", "rd", "wr", "temp", "procs", "gpu", "failed"}; +const char *const hNames[H_COUNT] = {"CPU", "I/O wait", "Load (1m)", "Memory", "Swap", "Disk usage", "Disk busy", "Net download", + "Net upload", "Disk read", "Disk write", "Temperature", "Processes", "GPU", "Failed services"}; +QString tierName(Tier t) { return QStringList{"every sample", "1 minute", "1 hour", "1 day"}.value(int(t)); } +static const QByteArray kHeader = QByteArray("SMH1") + char(H_COUNT) + char(0) + char(sizeof(HPoint) & 0xff) + char(sizeof(HPoint) >> 8); + +// ---- accumulator ---------------------------------------------------------------- +HistoryStore::Acc::Acc(qint64 b) : bucket(b) { std::fill(mx, mx + H_COUNT, NAN); } +void HistoryStore::Acc::add(const HPoint &p) +{ + n += p.n, nUp += p.nUp; + if (p.nUp) + for (int i = 0; i < H_COUNT; ++i) + if (!std::isnan(p.avg[i])) { + sum[i] += double(p.avg[i]) * p.nUp, cnt[i] += p.nUp; + if (std::isnan(mx[i]) || p.max[i] > mx[i]) mx[i] = p.max[i]; + } +} +HPoint HistoryStore::Acc::point() const +{ + HPoint p; + p.ts = bucket, p.n = n, p.nUp = nUp; + for (int i = 0; i < H_COUNT; ++i) p.avg[i] = cnt[i] ? float(sum[i] / cnt[i]) : NAN, p.max[i] = mx[i]; + return p; +} + +// ---- store ---------------------------------------------------------------------- +QString HistoryStore::file(int t) const { return m_dir + "/" + QStringList{"raw", "minute", "hour", "day"}[t] + ".bin"; } +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 + +HistoryStore::HistoryStore(const QString &dir) : m_dir(dir), m_tz(QDateTime::currentDateTime().offsetFromUtc()) +{ + QDir().mkpath(dir); + const qint64 now = QDateTime::currentSecsSinceEpoch(); + for (int t = 0; t < 4; ++t) { + QFile f(file(t)); + if (!f.open(QIODevice::ReadOnly)) continue; + const QByteArray d = f.readAll(); + if (!d.startsWith(kHeader)) { f.close(), QFile::remove(f.fileName() + ".old"), f.rename(f.fileName() + ".old"); continue; } + int bad = int((d.size() - kHeader.size()) % sizeof(HPoint)); // a cut-off record would misalign everything appended after it + for (int off = kHeader.size(); off + int(sizeof(HPoint)) <= d.size(); off += sizeof(HPoint)) { + HPoint p; + std::memcpy(&p, d.constData() + off, sizeof p); + if (p.ts < now - keep[t] || p.ts > now + 86400 || (!m_t[t].isEmpty() && p.ts <= m_t[t].last().ts)) ++bad; + else m_t[t] << p; + } + if (bad) rewrite(t); + } + 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 + const qint64 stored = m_t[t].isEmpty() ? -1 : m_t[t].last().ts; + auto feed = [&](const HPoint &p) { + const qint64 b = bucketOf(t, p.ts); + if (b <= stored) return; + if (b != m_acc[t].bucket) { + if (m_acc[t].n) append(t, m_acc[t].point()); + m_acc[t] = Acc(b); + } + m_acc[t].add(p); + }; + for (const HPoint &p : qAsConst(m_t[t - 1])) feed(p); + if (m_acc[t - 1].n) feed(m_acc[t - 1].point()); + } +} + +void HistoryStore::rewrite(int t) +{ + QSaveFile f(file(t)); + if (!f.open(QIODevice::WriteOnly)) return; + f.write(kHeader); + f.write(reinterpret_cast(m_t[t].constData()), qint64(m_t[t].size()) * sizeof(HPoint)); + f.commit(); +} + +void HistoryStore::append(int t, const HPoint &p) +{ + auto &v = m_t[t]; + if (!v.isEmpty() && p.ts <= v.last().ts) return; + v << p; + QFile f(file(t)); + if (f.open(QIODevice::Append)) { + if (f.size() < kHeader.size()) f.resize(0), f.write(kHeader); + f.write(reinterpret_cast(&p), sizeof p); + } + if (++m_appends[t] % 500) return; // trim expired points now and then + const auto it = std::find_if(v.begin(), v.end(), [&](const HPoint &x) { return x.ts >= p.ts - keep[t]; }); + if (it != v.begin()) v.erase(v.begin(), it), rewrite(t); +} + +void HistoryStore::add(qint64 ts, const float *val, bool up) +{ + HPoint raw; + raw.ts = ts, raw.n = 1, raw.nUp = up; + for (int i = 0; i < H_COUNT; ++i) raw.avg[i] = raw.max[i] = up ? val[i] : NAN; + append(0, raw); + for (int t = 1; t < 4; ++t) { // every coarser tier accumulates every raw sample + const qint64 b = bucketOf(t, ts); + if (m_acc[t].bucket != b) { + if (m_acc[t].n && m_acc[t].bucket < b) append(t, m_acc[t].point()); + m_acc[t] = Acc(b); + } + m_acc[t].add(raw); + } +} + +QVector HistoryStore::range(qint64 from, qint64 to, Tier tier) const +{ + const int t = int(tier); + const auto &v = m_t[t]; + auto it = std::lower_bound(v.begin(), v.end(), from, [](const HPoint &p, qint64 x) { return p.ts < x; }); + QVector out; + for (; it != v.end() && it->ts <= to; ++it) out << *it; + const Acc &a = m_acc[t]; + if (t && a.n && a.bucket >= from && a.bucket <= to && (out.isEmpty() || out.last().ts < a.bucket)) out << a.point(); + return out; +} + +QVector HistoryStore::range(qint64 from, qint64 to, Tier *used) const +{ + const qint64 now = QDateTime::currentSecsSinceEpoch(), maxSpan[3] = {6 * 3600, 8 * 86400, 400 * 86400}; + int t = 0; + while (t < 3 && (from < now - keep[t] || to - from > maxSpan[t])) ++t; + if (used) *used = Tier(t); + return range(from, to, Tier(t)); +} + +void HistoryStore::removeFiles() { QDir(m_dir).removeRecursively(), *this = HistoryStore(m_dir); } +qint64 HistoryStore::firstTs() const +{ + qint64 f = 0; + for (const auto &v : m_t) + if (!v.isEmpty() && (!f || v[0].ts < f)) f = v[0].ts; + return f; +} +qint64 HistoryStore::diskBytes() const +{ + qint64 b = 0; + for (int t = 0; t < 4; ++t) b += QFileInfo(file(t)).size(); + return b; +} + +Stats stats(const QVector &pts, int m) +{ + Stats s; + QVector v; + double sum = 0, w = 0; + for (const HPoint &p : pts) { + if (!p.nUp || std::isnan(p.avg[m])) continue; + v << p.avg[m], sum += double(p.avg[m]) * p.nUp, w += p.nUp; + if (std::isnan(s.max) || p.max[m] > s.max) s.max = p.max[m]; + } + if (v.isEmpty()) return s; + std::sort(v.begin(), v.end()); + s.count = v.size(), s.avg = sum / w, s.min = v[0], s.p95 = v[qMin(v.size() - 1, int(v.size() * 0.95))]; + return s; +} + +QString fmtMetric(int m, double v) +{ + if (std::isnan(v)) return "—"; + switch (m) { + case H_RX: case H_TX: case H_RD: case H_WR: return Fmt::rate(v); + case H_LOAD: return QString::number(v, 'f', 2); + case H_TEMP: return Fmt::temp(v); + case H_PROCS: case H_FAILED: return QString::number(v, 'f', 0); + default: return Fmt::pct(v); + } +} + +// ---- analysis ------------------------------------------------------------------- +Analysis::Analysis() { std::fill(&heat[0][0][0], &heat[0][0][0] + 336, NAN); } + +double regression(const QVector &pts, int m, double *r2) +{ + double n = 0, sx = 0, sy = 0, sxx = 0, sxy = 0, syy = 0, x0 = pts.isEmpty() ? 0 : pts[0].ts; + for (const HPoint &p : pts) + if (p.nUp && !std::isnan(p.avg[m])) { + const double x = p.ts - x0, y = p.avg[m]; + n++, sx += x, sy += y, sxx += x * x, sxy += x * y, syy += y * y; + } + const double den = n * sxx - sx * sx, num = n * sxy - sx * sy, vy = n * syy - sy * sy; + *r2 = n >= 3 && den > 0 && vy > 1e-9 ? num * num / (den * vy) : 0; // squared correlation + return n >= 3 && den > 0 ? num / den : 0; +} + +Analysis analyze(const HistoryStore &st, const Metrics &m, const AutopilotConfig &ap, const QVector &procs, + const QVector &svcs, bool online) +{ + Analysis a; + const qint64 now = a.when = QDateTime::currentSecsSinceEpoch(); + const auto &minute = st.tier(Tier::Minute), &hour = st.tier(Tier::Hour); + auto add = [&](QString key, QString sev, QString cat, QString title, QString detail, QString advice, QString action = {}, + QString arg = {}, QString label = {}, bool autoOk = false) { + a.findings << Finding{key, sev, cat, title, detail, advice, action, arg, label, autoOk}; + }; + auto sev = [](bool crit, bool warn) { return crit ? "critical" : warn ? "warning" : "info"; }; + + // availability + const qint64 spans[3] = {86400, 7 * 86400, 30 * 86400}; + for (int i = 0; i < 3; ++i) { + double n = 0, up = 0; + for (const HPoint &p : st.range(now - spans[i], now)) n += p.n, up += p.nUp; + a.up[i] = n ? up * 100 / n : NAN; + a.down[i] = n ? (n - up) / n * qMin(spans[i], now - st.firstTs()) : 0; // share of the monitored part of the window + } + if (a.up[0] < 99) + add("avail24", sev(a.up[0] < 95, true), "Availability", QString("Availability last 24 h is %1").arg(Fmt::pct(a.up[0], 2)), + QString("The server could not be reached for about %1 in the last day.").arg(Fmt::duration(a.down[0])), + "Check network stability, power and whether the machine rebooted (uptime)."); + const auto w30 = st.range(now - spans[2], now, Tier::Hour), w7 = st.range(now - spans[1], now, Tier::Minute); + a.cpu30 = stats(w30.size() >= 24 ? w30 : w7, H_CPU), a.mem30 = stats(w30.size() >= 24 ? w30 : w7, H_MEM); + + // disk forecast: regression over 7 d of hours, or 24 h of minutes, whichever fits better + double r2 = 0, r2b = 0, slope = 0; + const auto week = st.range(now - spans[1], now, Tier::Hour), day = st.range(now - 86400, now, Tier::Minute); + if (week.size() >= 48) slope = regression(week, H_DISK, &r2), a.diskBasis = "hourly averages, last 7 days"; + if (day.size() >= 120) { + const double s2 = regression(day, H_DISK, &r2b); + if (week.size() < 48 || r2b > r2) slope = s2, r2 = r2b, a.diskBasis = "minute averages, last 24 hours"; + } + a.diskSlopePerDay = slope * 86400; + if (a.diskSlopePerDay > 0.05 && r2 >= 0.3 && m.maxDiskPct > 0) a.diskFullDays = (100 - m.maxDiskPct) / a.diskSlopePerDay; + if (a.diskFullDays >= 0 && a.diskFullDays < 30) + add("diskfull", sev(a.diskFullDays < ap.diskForecastDays, a.diskFullDays < 14), "Disk", + QString("Disk %1 will be full in %2").arg(m.fullestMount, Fmt::duration(a.diskFullDays * 86400)), + 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), + "Clean logs/caches, rotate or move data, or grow the volume.", "disk_cleanup", "", "Run cleanup", ap.diskCleanup && a.diskFullDays < ap.diskForecastDays); + if (m.maxDiskPct >= ap.diskCleanupAt) + add("diskhigh", sev(m.maxDiskPct >= 97, true), "Disk", QString("Disk %1 is %2 full").arg(m.fullestMount, Fmt::pct(m.maxDiskPct)), + QString("Above the cleanup threshold of %1.").arg(Fmt::pct(ap.diskCleanupAt, 0)), "Free space soon: services fail when the disk is full.", + "disk_cleanup", "", "Run cleanup", ap.diskCleanup); + + // whole-machine memory trend over 6 h + const auto six = st.range(now - 6 * 3600, now, Tier::Minute); + if (six.size() >= 90) { + a.memSlopePerHour = regression(six, H_MEM, &a.memTrendR2) * 3600; + const double left = (100 - m.memPct) / qMax(0.01, a.memSlopePerHour); + if (a.memSlopePerHour > 1 && a.memTrendR2 > 0.8 && m.memPct > 40) + add("memtrend", sev(false, left < 12), "Memory", QString("Memory keeps growing (+%1 points/hour)").arg(a.memSlopePerHour, 0, 'f', 1), + 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)), + "Look for a leaking process (Processes tab, sort by RSS)."); + } + + // processes: leaks and runaways + for (const ProcTrend &p : procs) { + if (p.kernel) continue; + const QString who = QString("%1 (PID %2)").arg(p.name).arg(p.pid), pid = QString::number(p.pid); + if (p.minutesTracked >= 30 && p.rssGrowthPct >= 25 && p.rssGrowth >= 100e6 && p.rssMonotonic >= 0.8) + add("leak:" + pid, sev(m.memPct >= ap.leakMemPressure, true), "Process", "Possible memory leak: " + who, + 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)) + .arg(p.minutesTracked).arg(qRound(p.rssMonotonic * 100)).arg(Fmt::bytes(p.rssNow)), + "Restart the program/service at a quiet time and report the leak upstream.", "kill_pid", pid, "Terminate", + ap.leakMode == "terminate" && m.memPct >= ap.leakMemPressure); + if (p.highCpuMinutes >= ap.runawayMinutes) { + const bool term = ap.runawayMode == "terminate"; + add("runaway:" + pid, "warning", "Process", "Runaway process: " + who, + 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), + "Lower its priority (renice) or stop it if it is stuck.", term ? "kill_pid" : "renice", pid, term ? "Terminate" : "Renice to 19", ap.runawayMode != "none"); + } + } + + // services: failures and flapping + for (const ServiceTrend &s : svcs) { + const bool flap = s.failsLastHour >= 3 || s.autoRestartsLastHour >= ap.maxRestartsPerHour; + if (s.failedNow) + add("svc:" + s.unit, sev(flap, true), "Service", QString(flap ? "Service %1 keeps failing" : "Service %1 has failed").arg(s.unit), + s.preexisting ? "It was already failed when monitoring started, so the autopilot leaves it alone (it may be failed on purpose)." + : QString("Failed %1× in the last hour; autopilot restarted it %2×.").arg(s.failsLastHour).arg(s.autoRestartsLastHour), + flap ? "Automatic restarts were stopped. Read the logs (Services tab → Logs) and fix the cause." : "Restart it and check the logs.", + "restart_service", s.unit, "Restart", ap.restartFailed && !s.preexisting && s.autoRestartsLastHour < ap.maxRestartsPerHour); + else if (s.failsLastHour >= 3) + add("flap:" + s.unit, "warning", "Service", QString("Service %1 is unstable").arg(s.unit), + QString("It failed %1 times within the last hour.").arg(s.failsLastHour), "Inspect its logs and resource limits."); + } + + // overload and swap thrashing + const auto last15 = st.range(now - 900, now, Tier::Minute); + 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; + if (online && load15 / m.cpuCount > 1.5) + 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), + QString("15-minute average load is %1× the number of cores; tasks are waiting for CPU.").arg(load15 / m.cpuCount, 0, 'f', 1), + "Find the busiest processes, spread work over time, or add CPU."); + 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 + 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)) + : QString("Swap %1 used, memory %2 full and disks %3 busy.").arg(Fmt::pct(m.swapPct), Fmt::pct(m.memPct), Fmt::pct(busy15)), + "Stop memory-hungry processes or add RAM."); + + // anomalies: last 10 min vs same weekday+hour over 8 weeks (fallback: last 24 h) + const auto raw = st.range(now - 600, now, Tier::Raw); + const QDateTime lt = QDateTime::fromSecsSinceEpoch(now); + if (online && raw.size() >= 10) + 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}, + {H_IOWAIT, 3.0, false}, {H_RX, 256e3, true}, {H_TX, 256e3, true}}) { + if (hm == H_IOWAIT && !P::posixCpu) continue; + const double cur = stats(raw, hm).avg; + QVector v; + for (const HPoint &p : hour) { + const QDateTime t = QDateTime::fromSecsSinceEpoch(p.ts); + 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()) + v << p.avg[hm]; + } + QString basis = "same weekday & hour, last 8 weeks"; + if (v.size() < 3) { + v.clear(), basis = "last 24 hours"; + for (const HPoint &p : minute) + if (p.nUp && !std::isnan(p.avg[hm]) && now - p.ts <= 86400 && now - p.ts > 900) v << p.avg[hm]; + if (v.size() < 360) continue; + } + double mean = 0, var = 0; + for (double x : v) mean += x / v.size(); + for (double x : v) var += (x - mean) * (x - mean) / v.size(); + const double sd = std::sqrt(var), z = (cur - mean) / qMax(sd, floor); + a.anomalies << Anomaly{hNames[hm], basis, hm, cur, mean, sd, z}; + const bool hi = z >= ap.anomalyZ, lo = down && mean > 1e6 && cur < mean * 0.1; + if (ap.anomalyAlerts && (hi || lo)) + 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()), + 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), + hi ? "Check what changed: deploys, cron jobs, traffic, attacks." : "Traffic dropped sharply - check the service is still serving."); + } + + // weekly heatmaps from 4 weeks of hours + double sum[2][7][24] = {}; + for (const HPoint &p : hour) { + if (now - p.ts > 28 * 86400 || !p.nUp || std::isnan(p.avg[H_CPU])) continue; + const QDateTime t = QDateTime::fromSecsSinceEpoch(p.ts); + const int d = t.date().dayOfWeek() - 1, h = t.time().hour(), n = ++a.heatN[d][h]; + sum[0][d][h] += p.avg[H_CPU], sum[1][d][h] += std::isnan(p.avg[H_MEM]) ? 0 : p.avg[H_MEM]; + a.heat[0][d][h] = sum[0][d][h] / n, a.heat[1][d][h] = sum[1][d][h] / n; + } + + // capacity advice + 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"}, + {a.mem30, "Memory", 30.0, 85.0, "is under-used", "is tight - add RAM or reduce caches/limits"}}) + if (s.count >= 60) + a.capacity << QString("%1 %2 (p95 %3).").arg(name, s.p95 < lo ? loTxt : s.p95 > hi ? hiTxt : "headroom is healthy", Fmt::pct(s.p95)); + 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)); + else if (!a.diskBasis.isEmpty()) a.capacity << "Disk usage is stable."; + if (a.capacity.isEmpty()) a.capacity << "Collecting history - capacity advice appears after about an hour of data."; + + // health score + double score = 100, fp = 0; + auto pen = [&](bool when, double p, const QString &why) { + if (when && p > 0.5) score -= p, a.healthReasons << QString("−%1 %2").arg(qRound(p)).arg(why); + }; + const double cpu = std::isnan(cpu15) ? m.cpuUsage : cpu15; + for (const Finding &f : a.findings) fp += f.category == "Availability" ? 0 : f.severity == "critical" ? 15 : f.severity == "warning" ? 7 : 2; + pen(!online, 60, "server unreachable"); + pen(cpu > 70, qMin(24.0, (cpu - 70) * 0.8), "CPU busy (" + Fmt::pct(cpu) + ")"); + pen(m.memPct > 80, qMin(30.0, (m.memPct - 80) * 1.5), "memory high (" + Fmt::pct(m.memPct) + ")"); + pen(m.maxDiskPct > 80, qMin(40.0, (m.maxDiskPct - 80) * 2), "disk high (" + Fmt::pct(m.maxDiskPct) + ")"); + pen(m.swapPct > 50, 10, "heavy swap use"); + pen(m.maxTemp > 80, qMin(20.0, (m.maxTemp - 80) * 2), "hot (" + Fmt::temp(m.maxTemp) + ")"); + pen(a.up[0] < 100, qMin(30.0, (100 - a.up[0]) * 5), "downtime in last 24 h"); + pen(true, qMin(50.0, fp), QString("%1 finding(s)").arg(a.findings.size())); + a.health = qBound(0, qRound(score), 100); + a.grade = QString("FDCBA").at(a.health >= 90 ? 4 : a.health >= 75 ? 3 : a.health >= 60 ? 2 : a.health >= 40 ? 1 : 0); + auto rank = [](const QString &s) { return s == "critical" ? 0 : s == "warning" ? 1 : 2; }; + std::stable_sort(a.findings.begin(), a.findings.end(), [&](const Finding &x, const Finding &y) { return rank(x.severity) < rank(y.severity); }); + return a; +} diff --git a/Server Monitor(cqt-window)/src/core/History.h b/Server Monitor(cqt-window)/src/core/History.h new file mode 100644 index 0000000000000000000000000000000000000000..ead62778fe8acfa1c2ee1b7db37e33d7b945a72d --- /dev/null +++ b/Server Monitor(cqt-window)/src/core/History.h @@ -0,0 +1,87 @@ +// Persistent multi-resolution history (raw 6 h, minute 30 d, hour 2 y, day 20 y) +// and the statistics-only analyzer that feeds the autopilot. +#pragma once +#include "Model.h" +#include + +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 }; +extern const char *const hKeys[H_COUNT], *const hNames[H_COUNT]; +enum class Tier { Raw, Minute, Hour, Day }; +QString tierName(Tier t); + +#pragma pack(push, 1) +struct HPoint { + qint64 ts = 0; // seconds; bucket start for aggregates + quint32 n = 0, nUp = 0; // samples / online samples + float avg[H_COUNT], max[H_COUNT]; + double uptimePct() const { return n ? nUp * 100.0 / n : 0; } +}; +#pragma pack(pop) + +class HistoryStore { +public: + static constexpr qint64 step[4] = {1, 60, 3600, 86400}, keep[4] = {6 * 3600, 30 * 86400, 732 * 86400, 7320LL * 86400}; + explicit HistoryStore(const QString &dir); + void add(qint64 ts, const float *v, bool up); // up=false records downtime only + const QVector &tier(Tier t) const { return m_t[int(t)]; } + QVector range(qint64 from, qint64 to, Tier t) const; // includes the open bucket + QVector range(qint64 from, qint64 to, Tier *used = nullptr) const; // finest tier covering it + void removeFiles(); + qint64 firstTs() const; + qint64 diskBytes() const; + +private: + struct Acc { + qint64 bucket = -1; + quint32 n = 0, nUp = 0, cnt[H_COUNT] = {}; + double sum[H_COUNT] = {}; + float mx[H_COUNT]; + Acc(qint64 b = -1); + void add(const HPoint &p); + HPoint point() const; + }; + qint64 bucketOf(int t, qint64 ts) const; + void append(int t, const HPoint &p); + void rewrite(int t); + QString file(int t) const; + QString m_dir; + QVector m_t[4]; + Acc m_acc[4]; + qint64 m_tz; + int m_appends[4] = {}; +}; + +struct Stats { double min = NAN, avg = NAN, p95 = NAN, max = NAN; int count = 0; }; // max = peak of max[] +Stats stats(const QVector &pts, int metric); + +// ---- analysis ------------------------------------------------------------------- +struct Finding { + QString key, severity, category, title, detail, advice, action, actionArg, actionLabel; // action: disk_cleanup|restart_service|renice|kill_pid + bool autoEligible = false; +}; +struct ProcTrend { + int pid = 0, minutesTracked = 0; + QString name, user; + double cpuNow = 0, highCpuMinutes = 0, rssNow = 0, rssGrowth = 0, rssGrowthPct = 0, rssMonotonic = 0; + bool kernel = false; +}; +struct ServiceTrend { QString unit; bool failedNow = false, preexisting = false; int failsLastHour = 0, autoRestartsLastHour = 0; }; +struct Anomaly { QString metric, baseline; int hm = 0; double now = 0, mean = 0, sd = 0, z = 0; }; +struct Analysis { + qint64 when = 0; + int health = 100; + QString grade = "A", diskBasis; + QStringList healthReasons, capacity; + QVector findings; + QVector anomalies; + double diskFullDays = -1, diskSlopePerDay = 0, memSlopePerHour = 0, memTrendR2 = 0; + double up[3] = {NAN, NAN, NAN}, down[3] = {}; // 24 h, 7 d, 30 d: availability %, seconds offline + Stats cpu30, mem30; + double heat[2][7][24]; // weekly pattern: 0 = CPU, 1 = memory + int heatN[7][24] = {}; + Analysis(); +}; +Analysis analyze(const HistoryStore &st, const Metrics &m, const AutopilotConfig &ap, const QVector &procs, + const QVector &svcs, bool online); +double regression(const QVector &pts, int metric, double *r2); // slope per second +QString fmtMetric(int metric, double v); diff --git a/Server Monitor(cqt-window)/src/core/Model.cpp b/Server Monitor(cqt-window)/src/core/Model.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d124e3b054e2e77444a315998afa5b6b1f5de433 --- /dev/null +++ b/Server Monitor(cqt-window)/src/core/Model.cpp @@ -0,0 +1,128 @@ +#include "Model.h" +#include +#include +#include +#include + +// ---- formatting ------------------------------------------------------------- +QString Fmt::bytes(double b, int prec) +{ + static const char *u[] = {"B", "KB", "MB", "GB", "TB", "PB"}; + int i = 0; + for (; qAbs(b) >= 1024 && i < 5; ++i) b /= 1024; + return QString::number(b, 'f', i ? prec : 0) + " " + u[i]; +} +QString Fmt::count(double v) +{ + const double a = qAbs(v); + 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); +} +QString Fmt::duration(double sec) +{ + qint64 s = qint64(sec), d = s / 86400, h = s % 86400 / 3600, m = s % 3600 / 60; + 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); +} + +// ---- catalogues ------------------------------------------------------------- +const QVector &ruleMetrics() +{ + static const QVector d = {{"cpu", "CPU usage", "%"}, {"iowait", "CPU I/O wait", "%"}, {"load", "Load (1 min) per core", "%"}, + {"mem", "Memory usage", "%"}, {"swap", "Swap usage", "%"}, {"disk", "Fullest disk usage", "%"}, {"diskio", "Busiest disk utilisation", "%"}, + {"temp", "Hottest sensor", "°C"}, {"rx", "Network download", "MB/s"}, {"tx", "Network upload", "MB/s"}, {"failed", "Failed services", ""}, + {"procs", "Process count", ""}, {"gpu", "GPU usage (max)", "%"}, {"gputemp", "GPU temperature (max)", "°C"}}; + static const QVector noWait = d.mid(0, 1) + d.mid(2); + return P::posixCpu ? d : noWait; +} +QString defLabel(const QVector &d, const QString &k, bool unit) +{ + for (const Def &x : d) + if (x.key == k) return unit ? x.unit : x.label; + return unit ? QString() : k; +} + +QString Rule::conditionText() const +{ + const QString u = defLabel(ruleMetrics(), metric, true); + return QString("%1 %2 %3%4").arg(defLabel(ruleMetrics(), metric), op).arg(value).arg(u.isEmpty() ? "" : " " + u) + (duration ? QString(" for %1 s").arg(duration) : ""); +} +QString Rule::actionText() const { return defLabel(P::ruleActions(), action) + (arg.isEmpty() ? "" : ": " + arg); } + +// ---- JSON: one field list per struct drives both saving and loading --------------------------- +#define F(f) v(#f, x.f); +template 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) } +template 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) } +template static void each(AutopilotConfig &x, V v) +{ + F(enabled) F(dryRun) F(restartFailed) F(diskCleanup) F(anomalyAlerts) F(maxRestartsPerHour) F(runawayMinutes) F(diskForecastDays) + F(runawayCpu) F(diskCleanupAt) F(leakMemPressure) F(anomalyZ) F(runawayMode) F(leakMode) F(diskCleanupCommand) +} +#undef F +template static QJsonObject save(const T &c) +{ + QJsonObject o; + each(const_cast(c), [&](const char *k, const auto &f) { o[k] = QJsonValue::fromVariant(QVariant::fromValue(f)); }); + return o; +} +template static T load(const QJsonObject &o) +{ + T c; + each(c, [&](const char *k, auto &f) { if (o.contains(k)) f = o[k].toVariant().value>(); }); + return c; +} + +static QString xorB64(const QString &s, bool enc) // light obfuscation of secrets (NOT encryption) +{ + static const QByteArray k = "ServerMonitor/obfuscation/v1"; + QByteArray b = enc ? s.toUtf8() : QByteArray::fromBase64(s.toLatin1()); + for (int i = 0; i < b.size(); ++i) b[i] = char(b[i] ^ k[i % k.size()]); + return enc ? QString(b.toBase64()) : QString::fromUtf8(b); +} + +QJsonObject ServerConfig::toJson() const +{ + QJsonObject o = save(*this); + QJsonArray rs; + for (const Rule &r : rules) rs << save(r); + o["transport"] = int(transport), o["password"] = xorB64(password, true), o["rules"] = rs, o["autopilot"] = save(autopilot); + return o; +} + +ServerConfig ServerConfig::fromJson(const QJsonObject &o) +{ + ServerConfig c = load(o); + c.autopilot = load(o["autopilot"].toObject()); + if (o.contains("rules")) c.rules.clear(); + for (const auto &v : o["rules"].toArray()) c.rules << load(v.toObject()); + for (Rule &r : c.rules) + if (r.id.isEmpty()) r.id = newId(); + c.transport = o["transport"].toInt(1) == 0 ? Transport::Local : Transport::SSH; + c.password = xorB64(o["password"].toString(), false); + c.interval = qBound(1, c.interval, 300); + if (c.id.isEmpty()) c.id = newId(); + return c; +} + +QVector ServerConfig::defaultRules() +{ + QVector rs; + for (auto [m, v, d, s] : {std::tuple{"cpu", 90, 60, "warning"}, {"mem", 90, 60, "warning"}, {"swap", 80, 120, "warning"}, + {"disk", 90, 0, "critical"}, {"temp", 85, 30, "critical"}, {"load", 150, 120, "warning"}, {"failed", 0, 0, "warning"}}) { + Rule r; + r.id = newId(), r.metric = m, r.value = v, r.duration = d, r.severity = s; + rs << r; + } + return rs; +} +QString ServerConfig::newId() { return QUuid::createUuid().toString(QUuid::WithoutBraces).left(12); } +QString ServerConfig::address() const +{ + if (transport == Transport::Local) return "this machine"; + return (user.isEmpty() ? "" : user + "@") + host + (port != 22 ? QString(":%1").arg(port) : ""); +} + +double Metrics::gpuMax(bool t) const +{ + double v = 0; + for (const GpuInfo &g : gpus) v = qMax(v, t ? g.temp : g.util); + return v; +} diff --git a/Server Monitor(cqt-window)/src/core/Model.h b/Server Monitor(cqt-window)/src/core/Model.h new file mode 100644 index 0000000000000000000000000000000000000000..1e770def6a71b41063ff737b72918444b947996f --- /dev/null +++ b/Server Monitor(cqt-window)/src/core/Model.h @@ -0,0 +1,118 @@ +// Data model: server config, rules, autopilot policy, parsed metrics, formatting. +#pragma once +#include "Platform.h" +#include +#include +#include +#include +#include + +namespace Fmt { +QString bytes(double b, int prec = 1); +inline QString rate(double b) { return bytes(b) + "/s"; } +inline QString pct(double p, int prec = 1) { return QString::number(p, 'f', prec) + "%"; } +inline QString temp(double c) { return QString::number(c, 'f', 0) + " °C"; } +QString count(double v); +QString duration(double s); +} + +enum class Transport { Local, SSH }; +inline QString transportName(Transport t) { return t == Transport::Local ? "Local" : "SSH"; } + +const QVector &ruleMetrics(); +QString defLabel(const QVector &d, const QString &k, bool unit = false); + +// "When for s -> ()" +struct Rule { + QString id, metric = "cpu", op = ">", action = "notify", arg, severity = "warning"; + bool enabled = true; + double value = 90; + int duration = 60, cooldown = 300; + QString conditionText() const; + QString actionText() const; +}; + +// History-driven automatic control (evaluated by the Analyzer every minute). +struct AutopilotConfig { + bool enabled = true, dryRun = false, restartFailed = true, diskCleanup = false, anomalyAlerts = true; + int maxRestartsPerHour = 3, runawayMinutes = 10, diskForecastDays = 3; + double runawayCpu = 90, diskCleanupAt = 92, leakMemPressure = 90, anomalyZ = 3; + QString runawayMode = "renice", leakMode = "notify"; // none|renice|terminate, none|notify|terminate + QString diskCleanupCommand = P::cleanup; +}; + +struct ServerConfig { + QString id, name, group, host, user, keyFile, password, notes; + Transport transport = Transport::SSH; + int port = 22, interval = P::interval; + bool useSudo = false, enabled = true; + QVector rules = defaultRules(); + AutopilotConfig autopilot; + QString address() const; + QJsonObject toJson() const; + static ServerConfig fromJson(const QJsonObject &o); + static QVector defaultRules(); + static QString newId(); +}; + +// ---- one parsed sample ------------------------------------------------------ +struct CoreStat { double usage = 0, mhz = 0; }; +struct MountInfo { QString device, type, mount; double total = 0, used = 0, avail = 0, pct = 0; }; +struct DiskIO { QString name; double readBps = 0, writeBps = 0, readIops = 0, writeIops = 0, util = 0, totalRead = 0, totalWritten = 0; }; +struct NetIf { + QString name, state; + int speed = -1; + bool virt = false; + double rxBps = 0, txBps = 0, rxPps = 0, txPps = 0, rxBytes = 0, txBytes = 0, errors = 0, drops = 0; +}; +struct ProcInfo { + int pid = 0, ppid = 0, threads = 0, nice = 0; + QString name, user; + QChar state; + double cpu = 0, memPct = 0, rss = 0, vsz = 0, age = 0; // cpu: % of one core +}; +struct ServiceInfo { QString unit, load, active, sub, description; }; +struct TempSensor { QString name; double celsius = 0; }; +struct GpuInfo { int index = 0; QString name; double util = 0, memUsed = 0, memTotal = 0, temp = 0, power = 0, fan = 0; }; + +struct Metrics { + bool valid = false; + qint64 timestamp = 0; + QString hostname, os, kernel, arch, cpuModel, virt; + int cpuCount = 0, loggedUsers = 0, procsRunning = 0, procsBlocked = 0, threadsTotal = 0, socketsUsed = 0; + int servicesFailed = 0, servicesRunning = 0; + double uptime = 0, load1 = 0, load5 = 0, load15 = 0; + double cpuUsage = 0, cpuUser = 0, cpuSystem = 0, cpuIowait = 0, cpuSteal = 0, cpuIrq = 0; + double ctxtPerSec = 0, intrPerSec = 0, forksPerSec = 0, avgMhz = 0; + double memTotal = 0, memFree = 0, memAvailable = 0, memUsed = 0, buffers = 0, cached = 0, shared = 0, slab = 0, dirty = 0; + double swapTotal = 0, swapUsed = 0, memPct = 0, swapPct = 0; + double diskReadBps = 0, diskWriteBps = 0, maxDiskPct = 0, maxDiskUtil = 0, netRxBps = 0, netTxBps = 0, maxTemp = 0; + QString fullestMount, busiestDisk; + QVector cores; + QVector mounts; + QVector disks; + QVector nets; + QMap tcp; // ESTABLISHED -> n + QVector procs; + QVector services; + QVector temps; + QVector gpus; + double gpuMax(bool temp) const; +}; + +// Turns raw collector frames into Metrics; keeps counters for rates. process() is in Platform.cpp. +class MetricsEngine { +public: + Metrics process(const QByteArray &raw, qint64 nowMs); + void reset() { *this = MetricsEngine(); } + +private: + double m_upt = 0; + QVector> m_cpu; + QHash> m_ctr; // misc counters: "stat", "disk:sda", "net:eth0" + QHash m_ticks; + QHash m_info; + QHash m_users; + QVector m_services; + QVector m_gpus; +}; diff --git a/Server Monitor(cqt-window)/src/core/Platform.cpp b/Server Monitor(cqt-window)/src/core/Platform.cpp new file mode 100644 index 0000000000000000000000000000000000000000..0634c1a5de23c04074186f47829ebf19b856c71a --- /dev/null +++ b/Server Monitor(cqt-window)/src/core/Platform.cpp @@ -0,0 +1,377 @@ +// Windows: PowerShell collector (CIM classes + .NET), its parser, and the control commands. +#include "Model.h" +#include +#include +#include +#include + +static const char *const kCollector = R"SMSCRIPT( +# Server Monitor collector for Windows (PowerShell 5.1+, ASCII only). +# The caller prepends "$iv = ; $once = $false". One frame per interval: +# "@@SNAP_BEGIN", "@@S
" + rows (key=value or |-separated), "@@SNAP_END". +$ErrorActionPreference = 'SilentlyContinue' +$ProgressPreference = 'SilentlyContinue' +[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false +function Cim($class, $ns = 'root/cimv2') { Get-CimInstance -ClassName $class -Namespace $ns } +function Clean($s) { ("$s" -replace '[|\r\n]', ' ').Trim() } +$epoch = [DateTime]'1970-01-01' +$smi = Get-Command nvidia-smi.exe | Select-Object -First 1 -ExpandProperty Path +# Console.Out reports no error when the pipe is closed, so the collector also ends when its parent process is gone. +$parent = Get-Process -Id (Get-CimInstance Win32_Process -Filter "ProcessId = $PID").ParentProcessId +$n = 0 +while ($true) { + $t0 = Get-Date + $out = New-Object System.Collections.Generic.List[string] + $out.Add('@@SNAP_BEGIN') + $os = Cim Win32_OperatingSystem + if ($n % 15 -eq 0) { + $cs = Cim Win32_ComputerSystem + $cpu = @(Cim Win32_Processor)[0] + $virt = Clean ($cs.Manufacturer + ' ' + $cs.Model) + $admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) + $out.Add('@@S info') + $out.Add("hostname=$($cs.Name)") + $out.Add("os=$(Clean $os.Caption)") + $out.Add("kernel=$($os.Version)") + $out.Add("arch=$($os.OSArchitecture)") + $out.Add("cpumodel=$(Clean $cpu.Name)") + $out.Add("mhz=$($cpu.MaxClockSpeed)") + $out.Add("virt=$virt") + $out.Add("admin=$([int]$admin)") + if ($admin) { + $out.Add('@@S users') + Get-Process -IncludeUserName | ForEach-Object { $out.Add("$($_.Id)|$($_.UserName)") } + } + } + $out.Add('@@S os') + $out.Add("ts=$([long](([DateTime]::UtcNow - $epoch).TotalMilliseconds))") + $out.Add("uptime=$([long](((Get-Date) - $os.LastBootUpTime).TotalSeconds))") + $out.Add("memtotal=$([long]$os.TotalVisibleMemorySize * 1024)") + $out.Add("swaptotal=$([long]$os.SizeStoredInPagingFiles * 1024)") + $out.Add("swapfree=$([long]$os.FreeSpaceInPagingFiles * 1024)") + $out.Add('@@S cpu') + Cim Win32_PerfFormattedData_PerfOS_Processor | ForEach-Object { + $out.Add("$($_.Name)|$($_.PercentProcessorTime)|$($_.PercentUserTime)|$($_.PercentPrivilegedTime)|$([long]$_.PercentInterruptTime + [long]$_.PercentDPCTime)|$($_.InterruptsPersec)") + } + $sys = Cim Win32_PerfFormattedData_PerfOS_System + $out.Add('@@S sys') + $out.Add("queue=$($sys.ProcessorQueueLength)") + $out.Add("ctxt=$($sys.ContextSwitchesPersec)") + $out.Add("threads=$($sys.Threads)") + $pm = Cim Win32_PerfFormattedData_PerfOS_Memory + $out.Add('@@S mem') + $out.Add("avail=$($pm.AvailableBytes)") + $out.Add("free=$($pm.FreeAndZeroPageListBytes)") + $out.Add("standby=$([long]$pm.StandbyCacheCoreBytes + [long]$pm.StandbyCacheNormalPriorityBytes + [long]$pm.StandbyCacheReserveBytes)") + $out.Add("syscache=$($pm.CacheBytes)") + $out.Add("modified=$($pm.ModifiedPageListBytes)") + $out.Add("pool=$([long]$pm.PoolPagedBytes + [long]$pm.PoolNonpagedBytes)") + $out.Add("commit=$($pm.CommittedBytes)") + $out.Add("commitlimit=$($pm.CommitLimit)") + $out.Add("pages=$($pm.PagesPersec)") + $out.Add('@@S net') + [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | ForEach-Object { + $s = $null + $s = $_.GetIPStatistics() + 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)") } + } + $ip = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties() + $out.Add('@@S tcp') + $ip.GetActiveTcpConnections() | Group-Object State | ForEach-Object { $out.Add("$($_.Name) $($_.Count)") } + $out.Add("Listen $(@($ip.GetActiveTcpListeners()).Count)") + $out.Add('@@S disk') + Cim Win32_PerfFormattedData_PerfDisk_PhysicalDisk | Where-Object { $_.Name -ne '_Total' } | ForEach-Object { + $out.Add("$(Clean $_.Name)|$($_.DiskReadBytesPersec)|$($_.DiskWriteBytesPersec)|$($_.DiskReadsPersec)|$($_.DiskWritesPersec)|$($_.PercentIdleTime)") + } + $out.Add('@@S df') + [System.IO.DriveInfo]::GetDrives() | Where-Object { $_.IsReady -and $_.DriveType -eq 'Fixed' } | ForEach-Object { + $out.Add("$($_.Name)|$(Clean $_.VolumeLabel)|$($_.DriveFormat)|$($_.TotalSize)|$($_.AvailableFreeSpace)") + } + $sessions = @{} + $out.Add('@@S procs') + Cim Win32_Process | ForEach-Object { + $born = 0 + if ($_.CreationDate) { $born = [long](($_.CreationDate.ToUniversalTime() - $epoch).TotalSeconds) } + if ($_.Name -eq 'explorer.exe') { $sessions[$_.SessionId] = 1 } + $out.Add("$($_.ProcessId)|$($_.ParentProcessId)|$([long]$_.KernelModeTime + [long]$_.UserModeTime)|$($_.Priority)|$($_.ThreadCount)|$born|$($_.VirtualSize)|$($_.WorkingSetSize)|$(Clean $_.Name)") + } + $out.Add('@@S sessions') + $out.Add("$($sessions.Count)") + if ($n % 5 -eq 0) { + $out.Add('@@S services') + Cim Win32_Service | ForEach-Object { $out.Add("$($_.Name)|$($_.State)|$($_.StartMode)|$($_.ExitCode)|$(Clean $_.DisplayName)") } + } + $out.Add('@@S thermal') + Cim MSAcpi_ThermalZoneTemperature 'root/wmi' | ForEach-Object { $out.Add("$(Clean $_.InstanceName)|$(($_.CurrentTemperature - 2732) / 10)") } + if ($smi -and $n % 3 -eq 0) { + $out.Add('@@S gpu') + & $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("$_") } + } + $out.Add('@@SNAP_END') + try { [Console]::Out.Write(($out -join "`n") + "`n"); [Console]::Out.Flush() } catch { exit } + if ($once -or $parent.HasExited) { break } + $n++ + $left = $iv * 1000 - ((Get-Date) - $t0).TotalMilliseconds + if ($left -gt 0) { Start-Sleep -Milliseconds ([int]$left) } +} +)SMSCRIPT"; +static const char *const kFailed = "Get-CimInstance Win32_Service | Where-Object { $_.StartMode -eq 'Auto' -and $_.State -eq 'Stopped' -and $_.ExitCode -notin 0, 1077 }"; +static const char *const kRestartFailed = R"PS( | ForEach-Object { "restart $($_.Name)"; Start-Service -Name $_.Name })PS"; + +namespace P { +const char *const prioLabel = "Priority", *const kernelPrefix = "build ", + *const sshHint = "Uses your system ssh client. The server needs the OpenSSH Server feature and PowerShell; nothing else is installed. " + "For key login, add your public key to the server's authorized_keys.", + *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)"; +const bool sudo = false, posixCpu = false; +const int interval = 3, normalPrio = 8; + +// PowerShell runs whatever script arrives on stdin: the encoded command is iex (@($input) -join [char]10) +QStringList shell(int) +{ + return {"powershell", "-NoLogo", "-NoProfile", "-NonInteractive", "-ExecutionPolicy", "Bypass", "-OutputFormat", "Text", "-EncodedCommand", + "aQBlAHgAIAAoAEAAKAAkAGkAbgBwAHUAdAApACAALQBqAG8AaQBuACAAWwBjAGgAYQByAF0AMQAwACkA"}; +} +QByteArray collector(int iv) { return QString("$iv = %1; $once = $false\n").arg(iv).toUtf8() + kCollector; } +QByteArray wrap(const QString &cmd, bool) // no sudo on Windows: run the app elevated for privileged actions +{ + return ("[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false; $ProgressPreference = 'SilentlyContinue'; $Error.Clear(); $global:LASTEXITCODE = 0\n& {\n" + + cmd + "\n} 2>&1 | Out-String -Width 250 -Stream\nif ($LASTEXITCODE) { exit $LASTEXITCODE }\n" + "if ($Error | Where-Object { $_.FullyQualifiedErrorId -notlike 'NativeCommandError*' }) { exit 1 }; exit 0\n").toUtf8(); // stderr text of a program is not a failure +} +QString quote(QString s) { return "'" + s.replace("'", "''") + "'"; } +QString command(const QString &action, const QString &arg) +{ + const QString n = QString::number(arg.toInt()); + return QHash{{"kill_pid", "Stop-Process -Id " + n + " -Force"}, {"renice", "(Get-Process -Id " + n + ").PriorityClass = 'Idle'"}, + {"restart_service", "Restart-Service -Name " + quote(arg) + " -Force"}, {"restart_failed", QString(kFailed) + kRestartFailed}}.value(action); +} +QString serviceLogs(const QString &unit, int lines) +{ + return QString(R"($s = Get-CimInstance Win32_Service | Where-Object Name -eq %1; $s | Format-List Name, DisplayName, State, StartMode, ExitCode, ProcessId, PathName; )" + R"(Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Service Control Manager' } -MaxEvents 3000 -ErrorAction Ignore | )" + R"(Where-Object { $_.Message -like ('*' + $s.DisplayName + '*') } | Select-Object -First %2 | Format-Table TimeCreated, LevelDisplayName, Message -Wrap)") + .arg(quote(unit)).arg(lines); +} +QString power(bool reboot) { return reboot ? "shutdown /r /t 5" : "shutdown /s /t 5"; } +bool isProtected(int pid, int, double rss, const QString &name) +{ + static const QSet system = {"System", "Registry", "Memory Compression", "smss.exe", "csrss.exe", "wininit.exe", "winlogon.exe", "services.exe", + "lsass.exe", "svchost.exe", "sshd.exe", "dwm.exe"}; + return pid <= 4 || rss <= 0 || system.contains(name); +} + +const QVector &ruleActions() +{ + static const QVector d = {{"notify", "Notify only", ""}, {"restart_failed", "Restart failed services", ""}, {"restart_service", "Restart a service", "Spooler"}, + {"kill_top_cpu", "Terminate top CPU process", ""}, {"kill_top_mem", "Terminate top memory process", ""}, {"command", "Run a command", "Clear-DnsClientCache"}}; + return d; +} +const QVector &procActions() +{ + static const QVector d = {{"End task", "taskkill /PID %1"}, {"Kill", "taskkill /F /PID %1", true}, {"Kill tree", "taskkill /F /T /PID %1", true}}; + return d; +} +const QVector &priorities() +{ + static const QVector d = [] { + QVector v; + for (const char *p : {"Idle", "BelowNormal", "Normal", "AboveNormal", "High"}) v << Cmd{p, QString("(Get-Process -Id %1).PriorityClass = '") + p + "'"}; + return v; + }(); + return d; +} +const QVector &serviceActions() +{ + static const QVector d = {{"Start", "Start-Service -Name %1", false, false}, {"Stop", "Stop-Service -Name %1 -Force", true}, {"Restart", "Restart-Service -Name %1 -Force"}, + {"Enable", "Set-Service -Name %1 -StartupType Automatic", false, false}, {"Disable", "Set-Service -Name %1 -StartupType Disabled", true}}; + return d; +} +const QVector &diagnostics() +{ + static const QVector d = { + {"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)"}, + {"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)"}, + {"Memory", "Get-CimInstance Win32_OperatingSystem | Format-List TotalVisibleMemorySize, FreePhysicalMemory, TotalVirtualMemorySize, FreeVirtualMemory"}, + {"Top CPU processes", "Get-Process | Sort-Object CPU -Descending | Select-Object -First 20 Id, ProcessName, CPU, @{ n = 'MemMB'; e = { [int]($_.WorkingSet64 / 1MB) } }, StartTime"}, + {"Listening ports", "Get-NetTCPConnection -State Listen | Sort-Object LocalPort | Format-Table LocalAddress, LocalPort, OwningProcess"}, + {"System errors", "Get-WinEvent -FilterHashtable @{ LogName = 'System'; Level = 1, 2 } -MaxEvents 40 | Format-Table TimeCreated, ProviderName, Message -Wrap"}, + {"Application errors", "Get-WinEvent -FilterHashtable @{ LogName = 'Application'; Level = 1, 2 } -MaxEvents 40 | Format-Table TimeCreated, ProviderName, Message -Wrap"}, + {"Failed services", QString(kFailed) + " | Format-Table Name, ExitCode, DisplayName"}, + {"Logged-in users", "quser"}, + {"Last boots", "Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = 6005, 6006, 1074 } -MaxEvents 15 | Format-Table TimeCreated, Id, Message -Wrap"}}; + return d; +} +const QVector &systemActions() +{ + static const QVector d = {{"Clean temp files", cleanup}, {"Flush DNS cache", "Clear-DnsClientCache; 'done'"}, {"Restart failed services", QString(kFailed) + kRestartFailed}, + {"Reboot", "shutdown /r /t 5", true}, {"Shut down", "shutdown /s /t 5", true}}; + return d; +} +} // namespace P + +// ---- collector frame parser: rows are key=value or |-separated; most values are already rates ---------- +Metrics MetricsEngine::process(const QByteArray &raw, qint64 now) +{ + QHash sec; + QStringList *cur = nullptr; + for (const QByteArray &line : raw.split('\n')) { + const QString l = QString::fromUtf8(line).trimmed(); + if (l.startsWith("@@S ")) cur = &sec[l.mid(4)]; + else if (cur && !l.isEmpty() && !l.startsWith("@@")) cur->append(l); + } + auto kv = [&](const char *k) { + QHash h; + for (const QString &l : sec.value(k)) + if (const int e = l.indexOf('='); e > 0) h[l.left(e)] = l.mid(e + 1); + return h; + }; + auto rows = [&](const char *k, int minFields) { + QVector r; + for (const QString &l : sec.value(k)) + if (const QStringList f = l.split('|'); f.size() >= minFields) r << f; + return r; + }; + Metrics m; + m.timestamp = now; + if (sec.contains("info")) m_info = kv("info"); + if (sec.contains("users")) { + m_users.clear(); + for (const auto &f : rows("users", 2)) + if (!f[1].isEmpty()) m_users[f[0].toInt()] = f[1]; + } + m.hostname = m_info["hostname"], m.os = m_info["os"], m.kernel = m_info["kernel"], m.arch = m_info["arch"]; + m.cpuModel = m_info["cpumodel"], m.virt = m_info["virt"]; + const auto os = kv("os"); + const double ts = os["ts"].toDouble() / 1000; // collector clock, seconds + m.uptime = os["uptime"].toDouble(); + if (m.uptime <= 0 || ts <= 0) return m; + const double dt = m_upt > 0 ? ts - m_upt : 0; + const bool rates = dt > 0.05; + QHash> next; + auto delta = [&](const QString &key, const QVector &v) { // per-second rates of a counter vector + QVector d(v.size(), 0.0); + const auto p = m_ctr.value(key); + if (rates && p.size() == v.size()) + for (int i = 0; i < v.size(); ++i) d[i] = qMax(0.0, (v[i] - p[i]) / dt); + next[key] = v; + return d; + }; + auto pct = [](const QString &s) { return qBound(0.0, s.toDouble(), 100.0); }; + + // CPU: privileged time includes interrupts + DPCs; show them apart + QMap cores; + m.avgMhz = m_info["mhz"].toDouble(); + for (const auto &f : rows("cpu", 5)) { + if (f[0] != "_Total") { cores[f[0].toInt()] = {pct(f[1]), m.avgMhz}; continue; } + 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(); + } + m.cores = cores.values().toVector(); + m.cpuCount = qMax(1, m.cores.size()); + + // load average with the Unix meaning: running + waiting threads, smoothed over 1 / 5 / 15 minutes + const auto sys = kv("sys"); + const double queue = sys["queue"].toDouble(), inst = m.cpuUsage / 100 * m.cpuCount + queue, spans[3] = {60, 300, 900}; + QVector load = m_ctr.value("load", {inst, inst, inst}); + 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 + next["load"] = load; + m.load1 = load[0], m.load5 = load[1], m.load15 = load[2]; + m.ctxtPerSec = sys["ctxt"].toDouble(), m.procsRunning = qRound(m.cpuUsage / 100 * m.cpuCount), m.procsBlocked = int(queue); + + // memory: standby pages are the file cache, the page file is swap + const auto mem = kv("mem"); + m.memTotal = os["memtotal"].toDouble(), m.memAvailable = mem["avail"].toDouble(), m.memFree = mem["free"].toDouble(); + m.cached = mem["standby"].toDouble() + mem["syscache"].toDouble(), m.slab = mem["pool"].toDouble(), m.dirty = mem["modified"].toDouble(); + m.memUsed = qMax(0.0, m.memTotal - m.memAvailable), m.swapTotal = os["swaptotal"].toDouble(), m.swapUsed = qMax(0.0, m.swapTotal - os["swapfree"].toDouble()); + m.memPct = m.memTotal > 0 ? m.memUsed * 100 / m.memTotal : 0; + m.swapPct = m.swapTotal > 0 ? m.swapUsed * 100 / m.swapTotal : 0; + + // network: a VM's own NIC ("Microsoft Hyper-V Network Adapter") counts as physical, host-side virtual switches do not + static const QRegularExpression virt("virtual ethernet|virtualbox|vmware virtual|vethernet|loopback|pseudo|tap-|bluetooth|wan miniport|wsl|docker", QRegularExpression::CaseInsensitiveOption); + for (const auto &f : rows("net", 10)) { + NetIf n; + n.name = f[0], n.state = f[1].toLower(), n.speed = f[2].toInt() > 0 ? f[2].toInt() : -1; + n.virt = f[3] == "Loopback" || f[3] == "Tunnel" || virt.match(f[0] + " " + f.value(10)).hasMatch(); + n.rxBytes = f[4].toDouble(), n.txBytes = f[5].toDouble(), n.errors = f[8].toDouble(), n.drops = f[9].toDouble(); + const auto d = delta("net:" + n.name, {n.rxBytes, n.txBytes, f[6].toDouble(), f[7].toDouble()}); + n.rxBps = d[0], n.txBps = d[1], n.rxPps = d[2], n.txPps = d[3]; + if (!n.virt) m.netRxBps += n.rxBps, m.netTxBps += n.txBps; + m.nets << n; + } + 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; }); + static const QHash tcpNames = {{"Established", "ESTABLISHED"}, {"Listen", "LISTEN"}, {"TimeWait", "TIME_WAIT"}, {"CloseWait", "CLOSE_WAIT"}}; + for (const QString &l : sec.value("tcp")) { + const QStringList f = l.split(' '); + m.tcp[tcpNames.value(f[0], f[0].toUpper())] += f.value(1).toInt(), m.socketsUsed += f.value(1).toInt(); + } + + // disks and volumes + for (const auto &f : rows("disk", 6)) { + DiskIO d; + d.name = f[0], d.readBps = f[1].toDouble(), d.writeBps = f[2].toDouble(), d.readIops = f[3].toDouble(), d.writeIops = f[4].toDouble(); + d.util = f[5].isEmpty() ? 0 : 100 - pct(f[5]); // field = idle % + m.diskReadBps += d.readBps, m.diskWriteBps += d.writeBps; + if (d.util >= m.maxDiskUtil) m.maxDiskUtil = d.util, m.busiestDisk = d.name; + m.disks << d; + } + for (const auto &f : rows("df", 5)) { + MountInfo mt; + 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; + if (mt.total <= 0) continue; + mt.pct = mt.used * 100 / mt.total; + if (mt.pct >= m.maxDiskPct) m.maxDiskPct = mt.pct, m.fullestMount = mt.mount; + m.mounts << mt; + } + + // processes: "pid|ppid|cpuTime (100 ns)|priority|threads|created (unix s)|vsz|rss|name" + QHash ticks; + int fresh = 0; + for (const auto &f : rows("procs", 9)) { + ProcInfo p; + if ((p.pid = f[0].toInt()) <= 0) continue; // 0 = idle process + const double born = f[5].toDouble(); + 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; + p.vsz = f[6].toDouble(), p.rss = f[7].toDouble(), p.name = f.mid(8).join('|'); + ticks[p.pid] = f[2].toDouble(); + if (!m_ticks.contains(p.pid)) ++fresh; + else if (rates) p.cpu = qBound(0.0, (ticks[p.pid] - m_ticks[p.pid]) / 1e7 / dt * 100, 100.0 * m.cpuCount); + p.state = p.cpu > 0.5 ? 'R' : 'S'; + p.memPct = m.memTotal > 0 ? p.rss * 100 / m.memTotal : 0; + p.user = m_users.value(p.pid, "—"); + m.threadsTotal += p.threads; + m.procs << p; + } + m.forksPerSec = rates ? fresh / dt : 0; + 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; }); + m.loggedUsers = sec.value("sessions").value(0).toInt(); + + // services / GPUs arrive every few samples: keep the last list. "Failed" = automatic, stopped, with an error exit code + if (sec.contains("services")) { + m_services.clear(); + for (const auto &f : rows("services", 5)) { + const bool failed = f[2] == "Auto" && f[1] == "Stopped" && f[3].toInt() != 0 && f[3].toInt() != 1077; + m_services << ServiceInfo{f[0], f[2], failed ? "failed" : f[1] == "Running" ? "active" : "inactive", f[1].toLower(), f.mid(4).join('|')}; + } + } + m.services = m_services; + for (const auto &s : m.services) m.servicesFailed += s.active == "failed", m.servicesRunning += s.sub == "running"; + if (sec.contains("gpu")) { + m_gpus.clear(); + for (const QString &l : sec.value("gpu")) { + const QStringList f = l.split(','); + auto n = [&](int i) { return f[i].trimmed().toDouble(); }; + 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)}; + } + } + m.gpus = m_gpus; + QSet tn; + for (const auto &f : rows("thermal", 2)) { + TempSensor t{f[0], f[1].toDouble()}; + if (t.celsius <= 0 || t.celsius > 150 || tn.contains(t.name)) continue; + tn << t.name, m.temps << t, m.maxTemp = qMax(m.maxTemp, t.celsius); + } + + m_ctr = next, m_ticks = ticks, m_upt = ts; + m.valid = rates; // the first sample has no rates yet + return m; +} diff --git a/Server Monitor(cqt-window)/src/core/Platform.h b/Server Monitor(cqt-window)/src/core/Platform.h new file mode 100644 index 0000000000000000000000000000000000000000..2df02dc28a4462bcfd3d5c8eb6e8d5f1b008ec24 --- /dev/null +++ b/Server Monitor(cqt-window)/src/core/Platform.h @@ -0,0 +1,25 @@ +// Everything that depends on the operating system of the monitored machines: how to start a shell, the +// collector script with its parser (MetricsEngine::process), and the control commands. Linux and Windows +// editions differ only in Platform.cpp. +#pragma once +#include +#include + +struct Def { QString key, label, unit; }; // rule metric / action catalogue +struct Cmd { QString label, cmd; bool danger = false, confirm = true, button = true; }; // cmd: %1 = pid or quoted name + +namespace P { +extern const char *const prioLabel, *const kernelPrefix, *const sshHint, *const cleanup; // cleanup: default disk cleanup command +extern const bool sudo, posixCpu; // "sudo -n" exists; CPU time has I/O wait + steal +extern const int interval, normalPrio; // default sample interval (s); priority value of an ordinary process +QStringList shell(int interval = 0); // argv of a shell that runs a script from stdin (interval > 0: collector arguments) +QByteArray collector(int interval); // stdin for the collector +QByteArray wrap(const QString &cmd, bool sudo); // stdin for a one-shot command +QString quote(QString s); // shell quoting +QString command(const QString &action, const QString &arg); // kill_pid | renice | restart_service | restart_failed | drop_caches +QString serviceLogs(const QString &unit, int lines); +QString power(bool reboot); +bool isProtected(int pid, int ppid, double rss, const QString &name); // never killed automatically, no leak / runaway findings +const QVector &ruleActions(); // unit = argument hint ("" = none) +const QVector &procActions(), &priorities(), &serviceActions(), &diagnostics(), &systemActions(); +} diff --git a/Server Monitor(cqt-window)/src/core/Session.cpp b/Server Monitor(cqt-window)/src/core/Session.cpp new file mode 100644 index 0000000000000000000000000000000000000000..afd54dd3a321f81fb876747c93c1be4bf86974b8 --- /dev/null +++ b/Server Monitor(cqt-window)/src/core/Session.cpp @@ -0,0 +1,448 @@ +#include "Session.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// ---- Link --------------------------------------------------------------------------------- +Link::Link(const ServerConfig &c, QObject *parent) : QObject(parent), m_c(c) {} +Link::~Link() +{ + for (QProcess *p : findChildren()) { + p->disconnect(this); + if (p->state() != QProcess::NotRunning) p->kill(), p->waitForFinished(500); + } +} + +QProcess *Link::spawn(const QStringList &shell) +{ + auto *p = new QProcess(this); + QStringList a; + if (m_c.transport == Transport::Local) { + p->setProgram(shell[0]), p->setArguments(shell.mid(1)); + } else { + for (const char *o : {"ConnectTimeout=10", "ServerAliveInterval=10", "ServerAliveCountMax=3", "StrictHostKeyChecking=accept-new", "LogLevel=ERROR"}) a << "-o" << o; + auto env = QProcessEnvironment::systemEnvironment(); + if (m_c.password.isEmpty()) a << "-o" << "BatchMode=yes"; + else { // our own executable answers ssh's password prompt (see main.cpp) + a << "-o" << "NumberOfPasswordPrompts=1"; + env.insert("SSH_ASKPASS", QDir::toNativeSeparators(QCoreApplication::applicationFilePath())); + env.insert("SSH_ASKPASS_REQUIRE", "force"); + env.insert("SERVERMONITOR_ASKPASS", m_c.password); + if (!env.contains("DISPLAY")) env.insert("DISPLAY", ":0"); + } + p->setProcessEnvironment(env); + if (!m_c.keyFile.isEmpty()) a << "-i" << (m_c.keyFile.startsWith("~/") ? QDir::homePath() + m_c.keyFile.mid(1) : m_c.keyFile); + if (m_c.port != 22) a << "-p" << QString::number(m_c.port); + p->setProgram("ssh"), p->setArguments(a << "-T" << (m_c.user.isEmpty() ? m_c.host : m_c.user + "@" + m_c.host) << shell.join(' ')); + } + return p; +} +// Started only after the signals are connected: on Windows a failed start is reported inside start(). +static void feed(QProcess *p, const QByteArray &input) +{ + p->start(); + if (p->state() != QProcess::NotRunning) p->write(input), p->closeWriteChannel(); +} + +void Link::start() +{ + QProcess *p = spawn(P::shell(m_c.interval)); + connect(p, &QProcess::readyReadStandardOutput, this, [this, p] { + m_buf += p->readAllStandardOutput(); + for (int end; (end = m_buf.indexOf("@@SNAP_END")) >= 0;) { + const int begin = m_buf.lastIndexOf("@@SNAP_BEGIN", end); + if (begin >= 0) emit snapshot(m_buf.mid(begin, end - begin)); + m_buf.remove(0, end + 10); + } + if (m_buf.size() > 8 << 20) m_buf.clear(); + }); + connect(p, &QProcess::readyReadStandardError, this, [this, p] { m_err = (m_err + p->readAllStandardError()).right(4096); }); + connect(p, QOverload::of(&QProcess::finished), this, [this](int code) { + const QStringList l = QString(m_err).split('\n', Qt::SkipEmptyParts); + emit disconnected(l.isEmpty() ? QString("connection closed (exit code %1)").arg(code) : l.last()); + }); + connect(p, &QProcess::errorOccurred, this, [this, p](QProcess::ProcessError e) { + if (e == QProcess::FailedToStart) emit disconnected("cannot start " + p->program() + ": " + p->errorString()); + }); + feed(p, P::collector(m_c.interval)); +} + +int Link::exec(const QByteArray &input, int timeoutMs) +{ + const int id = m_next++; + QProcess *p = spawn(P::shell()); + p->setProcessChannelMode(QProcess::MergedChannels); + QTimer::singleShot(timeoutMs, p, [p] { p->kill(); }); + connect(p, QOverload::of(&QProcess::finished), this, [this, p, id](int code, QProcess::ExitStatus st) { + emit execFinished(id, st == QProcess::CrashExit ? -1 : code, p->readAll() + (st == QProcess::CrashExit ? "\n[killed or timed out]" : "")); + p->deleteLater(); + }); + connect(p, &QProcess::errorOccurred, this, [this, p, id](QProcess::ProcessError e) { + if (e == QProcess::FailedToStart) emit execFinished(id, -1, p->errorString()), p->deleteLater(); + }, Qt::QueuedConnection); // queued: the caller has to learn the id first + feed(p, input); + return id; +} + +// ---- live history ----------------------------------------------------------------------- +QString statusName(Status s) { return QStringList{"Disabled", "Connecting", "Online", "Offline"}.value(int(s)); } + +void Live::push(const Metrics &m) +{ + const int cap = 1800, n = t.size() + 1; + auto add = [&](QVector &v, double x) { + if (v.size() < n - 1) v.insert(0, n - 1 - v.size(), 0.0); // align series that appeared later + v << x; + if (v.size() > cap) v.remove(0, v.size() - cap); + }; + t << m.timestamp; + if (t.size() > cap) t.remove(0, t.size() - cap); + const double vals[N] = {m.cpuUsage, m.cpuUser, m.cpuSystem + m.cpuIrq, m.cpuIowait, m.cpuSteal, m.memPct, + m.memTotal > 0 ? (m.cached + m.buffers) * 100 / m.memTotal : 0, m.swapPct, m.netRxBps, m.netTxBps, + m.diskReadBps, m.diskWriteBps, m.load1}; + for (int i = 0; i < N; ++i) add(s[i], vals[i]); + for (const NetIf &i : m.nets) add(ifRx[i.name], i.rxBps), add(ifTx[i.name], i.txBps); +} + +// ---- session ---------------------------------------------------------------------------- +ServerSession::ServerSession(const ServerConfig &c, QObject *parent) : QObject(parent), m_cfg(c), m_store(ServerManager::configDir() + "/history/" + c.id) +{ + m_retry.setSingleShot(true), m_watchdog.setSingleShot(true); + connect(&m_retry, &QTimer::timeout, this, &ServerSession::start); + connect(&m_watchdog, &QTimer::timeout, this, [this] { onLost("no data received (timeout)"); }); + connect(&m_analysisTimer, &QTimer::timeout, this, &ServerSession::analyzeNow); + connect(&m_offlineTick, &QTimer::timeout, this, [this] { // downtime -> availability: one sample per interval, like uptime + if (m_status == Status::Offline || (m_status == Status::Connecting && m_retries)) record(false); + }); + m_analysisTimer.start(60000), m_offlineTick.start(c.interval * 1000); + QTimer::singleShot(3000, this, &ServerSession::analyzeNow); +} +ServerSession::~ServerSession() { stop(); } + +void ServerSession::setConfig(const ServerConfig &c) +{ + const bool reconnect = c.transport != m_cfg.transport || c.host != m_cfg.host || c.port != m_cfg.port || c.user != m_cfg.user || + c.keyFile != m_cfg.keyFile || c.password != m_cfg.password || c.interval != m_cfg.interval || c.enabled != m_cfg.enabled; + m_cfg = c, m_offlineTick.setInterval(c.interval * 1000); + if (reconnect) m_live = Live(), m_m = Metrics(), m_procs.clear(), m_svcs.clear(), c.enabled ? start() : stop(); // may be another machine now + emit updated(); +} + +void ServerSession::drop(const QString &why) +{ + if (m_link) m_link->disconnect(this), m_link->deleteLater(); + m_link = nullptr; + for (const Done &d : std::exchange(m_pending, {})) d(-1, why); +} + +void ServerSession::start() +{ + drop("connection restarted"); + m_retry.stop(); + if (!m_cfg.enabled) return setStatus(Status::Disabled); + m_engine.reset(), m_m.valid = false; // online() only again with a fresh sample + m_link = new Link(m_cfg, this); + connect(m_link, &Link::snapshot, this, &ServerSession::onFrame); + connect(m_link, &Link::disconnected, this, &ServerSession::onLost); + connect(m_link, &Link::execFinished, this, [this](int id, int code, const QString &out) { if (Done d = m_pending.take(id)) d(code, out); }); + setStatus(Status::Connecting), m_watchdog.start(25000), m_link->start(); +} + +void ServerSession::stop() +{ + m_retry.stop(), m_watchdog.stop(), drop("connection stopped"); + setStatus(m_cfg.enabled ? Status::Offline : Status::Disabled); +} + +void ServerSession::setStatus(Status s, const QString &err) +{ + if (!err.isEmpty() || s == Status::Online) m_err = err; + if (s != m_status) m_status = s, emit updated(); +} + +void ServerSession::onFrame(const QByteArray &raw) +{ + const qint64 now = QDateTime::currentMSecsSinceEpoch(); + m_watchdog.start(qMax(15, m_cfg.interval * 5 + 10) * 1000); + Metrics m = m_engine.process(raw, now); + if (m.uptime <= 0) return; + if (m_status != Status::Online) { + m_retries = 0; + if (std::exchange(m_offlineAlerted, false)) raise("resolved", "Server is back online"); + setStatus(Status::Online); + } + if (!m.valid || m_paused) return; // first sample has no rates yet + if (m.uptime < m_m.uptime) m_procs.clear(); // rebooted: PIDs start again, old trends would be blamed on new processes + const bool first = !m_m.valid; // first sample of this connection: analyze at once, the last analysis saw "unreachable" + m_m = m, m_live.push(m), record(true), track(now), evaluateRules(); + if (first) analyzeNow(); + emit updated(); +} + +void ServerSession::onLost(const QString &why) +{ + m_watchdog.stop(), drop("connection lost: " + why); + const bool was = m_status == Status::Online; + setStatus(Status::Offline, why); + if ((was || m_retries == 1) && !m_offlineAlerted) raise("critical", "Server is unreachable: " + why), m_offlineAlerted = true; + if (m_cfg.enabled) m_retry.start(QVector{3, 5, 10, 20, 30, 60}[qMin(m_retries++, 5)] * 1000); // back-off +} + +void ServerSession::exec(const QString &cmd, bool privileged, Done done, int timeoutMs) +{ + if (!m_link || m_status != Status::Online) { + if (done) QTimer::singleShot(0, this, [done] { done(-1, "server is not connected"); }); + return; + } + const int id = m_link->exec(P::wrap(cmd, privileged && m_cfg.useSudo), timeoutMs); + if (done) m_pending[id] = done; +} + +double ServerSession::metricValue(const QString &k) const +{ + const Metrics &m = m_m; + const QHash v = {{"cpu", m.cpuUsage}, {"iowait", m.cpuIowait}, {"load", m.load1 * 100 / qMax(1, m.cpuCount)}, + {"mem", m.memPct}, {"swap", m.swapPct}, {"disk", m.maxDiskPct}, {"diskio", m.maxDiskUtil}, {"temp", m.maxTemp}, + {"rx", m.netRxBps / 1e6}, {"tx", m.netTxBps / 1e6}, {"failed", double(m.servicesFailed)}, {"procs", double(m.procs.size())}, + {"gpu", m.gpuMax(false)}, {"gputemp", m.gpuMax(true)}}; + return v.value(k); +} + +QStringList ServerSession::activeAlerts() const +{ + QStringList out; + if (m_status == Status::Offline) out << "Unreachable: " + m_err; + for (const Rule &r : m_cfg.rules) + if (m_rules.value(r.id).active) out << r.conditionText(); + return out; +} + +void ServerSession::raise(const QString &sev, const QString &msg) { emit alertRaised({QDateTime::currentDateTime(), m_cfg.name, sev, msg}); } + +void ServerSession::record(bool up) +{ + const Metrics &m = m_m; + const float v[H_COUNT] = {float(m.cpuUsage), float(m.cpuIowait), float(m.load1), float(m.memPct), m.swapTotal > 0 ? float(m.swapPct) : NAN, + m.mounts.isEmpty() ? NAN : float(m.maxDiskPct), float(m.maxDiskUtil), float(m.netRxBps), float(m.netTxBps), + float(m.diskReadBps), float(m.diskWriteBps), m.temps.isEmpty() ? NAN : float(m.maxTemp), float(m.procs.size()), + m.gpus.isEmpty() ? NAN : float(m.gpuMax(false)), float(m.servicesFailed)}; + m_store.add(QDateTime::currentSecsSinceEpoch(), v, up); +} + +// per-process CPU streaks + RSS per minute; service failure transitions +void ServerSession::track(qint64 now) +{ + QHash procs; + for (const ProcInfo &p : qAsConst(m_m.procs)) { + ProcTrack t = m_procs.value(p.pid); + if (t.name != p.name) t = ProcTrack{p.name}; // new or pid reused + t.kernel = P::isProtected(p.pid, p.ppid, p.rss, p.name); + t.highSince = p.cpu < m_cfg.autopilot.runawayCpu ? 0 : t.highSince ? t.highSince : now; + if (now - t.lastMinute >= 60000) t.lastMinute = now, t.rss << p.rss; + if (t.rss.size() > 60) t.rss.removeFirst(); + procs[p.pid] = t; + } + m_procs = procs; + QHash svcs; + for (const ServiceInfo &s : qAsConst(m_m.services)) { + SvcTrack &t = svcs[s.unit] = m_svcs.value(s.unit); + const bool failed = s.active == "failed"; + if (t.last.isEmpty()) t.preexisting = failed; // failed before monitoring started: leave it alone + else if (failed && t.last != "failed") t.fails << now, t.preexisting = false; + else if (!failed) t.preexisting = false; + t.last = s.active; + for (auto *v : {&t.fails, &t.restarts}) + while (!v->isEmpty() && now - v->first() > 3600000) v->removeFirst(); + } + if (!svcs.isEmpty()) m_svcs = svcs; // forgets removed services; a sample without a service list changes nothing +} + +void ServerSession::evaluateRules() +{ + const qint64 now = QDateTime::currentMSecsSinceEpoch(); + for (const Rule &r : qAsConst(m_cfg.rules)) { + RuleState &st = m_rules[r.id]; + if (!r.enabled || ((r.metric == "gpu" || r.metric == "gputemp") && m_m.gpus.isEmpty()) || (r.metric == "temp" && m_m.temps.isEmpty())) { + st = {}; + continue; + } + const double v = metricValue(r.metric); + const QString now1 = QString::number(v, 'f', 1); + if (r.op == "<" ? v >= r.value : v <= r.value) { + if (st.active) raise("resolved", QString("Recovered: %1 (now %2)").arg(r.conditionText(), now1)); + st = {}; + continue; + } + if (!st.since) st.since = now; + if (now - st.since < r.duration * 1000LL) continue; + if (st.active && (r.action == "notify" || now - st.lastFire < r.cooldown * 1000LL)) continue; + const QString unit = defLabel(ruleMetrics(), r.metric, true); + if (!st.active) raise(r.severity, QString("%1 (now %2%3)").arg(r.conditionText(), now1, unit.isEmpty() ? "" : " " + unit)); + st.active = true, st.lastFire = now; + if (r.action == "notify") continue; + QString action = r.action, arg = r.arg; + if (action.startsWith("kill_top")) { // heaviest user process, never a protected one + const ProcInfo *best = nullptr; + for (const ProcInfo &p : m_m.procs) + 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; + if (!best) continue; + action = "kill_pid", arg = QString::number(best->pid); + } + run(action, arg, QString("Automation \"%1\": %2").arg(r.conditionText(), r.actionText())); + } +} + +void ServerSession::run(const QString &action, const QString &arg, const QString &what, Done done) +{ + const QString cmd = action == "command" ? arg : action == "disk_cleanup" ? m_cfg.autopilot.diskCleanupCommand : P::command(action, arg); + if (cmd.isEmpty()) return done ? done(-1, "nothing to do") : void(); + exec(cmd, true, [=](int code, const QString &out) { + const QString tail = out.simplified().right(300); // one line: events are lines in alerts.log + raise("action", what + " -> " + (code ? QString("failed (%1)").arg(code) : "OK") + (tail.isEmpty() ? "" : " | " + tail)); + if (done) done(code, out); + }, 300000); +} + +void ServerSession::runFinding(const Finding &f, bool automatic, Done done) +{ + if (automatic && f.action == "restart_service") m_svcs[f.actionArg].restarts << QDateTime::currentMSecsSinceEpoch(); + run(f.action, f.action == "disk_cleanup" ? QString() : f.actionArg, (automatic ? "Autopilot: " : "Manual fix: ") + f.actionLabel + " (" + f.title + ")", done); +} + +void ServerSession::analyzeNow() +{ + const qint64 now = QDateTime::currentMSecsSinceEpoch(); + QVector procs; + for (const ProcInfo &p : qAsConst(m_m.procs)) { + const ProcTrack t = m_procs.value(p.pid); + ProcTrend pt{p.pid, int(t.rss.size()), p.name, p.user, p.cpu, t.highSince ? (now - t.highSince) / 60000.0 : 0, p.rss}; + pt.kernel = t.kernel; + if (t.rss.size() >= 2) { + int grew = 0; + for (int i = 1; i < t.rss.size(); ++i) grew += t.rss[i] > t.rss[i - 1]; + pt.rssGrowth = t.rss.last() - t.rss[0], pt.rssGrowthPct = t.rss[0] > 0 ? pt.rssGrowth * 100 / t.rss[0] : 0; + pt.rssMonotonic = double(grew) / (t.rss.size() - 1); + } + if (pt.highCpuMinutes > 0 || pt.minutesTracked >= 30) procs << pt; + } + QVector svcs; + for (auto it = m_svcs.cbegin(); it != m_svcs.cend(); ++it) + if (it->last == "failed" || !it->fails.isEmpty()) svcs << ServiceTrend{it.key(), it->last == "failed", it->preexisting, int(it->fails.size()), int(it->restarts.size())}; + m_an = analyze(m_store, m_m, m_cfg.autopilot, procs, svcs, online()); + + QSet keys; // announce each new finding once + for (const Finding &f : qAsConst(m_an.findings)) + if (keys << f.key, !m_reported.contains(f.key) && f.category != "Availability") raise(f.severity, "Insight: " + f.title + " - " + f.detail); + m_reported = keys; + + const AutopilotConfig &ap = m_cfg.autopilot; // act on eligible findings, with cooldowns; a dry run says once what it would do + QSet dry; + if (ap.enabled && online()) + for (const Finding &f : qAsConst(m_an.findings)) { + const qint64 cd = f.action == "disk_cleanup" ? 6 * 3600000LL : f.action == "restart_service" ? 120000 : 900000; + if (!f.autoEligible) continue; + if (ap.dryRun) { + if (dry << f.key, !m_dry.contains(f.key)) raise("action", "Autopilot (dry run) would: " + f.actionLabel + " - " + f.title); + } else if (now - m_cooldown.value(f.key) >= cd) m_cooldown[f.key] = now, runFinding(f, true); + } + m_dry = dry; + emit analysisUpdated(); +} + +void ServerSession::deleteHistory() +{ + m_store.removeFiles(), m_an = Analysis(); + emit analysisUpdated(); +} + +// ---- manager ---------------------------------------------------------------------------- +QString ServerManager::configDir() +{ + static const QString d = QStandardPaths::writableLocation(QStandardPaths::AppConfigLocation); + QDir().mkpath(d); + return d; +} + +ServerSession *ServerManager::session(const QString &id) const +{ + for (ServerSession *s : m_s) + if (s->config().id == id) return s; + return nullptr; +} + +ServerSession *ServerManager::attach(const ServerConfig &c) +{ + auto *s = new ServerSession(c, this); + connect(s, &ServerSession::alertRaised, this, [this](const AlertEvent &e) { + m_alerts.prepend(e); + m_alerts.resize(qMin(m_alerts.size(), 2000)); + QFile f(configDir() + "/alerts.log"); + if (f.size() > 5 << 20) f.resize(0); + if (f.open(QIODevice::Append | QIODevice::Text)) + QTextStream(&f) << e.time.toString(Qt::ISODate) << '\t' << e.severity << '\t' << e.serverName << '\t' << e.message << '\n'; + emit alertRaised(e); + }); + m_s << s; + return s; +} + +void ServerManager::load() +{ + QFile f(configDir() + "/servers.json"); + if (f.open(QIODevice::ReadOnly)) + for (const auto &v : QJsonDocument::fromJson(f.readAll())["servers"].toArray()) attach(ServerConfig::fromJson(v.toObject())); + else { // first start: monitor this machine + ServerConfig c; + c.id = ServerConfig::newId(), c.name = "This computer", c.group = "Local", c.transport = Transport::Local; + attach(c); + save(); + } + for (ServerSession *s : qAsConst(m_s)) s->start(); + emit listChanged(); +} + +void ServerManager::save() const +{ + QJsonArray a; + for (const ServerSession *s : m_s) a << s->config().toJson(); + QSaveFile f(configDir() + "/servers.json"); + if (f.open(QIODevice::WriteOnly)) f.write(QJsonDocument(QJsonObject{{"version", 1}, {"servers", a}}).toJson()), f.commit(); + QFile::setPermissions(f.fileName(), QFileDevice::ReadOwner | QFileDevice::WriteOwner); +} + +ServerSession *ServerManager::add(const ServerConfig &c) +{ + ServerSession *s = attach(c); + save(), s->start(); + emit listChanged(); + return s; +} + +void ServerManager::update(const ServerConfig &c) +{ + if (ServerSession *s = session(c.id)) s->setConfig(c), save(), emit listChanged(); +} + +void ServerManager::remove(const QString &id, bool deleteHistory) +{ + ServerSession *s = session(id); + if (!s) return; + m_s.removeOne(s); + s->disconnect(this), s->stop(); + if (deleteHistory) s->deleteHistory(), QDir(configDir() + "/history").rmdir(id); // the store keeps an empty folder + s->deleteLater(); + save(); + emit listChanged(); +} + +void ServerManager::move(const QString &id, int d) +{ + const int i = m_s.indexOf(session(id)), j = qBound(0, i + d, m_s.size() - 1); + if (i >= 0 && i != j) m_s.move(i, j), save(), emit listChanged(); +} diff --git a/Server Monitor(cqt-window)/src/core/Session.h b/Server Monitor(cqt-window)/src/core/Session.h new file mode 100644 index 0000000000000000000000000000000000000000..eb1c155289421a4ab33b7d8fd546a247618b2172 --- /dev/null +++ b/Server Monitor(cqt-window)/src/core/Session.h @@ -0,0 +1,137 @@ +// Connection to one machine (local sh or system ssh), the per-server session +// (metrics, live history, rules, autopilot) and the manager of all sessions. +#pragma once +#include "History.h" +#include +#include +#include +#include +#include +#include +#include + +using Done = std::function; + +// Streams collector frames and runs one-shot commands. Deleting it kills everything. +class Link : public QObject { + Q_OBJECT +public: + Link(const ServerConfig &c, QObject *parent); + ~Link() override; + void start(); + int exec(const QByteArray &input, int timeoutMs); +signals: + void snapshot(const QByteArray &frame); + void disconnected(const QString &reason); + void execFinished(int id, int code, const QString &out); + +private: + QProcess *spawn(const QStringList &shell); // not started yet + ServerConfig m_c; + QByteArray m_buf, m_err; + int m_next = 1; +}; + +enum class Status { Disabled, Connecting, Online, Offline }; +QString statusName(Status s); +struct AlertEvent { QDateTime time; QString serverName, severity, message; }; // severity: info|warning|critical|resolved|action + +struct Live { // last hour in memory for the live charts + enum { CPU, USER, SYS, IOWAIT, STEAL, MEM, CACHE, SWAP, RX, TX, RD, WR, LOAD, N }; + QVector t; + QVector s[N]; + QHash> ifRx, ifTx; + void push(const Metrics &m); +}; + +class ServerSession : public QObject { + Q_OBJECT +public: + ServerSession(const ServerConfig &c, QObject *parent); + ~ServerSession() override; + const ServerConfig &config() const { return m_cfg; } + void setConfig(const ServerConfig &c); + Status status() const { return m_status; } + QString lastError() const { return m_err; } + const Metrics &metrics() const { return m_m; } + const Live &live() const { return m_live; } + bool online() const { return m_status == Status::Online && m_m.valid; } + bool isPaused() const { return m_paused; } + void setPaused(bool p) { m_paused = p, emit updated(); } + void start(); + void stop(); + void reconnect() { m_retries = 0, m_paused = false, start(); } + // privileged + "useSudo" wraps the command in sudo -n + void exec(const QString &cmd, bool privileged, Done done = {}, int timeoutMs = 60000); + double metricValue(const QString &key) const; + QStringList activeAlerts() const; + const HistoryStore &store() const { return m_store; } + const Analysis &analysis() const { return m_an; } + void analyzeNow(); + void runFinding(const Finding &f, bool automatic, Done done = {}); + void deleteHistory(); +signals: + void updated(); + void analysisUpdated(); + void alertRaised(const AlertEvent &e); + +private: + void setStatus(Status s, const QString &err = {}); + void drop(const QString &why); // closes the link and fails the commands that wait for it + void onFrame(const QByteArray &raw); + void onLost(const QString &why); + void record(bool up); + void track(qint64 now); + void evaluateRules(); + void run(const QString &action, const QString &arg, const QString &what, Done done = {}); + void raise(const QString &sev, const QString &msg); + + ServerConfig m_cfg; + Status m_status = Status::Disabled; + QString m_err; + QPointer m_link; + MetricsEngine m_engine; + Metrics m_m; + Live m_live; + QTimer m_retry, m_watchdog, m_analysisTimer, m_offlineTick; + int m_retries = 0; + bool m_paused = false, m_offlineAlerted = false; + QHash m_pending; + HistoryStore m_store; + Analysis m_an; + QSet m_reported, m_dry; + QHash m_cooldown; + struct RuleState { qint64 since = 0, lastFire = 0; bool active = false; }; + QHash m_rules; + struct ProcTrack { QString name; qint64 highSince = 0, lastMinute = 0; QVector rss; bool kernel = false; }; + QHash m_procs; + struct SvcTrack { QString last; bool preexisting = false; QVector fails, restarts; }; + QHash m_svcs; +}; + +class ServerManager : public QObject { + Q_OBJECT +public: + using QObject::QObject; + ~ServerManager() override { qDeleteAll(m_s); } + static QString configDir(); + void load(); + void save() const; + const QVector &sessions() const { return m_s; } + ServerSession *session(const QString &id) const; + ServerSession *add(const ServerConfig &c); + void update(const ServerConfig &c); + void remove(const QString &id, bool deleteHistory); + void move(const QString &id, int delta); + const QVector &alerts() const { return m_alerts; } + void clearAlerts() { m_alerts.clear(), emit alertsCleared(); } +signals: + void listChanged(); + void alertRaised(const AlertEvent &e); + void alertsCleared(); + +private: + ServerSession *attach(const ServerConfig &c); + QVector m_s; + QVector m_alerts; +}; diff --git a/Server Monitor(cqt-window)/src/main.cpp b/Server Monitor(cqt-window)/src/main.cpp new file mode 100644 index 0000000000000000000000000000000000000000..3080d6443322bc98ba4cff8a15c90283e273470e --- /dev/null +++ b/Server Monitor(cqt-window)/src/main.cpp @@ -0,0 +1,31 @@ +// Server Monitor - entry point. +#include "ui/Widgets.h" +#include "ui/Windows.h" +#include +#include +#include + +int main(int argc, char *argv[]) +{ + // ssh runs this executable as SSH_ASKPASS when a password is configured + if (const QByteArray pw = qEnvironmentVariable("SERVERMONITOR_ASKPASS").toUtf8(); !pw.isEmpty()) return std::puts(pw.constData()) < 0; + QApplication::setAttribute(Qt::AA_EnableHighDpiScaling), QApplication::setAttribute(Qt::AA_UseHighDpiPixmaps); + QApplication app(argc, argv); + QApplication::setApplicationName("ServerMonitor"), QApplication::setOrganizationName("ServerMonitor"), QApplication::setQuitOnLastWindowClosed(false); + app.setStyle(QStyleFactory::create("Fusion")); + QPalette pal; + for (auto [role, color] : {std::pair{QPalette::Window, C::bg}, {QPalette::WindowText, C::text}, {QPalette::Base, QColor(0x111727)}, {QPalette::AlternateBase, C::panel}, + {QPalette::Text, C::text}, {QPalette::Button, C::card}, {QPalette::ButtonText, C::text}, {QPalette::Highlight, QColor(0x17304a)}, + {QPalette::HighlightedText, C::text}, {QPalette::ToolTipBase, C::card}, {QPalette::ToolTipText, C::text}, {QPalette::PlaceholderText, C::faint}}) + pal.setColor(role, color); + pal.setColor(QPalette::Disabled, QPalette::Text, C::faint), pal.setColor(QPalette::Disabled, QPalette::ButtonText, C::faint); + app.setPalette(pal), app.setWindowIcon(C::appIcon()), app.setStyleSheet(C::styleSheet()); + + ServerManager mgr; + MainWindow w(&mgr); + mgr.load(); + w.show(); + if (const QString dir = qEnvironmentVariable("SERVERMONITOR_SNAPSHOT"); !dir.isEmpty()) // developer aid + QTimer::singleShot(qMax(1, qEnvironmentVariableIntValue("SERVERMONITOR_SNAPSHOT_DELAY")) * 1000, &w, [&w, dir] { w.saveSnapshots(dir), qApp->quit(); }); + return app.exec(); +} diff --git a/Server Monitor(cqt-window)/src/ui/Tabs.cpp b/Server Monitor(cqt-window)/src/ui/Tabs.cpp new file mode 100644 index 0000000000000000000000000000000000000000..82e2a49be6a95dd8fbe070cbcec88d52c2eeda57 --- /dev/null +++ b/Server Monitor(cqt-window)/src/ui/Tabs.cpp @@ -0,0 +1,884 @@ +// Detail-page tabs: each one shows an aspect of the bound server session. +#include "Widgets.h" +#include "Windows.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// ---- helpers ---------------------------------------------------------------------------- +static QVBoxLayout *scrollRoot(QWidget *tab) +{ + auto *outer = new QVBoxLayout(tab); + auto *sa = new QScrollArea; + auto *l = new QVBoxLayout(new QWidget); + outer->setContentsMargins(0, 0, 0, 0), outer->addWidget(sa); + sa->setWidgetResizable(true), sa->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff), sa->setWidget(l->parentWidget()); + l->setContentsMargins(4, 16, 10, 16), l->setSpacing(16); + return l; +} +static QVBoxLayout *plainRoot(QWidget *tab) +{ + auto *l = new QVBoxLayout(tab); + l->setContentsMargins(4, 16, 4, 12), l->setSpacing(10); + return l; +} +template static L *sub(QBoxLayout *parent, int stretch = 0) // nested layout with the standard spacing +{ + auto *l = new L; + l->setSpacing(14), parent->addLayout(l, stretch); + return l; +} +static QGridLayout *grid(QBoxLayout *parent, int stretch = 0) { return sub(parent, stretch); } +static QHBoxLayout *row(QBoxLayout *parent, int stretch = 0) { return sub(parent, stretch); } +static QVBoxLayout *lay(QFrame *f) { return static_cast(f->layout()); } +static QString kv(const QVector> &rows) +{ + QString h = ""; + for (const auto &r : rows) h += QString("").arg(r.first, r.second.toHtmlEscaped()); + return h + "
%1%2
"; +} +static QVector cpuSeries(const Live &h, bool steal) +{ + QVector s = {{"User", C::accent, h.s[Live::USER]}, {"System", C::violet, h.s[Live::SYS]}}; + if (P::posixCpu) s << Series{"I/O wait", C::amber, h.s[Live::IOWAIT]}; + if (P::posixCpu && steal) s << Series{"Steal", C::red, h.s[Live::STEAL]}; + return s; +} +// run a command and show the result in a status label +static void runReport(ServerSession *s, QLabel *status, const QString &cmd) +{ + status->setText("Running: " + cmd); + s->exec(cmd, true, [st = QPointer(status), cmd](int code, const QString &out) { + if (!st) return; + st->setText(code ? "✗ " + cmd + ": " + out.trimmed().left(300) : "✓ " + cmd); + st->setStyleSheet(QString("color: %1;").arg((code ? C::red : C::green).name())); + }); +} + +// ============================================================================ Overview +struct OverviewTab : Tab { + QVector g; + QVector t; + TimeChart *cpu = new TimeChart("CPU", pctFmt, 100), *mem = new TimeChart("Memory", pctFmt, 100), *net = new TimeChart("Network", rateFmt), + *io = new TimeChart("Disk I/O", rateFmt); + QLabel *info = label({}, nullptr, true); + + OverviewTab() + { + auto *l = scrollRoot(this); + auto *gp = panel(), *ip = panel("System", {info, nullptr}); + auto *gl = new QHBoxLayout; + for (const char *n : {"CPU", "Memory", "Fullest disk", "Swap", "Temperature", "Health"}) g << new RingGauge(n), gl->addWidget(g.last()); + g[4]->crit = 85; + lay(gp)->addLayout(gl), gp->setMinimumHeight(220), l->addWidget(gp); + t = addTiles(grid(l), {{"Load average", C::accent}, {"Processes", C::violet}, {"TCP connections", C::teal}, {"Services", C::green}, {"Uptime", C::amber}}); + auto *mid = row(l); + auto *charts = grid(mid, 1); + cpu->stacked = true; + for (auto *c : {cpu, mem, net, io}) c->setMinimumHeight(220), charts->addWidget(c, charts->count() / 2, charts->count() % 2); + ip->setFixedWidth(330), mid->addWidget(ip), l->addStretch(); + } + void refresh() override + { + const Metrics &m = s->metrics(); + const Live &h = s->live(); + const Analysis &a = s->analysis(); + const ServerConfig &c = s->config(); + g[0]->setValue(m.cpuUsage, {}, QString("%1 cores").arg(m.cpuCount)); + g[1]->setValue(m.memPct, {}, Fmt::bytes(m.memUsed) + " / " + Fmt::bytes(m.memTotal)); + g[2]->setValue(m.maxDiskPct, {}, m.fullestMount); + g[3]->setValue(m.swapPct, {}, m.swapTotal > 0 ? Fmt::bytes(m.swapUsed) + " / " + Fmt::bytes(m.swapTotal) : "no swap"); + 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())); + g[5]->setValue(a.health, QString::number(a.health), "grade " + a.grade, C::health(a.health)); + 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)); + t[1]->set(QString::number(m.procs.size()), QString("%1 threads · %2 running").arg(m.threadsTotal).arg(m.procsRunning)); + t[2]->set(QString::number(m.tcp["ESTABLISHED"]), QString("%1 listening · %2 time-wait").arg(m.tcp["LISTEN"]).arg(m.tcp["TIME_WAIT"])); + t[3]->set(QString::number(m.servicesRunning), m.servicesFailed ? QString("%1 failed").arg(m.servicesFailed) : "running · none failed", m.servicesFailed ? C::red : C::text); + t[4]->set(Fmt::duration(m.uptime), QString("%1 user(s) logged in").arg(m.loggedUsers)); + cpu->setData(h.t, cpuSeries(h, false), span); + 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); + net->setData(h.t, {{"Down", C::teal, h.s[Live::RX]}, {"Up", C::pink, h.s[Live::TX]}}, span); + io->setData(h.t, {{"Read", C::blue, h.s[Live::RD]}, {"Write", C::orange, h.s[Live::WR]}}, span); + info->setText(kv({{"Hostname", m.hostname}, {"OS", m.os}, {"Kernel", m.kernel + " " + m.arch}, {"CPU", m.cpuModel}, + {"Cores", QString::number(m.cpuCount) + (m.avgMhz > 0 ? QString(" @ %1 GHz").arg(m.avgMhz / 1000, 0, 'f', 2) : "")}, + {"Memory", Fmt::bytes(m.memTotal)}, {"Swap", m.swapTotal > 0 ? Fmt::bytes(m.swapTotal) : "none"}, {"Virtualisation", m.virt}, + {"Disks", QString("%1 mounted file systems").arg(m.mounts.size())}, {"Interfaces", QString::number(m.nets.size())}, + {"GPU", m.gpus.isEmpty() ? "none" : m.gpus[0].name}, {"Connection", c.address() + " (" + transportName(c.transport) + ")"}, + {"Sample interval", QString("%1 s").arg(c.interval)}})); + } +}; + +// ============================================================================ CPU +struct CpuTab : Tab { + QLabel *model = label({}, "H2"); + QVector t; + TimeChart *chart = new TimeChart("CPU time breakdown", pctFmt, 100), *load = new TimeChart("Load average (1 min)", numFmt(1)); + CoreGrid *cores = new CoreGrid; + QTableWidget *temps = table({"Sensor", "Temperature"}, {300}, {1}), *gpus = table({"#", "Name", "Usage", "Memory", "Temp", "Power", "Fan"}, {40, 220, 120, 160}, {2, 3}); + QFrame *gpuPanel = panel("GPUs", {gpus}); + + CpuTab() + { + auto *l = scrollRoot(this); + l->addWidget(model); + 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}, + {"Context switches", C::blue}, {"Interrupts", C::pink}, {"New processes", C::green}, {"Running / blocked", C::amber}}, 4); + auto *r = row(l); + chart->stacked = true, chart->setMinimumHeight(260), temps->setMinimumHeight(220); + r->addWidget(chart, 3), r->addWidget(load, 2), l->addWidget(panel("Per core", {cores})); + auto *b = row(l); + b->addWidget(panel("Temperatures", {temps}), 1), b->addWidget(gpuPanel, 1), l->addStretch(); + } + void refresh() override + { + const Metrics &m = s->metrics(); + const Live &h = s->live(); + model->setText(m.cpuModel.isEmpty() ? "Processor" : m.cpuModel); + 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)); + 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)); + t[2]->set(m.avgMhz > 0 ? QString("%1 GHz").arg(m.avgMhz / 1000, 0, 'f', 2) : "n/a"); + if (P::posixCpu) t[3]->set(Fmt::pct(m.cpuSteal) + " / " + Fmt::pct(m.cpuIrq), "steal > 5% = noisy neighbours", m.cpuSteal > 5 ? C::amber : QColor()); + else t[3]->set(Fmt::pct(m.cpuIrq), "hardware interrupts and deferred calls", m.cpuIrq > 15 ? C::amber : QColor()); + 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"); + 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()); + chart->setData(h.t, cpuSeries(h, true), span); + load->setData(h.t, {{"Load", C::violet, h.s[Live::LOAD]}, {"Cores", C::faint, QVector(h.t.size(), m.cpuCount), false, true}}, span); + cores->setCores(m.cores); + temps->clearSpans(); + fillRows(temps, m.temps, [](const TempSensor &x) { return Row{{x.name}, {Fmt::temp(x.celsius), {}, false, qMin(100.0, x.celsius)}}; }); + 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); + gpuPanel->setVisible(!m.gpus.isEmpty()); + fillRows(gpus, m.gpus, [](const GpuInfo &g) { + return Row{{QString::number(g.index)}, {g.name}, {Fmt::pct(g.util, 0), {}, false, g.util}, + {QString("%1 / %2 MiB").arg(g.memUsed).arg(g.memTotal), {}, false, g.memTotal > 0 ? g.memUsed * 100 / g.memTotal : 0}, + {Fmt::temp(g.temp), C::level(g.temp, 75, 88)}, {QString("%1 W").arg(g.power)}, {Fmt::pct(g.fan, 0)}}; + }); + } +}; + +// ============================================================================ Memory +struct MemoryTab : Tab { + QVector t; + SegmentBar *bar = new SegmentBar, *swap = new SegmentBar; + TimeChart *chart = new TimeChart("Memory usage", pctFmt, 100); + QLabel *detail = label({}, nullptr, true); + QTableWidget *top = table({"PID", "Process", "User", "RSS", "Memory %", "Virtual"}, {80, 220, 120, 110, 160}, {4}); + + MemoryTab() + { + auto *l = scrollRoot(this); + t = addTiles(grid(l), {{"Used", C::violet}, {"Available", C::green}, {"Cache + buffers", C::blue}, {"Swap used", C::pink}}); + l->addWidget(panel("Composition", {bar, label("SWAP", "Section"), swap})); + auto *r = row(l); + auto *dp = panel("Details", {detail, nullptr}); + chart->setMinimumHeight(280), dp->setFixedWidth(300), top->setMinimumHeight(360); + r->addWidget(chart, 3), r->addWidget(dp), l->addWidget(panel("Top memory consumers", {top})); + } + void refresh() override + { + const Metrics &m = s->metrics(); + const Live &h = s->live(); + const QColor free = C::grid.lighter(150); + t[0]->set(Fmt::bytes(m.memUsed), Fmt::pct(m.memPct) + " of " + Fmt::bytes(m.memTotal), C::level(m.memPct)); + t[1]->set(Fmt::bytes(m.memAvailable), "free " + Fmt::bytes(m.memFree)); + t[2]->set(Fmt::bytes(m.cached + m.buffers), "reclaimable when needed"); + 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)); + bar->setSegments({{qMax(0.0, m.memTotal - m.memFree - m.cached - m.buffers), C::violet, "Applications"}, {m.shared, C::pink, "Shared"}, + {m.buffers, C::teal, "Buffers"}, {qMax(0.0, m.cached - m.shared), C::blue, "Cache"}, {m.memFree, free, "Free"}}, m.memTotal); + swap->setSegments({{m.swapUsed, C::pink, "Used"}, {m.swapTotal - m.swapUsed, free, "Free"}}, m.swapTotal); + 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); + QVector> d; + for (auto [k, v] : {std::pair{"Total", m.memTotal}, {"Used", m.memUsed}, {"Available", m.memAvailable}, {"Free", m.memFree}, {"Buffers", m.buffers}, + {"Cached", m.cached}, {"Shared", m.shared}, {"Slab", m.slab}, {"Dirty", m.dirty}, {"Swap total", m.swapTotal}, {"Swap used", m.swapUsed}}) + d << qMakePair(QString(k), Fmt::bytes(v)); + detail->setText(kv(d)); + QVector p = m.procs; + std::partial_sort(p.begin(), p.begin() + qMin(15, p.size()), p.end(), [](const ProcInfo &a, const ProcInfo &b) { return a.rss > b.rss; }); + fillRows(top, p.mid(0, 15), [](const ProcInfo &x) { + return Row{{QString::number(x.pid), C::muted}, {x.name}, {x.user, C::muted}, {Fmt::bytes(x.rss), {}, true}, + {Fmt::pct(x.memPct), {}, false, qMin(100.0, x.memPct * 2)}, {Fmt::bytes(x.vsz), C::muted, true}}; + }); + } +}; + +// ============================================================================ Storage +struct StorageTab : Tab { + QVector t; + QTableWidget *mounts = table({"Mount point", "Device", "Type", "Size", "Used", "Free", "Usage"}, {260, 140, 80, 110, 110, 110}, {6}), + *disks = table({"Device", "Read/s", "Write/s", "Read IOPS", "Write IOPS", "Busy", "Total read", "Total written"}, {110, 110, 110, 100, 100, 150, 120}, {5}); + TimeChart *io = new TimeChart("Disk throughput", rateFmt); + + StorageTab() + { + auto *l = scrollRoot(this); + t = addTiles(grid(l), {{"Fullest file system", C::amber}, {"Read", C::blue}, {"Write", C::orange}, {"Busiest disk", C::red}}); + mounts->setMinimumHeight(220), disks->setMinimumHeight(200), io->setMinimumHeight(260); + l->addWidget(panel("File systems", {mounts})), l->addWidget(io), l->addWidget(panel("Block devices", {disks})); + } + void refresh() override + { + const Metrics &m = s->metrics(); + t[0]->set(Fmt::pct(m.maxDiskPct), m.fullestMount, C::level(m.maxDiskPct, 80, 90)); + 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)); + io->setData(s->live().t, {{"Read", C::blue, s->live().s[Live::RD]}, {"Write", C::orange, s->live().s[Live::WR]}}, span); + fillRows(mounts, m.mounts, [](const MountInfo &x) { + return Row{{x.mount}, {x.device, C::muted}, {x.type, C::muted}, {Fmt::bytes(x.total), {}, true}, {Fmt::bytes(x.used), {}, true}, + {Fmt::bytes(x.avail), {}, true}, {Fmt::pct(x.pct), {}, false, x.pct}}; + }); + fillRows(disks, m.disks, [](const DiskIO &d) { + 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}, + {QString::number(d.writeIops, 'f', 0), {}, true}, {Fmt::pct(d.util, 0), {}, false, d.util}, {Fmt::bytes(d.totalRead), C::muted, true}, + {Fmt::bytes(d.totalWritten), C::muted, true}}; + }); + } +}; + +// ============================================================================ Network +struct NetworkTab : Tab { + QVector t; + QComboBox *iface = new QComboBox; + QStringList shown; + TimeChart *chart = new TimeChart("Traffic", rateFmt); + 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}); + + NetworkTab() + { + auto *l = scrollRoot(this); + 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}}); + auto *r = row(l); + r->addWidget(label("Interface", "Muted")), r->addWidget(iface), r->addStretch(); + iface->setMinimumWidth(200), chart->setMinimumHeight(280), tbl->setMinimumHeight(240); + l->addWidget(chart), l->addWidget(panel("Interfaces", {tbl})); + connect(iface, QOverload::of(&QComboBox::activated), this, [this] { refresh(); }); + } + void refresh() override + { + const Metrics &m = s->metrics(); + const Live &h = s->live(); + t[0]->set(Fmt::rate(m.netRxBps), "physical interfaces"), t[1]->set(Fmt::rate(m.netTxBps)); + t[2]->set(QString::number(m.tcp["ESTABLISHED"]), "TCP"), t[3]->set(QString::number(m.tcp["LISTEN"]), "open TCP ports"); + 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()); + t[5]->set(QString::number(m.socketsUsed)); + QStringList names{"All physical (total)"}; + for (const NetIf &n : m.nets) names << n.name; + if (names != shown) { + const QString cur = iface->currentText(); + iface->clear(), iface->addItems(shown = names), iface->setCurrentIndex(qMax(0, names.indexOf(cur))); + } + const QString n = iface->currentText(); + const bool all = iface->currentIndex() <= 0; + chart->title = "Traffic — " + (all ? "all physical interfaces" : n); + 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); + fillRows(tbl, m.nets, [](const NetIf &x) { + const QColor dim = x.virt ? C::muted : QColor(); + return Row{{x.name + (x.virt ? " (virtual)" : ""), dim}, {x.state, x.state == "up" ? C::green : x.state == "down" ? C::red : C::muted}, + {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}, + {QString::number(x.rxPps, 'f', 0), dim, true}, {QString::number(x.txPps, 'f', 0), dim, true}, {Fmt::bytes(x.rxBytes), dim, true}, + {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}}; + }); + } +}; + +// ============================================================================ list tabs (processes, services) +using Act = QPair>; // context-menu entry; empty text = separator + +struct ListTab : Tab { // filterable, sortable table that keeps selection and scroll position across refreshes + QLineEdit *filter = new QLineEdit; + QLabel *summary = label({}, "Muted"), *status = label({}, "Muted"); + QTableWidget *tbl; + QHBoxLayout *bar; + + ListTab(const QStringList &headers, const QVector &widths, const QVector &bars, const QString &hint) + { + auto *l = plainRoot(this); + bar = row(l), tbl = table(headers, widths, bars); + tbl->setSortingEnabled(true), tbl->setContextMenuPolicy(Qt::CustomContextMenu); + filter->setClearButtonEnabled(true), filter->setMaximumWidth(300), filter->setPlaceholderText(hint); + bar->addWidget(filter), bar->addWidget(summary), bar->addStretch(); + l->addWidget(tbl, 1), l->addWidget(status); + connect(filter, &QLineEdit::textChanged, this, [this] { applyFilter(); }); + } + QString selectedKey() const + { + const int r = tbl->currentRow(); + return r >= 0 && !tbl->isRowHidden(r) && tbl->item(r, 0) ? tbl->item(r, 0)->text() : QString(); + } + virtual bool accept(int r) const + { + for (int c = 0; c < tbl->columnCount(); ++c) + if (tbl->item(r, c) && tbl->item(r, c)->text().contains(filter->text(), Qt::CaseInsensitive)) return true; + return false; + } + void applyFilter() + { + for (int r = 0; r < tbl->rowCount(); ++r) tbl->setRowHidden(r, !accept(r)); + } + template void fill(const V &items, F rowOf) + { + const QString sel = selectedKey(); + const int scroll = tbl->verticalScrollBar()->value(), col = qMax(0, tbl->currentColumn()); + int row = -1; // rows are reused: when the selected entry is gone the selection must go too, not pass to another entry + tbl->setSortingEnabled(false), fillRows(tbl, items, rowOf), tbl->setSortingEnabled(true); + for (int r = 0; r < tbl->rowCount() && row < 0 && !sel.isEmpty(); ++r) + if (tbl->item(r, 0)->text() == sel) row = r; + tbl->setCurrentCell(row, col), applyFilter(), tbl->verticalScrollBar()->setValue(scroll); + } + void addMenu(const QVector &items) + { + connect(tbl, &QWidget::customContextMenuRequested, this, [this, items](const QPoint &p) { + if (selectedKey().isEmpty()) return; + QMenu m; + for (const Act &a : items) a.first.isEmpty() ? (void)m.addSeparator() : (void)m.addAction(a.first, a.second); + m.exec(tbl->viewport()->mapToGlobal(p)); + }); + } +}; + +struct ProcessTab : ListTab { + QCheckBox *freeze = new QCheckBox("Freeze list"); + + 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…") + { + freeze->setToolTip("Stop refreshing so rows don't move while you pick one"); + bar->insertWidget(1, freeze), tbl->sortByColumn(4, Qt::DescendingOrder); + QVector menu; + for (const Cmd &c : P::procActions()) { + menu << Act{c.label, [this, c] { run(c); }}; + if (c.button) bar->addWidget(button(c.label, c.danger ? "Danger" : nullptr, menu.last().second)); + } + bar->addWidget(button("Priority…", nullptr, [this] { renice(); })); + addMenu(menu << Act{} << Act{"Change priority…", [this] { renice(); }}); + } + void bind(ServerSession *x) override + { + if (x != s) freeze->setChecked(false); // a frozen list would show the other server's PIDs + Tab::bind(x); + } + void refresh() override + { + if (freeze->isChecked()) return; + const Metrics &m = s->metrics(); + static const QHash> states = {{'R', {"Running", C::green}}, {'S', {"Sleeping", C::muted}}, {'D', {"Disk wait", C::amber}}, + {'Z', {"Zombie", C::red}}, {'T', {"Stopped", C::red}}, {'I', {"Idle", C::muted}}}; + int running = 0; + fill(m.procs, [&](const ProcInfo &p) { + const auto st = states.value(p.state, {QString(p.state), C::muted}); + running += p.state == 'R'; + return Row{{QString::number(p.pid), C::muted, true, -1, p.pid}, {p.name}, {p.user, C::muted}, {st.first, st.second}, + {Fmt::pct(p.cpu), {}, false, qMin(100.0, p.cpu), p.cpu}, {Fmt::pct(p.memPct), {}, false, p.memPct, p.memPct}, + {Fmt::bytes(p.rss), {}, true, -1, p.rss}, {QString::number(p.threads), {}, true, -1, p.threads}, + {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}}; + }); + summary->setText(QString("%1 processes · %2 running · %3 threads").arg(m.procs.size()).arg(running).arg(m.threadsTotal)); + } + QString pidName() const { return tbl->item(tbl->currentRow(), 1)->text() + " (" + selectedKey() + ")"; } + void run(const Cmd &c) + { + const int pid = selectedKey().toInt(); // read before the question: the list keeps refreshing behind it + if (!pid) return status->setText("Select a process first."); + 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)); + } + void renice() + { + const int pid = selectedKey().toInt(); + if (!pid) return status->setText("Select a process first."); + QStringList labels; + for (const Cmd &c : P::priorities()) labels << c.label; + bool ok = false; + const int i = labels.indexOf(QInputDialog::getItem(this, "Change priority", "Priority for " + pidName() + ":", labels, labels.size() / 2, false, &ok)); + if (ok && i >= 0) runReport(s, status, P::priorities()[i].cmd.arg(pid)); + } +}; + +struct ServiceTab : ListTab { + QComboBox *state = new QComboBox; + QString sig = "?"; // not a possible signature: the first refresh always fills + + ServiceTab() : ListTab({"Service", "Active", "State", "Load", "Description"}, {300, 100, 100, 90}, {}, "Filter services…") + { + state->addItems({"All", "Running", "Failed", "Not running"}); + bar->insertWidget(1, state), tbl->sortByColumn(0, Qt::AscendingOrder); + connect(state, QOverload::of(&QComboBox::currentIndexChanged), this, [this] { applyFilter(); }); + connect(tbl, &QTableWidget::cellDoubleClicked, this, [this] { showLogs(); }); + QVector menu; + for (const Cmd &c : P::serviceActions()) { + menu << Act{c.label, [this, c] { act(c); }}; + bar->addWidget(button(c.label, c.danger ? "Danger" : nullptr, menu.last().second)); + } + bar->addWidget(button("Logs", "Primary", [this] { showLogs(); })); + addMenu(menu << Act{} << Act{"Show logs", [this] { showLogs(); }}); + } + bool accept(int r) const override + { + const QString active = tbl->item(r, 1)->text(), sub = tbl->item(r, 2)->text(); + const int st = state->currentIndex(); + return (st == 0 || (st == 1 && sub == "running") || (st == 2 && active == "failed") || (st == 3 && sub != "running" && active != "failed")) && ListTab::accept(r); + } + void refresh() override + { + const Metrics &m = s->metrics(); + QString sg; + for (const ServiceInfo &x : m.services) sg += x.unit + x.active + x.sub; + if (sg == sig) return; // unchanged: keep the list still + sig = sg; + fill(m.services, [](const ServiceInfo &x) { + const QColor c = x.active == "failed" ? C::red : x.sub == "running" ? C::green : x.active == "active" ? C::teal : C::muted; + return Row{{x.unit}, {x.active, c}, {x.sub, c}, {x.load, C::muted}, {x.description, C::muted}}; + }); + 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)); + } + void act(const Cmd &c) + { + const QString unit = selectedKey(); + if (unit.isEmpty()) return status->setText("Select a service first."); + 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))); + } + void showLogs() + { + const QString unit = selectedKey(); + if (unit.isEmpty()) return; + auto *dlg = new QDialog(this); + auto *l = new QVBoxLayout(dlg); + auto *b = new QHBoxLayout; + auto *txt = new QPlainTextEdit("Loading…"); + auto *n = new QSpinBox; + dlg->setAttribute(Qt::WA_DeleteOnClose), dlg->setWindowTitle("Logs — " + unit + " — " + s->config().name), dlg->resize(1000, 640); + txt->setReadOnly(true), txt->setFont(QFont(C::mono(), 10)), txt->setLineWrapMode(QPlainTextEdit::NoWrap); + n->setRange(50, 5000), n->setValue(300), n->setSuffix(" lines"); + auto load = [ss = s, t = QPointer(txt), n, unit] { + 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()); }); + }; + l->addWidget(txt), l->addLayout(b); + b->addWidget(n), b->addWidget(button("Reload", nullptr, load)), b->addStretch(), b->addWidget(button("Close", nullptr, [dlg] { dlg->close(); })); + load(), dlg->show(); + } +}; + +// ============================================================================ Console +struct ConsoleTab : Tab { + QPlainTextEdit *out = new QPlainTextEdit; + QLineEdit *in = new QLineEdit; + QCheckBox *priv = new QCheckBox("privileged"); + QStringList hist; + int pos = 0; + + ConsoleTab() + { + auto *l = new QHBoxLayout(this); + auto *left = new QVBoxLayout, *side = new QVBoxLayout; + auto *r = new QHBoxLayout; + auto *prompt = label("$"); + auto *run = button("Run", "Primary", [this] { + const QString c = in->text().trimmed(); + if (c.isEmpty()) return; + if (hist.isEmpty() || hist.last() != c) hist << c; + pos = hist.size(), in->clear(), exec(c, priv->isChecked()); + }); + l->setContentsMargins(4, 16, 4, 12), l->setSpacing(14), l->addLayout(left, 1), l->addLayout(side); + out->setReadOnly(true), out->setFont(QFont(C::mono(), 10)), out->setMaximumBlockCount(20000); + out->setStyleSheet("QPlainTextEdit { background: #080b12; border-radius: 10px; padding: 10px; color: #cfe3ff; }"); + in->setFont(QFont(C::mono(), 11)), in->setPlaceholderText("Type a shell command and press Enter (↑/↓ history)"), in->installEventFilter(this); + priv->setToolTip("Wrap in sudo -n when the server has 'Run control commands with sudo' enabled"), priv->setVisible(P::sudo); + prompt->setStyleSheet("color: #38bdf8; font-weight: 700; font-size: 15px;"); + r->addWidget(prompt), r->addWidget(in, 1), r->addWidget(priv), r->addWidget(run), r->addWidget(button("Clear", nullptr, [this] { out->clear(); })); + left->addWidget(out, 1), left->addLayout(r); + connect(in, &QLineEdit::returnPressed, run, &QPushButton::click); + auto addGroup = [&](const QString &title, const QVector &items, bool system) { + auto *p = panel(title); + p->setFixedWidth(270), side->addWidget(p); + for (const Cmd &q : items) { + auto *b = button(q.label, q.danger ? "Danger" : "Side", [this, q, system] { + 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); + }); + b->setToolTip(q.cmd), lay(p)->addWidget(b); + } + }; + addGroup("Quick diagnostics", P::diagnostics(), false), addGroup("System actions", P::systemActions(), true); + side->addStretch(); + } + void bind(ServerSession *x) override + { + if (x == s) return; + out->clear(), Tab::bind(x); + if (x) out->appendHtml(QString("Console for %1 (%2). Commands run non-interactively with a 120 s timeout.").arg(x->config().name.toHtmlEscaped(), x->config().address())); + } + bool eventFilter(QObject *o, QEvent *e) override + { + const int k = e->type() == QEvent::KeyPress ? static_cast(e)->key() : 0; + if (o != in || hist.isEmpty() || (k != Qt::Key_Up && k != Qt::Key_Down)) return Tab::eventFilter(o, e); + return pos = qBound(0, pos + (k == Qt::Key_Up ? -1 : 1), hist.size()), in->setText(hist.value(pos)), true; + } + void exec(const QString &cmd, bool privileged) + { + out->appendHtml(QString("
%1 $ %2").arg(QTime::currentTime().toString("HH:mm:ss"), cmd.toHtmlEscaped())); + auto clock = std::make_shared(); + clock->start(); + s->exec(cmd, privileged, [o = QPointer(out), clock](int code, const QString &text) { + if (!o) return; + if (!text.isEmpty()) o->appendPlainText(text.endsWith('\n') ? text.chopped(1) : text); + o->appendHtml(QString("[exit %2 · %3 ms]").arg(code ? "#ef4444" : "#22c55e").arg(code).arg(clock->elapsed())); + o->verticalScrollBar()->setValue(o->verticalScrollBar()->maximum()); + }, 120000); + } +}; + +// ============================================================================ Alert rules +struct RulesTab : Tab { + QTableWidget *rules = table({"On", "Condition", "Severity", "Action", "Cooldown", "Live value"}, {50, 380, 100, 330, 100}), *live = table({"Active problems"}); + + RulesTab() + { + auto *l = plainRoot(this); + 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; " + "if it is still true after the cooldown the action runs again. History-based automation lives in the Insights tab.", "Muted", true)); + auto *b = row(l); + b->addWidget(button("+ Add rule", "Primary", [this] { editRule(-1); })), b->addWidget(button("Edit", nullptr, [this] { editRule(rules->currentRow()); })); + b->addWidget(button("Delete", "Danger", [this] { + auto rs = s->config().rules; + if (rules->currentRow() >= 0 && rules->currentRow() < rs.size()) rs.remove(rules->currentRow()), store(rs); + })); + b->addStretch(); + b->addWidget(button("Reset to defaults", nullptr, [this] { + if (ask(this, "Reset rules", "Replace all rules with the defaults?")) store(ServerConfig::defaultRules()); + })); + live->setMaximumHeight(160), l->addWidget(rules, 2), l->addWidget(live, 1); + connect(rules, &QTableWidget::cellDoubleClicked, this, [this](int r) { editRule(r); }); + connect(rules, &QTableWidget::itemChanged, this, [this](QTableWidgetItem *it) { // the "On" checkbox + auto rs = s->config().rules; + const bool on = it->checkState() == Qt::Checked; + if (it->column() == 0 && it->row() < rs.size() && rs[it->row()].enabled != on) rs[it->row()].enabled = on, store(rs); + }); + } + void bind(ServerSession *x) override { Tab::bind(x), reload(); } + void store(const QVector &rs) + { + ServerConfig c = s->config(); + c.rules = rs, save(c), reload(); + } + void reload() + { + if (!s) return; + QSignalBlocker block(rules); + fillRows(rules, s->config().rules, [](const Rule &r) { + return Row{{}, {r.conditionText(), r.enabled ? QColor() : C::faint}, {r.severity, C::severity(r.severity)}, + {r.actionText(), r.action == "notify" ? C::muted : C::violet}, {QString("%1 s").arg(r.cooldown), C::muted}}; + }); + for (int i = 0; i < rules->rowCount(); ++i) rules->item(i, 0)->setCheckState(s->config().rules[i].enabled ? Qt::Checked : Qt::Unchecked); + refresh(); + } + void refresh() override + { + const auto &rs = s->config().rules; + const QStringList act = s->activeAlerts(); + QSignalBlocker block(rules); + for (int i = 0; i < rs.size() && i < rules->rowCount(); ++i) { + const double v = s->metricValue(rs[i].metric); + 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}); + } + fillRows(live, act, [](const QString &a) { return Row{{"⚠ " + a, C::red}}; }); + if (act.isEmpty()) live->setRowCount(1), cell(live, 0, 0, {"✓ No rule is currently triggered", C::green}); + } + void editRule(int idx) + { + auto rs = s->config().rules; + Rule r; + r.id = ServerConfig::newId(); + if (idx >= 0 && idx < rs.size()) r = rs[idx]; + else idx = -1; + QDialog dlg(this); + dlg.setWindowTitle(idx < 0 ? "New rule" : "Edit rule"); + auto *f = new QFormLayout(&dlg); + auto *metric = new QComboBox, *op = new QComboBox, *sev = new QComboBox, *action = new QComboBox; + auto *value = new QDoubleSpinBox; + auto *dur = new QSpinBox, *cool = new QSpinBox; + auto *arg = new QLineEdit(r.arg); + auto *en = new QCheckBox("Enabled"); + auto *cond = new QHBoxLayout; + auto *bb = new QDialogButtonBox(QDialogButtonBox::Ok | QDialogButtonBox::Cancel); + for (const Def &d : ruleMetrics()) metric->addItem(d.label + (d.unit.isEmpty() ? "" : " (" + d.unit + ")"), d.key); + for (const Def &d : P::ruleActions()) action->addItem(d.label, d.key); + op->addItems({">", "<"}), sev->addItems({"info", "warning", "critical"}); + metric->setCurrentIndex(qMax(0, metric->findData(r.metric))), action->setCurrentIndex(qMax(0, action->findData(r.action))); + op->setCurrentText(r.op), sev->setCurrentText(r.severity), en->setChecked(r.enabled); + value->setRange(-1e9, 1e9), value->setValue(r.value); + dur->setRange(0, 86400), dur->setSuffix(" s"), dur->setValue(r.duration); + cool->setRange(10, 86400), cool->setSuffix(" s"), cool->setValue(r.cooldown); + auto sync = [action, arg] { + const QString hint = defLabel(P::ruleActions(), action->currentData().toString(), true); + arg->setEnabled(!hint.isEmpty()), arg->setPlaceholderText(hint); + }; + connect(action, QOverload::of(&QComboBox::currentIndexChanged), &dlg, sync); + connect(bb, &QDialogButtonBox::accepted, &dlg, &QDialog::accept), connect(bb, &QDialogButtonBox::rejected, &dlg, &QDialog::reject); + cond->addWidget(op), cond->addWidget(value, 1), sync(); + f->addRow("When", metric), f->addRow("is", cond), f->addRow("for at least", dur), f->addRow("Severity", sev), f->addRow("Then", action); + f->addRow("Argument", arg), f->addRow("Repeat after", cool), f->addRow("", en), f->addRow(bb); + if (dlg.exec() != QDialog::Accepted) return; + r.metric = metric->currentData().toString(), r.op = op->currentText(), r.value = value->value(), r.duration = dur->value(), r.severity = sev->currentText(); + r.action = action->currentData().toString(), r.arg = arg->isEnabled() ? arg->text().trimmed() : "", r.cooldown = cool->value(), r.enabled = en->isChecked(); + idx < 0 ? (void)(rs << r) : (void)(rs[idx] = r); + store(rs); + } +}; + +// ============================================================================ History +struct HistoryTab : Tab { + qint64 range = 86400, lastLoad = 0; + QLabel *res = label({}, "Muted"); + QVector charts; + QTableWidget *st = table({"Metric", "Minimum", "Average", "95th percentile", "Peak", "Points"}, {200, 150, 150, 150, 150}); + QVector pts; + + HistoryTab() + { + auto *l = scrollRoot(this); + auto *b = row(l); + auto *group = new QButtonGroup(this); + b->setSpacing(6); + 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}}) { + auto *btn = button(text); + btn->setCheckable(true), btn->setChecked(sec == 86400), group->addButton(btn, sec / 60), b->addWidget(btn); + } + b->addSpacing(14), b->addWidget(res), b->addStretch(), b->addWidget(button("Export CSV…", nullptr, [this] { exportCsv(); })); + connect(group, &QButtonGroup::idClicked, this, [this](int id) { range = id * 60LL, reload(); }); + auto *g = grid(l); + for (auto [title, fmt, max] : {std::tuple{"CPU", pctFmt, 100.0}, {"Memory & swap", pctFmt, 100.0}, {"Disk usage (fullest)", pctFmt, 100.0}, + {"Disk throughput", rateFmt, 0.0}, {"Network", rateFmt, 0.0}, {"Load average", numFmt(1), 0.0}, + {"Temperature", FmtFn([](double v) { return QString::number(v, 'f', 0) + "°"; }), 0.0}, {"Availability", pctFmt, 100.0}}) { + charts << new TimeChart(title, fmt, max); + 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); + } + st->setMinimumHeight(14 * 30 + 40), l->addWidget(panel("Statistics for the selected range", {st})); + } + void bind(ServerSession *x) override { Tab::bind(x), lastLoad = 0; } + void refresh() override + { + if (QDateTime::currentMSecsSinceEpoch() - lastLoad >= (range && range <= 21600 ? 5000 : 60000)) reload(); + } + void reload() + { + lastLoad = QDateTime::currentMSecsSinceEpoch(); + const qint64 now = QDateTime::currentSecsSinceEpoch(), from = range ? now - range : qMax(1, s->store().firstTs()); + Tier tier; + pts = s->store().range(from, now, &tier); + const qint64 step = qMax(HistoryStore::step[int(tier)], s->config().interval); + QVector t; + enum { CPU, CPUMAX, MEM, SWAP, DISK, RD, WR, RX, TX, RXMAX, LOAD, TEMP, TEMPMAX, AVAIL, N }; + QVector v[N]; + double n = 0, up = 0; + auto push = [&](qint64 ts, const HPoint *p) { // p = nullptr inserts a gap + t << ts * 1000; + 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}; + for (int i = 0; i < N; ++i) + 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]]); + }; + for (const HPoint &p : qAsConst(pts)) { + if (!t.isEmpty() && p.ts * 1000 - t.last() > step * 3000) push(t.last() / 1000 + step, nullptr); // app was not running + push(p.ts, &p), n += p.n, up += p.nUp; + } + if (!t.isEmpty() && now * 1000 - t.last() > step * 3000) push(now, nullptr); + const bool agg = tier != Tier::Raw; + auto peak = [&](QVector s, const QString &name, const QColor &c, const QVector &d) { if (agg) s << Series{name, c, d, false, true}; return s; }; + const QVector> data = {peak({{"Average", C::accent, v[CPU]}}, "Peak", C::red, v[CPUMAX]), + {{"Memory", C::violet, v[MEM]}, {"Swap", C::pink, v[SWAP], false}}, {{"Usage", C::amber, v[DISK]}}, + {{"Read", C::blue, v[RD]}, {"Write", C::orange, v[WR]}}, + peak({{"Down", C::teal, v[RX]}, {"Up", C::pink, v[TX]}}, "Peak down", C::teal.lighter(140), v[RXMAX]), + {{"Load", C::violet, v[LOAD]}}, peak({{"Average", C::orange, v[TEMP]}}, "Peak", C::red, v[TEMPMAX]), + {{"Online", C::green, v[AVAIL]}}}; + 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); + 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()))); + QVector 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}; + if (!P::posixCpu) ms.remove(1); + fillRows(st, ms, [&](int m) { + const Stats x = stats(pts, m); + return Row{{hNames[m]}, {fmtMetric(m, x.min), C::muted, true}, {fmtMetric(m, x.avg), {}, true}, {fmtMetric(m, x.p95), C::amber, true}, + {fmtMetric(m, x.max), C::red, true}, {QString::number(x.count), C::muted, true}}; + }); + } + void exportCsv() + { + const QString fn = QFileDialog::getSaveFileName(this, "Export history", s->config().name + "-history.csv", "CSV (*.csv)"); + QFile f(fn); + if (fn.isEmpty() || !f.open(QIODevice::WriteOnly | QIODevice::Text)) return; + QTextStream ts(&f); + ts << "time,samples,online_pct"; + for (const char *k : hKeys) ts << ',' << k << "_avg," << k << "_max"; + auto num = [](float x) { return std::isnan(x) ? QString() : QString::number(x, 'f', 3); }; + for (const HPoint &p : qAsConst(pts)) { + ts << '\n' << QDateTime::fromSecsSinceEpoch(p.ts).toString(Qt::ISODate) << ',' << p.n << ',' << p.uptimePct(); + for (int m = 0; m < H_COUNT; ++m) ts << ',' << num(p.avg[m]) << ',' << num(p.max[m]); + } + } +}; + +// ============================================================================ Insights & Autopilot +struct InsightsTab : Tab { + RingGauge *health = new RingGauge("Health score"); + QLabel *reasons = label({}, "Muted", true), *capacity = label({}, nullptr, true); + QVector t; + QVBoxLayout *findings = new QVBoxLayout; + WeekHeatmap *heat = new WeekHeatmap; + QComboBox *heatMetric = new QComboBox; + QTableWidget *anomalies = table({"Metric", "Last 10 min", "Usual", "Deviation", "Baseline"}, {110, 110, 160, 90}); + QVector> binds; // autopilot form <-> config + bool loading = false; + + // form-field builders bound to AutopilotConfig members + QWidget *chk(const QString &text, bool AutopilotConfig::*f) + { + auto *w = new QCheckBox(text); + binds << [w, f](AutopilotConfig &a, bool ld) { ld ? w->setChecked(a.*f) : void(a.*f = w->isChecked()); }; + connect(w, &QCheckBox::toggled, this, [this] { store(); }); + return w; + } + template QWidget *spin(T AutopilotConfig::*f, double lo, double hi, const QString &pre, const QString &suf) + { + auto *w = new W; + w->setRange(lo, hi), w->setPrefix(pre), w->setSuffix(suf); + if constexpr (std::is_same_v) w->setDecimals(f == &AutopilotConfig::anomalyZ ? 1 : 0), w->setSingleStep(f == &AutopilotConfig::anomalyZ ? 0.5 : 1); + binds << [w, f](AutopilotConfig &a, bool ld) { ld ? w->setValue(a.*f) : void(a.*f = w->value()); }; + connect(w, QOverload::of(&W::valueChanged), this, [this] { store(); }); + return w; + } + QWidget *combo(QString AutopilotConfig::*f, const QStringList &keys, const QStringList &labels) + { + auto *w = new QComboBox; + for (int i = 0; i < keys.size(); ++i) w->addItem(labels[i], keys[i]); + binds << [w, f](AutopilotConfig &a, bool ld) { ld ? w->setCurrentIndex(qMax(0, w->findData(a.*f))) : void(a.*f = w->currentData().toString()); }; + connect(w, QOverload::of(&QComboBox::currentIndexChanged), this, [this] { store(); }); + return w; + } + + InsightsTab() + { + using A = AutopilotConfig; + using DS = QDoubleSpinBox; + auto *l = scrollRoot(this); + auto *top = row(l); + auto *hp = panel("Health", {health, reasons, button("Analyze now", nullptr, [this] { s->analyzeNow(); })}); + hp->setFixedWidth(330), health->setMinimumHeight(190), top->addWidget(hp); + auto *right = sub(top, 1); + t = addTiles(grid(right), {{"Disk full forecast", C::amber}, {"Memory trend (6 h)", C::violet}, {"CPU / memory p95 (30 d)", C::accent}, + {"Availability 24 h", C::green}, {"Availability 7 d", C::green}, {"Availability 30 d", C::green}}, 3); + right->addWidget(panel("Capacity planning", {capacity, nullptr})); + + auto *mid = row(l); + auto *fp = panel("Findings from history analysis"); + 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)}); + auto *form = new QFormLayout; + auto *runRow = new QHBoxLayout; + auto *cmd = new QLineEdit; + findings->setSpacing(10), lay(fp)->addLayout(findings), lay(fp)->addStretch(), mid->addWidget(fp, 1); + runRow->addWidget(spin(&A::runawayCpu, 10, 6400, "≥ ", " %")), runRow->addWidget(spin(&A::runawayMinutes, 1, 1440, "for ", " min")); + cmd->setFont(QFont(C::mono(), 9)); + binds << [cmd](A &a, bool ld) { ld ? cmd->setText(a.diskCleanupCommand) : void(a.diskCleanupCommand = cmd->text().trimmed()); }; + connect(cmd, &QLineEdit::editingFinished, this, [this] { store(); }); + form->addRow(chk("Autopilot enabled", &A::enabled), chk("Dry run (only report)", &A::dryRun)); + form->addRow(chk("Restart failed services", &A::restartFailed), spin(&A::maxRestartsPerHour, 1, 20, "", " / hour max")); + form->addRow("Runaway processes", combo(&A::runawayMode, {"none", "renice", "terminate"}, {"Ignore", "Lower priority (renice 19)", "Terminate"})); + form->addRow("", runRow); + form->addRow("Memory leaks", combo(&A::leakMode, {"none", "notify", "terminate"}, {"Ignore", "Notify", "Terminate under pressure"})); + form->addRow(" pressure ≥", spin(&A::leakMemPressure, 50, 100, "", " % memory")); + form->addRow(chk("Disk cleanup", &A::diskCleanup), spin(&A::diskForecastDays, 1, 60, "full in < ", " days")); + form->addRow("", spin(&A::diskCleanupAt, 50, 100, "or usage ≥ ", " %")); + form->addRow(" command", cmd); + form->addRow(chk("Anomaly alerts", &A::anomalyAlerts), spin(&A::anomalyZ, 1.5, 10, "z ≥ ", " σ")); + ap->setFixedWidth(430), lay(ap)->addLayout(form), lay(ap)->addStretch(), mid->addWidget(ap, 0, Qt::AlignTop); + + auto *bot = row(l); + heatMetric->addItems({"CPU", "Memory"}), heatMetric->setFixedWidth(140), anomalies->setMinimumHeight(230); + connect(heatMetric, QOverload::of(&QComboBox::currentIndexChanged), this, [this] { analysis(); }); + bot->addWidget(panel("Weekly pattern (last 4 weeks, hourly averages)", {heatMetric, heat}), 3), bot->addWidget(panel("Now vs. normal (baselines)", {anomalies}), 2); + } + void bind(ServerSession *x) override + { + Tab::bind(x); + if (!x) return; + AutopilotConfig a = x->config().autopilot; + loading = true; + for (auto &b : binds) b(a, true); + loading = false, analysis(); + } + void store() + { + if (loading || !s) return; + ServerConfig c = s->config(); + for (auto &b : binds) b(c.autopilot, false); + save(c); + } + void analysis() override + { + const Analysis &a = s->analysis(); + const int hi = heatMetric->currentIndex(); + health->setValue(a.health, QString::number(a.health), "grade " + a.grade, C::health(a.health)); + reasons->setText((a.healthReasons.isEmpty() ? "No deductions — everything looks healthy." : a.healthReasons.join('\n')) + + (a.when ? "\n\nAnalyzed " + QDateTime::fromSecsSinceEpoch(a.when).toString("HH:mm:ss") : "")); + 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()); + 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); + 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()); + else t[1]->set("—", "needs ~90 min of history"); + 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"); + for (int i = 0; i < 3; ++i) + std::isnan(a.up[i]) ? t[3 + i]->set("—", "no data yet") + : 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); + capacity->setText("

• " + a.capacity.join("

• ") + "

"); + heat->setData(a.heat[hi], a.heatN, hi ? "% memory" : "% CPU", hi ? C::violet : C::accent); + fillRows(anomalies, a.anomalies, [](const Anomaly &x) { + const double az = qAbs(x.z); + return Row{{x.metric}, {fmtMetric(x.hm, x.now), {}, true}, {fmtMetric(x.hm, x.mean) + " ± " + fmtMetric(x.hm, x.sd), C::muted, true}, + {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}}; + }); + + while (QLayoutItem *it = findings->takeAt(0)) { // rebuild the finding cards + if (it->widget()) it->widget()->deleteLater(); + delete it; + } + if (a.findings.isEmpty()) { + 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); + ok->setStyleSheet("color: #22c55e; padding: 10px;"), findings->addWidget(ok); + } + const AutopilotConfig &ap = s->config().autopilot; + for (const Finding &f : a.findings) { + const QColor c = C::severity(f.severity); + auto *card = new QFrame; + auto *cl = new QHBoxLayout(card); + card->setObjectName("F"); + card->setStyleSheet(QString("#F { background: #1a2133; border: 1px solid #27314a; border-left: 4px solid %1; border-radius: 10px; }").arg(c.name())); + cl->addWidget(label(QString("%2 · %3
%4
%5
" + "→ %6%7").arg(c.name(), f.severity.toUpper(), f.category.toUpper(), f.title.toHtmlEscaped(), f.detail.toHtmlEscaped(), f.advice.toHtmlEscaped(), + f.autoEligible && ap.enabled ? QString("
%1").arg(ap.dryRun ? "Autopilot (dry run) would act on this" : "Autopilot handles this automatically") : ""), + nullptr, true), 1); + findings->addWidget(card); + if (f.action.isEmpty()) continue; + auto *b = button(f.actionLabel, f.action == "kill_pid" ? "Danger" : "Primary"); + cl->addWidget(b, 0, Qt::AlignVCenter); + connect(b, &QPushButton::clicked, this, [this, f, pb = QPointer(b)] { // the card may be rebuilt while the question is open + if (!ask(this, f.actionLabel, QString("%1 on %2?\n\n%3").arg(f.actionLabel, s->config().name, f.title))) return; + if (pb) pb->setEnabled(false), pb->setText("Working…"); + s->runFinding(f, false, [pb](int code, const QString &) { if (pb) pb->setText(code ? "✗ Failed" : "✓ Done"); }); + }); + } + } +}; + +QVector> makeTabs() +{ + return {{"Overview", new OverviewTab}, {"CPU", new CpuTab}, {"Memory", new MemoryTab}, {"Storage", new StorageTab}, {"Network", new NetworkTab}, + {"Processes", new ProcessTab}, {"Services", new ServiceTab}, {"History", new HistoryTab}, {"Insights && Autopilot", new InsightsTab}, + {"Alert rules", new RulesTab}, {"Console", new ConsoleTab}}; +} diff --git a/Server Monitor(cqt-window)/src/ui/Widgets.cpp b/Server Monitor(cqt-window)/src/ui/Widgets.cpp new file mode 100644 index 0000000000000000000000000000000000000000..c9dccd43ba64fc5b7474517b80eb01d724757ced --- /dev/null +++ b/Server Monitor(cqt-window)/src/ui/Widgets.cpp @@ -0,0 +1,485 @@ +#include "Widgets.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +// ---- theme -------------------------------------------------------------------------------- +QColor C::level(double p, double w, double c) { return p >= c ? red : p >= w ? amber : green; } +QColor C::severity(const QString &s) { return s == "critical" ? red : s == "warning" ? amber : s == "resolved" ? green : s == "action" ? violet : accent; } +QColor C::health(int h) { return h >= 90 ? green : h >= 75 ? teal : h >= 60 ? amber : h >= 40 ? orange : red; } +QColor C::mix(const QColor &a, const QColor &b, double t) +{ + t = qBound(0.0, t, 1.0); + return QColor::fromRgbF(a.redF() + (b.redF() - a.redF()) * t, a.greenF() + (b.greenF() - a.greenF()) * t, a.blueF() + (b.blueF() - a.blueF()) * t); +} +QString C::mono() { return QFontDatabase::systemFont(QFontDatabase::FixedFont).family(); } + +QString C::styleSheet() +{ + return R"( +* { color: #e6ebf5; font-size: 13px; } +QMainWindow, QDialog, #Page { background: #0d111c; } +#Sidebar { background: #10151f; border-right: 1px solid #1f2738; } +QToolTip { background: #1a2133; border: 1px solid #38bdf8; padding: 6px; border-radius: 6px; } +QLabel#H1 { font-size: 22px; font-weight: 700; } QLabel#H2 { font-size: 16px; font-weight: 600; } +QLabel#Muted { color: #8b95ab; } QLabel#Section { color: #8b95ab; font-size: 11px; font-weight: 700; letter-spacing: 1px; } +QFrame#Panel { background: #161c2b; border: 1px solid #232c41; border-radius: 12px; } +QPushButton { background: #1d2538; border: 1px solid #2c3650; border-radius: 8px; padding: 7px 14px; font-weight: 600; } +QPushButton:hover { background: #253049; border-color: #38bdf8; } QPushButton:pressed { background: #18324a; } +QPushButton:disabled { color: #5a657d; border-color: #222a3c; } +QPushButton:checked, QPushButton#Primary { background: #0e7ab8; border-color: #38bdf8; color: white; } QPushButton#Primary:hover { background: #1190d8; } +QPushButton#Danger { background: #3a1820; border-color: #7f2a36; color: #ffb4bd; } QPushButton#Danger:hover { background: #55202b; border-color: #ef4444; } +QPushButton#Nav { text-align: left; padding: 10px 14px; border: none; background: transparent; font-size: 14px; } +QPushButton#Nav:hover { background: #1a2133; } QPushButton#Nav:checked { background: #17304a; color: #7dd3fc; } +QPushButton#Flat { background: transparent; border: none; padding: 4px 8px; color: #8b95ab; } QPushButton#Flat:hover { color: #e6ebf5; } +QPushButton#Side { text-align: left; padding: 6px 12px; } +QLineEdit, QSpinBox, QDoubleSpinBox, QComboBox, QPlainTextEdit { background: #111727; border: 1px solid #2a3449; border-radius: 7px; padding: 6px 8px; selection-background-color: #0e7ab8; } +QLineEdit:focus, QSpinBox:focus, QDoubleSpinBox:focus, QComboBox:focus, QPlainTextEdit:focus { border-color: #38bdf8; } +QComboBox::drop-down { border: none; width: 22px; } +QComboBox QAbstractItemView { background: #161c2b; border: 1px solid #2a3449; selection-background-color: #17304a; } +QCheckBox::indicator { width: 16px; height: 16px; border-radius: 4px; border: 1px solid #3a4662; background: #111727; } +QCheckBox::indicator:checked { background: #0ea5e9; border-color: #38bdf8; } +QTabWidget::pane { border: none; } +QTabBar::tab { background: transparent; color: #8b95ab; padding: 10px 14px; border-bottom: 2px solid transparent; } +QTabBar::tab:hover { color: #e6ebf5; } QTabBar::tab:selected { color: #7dd3fc; border-bottom: 2px solid #38bdf8; } +QTableView, QListView { background: #131929; alternate-background-color: #161d2e; border: 1px solid #232c41; border-radius: 10px; + selection-background-color: #17304a; selection-color: #e6ebf5; outline: none; } +QTableView::item { padding: 4px; } +QHeaderView::section { background: #182033; color: #8b95ab; border: none; border-bottom: 1px solid #27314a; padding: 7px 8px; font-weight: 700; font-size: 12px; } +QScrollBar:vertical { background: transparent; width: 10px; margin: 2px; } QScrollBar:horizontal { background: transparent; height: 10px; margin: 2px; } +QScrollBar::handle { background: #2a3449; border-radius: 4px; min-height: 30px; min-width: 30px; } QScrollBar::handle:hover { background: #3b4866; } +QScrollBar::add-line, QScrollBar::sub-line { width: 0; height: 0; } QScrollBar::add-page, QScrollBar::sub-page { background: none; } +QScrollArea { border: none; background: transparent; } QScrollArea > QWidget > QWidget { background: transparent; } +QMenu { background: #161c2b; border: 1px solid #2a3449; border-radius: 8px; padding: 6px; } +QMenu::item { padding: 7px 22px; border-radius: 5px; } QMenu::item:selected { background: #17304a; } +QMenu::separator { height: 1px; background: #27314a; margin: 4px 8px; } +)"; +} + +QIcon C::appIcon() +{ + QIcon icon; + for (int s : {16, 32, 64, 128, 256}) { + QPixmap pm(s, s); + pm.fill(Qt::transparent); + QPainter p(&pm); + p.setRenderHint(QPainter::Antialiasing); + QLinearGradient g(0, 0, s, s); + g.setColorAt(0, 0x0ea5e9), g.setColorAt(1, 0x7c3aed); + p.setBrush(g), p.setPen(Qt::NoPen); + p.drawRoundedRect(QRectF(0, 0, s, s), s * .22, s * .22); + p.setPen(QPen(Qt::white, qMax(1.5, s * .075), Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); + 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}})); + icon.addPixmap(pm); + } + return icon; +} + +QFont pxFont(QFont f, int px, bool bold) { return f.setPixelSize(px), f.setBold(bold), f; } +static double niceCeil(double v) +{ + if (v <= 0) return 1; + const double e = std::pow(10, std::floor(std::log10(v))), f = v / e; + return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * e; +} +static void roundedPanel(QPainter &p, const QRectF &r, const QBrush &b, const QColor &border = C::border, double rad = 12) +{ + p.setPen(QPen(border, 1)), p.setBrush(b); + p.drawRoundedRect(r.adjusted(.5, .5, -.5, -.5), rad, rad); +} + +void paintRing(QPainter &p, const QRectF &r, double pct, const QColor &c, double t, bool glow) +{ + p.save(); + p.setRenderHint(QPainter::Antialiasing); + const QRectF rr = r.adjusted(t / 2, t / 2, -t / 2, -t / 2); + p.setPen(QPen(C::grid, t, Qt::SolidLine, Qt::RoundCap)); + p.drawArc(rr, 225 * 16, -270 * 16); + const int span = int(-270 * 16 * qBound(0.0, pct, 100.0) / 100); + if (span < -3) { + if (glow) p.setPen(QPen(C::tint(c, 45), t * 2, Qt::SolidLine, Qt::RoundCap)), p.drawArc(rr, 225 * 16, span); + p.setPen(QPen(c, t, Qt::SolidLine, Qt::RoundCap)); + p.drawArc(rr, 225 * 16, span); + } + p.restore(); +} + +// ---- RingGauge ------------------------------------------------------------------------------ +RingGauge::RingGauge(const QString &title) : m_title(title) +{ + m_anim.setDuration(450), m_anim.setEasingCurve(QEasingCurve::OutCubic); + connect(&m_anim, &QVariantAnimation::valueChanged, this, [this](const QVariant &v) { m_shown = v.toDouble(), update(); }); +} +void RingGauge::setValue(double pct, const QString ¢er, const QString &sub, const QColor &color) +{ + m_center = center, m_sub = sub, m_color = color; + pct = std::isnan(pct) ? 0 : pct; + if (qAbs(pct - m_target) > 0.05) m_anim.stop(), m_anim.setStartValue(m_shown), m_anim.setEndValue(m_target = pct), m_anim.start(); + update(); +} +void RingGauge::paintEvent(QPaintEvent *) +{ + AA p(this); + const double s = qMin(width() - 8.0, height() - 28.0); + const QRectF r((width() - s) / 2, 4, s, s); + paintRing(p, r, m_shown, m_color.isValid() ? m_color : C::level(m_target, warn, crit), qMax(7.0, s * .085)); + p.setFont(pxFont(font(), int(s * .2), true)), p.setPen(C::text); + 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); + p.setFont(pxFont(font(), qMax(10, int(s * .075)))), p.setPen(C::muted); + 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))); + p.setFont(pxFont(font(), 13, true)), p.setPen(C::text); + p.drawText(QRectF(0, r.bottom() - s * .06, width(), 22), Qt::AlignHCenter, m_title); +} + +// ---- TimeChart -------------------------------------------------------------------------------- +TimeChart::TimeChart(const QString &t, FmtFn fmt, double yMax) : title(t), m_fmt(fmt), m_yMax(yMax) +{ + setMouseTracking(true), setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Expanding); +} +void TimeChart::setData(const QVector &t, const QVector &s, qint64 span) { m_t = t, m_s = s, m_span = span, update(); } +void TimeChart::mouseMoveEvent(QMouseEvent *e) { m_hover = e->pos().x(), update(); } + +void TimeChart::paintEvent(QPaintEvent *) +{ + AA p(this); + roundedPanel(p, rect(), C::panel); + p.setFont(pxFont(font(), 13, true)), p.setPen(C::text); + p.drawText(16, 10, width(), 20, Qt::AlignVCenter, title); + const int titleW = p.fontMetrics().horizontalAdvance(title); + p.setFont(pxFont(font(), 11)), p.setPen(C::muted); + p.drawText(24 + titleW, 10, width(), 20, Qt::AlignVCenter, subtitle); + double lx = width() - 16; // legend with latest values, right-aligned + for (int i = m_s.size() - 1; i >= 0; --i) { + const Series &s = m_s[i]; + double last = NAN; + for (int k = s.v.size() - 1; k >= qMax(0, s.v.size() - 5) && std::isnan(last); --k) last = s.v[k]; + const QString txt = s.name + (std::isnan(last) ? "" : " " + m_fmt(last)); + const int w = p.fontMetrics().horizontalAdvance(txt); + if ((lx -= w) < 40 + titleW) break; + p.setPen(C::muted), p.drawText(QRectF(lx, 10, w, 20), Qt::AlignVCenter, txt); + p.setPen(Qt::NoPen), p.setBrush(s.color), p.drawRoundedRect(QRectF(lx -= 14, 16, 9, 9), 2, 2); + lx -= 14; + } + const int n = m_t.size(); + int first = 0; + if (n && m_span) + while (first < n && m_t[first] < m_t.last() - m_span) ++first; + QRectF plot(56, 40, width() - 72, height() - 70); + if (n - first < 2 || plot.height() < 20) return p.setPen(C::faint), p.drawText(plot, Qt::AlignCenter, empty); + + double yMax = m_yMax; + if (yMax <= 0) { + for (int i = first; i < n; ++i) { + double sum = 0; + for (const Series &s : m_s) + if (i < s.v.size() && !std::isnan(s.v[i])) sum = stacked ? sum + s.v[i] : qMax(sum, s.v[i]); + yMax = qMax(yMax, sum); + } + yMax = niceCeil(yMax * 1.12); + } + p.setFont(pxFont(font(), 10)); + int lw = 0; + for (int g = 0; g <= 4; ++g) lw = qMax(lw, p.fontMetrics().horizontalAdvance(m_fmt(yMax * g / 4))); + plot.setLeft(qMax(40, lw + 18)); + const qint64 t1 = m_t.last(), t0 = m_span ? t1 - m_span : m_t[first]; + const double tr = qMax(1, t1 - t0); + auto X = [&](qint64 t) { return plot.left() + (t - t0) / tr * plot.width(); }; + auto Y = [&](double v) { return plot.bottom() - qBound(0.0, v, yMax) / yMax * plot.height(); }; + const QString tf = tr <= 72e5 ? "HH:mm" : tr <= 2.6e8 ? "ddd HH:mm" : tr <= 3.5e10 ? "dd MMM" : "MMM yyyy"; + for (int g = 0; g <= 4; ++g) { // grid, y labels, time labels + const double y = Y(yMax * g / 4), x = X(t0 + qint64(tr * g / 4)); + p.setPen(QPen(C::grid, 1, g ? Qt::DashLine : Qt::SolidLine)), p.drawLine(QPointF(plot.left(), y), QPointF(plot.right(), y)); + p.setPen(C::faint); + p.drawText(QRectF(0, y - 8, plot.left() - 8, 16), Qt::AlignRight | Qt::AlignVCenter, m_fmt(yMax * g / 4)); + 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), + QDateTime::fromMSecsSinceEpoch(t0 + qint64(tr * g / 4)).toString(tf)); + } + const int step = qMax(1, (n - first) / qMax(50, int(plot.width() * 1.5))); // ~1.5 points per pixel + QVector base(n, 0.0); + p.setClipRect(plot.adjusted(-2, -4, 2, 2)); + for (const Series &s : m_s) { + QVector top(1), bot(1); // runs split at gaps (NaN) + for (int i = first; i < n; i += step) { + double sum = 0, bs = 0; + int c = 0; + for (int k = i; k < qMin(n, i + step); ++k) + if (k < s.v.size() && !std::isnan(s.v[k])) sum += s.v[k], bs += base[k], ++c; + if (!c) { if (!top.last().isEmpty()) top << QPolygonF(), bot << QPolygonF(); continue; } + const double x = X(m_t[qMin(n - 1, i + step / 2)]), b = stacked ? bs / c : 0; + top.last() << QPointF(x, Y(sum / c + b)), bot.last() << QPointF(x, Y(b)); + } + if (stacked) + for (int k = first; k < qMin(n, s.v.size()); ++k) base[k] += std::isnan(s.v[k]) ? 0 : s.v[k]; + for (int r = 0; r < top.size(); ++r) { + if (top[r].size() < 2) continue; + if (s.fill) { + QPolygonF area = top[r]; + for (int i = bot[r].size() - 1; i >= 0; --i) area << bot[r][i]; + QLinearGradient g(0, plot.top(), 0, plot.bottom()); + g.setColorAt(0, C::tint(s.color, stacked ? 120 : 95)), g.setColorAt(1, C::tint(s.color, stacked ? 60 : 4)); + p.setPen(Qt::NoPen), p.setBrush(g), p.drawPolygon(area); + } + p.setBrush(Qt::NoBrush), p.setPen(QPen(s.color, s.dashed ? 1.3 : 2, s.dashed ? Qt::DashLine : Qt::SolidLine, Qt::RoundCap, Qt::RoundJoin)); + p.drawPolyline(top[r]); + } + } + p.setClipping(false); + if (m_hover < plot.left() || m_hover > plot.right()) return; + const qint64 ht = t0 + qint64((m_hover - plot.left()) / plot.width() * tr); // crosshair + tooltip + const int best = std::lower_bound(m_t.begin() + first, m_t.end(), ht) - m_t.begin() - (m_t.last() < ht); + const double x = X(m_t[best]); + p.setPen(QPen(QColor(255, 255, 255, 70), 1, Qt::DashLine)), p.drawLine(QPointF(x, plot.top()), QPointF(x, plot.bottom())); + QStringList lines{QDateTime::fromMSecsSinceEpoch(m_t[best]).toString(tr > 864e5 ? "ddd dd MMM HH:mm" : "HH:mm:ss")}; + double stack = 0; + for (const Series &s : m_s) { + const double v = best < s.v.size() ? s.v[best] : NAN; + lines << s.name + ": " + (std::isnan(v) ? "—" : m_fmt(v)); + if (std::isnan(v)) continue; + stack = stacked ? stack + v : v; + p.setPen(QPen(C::panel, 2)), p.setBrush(s.color), p.drawEllipse(QPointF(x, Y(stack)), 4, 4); + } + p.setFont(pxFont(font(), 11)); + int tw = 0; + for (const QString &l : lines) tw = qMax(tw, p.fontMetrics().horizontalAdvance(l)); + const QRectF tip(qMin(x + 12, plot.right() - tw - 20), plot.top() + 4, tw + 18, lines.size() * 16 + 10); + roundedPanel(p, tip, QColor(13, 17, 28, 235), C::border, 7); + 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]); +} + +// ---- SegmentBar -------------------------------------------------------------------------------- +SegmentBar::SegmentBar() { setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed), setFixedHeight(58); } +void SegmentBar::setSegments(const QVector &s, double total) { m_s = s, m_total = total > 0 ? total : 1, update(); } +void SegmentBar::paintEvent(QPaintEvent *) +{ + AA p(this); + QPainterPath clip; + clip.addRoundedRect(QRectF(0, 2, width(), 14), 7, 7); + p.setClipPath(clip); + p.fillRect(rect(), C::grid); + double x = 0, lx = 0, ly = 26; + 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()); + p.setClipping(false); + p.setFont(pxFont(font(), 11)); + for (const Segment &s : m_s) { + const QString t = s.label + " " + Fmt::bytes(s.value); + const int w = p.fontMetrics().horizontalAdvance(t) + 26; + if (lx + w > width()) lx = 0, ly += 18; + p.setPen(Qt::NoPen), p.setBrush(s.color), p.drawRoundedRect(QRectF(lx, ly + 3, 9, 9), 2, 2); + p.setPen(C::muted), p.drawText(QRectF(lx + 14, ly, w, 16), Qt::AlignVCenter, t); + lx += w; + } +} + +// ---- StatTile ------------------------------------------------------------------------------------ +StatTile::StatTile(const QString &title, const QColor &accent) : m_accent(accent) +{ + auto *l = new QVBoxLayout(this); + l->setContentsMargins(16, 12, 14, 12), l->setSpacing(2); + l->addWidget(label(title.toUpper(), "Section")); + l->addWidget(m_value = new QLabel("—")); + l->addWidget(m_sub = label({}, "Muted")); + m_sub->setStyleSheet("font-size: 11px;"); + setMinimumHeight(84), setSizePolicy(QSizePolicy::Expanding, QSizePolicy::Fixed), set("—"); +} +void StatTile::set(const QString &v, const QString &sub, const QColor &c) +{ + m_value->setText(v), m_sub->setText(sub), m_sub->setVisible(!sub.isEmpty()); + m_value->setStyleSheet(QString("font-size: 21px; font-weight: 700; color: %1;").arg((c.isValid() ? c : C::text).name())); +} +void StatTile::paintEvent(QPaintEvent *) +{ + AA p(this); + QLinearGradient g(0, 0, width(), height()); + g.setColorAt(0, C::card), g.setColorAt(1, C::panel); + roundedPanel(p, rect(), g); + p.setPen(Qt::NoPen), p.setBrush(m_accent), p.drawRoundedRect(QRectF(0, 14, 4, height() - 28), 2, 2); +} +QVector addTiles(QGridLayout *g, const QVector> &defs, int cols) +{ + QVector out; + g->setSpacing(14); + for (const auto &d : defs) out << new StatTile(d.first, d.second), g->addWidget(out.last(), (out.size() - 1) / cols, (out.size() - 1) % cols); + return out; +} + +// ---- CoreGrid --------------------------------------------------------------------------------------- +CoreGrid::CoreGrid() +{ + QSizePolicy sp(QSizePolicy::Expanding, QSizePolicy::Preferred); + sp.setHeightForWidth(true); + setSizePolicy(sp); +} +void CoreGrid::setCores(const QVector &c) +{ + if (c.size() != m_c.size()) updateGeometry(); + m_c = c, update(); +} +void CoreGrid::paintEvent(QPaintEvent *) +{ + AA p(this); + const int cols = qMax(1, width() / 92); + const double cw = double(width()) / cols; + for (int i = 0; i < m_c.size(); ++i) { + const double u = m_c[i].usage; + const QColor c = C::level(u, 60, 85); + 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); + roundedPanel(p, r, C::mix(C::card, c, u / 420), C::mix(C::border, c, u / 160), 8); + p.setPen(Qt::NoPen), p.setBrush(C::grid), p.drawRoundedRect(bar, 2, 2); + p.setBrush(c), p.drawRoundedRect(QRectF(bar.left(), bar.top(), bar.width() * u / 100, 4), 2, 2); + p.setFont(pxFont(font(), 10)), p.setPen(C::muted); + p.drawText(r.adjusted(8, 5, -8, 0), Qt::AlignLeft, QString("CPU %1").arg(i)); + 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"); + p.setFont(pxFont(font(), 16, true)), p.setPen(C::text); + p.drawText(r.adjusted(8, 18, -8, -14), Qt::AlignVCenter, QString::number(u, 'f', 0) + "%"); + } +} + +// ---- WeekHeatmap --------------------------------------------------------------------------------------- +static const QStringList kDays = {"Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday"}; +WeekHeatmap::WeekHeatmap() : m_hot(C::accent) +{ + std::fill(&m_v[0][0], &m_v[0][0] + 168, NAN), std::fill(&m_n[0][0], &m_n[0][0] + 168, 0); + setMouseTracking(true), setMinimumHeight(230); +} +void WeekHeatmap::setData(const double v[7][24], const int n[7][24], const QString &unit, const QColor &hot) +{ + std::copy(&v[0][0], &v[0][0] + 168, &m_v[0][0]); + std::copy(&n[0][0], &n[0][0] + 168, &m_n[0][0]); + m_unit = unit, m_hot = hot, update(); +} +QRectF WeekHeatmap::cell(int d, int h) const +{ + const double cw = (width() - 44) / 24.0, ch = (height() - 30) / 7.0; + return QRectF(40 + h * cw + 1.5, 6 + d * ch + 1.5, cw - 3, ch - 3); +} +void WeekHeatmap::paintEvent(QPaintEvent *) +{ + AA p(this); + p.setFont(pxFont(font(), 10)); + bool any = false; + for (int d = 0; d < 7; ++d) { + 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)); + for (int h = 0; h < 24; ++h) { + const double v = m_v[d][h]; + any |= !std::isnan(v); + 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))); + p.drawRoundedRect(cell(d, h), 3, 3); + } + } + p.setPen(C::faint); + 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'))); + if (any) return; + const QRectF box(cell(2, 3).topLeft(), cell(4, 20).bottomRight()); + p.fillRect(box, QColor(13, 17, 28, 200)), p.setPen(C::text), p.setFont(pxFont(font(), 12)); + p.drawText(box, Qt::AlignCenter, "Collecting hourly history… the weekly pattern fills in over time"); +} +void WeekHeatmap::mouseMoveEvent(QMouseEvent *e) +{ + for (int d = 0; d < 7; ++d) + for (int h = 0; h < 24; ++h) + if (cell(d, h).contains(e->pos())) + return QToolTip::showText(e->globalPos(), std::isnan(m_v[d][h]) ? QString("%1 %2:00 — no data").arg(kDays[d]).arg(h) + : 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); + QToolTip::hideText(); +} + +// ---- table helpers -------------------------------------------------------------------------------------- +void BarDelegate::paint(QPainter *p, const QStyleOptionViewItem &o, const QModelIndex &i) const +{ + const QVariant pv = i.data(Qt::UserRole); + if (!pv.isValid()) return QStyledItemDelegate::paint(p, o, i); + p->save(); + p->setRenderHint(QPainter::Antialiasing); + if (o.state & QStyle::State_Selected) p->fillRect(o.rect, o.palette.highlight()); + const double pct = qBound(0.0, pv.toDouble(), 100.0); + const QRectF r = QRectF(o.rect).adjusted(6, o.rect.height() / 2.0 - 7, -6, -(o.rect.height() / 2.0 - 7)); + const QColor c = C::level(pct); + p->setPen(Qt::NoPen), p->setBrush(C::grid), p->drawRoundedRect(r, 4, 4); + p->setBrush(C::tint(c, 200)), p->drawRoundedRect(QRectF(r.left(), r.top(), r.width() * pct / 100, r.height()), 4, 4); + p->setFont(pxFont(o.font, 11, true)), p->setPen(C::text), p->drawText(r, Qt::AlignCenter, i.data().toString()); + p->restore(); +} + +int FlowLayout::place(const QRect &r, bool apply) const +{ + if (m_items.isEmpty()) return 0; + 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; + int y = r.y(), rowH = 0, col = 0; + for (QLayoutItem *it : m_items) { + if (it->widget() && it->widget()->isHidden()) continue; + if (apply) it->setGeometry(QRect(r.x() + col * (w + sp), y, w, it->sizeHint().height())); + rowH = qMax(rowH, it->sizeHint().height()); + if (++col == cols) col = 0, y += rowH + sp, rowH = 0; + } + return y + rowH - r.y(); +} + +// ---- builders ---------------------------------------------------------------------------------------- +QLabel *label(const QString &text, const char *name, bool wrap) +{ + auto *l = new QLabel(text); + if (name) l->setObjectName(name); + l->setWordWrap(wrap); + return l; +} +QPushButton *button(const QString &text, const char *style, std::function onClick) +{ + auto *b = new QPushButton(text); + if (style) b->setObjectName(style); + if (onClick) QObject::connect(b, &QPushButton::clicked, b, onClick); + return b; +} +QFrame *panel(const QString &title, std::initializer_list content) +{ + auto *f = new QFrame; + f->setObjectName("Panel"); + auto *l = new QVBoxLayout(f); + l->setContentsMargins(16, 14, 16, 14), l->setSpacing(10); + if (!title.isEmpty()) l->addWidget(label(title.toUpper(), "Section")); + for (QWidget *w : content) w ? l->addWidget(w) : l->addStretch(); + return f; +} +bool ask(QWidget *parent, const QString &title, const QString &text) { return QMessageBox::question(parent, title, text) == QMessageBox::Yes; } + +namespace { +struct SortItem : QTableWidgetItem { // sorts by Qt::UserRole+1 when set (numbers sort numerically) + bool operator<(const QTableWidgetItem &o) const override + { + const QVariant a = data(Qt::UserRole + 1), b = o.data(Qt::UserRole + 1); + if (!a.isValid() || !b.isValid()) return text() < o.text(); + return a.type() == QVariant::String ? a.toString() < b.toString() : a.toDouble() < b.toDouble(); + } +}; +} + +QTableWidget *table(const QStringList &headers, const QVector &widths, const QVector &bars) +{ + auto *t = new QTableWidget(0, headers.size()); + t->setHorizontalHeaderLabels(headers); + t->verticalHeader()->hide(), t->verticalHeader()->setDefaultSectionSize(30); + t->setAlternatingRowColors(true), t->setShowGrid(false), t->setWordWrap(false); + t->setSelectionBehavior(QAbstractItemView::SelectRows), t->setSelectionMode(QAbstractItemView::SingleSelection); + t->setEditTriggers(QAbstractItemView::NoEditTriggers), t->setFocusPolicy(Qt::NoFocus), t->setVerticalScrollMode(QAbstractItemView::ScrollPerPixel); + t->horizontalHeader()->setHighlightSections(false), t->horizontalHeader()->setStretchLastSection(true); + t->horizontalHeader()->setDefaultAlignment(Qt::AlignLeft | Qt::AlignVCenter); + for (int i = 0; i < widths.size(); ++i) t->setColumnWidth(i, widths[i]); + for (int c : bars) t->setItemDelegateForColumn(c, new BarDelegate(t)); + return t; +} +void cell(QTableWidget *t, int r, int c, const Cell &x) +{ + QTableWidgetItem *it = t->item(r, c); + if (!it) t->setItem(r, c, it = new SortItem); + if (it->text() != x.text) it->setText(x.text); + it->setTextAlignment(int(x.right ? Qt::AlignRight : Qt::AlignLeft) | Qt::AlignVCenter); + it->setForeground(x.color.isValid() ? x.color : C::text); + if (x.pct >= 0) it->setData(Qt::UserRole, x.pct); + if (x.key.isValid()) it->setData(Qt::UserRole + 1, x.key); +} diff --git a/Server Monitor(cqt-window)/src/ui/Widgets.h b/Server Monitor(cqt-window)/src/ui/Widgets.h new file mode 100644 index 0000000000000000000000000000000000000000..916e8c4a461ff62a1c9d679e3c76e37eaaf20da4 --- /dev/null +++ b/Server Monitor(cqt-window)/src/ui/Widgets.h @@ -0,0 +1,150 @@ +// Theme, hand-painted widgets (gauges, time charts, bars, tiles, core grid, weekly +// heatmap), a flow layout and small builders for labels, buttons, panels and tables. +#pragma once +#include "core/Model.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include + +namespace C { // palette +inline const QColor bg{0x0d111c}, panel{0x161c2b}, card{0x1a2133}, cardHover{0x20293f}, border{0x27314a}, grid{0x242d42}, + text{0xe6ebf5}, muted{0x8b95ab}, faint{0x5a657d}, accent{0x38bdf8}, green{0x22c55e}, amber{0xf59e0b}, red{0xef4444}, + violet{0xa78bfa}, pink{0xf472b6}, teal{0x2dd4bf}, orange{0xfb923c}, blue{0x60a5fa}; +QColor level(double pct, double warn = 70, double crit = 90); // green / amber / red +QColor severity(const QString &s); +QColor health(int h); +QColor mix(const QColor &a, const QColor &b, double t); +inline QColor tint(QColor c, int alpha) { return c.setAlpha(alpha), c; } +QString styleSheet(); +QIcon appIcon(); +QString mono(); +} + +using FmtFn = std::function; +inline const FmtFn pctFmt = [](double v) { return QString::number(v, 'f', 0) + "%"; }, rateFmt = Fmt::rate; +inline FmtFn numFmt(int prec) { return [prec](double v) { return QString::number(v, 'f', prec); }; } + +struct AA : QPainter { // antialiased painter + explicit AA(QPaintDevice *d) : QPainter(d) { setRenderHint(Antialiasing); } +}; +QFont pxFont(QFont f, int px, bool bold = false); +void paintRing(QPainter &p, const QRectF &r, double pct, const QColor &c, double thick, bool glow = true); // 270° arc + +struct RingGauge : QWidget { + explicit RingGauge(const QString &title); + void setValue(double pct, const QString ¢er = {}, const QString &sub = {}, const QColor &color = {}); + double warn = 70, crit = 90; + QSize sizeHint() const override { return {170, 190}; } + void paintEvent(QPaintEvent *) override; + QString m_title, m_center, m_sub; + QColor m_color; + double m_target = 0, m_shown = 0; + QVariantAnimation m_anim; +}; + +struct Series { QString name; QColor color; QVector v; bool fill = true, dashed = false; }; +struct TimeChart : QWidget { + explicit TimeChart(const QString &title, FmtFn fmt = pctFmt, double yMax = 0); // yMax 0 = auto + void setData(const QVector &tMs, const QVector &s, qint64 spanMs = 0); // span 0 = all + QString title, subtitle, empty = "Waiting for data…"; + bool stacked = false; + QSize sizeHint() const override { return {480, 230}; } + QSize minimumSizeHint() const override { return {260, 200}; } + void paintEvent(QPaintEvent *) override; + void mouseMoveEvent(QMouseEvent *) override; + void leaveEvent(QEvent *) override { m_hover = -1, update(); } + FmtFn m_fmt; + double m_yMax; + QVector m_t; + QVector m_s; + qint64 m_span = 0; + int m_hover = -1; +}; + +struct Segment { double value; QColor color; QString label; }; +struct SegmentBar : QWidget { + SegmentBar(); + void setSegments(const QVector &s, double total); + QSize sizeHint() const override { return {300, 58}; } + void paintEvent(QPaintEvent *) override; + QVector m_s; + double m_total = 1; +}; + +struct StatTile : QFrame { + StatTile(const QString &title, const QColor &accent); + void set(const QString &value, const QString &sub = {}, const QColor &color = {}); + void paintEvent(QPaintEvent *) override; + QLabel *m_value, *m_sub; + QColor m_accent; +}; +// creates tiles in a grid (cols per row) from {title, colour} pairs +QVector addTiles(class QGridLayout *g, const QVector> &defs, int cols = 99); + +struct CoreGrid : QWidget { + CoreGrid(); + void setCores(const QVector &c); + bool hasHeightForWidth() const override { return true; } + int heightForWidth(int w) const override { return (qMax(1, m_c.size()) + qMax(1, w / 92) - 1) / qMax(1, w / 92) * 66; } + void paintEvent(QPaintEvent *) override; + QVector m_c; +}; + +struct WeekHeatmap : QWidget { + WeekHeatmap(); + void setData(const double v[7][24], const int n[7][24], const QString &unit, const QColor &hot); + QSize sizeHint() const override { return {560, 230}; } + void paintEvent(QPaintEvent *) override; + void mouseMoveEvent(QMouseEvent *) override; + QRectF cell(int d, int h) const; + double m_v[7][24]; + int m_n[7][24]; + QString m_unit; + QColor m_hot; +}; + +// table cell bar: Qt::UserRole = percent, DisplayRole = text on the bar +struct BarDelegate : QStyledItemDelegate { + using QStyledItemDelegate::QStyledItemDelegate; + void paint(QPainter *p, const QStyleOptionViewItem &o, const QModelIndex &i) const override; +}; + +struct FlowLayout : QLayout { // equal-width columns of cards + FlowLayout(QWidget *parent) : QLayout(parent) {} + ~FlowLayout() override { qDeleteAll(m_items); } + void addItem(QLayoutItem *i) override { m_items << i; } + int count() const override { return m_items.size(); } + QLayoutItem *itemAt(int i) const override { return m_items.value(i); } + QLayoutItem *takeAt(int i) override { return i >= 0 && i < m_items.size() ? m_items.takeAt(i) : nullptr; } + bool hasHeightForWidth() const override { return true; } + int heightForWidth(int w) const override { return place(QRect(0, 0, w, 0), false); } + void setGeometry(const QRect &r) override { QLayout::setGeometry(r), place(r, true); } + QSize sizeHint() const override { return {340, 270}; } + int place(const QRect &r, bool apply) const; + QList m_items; +}; + +// ---- small builders ---------------------------------------------------------------- +QLabel *label(const QString &text, const char *objectName = nullptr, bool wrap = false); +QPushButton *button(const QString &text, const char *style = nullptr, std::function onClick = {}); +QFrame *panel(const QString &title = {}, std::initializer_list content = {}); // nullptr = stretch +bool ask(QWidget *parent, const QString &title, const QString &text); + +struct Cell { QString text; QColor color; bool right = false; double pct = -1; QVariant key; }; // pct = bar, key = sort value +using Row = QVector; +QTableWidget *table(const QStringList &headers, const QVector &widths = {}, const QVector &barColumns = {}); +void cell(QTableWidget *t, int r, int c, const Cell &x); +template void fillRows(QTableWidget *t, const V &items, F rowOf) // one row per item +{ + t->setRowCount(items.size()); + for (int r = 0; r < items.size(); ++r) { + const Row row = rowOf(items[r]); + for (int c = 0; c < row.size(); ++c) cell(t, r, c, row[c]); + } +} diff --git a/Server Monitor(cqt-window)/src/ui/Windows.cpp b/Server Monitor(cqt-window)/src/ui/Windows.cpp new file mode 100644 index 0000000000000000000000000000000000000000..97fc3f5ec0f2c5348ab97d5e3b3ddc6233a675f6 --- /dev/null +++ b/Server Monitor(cqt-window)/src/ui/Windows.cpp @@ -0,0 +1,614 @@ +// Main window: sidebar, dashboard with server cards, server detail page, events page, tray icon. +#include "Windows.h" +#include "Widgets.h" +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +struct Actions { std::function open, edit, remove; std::function add, back; }; // set by the main window +static QColor statusColor(Status s) { return s == Status::Online ? C::green : s == Status::Connecting ? C::amber : s == Status::Offline ? C::red : C::faint; } +static QHBoxLayout *hbox() +{ + auto *h = new QHBoxLayout; + h->setSpacing(10); + return h; +} +static QVBoxLayout *page(QWidget *w, int top = 22) +{ + auto *l = new QVBoxLayout(w); + w->setObjectName("Page"), l->setContentsMargins(28, top, 28, 18), l->setSpacing(14); + return l; +} + +// ============================================================================ dashboard cards +struct Card : QWidget { + bool hover = false; + Card() { setCursor(Qt::PointingHandCursor), setMinimumSize(320, 262); } + QSize sizeHint() const override { return {340, 262}; } + void enterEvent(QEvent *) override { hover = true, update(); } + void leaveEvent(QEvent *) override { hover = false, update(); } +}; + +struct ServerCard : Card { + ServerSession *s; + const Actions *act; + ServerCard(ServerSession *x, const Actions *a) : s(x), act(a) + { + connect(x, &ServerSession::updated, this, QOverload<>::of(&QWidget::update)); + connect(x, &ServerSession::analysisUpdated, this, QOverload<>::of(&QWidget::update)); + } + void mouseReleaseEvent(QMouseEvent *e) override { if (e->button() == Qt::LeftButton) act->open(s->config().id); } + void contextMenuEvent(QContextMenuEvent *e) override + { + const QString id = s->config().id; + QMenu m; + m.addAction("Open details", [=] { act->open(id); }), m.addAction("Reconnect", s, &ServerSession::reconnect), m.addSeparator(); + m.addAction("Edit…", [=] { act->edit(id); }), m.addAction("Remove…", [=] { act->remove(id); }); + m.exec(e->globalPos()); + } + void paintEvent(QPaintEvent *) override + { + AA p(this); + const ServerConfig &c = s->config(); + const Metrics &m = s->metrics(); + const Analysis &an = s->analysis(); + const bool live = s->online(); + const QColor sc = statusColor(s->status()), muted = live ? C::text : C::faint; + QLinearGradient bg(0, 0, 0, height()), strip(0, 0, width(), 0); + bg.setColorAt(0, hover ? C::cardHover : C::card), bg.setColorAt(1, C::panel); + strip.setColorAt(0, sc), strip.setColorAt(.6, C::tint(sc, 0)); + 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); + p.setPen(Qt::NoPen), p.setBrush(strip), p.drawRoundedRect(QRectF(1, 1, width() - 2, 6), 3, 3); + p.setBrush(sc), p.drawEllipse(QPointF(22, 28), 5, 5); + p.setFont(pxFont(font(), 16, true)), p.setPen(C::text); + p.drawText(QRectF(36, 16, width() - 120, 24), Qt::AlignVCenter, p.fontMetrics().elidedText(c.name, Qt::ElideRight, width() - 120)); + p.setFont(pxFont(font(), 11)), p.setPen(C::muted); + p.drawText(QRectF(36, 38, width() - 60, 16), Qt::AlignVCenter, p.fontMetrics().elidedText(c.address() + (m.os.isEmpty() ? "" : " · " + m.os), Qt::ElideRight, width() - 60)); + if (live) { // health badge + const QRectF hb(width() - 62, 12, 44, 44); + paintRing(p, hb, an.health, C::health(an.health), 4, false); + p.setFont(pxFont(font(), 15, true)), p.setPen(C::health(an.health)), p.drawText(hb, Qt::AlignCenter, an.grade); + } else { + p.setFont(pxFont(font(), 10, true)); + const QString chip = statusName(s->status()).toUpper(); + const QRectF cr(width() - p.fontMetrics().horizontalAdvance(chip) - 34, 18, p.fontMetrics().horizontalAdvance(chip) + 18, 20); + p.setPen(sc), p.setBrush(C::tint(sc, 40)), p.drawRoundedRect(cr, 10, 10), p.drawText(cr, Qt::AlignCenter, chip); + } + const bool temp = !m.temps.isEmpty(); // four gauges + 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); + const char *names[4] = {"CPU", "Memory", "Disk", temp ? "Temp" : "Swap"}; + for (int i = 0; i < 4; ++i) { + const double cx = 16 + gw * i + gw / 2; + const QRectF r(cx - gs / 2, 66, gs, gs); + 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); + p.setFont(pxFont(font(), 14, true)), p.setPen(muted); + p.drawText(r, Qt::AlignCenter, !live ? "—" : i == 3 && temp ? QString::number(vals[i], 'f', 0) + "°" : QString::number(vals[i], 'f', 0) + "%"); + p.setFont(pxFont(font(), 11)), p.setPen(C::muted), p.drawText(QRectF(cx - gw / 2, r.bottom() - 4, gw, 16), Qt::AlignCenter, names[i]); + } + const QRectF sp(16, 166, width() - 32, 44); // CPU + memory sparkline (last 5 min) + p.setPen(Qt::NoPen), p.setBrush(QColor(0, 0, 0, 40)), p.drawRoundedRect(sp, 8, 8); + for (auto [series, color] : {std::pair{Live::MEM, C::violet}, {Live::CPU, C::accent}}) { + const QVector &v = s->live().s[series]; + const int n = qMin(150, v.size()); + if (n < 2) continue; + QPolygonF line; + 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)); + QPolygonF area = line; + area << QPointF(line.last().x(), sp.bottom() - 2) << QPointF(line.first().x(), sp.bottom() - 2); + p.setPen(Qt::NoPen), p.setBrush(C::tint(color, 40)), p.drawPolygon(area); + p.setPen(QPen(color, 1.5)), p.setBrush(Qt::NoBrush), p.drawPolyline(line); + } + p.setFont(pxFont(font(), 10)), p.setPen(C::accent), p.drawText(sp.adjusted(8, 3, 0, 0), Qt::AlignLeft, "CPU"); + p.setPen(C::violet), p.drawText(sp.adjusted(36, 3, 0, 0), Qt::AlignLeft, "MEM"); + p.setFont(pxFont(font(), 11)); + const QRectF ft(16, 218, width() - 32, 32); + if (!live) { + p.setPen(s->status() == Status::Offline ? C::red : C::muted); + return p.drawText(ft, Qt::AlignVCenter | Qt::TextWordWrap, s->status() == Status::Disabled ? "Monitoring disabled" : s->status() == Status::Offline ? "Unreachable: " + s->lastError() : "Waiting for data…"); + } + p.setPen(C::teal), p.drawText(ft, Qt::AlignLeft, "↓ " + Fmt::rate(m.netRxBps)); + p.setPen(C::pink), p.drawText(ft.adjusted(100, 0, 0, 0), Qt::AlignLeft, "↑ " + Fmt::rate(m.netTxBps)); + 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))); + 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" : "")); + const int rules = s->activeAlerts().size(), alerts = rules + an.findings.size(); + if (!alerts) return; + bool crit = rules; + for (const Finding &f : an.findings) crit |= f.severity == "critical"; + const QString txt = QString("⚠ %1").arg(alerts); + const QColor ac = crit ? C::red : C::amber; + const QRectF ar(ft.right() - p.fontMetrics().horizontalAdvance(txt) - 14, ft.top() + 15, p.fontMetrics().horizontalAdvance(txt) + 14, 17); + p.setPen(Qt::NoPen), p.setBrush(C::tint(ac, 45)), p.drawRoundedRect(ar, 8, 8), p.setPen(ac), p.drawText(ar, Qt::AlignCenter, txt); + } +}; + +struct AddCard : Card { + const Actions *act; + explicit AddCard(const Actions *a) : act(a) {} + void mouseReleaseEvent(QMouseEvent *) override { act->add(); } + void paintEvent(QPaintEvent *) override + { + AA p(this); + const QRectF r = QRectF(rect()).adjusted(2, 2, -2, -2); + const QPointF c = r.center() - QPointF(0, 14); + 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); + p.setPen(QPen(hover ? C::accent : C::muted, 3, Qt::SolidLine, Qt::RoundCap)); + p.drawLine(c - QPointF(14, 0), c + QPointF(14, 0)), p.drawLine(c - QPointF(0, 14), c + QPointF(0, 14)); + p.setFont(pxFont(font(), 14, true)), p.drawText(QRectF(r.left(), c.y() + 26, r.width(), 22), Qt::AlignCenter, "Add server"); + 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"); + } +}; + +// ============================================================================ dashboard +struct DashboardPage : QWidget { + ServerManager *mgr; + const Actions *act; + FlowLayout *flow = new FlowLayout(new QWidget); + QList cards; + AddCard *addCard; + QLineEdit *search = new QLineEdit; + QLabel *subtitle = label({}, "Muted"); + QVector t; + QListWidget *events = new QListWidget; + + DashboardPage(ServerManager *m, const Actions *a) : mgr(m), act(a), addCard(new AddCard(a)) + { + auto *l = page(this); + auto *head = hbox(), *body = hbox(); + auto *titles = new QVBoxLayout; + auto *g = new QGridLayout; + auto *scroll = new QScrollArea; + auto *ev = panel("Recent events", {events}); + titles->addWidget(label("Dashboard", "H1")), titles->addWidget(subtitle); + search->setPlaceholderText("Search servers…"), search->setClearButtonEnabled(true), search->setFixedWidth(240); + head->addLayout(titles), head->addStretch(), head->addWidget(search), head->addWidget(button("+ Add server", "Primary", [this] { act->add(); })); + 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}}); + scroll->setWidgetResizable(true), scroll->setHorizontalScrollBarPolicy(Qt::ScrollBarAlwaysOff), scroll->setWidget(flow->parentWidget()); + events->setStyleSheet("QListWidget { background: transparent; border: none; } QListWidget::item { padding: 6px 2px; border-bottom: 1px solid #1f2738; }"); + events->setWordWrap(true), events->setSelectionMode(QAbstractItemView::NoSelection), ev->setFixedWidth(330); + body->addWidget(scroll, 1), body->addWidget(ev); + l->addLayout(head), l->addLayout(g), l->addLayout(body, 1); + connect(search, &QLineEdit::textChanged, this, [this] { filter(); }); + connect(mgr, &ServerManager::listChanged, this, [this] { rebuild(); }); + connect(mgr, &ServerManager::alertsCleared, events, &QListWidget::clear); + connect(mgr, &ServerManager::alertRaised, this, [this](const AlertEvent &e) { + events->insertItem(0, e.time.toString("HH:mm:ss") + " · " + e.serverName + "\n" + e.message); + events->item(0)->setForeground(C::severity(e.severity)); + if (events->count() > 200) delete events->takeItem(200); + }); + } + void rebuild() + { + for (ServerCard *c : qAsConst(cards)) c->hide(), c->deleteLater(); // not deleted at once: a card's own menu may have caused this + cards.clear(), flow->removeWidget(addCard); + for (ServerSession *s : mgr->sessions()) cards << new ServerCard(s, act), flow->addWidget(cards.last()); + flow->addWidget(addCard), filter(), refresh(); + } + void filter() + { + for (ServerCard *c : qAsConst(cards)) + 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)); + flow->invalidate(); + } + void refresh() + { + int online = 0, total = 0, problems = 0; + double cpu = 0, mem = 0, rx = 0, tx = 0, health = 0; + for (ServerSession *s : mgr->sessions()) { + if (!s->config().enabled) continue; + ++total, problems += s->activeAlerts().size(); + if (!s->online()) continue; + const Metrics &m = s->metrics(); + ++online, cpu += m.cpuUsage, mem += m.memPct, rx += m.netRxBps, tx += m.netTxBps, health += s->analysis().health; + for (const Finding &f : s->analysis().findings) problems += f.severity != "info"; + } + subtitle->setText(QString("%1 server(s) monitored · updated %2").arg(mgr->sessions().size()).arg(QTime::currentTime().toString("HH:mm:ss"))); + 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); + t[2]->set(QString::number(problems), problems ? "alerts + insights" : "all clear", problems ? C::red : C::green); + if (!online) { + for (int i : {1, 3, 4, 5}) t[i]->set("—"); + return; + } + t[1]->set(QString::number(qRound(health / online)), "score 0–100", C::health(qRound(health / online))); + t[3]->set(Fmt::pct(cpu / online), {}, C::level(cpu / online)), t[4]->set(Fmt::pct(mem / online), {}, C::level(mem / online)); + t[5]->set(Fmt::rate(rx + tx), "↓ " + Fmt::rate(rx) + " ↑ " + Fmt::rate(tx)); + } +}; + +// ============================================================================ detail page +struct DetailPage : QWidget { + ServerManager *mgr; + const Actions *act; + QPointer s; + QTabWidget *tabs = new QTabWidget; + QLabel *name = label({}, "H1"), *state = new QLabel, *sub = label({}, "Muted"), *chips = label({}, nullptr, true); + QPushButton *pause = button("❚❚ Pause", nullptr, [this] { s->setPaused(!s->isPaused()); }); + QComboBox *span = new QComboBox; + QList conns; + + DetailPage(ServerManager *m, const Actions *a) : mgr(m), act(a) + { + auto *l = page(this, 18); + auto *head = hbox(), *nameRow = hbox(); + auto *titles = new QVBoxLayout, *spanBox = new QVBoxLayout; + auto *power = button("⏻ Power", "Danger"); + auto *pm = new QMenu(power); + nameRow->addWidget(name), nameRow->addWidget(state), nameRow->addStretch(); + titles->addWidget(button("‹ Dashboard", "Flat", [this] { act->back(); }), 0, Qt::AlignLeft), titles->addLayout(nameRow), titles->addWidget(sub), titles->addWidget(chips); + 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); + span->setCurrentIndex(1), spanBox->addWidget(label("LIVE WINDOW", "Section")), spanBox->addWidget(span); + for (bool reboot : {true, false}) { + const QString t = reboot ? "Reboot…" : "Shut down…"; + pm->addAction(t, this, [this, t, reboot] { + 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); + }); + } + pm->addSeparator(), pm->addAction("Remove from monitor…", this, [this] { act->remove(s->config().id); }), power->setMenu(pm); + head->addLayout(titles, 1), head->addLayout(spanBox); + 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); + tabs->setDocumentMode(true), tabs->tabBar()->setElideMode(Qt::ElideNone), tabs->tabBar()->setExpanding(false); + tabs->tabBar()->setFont(pxFont(tabs->tabBar()->font(), 13, true)); + for (const auto &[title, w] : makeTabs()) w->save = [this](const ServerConfig &c) { mgr->update(c); }, tabs->addTab(w, title); + l->setSpacing(6), l->addLayout(head), l->addWidget(tabs, 1); + connect(tabs, &QTabWidget::currentChanged, this, [this] { refreshTab(true); }); + connect(span, QOverload::of(&QComboBox::currentIndexChanged), this, [this] { refreshTab(false); }); + } + Tab *tab(int i) const { return static_cast(tabs->widget(i)); } + void refreshTab(bool withAnalysis) + { + Tab *t = tab(tabs->currentIndex()); + if (!s) return; + t->span = span->currentData().toInt() * 60000LL, t->refresh(); + if (withAnalysis) t->analysis(); + } + void bind(ServerSession *x) + { + for (const auto &c : qAsConst(conns)) disconnect(c); + conns.clear(), s = x; + for (int i = 0; i < tabs->count(); ++i) tab(i)->bind(x); + if (!x) return; + conns << connect(x, &ServerSession::updated, this, [this] { header(), refreshTab(false); }) + << connect(x, &ServerSession::analysisUpdated, this, [this] { header(), tab(tabs->currentIndex())->analysis(); }); + header(), refreshTab(true); + } + void header() + { + const ServerConfig &c = s->config(); + const Metrics &m = s->metrics(); + const Analysis &a = s->analysis(); + QString h; + auto chip = [&](const QString &t, const QString &color = "#b9c3d8") { + if (!t.trimmed().isEmpty()) h += QString("  %1    ").arg(t.toHtmlEscaped().replace(" ", " ").replace("-", "‑"), color); + }; + name->setText(c.name); + state->setText(" ● " + (s->isPaused() ? QString("Paused") : statusName(s->status())).toUpper()); + state->setStyleSheet(QString("color: %1; font-weight: 700; font-size: 12px;").arg((s->isPaused() ? C::amber : statusColor(s->status())).name())); + sub->setText(c.address() + " · " + transportName(c.transport) + (m.hostname.isEmpty() ? "" : " · host " + m.hostname) + + (s->online() ? " · up " + Fmt::duration(m.uptime) : s->status() == Status::Offline ? " · " + s->lastError() : "")); + chip(m.os), chip(m.kernel.isEmpty() ? "" : P::kernelPrefix + m.kernel), chip(m.cpuCount ? QString("%1 cores").arg(m.cpuCount) : ""); + chip(m.memTotal > 0 ? Fmt::bytes(m.memTotal) + " RAM" : ""), chip(c.group, "#7dd3fc"); + if (s->online()) chip(QString("health %1 (%2)").arg(a.health).arg(a.grade), C::health(a.health).name()); + if (c.autopilot.enabled) chip(c.autopilot.dryRun ? "autopilot: dry run" : "autopilot: on", "#a78bfa"); + chips->setText(h), pause->setText(s->isPaused() ? "▶ Resume" : "❚❚ Pause"); + } +}; + +// ============================================================================ add / edit dialog +static bool editServer(QWidget *parent, ServerConfig &cfg, const QStringList &groups) +{ + QDialog dlg(parent); + dlg.setWindowTitle(cfg.name.isEmpty() ? "Add server" : "Edit server — " + cfg.name); + dlg.setMinimumWidth(620); + auto *l = new QVBoxLayout(&dlg); + l->setContentsMargins(24, 20, 24, 20), l->setSpacing(14); + l->addWidget(label(cfg.name.isEmpty() ? "Add a server" : "Edit server", "H2")); + auto *f = new QFormLayout; + 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); + auto *group = new QComboBox, *via = new QComboBox; + auto *port = new QSpinBox, *interval = new QSpinBox; + auto *sudo = new QCheckBox("Run control commands with sudo -n (needs passwordless sudo)"), *enabled = new QCheckBox("Monitoring enabled"); + auto *notes = new QPlainTextEdit(cfg.notes); + auto *browse = button("Browse…", nullptr, [&] { + const QString fn = QFileDialog::getOpenFileName(&dlg, "Private key", QDir::homePath() + "/.ssh"); + if (!fn.isEmpty()) key->setText(fn); + }); + auto *test = button("Test connection"); + auto *hint = label({}, "Muted", true), *result = label({}, nullptr, true); + group->setEditable(true), group->addItems(groups), group->setCurrentText(cfg.group); + via->addItems({"This machine (local)", "SSH — nothing to install on the server"}), via->setCurrentIndex(int(cfg.transport)); + port->setRange(1, 65535), port->setValue(cfg.port), port->setPrefix("port "); + interval->setRange(1, 300), interval->setValue(cfg.interval), interval->setSuffix(" s"); + pass->setEchoMode(QLineEdit::Password), sudo->setChecked(cfg.useSudo), enabled->setChecked(cfg.enabled), notes->setMaximumHeight(70); + name->setPlaceholderText("e.g. web-01"), host->setPlaceholderText("hostname or IP address"), user->setPlaceholderText("default: your local user name"); + key->setPlaceholderText("default keys / ssh-agent (~/.ssh/id_*)"), pass->setPlaceholderText("optional — keys are recommended"); + auto *addr = hbox(), *keyRow = hbox(), *testRow = hbox(); + addr->addWidget(host, 1), addr->addWidget(port), keyRow->addWidget(key, 1), keyRow->addWidget(browse), testRow->addWidget(test), testRow->addWidget(result, 1); + f->addRow("Name", name), f->addRow("Group", group), f->addRow("Connect via", via), f->addRow("Address", addr), f->addRow("User", user); + f->addRow("Private key", keyRow), f->addRow("Password", pass), f->addRow("Sample every", interval), f->addRow("", enabled), f->addRow("Notes", notes); + P::sudo ? f->insertRow(8, "", sudo) : (sudo->setParent(&dlg), sudo->hide()); + auto *bb = new QDialogButtonBox(QDialogButtonBox::Save | QDialogButtonBox::Cancel); + l->addLayout(f), l->addWidget(hint), l->addLayout(testRow), l->addWidget(bb); + auto collect = [&] { + ServerConfig c = cfg; + c.name = name->text().trimmed(), c.group = group->currentText().trimmed(), c.transport = Transport(via->currentIndex()); + c.host = c.transport == Transport::Local ? "" : host->text().trimmed(), c.port = port->value(), c.user = user->text().trimmed(); + c.keyFile = key->text().trimmed(), c.password = pass->text(), c.interval = interval->value(), c.useSudo = sudo->isChecked(); + c.enabled = enabled->isChecked(), c.notes = notes->toPlainText(); + return c; + }; + auto show = [&](const QString &text, const QColor &c) { result->setText(text), result->setStyleSheet("color: " + c.name() + ";"); }; + auto sync = [&] { + const bool ssh = via->currentIndex() == 1; + for (QWidget *w : std::initializer_list{host, port, user, key, browse, pass}) w->setEnabled(ssh); + hint->setText(ssh ? P::sshHint : "Monitors the computer this program runs on. No setup needed."); + if (!ssh && name->text().isEmpty()) name->setText("This computer"); + }; + QObject::connect(via, QOverload::of(&QComboBox::currentIndexChanged), &dlg, sync); + QObject::connect(bb, &QDialogButtonBox::rejected, &dlg, &QDialog::reject); + QObject::connect(bb, &QDialogButtonBox::accepted, &dlg, [&] { + const ServerConfig c = collect(); + if (c.name.isEmpty() || (c.transport == Transport::SSH && c.host.isEmpty())) return show("Please enter a name and an address.", C::red); + dlg.accept(); + }); + QPointer link; + QObject::connect(test, &QPushButton::clicked, &dlg, [&] { // two frames prove that data and rates work + ServerConfig c = collect(); + c.interval = 1; + delete link; + link = new Link(c, &dlg); + auto engine = std::make_shared(); + auto clock = std::make_shared(); + auto frames = std::make_shared(0); + clock->start(), test->setEnabled(false), show("Connecting…", C::amber); + auto finish = [&, l = link.data()](const QString &msg, const QColor &col) { show(msg, col), test->setEnabled(true), l->disconnect(), l->deleteLater(); }; + QObject::connect(link, &Link::snapshot, &dlg, [=](const QByteArray &raw) { + const Metrics m = engine->process(raw, QDateTime::currentMSecsSinceEpoch()); + if (++*frames == 2) + 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); + }); + QObject::connect(link, &Link::disconnected, &dlg, [=](const QString &why) { finish("✗ " + why, C::red); }); + QTimer::singleShot(20000, link, [=] { finish("✗ Timed out after 20 s", C::red); }); + link->start(); + }); + sync(); + if (dlg.exec() != QDialog::Accepted) return false; + cfg = collect(); + return true; +} + +// ============================================================================ main window +struct MainWindow::Ui { + ServerManager *mgr; + Actions act; + QStackedWidget *stack = new QStackedWidget; + DashboardPage *dash = new DashboardPage(mgr, &act); + DetailPage *detail = new DetailPage(mgr, &act); + QWidget *eventsPage = new QWidget; + QTableWidget *events = table({"Time", "Server", "Type", "Message"}, {170, 180, 100}); + QComboBox *eventFilter = new QComboBox; + QListWidget *list = new QListWidget; + QPushButton *navDash = button("▦ Dashboard", "Nav"), *navEvents = button("◉ Events && alerts", "Nav"); + QLabel *badge = new QLabel; + QSystemTrayIcon *tray = nullptr; + int unseen = 0; + bool quitting = false; +}; + +struct ServerItemDelegate : QStyledItemDelegate { // sidebar row: dot, name, alert count, mini CPU/MEM bars + ServerManager *mgr; + ServerItemDelegate(ServerManager *m, QObject *parent) : QStyledItemDelegate(parent), mgr(m) {} + QSize sizeHint(const QStyleOptionViewItem &, const QModelIndex &) const override { return {220, 58}; } + void paint(QPainter *p, const QStyleOptionViewItem &o, const QModelIndex &i) const override + { + ServerSession *s = mgr->session(i.data(Qt::UserRole).toString()); + if (!s) return; + const QRectF r = QRectF(o.rect).adjusted(6, 2, -6, -2); + const Metrics &m = s->metrics(); + int y = int(r.top()) + 34; + p->save(); + p->setRenderHint(QPainter::Antialiasing), p->setPen(Qt::NoPen); + 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); + p->setBrush(statusColor(s->status())), p->drawEllipse(QPointF(r.left() + 14, r.top() + 18), 4.5, 4.5); + p->setFont(pxFont(o.font, 13, true)), p->setPen(C::text); + 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))); + if (const int n = s->activeAlerts().size()) { + const QRectF b(r.right() - 26, r.top() + 10, 20, 16); + 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)); + } + for (auto [lbl, v] : {std::pair{"CPU", m.cpuUsage}, {"MEM", m.memPct}}) { + const QRectF track(r.left() + 56, y - 2, r.width() - 70, 4); + p->setFont(pxFont(o.font, 9)), p->setPen(C::faint), p->drawText(QRectF(r.left() + 26, y - 5, 30, 10), Qt::AlignVCenter, lbl); + p->setPen(Qt::NoPen), p->setBrush(C::grid), p->drawRoundedRect(track, 2, 2); + 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); + y += 11; + } + p->restore(); + } +}; + +MainWindow::MainWindow(ServerManager *mgr) : ui(new Ui{mgr}) +{ + setWindowTitle("Server Monitor"), setWindowIcon(C::appIcon()), resize(1500, 940), setMinimumSize(1100, 700); + + // navigation and server actions + auto nav = [this](QWidget *pageW) { + ui->stack->setCurrentWidget(pageW); + ui->navDash->setChecked(pageW == ui->dash), ui->navEvents->setChecked(pageW == ui->eventsPage); + if (pageW != ui->detail) ui->list->clearSelection(); + }; + auto refreshEvents = [this] { + QVector rs; + for (const AlertEvent &e : ui->mgr->alerts()) + if (!ui->eventFilter->currentIndex() || e.severity == ui->eventFilter->currentText()) rs << e; + fillRows(ui->events, rs, [](const AlertEvent &e) { + return Row{{e.time.toString("yyyy-MM-dd HH:mm:ss"), C::muted}, {e.serverName}, {e.severity.toUpper(), C::severity(e.severity)}, {e.message}}; + }); + }; + auto showDash = [=] { nav(ui->dash), ui->dash->refresh(); }; + auto showEvents = [=] { nav(ui->eventsPage), ui->unseen = 0, ui->badge->hide(), refreshEvents(); }; + auto showServer = [=](const QString &id) { + if (!mgr->session(id)) return; + ui->detail->bind(mgr->session(id)), nav(ui->detail); + for (int i = 0; i < ui->list->count(); ++i) + if (ui->list->item(i)->data(Qt::UserRole) == id) ui->list->setCurrentRow(i); + }; + auto groups = [mgr] { + QStringList g; + for (ServerSession *s : mgr->sessions()) + if (!s->config().group.isEmpty() && !g.contains(s->config().group)) g << s->config().group; + return g; + }; + auto addServer = [=] { + ServerConfig c; + c.id = ServerConfig::newId(); + if (editServer(this, c, groups())) showServer(mgr->add(c)->config().id); + }; + auto editSrv = [=](const QString &id) { + ServerConfig c = mgr->session(id) ? mgr->session(id)->config() : ServerConfig(); + if (mgr->session(id) && editServer(this, c, groups())) mgr->update(c); + }; + auto removeSrv = [=](const QString &id) { + ServerSession *s = mgr->session(id); + if (!s) return; + QMessageBox box(QMessageBox::Warning, "Remove server", QString("Stop monitoring \"%1\" and remove it from the list?").arg(s->config().name), QMessageBox::Cancel, this); + auto *withHist = box.addButton("Remove + delete history", QMessageBox::DestructiveRole), *keep = box.addButton("Remove, keep history files", QMessageBox::AcceptRole); + box.exec(); + if (box.clickedButton() != withHist && box.clickedButton() != keep) return; + if (ui->detail->s == s) ui->detail->bind(nullptr), showDash(); + mgr->remove(id, box.clickedButton() == withHist); + }; + auto selectedId = [this] { return ui->list->currentItem() ? ui->list->currentItem()->data(Qt::UserRole).toString() : QString(); }; + ui->act = {showServer, editSrv, removeSrv, addServer, showDash}; + + // sidebar + auto *central = new QWidget, *side = new QWidget; + auto *h = new QHBoxLayout(central); + auto *sl = new QVBoxLayout(side), *bt = new QVBoxLayout; + auto *brand = hbox(), *evRow = hbox(), *btns = hbox(); + auto *logo = new QLabel, *title = label("Server Monitor"); + h->setContentsMargins(0, 0, 0, 0), h->setSpacing(0), h->addWidget(side), h->addWidget(ui->stack, 1); + setCentralWidget(central); + side->setObjectName("Sidebar"), side->setFixedWidth(260); + logo->setPixmap(C::appIcon().pixmap(34, 34)), title->setStyleSheet("font-size: 16px; font-weight: 800;"); + bt->setSpacing(0), bt->addWidget(title), bt->addWidget(label("monitor · analyze · control", "Muted")); + brand->addWidget(logo), brand->addLayout(bt, 1); + ui->badge->setStyleSheet("background: #ef4444; color: white; border-radius: 9px; padding: 1px 7px; font-size: 11px; font-weight: 700;"), ui->badge->hide(); + evRow->addWidget(ui->navEvents, 1), evRow->addWidget(ui->badge); + ui->navDash->setCheckable(true), ui->navEvents->setCheckable(true); + ui->list->setStyleSheet("QListWidget { background: transparent; border: none; }"); + ui->list->setItemDelegate(new ServerItemDelegate(mgr, ui->list)), ui->list->setMouseTracking(true), ui->list->setContextMenuPolicy(Qt::CustomContextMenu); + btns->setSpacing(6), btns->addWidget(button("+ Add", "Primary", addServer), 1); + btns->addWidget(button("Edit", nullptr, [=] { editSrv(selectedId()); }), 1), btns->addWidget(button("Remove", "Danger", [=] { removeSrv(selectedId()); }), 1); + sl->setContentsMargins(12, 18, 12, 14), sl->setSpacing(6); + sl->addLayout(brand), sl->addSpacing(14), sl->addWidget(ui->navDash), sl->addLayout(evRow), sl->addSpacing(12); + sl->addWidget(label(" SERVERS", "Section")), sl->addWidget(ui->list, 1), sl->addLayout(btns); + + // events page + auto *el = page(ui->eventsPage); + auto *eh = hbox(); + auto *et = new QVBoxLayout; + et->addWidget(label("Events & alerts", "H1")); + et->addWidget(label("Alerts, recoveries, insights and every automatic or manual action, newest first. Also written to alerts.log.", "Muted")); + ui->eventFilter->addItems({"All events", "critical", "warning", "info", "resolved", "action"}); + eh->addLayout(et, 1), eh->addWidget(ui->eventFilter); + eh->addWidget(button("Open log folder", nullptr, [] { QDesktopServices::openUrl(QUrl::fromLocalFile(ServerManager::configDir())); })); + eh->addWidget(button("Clear list", nullptr, [mgr] { mgr->clearAlerts(); })); + el->addLayout(eh), el->addWidget(ui->events, 1); + for (QWidget *w : std::initializer_list{ui->dash, ui->detail, ui->eventsPage}) ui->stack->addWidget(w); + + connect(ui->navDash, &QPushButton::clicked, this, showDash); + connect(ui->navEvents, &QPushButton::clicked, this, showEvents); + connect(ui->list, &QListWidget::itemClicked, this, [=](QListWidgetItem *it) { showServer(it->data(Qt::UserRole).toString()); }); + connect(ui->list, &QWidget::customContextMenuRequested, this, [=](const QPoint &pos) { + QListWidgetItem *it = ui->list->itemAt(pos); + if (!it) return; + const QString id = it->data(Qt::UserRole).toString(); + QMenu m; + m.addAction("Open", [=] { showServer(id); }), m.addAction("Reconnect", [=] { mgr->session(id)->reconnect(); }), m.addSeparator(); + m.addAction("Move up", [=] { mgr->move(id, -1); }), m.addAction("Move down", [=] { mgr->move(id, 1); }), m.addSeparator(); + m.addAction("Edit…", [=] { editSrv(id); }), m.addAction("Remove…", [=] { removeSrv(id); }); + m.exec(ui->list->viewport()->mapToGlobal(pos)); + }); + connect(ui->eventFilter, QOverload::of(&QComboBox::currentIndexChanged), this, refreshEvents); + connect(mgr, &ServerManager::alertsCleared, this, refreshEvents); + connect(mgr, &ServerManager::listChanged, this, [=] { + const QString cur = selectedId(); + ui->list->clear(); + for (ServerSession *s : mgr->sessions()) { + auto *it = new QListWidgetItem(s->config().name, ui->list); + it->setData(Qt::UserRole, s->config().id); + if (s->config().id == cur) ui->list->setCurrentItem(it); + } + }); + connect(mgr, &ServerManager::alertRaised, this, [=](const AlertEvent &e) { + const bool important = e.severity == "critical" || e.severity == "warning" || e.severity == "action"; + if (ui->stack->currentWidget() == ui->eventsPage) refreshEvents(); + else if (important) ui->badge->setText(QString::number(++ui->unseen)), ui->badge->show(); + if (ui->tray && important && QSettings().value("notify", true).toBool()) + ui->tray->showMessage(e.serverName + " — " + e.severity, e.message, e.severity == "critical" ? QSystemTrayIcon::Critical : e.severity == "warning" ? QSystemTrayIcon::Warning : QSystemTrayIcon::Information, 8000); + }); + auto *tick = new QTimer(this); // sidebar bars + dashboard tiles + connect(tick, &QTimer::timeout, this, [this] { + ui->list->viewport()->update(); + if (ui->stack->currentWidget() == ui->dash) ui->dash->refresh(); + }); + tick->start(1000); + + if (QSystemTrayIcon::isSystemTrayAvailable()) { + ui->tray = new QSystemTrayIcon(C::appIcon(), this); + auto *menu = new QMenu(this); + menu->addAction("Show window", this, [this] { showNormal(), raise(), activateWindow(); }); + for (auto [text, key] : {std::pair{"Desktop notifications", "notify"}, {"Keep running in tray when closed", "closeToTray"}}) { + QAction *a = menu->addAction(text); + a->setCheckable(true), a->setChecked(QSettings().value(key, true).toBool()); + connect(a, &QAction::toggled, [k = QString(key)](bool on) { QSettings().setValue(k, on); }); + } + menu->addSeparator(), menu->addAction("Quit", this, [this] { ui->quitting = true, qApp->quit(); }); + ui->tray->setContextMenu(menu), ui->tray->setToolTip("Server Monitor"), ui->tray->show(); + connect(ui->tray, &QSystemTrayIcon::activated, this, [this](QSystemTrayIcon::ActivationReason r) { + if (r == QSystemTrayIcon::Trigger) isVisible() && !isMinimized() ? hide() : (showNormal(), raise(), activateWindow()); + }); + } + restoreGeometry(QSettings().value("geometry").toByteArray()); + showDash(); +} + +void MainWindow::closeEvent(QCloseEvent *e) +{ + QSettings st; + st.setValue("geometry", saveGeometry()); + if (ui->quitting || !ui->tray || !st.value("closeToTray", true).toBool()) return qApp->quit(); + hide(), e->ignore(); + 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); +} + +void MainWindow::saveSnapshots(const QString &dir) +{ + auto settle = [] { QEventLoop loop; QTimer::singleShot(700, &loop, &QEventLoop::quit), loop.exec(); }; // let animations finish + QTabWidget *tabs = ui->detail->tabs; + grab().save(dir + "/00-dashboard.png"); + if (ui->mgr->sessions().isEmpty()) return; + ui->act.open(ui->mgr->sessions()[0]->config().id); + for (int i = 0; i < tabs->count(); ++i) + 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())); + ui->navEvents->click(), settle(), grab().save(dir + "/99-events.png"); +} diff --git a/Server Monitor(cqt-window)/src/ui/Windows.h b/Server Monitor(cqt-window)/src/ui/Windows.h new file mode 100644 index 0000000000000000000000000000000000000000..71bc26fbd4c8a818eb3631f899c05804d62a840e --- /dev/null +++ b/Server Monitor(cqt-window)/src/ui/Windows.h @@ -0,0 +1,22 @@ +// Detail-page tab interface and the main window (sidebar, dashboard, server page, events, tray). +#pragma once +#include "core/Session.h" +#include + +struct Tab : QWidget { // one aspect of the bound server session + QPointer s; + qint64 span = 15 * 60000; // live chart window + std::function save; // persists config edits + virtual void bind(ServerSession *x) { s = x; } + virtual void refresh() {} // new sample (only while visible) + virtual void analysis() {} // analyzer ran +}; +QVector> makeTabs(); + +struct MainWindow : QMainWindow { + explicit MainWindow(ServerManager *mgr); + void saveSnapshots(const QString &dir); // developer aid: PNG of every page + void closeEvent(QCloseEvent *e) override; + struct Ui; + Ui *ui; +}; diff --git a/Server Monitor(python-linux)/README.md b/Server Monitor(python-linux)/README.md new file mode 100644 index 0000000000000000000000000000000000000000..da38c6addfd27f105971e77e0ebffa7bb5a4e34d --- /dev/null +++ b/Server Monitor(python-linux)/README.md @@ -0,0 +1,58 @@ +# Server Monitor (Python, Linux) + +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. + +## Requirements + +- Linux, Python 3.8 or newer with tkinter (`sudo apt install python3-tk` on Debian/Ubuntu). No pip packages. +- The system `ssh` client, only for remote servers. + +## Run + +```bash +./run.sh # or: python3 main.py +``` + +The first start adds "This computer". Closing the window ends the program (there is no tray icon). + +## How it connects + +- **This machine:** no setup. A small POSIX `sh` script (embedded in `plat.py`) reads `/proc` and `/sys`. +- **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. + +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). + +## Features + +- **Dashboard:** a live card per server (gauges, sparkline, health grade), totals, recent events, search. +- **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. +- **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. +- **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. +- **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. +- **Alert rules:** "CPU > 90 % for 60 s → warning → restart a service"; events go to the Events page and to `alerts.log`. + +## Data + +Everything is stored in `~/.config/ServerMonitorPy` (or `$XDG_CONFIG_HOME/ServerMonitorPy`): + +- `servers.json` (mode 600): servers, rules and autopilot settings. Saved SSH passwords are only lightly disguised, not encrypted, so prefer keys. +- `history//{raw,minute,hour,day}.bin`: the history tiers. +- `alerts.log`: every alert and action. + +The file formats are the same as in the other Server Monitor editions, so files can be copied between them. + +## Code + +``` +main.py entry point +plat.py everything Linux-specific: collector script, spawning, frame parser, command tables +metrics.py one parsed sample + helpers shared by the platform parsers +model.py configuration, rules, formatting +history.py history store + analyzer +session.py ssh/local link, per-server session (rules, autopilot), manager +widgets.py theme, hand-drawn widgets, small UI builders +tabs.py server detail tabs +ui.py dashboard, detail page, add/edit dialog, main window +``` + +Only `plat.py` differs from the Windows edition. diff --git a/Server Monitor(python-linux)/history.py b/Server Monitor(python-linux)/history.py new file mode 100644 index 0000000000000000000000000000000000000000..9e456306b0657c3054ab8875b521e1158918927f --- /dev/null +++ b/Server Monitor(python-linux)/history.py @@ -0,0 +1,331 @@ +"""Persistent multi-resolution history (raw 6 h, minute 30 d, hour 2 y, day 20 y) +and the statistics-only analyzer that feeds the autopilot.""" +import math, os, struct, time +from array import array +from bisect import bisect_left, bisect_right +from collections import namedtuple + +import plat +from model import duration, fmt_bytes, pct, rate, rnd, temp + +KEYS = 'cpu iowait load mem swap disk diskio rx tx rd wr temp procs gpu failed'.split() +NAMES = ['CPU', 'I/O wait', 'Load (1m)', 'Memory', 'Swap', 'Disk usage', 'Disk busy', 'Net download', 'Net upload', 'Disk read', + 'Disk write', 'Temperature', 'Processes', 'GPU', 'Failed services'] +CPU, IOWAIT, LOAD, MEM, SWAP, DISK, DISKIO, RX, TX, RD, WR, TEMP, PROCS, GPU, FAILED = range(15) +H_COUNT, NAN = len(KEYS), math.nan +TIERS, TIER_NAMES = ('raw', 'minute', 'hour', 'day'), ('every sample', '1 minute', '1 hour', '1 day') +STEP, KEEP, MAX_SPAN = (1, 60, 3600, 86400), (6 * 3600, 30 * 86400, 732 * 86400, 7320 * 86400), (6 * 3600, 8 * 86400, 400 * 86400) +REC = struct.Struct(' self.max[i]: self.max[i] = mx + def row(self): # through the record format, so the values are float32 like the stored ones + 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)) + +class Store: + def __init__(self, path): + self.dir, self.tz, self.appends = path, time.localtime().tm_gmtoff, [0] * 4 + os.makedirs(path, exist_ok=True) + now = int(time.time()) + self.tiers, self.acc = [Points() for _ in TIERS], [Acc() for _ in TIERS] + for t in range(4): self.load(t, now) + 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 + finer, stored = self.tiers[t - 1], self.tiers[t].ts[-1] if len(self.tiers[t]) else -1 + for r in [*finer.cut(bisect_right(finer.ts, stored)).rows(), *([self.acc[t - 1].row()] if self.acc[t - 1].n else [])]: + b, a = self.bucket(t, r[0]), self.acc[t] + if b <= stored: continue + if b != a.bucket: + if a.n: self.append(t, a.row()) + a = self.acc[t] = Acc(b) + a.add(r) + def file(self, t): return os.path.join(self.dir, TIERS[t] + '.bin') + 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 + def load(self, t, now): + try: + with open(self.file(t), 'rb') as f: data = f.read() + except OSError: + return + if not data.startswith(HEADER): return os.replace(self.file(t), self.file(t) + '.old') + rows, last = [], -1 + for r in REC.iter_unpack(data[len(HEADER):len(data) - (len(data) - len(HEADER)) % REC.size]): + if now - KEEP[t] <= r[0] <= now + 86400 and r[0] > last: + rows.append(r) + last = r[0] + self.tiers[t] = Points(rows) + if len(HEADER) + len(rows) * REC.size != len(data): # expired or damaged records, or a cut-off one that would misalign what is appended + self.rewrite(t) + def rewrite(self, t): + try: + with open(self.file(t) + '.tmp', 'wb') as f: f.write(HEADER + b''.join(REC.pack(*r) for r in self.tiers[t].rows())) + os.replace(self.file(t) + '.tmp', self.file(t)) + except OSError: + pass # history stays in memory when the disk is full or read-only + def append(self, t, row): + p = self.tiers[t] + if len(p) and row[0] <= p.ts[-1]: return + p.add(row) + try: + with open(self.file(t), 'ab') as f: + if f.tell() < len(HEADER): + f.truncate(0) + f.write(HEADER) + f.write(REC.pack(*row)) + except OSError: + pass + self.appends[t] += 1 + if self.appends[t] % 500 == 0: # trim expired points now and then + k = bisect_left(p.ts, row[0] - KEEP[t]) + if k: + self.tiers[t] = p.cut(k) + self.rewrite(t) + def add(self, ts, values, up): + """Records one sample; up=False records downtime only.""" + v = values if up else [NAN] * H_COUNT + raw = REC.unpack(REC.pack(ts, 1, int(up), *v, *v)) + self.append(0, raw) + for t in (1, 2, 3): # every coarser tier accumulates every raw sample + b, a = self.bucket(t, ts), self.acc[t] + if a.bucket != b: + if a.n and a.bucket < b: self.append(t, a.row()) + a = self.acc[t] = Acc(b) + a.add(raw) + def range(self, frm, to, t): + """Points of tier t in [frm, to], including the open bucket.""" + p, a = self.tiers[t], self.acc[t] + out = p.cut(bisect_left(p.ts, frm), bisect_right(p.ts, to)) + if t and a.n and frm <= a.bucket <= to and (not len(out) or out.ts[-1] < a.bucket): out.add(a.row()) + return out + def span(self, frm, to): + """(points, tier) from the finest tier that covers the range.""" + now, t = int(time.time()), 0 + while t < 3 and (frm < now - KEEP[t] or to - frm > MAX_SPAN[t]): t += 1 + return self.range(frm, to, t), t + def first_ts(self): return min((p.ts[0] for p in self.tiers if len(p)), default=0) + def disk_bytes(self): return sum(os.path.getsize(self.file(t)) for t in range(4) if os.path.exists(self.file(t))) + +Stats = namedtuple('Stats', 'min avg p95 max count', defaults=(NAN, NAN, NAN, NAN, 0)) # max = peak of max[] + +def stats(p, m): + v = [(a, x, u) for a, x, u in zip(p.avg[m], p.max[m], p.up) if u and a == a] + if not v: return Stats() + a = sorted(r[0] for r in v) + 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)) + +def regression(p, m): + """Least-squares (slope per second, squared correlation) of a metric over time.""" + xy = [(t - p.ts[0], y) for t, y, u in zip(p.ts, p.avg[m], p.up) if u and y == y] + n, sx, sy = len(xy), sum(x for x, _ in xy), sum(y for _, y in xy) + 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 + if n < 3 or den <= 0: return 0.0, 0.0 + return num / den, num * num / (den * vy) if vy > 1e-9 else 0.0 + +def slot(ts): + """(weekday, hour) of a timestamp in local time; Monday = 0.""" + t = time.localtime(ts) + return t.tm_wday, t.tm_hour + +def fmt_metric(m, v): + if v != v: return '—' + 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) + +# ---- analysis ------------------------------------------------------------------- +# action: disk_cleanup | restart_service | renice | kill_pid +Finding = namedtuple('Finding', 'key severity category title detail advice action arg label auto') +ProcTrend = namedtuple('ProcTrend', 'pid minutes name user cpu_now high_cpu_minutes rss_now rss_growth rss_growth_pct rss_monotonic protected', + defaults=(0, 0, '', '', 0, 0, 0, 0, 0, 0, False)) +ServiceTrend = namedtuple('ServiceTrend', 'unit failed_now preexisting fails_last_hour auto_restarts_last_hour') +Anomaly = namedtuple('Anomaly', 'metric baseline hm now mean sd z') + +class Analysis: + def __init__(self): + self.when, self.health, self.grade, self.disk_basis = 0, 100, 'A', '' + self.reasons, self.capacity, self.findings, self.anomalies = [], [], [], [] + self.disk_full_days, self.disk_slope_per_day, self.mem_slope_per_hour, self.mem_trend_r2 = -1, 0, 0, 0 + self.up, self.down, self.cpu30, self.mem30 = [NAN] * 3, [0] * 3, Stats(), Stats() # 24 h, 7 d, 30 d: availability %, seconds offline + self.heat = [[[NAN] * 24 for _ in range(7)] for _ in range(2)] # weekly pattern: 0 = CPU, 1 = memory + self.heat_n = [[0] * 24 for _ in range(7)] + +def analyze(st, m, ap, procs, svcs, online): + a = Analysis() + now = a.when = int(time.time()) + minute, hour, cores = st.tiers[1], st.tiers[2], max(1, m.cpu_count) + + def add(key, sev, cat, title, detail, advice, action='', arg='', label='', auto=False): + a.findings.append(Finding(key, sev, cat, title, detail, advice, action, arg, label, bool(auto))) + + def sev(crit, warn): return 'critical' if crit else 'warning' if warn else 'info' + + # availability + spans = (86400, 7 * 86400, 30 * 86400) + for i, span in enumerate(spans): + p = st.span(now - span, now)[0] + n, up = sum(p.n), sum(p.up) + 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 + if a.up[0] < 99: + add('avail24', sev(a.up[0] < 95, True), 'Availability', f'Availability last 24 h is {pct(a.up[0], 2)}', + f'The server could not be reached for about {duration(a.down[0])} in the last day.', + 'Check network stability, power and whether the machine rebooted (uptime).') + w30, w7 = st.range(now - spans[2], now, 2), st.range(now - spans[1], now, 1) + a.cpu30, a.mem30 = (stats(w30 if len(w30) >= 24 else w7, k) for k in (CPU, MEM)) + + # disk forecast: regression over 7 d of hours, or 24 h of minutes, whichever fits better + slope = r2 = 0.0 + week, day = st.range(now - spans[1], now, 2), st.range(now - 86400, now, 1) + if len(week) >= 48: (slope, r2), a.disk_basis = regression(week, DISK), 'hourly averages, last 7 days' + if len(day) >= 120: + s2, r2b = regression(day, DISK) + if len(week) < 48 or r2b > r2: slope, r2, a.disk_basis = s2, r2b, 'minute averages, last 24 hours' + a.disk_slope_per_day = slope * 86400 + 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 + if 0 <= a.disk_full_days < 30: + add('diskfull', sev(a.disk_full_days < ap.diskForecastDays, a.disk_full_days < 14), 'Disk', + f'Disk {m.fullest_mount} will be full in {duration(a.disk_full_days * 86400)}', + 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}).', + 'Clean logs/caches, rotate or move data, or grow the volume.', 'disk_cleanup', '', 'Run cleanup', + ap.diskCleanup and a.disk_full_days < ap.diskForecastDays) + if m.max_disk_pct >= ap.diskCleanupAt: + add('diskhigh', sev(m.max_disk_pct >= 97, True), 'Disk', f'Disk {m.fullest_mount} is {pct(m.max_disk_pct)} full', + f'Above the cleanup threshold of {pct(ap.diskCleanupAt, 0)}.', 'Free space soon: services fail when the disk is full.', + 'disk_cleanup', '', 'Run cleanup', ap.diskCleanup) + + # whole-machine memory trend over 6 h + six = st.range(now - 6 * 3600, now, 1) + if len(six) >= 90: + slope, a.mem_trend_r2 = regression(six, MEM) + a.mem_slope_per_hour = slope * 3600 + left = (100 - m.mem_pct) / max(0.01, a.mem_slope_per_hour) + if a.mem_slope_per_hour > 1 and a.mem_trend_r2 > 0.8 and m.mem_pct > 40: + add('memtrend', sev(False, left < 12), 'Memory', f'Memory keeps growing (+{a.mem_slope_per_hour:.1f} points/hour)', + f'Steady growth over 6 h (R² {a.mem_trend_r2:.2f}). At this rate memory is exhausted in about {duration(left * 3600)}.', + 'Look for a leaking process (Processes tab, sort by RSS).') + + # processes: leaks and runaways + for p in procs: + if p.protected: continue + who = f'{p.name} (PID {p.pid})' + if p.minutes >= 30 and p.rss_growth_pct >= 25 and p.rss_growth >= 100e6 and p.rss_monotonic >= 0.8: + add(f'leak:{p.pid}', sev(m.mem_pct >= ap.leakMemPressure, True), 'Process', 'Possible memory leak: ' + who, + f'RSS grew {fmt_bytes(p.rss_growth)} (+{pct(p.rss_growth_pct, 0)}) in {p.minutes} min and rose in ' + f'{rnd(p.rss_monotonic * 100)}% of the minutes; now {fmt_bytes(p.rss_now)}.', + 'Restart the program/service at a quiet time and report the leak upstream.', 'kill_pid', str(p.pid), 'Terminate', + ap.leakMode == 'terminate' and m.mem_pct >= ap.leakMemPressure) + if p.high_cpu_minutes >= ap.runawayMinutes: + term = ap.runawayMode == 'terminate' + add(f'runaway:{p.pid}', 'warning', 'Process', 'Runaway process: ' + who, + f'Above {pct(ap.runawayCpu, 0)} CPU for {rnd(p.high_cpu_minutes)} min (now {pct(p.cpu_now)}, user {p.user}).', + plat.TEXT['renice_advice'], 'kill_pid' if term else 'renice', str(p.pid), 'Terminate' if term else plat.TEXT['renice'], + ap.runawayMode != 'none') + + # services: failures and flapping + for s in svcs: + flap = s.fails_last_hour >= 3 or s.auto_restarts_last_hour >= ap.maxRestartsPerHour + if s.failed_now: + add('svc:' + s.unit, sev(flap, True), 'Service', f'Service {s.unit} ' + ('keeps failing' if flap else 'has failed'), + 'It was already failed when monitoring started, so the autopilot leaves it alone (it may be failed on purpose).' if s.preexisting + else f'Failed {s.fails_last_hour}× in the last hour; autopilot restarted it {s.auto_restarts_last_hour}×.', + 'Automatic restarts were stopped. Read the logs (Services tab → Logs) and fix the cause.' if flap else 'Restart it and check the logs.', + 'restart_service', s.unit, 'Restart', ap.restartFailed and not s.preexisting and s.auto_restarts_last_hour < ap.maxRestartsPerHour) + elif s.fails_last_hour >= 3: + add('flap:' + s.unit, 'warning', 'Service', f'Service {s.unit} is unstable', + f'It failed {s.fails_last_hour} times within the last hour.', 'Inspect its logs and resource limits.') + + # overload and swap thrashing + last15 = st.range(now - 900, now, 1) + load15, io15, cpu15, busy15 = (stats(last15, k).avg for k in (LOAD, IOWAIT, CPU, DISKIO)) + if online and load15 / cores > 1.5: + add('load', sev(load15 / cores > 3, True), 'CPU', f'CPU is overloaded (load {load15:.1f} on {cores} cores)', + f'15-minute average load is {load15 / cores:.1f}× the number of cores; tasks are waiting for CPU.', + 'Find the busiest processes, spread work over time, or add CPU.') + thrash = plat.thrashing(io15, m.mem_pct, busy15) + if online and m.swap_pct > 50 and thrash: + add('thrash', 'critical', 'Memory', 'Swap thrashing', f'Swap {pct(m.swap_pct)} used{thrash}.', 'Stop memory-hungry processes or add RAM.') + + # anomalies: last 10 min vs same weekday+hour over 8 weeks (fallback: last 24 h) + raw = st.range(now - 600, now, 0) + 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)] + recent = range(bisect_left(minute.ts, now - 86400), bisect_left(minute.ts, now - 900)) + checks = [(CPU, 5.0, False), (MEM, 3.0, False), (LOAD, 0.25 * cores, False), (IOWAIT, 3.0, False), (RX, 256e3, True), (TX, 256e3, True)] + for hm, floor, down in checks if online and len(raw) >= 10 else (): # (metric, smallest deviation unit, alert on drops) + if hm == IOWAIT and not plat.POSIX_CPU: continue + cur, basis = stats(raw, hm).avg, 'same weekday & hour, last 8 weeks' + v = [hour.avg[hm][i] for i in same if hour.up[i] and hour.avg[hm][i] == hour.avg[hm][i]] + if len(v) < 3: + 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' + if len(v) < 360: continue + mean = sum(v) / len(v) + sd = math.sqrt(sum((x - mean) ** 2 for x in v) / len(v)) + z = (cur - mean) / max(sd, floor) + a.anomalies.append(Anomaly(NAMES[hm], basis, hm, cur, mean, sd, z)) + hi, lo = z >= ap.anomalyZ, down and mean > 1e6 and cur < mean * 0.1 + if ap.anomalyAlerts and (hi or lo): + add('anomaly:' + KEYS[hm], sev(False, z >= ap.anomalyZ * 2), 'Anomaly', f'Unusually {"high" if hi else "low"} {NAMES[hm].lower()}', + f'Last 10 min {fmt_metric(hm, cur)}, usually {fmt_metric(hm, mean)} ± {fmt_metric(hm, sd)} ({basis}); {z:.1f}σ.', + 'Check what changed: deploys, cron jobs, traffic, attacks.' if hi else 'Traffic dropped sharply - check the service is still serving.') + + # weekly heatmaps from 4 weeks of hours + total = [[[0.0] * 24 for _ in range(7)] for _ in range(2)] + for i in range(bisect_left(hour.ts, now - 28 * 86400), len(hour)): + cpu, mem = hour.avg[CPU][i], hour.avg[MEM][i] + if not hour.up[i] or cpu != cpu: continue + d, h = slot(hour.ts[i]) + a.heat_n[d][h] += 1 + for k, v in enumerate((cpu, mem if mem == mem else 0)): + total[k][d][h] += v + a.heat[k][d][h] = total[k][d][h] / a.heat_n[d][h] + + # capacity advice + 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'), + (a.mem30, 'Memory', 30, 85, 'is under-used', 'is tight - add RAM or reduce caches/limits')): + 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)}).') + if a.disk_full_days >= 0: + a.capacity.append(f'Disk grows {a.disk_slope_per_day:.2f} points/day - full in about {duration(a.disk_full_days * 86400)}.') + elif a.disk_basis: + a.capacity.append('Disk usage is stable.') + if not a.capacity: a.capacity.append('Collecting history - capacity advice appears after about an hour of data.') + + # health score + score = 100.0 + + def pen(when, p, why): + nonlocal score + if when and p > 0.5: + score -= p + a.reasons.append(f'−{rnd(p)} {why}') + + cpu = m.cpu_usage if cpu15 != cpu15 else cpu15 + pen(not online, 60, 'server unreachable') + pen(cpu > 70, min(24, (cpu - 70) * 0.8), f'CPU busy ({pct(cpu)})') + pen(m.mem_pct > 80, min(30, (m.mem_pct - 80) * 1.5), f'memory high ({pct(m.mem_pct)})') + pen(m.max_disk_pct > 80, min(40, (m.max_disk_pct - 80) * 2), f'disk high ({pct(m.max_disk_pct)})') + pen(m.swap_pct > 50, 10, 'heavy swap use') + pen(m.max_temp > 80, min(20, (m.max_temp - 80) * 2), f'hot ({temp(m.max_temp)})') + pen(a.up[0] < 100, min(30, (100 - a.up[0]) * 5), 'downtime in last 24 h') + pen(True, min(50, sum(0 if f.category == 'Availability' else {'critical': 15, 'warning': 7}.get(f.severity, 2) for f in a.findings)), + f'{len(a.findings)} finding(s)') + a.health = min(max(rnd(score), 0), 100) + a.grade = 'FDCBA'[sum(a.health >= x for x in (40, 60, 75, 90))] + a.findings.sort(key=lambda f: {'critical': 0, 'warning': 1}.get(f.severity, 2)) + return a diff --git a/Server Monitor(python-linux)/main.py b/Server Monitor(python-linux)/main.py new file mode 100644 index 0000000000000000000000000000000000000000..d6fa04eaa83e384697799a41ff0a16c1f8cf39c4 --- /dev/null +++ b/Server Monitor(python-linux)/main.py @@ -0,0 +1,13 @@ +"""Server Monitor - entry point.""" +import tkinter as tk + +from session import Manager +from ui import MainWindow + +def main(): + root, mgr = tk.Tk(), Manager() + MainWindow(root, mgr) + mgr.load() + root.mainloop() + +if __name__ == '__main__': main() diff --git a/Server Monitor(python-linux)/metrics.py b/Server Monitor(python-linux)/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..69e4708f016f1776f6d4b5f3d5bd10ec0ae26bd1 --- /dev/null +++ b/Server Monitor(python-linux)/metrics.py @@ -0,0 +1,84 @@ +"""One parsed sample (Metrics) and the frame helpers shared by the platform parsers.""" +from collections import namedtuple + +Core = namedtuple('Core', 'usage mhz') +Mount = namedtuple('Mount', 'device type mount total used avail pct') +Disk = namedtuple('Disk', 'name read_bps write_bps read_iops write_iops util total_read total_written') +Net = namedtuple('Net', 'name state speed virt rx_bps tx_bps rx_pps tx_pps rx_bytes tx_bytes errors drops') +Proc = namedtuple('Proc', 'pid ppid threads nice name user state cpu mem_pct rss vsz age') # cpu: % of one core +Service = namedtuple('Service', 'unit load active sub description') +Temp = namedtuple('Temp', 'name celsius') +Gpu = namedtuple('Gpu', 'index name util mem_used mem_total temp power fan') + +class Metrics: + TEXTS = 'hostname os kernel arch cpu_model virt fullest_mount busiest_disk' + NUMBERS = ('cpu_count logged_users procs_running procs_blocked threads_total sockets_used services_failed services_running ' + 'uptime load1 load5 load15 cpu_usage cpu_user cpu_system cpu_iowait cpu_steal cpu_irq ctxt_per_sec intr_per_sec ' + 'forks_per_sec avg_mhz mem_total mem_free mem_available mem_used buffers cached shared slab dirty swap_total ' + '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') + LISTS = 'cores mounts disks nets procs services temps gpus' + def __init__(self, timestamp=0): + self.valid, self.timestamp, self.tcp = False, timestamp, {} # tcp: state name -> connections + for names, value in ((self.TEXTS, ''), (self.NUMBERS, 0)): + for k in names.split(): setattr(self, k, value) + for k in self.LISTS.split(): setattr(self, k, []) + def gpu_max(self, temp=False): return max((g.temp if temp else g.util for g in self.gpus), default=0) + +def num(s): + """Number from text; 0 when missing or malformed.""" + try: return float(s) + except (TypeError, ValueError): return 0.0 + +def to_int(s, base=10): + try: return int(str(s).strip(), base) + except ValueError: return 0 + +def sections(frame): + """Splits a collector frame into {section name: lines}.""" + sec, cur = {}, None + for line in frame.replace('\r', '').split('\n'): + if line.startswith('@@S '): cur = sec.setdefault(line[4:].strip(), []) + elif cur is not None and not line.startswith('@@'): cur.append(line) + return sec + +def rates(state, dt): + """Returns delta(key, counters) -> per-second rates against the previous frame; remembers the new counters.""" + prev, state['counters'] = state.get('counters', {}), {} + + def delta(key, v): + p = prev.get(key, ()) + state['counters'][key] = v + 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) + return delta + +def add_disk(m, d, physical=True): + """Lists a disk; physical ones count towards the totals and the busiest-disk figure.""" + m.disks.append(d) + if physical: + m.disk_read_bps += d.read_bps + m.disk_write_bps += d.write_bps + if d.util >= m.max_disk_util: m.max_disk_util, m.busiest_disk = d.util, d.name + +def add_mount(m, mt): + m.mounts.append(mt) + if mt.pct >= m.max_disk_pct: m.max_disk_pct, m.fullest_mount = mt.pct, mt.mount + +def finish(m, sec, state, temp_unit): + """What every platform shares: percentages, totals, sensors (value / temp_unit = Celsius), cached GPUs and services, ordering.""" + m.mem_pct = m.mem_used * 100 / m.mem_total if m.mem_total > 0 else 0 + m.swap_pct = m.swap_used * 100 / m.swap_total if m.swap_total > 0 else 0 + 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')) + m.threads_total = sum(p.threads for p in m.procs) + if 'gpu' in sec: # nvidia-smi CSV; like the services it arrives every few samples: keep the last list + 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] + m.gpus, m.services = state.get('gpus', []), state.get('services', []) + m.services_failed = sum(s.active == 'failed' for s in m.services) + m.services_running = sum(s.sub == 'running' for s in m.services) + for line in sec.get('thermal', ()): + name, _, value = line.rpartition('|') + t = Temp(name.strip(), num(value) / temp_unit) + if name and 0 < t.celsius <= 150 and all(t.name != x.name for x in m.temps): m.temps.append(t) + m.max_temp = max((t.celsius for t in m.temps), default=0) + m.nets.sort(key=lambda n: (n.virt, n.name)) + m.procs.sort(key=lambda p: (-p.cpu, -p.rss)) + return m diff --git a/Server Monitor(python-linux)/model.py b/Server Monitor(python-linux)/model.py new file mode 100644 index 0000000000000000000000000000000000000000..a6c3f05c0a8c4c0523d4564ca98e2a4227eae409 --- /dev/null +++ b/Server Monitor(python-linux)/model.py @@ -0,0 +1,117 @@ +"""Server configuration, alert rules, autopilot policy and text formatting.""" +import base64, binascii, math, uuid +from dataclasses import asdict, dataclass, field, fields + +import plat +from metrics import to_int + +# ---- formatting ------------------------------------------------------------- +def fmt_bytes(b, prec=1): + i = 0 + while abs(b) >= 1024 and i < 5: b, i = b / 1024, i + 1 + return f'{b:.{prec if i else 0}f} ' + 'B KB MB GB TB PB'.split()[i] + +def rate(b): return fmt_bytes(b) + '/s' +def pct(p, prec=1): return f'{p:.{prec}f}%' +def temp(c): return f'{c:.0f} °C' + +def count(v): + a = abs(v) + 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}' + +def duration(sec): + s = int(sec) + d, h, m = s // 86400, s % 86400 // 3600, s % 3600 // 60 + 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' + +def rnd(x): + """Rounds half up (Python's round() rounds half to even).""" + return math.floor(x + 0.5) + +def command(template, q='', n=None): + """Fills a platform command template: {q} = quoted argument, {n} = integer argument (default: q as a number).""" + return template.replace('{q}', plat.quote(str(q))).replace('{n}', str(to_int(q if n is None else n))) + +# ---- catalogues: (key, label, unit) and (key, label, argument hint) ------------ +RULE_METRICS = [d for d in ( + ('cpu', 'CPU usage', '%'), ('iowait', 'CPU I/O wait', '%'), ('load', 'Load (1 min) per core', '%'), ('mem', 'Memory usage', '%'), + ('swap', 'Swap usage', '%'), ('disk', 'Fullest disk usage', '%'), ('diskio', 'Busiest disk utilisation', '%'), + ('temp', 'Hottest sensor', '°C'), ('rx', 'Network download', 'MB/s'), ('tx', 'Network upload', 'MB/s'), ('failed', 'Failed services', ''), + ('procs', 'Process count', ''), ('gpu', 'GPU usage (max)', '%'), ('gputemp', 'GPU temperature (max)', '°C')) if plat.POSIX_CPU or d[0] != 'iowait'] +RULE_ACTIONS = [(k, text, plat.HINTS.get(k, '')) for k, text in ( + ('notify', 'Notify only'), ('restart_failed', 'Restart failed services'), ('restart_service', 'Restart a service'), + ('kill_top_cpu', 'Terminate top CPU process'), ('kill_top_mem', 'Terminate top memory process'), + ('drop_caches', 'Sync + drop page cache'), ('command', 'Run a command')) if k != 'drop_caches' or k in plat.CMD] + +def catalogue(defs, key, col=1): + """Label (col 1) or unit / hint (col 2) of a rule metric or action.""" + return next((d[col] for d in defs if d[0] == key), key if col == 1 else '') + +# ---- configuration (field names = servers.json keys) --------------------------- +@dataclass +class Rule: + """When for s -> (), again after s.""" + id: str = ''; metric: str = 'cpu'; op: str = '>'; action: str = 'notify'; arg: str = ''; severity: str = 'warning' + enabled: bool = True; value: float = 90.0; duration: int = 60; cooldown: int = 300 + def condition(self): + unit = catalogue(RULE_METRICS, self.metric, 2) + return (f'{catalogue(RULE_METRICS, self.metric)} {self.op} {self.value:g}' + (f' {unit}' if unit else '') + + (f' for {self.duration} s' if self.duration else '')) + def action_text(self): return catalogue(RULE_ACTIONS, self.action) + (f': {self.arg}' if self.arg else '') + +@dataclass +class AutopilotConfig: + """History-driven automatic control (evaluated by the analyzer every minute).""" + enabled: bool = True; dryRun: bool = False; restartFailed: bool = True; diskCleanup: bool = False; anomalyAlerts: bool = True + maxRestartsPerHour: int = 3; runawayMinutes: int = 10; diskForecastDays: int = 3 + runawayCpu: float = 90.0; diskCleanupAt: float = 92.0; leakMemPressure: float = 90.0; anomalyZ: float = 3.0 + runawayMode: str = 'renice'; leakMode: str = 'notify' # none|renice|terminate, none|notify|terminate + diskCleanupCommand: str = plat.CLEANUP + +def new_id(): return str(uuid.uuid4())[:12] + +def default_rules(): + return [Rule(new_id(), m, value=float(v), duration=d, severity=s) for m, v, d, s in ( + ('cpu', 90, 60, 'warning'), ('mem', 90, 60, 'warning'), ('swap', 80, 120, 'warning'), ('disk', 90, 0, 'critical'), + ('temp', 85, 30, 'critical'), ('load', 150, 120, 'warning'), ('failed', 0, 0, 'warning'))] + +def load(cls, o): + """Dataclass from a JSON object: known scalar fields only, converted to the declared type.""" + c = cls() + for f in fields(cls): + if f.type in (str, int, float, bool) and o.get(f.name) is not None: + try: setattr(c, f.name, f.type(o[f.name])) + except (TypeError, ValueError): pass + return c + +def xor_b64(s, encode): + """Light obfuscation of saved passwords (NOT encryption).""" + key = b'ServerMonitor/obfuscation/v1' + try: b = s.encode() if encode else base64.b64decode(s) + except binascii.Error: return '' + b = bytes(x ^ key[i % len(key)] for i, x in enumerate(b)) + return base64.b64encode(b).decode() if encode else b.decode('utf-8', 'replace') + +@dataclass +class ServerConfig: + id: str = ''; name: str = ''; group: str = ''; host: str = ''; user: str = ''; keyFile: str = ''; password: str = ''; notes: str = '' + transport: int = 1; port: int = 22; interval: int = plat.INTERVAL; useSudo: bool = False; enabled: bool = True # transport: 0 Local, 1 SSH + rules: list = field(default_factory=default_rules) + autopilot: AutopilotConfig = field(default_factory=AutopilotConfig) + def address(self): + if not self.transport: return 'this machine' + return (f'{self.user}@' if self.user else '') + self.host + (f':{self.port}' if self.port != 22 else '') + def to_json(self): return {**asdict(self), 'password': xor_b64(self.password, True)} + @classmethod + def from_json(cls, o): + c = load(cls, o) + c.autopilot = load(AutopilotConfig, o.get('autopilot', {})) + if 'rules' in o: c.rules = [load(Rule, r) for r in o['rules']] + for r in c.rules: r.id = r.id or new_id() + c.transport = 0 if o.get('transport', 1) == 0 else 1 + c.password = xor_b64(o.get('password', ''), False) + c.interval = min(max(c.interval, 1), 300) + c.id = c.id or new_id() + return c + +TRANSPORTS = ('Local', 'SSH') diff --git a/Server Monitor(python-linux)/plat.py b/Server Monitor(python-linux)/plat.py new file mode 100644 index 0000000000000000000000000000000000000000..180fec47d433f316cee650d06809432a3a19efa4 --- /dev/null +++ b/Server Monitor(python-linux)/plat.py @@ -0,0 +1,295 @@ +"""Platform module (Linux): everything OS-specific - collector script, process spawning, frame parser, +command tables and the texts that differ between the editions.""" +import atexit, functools, os, re, signal, subprocess, tempfile + +from metrics import Core, Disk, Metrics, Mount, Net, Proc, Service, add_disk, add_mount, finish, num, rates, sections, to_int + +NAME, HAS_SUDO, POSIX_CPU, INTERVAL = 'Linux', True, True, 2 # POSIX_CPU: I/O wait and steal exist; INTERVAL: default sample seconds +SPAWN = {'start_new_session': True} # extra subprocess.Popen arguments: own process group, so that kill() reaches what the shell started + +def config_dir(): return os.path.join(os.environ.get('XDG_CONFIG_HOME') or os.path.expanduser('~/.config'), 'ServerMonitorPy') +def open_folder(path): subprocess.Popen(['xdg-open', path]) + +def shell(interval=None): + """Command line that runs the script arriving on stdin (locally, or joined by spaces as the ssh remote command).""" + return ['sh', '-s'] + (['--', str(interval)] if interval else []) + +def collector(interval): + """Stdin for the collector process (the interval travels on the command line).""" + return COLLECTOR + +def kill(p): + """Ends a child process with everything it started (a shell's sleep or pipeline would keep its output pipe open).""" + try: p.poll() is None and os.killpg(p.pid, signal.SIGKILL) + except OSError: pass + +def quote(s): return "'" + s.replace("'", "'\\''") + "'" + +def wrap(cmd, privileged, sudo): + """Stdin for a one-shot command.""" + return (f'sudo -n sh -c {quote(cmd)}' if privileged and sudo else cmd) + '\n' + +@functools.lru_cache(None) +def askpass(): + """Helper script that answers ssh's password prompt from $SERVERMONITOR_ASKPASS; removed on exit.""" + fd, path = tempfile.mkstemp(prefix='servermonitor-askpass-', suffix='.sh') + os.write(fd, b'#!/bin/sh\nprintf \'%s\\n\' "$SERVERMONITOR_ASKPASS"\n') + os.close(fd) + os.chmod(path, 0o700) + atexit.register(os.remove, path) + return path + +def protected(p): + """Processes that are never killed automatically and get no leak / runaway findings.""" + return p.pid <= 2 or p.ppid == 2 or p.rss <= 0 or p.name in ('sshd', 'systemd') + +def thrashing(iowait, mem, disk_busy): + """Rest of the sentence "Swap … used" when heavy swap use is thrashing ('' = it is not); iowait and disk_busy are 15-minute averages.""" + return f' and CPU waits on I/O {iowait:.1f}% of the time' if iowait > 20 else '' + +def priority_level(nice): + """How the priority column value compares with normal: > 0 raised, < 0 lowered.""" + return -nice + +def cpu_tile(m): + """(value, sub text, warn) of the CPU tab tile TEXT['cpu_tile'].""" + return f'{m.cpu_steal:.1f}% / {m.cpu_irq:.1f}%', 'steal > 5% = noisy neighbours', m.cpu_steal > 5 + +# ---- command tables: {q} = quoted argument, {n} = integer argument --------------------------- +CMD = { + 'kill_pid': 'kill -TERM {n}', 'renice': 'renice -n 19 -p {n}', 'drop_caches': 'sync && echo 3 > /proc/sys/vm/drop_caches', + 'restart_service': 'systemctl reset-failed {q} 2>/dev/null; systemctl restart {q}', + 'restart_failed': "for u in $(systemctl list-units --type=service --state=failed --no-legend --plain | awk '{print $1}'); " + "do echo restart $u; systemctl restart $u; done"} +CLEANUP = ('journalctl --vacuum-time=7d 2>/dev/null; apt-get clean 2>/dev/null; dnf clean all 2>/dev/null; ' + 'find /tmp /var/tmp -xdev -type f -atime +7 -delete 2>/dev/null; true') +HINTS = {'restart_service': 'nginx.service', 'command': 'find /tmp -mtime +7 -delete'} # rule-argument placeholders +POWER = {'Reboot': '(sleep 2; systemctl reboot) >/dev/null 2>&1 &', 'Shut down': '(sleep 2; systemctl poweroff) >/dev/null 2>&1 &'} +# (label, command, flags): b = toolbar button, c = ask first, d = dangerous +PROC_ACTIONS = [('Terminate', 'kill -TERM {n}', 'bc'), ('Kill', 'kill -KILL {n}', 'bcd'), ('Hang up', 'kill -HUP {n}', 'c'), + ('Suspend', 'kill -STOP {n}', 'bc'), ('Resume', 'kill -CONT {n}', 'b')] +PRIORITIES = {'-20 (highest)': -20, '-10': -10, '0 (normal)': 0, '10': 10, '19 (lowest)': 19} +PRIORITY_CMD = 'renice -n {v} -p {n}' +SERVICE_VERBS = {v: f'systemctl {v} {{q}}' for v in ('start', 'stop', 'restart', 'reload', 'enable', 'disable')} +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" +QUICK = [ # console: quick diagnostics + ('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'), + ('Memory', 'free -h; echo; vmstat 1 3'), + ('Top CPU processes', 'ps -eo pid,user,pcpu,pmem,rss,etime,comm --sort=-pcpu | head -n 20'), + ('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'), + ('Errors in journal', 'journalctl -p err -n 60 --no-pager'), + ('Failed services', 'systemctl --failed --no-pager'), + ('Logged-in users', 'w'), + ('Last reboots', 'last -x reboot shutdown 2>/dev/null | head -n 15')] +ACTIONS = [ # console: system actions (confirmed, privileged); the POWER ones are shown as dangerous + ('Sync + drop page cache', CMD['drop_caches'] + ' && echo done'), + ('Vacuum journal to 200 MB', 'journalctl --vacuum-size=200M'), + ('Clean package cache', '(apt-get clean || dnf clean all || yum clean all) 2>&1'), + ('Restart failed services', CMD['restart_failed'] + '; echo done'), + ('Reboot', POWER['Reboot'] + " echo 'reboot scheduled'"), + ('Shut down', POWER['Shut down'] + " echo 'shutdown scheduled'")] +TEXT = { + 'cpu_tile': 'Steal / IRQ', 'priority': 'Nice', 'kernel': 'Linux ', + 'renice': 'Renice to 19', 'renice_mode': 'Lower priority (renice 19)', 'renice_advice': 'Lower its priority (renice) or stop it if it is stuck.', + 'ssh_hint': 'Uses your system ssh client; nothing is installed on the server. Set up key login once with: ssh-copy-id user@host', + 'key_hint': 'default keys / ssh-agent (~/.ssh/id_*)', 'sudo': 'Run control commands with sudo -n (needs passwordless sudo)', + 'console_hint': 'Type a shell command and press Enter (↑/↓ history)', + 'privileged_tip': "Wrap in sudo -n when the server has 'Run control commands with sudo' enabled"} + +# ---- collector frame parser ------------------------------------------------------------------- +VIRTUAL_IF = re.compile(r'lo|veth|docker|br-|virbr|cni|flannel|cali|vxlan|kube|tun|tap') +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+)$') +TCP_STATES = ['', 'ESTABLISHED', 'SYN_SENT', 'SYN_RECV', 'FIN_WAIT1', 'FIN_WAIT2', 'TIME_WAIT', 'CLOSE', 'CLOSE_WAIT', 'LAST_ACK', 'LISTEN', 'CLOSING'] +SKIP_FS = {'tmpfs', 'devtmpfs', 'squashfs', 'overlay', 'efivarfs', 'ramfs', 'proc', 'sysfs', 'autofs', 'nsfs', 'devfs', 'cgroup', 'cgroup2', + 'fuse.snapfuse', 'fuse.portal'} + +def parse(frame, st, now): + """Collector frame -> Metrics; st keeps the counters of the previous frame (rates) and the slow sections.""" + sec, m = sections(frame), Metrics(now) + + def rows(name): # non-empty lines of a section, split into fields + return [f for f in map(str.split, sec.get(name, ())) if f] + + def first(name): return (rows(name) or [['']])[0] + + info = st.setdefault('info', {}) + for line in sec.get('info', ()): + k, eq, v = line.partition('=') + if eq and k: info[k] = v.strip() + if 'passwd' in sec: st['users'] = {to_int(uid): name for name, _, uid in (l.rpartition(':') for l in sec['passwd']) if name} + 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')) + clk, page = max(1, to_int(info.get('clk', 100))), max(512, to_int(info.get('page', 4096))) + m.load1, m.load5, m.load15 = (num(x) for x in (first('loadavg') + [''] * 3)[:3]) + m.uptime = num(first('uptime')[0]) + if m.uptime <= 0: return m + dt = m.uptime - st['uptime'] if st.get('uptime', 0) > 0 else 0 + live, delta = dt > 0.05, rates(st, dt) + + # CPU + cpu, counters = [], [0.0] * 3 + for f in rows('stat'): + v = num(f[1]) if len(f) > 1 else 0.0 + if f[0].startswith('cpu'): cpu.append([num(x) for x in (f[1:9] + [''] * 8)[:8]]) + elif f[0] in ('ctxt', 'intr', 'processes'): counters[('ctxt', 'intr', 'processes').index(f[0])] = v + elif f[0] == 'procs_running': m.procs_running = int(v) + elif f[0] == 'procs_blocked': m.procs_blocked = int(v) + m.cpu_count = max(1, len(cpu) - 1) + usage, mhz, jiffies, old = [0.0] * m.cpu_count, [0.0] * m.cpu_count, 0, st.get('cpu', []) + for i, (new, was) in enumerate(zip(cpu, old) if live and len(cpu) == len(old) else ()): + d = [a - b for a, b in zip(new, was)] + total = sum(d) + if total <= 0: continue + p = [min(max(x * 100 / total, 0), 100) for x in d] # user nice system idle iowait irq softirq steal + use = min(max(100 - p[3] - p[4], 0), 100) + if i: + usage[i - 1] = use + else: + 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] + st['cpu'] = cpu + m.ctxt_per_sec, m.intr_per_sec, m.forks_per_sec = delta('stat', counters) + 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] + for i, v in freqs: mhz[i] = v + m.avg_mhz = sum(v for _, v in freqs) / len(freqs) if freqs else 0 + m.cores = [Core(*c) for c in zip(usage, mhz)] + + # memory + mi = {k: num((v.split() or [''])[0]) * 1024 for k, _, v in (l.partition(':') for l in sec.get('meminfo', ())) if v} + m.mem_total, m.mem_free, m.buffers, m.cached = (mi.get(k, 0.0) for k in ('MemTotal', 'MemFree', 'Buffers', 'Cached')) + m.cached += mi.get('SReclaimable', 0.0) + m.mem_available = mi.get('MemAvailable', m.mem_free + m.buffers + m.cached) + m.shared, m.slab, m.dirty, m.swap_total = (mi.get(k, 0.0) for k in ('Shmem', 'Slab', 'Dirty', 'SwapTotal')) + 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)) + + # network + state = {f[0]: f for f in rows('netstate')} + for line in sec.get('netdev', ()): + name, _, rest = line.partition(':') + name, f = name.strip(), [num(x) for x in rest.split()] + if not name or len(f) < 16: continue + s = state.get(name, []) + 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)), + *delta('net:' + name, [f[0], f[8], f[1], f[9]]), f[0], f[8], f[2] + f[10], f[3] + f[11])) + for f in rows('tcp'): + i = to_int(f[0], 16) + name = TCP_STATES[i] if i < len(TCP_STATES) else '?' + m.tcp[name] = m.tcp.get(name, 0) + to_int(f[-1] if len(f) > 1 else 0) + for f in rows('sockstat'): + if f[0] == 'sockets:' and len(f) > 2: m.sockets_used = to_int(f[2]) + + # disks: whole devices + device-mapper; totals over physical disks only + for f in rows('diskstats'): + whole = bool(WHOLE_DISK.match(f[2])) if len(f) >= 14 else False + if len(f) < 14 or not (whole or f[2].startswith('dm-')): continue + read, written = num(f[5]) * 512, num(f[9]) * 512 + r = delta('disk:' + f[2], [num(f[3]), read, num(f[7]), written, num(f[12])]) + 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')) + df, seen = sec.get('df', []), set() + b = int(bool(df) and 'Type' in df[0]) # 1 when df printed the file system type + for f in map(str.split, df[1:]): + if len(f) < 6 + b: continue + device, fs, mount = f[0], f[1] if b else '', ' '.join(f[5 + b:]) + total, used, avail = (num(x) * 1024 for x in f[1 + b:4 + b]) + if (fs if b else device) in SKIP_FS or total <= 0 or mount.startswith('/snap/') or (device.startswith('/') and (device, total) in seen): + continue + seen.add((device, total)) + add_mount(m, Mount(device, fs, mount, total, used, avail, used * 100 / (used + avail) if used + avail > 0 else 0)) + + # processes: "pid state ppid ticks nice threads start vsize rss comm..." + uid = {to_int(f[0]): to_int(f[1]) for f in rows('uids') if len(f) > 1} + users, old, ticks = st.get('users', {}), st.get('ticks', {}), {} + per_core = jiffies / m.cpu_count if jiffies > 0 else dt * clk if live else 0 + for line in sec.get('procs', ()): + f = line.split(' ', 9) + pid = to_int(f[0]) + if len(f) < 10 or pid <= 0: continue + ticks[pid], rss = num(f[3]), num(f[8]) * page + 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 + 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 '?', + 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))) + + 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')] + m.logged_users = to_int(first('users')[0]) + st['ticks'], st['uptime'] = ticks, m.uptime + m.valid = live # the first sample has no rates yet + return finish(m, sec, st, 1000) + +COLLECTOR = r'''sm_main() { +iv="${1:-2}" once="${2:-0}" n=0 +export LC_ALL=C +while :; do + echo "@@SNAP_BEGIN" + if [ $((n % 15)) -eq 0 ]; then + echo "@@S info" + echo "hostname=$(cat /proc/sys/kernel/hostname 2>/dev/null)" + echo "kernel=$(uname -r 2>/dev/null)" + echo "arch=$(uname -m 2>/dev/null)" + echo "os=$(sed -n 's/^PRETTY_NAME=//p' /etc/os-release 2>/dev/null | tr -d '"')" + echo "cpumodel=$(grep -m1 -E '^(model name|Hardware|Processor|cpu model)' /proc/cpuinfo 2>/dev/null | cut -d: -f2- | sed 's/^ *//')" + echo "clk=$(getconf CLK_TCK 2>/dev/null || echo 100)" + echo "page=$(getconf PAGESIZE 2>/dev/null || echo 4096)" + echo "virt=$(systemd-detect-virt 2>/dev/null || echo unknown)" + echo "@@S passwd"; cut -d: -f1,3 /etc/passwd 2>/dev/null + fi + echo "@@S uptime"; cat /proc/uptime + echo "@@S loadavg"; cat /proc/loadavg + echo "@@S stat" + grep -E '^(cpu|ctxt|processes|procs_)' /proc/stat + awk '/^intr/ {print "intr", $2}' /proc/stat + echo "@@S meminfo"; cat /proc/meminfo + echo "@@S netdev"; cat /proc/net/dev + echo "@@S netstate" + for i in /sys/class/net/*; do + [ -e "$i" ] || continue + echo "${i##*/} $(cat "$i/operstate" 2>/dev/null || echo unknown) $(cat "$i/speed" 2>/dev/null || echo -1)" + done + echo "@@S diskstats"; cat /proc/diskstats + echo "@@S df"; df -P -T -k 2>/dev/null || df -P -k 2>/dev/null + echo "@@S sockstat"; cat /proc/net/sockstat 2>/dev/null + echo "@@S tcp" + 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]}' + echo "@@S thermal" + for z in /sys/class/thermal/thermal_zone*; do + [ -r "$z/temp" ] && echo "$(cat "$z/type" 2>/dev/null)|$(cat "$z/temp" 2>/dev/null)" + done + for h in /sys/class/hwmon/hwmon*; do + [ -d "$h" ] || continue + hn=$(cat "$h/name" 2>/dev/null) + for t in "$h"/temp*_input; do + [ -r "$t" ] || continue + l=$(cat "${t%_input}_label" 2>/dev/null) + echo "$hn ${l:-${t##*/}}|$(cat "$t" 2>/dev/null)" + done + done + echo "@@S freq" + for c in /sys/devices/system/cpu/cpu[0-9]*; do + f=$(cat "$c/cpufreq/scaling_cur_freq" 2>/dev/null) && echo "${c##*/cpu} $f" + done + echo "@@S procs" + cat /proc/[0-9]*/stat 2>/dev/null | awk '{ + if (!match($0, /\(.*\)/)) next + comm = substr($0, RSTART + 1, RLENGTH - 2) + rest = substr($0, RSTART + RLENGTH + 1) + k = split(rest, r, " ") + if (k < 22) next + print $1, r[1], r[2], r[12] + r[13], r[17], r[18], r[20], r[21], r[22], comm + }' + echo "@@S uids"; ls -ln /proc 2>/dev/null | awk '$NF ~ /^[0-9]+$/ {print $NF, $3}' + if [ $((n % 5)) -eq 0 ]; then + echo "@@S services" + systemctl list-units --type=service --all --no-legend --no-pager --plain 2>/dev/null | head -n 600 + fi + if [ $((n % 3)) -eq 0 ] && command -v nvidia-smi >/dev/null 2>&1; then + echo "@@S gpu" + 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 + fi + echo "@@S users"; who 2>/dev/null | wc -l + echo "@@SNAP_END" || exit 0 + [ "$once" = "once" ] && break + n=$((n + 1)) + sleep "$iv" +done +} +sm_main "$@" +''' diff --git a/Server Monitor(python-linux)/run.sh b/Server Monitor(python-linux)/run.sh new file mode 100755 index 0000000000000000000000000000000000000000..72150e00377154fe6fe8e159a610cc951cc49f12 --- /dev/null +++ b/Server Monitor(python-linux)/run.sh @@ -0,0 +1,3 @@ +#!/bin/sh +# Start Server Monitor (needs Python 3.8+ with tkinter). +exec python3 "$(dirname "$0")/main.py" "$@" diff --git a/Server Monitor(python-linux)/session.py b/Server Monitor(python-linux)/session.py new file mode 100644 index 0000000000000000000000000000000000000000..8938a2107fc333a6c2794a782cd8182d32fbf528 --- /dev/null +++ b/Server Monitor(python-linux)/session.py @@ -0,0 +1,411 @@ +"""Connection to one machine (local shell or system ssh), the per-server session +(metrics, live history, rules, autopilot) and the manager of all sessions.""" +import json, os, queue, shutil, subprocess, threading, time +from collections import namedtuple +from datetime import datetime +from types import SimpleNamespace + +import plat +from history import Analysis, ProcTrend, ServiceTrend, Store, analyze +from metrics import Metrics +from model import RULE_METRICS, ServerConfig, catalogue, command, new_id + +PIPE = subprocess.PIPE +SSH_OPTIONS = ['ConnectTimeout=10', 'ServerAliveInterval=10', 'ServerAliveCountMax=3', 'StrictHostKeyChecking=accept-new', 'LogLevel=ERROR'] +STATUS = ('Disabled', 'Connecting', 'Online', 'Offline') +DISABLED, CONNECTING, ONLINE, OFFLINE = range(4) +AlertEvent = namedtuple('AlertEvent', 'time server severity message') # severity: info|warning|critical|resolved|action + +# ---- UI-thread dispatch ----------------------------------------------------------------- +class Loop: + """Hands work to the UI thread: worker threads post() calls, timers are due in pump(), which the UI calls often.""" + def __init__(self): self.calls, self.timers = queue.SimpleQueue(), set() + def post(self, fn, *args): self.calls.put((fn, args)) + def pump(self): + while not self.calls.empty(): + fn, args = self.calls.get() + fn(*args) + now = time.monotonic() + for t in [t for t in self.timers if t.due <= now]: + if t in self.timers: # not stopped by a call that ran just before + t.start() if t.every else t.stop() + t.fn() + +loop = Loop() + +class Timer: + """Restartable timer on the loop; with every (seconds) it repeats.""" + def __init__(self, fn, every=0): + self.fn, self.every = fn, every + if every: self.start() + def start(self, seconds=None): + self.due = time.monotonic() + (seconds or self.every) + loop.timers.add(self) + def stop(self): loop.timers.discard(self) + +class Signal(list): + """List of listeners; calling it calls them all.""" + def __call__(self, *args): + for fn in list(self): fn(*args) + +# ---- Link --------------------------------------------------------------------------------- +class Link: + """Streams collector frames and runs one-shot commands on one machine. close() kills everything.""" + def __init__(self, cfg, on_frame, on_lost): + self.cfg, self.on_frame, self.on_lost, self.procs, self.pending, self.closed = cfg, on_frame, on_lost, set(), {}, False + def spawn(self, interval=None, **kw): + c, argv, env = self.cfg, plat.shell(interval), None + if c.transport: + options = SSH_OPTIONS + (['NumberOfPasswordPrompts=1'] if c.password else ['BatchMode=yes']) + if c.password: # a helper script answers ssh's password prompt + env = {'DISPLAY': ':0', **os.environ, 'SSH_ASKPASS': plat.askpass(), 'SSH_ASKPASS_REQUIRE': 'force', 'SERVERMONITOR_ASKPASS': c.password} + argv = ['ssh', *(x for o in options for x in ('-o', o)), *(['-i', os.path.expanduser(c.keyFile)] if c.keyFile else []), + *(['-p', str(c.port)] if c.port != 22 else []), '-T', f'{c.user}@{c.host}' if c.user else c.host, ' '.join(argv)] + try: p = subprocess.Popen(argv, stdin=PIPE, stdout=PIPE, env=env, **plat.SPAWN, **kw) + except OSError as e: raise OSError(f'cannot start {argv[0]}: {e.strerror}') from e + self.procs.add(p) + return p + def post(self, fn, *args): # results reach the UI thread, unless the link was closed meanwhile + loop.post(lambda: self.closed or fn(*args)) + def start(self): + try: p = self.spawn(self.cfg.interval, stderr=PIPE) + except OSError as e: return self.post(self.on_lost, str(e)) + threading.Thread(target=self.stream, args=(p,), daemon=True).start() + def stream(self, p): # worker thread: frames out of stdout, the last error line out of stderr + buf, err = b'', [b''] + + def errors(): + for chunk in iter(lambda: p.stderr.read1(4096), b''): err[0] = (err[0] + chunk)[-4096:] + + reader = threading.Thread(target=errors, daemon=True) + reader.start() + try: + p.stdin.write(plat.collector(self.cfg.interval).encode()) + p.stdin.close() + for chunk in iter(lambda: p.stdout.read1(1 << 16), b''): + buf += chunk + while b'@@SNAP_END' in buf: + end = buf.find(b'@@SNAP_END') + begin = buf.rfind(b'@@SNAP_BEGIN', 0, end) + if begin >= 0 and loop.calls.qsize() < 100: # a stalled UI must not pile up frames + self.post(self.on_frame, buf[begin:end].decode('utf-8', 'replace')) + buf = buf[end + 10:] + if len(buf) > 8 << 20: buf = b'' + except (OSError, ValueError): + pass # killed while writing or reading + code = p.wait() + reader.join(2) + lines = err[0].decode('utf-8', 'replace').split('\n') + self.post(self.on_lost, next((l.strip() for l in reversed(lines) if l.strip()), f'connection closed (exit code {code})')) + def exec(self, script, timeout, done=None): + """Runs a script; done(code, output) is called on the UI thread (code -1: killed, timed out or not started).""" + try: p = self.spawn(stderr=subprocess.STDOUT) + except OSError as e: return done and self.post(done, -1, str(e)) + self.pending[p] = done + + def work(): + try: + out, code = p.communicate(script.encode(), timeout)[0], p.returncode + except subprocess.TimeoutExpired: + plat.kill(p) + try: out, code = p.communicate(timeout=2)[0], -1 + except subprocess.TimeoutExpired: out, code = b'', -1 # something it started still holds the pipe + 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 '')) + + threading.Thread(target=work, daemon=True).start() + def finished(self, p, code, out): + self.procs.discard(p) + done = self.pending.pop(p) + if done: done(code, out) + def close(self, reason='connection stopped'): + self.closed = True + for p in self.procs: plat.kill(p) + for done in self.pending.values(): + if done: done(-1, reason) + +# ---- live history ----------------------------------------------------------------------- +class Live: + """The last hour of samples in memory, for the live charts.""" + KEYS, CAP = 'cpu user sys iowait steal mem cache swap rx tx rd wr load'.split(), 1800 + def __init__(self): self.t, self.s, self.if_rx, self.if_tx = [], {k: [] for k in self.KEYS}, {}, {} + def push(self, m): + n = len(self.t) + + def add(v, x): + v[:0] = [0.0] * (n - len(v)) # align series that appeared later + v.append(x) + del v[:-self.CAP] + + add(self.t, m.timestamp) + values = (m.cpu_usage, m.cpu_user, m.cpu_system + m.cpu_irq, m.cpu_iowait, m.cpu_steal, m.mem_pct, + (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, + m.disk_read_bps, m.disk_write_bps, m.load1) + for k, x in zip(self.KEYS, values): add(self.s[k], x) + for i in m.nets: + add(self.if_rx.setdefault(i.name, []), i.rx_bps) + add(self.if_tx.setdefault(i.name, []), i.tx_bps) + +# ---- session ---------------------------------------------------------------------------- +class Session: + def __init__(self, cfg): + self.cfg, self.status, self.err, self.link, self.engine = cfg, DISABLED, '', None, {} + self.m, self.live, self.an = Metrics(), Live(), Analysis() + self.store = Store(os.path.join(Manager.config_dir(), 'history', cfg.id)) + self.retries, self.paused, self.offline_alerted = 0, False, False + self.reported, self.dry, self.cooldown, self.rules, self.procs, self.svcs = set(), set(), {}, {}, {}, {} # analyzer / rule / tracking state + self.updated, self.analysis_updated, self.alert = Signal(), Signal(), Signal() + self.retry, self.watchdog, first = Timer(self.start), Timer(lambda: self.lost('no data received (timeout)')), Timer(self.analyze) + self.offline = Timer(self.down, cfg.interval) # downtime -> availability: one sample per interval, like uptime + self.timers = [self.retry, self.watchdog, first, self.offline, Timer(self.analyze, 60)] + first.start(3) + def online(self): return self.status == ONLINE and self.m.valid + def down(self): + if self.status == OFFLINE or (self.status == CONNECTING and self.retries): self.record(False) + def set_config(self, c): + old, self.cfg, self.offline.every = self.cfg, c, c.interval + if any(getattr(c, k) != getattr(old, k) for k in ('transport', 'host', 'port', 'user', 'keyFile', 'password', 'interval', 'enabled')): + self.live, self.m, self.procs, self.svcs = Live(), Metrics(), {}, {} # may be another machine now + self.start() if c.enabled else self.stop() + self.updated() + def set_paused(self, paused): + self.paused = paused + self.updated() + def reconnect(self): + self.retries, self.paused = 0, False + self.start() + def drop_link(self, reason): + self.retry.stop() + self.watchdog.stop() + link, self.link = self.link, None + if link: link.close(reason) + def start(self): + self.drop_link('connection restarted') + if not self.cfg.enabled: return self.set_status(DISABLED) + self.engine, self.m.valid = {}, False # online() only again with a fresh sample + self.link = Link(self.cfg, self.frame, self.lost) + self.set_status(CONNECTING) + self.watchdog.start(25) + self.link.start() + def stop(self): + self.drop_link('connection stopped') + self.set_status(OFFLINE if self.cfg.enabled else DISABLED) + def close(self): + self.stop() + for t in self.timers: t.stop() + def set_status(self, status, err=''): + if err or status == ONLINE: self.err = err + if status != self.status: + self.status = status + self.updated() + def frame(self, raw): + now = time.time() * 1000 + self.watchdog.start(max(15, self.cfg.interval * 5 + 10)) + m = plat.parse(raw, self.engine, now) + if m.uptime <= 0: return + if self.status != ONLINE: + self.retries = 0 + if self.offline_alerted: self.raise_alert('resolved', 'Server is back online') + self.offline_alerted = False + self.set_status(ONLINE) + if not m.valid or self.paused: # the first sample has no rates yet + return + if m.uptime < self.m.uptime: self.procs = {} # rebooted: PIDs start again, old trends would be blamed on new processes + first, self.m = not self.m.valid, m + self.live.push(m) + self.record(True) + self.track(now) + self.evaluate_rules() + if first: self.analyze() # first sample of this connection: the last analysis saw "unreachable" + self.updated() + def lost(self, why): + was = self.status == ONLINE + self.drop_link('connection lost: ' + why) + self.set_status(OFFLINE, why) + if (was or self.retries == 1) and not self.offline_alerted: + self.raise_alert('critical', 'Server is unreachable: ' + why) + self.offline_alerted = True + if self.cfg.enabled: + self.retry.start((3, 5, 10, 20, 30, 60)[min(self.retries, 5)]) # back-off + self.retries += 1 + def exec(self, cmd, privileged, done=None, timeout=60): + """Runs a command on the machine; privileged ones go through sudo when the server is set up for it.""" + if self.link and self.status == ONLINE: self.link.exec(plat.wrap(cmd, privileged, self.cfg.useSudo), timeout, done) + elif done: loop.post(done, -1, 'server is not connected') + def metric_value(self, key): + m = self.m + 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, + '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, + 'failed': m.services_failed, 'procs': len(m.procs), 'gpu': m.gpu_max(), 'gputemp': m.gpu_max(True)}.get(key, 0) + def active_alerts(self): + down = ['Unreachable: ' + self.err] if self.status == OFFLINE else [] + return down + [r.condition() for r in self.cfg.rules if r.id in self.rules and self.rules[r.id].active] + def raise_alert(self, severity, message): self.alert(AlertEvent(datetime.now(), self.cfg.name, severity, message)) + def record(self, up): + m, nan = self.m, float('nan') + self.store.add(int(time.time()), ( + 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, + 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), + m.gpu_max() if m.gpus else nan, m.services_failed), up) + def track(self, now): + """Per-process CPU streaks and RSS per minute; service failure transitions.""" + procs = {} + for p in self.m.procs: + t = self.procs.get(p.pid) + if not t or t.name != p.name: # new, or the pid was reused + t = SimpleNamespace(name=p.name, high_since=0, last_minute=0, rss=[]) + t.protected = plat.protected(p) + t.high_since = 0 if p.cpu < self.cfg.autopilot.runawayCpu else t.high_since or now + if now - t.last_minute >= 60000: t.last_minute, t.rss = now, t.rss[-59:] + [p.rss] + procs[p.pid] = t + self.procs, svcs = procs, {} + for s in self.m.services: + t, failed = self.svcs.get(s.unit) or SimpleNamespace(last='', preexisting=False, fails=[], restarts=[]), s.active == 'failed' + svcs[s.unit] = t + if not t.last: + t.preexisting = failed # failed before monitoring started: leave it alone + elif failed and t.last != 'failed': + t.fails.append(now) + t.preexisting = False + elif not failed: + t.preexisting = False + t.last = s.active + t.fails, t.restarts = ([x for x in v if now - x <= 3600000] for v in (t.fails, t.restarts)) + if svcs: self.svcs = svcs # forgets removed services; a sample without a service list changes nothing + def evaluate_rules(self): + now, m = time.time() * 1000, self.m + for r in self.cfg.rules: + st = self.rules.setdefault(r.id, SimpleNamespace(since=0, last_fire=0, active=False)) + v = self.metric_value(r.metric) + idle = not r.enabled or (r.metric in ('gpu', 'gputemp') and not m.gpus) or (r.metric == 'temp' and not m.temps) + if idle or (v >= r.value if r.op == '<' else v <= r.value): + if st.active and not idle: self.raise_alert('resolved', f'Recovered: {r.condition()} (now {v:.1f})') + del self.rules[r.id] + continue + st.since = st.since or now + if now - st.since < r.duration * 1000 or (st.active and (r.action == 'notify' or now - st.last_fire < r.cooldown * 1000)): continue + unit = catalogue(RULE_METRICS, r.metric, 2) + if not st.active: self.raise_alert(r.severity, f'{r.condition()} (now {v:.1f}' + (f' {unit}' if unit else '') + ')') + st.active, st.last_fire = True, now + action, arg = r.action, r.arg + if action.startswith('kill_top'): # heaviest process that is not protected + 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) + action, arg = ('kill_pid', str(best.pid)) if best else ('notify', '') + if action != 'notify': self.run(action, arg, f'Automation "{r.condition()}": {r.action_text()}') + def run(self, action, arg, what, done=None): + cmds = {'command': arg, 'disk_cleanup': self.cfg.autopilot.diskCleanupCommand, **{k: command(v, arg) for k, v in plat.CMD.items()}} + if not cmds.get(action): return done and done(-1, 'nothing to do') + + def report(code, out): + tail = ' '.join(out.split())[-300:] # one line: events are lines in alerts.log + self.raise_alert('action', f'{what} -> ' + (f'failed ({code})' if code else 'OK') + (f' | {tail}' if tail else '')) + if done: done(code, out) + + self.exec(cmds[action], True, report, 300) + def run_finding(self, f, automatic, done=None): + if automatic and f.action == 'restart_service': self.svcs[f.arg].restarts.append(time.time() * 1000) + self.run(f.action, '' if f.action == 'disk_cleanup' else f.arg, ('Autopilot: ' if automatic else 'Manual fix: ') + f'{f.label} ({f.title})', done) + def analyze(self): + now, trends, ap = time.time() * 1000, [], self.cfg.autopilot + for p in self.m.procs: + t = self.procs.get(p.pid) + rss = t.rss if t else [] + growth = rss[-1] - rss[0] if len(rss) >= 2 else 0 + 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, + growth * 100 / rss[0] if growth and rss[0] > 0 else 0, + 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)) + if pt.high_cpu_minutes > 0 or pt.minutes >= 30: trends.append(pt) + svcs = [ServiceTrend(unit, t.last == 'failed', t.preexisting, len(t.fails), len(t.restarts)) + for unit, t in self.svcs.items() if t.last == 'failed' or t.fails] + self.an = analyze(self.store, self.m, ap, trends, svcs, self.online()) + + for f in self.an.findings: # announce each new finding once + if f.key not in self.reported and f.category != 'Availability': self.raise_alert(f.severity, f'Insight: {f.title} - {f.detail}') + self.reported = {f.key for f in self.an.findings} + + dry = set() # act on eligible findings, with cooldowns; a dry run says once what it would do + for f in self.an.findings if ap.enabled and self.online() else (): + if not f.auto: continue + if ap.dryRun: + dry.add(f.key) + if f.key not in self.dry: self.raise_alert('action', f'Autopilot (dry run) would: {f.label} - {f.title}') + elif now - self.cooldown.get(f.key, 0) >= {'disk_cleanup': 6 * 3600000, 'restart_service': 120000}.get(f.action, 900000): + self.cooldown[f.key] = now + self.run_finding(f, True) + self.dry = dry + self.analysis_updated() + +# ---- manager ---------------------------------------------------------------------------- +class Manager: + def __init__(self): + self.sessions, self.alerts = [], [] + self.changed, self.alert, self.cleared = Signal(), Signal(), Signal() # server list changed, alert raised, alerts cleared + @staticmethod + def config_dir(): + os.makedirs(plat.config_dir(), exist_ok=True) + return plat.config_dir() + def path(self, name): return os.path.join(self.config_dir(), name) + def session(self, server_id): return next((s for s in self.sessions if s.cfg.id == server_id), None) + def attach(self, cfg): + s = Session(cfg) + s.alert.append(self.on_alert) + self.sessions.append(s) + return s + def on_alert(self, e): + self.alerts[:0] = [e] + del self.alerts[2000:] + log = self.path('alerts.log') + try: + with open(log, 'w' if os.path.exists(log) and os.path.getsize(log) > 5 << 20 else 'a', encoding='utf-8') as f: + f.write(f'{e.time.isoformat(timespec="seconds")}\t{e.severity}\t{e.server}\t{e.message}\n') + except OSError: + pass # the event still reaches the window + self.alert(e) + def load(self): + try: + with open(self.path('servers.json'), encoding='utf-8') as f: + for o in json.load(f)['servers']: self.attach(ServerConfig.from_json(o)) + except FileNotFoundError: # first start: monitor this machine + self.attach(ServerConfig(new_id(), 'This computer', 'Local', transport=0)) + self.save() + except (OSError, ValueError, LookupError, TypeError, AttributeError): + pass # unreadable or damaged file: start with the servers read so far + for s in self.sessions: s.start() + self.changed() + def save(self): + tmp = self.path('servers.json.tmp') + with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), 'w', encoding='utf-8') as f: + json.dump({'version': 1, 'servers': [s.cfg.to_json() for s in self.sessions]}, f, indent=4) + os.replace(tmp, self.path('servers.json')) + def add(self, cfg): + s = self.attach(cfg) + self.save() + s.start() + self.changed() + return s + def update(self, cfg): + s = self.session(cfg.id) + if s: + s.set_config(cfg) + self.save() + self.changed() + def remove(self, server_id, delete_history): + s = self.session(server_id) + if not s: return + self.sessions.remove(s) + s.alert.clear() + s.close() + if delete_history: shutil.rmtree(s.store.dir, ignore_errors=True) + self.save() + self.changed() + def move(self, server_id, delta): + i = self.sessions.index(self.session(server_id)) + j = min(max(i + delta, 0), len(self.sessions) - 1) + if i != j: + self.sessions.insert(j, self.sessions.pop(i)) + self.save() + self.changed() + def clear_alerts(self): + self.alerts.clear() + self.cleared() + def close(self): + for s in self.sessions: s.close() diff --git a/Server Monitor(python-linux)/tabs.py b/Server Monitor(python-linux)/tabs.py new file mode 100644 index 0000000000000000000000000000000000000000..9b4520ec421bb4a806046a3286ec174e30dd6a2d --- /dev/null +++ b/Server Monitor(python-linux)/tabs.py @@ -0,0 +1,654 @@ +"""Detail-page tabs: each one shows an aspect of the bound server session.""" +import copy, math, time, tkinter as tk +from datetime import datetime +from tkinter import filedialog + +import plat +from history import (CPU, DISK, DISKIO, GPU, IOWAIT, KEYS, LOAD, MEM, NAMES, PROCS, RD, RX, STEP, SWAP, TEMP, TIER_NAMES, TX, WR, fmt_metric, + stats) +from model import (RULE_ACTIONS, RULE_METRICS, TRANSPORTS, Rule, catalogue, command, count, default_rules, duration, fmt_bytes, new_id, pct, rate, + temp) +from widgets import (C, Cell as X, Chart, CoreGrid, Dialog, Entry, F, Gauge, Heatmap, KeyValues, Scroll, SegmentBar, Spin, Table, ask, box, + button, check, choose, combo, decimals, down, field, health, label, level, mix, panel, pct0, popup, press, right, severity, + spread, textbox, tiles, tip, write) + +class Tab(tk.Frame): + """One aspect of the bound session s. save(config) persists config edits.""" + span = 15 * 60000 # live chart window + def __init__(self, parent, save): + super().__init__(parent, bg=C.bg) + self.s, self.save = None, save + self.build() + def page(self, scroll=True): + """Padded root for the content; scrolls when the tab is taller than the window.""" + if scroll: return down(box(down(Scroll(self), 0, fill='both', expand=True).body), 0, fill='both', expand=True, padx=(4, 10), pady=16) + return down(box(self), 0, fill='both', expand=True, padx=4, pady=(16, 12)) + def attach(self, s): self.s = s + def refresh(self): """A new sample arrived (called only while the tab is visible).""" + def analysis(self): """The analyzer ran.""" + def run(self, cmd, status): + """Runs a command and reports the result in a status label.""" + status.config(text='Running: ' + cmd, fg=C.muted) + self.s.exec(cmd, True, lambda code, out: status.winfo_exists() and status.config( + text=f'✗ {cmd}: {out.strip()[:300]}' if code else f'✓ {cmd}', fg=C.red if code else C.green)) + +def io_wait(live): return [('I/O wait', C.amber, live.s['iowait'])] if plat.POSIX_CPU else [] + +# ============================================================================ Overview +class Overview(Tab): + def build(self): + b = self.page() + gauges = down(panel(b)) + self.g = [Gauge(gauges, name, 85 if name == 'Temperature' else 90) for name in ('CPU', 'Memory', 'Fullest disk', 'Swap', 'Temperature', 'Health')] + spread(self.g, gap=0) # equal widths: all six stay visible in a narrow window + self.t = tiles(b, [('Load average', C.accent), ('Processes', C.violet), ('TCP connections', C.teal), ('Services', C.green), ('Uptime', C.amber)]) + mid = down(box(b), 0) + system = panel(mid, 'System', 330) + system.pack(side='right', fill='y') + self.info = down(KeyValues(system)) + charts = right(box(mid), 14, True) + self.cpu, self.mem = Chart(charts, 'CPU', pct0, 100, stacked=True), Chart(charts, 'Memory', pct0, 100) + self.net, self.io = Chart(charts, 'Network', rate), Chart(charts, 'Disk I/O', rate) + spread([self.cpu, self.mem, self.net, self.io], 2) + def refresh(self): + 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 + g[0].set(m.cpu_usage, sub=f'{m.cpu_count} cores') + g[1].set(m.mem_pct, sub=f'{fmt_bytes(m.mem_used)} / {fmt_bytes(m.mem_total)}') + g[2].set(m.max_disk_pct, sub=m.fullest_mount) + 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') + 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') + g[5].set(a.health, str(a.health), 'grade ' + a.grade, health(a.health)) + 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)) + t[1].set(str(len(m.procs)), f'{m.threads_total} threads · {m.procs_running} running') + t[2].set(str(tcp.get('ESTABLISHED', 0)), f'{tcp.get("LISTEN", 0)} listening · {tcp.get("TIME_WAIT", 0)} time-wait') + 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) + t[4].set(duration(m.uptime), f'{m.logged_users} user(s) logged in') + self.cpu.set(h.t, [('User', C.accent, h.s['user']), ('System', C.violet, h.s['sys'])] + io_wait(h), self.span) + 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) + self.net.set(h.t, [('Down', C.teal, h.s['rx']), ('Up', C.pink, h.s['tx'])], self.span) + self.io.set(h.t, [('Read', C.blue, h.s['rd']), ('Write', C.orange, h.s['wr'])], self.span) + self.info.set([('Hostname', m.hostname), ('OS', m.os), ('Kernel', f'{m.kernel} {m.arch}'), ('CPU', m.cpu_model), + ('Cores', str(m.cpu_count) + (f' @ {m.avg_mhz / 1000:.2f} GHz' if m.avg_mhz > 0 else '')), ('Memory', fmt_bytes(m.mem_total)), + ('Swap', fmt_bytes(m.swap_total) if m.swap_total > 0 else 'none'), ('Virtualisation', m.virt), + ('Disks', f'{len(m.mounts)} mounted file systems'), ('Interfaces', str(len(m.nets))), ('GPU', m.gpus[0].name if m.gpus else 'none'), + ('Connection', f'{c.address()} ({TRANSPORTS[c.transport]})'), ('Sample interval', f'{c.interval} s')]) + +# ============================================================================ CPU +class CpuTab(Tab): + def build(self): + b = self.page() + self.model = down(label(b, kind='H2')) + self.t = tiles(b, [('Usage', C.accent), ('Load 1 / 5 / 15', C.violet), ('Avg frequency', C.teal), (plat.TEXT['cpu_tile'], C.orange), + ('Context switches', C.blue), ('Interrupts', C.pink), ('New processes', C.green), ('Running / blocked', C.amber)], 4) + r = down(box(b)) + self.chart, self.load = Chart(r, 'CPU time breakdown', pct0, 100, 260, True), Chart(r, 'Load average (1 min)', decimals(1), height=260) + spread([self.chart, self.load], weights=(3, 2)) + self.cores = down(CoreGrid(down(panel(b, 'Per core'))), 0) + r = down(box(b), 0) + temps, self.gpu_panel = right(panel(r, 'Temperatures'), 0, True), panel(r, 'GPUs') + self.temps = down(Table(temps, ['Sensor', 'Temperature'], [300], [1]), 0) + self.gpus = down(Table(self.gpu_panel, ['#', 'Name', 'Usage', 'Memory', 'Temp', 'Power', 'Fan'], [40, 220, 120, 160], [2, 3]), 0) + def refresh(self): + m, h, t = self.s.m, self.s.live, self.t + self.model.config(text=m.cpu_model or 'Processor') + 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 ''), + level(m.cpu_usage)) + 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') + t[2].set(f'{m.avg_mhz / 1000:.2f} GHz' if m.avg_mhz > 0 else 'n/a') + value, sub, warn = plat.cpu_tile(m) + t[3].set(value, sub, C.amber if warn else None) + t[4].set(count(m.ctxt_per_sec) + '/s') + t[5].set(count(m.intr_per_sec) + '/s') + t[6].set(f'{m.forks_per_sec:.1f}/s') + t[7].set(f'{m.procs_running} / {m.procs_blocked}', 'blocked = waiting for ' + ('I/O' if plat.POSIX_CPU else 'a CPU'), + C.amber if m.procs_blocked > m.cpu_count else None) + self.chart.set(h.t, [('User', C.accent, h.s['user']), ('System', C.violet, h.s['sys'])] + io_wait(h) + + ([('Steal', C.red, h.s['steal'])] if plat.POSIX_CPU else []), self.span) + self.load.set(h.t, [('Load', C.violet, h.s['load']), ('Cores', C.faint, [m.cpu_count] * len(h.t), False, True)], self.span) + self.cores.set(m.cores) + self.temps.set([[x.name, X(temp(x.celsius), pct=min(100, x.celsius))] for x in m.temps] + or [[X('No temperature sensors exposed (common on VMs)', C.muted)]]) + if bool(m.gpus) != bool(self.gpu_panel.winfo_manager()): + right(self.gpu_panel, 0, True, padx=(14, 0)) if m.gpus else self.gpu_panel.pack_forget() + self.gpus.set([[str(g.index), g.name, X(pct(g.util, 0), pct=g.util), + 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), + X(temp(g.temp), level(g.temp, 75, 88)), f'{g.power:g} W', pct(g.fan, 0)] for g in m.gpus]) + +# ============================================================================ Memory +class MemoryTab(Tab): + def build(self): + b = self.page() + self.t = tiles(b, [('Used', C.violet), ('Available', C.green), ('Cache + buffers', C.blue), ('Swap used', C.pink)]) + composition = down(panel(b, 'Composition')) + self.bar = down(SegmentBar(composition), 10) + down(label(composition, 'SWAP', 'Section'), 10) + self.swap = down(SegmentBar(composition), 0) + r = down(box(b)) + details = panel(r, 'Details', 300) + details.pack(side='right', fill='y') + self.detail = down(KeyValues(details)) + self.chart = right(Chart(r, 'Memory usage', pct0, 100, 280), 14, True) + self.top = down(Table(down(panel(b, 'Top memory consumers'), 0), ['PID', 'Process', 'User', 'RSS', 'Memory %', 'Virtual'], + [80, 220, 120, 110, 160], [4], height=360), 0) + def refresh(self): + m, h, t, free = self.s.m, self.s.live, self.t, mix(C.grid, '#ffffff', .18) + t[0].set(fmt_bytes(m.mem_used), f'{pct(m.mem_pct)} of {fmt_bytes(m.mem_total)}', level(m.mem_pct)) + t[1].set(fmt_bytes(m.mem_available), 'free ' + fmt_bytes(m.mem_free)) + t[2].set(fmt_bytes(m.cached + m.buffers), 'reclaimable when needed') + 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 '', + level(m.swap_pct, 40, 80)) + self.bar.set([(max(0.0, m.mem_total - m.mem_free - m.cached - m.buffers), C.violet, 'Applications'), (m.shared, C.pink, 'Shared'), + (m.buffers, C.teal, 'Buffers'), (max(0.0, m.cached - m.shared), C.blue, 'Cache'), (m.mem_free, free, 'Free')], m.mem_total) + self.swap.set([(m.swap_used, C.pink, 'Used'), (m.swap_total - m.swap_used, free, 'Free')], m.swap_total) + 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) + self.detail.set([(k, fmt_bytes(v)) for k, v in ( + ('Total', m.mem_total), ('Used', m.mem_used), ('Available', m.mem_available), ('Free', m.mem_free), ('Buffers', m.buffers), + ('Cached', m.cached), ('Shared', m.shared), ('Slab', m.slab), ('Dirty', m.dirty), ('Swap total', m.swap_total), ('Swap used', m.swap_used))]) + 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)), + X(fmt_bytes(p.vsz), C.muted, True)] for p in sorted(m.procs, key=lambda p: -p.rss)[:15]]) + +# ============================================================================ Storage +class StorageTab(Tab): + def build(self): + b = self.page() + self.t = tiles(b, [('Fullest file system', C.amber), ('Read', C.blue), ('Write', C.orange), ('Busiest disk', C.red)]) + self.mounts = down(Table(down(panel(b, 'File systems')), ['Mount point', 'Device', 'Type', 'Size', 'Used', 'Free', 'Usage'], + [260, 140, 80, 110, 110, 110], [6]), 0) + self.io = down(Chart(b, 'Disk throughput', rate, height=260)) + self.disks = down(Table(down(panel(b, 'Block devices'), 0), ['Device', 'Read/s', 'Write/s', 'Read IOPS', 'Write IOPS', 'Busy', 'Total read', + 'Total written'], [110, 110, 110, 100, 100, 150, 120], [5], height=200), 0) + def refresh(self): + m, h, t = self.s.m, self.s.live, self.t + t[0].set(pct(m.max_disk_pct), m.fullest_mount, level(m.max_disk_pct, 80, 90)) + t[1].set(rate(m.disk_read_bps)) + t[2].set(rate(m.disk_write_bps)) + t[3].set(pct(m.max_disk_util), m.busiest_disk, level(m.max_disk_util, 60, 90)) + self.io.set(h.t, [('Read', C.blue, h.s['rd']), ('Write', C.orange, h.s['wr'])], self.span) + 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), + X(fmt_bytes(x.avail), right=True), X(pct(x.pct), pct=x.pct)] for x in m.mounts]) + 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), + 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), + X(fmt_bytes(d.total_written), C.muted, True)] for d in m.disks]) + +# ============================================================================ Network +class NetworkTab(Tab): + def build(self): + b = self.page() + self.t = tiles(b, [('Download', C.teal), ('Upload', C.pink), ('Established', C.accent), ('Listening', C.green), + ('Time-wait / close-wait', C.amber), ('Sockets in use', C.violet)]) + r = down(box(b)) + right(label(r, 'Interface', 'Muted')) + self.iface = right(combo(r, ['All physical (total)'], 28, self.refresh), fill='none') + self.chart = down(Chart(b, 'Traffic', rate, height=280)) + self.tbl = down(Table(down(panel(b, 'Interfaces'), 0), ['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], height=240), 0) + def refresh(self): + m, h, t, tcp = self.s.m, self.s.live, self.t, self.s.m.tcp + t[0].set(rate(m.net_rx_bps), 'physical interfaces') + t[1].set(rate(m.net_tx_bps)) + t[2].set(str(tcp.get('ESTABLISHED', 0)), 'TCP') + t[3].set(str(tcp.get('LISTEN', 0)), 'open TCP ports') + t[4].set(f'{tcp.get("TIME_WAIT", 0)} / {tcp.get("CLOSE_WAIT", 0)}', 'many close-wait = app not closing sockets', + C.amber if tcp.get('CLOSE_WAIT', 0) > 100 else None) + t[5].set(str(m.sockets_used)) + names = ['All physical (total)'] + [n.name for n in m.nets] + if list(self.iface['values']) != names: + current = self.iface.get() + self.iface.config(values=names) + self.iface.current(names.index(current) if current in names else 0) + name, total = self.iface.get(), self.iface.current() <= 0 + self.chart.title = 'Traffic — ' + ('all physical interfaces' if total else name) + self.chart.set(h.t, [('Down', C.teal, h.s['rx'] if total else h.if_rx.get(name, [])), + ('Up', C.pink, h.s['tx'] if total else h.if_tx.get(name, []))], self.span) + + def row(x): + dim = C.muted if x.virt else '' + return [X(x.name + (' (virtual)' if x.virt else ''), dim), X(x.state, {'up': C.green, 'down': C.red}.get(x.state, C.muted)), + 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), + 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), + 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)] + self.tbl.set([row(x) for x in m.nets]) + +# ============================================================================ list tabs (processes, services) +class ListTab(Tab): + """Filterable, sortable table that keeps the selection across refreshes; rows are lists of Cell.""" + def build_list(self, headers, widths, bars, hint, sort): + b = self.page(False) + self.bar, self.rows = down(box(b), 10), [] + self.actions = box(self.bar) # packed first: in a narrow window the summary gives way, not the buttons + self.actions.pack(side='right') + self.filter = right(Entry(self.bar, hint=hint, width=26)) + self.filter.bind('', lambda e: self.show()) + self.bar.bind('', lambda e: self.filter.config(width=26 if e.width > 1000 else 12)) + self.summary = right(label(self.bar, kind='Muted')) + self.tbl = down(Table(b, headers, widths, bars, sort), 8, fill='both', expand=True) + self.status = down(label(b, kind='Muted'), 0) + def accept(self, row): return True + def show(self, rows=None): + self.rows = self.rows if rows is None else rows + needle = self.filter.text().lower() + self.tbl.set([r for r in self.rows if self.accept(r) and any(needle in c.text.lower() for c in r)]) + +STATES = {'R': ('Running', C.green), 'S': ('Sleeping', C.muted), 'D': ('Disk wait', C.amber), 'Z': ('Zombie', C.red), 'T': ('Stopped', C.red), + 'I': ('Idle', C.muted)} + +class ProcessTab(ListTab): + def build(self): + self.build_list(['PID', 'Name', 'User', 'State', 'CPU', 'Memory', 'RSS', 'Threads', plat.TEXT['priority'], 'Running for'], + [80, 230, 120, 100, 130, 130, 100, 80, 70], [4, 5], 'Filter by name, user or PID…', (4, True)) + self.freeze = check(self.bar, 'Freeze list') + tip(self.freeze, "Stop refreshing so rows don't move while you pick one").pack(side='left', after=self.filter, padx=(0, 10)) + menu = [] + for verb, cmd, flags in plat.PROC_ACTIONS: + menu.append((verb, lambda verb=verb, cmd=cmd, flags=flags: self.signal(verb, cmd, 'c' in flags))) + if 'b' in flags: right(button(self.actions, verb, menu[-1][1], 'Danger' if 'd' in flags else None), 6) + right(button(self.actions, 'Priority…', self.priority), 0) + self.tbl.on_menu = lambda e: popup(self, e, menu + [None, ('Change priority…', self.priority)]) + def attach(self, s): + if s is not self.s: self.freeze.var.set(False) # a frozen list would show the other server's PIDs + self.s = s + def refresh(self): + if self.freeze.var.get(): return + m = self.s.m + + def row(p): + state, color = STATES.get(p.state, (p.state, C.muted)) + raised = plat.priority_level(p.nice) + 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), + 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), + 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)] + self.show([row(p) for p in m.procs]) + self.summary.config(text=f'{len(m.procs)} processes · {sum(p.state == "R" for p in m.procs)} running · {m.threads_total} threads') + def selected(self): + """(pid, 'name (pid)') of the selected process, or None after a hint in the status line.""" + row = self.tbl.row() + if row: return row[0].text, f'{row[1].text} ({row[0].text})' + self.status.config(text='Select a process first.', fg=C.muted) + def signal(self, verb, cmd, confirm): + sel = self.selected() + 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) + def priority(self): + sel = self.selected() + choice = sel and choose(self, 'Change priority', f'Priority for {sel[1]}:', [(k, None) for k in plat.PRIORITIES] + [('Cancel', 'Flat')]) + if choice in plat.PRIORITIES: self.run(command(plat.PRIORITY_CMD.replace('{v}', str(plat.PRIORITIES[choice])), sel[0]), self.status) + +class ServiceTab(ListTab): + def build(self): + self.build_list(['Service', 'Active', 'State', 'Load', 'Description'], [300, 100, 100, 90], [], 'Filter services…', (0, False)) + self.state, self.shown = combo(self.bar, ['All', 'Running', 'Failed', 'Not running'], 12, self.show), None + self.state.pack(side='left', after=self.filter, padx=(0, 10)) + menu = [(verb.capitalize(), lambda verb=verb: self.act(verb)) for verb in plat.SERVICE_VERBS] + for text, act in menu: right(button(self.actions, text, act, 'Danger' if text in ('Stop', 'Disable') else None), 6) + right(button(self.actions, 'Logs', self.logs, 'Primary'), 0) + self.tbl.on_open = self.logs + self.tbl.on_menu = lambda e: popup(self, e, menu + [None, ('Show logs', self.logs)]) + def attach(self, s): self.s, self.shown = s, None + def accept(self, row): + active, sub, state = row[1].text, row[2].text, self.state.current() + return state == 0 or (state == 1 and sub == 'running') or (state == 2 and active == 'failed') or (state == 3 and sub != 'running' and active != 'failed') + def refresh(self): + m = self.s.m + shown = [(x.unit, x.active, x.sub) for x in m.services] + if shown == self.shown: # unchanged: keep the list still + return + self.shown = shown + + def row(x): + c = C.red if x.active == 'failed' else C.green if x.sub == 'running' else C.teal if x.active == 'active' else C.muted + return [X(x.unit), X(x.active, c), X(x.sub, c), X(x.load, C.muted), X(x.description, C.muted)] + self.show([row(x) for x in m.services]) + self.summary.config(text=f'{len(m.services)} services · {m.services_running} running · {m.services_failed} failed' if m.services + else 'No services reported by this machine') + def act(self, verb): + unit = self.tbl.row() and self.tbl.selected + if not unit: return self.status.config(text='Select a service first.', fg=C.muted) + if verb not in ('stop', 'disable', 'restart') or ask(self, 'Confirm', f'{verb.capitalize()} {unit} on {self.s.cfg.name}?'): + self.run(command(plat.SERVICE_VERBS[verb], unit), self.status) + def logs(self): + s, unit = self.s, self.tbl.row() and self.tbl.selected + if not unit: return + d = Dialog(self, f'Logs — {unit} — {s.cfg.name}') + d.geometry('1000x640') + text = textbox(d) + write(text, 'Loading…') + down(text.frame, 12, fill='both', expand=True) + r = down(box(d), 0) + lines = right(Spin(r, 50, 5000, 300), 6) + right(label(r, 'lines', 'Muted')) + + def load(): + s.exec(command(plat.SERVICE_LOGS, unit, lines.value()), True, lambda code, out: text.winfo_exists() and write(text, out, clear=True)) + right(button(r, 'Reload', load)) + button(r, 'Close', d.close).pack(side='right') + load() + +# ============================================================================ Console +class ConsoleTab(Tab): + def build(self): + b = self.page(False) + side = Scroll(b) # the command lists scroll in a low window + side.cv.config(width=288) + side.pack(side='right', fill='y', padx=(14, 0)) + self.out, self.history, self.pos = textbox(b), [], 0 + down(self.out.frame, 10, fill='both', expand=True) + r = down(box(b), 0) + right(label(r, '$', fg=C.accent, font=F(15, True))) + self.cmd = right(Entry(r, hint=plat.TEXT['console_hint'], mono=True), grow=True) + self.privileged = check(r, 'privileged') + if plat.HAS_SUDO: right(tip(self.privileged, plat.TEXT['privileged_tip'])) + right(button(r, 'Run', self.enter, 'Primary')) + right(button(r, 'Clear', lambda: write(self.out, '', clear=True)), 0) + for key, handler in (('', self.enter), ('', lambda: self.recall(-1)), ('', lambda: self.recall(1))): + self.cmd.bind(key, lambda e, handler=handler: handler()) + for title, items, system in (('Quick diagnostics', plat.QUICK, False), ('System actions', plat.ACTIONS, True)): + p = down(panel(side.body, title, 270)) + for text, cmd in items: + tip(down(button(p, text, lambda text=text, cmd=cmd, system=system: self.quick(text, cmd, system), + 'Danger' if text in plat.POWER else 'Side', pady=3), 6), cmd) + def attach(self, s): + if s is self.s: return + self.s = s + write(self.out, '', clear=True) + 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) + def enter(self): + cmd = self.cmd.text().strip() + if cmd: + if self.history[-1:] != [cmd]: self.history.append(cmd) + self.pos = len(self.history) + self.cmd.put('') + self.exec(cmd, self.privileged.var.get()) + def recall(self, step): + if self.history: + self.pos = min(max(self.pos + step, 0), len(self.history)) + self.cmd.put((self.history + [''])[self.pos]) + def quick(self, text, cmd, system): + danger = text in plat.POWER + question = f'{text} on {self.s.cfg.name}?' + ('\n\nThe machine will be unavailable until it comes back.' if danger else '') + if not system or ask(self, text, question, danger): self.exec(cmd, system) + def exec(self, cmd, privileged): + out, t0 = self.out, time.monotonic() + write(out, f'\n{time.strftime("%H:%M:%S")} $ ', C.accent) + write(out, cmd + '\n') + + def done(code, text): + if out.winfo_exists(): + write(out, text.rstrip('\n') + '\n' if text else '') + write(out, f'[exit {code} · {(time.monotonic() - t0) * 1000:.0f} ms]\n', C.red if code else C.green) + self.s.exec(cmd, privileged, done, 120) + +# ============================================================================ Alert rules +class RulesTab(Tab): + def build(self): + b = self.page(False) + 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; ' + 'if it is still true after the cooldown the action runs again. History-based automation lives in the Insights tab.', 'Muted', True), 10) + r = down(box(b), 10) + right(button(r, '+ Add rule', lambda: self.edit(-1), 'Primary')) + right(button(r, 'Edit', lambda: self.edit(self.index()))) + 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')) + button(r, 'Reset to defaults', lambda: ask(self, 'Reset rules', 'Replace all rules with the defaults?') and self.store(default_rules())).pack(side='right') + self.rules = down(Table(b, ['On', 'Condition', 'Severity', 'Action', 'Cooldown', 'Live value'], [50, 380, 100, 330, 100]), 10, fill='both', expand=True) + self.active = down(Table(b, ['Active problems'], height=128), 0) + self.rules.on_open = lambda: self.edit(self.index()) + self.rules.on_click = lambda i, col: col == 0 and self.toggle(i) + def attach(self, s): + self.s = s + if s: self.refresh() + def index(self): + """Index of the selected rule, -1 without a selection.""" + return self.rules.selected if self.rules.row() else -1 + def store(self, rules): + c = copy.copy(self.s.cfg) + c.rules = rules + self.save(c) + self.refresh() + def toggle(self, i): + rules = copy.deepcopy(self.s.cfg.rules) + rules[i].enabled = not rules[i].enabled + self.store(rules) + def refresh(self): + s, rows = self.s, [] + for i, r in enumerate(s.cfg.rules): + v = s.metric_value(r.metric) + hit = v < r.value if r.op == '<' else v > r.value + 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), + X(r.severity, severity(r.severity)), + X(r.action_text(), C.muted if r.action == 'notify' else C.violet), X(f'{r.cooldown} s', C.muted), + X(f'{v:.1f} {catalogue(RULE_METRICS, r.metric, 2)}', C.red if hit else C.green)]) + self.rules.set(rows) + self.active.set([[X('⚠ ' + a, C.red)] for a in s.active_alerts()] or [[X('✓ No rule is currently triggered', C.green)]]) + def edit(self, i): + rules = copy.deepcopy(self.s.cfg.rules) + r = rules[i] if 0 <= i < len(rules) else Rule(new_id()) + d = Dialog(self, 'Edit rule' if r in rules else 'New rule') + f = down(box(d)) + metric = field(f, 'When', combo(f, [m[1] + (f' ({m[2]})' if m[2] else '') for m in RULE_METRICS], 34)) + condition = field(f, 'is', box(f)) + op, value = right(combo(condition, ['>', '<'], 3)), right(Spin(condition, -1e9, 1e9, r.value, .5), 0, True) + hold = field(f, 'for at least (s)', Spin(f, 0, 86400, r.duration)) + level_ = field(f, 'Severity', combo(f, ['info', 'warning', 'critical'])) + action = field(f, 'Then', combo(f, [a[1] for a in RULE_ACTIONS], 34, lambda: sync())) + arg = field(f, 'Argument', Entry(f, r.arg)) + cooldown = field(f, 'Repeat after (s)', Spin(f, 10, 86400, r.cooldown)) + enabled = field(f, '', check(f, 'Enabled', r.enabled)) + 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), + (op, ['>', '<'], r.op), (level_, ['info', 'warning', 'critical'], r.severity)): + w.current(values.index(current) if current in values else 0) + + def sync(): # only some actions take an argument + hint = RULE_ACTIONS[action.current()][2] + arg.config(state='normal') + arg.put(arg.text(), hint) + arg.config(state='normal' if hint else 'disabled') + + def ok(): + r.metric, r.op, r.severity, r.action = RULE_METRICS[metric.current()][0], op.get(), level_.get(), RULE_ACTIONS[action.current()][0] + r.value, r.duration, r.cooldown, r.enabled = float(value.value()), hold.value(), cooldown.value(), enabled.var.get() + r.arg = arg.text().strip() if RULE_ACTIONS[action.current()][2] else '' + d.close(True) + + sync() + d.buttons(('Cancel', d.close), ('OK', ok, 'Primary')) + if d.run(): self.store(rules if r in rules else rules + [r]) + +# ============================================================================ History +RANGES = (('1 h', 3600), ('6 h', 21600), ('24 h', 86400), ('7 d', 604800), ('30 d', 2592000), ('90 d', 7776000), ('1 y', 31536000), ('All', 0)) +# chart series: (metric, peak instead of average); metric -1 = availability +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)) + +class HistoryTab(Tab): + def build(self): + b = self.page() + r = down(box(b)) + self.range, self.loaded, self.pts = 86400, 0, None + button(r, 'Export CSV…', self.export).pack(side='right', anchor='n') # packed first: in a narrow window the summary wraps instead + self.ranges = {sec: right(button(r, text, lambda sec=sec: self.pick(sec)), 6, fill='none', anchor='n') for text, sec in RANGES} + press(self.ranges[self.range], True) + self.res = right(label(r, kind='Muted', wrap=True), 0, True, padx=8) + g = down(box(b)) + self.charts = [Chart(g, title, fmt, ymax, 240, empty='No history for this range yet') for title, fmt, ymax in ( + ('CPU', pct0, 100), ('Memory & swap', pct0, 100), ('Disk usage (fullest)', pct0, 100), ('Disk throughput', rate, 0), ('Network', rate, 0), + ('Load average', decimals(1), 0), ('Temperature', lambda v: f'{v:.0f}°', 0), ('Availability', pct0, 100))] + spread(self.charts, 2) + self.stats = down(Table(down(panel(b, 'Statistics for the selected range'), 0), ['Metric', 'Minimum', 'Average', '95th percentile', 'Peak', 'Points'], + [200, 150, 150, 150, 150], height=14 * 30 + 34), 0) + def attach(self, s): self.s, self.loaded = s, 0 + def pick(self, sec): + press(self.ranges[self.range], False) + self.range = sec + press(self.ranges[sec], True) + self.reload() + def refresh(self): + if time.time() - self.loaded >= (5 if 0 < self.range <= 21600 else 60): self.reload() + def reload(self): + s, self.loaded = self.s, time.time() + now = int(self.loaded) + frm = now - self.range if self.range else max(1, s.store.first_ts()) + p, tier = s.store.span(frm, now) + self.pts = p + step, t, v = max(STEP[tier], s.cfg.interval), [], [[] for _ in SERIES] + + def push(ts, i=None): # without a point index: a gap + t.append(ts * 1000) + for col, (m, peak) in zip(v, SERIES): + 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) + + for i, ts in enumerate(p.ts): + if t and ts * 1000 - t[-1] > step * 3000: # the app was not running + push(t[-1] // 1000 + step) + push(ts, i) + if t and now * 1000 - t[-1] > step * 3000: push(now) + cpu, cpu_max, mem, swap, disk, rd, wr, rx, tx, rx_max, load, temp_, temp_max, avail = v + 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)] + cpu_peak, rx_peak, temp_peak = peak if tier else ([], [], []) # aggregated tiers also show the peaks + data = ([('Average', C.accent, cpu)] + cpu_peak, [('Memory', C.violet, mem), ('Swap', C.pink, swap, False)], [('Usage', C.amber, disk)], + [('Read', C.blue, rd), ('Write', C.orange, wr)], [('Down', C.teal, rx), ('Up', C.pink, tx)] + rx_peak, [('Load', C.violet, load)], + [('Average', C.orange, temp_)] + temp_peak, [('Online', C.green, avail)]) + for chart, series in zip(self.charts, data): + chart.subtitle = f'avg per {TIER_NAMES[tier]}' if tier else '' + chart.set(t, series, (now - frm) * 1000) + n, up = sum(p.n), sum(p.up) + self.res.config(text=f'Resolution: {TIER_NAMES[tier]} · {len(p)} points · availability {pct(up * 100 / n, 2) if n else "—"}' + f' · stored {fmt_bytes(s.store.disk_bytes())}') + + def row(m): + x = stats(p, m) + 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), + X(fmt_metric(m, x.max), C.red, True), X(str(x.count), C.muted, True)] + 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]) + def export(self): + name = filedialog.asksaveasfilename(parent=self, title='Export history', initialfile=f'{self.s.cfg.name}-history.csv', filetypes=[('CSV', '*.csv')], + defaultextension='.csv') + if not name or self.pts is None: return + with open(name, 'w', encoding='utf-8', newline='\n') as f: + f.write('time,samples,online_pct' + ''.join(f',{k}_avg,{k}_max' for k in KEYS)) + for ts, n, up, *values in self.pts.rows(): + cells = [(values[m], values[len(KEYS) + m]) for m in range(len(KEYS))] + f.write(f'\n{datetime.fromtimestamp(ts).isoformat()},{n},{up * 100 / n if n else 0:g}' + + ''.join(',' + ','.join('' if x != x else f'{x:.3f}' for x in pair) for pair in cells)) + +# ============================================================================ Insights & Autopilot +class InsightsTab(Tab): + def build(self): + b, self.binds, self.loading = self.page(), [], False # binds: (config field, widget getter, widget setter) + top = down(box(b)) + hp = right(panel(top, 'Health', 330), 14) + self.health = down(Gauge(hp, 'Health score'), 10) + self.reasons = down(label(hp, kind='Muted', wrap=296), 10) + down(button(hp, 'Analyze now', lambda: self.s.analyze()), 0) + side = right(box(top), 0, True) + self.t = tiles(side, [('Disk full forecast', C.amber), ('Memory trend (6 h)', C.violet), ('CPU / memory p95 (30 d)', C.accent), + ('Availability 24 h', C.green), ('Availability 7 d', C.green), ('Availability 30 d', C.green)], 3) + self.capacity = down(label(down(panel(side, 'Capacity planning'), 0, fill='both', expand=True), wrap=True), 0) + + mid = down(box(b)) + ap = panel(mid, 'Autopilot — automatic control', 430) + ap.pack(side='right', anchor='n') + 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) + form = down(box(ap), 0) + self.findings = down(box(right(panel(mid, 'Findings from history analysis'), 14, True)), 0) + + def line(*parts): # form row: the first part in the left column, the others side by side in the right one + r, cell = form.grid_size()[1], box(form) + for i, part in enumerate(parts): + w = label(cell if i else form, part, 'Muted') if isinstance(part, str) else part(cell if i else form) + right(w, 6) if i else w.grid(row=r, column=0, sticky='w', padx=(0, 10), pady=4) + cell.grid(row=r, column=1, sticky='w', pady=4) + + tie = self.tie + line(tie('enabled', check, 'Autopilot enabled'), tie('dryRun', check, 'Dry run (only report)')) + line(tie('restartFailed', check, 'Restart failed services'), tie('maxRestartsPerHour', Spin, 1, 20), '/ hour max') + line('Runaway processes', tie('runawayMode', combo, ['Ignore', plat.TEXT['renice_mode'], 'Terminate'], 26, keys=['none', 'renice', 'terminate'])) + line('', '≥', tie('runawayCpu', Spin, 10, 6400), '% for', tie('runawayMinutes', Spin, 1, 1440), 'min') + line('Memory leaks', tie('leakMode', combo, ['Ignore', 'Notify', 'Terminate under pressure'], 26, keys=['none', 'notify', 'terminate'])) + line(' pressure ≥', tie('leakMemPressure', Spin, 50, 100), '% memory') + line(tie('diskCleanup', check, 'Disk cleanup'), 'full in <', tie('diskForecastDays', Spin, 1, 60), 'days') + line('', 'or usage ≥', tie('diskCleanupAt', Spin, 50, 100), '%') + line(' command', tie('diskCleanupCommand', Entry, width=34, mono=True)) + line(tie('anomalyAlerts', check, 'Anomaly alerts'), 'z ≥', tie('anomalyZ', Spin, 1.5, 10, step=.5), 'σ') + + bottom = down(box(b), 0) + weekly, usual = panel(bottom, 'Weekly pattern (last 4 weeks, hourly averages)'), panel(bottom, 'Now vs. normal (baselines)') + self.heat_metric = down(combo(weekly, ['CPU', 'Memory'], 12, self.analysis), 10, fill='none', anchor='w') + self.heat = down(Heatmap(weekly), 0, fill='both', expand=True) + self.anomalies = down(Table(usual, ['Metric', 'Last 10 min', 'Usual', 'Deviation', 'Baseline'], [110, 110, 160, 90], height=230), 0) + spread([weekly, usual], weights=(3, 2)) + def tie(self, name, make, *args, keys=None, **kw): + """Factory for a form widget bound to an AutopilotConfig field; every change is stored.""" + def create(parent): + if make is Entry: + w = Entry(parent, **kw) + w.bind('', lambda e: self.store(), add='+') + w.bind('', lambda e: self.store()) + self.binds.append((name, lambda: w.text().strip(), w.put)) + else: + w = make(parent, *args, command=self.store, **kw) + self.binds.append((name, w.var.get, w.var.set) if make is check else (name, w.value, w.put) if make is Spin + else (name, lambda: keys[w.current()], lambda v: w.current(keys.index(v) if v in keys else 0))) + return w + return create + def attach(self, s): + self.s = s + if s: + self.loading = True + for name, _, put in self.binds: put(getattr(s.cfg.autopilot, name)) + self.loading = False + def store(self): + if self.loading or not self.s: return + c = copy.deepcopy(self.s.cfg) + for name, get, _ in self.binds: setattr(c.autopilot, name, type(getattr(c.autopilot, name))(get())) + if c.autopilot != self.s.cfg.autopilot: self.save(c) + def analysis(self): + s, a, t, hi = self.s, self.s.an, self.t, self.heat_metric.current() + self.health.set(a.health, str(a.health), 'grade ' + a.grade, health(a.health)) + self.reasons.config(text=('\n'.join(a.reasons) or 'No deductions — everything looks healthy.') + + (f'\n\nAnalyzed {time.strftime("%H:%M:%S", time.localtime(a.when))}' if a.when else '')) + if a.disk_full_days >= 0: + t[0].set(duration(a.disk_full_days * 86400), f'+{a.disk_slope_per_day:.2f} pts/day · {a.disk_basis}', + C.red if a.disk_full_days < 7 else C.amber if a.disk_full_days < 30 else None) + else: + 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) + if a.mem_trend_r2 > 0: + 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) + else: + t[1].set('—', 'needs ~90 min of history') + 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)}') + else: t[2].set('—', 'collecting') + for tile, up, off in zip(t[3:], a.up, a.down): + if up != up: tile.set('—', 'no data yet') + 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) + self.capacity.config(text='\n\n'.join('• ' + c for c in a.capacity)) + self.heat.set(a.heat[hi], a.heat_n, '% memory' if hi else '% CPU', C.violet if hi else C.accent) + 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), + 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)] + for x in a.anomalies]) + + for w in self.findings.winfo_children(): # rebuild the finding cards + w.destroy() + if not a.findings: + down(label(self.findings, '✓ No problems found in the history. The analyzer checks disk forecasts, memory trends, leaks, runaway processes, ' + 'service failures, overload and anomalies every minute.', wrap=True, fg=C.green), 0) + ap = s.cfg.autopilot + for f in a.findings: + color = severity(f.severity) + card = down(tk.Frame(self.findings, bg=C.card, highlightthickness=1, highlightbackground=C.border), 10) + right(tk.Frame(card, bg=color, width=4), 0) + if f.action: + b = button(card, f.label, kind='Danger' if f.action == 'kill_pid' else 'Primary') + b.config(command=lambda f=f, b=b: self.fix(f, b)) + b.pack(side='right', padx=12) + text = right(box(card), 0, True, padx=12, pady=10) + down(label(text, f'{f.severity.upper()} · {f.category.upper()}', fg=color, font=F(11, True)), 2) + down(label(text, f.title, wrap=True, font=F(14, True)), 2) + down(label(text, f.detail, wrap=True), 2) + down(label(text, '→ ' + f.advice, 'Muted', True), 0) + if f.auto and ap.enabled: + down(label(text, 'Autopilot (dry run) would act on this' if ap.dryRun else 'Autopilot handles this automatically', 'Small', fg=C.violet), 0) + def fix(self, f, b): + if ask(self, f.label, f'{f.label} on {self.s.cfg.name}?\n\n{f.title}', f.action == 'kill_pid'): + if b.winfo_exists(): # the card may have been rebuilt while the question was open + b.config(state='disabled', text='Working…') + self.s.run_finding(f, False, lambda code, out: b.winfo_exists() and b.config(text='✗ Failed' if code else '✓ Done')) + +TABS = (('Overview', Overview), ('CPU', CpuTab), ('Memory', MemoryTab), ('Storage', StorageTab), ('Network', NetworkTab), ('Processes', ProcessTab), + ('Services', ServiceTab), ('History', HistoryTab), ('Insights & Autopilot', InsightsTab), ('Alert rules', RulesTab), ('Console', ConsoleTab)) diff --git a/Server Monitor(python-linux)/ui.py b/Server Monitor(python-linux)/ui.py new file mode 100644 index 0000000000000000000000000000000000000000..c5af8f8d1dc853b81754b600abf6fa3c131400a7 --- /dev/null +++ b/Server Monitor(python-linux)/ui.py @@ -0,0 +1,474 @@ +"""Main window: sidebar, dashboard with server cards, server detail page, events page, add / edit dialog.""" +import copy, json, os, time, tkinter as tk +from tkinter import filedialog + +import plat +from model import ServerConfig, TRANSPORTS, duration, fmt_bytes, new_id, pct, rate +from session import DISABLED, OFFLINE, STATUS, Link, Timer, loop +from tabs import TABS +from widgets import (C, Cell, Chips, Dialog, Entry, F, FIELD, Paint, Scroll, Spin, Table, Tabs, app_icon, ask, box, button, check, choose, combo, down, + elide, field, health, label, level, mix, on_wheel, panel, popup, press, right, severity, textbox, theme, tiles, write) + +STATUS_COLORS = (C.faint, C.amber, C.green, C.red) # disabled, connecting, online, offline + +# ============================================================================ dashboard cards +class Card(Paint): + def __init__(self, parent, on_click): + super().__init__(parent, 340, 262, cursor='hand2') + self.over = False + self.bind('', lambda e: self.hover(True)) + self.bind('', lambda e: self.hover(False)) + self.bind('', lambda e: on_click()) + def hover(self, over): + self.over = over + self.redraw() + +class ServerCard(Card): + def __init__(self, parent, s, win): + super().__init__(parent, lambda: win.open(s.cfg.id)) + self.s = s + for signal in (s.updated, s.analysis_updated): + signal.append(self.redraw) + self.bind('', lambda e, signal=signal: signal.remove(self.redraw), add='+') + self.bind('', lambda e: popup(self, e, [('Open details', lambda: win.open(s.cfg.id)), ('Reconnect', s.reconnect), None, + ('Edit…', lambda: win.edit(s.cfg.id)), ('Remove…', lambda: win.remove(s.cfg.id))])) + def draw(self): + s, c, m, an, w = self.s, self.s.cfg, self.s.m, self.s.an, self.w + live, sc, bg = s.online(), STATUS_COLORS[s.status], C.hover if self.over else C.card + self.rrect(1, 1, w - 1, self.h - 1, 14, bg, C.accent if self.over else C.border) + for i in range(12): # status strip fading out to the right + self.create_rectangle(10 + i * w / 20, 2, 11 + (i + 1) * w / 20, 6, width=0, fill=mix(sc, bg, i / 12)) + self.create_oval(17, 23, 27, 33, fill=sc, width=0) + self.text(36, 28, elide(c.name, F(16, True), w - 120), px=16, bold=True) + self.text(36, 47, elide(c.address() + (f' · {m.os}' if m.os else ''), F(11), w - 60), C.muted, 11) + if live: # health badge + self.ring(w - 62, 12, 44, an.health, health(an.health), 4, False) + self.text(w - 40, 34, an.grade, health(an.health), 15, True, 'center') + else: + chip = STATUS[s.status].upper() + cw = F(10, True).measure(chip) + 18 + self.rrect(w - cw - 16, 18, w - 16, 38, 10, mix(bg, sc, .16), sc) + self.text(w - 16 - cw / 2, 28, chip, sc, 10, True, 'center') + hot = bool(m.temps) # four gauges; the last one shows the temperature when there are sensors + gw = (w - 32) / 4 + gs = min(gw - 14, 70) + last = ('Temp', m.max_temp) if hot else ('Swap', m.swap_pct) + for i, (name, v) in enumerate((('CPU', m.cpu_usage), ('Memory', m.mem_pct), ('Disk', m.max_disk_pct), last)): + cx, color = 16 + gw * i + gw / 2, level(v, 70, 85) if hot and i == 3 else level(v) + self.ring(cx - gs / 2, 66, gs, min(100, v) if live else 0, color if live else C.faint, 6, live) + self.text(cx, 66 + gs / 2, f'{v:.0f}' + ('°' if hot and i == 3 else '%') if live else '—', C.text if live else C.faint, 14, True, 'center') + self.text(cx, 70 + gs, name, C.muted, 11, anchor='center') + x0, y0, x1, y1 = 16, 166, w - 16, 210 # CPU + memory sparkline (last 5 min) + spark = mix(bg, '#000000', .16) + self.rrect(x0, y0, x1, y1, 8, spark) + for key, color in (('mem', C.violet), ('cpu', C.accent)): + v = s.live.s[key][-150:] + if len(v) > 1: + line = [(x1 - 4 - (x1 - x0 - 8) * (len(v) - 1 - i) / 149, y1 - 4 - min(max(x, 0), 100) / 100 * (y1 - y0 - 8)) for i, x in enumerate(v)] + self.create_polygon(line + [(line[-1][0], y1 - 2), (line[0][0], y1 - 2)], fill=mix(spark, color, .16), width=0) + self.create_line(line, fill=color, width=1.5) + self.text(x0 + 8, y0 + 10, 'CPU', C.accent, 10) + self.text(x0 + 36, y0 + 10, 'MEM', C.violet, 10) + if not live: + state = {DISABLED: 'Monitoring disabled', OFFLINE: 'Unreachable: ' + s.err}.get(s.status, 'Waiting for data…') + return self.text(16, 218, state, C.red if s.status == OFFLINE else C.muted, 11, anchor='nw', width=w - 32) + self.text(16, 226, '↓ ' + rate(m.net_rx_bps), C.teal, 11) + self.text(116, 226, '↑ ' + rate(m.net_tx_bps), C.pink, 11) + self.text(w - 16, 226, f'load {m.load1:.2f} · up {duration(m.uptime)}', C.muted, 11, anchor='e') + pilot = (' · autopilot (dry run)' if c.autopilot.dryRun else ' · autopilot on') if c.autopilot.enabled else '' + self.text(16, 242, f'{m.cpu_count} cores · {len(m.procs)} procs{pilot}', C.muted, 11) + rules = len(s.active_alerts()) + if rules + len(an.findings): + badge, color = f'⚠ {rules + len(an.findings)}', C.red if rules or any(f.severity == 'critical' for f in an.findings) else C.amber + bw = F(11).measure(badge) + 14 + self.rrect(w - 16 - bw, 233, w - 16, 250, 8, mix(bg, color, .18)) + self.text(w - 16 - bw / 2, 242, badge, color, 11, anchor='center') + +class AddCard(Card): + def draw(self): + color, cx, cy = C.accent if self.over else C.muted, self.w / 2, self.h / 2 - 14 + self.rrect(2, 2, self.w - 2, self.h - 2, 14, mix(C.bg, C.accent, .07) if self.over else '', C.accent if self.over else C.border, width=1.5, dash=(5, 4)) + self.create_line(cx - 14, cy, cx + 14, cy, fill=color, width=3, capstyle='round') + self.create_line(cx, cy - 14, cx, cy + 14, fill=color, width=3, capstyle='round') + self.text(cx, cy + 37, 'Add server', color, 14, True, 'center') + self.text(cx, cy + 57, 'This machine · SSH', C.faint, 11, anchor='center') + +class Flow(tk.Frame): + """Lays its cards out in equally wide columns.""" + def __init__(self, parent): + super().__init__(parent, bg=parent['bg']) + self.cards = [] + self.bind('', lambda e: self.arrange()) + def arrange(self): + gap, width = 16, self.winfo_width() + cols = max(1, (width + gap) // (320 + gap)) + cw = (width - (cols - 1) * gap) // cols + for i, card in enumerate(self.cards): card.place(x=i % cols * (cw + gap), y=i // cols * (262 + gap), width=cw, height=262) + self.config(height=max(1, -(-len(self.cards) // cols) * (262 + gap))) + +# ============================================================================ dashboard +class Dashboard(tk.Frame): + def __init__(self, parent, mgr, win): + super().__init__(parent, bg=C.bg, padx=28, pady=20) + self.mgr, self.win, self.cards = mgr, win, [] + head = down(box(self)) + button(head, '+ Add server', win.add, 'Primary').pack(side='right') + self.search = Entry(head, hint='Search servers…', width=28) + self.search.pack(side='right', padx=10) + self.search.bind('', lambda e: self.filter()) + down(label(head, 'Dashboard', 'H1'), 2) + self.subtitle = down(label(head, kind='Muted'), 0) + self.t = tiles(self, [('Servers online', C.green), ('Avg health', C.teal), ('Active problems', C.red), ('Avg CPU', C.accent), + ('Avg memory', C.violet), ('Total network', C.pink)]) + events = panel(self, 'Recent events', 330) + events.pack(side='right', fill='y') + self.events = textbox(events, False, bg=C.panel, wrap='word', padx=0, pady=0, spacing3=8) + down(self.events.frame, 0, fill='both', expand=True) + self.flow = down(Flow(right(Scroll(self), 14, True).body), 0) + self.add_card = AddCard(self.flow, win.add) + mgr.changed.append(self.rebuild) + mgr.alert.append(lambda e: self.list_events()) + mgr.cleared.append(self.list_events) + def list_events(self): + write(self.events, '', clear=True) + for e in self.mgr.alerts[:200]: write(self.events, f'{e.time:%H:%M:%S} · {e.server}\n{e.message}\n', severity(e.severity)) + self.events.yview_moveto(0) + def rebuild(self): + for card in self.cards: # not destroyed at once: a card's own menu may have caused this + card.place_forget() + card.after_idle(card.destroy) + self.cards = [ServerCard(self.flow, s, self.win) for s in self.mgr.sessions] + self.filter() + self.refresh() + def filter(self): + needle = self.search.text().lower() + for card in self.cards + [self.add_card]: card.place_forget() + self.flow.cards = [c for c in self.cards if needle in ' '.join((c.s.cfg.name, c.s.cfg.host, c.s.cfg.group, c.s.m.hostname)).lower()] + [self.add_card] + self.flow.arrange() + def refresh(self): + t, enabled = self.t, [s for s in self.mgr.sessions if s.cfg.enabled] + up = [s for s in enabled if s.online()] + problems = sum(len(s.active_alerts()) for s in enabled) + sum(f.severity != 'info' for s in up for f in s.an.findings) + self.subtitle.config(text=f'{len(self.mgr.sessions)} server(s) monitored · updated {time.strftime("%H:%M:%S")}') + t[0].set(f'{len(up)} / {len(enabled)}', f'{len(enabled) - len(up)} unreachable' if len(enabled) > len(up) else 'all reachable', + C.green if len(up) == len(enabled) else C.amber) + t[2].set(str(problems), 'alerts + insights' if problems else 'all clear', C.red if problems else C.green) + if not up: + for i in (1, 3, 4, 5): t[i].set('—') + return + score, cpu, mem = (sum(v) / len(up) for v in zip(*((s.an.health, s.m.cpu_usage, s.m.mem_pct) for s in up))) + rx, tx = sum(s.m.net_rx_bps for s in up), sum(s.m.net_tx_bps for s in up) + t[1].set(f'{score:.0f}', 'score 0–100', health(score)) + t[3].set(pct(cpu), color=level(cpu)) + t[4].set(pct(mem), color=level(mem)) + t[5].set(rate(rx + tx), f'↓ {rate(rx)} ↑ {rate(tx)}') + +# ============================================================================ detail page +class Detail(tk.Frame): + def __init__(self, parent, mgr, win): + super().__init__(parent, bg=C.bg, padx=28, pady=16) + self.s, self.win = None, win + head = down(box(self), 6) + actions = box(head) + actions.pack(side='right', anchor='s') + window = right(box(actions)) + down(label(window, 'LIVE WINDOW', 'Section'), 4) + self.span = down(combo(window, ['Last 5 minutes', 'Last 15 minutes', 'Last 30 minutes', 'Last hour'], 16, lambda: self.refresh(False)), 0) + self.span.current(1) + right(button(actions, '⟳ Reconnect', lambda: self.s.reconnect()), anchor='s', fill='none') + self.pause = right(button(actions, '❚❚ Pause', lambda: self.s.set_paused(not self.s.paused)), anchor='s', fill='none') + right(button(actions, 'Edit', lambda: win.edit(self.s.cfg.id)), anchor='s', fill='none') + power = right(button(actions, '⏻ Power', kind='Danger'), 0, anchor='s', fill='none') + power.bind('', lambda e: popup(self, e, [(f'{text}…', lambda text=text, cmd=cmd: self.power(text, cmd)) for text, cmd in plat.POWER.items()] + + [None, ('Remove from monitor…', lambda: win.remove(self.s.cfg.id))])) + down(button(head, '‹ Dashboard', win.show_dashboard, 'Flat', padx=0), 2, fill='none', anchor='w') + names = down(box(head), 2) + self.name, self.state = right(label(names, kind='H1')), right(label(names, font=F(12, True))) + self.sub = down(label(head, kind='Muted', wrap=True), 6) + self.chips = down(Chips(head), 0) + self.tabs = down(Tabs(self, lambda: self.refresh(True)), 0, fill='both', expand=True) + for title, make in TABS: self.tabs.add(title, make(self.tabs, mgr.update)) + def power(self, text, cmd): + if ask(self, f'{text}…', f'{text} {self.s.cfg.name} now?', True): self.s.exec(cmd, True) + def attach(self, s): + if self.s: + self.s.updated.remove(self.update_sample) + self.s.analysis_updated.remove(self.update_analysis) + self.s = s + for tab in self.tabs.pages: tab.attach(s) + if s: + s.updated.append(self.update_sample) + s.analysis_updated.append(self.update_analysis) + self.header() + self.tabs.show(self.tabs.current) + def refresh(self, with_analysis): + tab = self.tabs.pages[self.tabs.current] + if self.s: + tab.span = (5, 15, 30, 60)[self.span.current()] * 60000 + tab.refresh() + if with_analysis: tab.analysis() + def update_sample(self): + if self.winfo_ismapped(): + self.header() + self.refresh(False) + def update_analysis(self): + if self.winfo_ismapped(): + self.header() + self.tabs.pages[self.tabs.current].analysis() + def header(self): + s, c, m, a = self.s, self.s.cfg, self.s.m, self.s.an + self.name.config(text=c.name) + self.state.config(text='● ' + ('PAUSED' if s.paused else STATUS[s.status].upper()), fg=C.amber if s.paused else STATUS_COLORS[s.status]) + self.sub.config(text=f'{c.address()} · {TRANSPORTS[c.transport]}' + (f' · host {m.hostname}' if m.hostname else '') + + (f' · up {duration(m.uptime)}' if s.online() else f' · {s.err}' if s.status == OFFLINE else '')) + chips = [(m.os, ''), (plat.TEXT['kernel'] + m.kernel if m.kernel else '', ''), (f'{m.cpu_count} cores' if m.cpu_count else '', ''), + (f'{fmt_bytes(m.mem_total)} RAM' if m.mem_total > 0 else '', ''), (c.group, '#7dd3fc'), + (f'health {a.health} ({a.grade})' if s.online() else '', health(a.health)), + (('autopilot: dry run' if c.autopilot.dryRun else 'autopilot: on') if c.autopilot.enabled else '', C.violet)] + self.chips.set([(text, color or '#b9c3d8') for text, color in chips if text.strip()]) + self.pause.config(text='▶ Resume' if s.paused else '❚❚ Pause') + +# ============================================================================ add / edit dialog +class ServerDialog(Dialog): + """Edits a copy of a server configuration; run() returns it, or None when cancelled.""" + def __init__(self, parent, cfg, groups): + super().__init__(parent, f'Edit server — {cfg.name}' if cfg.name else 'Add server') + self.cfg, self.link, self.timeout = cfg, None, Timer(lambda: self.tested('✗ Timed out after 20 s', C.red)) + down(label(self, 'Edit server' if cfg.name else 'Add a server', 'H2')) + f = down(box(self)) + self.name = field(f, 'Name', Entry(f, cfg.name, 'e.g. web-01', 50)) + self.group = field(f, 'Group', combo(f, groups, edit=True)) + self.group.set(cfg.group) + self.via = field(f, 'Connect via', combo(f, ['This machine (local)', 'SSH — nothing to install on the server'], command=self.sync)) + self.via.current(cfg.transport) + address, key = field(f, 'Address', box(f)), box(f) + self.host = right(Entry(address, cfg.host, 'hostname or IP address'), grow=True) + right(label(address, 'port', 'Muted'), 6) + self.port = right(Spin(address, 1, 65535, cfg.port), 0) + self.user = field(f, 'User', Entry(f, cfg.user, 'default: your local user name')) + self.key = right(Entry(field(f, 'Private key', key), cfg.keyFile, plat.TEXT['key_hint']), grow=True) + self.browse = right(button(key, 'Browse…', lambda: self.key.put(filedialog.askopenfilename( + parent=self, title='Private key', initialdir=os.path.expanduser('~/.ssh')) or self.key.text())), 0) + self.password = field(f, 'Password', Entry(f, cfg.password, 'optional — keys are recommended', show='•')) + every = field(f, 'Sample every', box(f)) + self.interval = right(Spin(every, 1, 300, cfg.interval), 6) + right(label(every, 's', 'Muted')) + self.sudo = check(f, plat.TEXT.get('sudo', ''), cfg.useSudo) + if plat.HAS_SUDO: field(f, '', self.sudo) + self.enabled = field(f, '', check(f, 'Monitoring enabled', cfg.enabled)) + self.notes = field(f, 'Notes', tk.Text(f, height=3, width=1, font=F(13), **FIELD)) + self.notes.insert('1.0', cfg.notes) + self.hint = down(label(self, kind='Muted', wrap=600)) + r = down(box(self)) + self.test = right(button(r, 'Test connection', self.run_test)) + self.outcome = right(label(r, wrap=440), 0, True) # not .result: that is what run() returns + self.buttons(('Cancel', self.close), ('Save', self.save, 'Primary')) + self.sync() + def collect(self): + c, ssh = copy.deepcopy(self.cfg), self.via.current() + c.name, c.group, c.transport, c.port = self.name.text().strip(), self.group.get().strip(), ssh, self.port.value() + c.host = self.host.text().strip() if ssh else '' + c.user, c.keyFile, c.password, c.interval = self.user.text().strip(), self.key.text().strip(), self.password.text(), self.interval.value() + c.useSudo, c.enabled, c.notes = self.sudo.var.get(), self.enabled.var.get(), self.notes.get('1.0', 'end-1c') + return c + def sync(self): + ssh = self.via.current() == 1 + for w in (self.host, self.port, self.user, self.key, self.browse, self.password): w.config(state='normal' if ssh else 'disabled') + self.hint.config(text=plat.TEXT['ssh_hint'] if ssh else 'Monitors the computer this program runs on. No setup needed.') + if not ssh and not self.name.text(): self.name.put('This computer') + def show(self, text, color): self.outcome.config(text=text, fg=color) + def save(self): + c = self.collect() + if not c.name or (c.transport and not c.host): return self.show('Please enter a name and an address.', C.red) + self.close(c) + def run_test(self): + """Two frames prove that data and rates work.""" + c, state, frames, t0 = self.collect(), {}, [], time.monotonic() + c.interval = 1 + + def frame(raw): + frames.append(plat.parse(raw, state, time.time() * 1000)) + if len(frames) == 2: + m = frames[1] + self.tested(f'✓ Connected in {(time.monotonic() - t0) * 1000:.0f} ms — {m.hostname} · {m.os} · {m.cpu_count} cores · ' + f'{fmt_bytes(m.mem_total)} RAM · CPU {pct(m.cpu_usage, 0)}', C.green) + + self.stop_test() + self.link = Link(c, frame, lambda why: self.tested('✗ ' + why, C.red)) + self.test.config(state='disabled') + self.show('Connecting…', C.amber) + self.timeout.start(20) + self.link.start() + def stop_test(self): + self.timeout.stop() + if self.link: + self.link.close() + self.link = None + def tested(self, text, color): + self.stop_test() + self.show(text, color) + self.test.config(state='normal') + def destroy(self): # also when the app quits while the dialog is open + self.stop_test() + super().destroy() + +# ============================================================================ main window +class ServerList(Paint): + """Sidebar list: one row per server with status dot, name, alert count and mini CPU / memory bars.""" + ROW = 58 + def __init__(self, parent, mgr, win): + super().__init__(parent, 220, 200) + self.mgr, self.current, self.over, self.top = mgr, None, None, 0 + self.bind('', lambda e: self.hover(self.at(e))) + self.bind('', lambda e: self.hover(None)) + self.bind('', lambda e: self.at(e) and win.open(self.at(e).cfg.id)) + self.bind('', lambda e: self.at(e) and popup(self, e, self.menu(self.at(e).cfg.id, win))) + def menu(self, sid, win): + return [('Open', lambda: win.open(sid)), ('Reconnect', lambda: self.mgr.session(sid).reconnect()), None, + ('Move up', lambda: self.mgr.move(sid, -1)), ('Move down', lambda: self.mgr.move(sid, 1)), None, + ('Edit…', lambda: win.edit(sid)), ('Remove…', lambda: win.remove(sid))] + def at(self, e): + i = self.top + e.y // self.ROW + return self.mgr.sessions[i] if i < len(self.mgr.sessions) else None + def hover(self, s): + if s is not self.over: + self.over = s + self.redraw() + def scroll(self, step): + top = min(max(self.top + (step > 0) - (step < 0), 0), max(0, len(self.mgr.sessions) - self.h // self.ROW)) + moved, self.top = top != self.top, top + self.redraw() + return moved + def draw(self): + w = self.w + for i, s in enumerate(self.mgr.sessions[self.top:]): + y, m, alerts = i * self.ROW + 2, s.m, len(s.active_alerts()) + if s.cfg.id == self.current or s is self.over: self.rrect(6, y, w - 6, y + 54, 8, C.select if s.cfg.id == self.current else C.card) + self.create_oval(15.5, y + 13.5, 24.5, y + 22.5, fill=STATUS_COLORS[s.status], width=0) + self.text(32, y + 18, elide(s.cfg.name, F(13, True), w - 82), bold=True) + if alerts: + self.rrect(w - 32, y + 10, w - 12, y + 26, 8, C.red) + self.text(w - 22, y + 18, str(alerts), '#ffffff', 10, True, 'center') + for k, (name, v) in enumerate((('CPU', m.cpu_usage), ('MEM', m.mem_pct))): + by = y + 34 + k * 11 + self.text(32, by, name, C.faint, 9) + self.rrect(62, by - 2, w - 20, by + 2, 2, C.grid) + if s.online() and v >= 1: self.rrect(62, by - 2, 62 + (w - 82) * min(v, 100) / 100, by + 2, 2, level(v)) + +class MainWindow: + def __init__(self, root, mgr): + self.root, self.mgr, self.unseen = root, mgr, 0 + theme(root) + try: + with open(mgr.path('window.json')) as f: geometry = json.load(f)['geometry'] + except (OSError, ValueError, KeyError): + geometry = '1500x940' + root.title('Server Monitor') + root.geometry(geometry) + root.minsize(1100, 700) + self.icons = app_icon(64), app_icon(34) + root.iconphoto(True, self.icons[0]) + root.protocol('WM_DELETE_WINDOW', self.quit) + for event in ('', '', ''): root.bind_all(event, on_wheel) + + side = tk.Frame(root, bg=C.side, width=260, padx=12, pady=16) + side.pack(side='left', fill='y') + side.pack_propagate(False) + brand = down(box(side), 18) + right(tk.Label(brand, image=self.icons[1], bg=C.side)) + down(label(brand, 'Server Monitor', font=F(16, True)), 0) + down(label(brand, 'monitor · analyze · control', 'Small'), 0) + self.nav_dash = down(button(side, '▦ Dashboard', self.show_dashboard, 'Nav', pady=8), 4) + row = down(box(side), 14) + self.badge = tk.Label(row, bg=C.red, fg='#ffffff', font=F(11, True), padx=7) + self.nav_events = right(button(row, '◉ Events & alerts', self.show_events, 'Nav', pady=8), 6, True) + down(label(side, ' SERVERS', 'Section'), 6) + buttons = box(side) + buttons.pack(side='bottom', fill='x') + self.list = down(ServerList(side, mgr, self), 8, fill='both', expand=True) + for i, (text, command, kind) in enumerate((('+ Add', self.add, 'Primary'), ('Edit', lambda: self.edit(self.list.current), None), + ('Remove', lambda: self.remove(self.list.current), 'Danger'))): + button(buttons, text, command, kind, padx=4).grid(row=0, column=i, sticky='ew', padx=(6 if i else 0, 0)) + buttons.columnconfigure(i, weight=1, uniform='buttons') + + self.dash, self.detail, self.events_page = Dashboard(root, mgr, self), Detail(root, mgr, self), tk.Frame(root, bg=C.bg, padx=28, pady=20) + head = down(box(self.events_page)) + button(head, 'Clear list', mgr.clear_alerts).pack(side='right') + button(head, 'Open log folder', lambda: plat.open_folder(mgr.config_dir())).pack(side='right', padx=10) + self.event_filter = combo(head, ['All events', 'critical', 'warning', 'info', 'resolved', 'action'], 12, self.list_events) + self.event_filter.pack(side='right') + down(label(head, 'Events & alerts', 'H1'), 2) + down(label(head, 'Alerts, recoveries, insights and every automatic or manual action, newest first. Also written to alerts.log.', 'Muted'), 0) + self.events = down(Table(self.events_page, ['Time', 'Server', 'Type', 'Message'], [170, 180, 100]), 0, fill='both', expand=True) + self.page = self.dash + + mgr.changed.append(self.list.redraw) + mgr.cleared.append(self.list_events) + mgr.alert.append(self.on_alert) + Timer(self.tick, 1) + self.show_dashboard() + self.pump() + def pump(self): # worker-thread results and timers run on the UI thread + self.root.after(20, self.pump) + loop.pump() + def tick(self): # sidebar bars + dashboard tiles + self.list.redraw() + if self.page is self.dash: self.dash.refresh() + def show(self, page): + self.page.pack_forget() + self.page = page + page.pack(side='left', fill='both', expand=True) + press(self.nav_dash, page is self.dash) + press(self.nav_events, page is self.events_page) + if page is not self.detail: self.list.current = None + self.list.redraw() + def show_dashboard(self): + self.show(self.dash) + self.dash.refresh() + def show_events(self): + self.show(self.events_page) + self.unseen = 0 + self.badge.pack_forget() + self.list_events() + def list_events(self): + kind = self.event_filter.get() if self.event_filter.current() else None + self.events.set([[Cell(f'{e.time:%Y-%m-%d %H:%M:%S}', C.muted, key=i), e.server, Cell(e.severity.upper(), severity(e.severity)), + e.message.replace('\n', ' ')] for i, e in enumerate(self.mgr.alerts) if kind in (None, e.severity)]) + def on_alert(self, e): + if self.page is self.events_page: + self.list_events() + elif e.severity in ('critical', 'warning', 'action'): + self.unseen += 1 + self.badge.config(text=str(self.unseen)) + self.badge.pack(side='left') + def open(self, sid): + if self.mgr.session(sid): + self.detail.attach(self.mgr.session(sid)) + self.show(self.detail) + self.list.current = sid + self.list.redraw() + def dialog(self, cfg): + groups = list(dict.fromkeys(s.cfg.group for s in self.mgr.sessions if s.cfg.group)) + return ServerDialog(self.root, cfg, groups).run() + def add(self): + cfg = self.dialog(ServerConfig(new_id())) + if cfg: self.open(self.mgr.add(cfg).cfg.id) + def edit(self, sid): + cfg = self.mgr.session(sid) and self.dialog(self.mgr.session(sid).cfg) + if cfg: self.mgr.update(cfg) + def remove(self, sid): + s = self.mgr.session(sid) + choice = s and choose(self.root, 'Remove server', f'Stop monitoring "{s.cfg.name}" and remove it from the list?', + [('Cancel', None), ('Remove, keep history files', None), ('Remove + delete history', 'Danger')]) + if choice and choice != 'Cancel': + if self.detail.s is s: + self.detail.attach(None) + self.show_dashboard() + self.mgr.remove(sid, 'delete' in choice) + def quit(self): + try: + with open(self.mgr.path('window.json'), 'w') as f: json.dump({'geometry': self.root.geometry()}, f) + except OSError: + pass + self.mgr.close() + self.root.destroy() diff --git a/Server Monitor(python-linux)/widgets.py b/Server Monitor(python-linux)/widgets.py new file mode 100644 index 0000000000000000000000000000000000000000..d3584f3d849526d172f845f8a5683afdb598bfcf --- /dev/null +++ b/Server Monitor(python-linux)/widgets.py @@ -0,0 +1,711 @@ +"""Theme, hand-drawn widgets (gauges, time charts, bars, tiles, core grid, weekly heatmap, table) +and small builders for labels, buttons, panels, forms and dialogs.""" +import functools, math, time, tkinter as tk +from bisect import bisect_left, bisect_right +from collections import namedtuple +from tkinter import font as tkfont, ttk +from types import SimpleNamespace + +from metrics import num +from model import fmt_bytes + +C = SimpleNamespace( # palette + bg='#0d111c', side='#10151f', panel='#161c2b', card='#1a2133', hover='#20293f', border='#27314a', line='#232c41', grid='#242d42', + field='#111727', select='#17304a', text='#e6ebf5', muted='#8b95ab', faint='#5a657d', accent='#38bdf8', green='#22c55e', amber='#f59e0b', + red='#ef4444', violet='#a78bfa', pink='#f472b6', teal='#2dd4bf', orange='#fb923c', blue='#60a5fa') + +def level(p, warn=70, crit=90): return C.red if p >= crit else C.amber if p >= warn else C.green +def severity(s): return {'critical': C.red, 'warning': C.amber, 'resolved': C.green, 'action': C.violet}.get(s, C.accent) +def health(h): return C.green if h >= 90 else C.teal if h >= 75 else C.amber if h >= 60 else C.orange if h >= 40 else C.red + +def mix(a, b, t): + """Colour between a and b (t = 0..1). A Tk canvas has no transparency, so tints are mixed with the background.""" + t = min(max(t, 0), 1) + return '#%02x%02x%02x' % tuple(round(int(a[i:i + 2], 16) * (1 - t) + int(b[i:i + 2], 16) * t) for i in (1, 3, 5)) + +@functools.lru_cache(None) +def F(px, bold=False, mono=False): + """Font by pixel size.""" + family = tkfont.nametofont('TkFixedFont' if mono else 'TkDefaultFont').actual('family') + return tkfont.Font(family=family, size=-px, weight='bold' if bold else 'normal') + +def elide(s, font, width): + """Text shortened to fit the width.""" + if font.measure(s) <= width: return s + s = s[:int(len(s) * width / font.measure(s)) + 2] + while s and font.measure(s + '…') > width: s = s[:-1] + return s + '…' + +def pct0(v): return f'{v:.0f}%' +def decimals(prec): return lambda v: f'{v:.{prec}f}' + +def theme(root): + """Dark colours for the classic and the ttk widgets.""" + root.configure(bg=C.bg) + for k, v in {'*font': F(13), '*background': C.bg, '*foreground': C.text, '*selectBackground': '#0e7ab8', '*selectForeground': C.text, + '*Menu.background': C.panel, '*Menu.activeBackground': C.select, '*Menu.activeForeground': C.text, '*Menu.borderWidth': 1, + '*Menu.activeBorderWidth': 0, '*Menu.relief': 'flat', '*TCombobox*Listbox.background': C.panel, '*TCombobox*Listbox.font': F(13), + '*TCombobox*Listbox.selectBackground': C.select}.items(): + root.option_add(k, v) + s, edge = ttk.Style(root), '#2a3449' + s.theme_use('clam') + s.configure('.', font=F(13), background=C.bg, foreground=C.text) + s.configure('TCombobox', fieldbackground=C.field, background=C.card, foreground=C.text, arrowcolor=C.muted, bordercolor=edge, + lightcolor=C.field, darkcolor=C.field, padding=5) + s.map('TCombobox', fieldbackground=[('readonly', C.field)], selectbackground=[('readonly', C.field)], selectforeground=[('readonly', C.text)], + bordercolor=[('focus', C.accent)], background=[('active', C.hover)]) + s.layout('Vertical.TScrollbar', [('Vertical.Scrollbar.trough', {'sticky': 'ns', 'children': [('Vertical.Scrollbar.thumb', {'expand': '1', 'sticky': 'nswe'})]})]) + trough = mix(C.bg, C.panel, .5) + s.configure('TScrollbar', troughcolor=trough, bordercolor=trough, gripcount=0, width=9) + for part in ('background', 'lightcolor', 'darkcolor'): # the thumb; invisible while there is nothing to scroll + s.map('TScrollbar', **{part: [('disabled', trough), ('active', '#3b4866'), ('', edge)]}) + +# ---- hand-drawn widgets --------------------------------------------------------------------- +class Paint(tk.Canvas): + """Canvas that repaints itself in draw() after a resize or a redraw() call.""" + def __init__(self, parent, width, height, bg=None, **kw): + super().__init__(parent, width=width, height=height, bg=bg or parent['bg'], highlightthickness=0, bd=0, **kw) + self.bind('', lambda e: self.redraw()) + def redraw(self): + self.w, self.h = self.winfo_width(), self.winfo_height() + if self.w > 1: + self.delete('all') + self.draw() + def need_height(self, h): # for widgets whose height follows their content + if h != self.winfo_reqheight(): self.config(height=h) + def rrect(self, x0, y0, x1, y1, r, fill='', outline='', **kw): + """Rounded rectangle.""" + r = max(0, min(r, (x1 - x0) / 2, (y1 - y0) / 2)) + p = (x0 + r, y0, x0 + r, y0, x1 - r, y0, x1 - r, y0, x1, y0, x1, y0 + r, x1, y0 + r, x1, y1 - r, x1, y1 - r, x1, y1, + x1 - r, y1, x1 - r, y1, x0 + r, y1, x0 + r, y1, x0, y1, x0, y1 - r, x0, y1 - r, x0, y0 + r, x0, y0 + r, x0, y0) + return self.create_polygon(p, smooth=True, fill=fill, outline=outline, **kw) + def text(self, x, y, s, fill=C.text, px=13, bold=False, anchor='w', **kw): + return self.create_text(x, y, text=s, fill=fill, font=F(px, bold), anchor=anchor, **kw) + def ring(self, x, y, size, pct, color, thick, glow=True): + """270-degree gauge arc with round ends inside the square at (x, y).""" + r, cx, cy = (size - thick) / 2, x + size / 2, y + size / 2 + + def arc(extent, c, width): + self.create_arc(cx - r, cy - r, cx + r, cy + r, start=225, extent=-extent, style='arc', outline=c, width=width) + for angle in (225, 225 - extent): + ex, ey = cx + r * math.cos(math.radians(angle)), cy - r * math.sin(math.radians(angle)) + self.create_oval(ex - width / 2, ey - width / 2, ex + width / 2, ey + width / 2, fill=c, width=0) + + arc(270, C.grid, thick) + extent = 270 * min(max(pct, 0), 100) / 100 + if extent > 0.2: + if glow: arc(extent, mix(self['bg'], color, .2), thick * 2) + arc(extent, color, thick) + +class Gauge(Paint): + """Ring gauge with a centre value, a sub text and a title; glides to new values.""" + def __init__(self, parent, title, crit=90): + super().__init__(parent, 150, 190) + self.title, self.crit, self.target, self.shown, self.center, self.sub, self.color, self.gliding = title, crit, 0, 0, '', '', None, False + def set(self, pct, center='', sub='', color=None): + self.center, self.sub, self.color = center, sub, color + pct = 0 if pct != pct else pct + if abs(pct - self.target) > 0.05: + self.target, self.start, self.t0 = pct, self.shown, time.monotonic() + if not self.gliding: self.glide() + self.redraw() + def glide(self): + k = min(1, (time.monotonic() - self.t0) / .45) + self.shown = self.start + (self.target - self.start) * (1 - (1 - k) ** 3) + self.gliding = k < 1 + self.redraw() + if self.gliding: self.after(30, self.glide) + def draw(self): + s = min(self.w - 8, self.h - 28) + x, mid = (self.w - s) / 2, self.w / 2 + self.ring(x, 4, s, self.shown, self.color or level(self.target, 70, self.crit), max(7, s * .085)) + self.text(mid, 4 + s * .43, self.center or f'{self.shown:.0f}%', px=int(s * .2), bold=True, anchor='center') + sub = F(max(10, int(s * .075))) + self.create_text(mid, 4 + s * .63, text=elide(self.sub, sub, s * .76), fill=C.muted, font=sub) + self.text(mid, s + 15, self.title, bold=True, anchor='center') + +class Chart(Paint): + """Time chart: grid, legend with the latest values, stacked or overlaid areas, gaps where data is missing, hover read-out.""" + def __init__(self, parent, title, fmt=pct0, ymax=0, height=230, stacked=False, empty='Waiting for data…'): # ymax 0 = auto + super().__init__(parent, 260, height) + self.title, self.fmt, self.ymax, self.stacked, self.empty, self.subtitle = title, fmt, ymax, stacked, empty, '' + self.t, self.series, self.span, self.hover, self.geo = [], [], 0, -1, None + self.bind('', lambda e: self.point(e.x)) + self.bind('', lambda e: self.point(-1)) + def set(self, t, series, span=0): + """t: times in ms; series: (name, colour, values[, fill[, dashed]]); span: visible ms before the last time, 0 = all.""" + n = len(t) + self.t, self.span = list(t), span + self.series = [(s[0], s[1], (list(s[2]) + [math.nan] * n)[:n], *s[3:], *(True, False)[len(s) - 3:]) for s in series] + self.redraw() + def draw(self): + w, h, fmt, t, self.geo = self.w, self.h, self.fmt, self.t, None + self.rrect(.5, .5, w - 1, h - 1, 12, C.panel, C.border) + self.text(16, 20, self.title, bold=True) + title_w = F(13, True).measure(self.title) + lx = w - 16 + for name, color, v, *_ in reversed(self.series): # legend with the latest values, right-aligned + last = next((x for x in v[:-6:-1] if x == x), None) + label = name if last is None else f'{name} {fmt(last)}' + lx -= F(11).measure(label) + if lx < 40 + title_w: break + self.text(lx, 20, label, C.muted, 11) + self.rrect(lx - 14, 16, lx - 5, 25, 2, color) + lx -= 28 + if 24 + title_w + F(11).measure(self.subtitle) < lx: self.text(24 + title_w, 20, self.subtitle, C.muted, 11) # where the legend leaves room + n = len(t) + first = bisect_left(t, t[-1] - self.span) if n and self.span else 0 + left, top, right, bottom = 56, 40, w - 16, h - 30 + if n - first < 2 or bottom - top < 20: return self.text((left + right) / 2, (top + bottom) / 2, self.empty, C.faint, anchor='center') + + ymax = self.ymax + if ymax <= 0: + clean = [[x if x == x else 0 for x in v[first:]] for _, _, v, *_ in self.series] + ymax = nice_ceil(max(map(sum if self.stacked else max, zip(*clean)), default=0) * 1.12) + left = max(40, max(F(10).measure(fmt(ymax * g / 4)) for g in range(5)) + 18) + t1 = t[-1] + t0 = t1 - self.span if self.span else t[first] + tr = max(1, t1 - t0) + + def X(ms): return left + (ms - t0) / tr * (right - left) + def Y(v): return bottom - min(max(v, 0), ymax) / ymax * (bottom - top) + + when = '%H:%M' if tr <= 72e5 else '%a %H:%M' if tr <= 2.6e8 else '%d %b' if tr <= 3.5e10 else '%b %Y' + for g in range(5): # grid, y labels, time labels + y, at = Y(ymax * g / 4), t0 + tr * g / 4 + self.create_line(left, y, right, y, fill=C.grid, dash=(4, 3) if g else '') + self.text(left - 8, y, fmt(ymax * g / 4), C.faint, 10, anchor='e') + self.text(X(at), bottom + 14, time.strftime(when, time.localtime(at / 1000)), C.faint, 10, anchor=('w', 'center', 'center', 'center', 'e')[g]) + step = max(1, (n - first) // max(50, int((right - left) * 1.5))) # about 1.5 points per pixel + base, lines = [0.0] * n, [] + for name, color, v, fill, dashed in self.series: + runs = [[]] # (x, y, y of the base) runs, split at gaps + for i in range(first, n, step): + ok = [(x, b) for x, b in zip(v[i:i + step], base[i:i + step]) if x == x] + if ok: + b = sum(b for _, b in ok) / len(ok) + runs[-1].append((X(t[min(n - 1, i + step // 2)]), Y(sum(x for x, _ in ok) / len(ok) + b), Y(b))) + elif runs[-1]: + runs.append([]) + if self.stacked: base = [b + (x if x == x else 0) for b, x in zip(base, v)] + for run in runs: + if len(run) < 2: continue + if fill: + area = [(x, y) for x, y, _ in run] + [(x, yb) for x, _, yb in reversed(run)] + self.create_polygon(area, fill=mix(C.panel, color, .38 if self.stacked else .16), width=0) + lines.append(([(x, y) for x, y, _ in run], color, dashed)) + for points, color, dashed in lines: # lines above all areas: an area must not hide another series + self.create_line(points, fill=color, width=1.3 if dashed else 2, dash=(5, 3) if dashed else '', joinstyle='round', capstyle='round') + self.geo = (left, top, right, bottom, t0, tr, X, Y, first) + self.mark() + def point(self, x): + self.hover = x + self.delete('hover') + self.mark() + def mark(self): + """Crosshair and values at the hovered time.""" + if not self.geo or not self.geo[0] <= self.hover <= self.geo[2]: return + left, top, right, bottom, t0, tr, X, Y, first = self.geo + t = self.t + best = min(bisect_left(t, t0 + (self.hover - left) / (right - left) * tr, first), len(t) - 1) + x, stack = X(t[best]), 0 + self.create_line(x, top, x, bottom, fill='#565b68', dash=(4, 3), tags='hover') + rows = [time.strftime('%a %d %b %H:%M' if tr > 864e5 else '%H:%M:%S', time.localtime(t[best] / 1000))] + for name, color, v, *_ in self.series: + rows.append(f'{name}: ' + ('—' if v[best] != v[best] else self.fmt(v[best]))) + if v[best] == v[best]: + stack = stack + v[best] if self.stacked else v[best] + self.create_oval(x - 4, Y(stack) - 4, x + 4, Y(stack) + 4, fill=color, outline=C.panel, width=2, tags='hover') + width = max(F(11).measure(r) for r in rows) + tx = min(x + 12, right - width - 20) + self.rrect(tx, top + 4, tx + width + 18, top + 14 + len(rows) * 16, 7, C.bg, C.border, tags='hover') + for i, r in enumerate(rows): self.text(tx + 9, top + 17 + i * 16, r, C.text if i else C.muted, 11, tags='hover') + +def nice_ceil(v): + if v <= 0: return 1 + e = 10 ** math.floor(math.log10(v)) + return next((k for k in (1, 2, 2.5, 5) if v / e <= k), 10) * e + +class SegmentBar(Paint): + """Stacked horizontal bar with a legend: (value, colour, label) segments of a total, in bytes.""" + def __init__(self, parent): + super().__init__(parent, 300, 58) + self.segments, self.total = [], 1 + def set(self, segments, total): + self.segments, self.total = segments, total if total > 0 else 1 + self.redraw() + def draw(self): + x = lx = 0 + ly, f = 26, F(11) + self.create_rectangle(0, 2, self.w, 16, fill=C.grid, width=0) + for value, color, _ in self.segments: + width = max(0, value / self.total * self.w) + self.create_rectangle(x, 2, x + width, 16, fill=color, width=0) + x += width + self.rrect(-3, -1, self.w + 3, 19, 10, outline=self['bg'], width=6) # rounds the ends of the bar + for value, color, name in self.segments: + label = f'{name} {fmt_bytes(value)}' + if lx + f.measure(label) + 26 > self.w: lx, ly = 0, ly + 18 + self.rrect(lx, ly + 3, lx + 9, ly + 12, 2, color) + self.text(lx + 14, ly + 8, label, C.muted, 11) + lx += f.measure(label) + 26 + +class Tile(Paint): + """Stat tile: title, large value, sub text and an accent stripe.""" + def __init__(self, parent, title, accent): + super().__init__(parent, 150, 84) + self.title, self.accent, self.shown = title.upper(), accent, ('—', '', None) + def set(self, value, sub='', color=None): + if (value, sub, color) != self.shown: + self.shown = (value, sub, color) + self.redraw() + def draw(self): + value, sub, color = self.shown + self.rrect(.5, .5, self.w - 1, self.h - 1, 12, C.card, C.border) + self.rrect(0, 14, 4, self.h - 14, 2, self.accent) + self.text(16, 20, elide(self.title, F(11, True), self.w - 28), C.muted, 11, True) + px = next((p for p in (21, 17, 14) if F(p, True).measure(value) <= self.w - 28), 14) # a narrow tile gets smaller digits + self.text(16, 44 if sub else 50, elide(value, F(px, True), self.w - 28), color or C.text, px, True) + self.text(16, 68, elide(sub, F(11), self.w - 28), C.muted, 11) + +class CoreGrid(Paint): + """One cell per CPU core: usage, bar and frequency.""" + def __init__(self, parent): + super().__init__(parent, 300, 66) + self.cores = [] + def set(self, cores): + self.cores = cores + self.redraw() + def draw(self): + cols = max(1, self.w // 92) + cw = self.w / cols + self.need_height(-(-max(1, len(self.cores)) // cols) * 66) + for i, core in enumerate(self.cores): + u, c, x, y = core.usage, level(core.usage, 60, 85), cw * (i % cols) + 3, i // cols * 66 + 3 + self.rrect(x, y, x + cw - 6, y + 60, 8, mix(C.card, c, u / 420), mix(C.border, c, u / 160)) + self.rrect(x + 8, y + 50, x + cw - 14, y + 54, 2, C.grid) + if u >= 1: self.rrect(x + 8, y + 50, x + 8 + (cw - 22) * u / 100, y + 54, 2, c) + self.text(x + 8, y + 12, f'CPU {i}', C.muted, 10) + if core.mhz > 0: self.text(x + cw - 14, y + 12, f'{core.mhz / 1000:.1f}G', C.muted, 10, anchor='e') + self.text(x + 8, y + 32, f'{u:.0f}%', px=16, bold=True) + +class Heatmap(Paint): + """Weekly pattern: average value per weekday and hour, with a tooltip.""" + DAYS = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') + def __init__(self, parent): + super().__init__(parent, 560, 230) + self.v, self.n, self.unit, self.hot, self.at = [[math.nan] * 24] * 7, [[0] * 24] * 7, '', C.accent, None + self.bind('', lambda e: self.point(int((e.y - 6) // ((self.h - 30) / 7)), int((e.x - 40) // ((self.w - 44) / 24)))) + self.bind('', lambda e: self.point(-1, -1)) + def set(self, v, n, unit, hot): + self.v, self.n, self.unit, self.hot = v, n, unit, hot + self.redraw() + def cell(self, d, h): + cw, ch = (self.w - 44) / 24, (self.h - 30) / 7 + return 40 + h * cw + 1.5, 6 + d * ch + 1.5, 40 + (h + 1) * cw - 1.5, 6 + (d + 1) * ch - 1.5 + def draw(self): + for d in range(7): + self.text(34, (self.cell(d, 0)[1] + self.cell(d, 0)[3]) / 2, self.DAYS[d][:3], C.muted, 10, anchor='e') + for h in range(24): + v = self.v[d][h] + self.rrect(*self.cell(d, h), 3, C.card if v != v else mix('#1b2a44', self.hot, .15 + .85 * min(max(v / 100, 0), 1))) + for h in range(0, 24, 3): self.text(self.cell(6, h)[0] - 4, self.cell(6, h)[3] + 11, f'{h:02d}:00', C.faint, 10) + if all(v != v for row in self.v for v in row): + x0, y0, x1, y1 = self.cell(2, 3)[:2] + self.cell(4, 20)[2:] + self.create_rectangle(x0, y0, x1, y1, fill=C.bg, width=0) + self.text((x0 + x1) / 2, (y0 + y1) / 2, 'Collecting hourly history… the weekly pattern fills in over time', px=12, anchor='center') + def point(self, d, h): + at = (d, h) if 0 <= d < 7 and 0 <= h < 24 else None + if at != self.at: + self.at, v = at, at and self.v[d][h] + show_tip(self, at and f'{self.DAYS[d]} {h}:00 — ' + ('no data' if v != v else f'avg {v:.1f}{self.unit} ({self.n[d][h]} samples)')) + +class KeyValues(Paint): + """List of (key, value) rows; long values wrap.""" + def __init__(self, parent, key_width=110): + super().__init__(parent, 200, 20) + self.rows, self.key_width = [], key_width + def set(self, rows): + if rows != self.rows: + self.rows = rows + self.redraw() + def draw(self): + y = 2 + for key, value in self.rows: + self.text(0, y, key, C.muted, anchor='nw') + y = self.bbox(self.text(self.key_width, y, value or ' ', anchor='nw', width=max(60, self.w - self.key_width)))[3] + 7 + self.need_height(y) + +class Chips(Paint): + """Row of small rounded (text, colour) labels that wraps.""" + def __init__(self, parent): + super().__init__(parent, 200, 22) + self.chips = [] + def set(self, chips): + if chips != self.chips: + self.chips = chips + self.redraw() + def draw(self): + x = y = 0 + for label, color in self.chips: + width = F(12).measure(label) + 18 + if x and x + width > self.w: x, y = 0, y + 26 + self.rrect(x, y, x + width, y + 22, 6, '#1f2a40') + self.text(x + 9, y + 11, label, color, 12) + x += width + 8 + self.need_height(y + 22) + +Cell = namedtuple('Cell', 'text color right pct key', defaults=('', False, -1, None)) # pct = bar, key = sort value + +class Table(tk.Frame): + """Hand-drawn table: coloured cells, bar cells, sortable columns and a selected row; only the visible rows are drawn. + A row is a list of cells (Cell or text); its first cell identifies it (by key, or else by text).""" + ROW, HEAD = 30, 32 + def __init__(self, parent, headers, widths=(), bars=(), sort=None, height=220): # sort: (column, descending), None = keep the order + super().__init__(parent, bg=C.line, padx=1, pady=1) + self.headers, self.widths, self.bars, self.sort, self.rows, self.top, self.selected = headers, widths, bars, sort, [], 0, None + self.on_open = self.on_menu = self.on_click = None # double click, right click (event), click (row index, column) + self.bar = ttk.Scrollbar(self, command=self.drag) + self.cv = Paint(self, 200, height, bg='#131929') + self.cv.draw = self.draw + self.cv.pack(side='left', fill='both', expand=True) + self.cv.bind('', self.click) + self.cv.bind('', lambda e: e.y > self.HEAD and self.on_open and self.on_open()) + self.cv.bind('', lambda e: self.click(e) or (self.on_menu and self.row() and self.on_menu(e))) + def set(self, rows): + self.rows = [[c if isinstance(c, Cell) else Cell(c) for c in r] for r in rows] + if not self.row(): self.selected = None # its entry is gone: the selection must not pass to a later one with the same key + if self.sort: + self.rows.sort(key=lambda r: r[self.sort[0]].text.lower() if r[self.sort[0]].key is None else r[self.sort[0]].key, reverse=self.sort[1]) + self.cv.redraw() + @staticmethod + def ident(row): return row[0].text if row[0].key is None else row[0].key + def row(self): + """The selected row, if it is still listed.""" + return next((r for r in self.rows if self.ident(r) == self.selected), None) + def visible(self): return max(1, (self.cv.winfo_height() - self.HEAD) // self.ROW) + def scroll(self, step, to=None): + """Scrolls by rows (or to a row); False when it cannot move any further.""" + top = min(max(self.top + step if to is None else to, 0), max(0, len(self.rows) - self.visible())) + moved, self.top = top != self.top, top + if moved: self.cv.redraw() + return moved + def drag(self, kind, value, unit=None): # scrollbar: ('moveto', fraction) or ('scroll', n, 'units' | 'pages') + if kind == 'moveto': self.scroll(0, round(float(value) * len(self.rows))) + else: self.scroll(int(value) * (self.visible() if unit == 'pages' else 1)) + def edges(self): + """Column x positions: given widths (100 when not given), the last column takes the rest; all shrink in a narrow table.""" + ws = [self.widths[i] if i < len(self.widths) else 100 for i in range(len(self.headers) - 1)] + xs, k = [0], min(1, self.cv.w / (sum(ws) + 90)) + for w in ws: xs.append(xs[-1] + w * k) + return xs + [self.cv.w] + def click(self, e): + col, i = bisect_right(self.edges(), e.x) - 1, self.top + (e.y - self.HEAD) // self.ROW + if e.y < self.HEAD: + if self.sort is not None and e.num == 1: + self.sort = (col, self.sort[0] == col and not self.sort[1]) + self.set(self.rows) + elif i < len(self.rows): + self.selected = self.ident(self.rows[i]) + self.cv.redraw() + if self.on_click and e.num == 1: self.on_click(i, col) + def draw(self): + cv, xs, n, shown = self.cv, self.edges(), len(self.rows), self.visible() + self.top = min(self.top, max(0, n - shown)) + for i in range(self.top, min(n, self.top + shown + 1)): + row, y = self.rows[i], self.HEAD + (i - self.top) * self.ROW + self.ROW / 2 + cv.create_rectangle(0, y - 15, cv.w, y + 15, width=0, fill=C.select if self.ident(row) == self.selected else '#161d2e' if i % 2 else '#131929') + for c, cell in enumerate(row): + x0, x1 = xs[c] + 8, (xs[c + 1] if len(row) > 1 else cv.w) - 8 + if c in self.bars and cell.pct >= 0: + p = min(max(cell.pct, 0), 100) + cv.rrect(x0 - 2, y - 7, x1 + 2, y + 7, 4, C.grid) + if p >= 1: cv.rrect(x0 - 2, y - 7, x0 - 2 + (x1 - x0 + 4) * p / 100, y + 7, 4, mix(C.grid, level(p), .78)) + cv.text((x0 + x1) / 2, y, cell.text, px=11, bold=True, anchor='center') + else: + cv.text(x1 if cell.right else x0, y, elide(cell.text, F(13), x1 - x0), cell.color or C.text, anchor='e' if cell.right else 'w') + cv.create_rectangle(0, 0, cv.w, self.HEAD, fill='#182033', width=0) + cv.create_line(0, self.HEAD, cv.w, self.HEAD, fill=C.border) + for c, title in enumerate(self.headers): + arrow = (' ▾' if self.sort[1] else ' ▴') if self.sort and self.sort[0] == c else '' + cv.text(xs[c] + 8, self.HEAD / 2, title + arrow, C.muted, 12, True) + self.bar.set(self.top / max(1, n), min(1, (self.top + shown) / max(1, n))) + if (n > shown) != bool(self.bar.winfo_manager()): self.bar.pack(side='right', fill='y', before=cv) if n > shown else self.bar.pack_forget() + +# ---- containers ------------------------------------------------------------------------------ +class Scroll(tk.Frame): + """Vertically scrollable area; the content goes into .body.""" + def __init__(self, parent): + super().__init__(parent, bg=parent['bg']) + self.cv = tk.Canvas(self, bg=parent['bg'], highlightthickness=0, yscrollincrement=20) + bar = ttk.Scrollbar(self, command=self.cv.yview) + self.body = tk.Frame(self.cv, bg=parent['bg']) + window = self.cv.create_window(0, 0, window=self.body, anchor='nw') + self.cv.config(yscrollcommand=bar.set) + bar.pack(side='right', fill='y') + self.cv.pack(side='left', fill='both', expand=True) + self.body.bind('', lambda e: self.cv.config(scrollregion=(0, 0, e.width, e.height))) + self.cv.bind('', lambda e: self.cv.itemconfig(window, width=e.width)) + def scroll(self, step): + before = self.cv.yview() + self.cv.yview_scroll(step, 'units') + return self.cv.yview() != before + +def on_wheel(e): + """Mouse wheel: scrolls the innermost Table / Scroll under the pointer that can still move.""" + w, step = e.widget, -3 if e.num == 4 or e.delta > 0 else 3 + while isinstance(w, tk.Misc) and not isinstance(w, tk.Text): + if hasattr(w, 'scroll') and w.scroll(step): break + w = w.master + +class Tabs(tk.Frame): + """Tab bar (the current tab is underlined) above a stack of pages; pages are created with the Tabs as parent.""" + def __init__(self, parent, on_change): + super().__init__(parent, bg=parent['bg']) + self.bar, self.pages, self.marks, self.current, self.on_change = down(box(self), 0), [], [], 0, on_change + down(tk.Frame(self, bg=C.line, height=1), 0) + self.bind('', lambda e: self.fit(e.width)) + def fit(self, width): # a narrow window gets tighter tabs + pad = min(13, max(2, (width - sum(F(13, True).measure(text['text']) for text, _ in self.marks)) // (2 * len(self.marks)) - 1)) + for text, _ in self.marks: text.config(padx=pad) + def add(self, title, page): + i, f = len(self.pages), right(box(self.bar), 0) + text = down(tk.Label(f, text=title, bg=self['bg'], fg=C.muted, font=F(13, True), padx=13, pady=9, cursor='hand2'), 0) + text.bind('', lambda e: self.show(i)) + self.marks.append((text, down(tk.Frame(f, height=2, bg=self['bg']), 0))) + self.pages.append(page) + def show(self, i): + self.pages[self.current].pack_forget() + self.current = i + self.pages[i].pack(fill='both', expand=True) + for k, (text, underline) in enumerate(self.marks): + text.config(fg='#7dd3fc' if k == i else C.muted) + underline.config(bg=C.accent if k == i else self['bg']) + self.on_change() + +# ---- small builders ---------------------------------------------------------------------------- +def down(w, gap=14, **kw): + """Packs w below its siblings (full width, gap underneath) and returns it.""" + w.pack(**{'side': 'top', 'fill': 'x', 'pady': (0, gap), **kw}) + return w + +def right(w, gap=10, grow=False, **kw): + """Packs w to the right of its siblings (gap after it) and returns it.""" + w.pack(**{'side': 'left', 'fill': 'both', 'expand': grow, 'padx': (0, gap), **kw}) + return w + +def spread(widgets, cols=99, weights=None, gap=14): + """Grids the children of one frame into columns of equal (or weighted) width.""" + for i, w in enumerate(widgets): + w.grid(row=i // cols, column=i % cols, sticky='nsew', padx=(gap if i % cols else 0, 0), pady=(gap if i >= cols else 0, 0)) + w.master.columnconfigure(i % cols, weight=weights[i] if weights else 1, uniform='columns') + +def box(parent, **kw): return tk.Frame(parent, bg=parent['bg'], **kw) + +def panel(parent, title='', width=0): + """Bordered panel with an optional title and minimum width.""" + f = tk.Frame(parent, bg=C.panel, padx=16, pady=14, highlightthickness=1, highlightbackground=C.line) + if width: tk.Frame(f, bg=C.panel, width=width - 34, height=0).pack() + if title: down(label(f, title.upper(), 'Section'), 10) + return f + +def tiles(parent, defs, cols=99): + """Row(s) of stat tiles from (title, colour) pairs.""" + f = down(box(parent)) + made = [Tile(f, *d) for d in defs] + spread(made, cols) + return made + +STYLES = {'H1': (22, True, C.text), 'H2': (16, True, C.text), 'Muted': (13, False, C.muted), 'Section': (11, True, C.muted), 'Small': (11, False, C.muted)} + +def label(parent, text='', kind=None, wrap=0, **kw): + """Text label; wrap = pixels, or True to wrap at the width the layout gives it.""" + px, bold, color = STYLES.get(kind, (13, False, C.text)) + w = tk.Label(parent, **{'text': text, 'bg': parent['bg'], 'fg': color, 'font': F(px, bold), 'justify': 'left', 'anchor': 'w', + 'wraplength': 300 if wrap is True else wrap, **kw}) + if wrap is True: w.bind('', lambda e: w.config(wraplength=e.width)) + return w + +# background, text, hover background, border (None = like the parent) +BUTTONS = {None: ('#1d2538', C.text, '#253049', '#2c3650'), 'Primary': ('#0e7ab8', '#ffffff', '#1190d8', C.accent), + 'Danger': ('#3a1820', '#ffb4bd', '#55202b', '#7f2a36'), 'Side': ('#1d2538', C.text, '#253049', '#2c3650'), + 'Flat': (None, C.muted, None, None), 'Nav': (None, C.text, C.card, None)} + +def button(parent, text, command=None, kind=None, **kw): + bg, fg, over, border = (x or parent['bg'] for x in BUTTONS[kind]) + b = tk.Button(parent, **{'text': text, 'command': command, 'bg': bg, 'fg': fg, 'activebackground': over, 'cursor': 'hand2', + 'activeforeground': C.text if kind == 'Flat' else fg, 'disabledforeground': C.faint, 'relief': 'flat', 'bd': 0, + 'highlightthickness': 1, 'highlightbackground': border, 'padx': 13, 'pady': 5, 'takefocus': 0, + 'font': F(14 if kind == 'Nav' else 13, kind in (None, 'Primary', 'Danger')), + 'anchor': 'w' if kind in ('Nav', 'Side') else 'center', **kw}) + b.kind, b.colors = kind, (bg, fg) + b.bind('', lambda e: b['state'] != 'disabled' and b.config(bg=b['activebackground'])) + b.bind('', lambda e: b.config(bg=b.colors[0])) + return b + +def press(b, on): + """Shows a button as checked or not.""" + normal = [x or b.master['bg'] for x in BUTTONS[b.kind][:2]] + b.colors = ((C.select, '#7dd3fc') if b.kind == 'Nav' else BUTTONS['Primary'][:2]) if on else normal + b.config(bg=b.colors[0], fg=b.colors[1]) + +FIELD = {'bg': C.field, 'fg': C.text, 'insertbackground': C.text, 'relief': 'flat', 'bd': 5, 'highlightthickness': 1, + 'highlightbackground': '#2a3449', 'highlightcolor': C.accent} +OFF = {'disabledbackground': C.bg, 'disabledforeground': C.faint} # look of disabled entry fields + +class Entry(tk.Entry): + """Text field with a placeholder (hint); text() is '' while the hint shows.""" + def __init__(self, parent, text='', hint='', width=20, show='', mono=False): + super().__init__(parent, width=width, font=F(13, mono=mono), **FIELD, **OFF) + self.hint, self.mask, self.hinting = hint, show, False + self.insert(0, text) + self.bind('', lambda e: self.blur(False)) + self.bind('', lambda e: self.blur(True)) + self.blur(True) + def blur(self, away): + if self.hinting and not away: + self.hinting = False + self.delete(0, 'end') + elif away and not self.get() and self.hint: + self.hinting = True + self.insert(0, self.hint) + self.config(fg=C.faint if self.hinting else C.text, show='' if self.hinting else self.mask) + def text(self): return '' if self.hinting else self.get() + def put(self, text, hint=None): + self.blur(False) + self.hint = self.hint if hint is None else hint + self.delete(0, 'end') + self.insert(0, text) + self.blur(self.focus_get() is not self) + +class Spin(tk.Spinbox): + """Number field; value() is clamped to the range (an int when the step is whole).""" + def __init__(self, parent, lo, hi, value=0, step=1, width=7, command=None): + super().__init__(parent, from_=lo, to=hi, increment=step, width=width, font=F(13), buttonbackground=C.card, command=command, **FIELD, **OFF) + self.lo, self.hi, self.step = lo, hi, step + self.put(value) + if command: + self.bind('', lambda e: command()) + self.bind('', lambda e: command()) + def put(self, value): + self.delete(0, 'end') + self.insert(0, f'{value:.12g}') + def value(self): + v = min(max(num(self.get()), self.lo), self.hi) + return v if self.step % 1 else int(v) + +def combo(parent, values, width=18, command=None, edit=False): + c = ttk.Combobox(parent, values=values, width=width, state='normal' if edit else 'readonly', font=F(13)) + if values and not edit: c.current(0) + c.bind('<>', lambda e: (c.selection_clear(), command and command())) + return c + +def check(parent, text, on=False, command=None): + """Check box; .var holds the state.""" + var = tk.BooleanVar(value=on) + c = tk.Checkbutton(parent, text=text, variable=var, command=command, bg=parent['bg'], fg=C.text, activebackground=parent['bg'], + activeforeground=C.text, selectcolor=C.field, anchor='w', font=F(13), cursor='hand2', highlightthickness=0, bd=0) + c.var = var + return c + +def textbox(parent, mono=True, **kw): + """Read-only text area with a scrollbar; pack its .frame. Fill it with write().""" + frame = box(parent) + t = tk.Text(frame, **{'bg': '#080b12', 'fg': '#cfe3ff', 'font': F(12, mono=mono), 'relief': 'flat', 'bd': 0, 'padx': 10, 'pady': 10, 'wrap': 'none', + 'state': 'disabled', 'width': 1, 'height': 1, 'highlightthickness': 0, **kw}) + bar = ttk.Scrollbar(frame, command=t.yview) + t.config(yscrollcommand=bar.set) + bar.pack(side='right', fill='y') + t.pack(side='left', fill='both', expand=True) + t.frame = frame + return t + +def write(t, text, color=None, clear=False): + """Appends text (optionally coloured) to a read-only text area and scrolls to the end.""" + t.config(state='normal') + if clear: t.delete('1.0', 'end') + t.insert('end', text, color or ()) + t.delete('1.0', 'end - 20000 lines') + if color: t.tag_config(color, foreground=color) + t.config(state='disabled') + t.see('end') + +def field(form, text, widget): + """Adds a labelled row to a form frame and returns the widget.""" + r = form.grid_size()[1] + label(form, text, 'Muted').grid(row=r, column=0, sticky='w', padx=(0, 14), pady=5) + widget.grid(row=r, column=1, sticky='ew', pady=5) + form.columnconfigure(1, weight=1) + return widget + +def popup(widget, event, items): + """Context menu from (text, command) pairs; None = separator.""" + if getattr(popup, 'menu', None): popup.menu.destroy() # the previous one + popup.menu = m = tk.Menu(widget, tearoff=0) + for item in items: m.add_command(label=item[0], command=item[1]) if item else m.add_separator() + m.tk_popup(event.x_root, event.y_root) + +def show_tip(widget, text): + """Shows a tooltip near the pointer; an empty text hides it.""" + tip = getattr(show_tip, 'window', None) + if tip: tip.destroy() + show_tip.window = None + if text: + show_tip.window = tip = tk.Toplevel(widget, bg=C.accent, padx=1, pady=1) + tip.overrideredirect(True) + tk.Label(tip, text=text, bg=C.card, fg=C.text, padx=8, pady=5, justify='left', wraplength=560, font=F(11)).pack() + tip.geometry(f'+{widget.winfo_pointerx() + 14}+{widget.winfo_pointery() + 18}') + +def tip(widget, text): + widget.bind('', lambda e: show_tip(widget, text), add='+') + widget.bind('', lambda e: show_tip(widget, ''), add='+') + return widget + +class Dialog(tk.Toplevel): + """Dark dialog window; run() shows it modally and returns what close() was given.""" + def __init__(self, parent, title): + super().__init__(parent, bg=C.bg, padx=24, pady=20) + self.title(title) + self.transient(parent.winfo_toplevel()) + self.result = None + self.protocol('WM_DELETE_WINDOW', self.close) + self.bind('', lambda e: self.close()) + def buttons(self, *defs): + """Row of (text, command[, kind]) buttons at the bottom right.""" + row = down(box(self), 0) + for d in reversed(defs): button(row, *d).pack(side='right', padx=(8, 0)) + def close(self, result=None): + self.result = result + self.destroy() + def run(self): + self.update_idletasks() + top = self.master.winfo_toplevel() + self.geometry(f'+{top.winfo_rootx() + max(0, (top.winfo_width() - self.winfo_reqwidth()) // 2)}+{top.winfo_rooty() + 120}') + self.wait_visibility() + self.grab_set() + self.wait_window() + return self.result + +def choose(parent, title, text, options): + """Modal question with (text, kind) buttons; returns the text of the chosen one, None when dismissed.""" + d = Dialog(parent, title) + down(label(d, text, wrap=460), 18) + d.buttons(*((name, lambda name=name: d.close(name), kind) for name, kind in options)) + return d.run() + +def ask(parent, title, text, danger=False): return choose(parent, title, text, [('No', None), ('Yes', 'Danger' if danger else 'Primary')]) == 'Yes' + +def app_icon(size): + """App icon: gradient tile with a pulse line.""" + line = [(.12, .56), (.34, .56), (.44, .28), (.56, .78), (.66, .48), (.88, .48)] + + def near(x, y, a, b): # distance from (x, y) to the segment a-b + (ax, ay), (bx, by) = a, b + k = min(max(((x - ax) * (bx - ax) + (y - ay) * (by - ay)) / ((bx - ax) ** 2 + (by - ay) ** 2), 0), 1) + return math.hypot(x - ax - k * (bx - ax), y - ay - k * (by - ay)) + + image = tk.PhotoImage(width=size, height=size) + cells = [[(x + .5) / size, (y + .5) / size] for y in range(size) for x in range(size)] + colors = ['#ffffff' if min(near(x, y, a, b) for a, b in zip(line, line[1:])) < .042 else mix('#0ea5e9', '#7c3aed', (x + y) / 2) for x, y in cells] + image.put(' '.join('{' + ' '.join(colors[r * size:(r + 1) * size]) + '}' for r in range(size))) + return image diff --git a/Server Monitor(python-window)/README.md b/Server Monitor(python-window)/README.md new file mode 100644 index 0000000000000000000000000000000000000000..75f6ccbee602a79c5978d968570b59f57c1704c4 --- /dev/null +++ b/Server Monitor(python-window)/README.md @@ -0,0 +1,59 @@ +# Server Monitor (Python, Windows) + +A desktop program 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 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. + +## Requirements + +- Windows 10 / 11 or Windows Server 2016 and newer, with Windows PowerShell 5.1 (built in). +- Python 3.8 or newer from python.org (tkinter is included). No pip packages. +- The OpenSSH client (`ssh`, built in since Windows 10 1809 / Server 2019), only for remote servers. Password login needs OpenSSH 8.4 or newer; key login works with any version. + +## Run + +Double-click `run.bat`, or run `python main.py`. + +The first start adds "This computer". Closing the window ends the program (there is no tray icon). + +## How it connects + +- **This machine:** no setup. A PowerShell script (embedded in `plat.py`) reads performance counters and WMI. +- **SSH:** nothing to install on the server besides the built-in OpenSSH Server feature. The same script is sent over your `ssh` client to the server's `powershell`. Keys are recommended; a password also works, and a small temporary helper script answers ssh's password prompt. + +All calculations happen in the app. Control actions (stopping processes of other users, services, cleanup) need administrator rights: start the app elevated, or log in over SSH as an administrator. Process owners are shown only when elevated. + +## Features + +- **Dashboard:** a live card per server (gauges, sparkline, health grade), totals, recent events, search. +- **Server tabs:** Overview, CPU (per core, temperatures, GPUs), Memory, Storage, Network, Processes (end task, kill, priority), Services (start/stop/restart/enable/disable, events), History, Insights & Autopilot, Alert rules, Console (PowerShell). +- **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. +- **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. +- **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. +- **Alert rules:** "CPU > 90 % for 60 s → warning → restart a service"; events go to the Events page and to `alerts.log`. + +The load average has the Unix meaning (running plus waiting tasks, averaged over 1 / 5 / 15 minutes); it is computed from CPU usage and the processor queue length. + +## Data + +Everything is stored in `%APPDATA%\ServerMonitorPy`: + +- `servers.json`: servers, rules and autopilot settings. Saved SSH passwords are only lightly disguised, not encrypted, so prefer keys. +- `history\\{raw,minute,hour,day}.bin`: the history tiers. +- `alerts.log`: every alert and action. + +The file formats are the same as in the other Server Monitor editions, so files can be copied between them. + +## Code + +``` +main.py entry point +plat.py everything Windows-specific: collector script, spawning, frame parser, command tables +metrics.py one parsed sample + helpers shared by the platform parsers +model.py configuration, rules, formatting +history.py history store + analyzer +session.py ssh/local link, per-server session (rules, autopilot), manager +widgets.py theme, hand-drawn widgets, small UI builders +tabs.py server detail tabs +ui.py dashboard, detail page, add/edit dialog, main window +``` + +Only `plat.py` differs from the Linux edition. diff --git a/Server Monitor(python-window)/history.py b/Server Monitor(python-window)/history.py new file mode 100644 index 0000000000000000000000000000000000000000..9e456306b0657c3054ab8875b521e1158918927f --- /dev/null +++ b/Server Monitor(python-window)/history.py @@ -0,0 +1,331 @@ +"""Persistent multi-resolution history (raw 6 h, minute 30 d, hour 2 y, day 20 y) +and the statistics-only analyzer that feeds the autopilot.""" +import math, os, struct, time +from array import array +from bisect import bisect_left, bisect_right +from collections import namedtuple + +import plat +from model import duration, fmt_bytes, pct, rate, rnd, temp + +KEYS = 'cpu iowait load mem swap disk diskio rx tx rd wr temp procs gpu failed'.split() +NAMES = ['CPU', 'I/O wait', 'Load (1m)', 'Memory', 'Swap', 'Disk usage', 'Disk busy', 'Net download', 'Net upload', 'Disk read', + 'Disk write', 'Temperature', 'Processes', 'GPU', 'Failed services'] +CPU, IOWAIT, LOAD, MEM, SWAP, DISK, DISKIO, RX, TX, RD, WR, TEMP, PROCS, GPU, FAILED = range(15) +H_COUNT, NAN = len(KEYS), math.nan +TIERS, TIER_NAMES = ('raw', 'minute', 'hour', 'day'), ('every sample', '1 minute', '1 hour', '1 day') +STEP, KEEP, MAX_SPAN = (1, 60, 3600, 86400), (6 * 3600, 30 * 86400, 732 * 86400, 7320 * 86400), (6 * 3600, 8 * 86400, 400 * 86400) +REC = struct.Struct(' self.max[i]: self.max[i] = mx + def row(self): # through the record format, so the values are float32 like the stored ones + 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)) + +class Store: + def __init__(self, path): + self.dir, self.tz, self.appends = path, time.localtime().tm_gmtoff, [0] * 4 + os.makedirs(path, exist_ok=True) + now = int(time.time()) + self.tiers, self.acc = [Points() for _ in TIERS], [Acc() for _ in TIERS] + for t in range(4): self.load(t, now) + 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 + finer, stored = self.tiers[t - 1], self.tiers[t].ts[-1] if len(self.tiers[t]) else -1 + for r in [*finer.cut(bisect_right(finer.ts, stored)).rows(), *([self.acc[t - 1].row()] if self.acc[t - 1].n else [])]: + b, a = self.bucket(t, r[0]), self.acc[t] + if b <= stored: continue + if b != a.bucket: + if a.n: self.append(t, a.row()) + a = self.acc[t] = Acc(b) + a.add(r) + def file(self, t): return os.path.join(self.dir, TIERS[t] + '.bin') + 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 + def load(self, t, now): + try: + with open(self.file(t), 'rb') as f: data = f.read() + except OSError: + return + if not data.startswith(HEADER): return os.replace(self.file(t), self.file(t) + '.old') + rows, last = [], -1 + for r in REC.iter_unpack(data[len(HEADER):len(data) - (len(data) - len(HEADER)) % REC.size]): + if now - KEEP[t] <= r[0] <= now + 86400 and r[0] > last: + rows.append(r) + last = r[0] + self.tiers[t] = Points(rows) + if len(HEADER) + len(rows) * REC.size != len(data): # expired or damaged records, or a cut-off one that would misalign what is appended + self.rewrite(t) + def rewrite(self, t): + try: + with open(self.file(t) + '.tmp', 'wb') as f: f.write(HEADER + b''.join(REC.pack(*r) for r in self.tiers[t].rows())) + os.replace(self.file(t) + '.tmp', self.file(t)) + except OSError: + pass # history stays in memory when the disk is full or read-only + def append(self, t, row): + p = self.tiers[t] + if len(p) and row[0] <= p.ts[-1]: return + p.add(row) + try: + with open(self.file(t), 'ab') as f: + if f.tell() < len(HEADER): + f.truncate(0) + f.write(HEADER) + f.write(REC.pack(*row)) + except OSError: + pass + self.appends[t] += 1 + if self.appends[t] % 500 == 0: # trim expired points now and then + k = bisect_left(p.ts, row[0] - KEEP[t]) + if k: + self.tiers[t] = p.cut(k) + self.rewrite(t) + def add(self, ts, values, up): + """Records one sample; up=False records downtime only.""" + v = values if up else [NAN] * H_COUNT + raw = REC.unpack(REC.pack(ts, 1, int(up), *v, *v)) + self.append(0, raw) + for t in (1, 2, 3): # every coarser tier accumulates every raw sample + b, a = self.bucket(t, ts), self.acc[t] + if a.bucket != b: + if a.n and a.bucket < b: self.append(t, a.row()) + a = self.acc[t] = Acc(b) + a.add(raw) + def range(self, frm, to, t): + """Points of tier t in [frm, to], including the open bucket.""" + p, a = self.tiers[t], self.acc[t] + out = p.cut(bisect_left(p.ts, frm), bisect_right(p.ts, to)) + if t and a.n and frm <= a.bucket <= to and (not len(out) or out.ts[-1] < a.bucket): out.add(a.row()) + return out + def span(self, frm, to): + """(points, tier) from the finest tier that covers the range.""" + now, t = int(time.time()), 0 + while t < 3 and (frm < now - KEEP[t] or to - frm > MAX_SPAN[t]): t += 1 + return self.range(frm, to, t), t + def first_ts(self): return min((p.ts[0] for p in self.tiers if len(p)), default=0) + def disk_bytes(self): return sum(os.path.getsize(self.file(t)) for t in range(4) if os.path.exists(self.file(t))) + +Stats = namedtuple('Stats', 'min avg p95 max count', defaults=(NAN, NAN, NAN, NAN, 0)) # max = peak of max[] + +def stats(p, m): + v = [(a, x, u) for a, x, u in zip(p.avg[m], p.max[m], p.up) if u and a == a] + if not v: return Stats() + a = sorted(r[0] for r in v) + 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)) + +def regression(p, m): + """Least-squares (slope per second, squared correlation) of a metric over time.""" + xy = [(t - p.ts[0], y) for t, y, u in zip(p.ts, p.avg[m], p.up) if u and y == y] + n, sx, sy = len(xy), sum(x for x, _ in xy), sum(y for _, y in xy) + 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 + if n < 3 or den <= 0: return 0.0, 0.0 + return num / den, num * num / (den * vy) if vy > 1e-9 else 0.0 + +def slot(ts): + """(weekday, hour) of a timestamp in local time; Monday = 0.""" + t = time.localtime(ts) + return t.tm_wday, t.tm_hour + +def fmt_metric(m, v): + if v != v: return '—' + 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) + +# ---- analysis ------------------------------------------------------------------- +# action: disk_cleanup | restart_service | renice | kill_pid +Finding = namedtuple('Finding', 'key severity category title detail advice action arg label auto') +ProcTrend = namedtuple('ProcTrend', 'pid minutes name user cpu_now high_cpu_minutes rss_now rss_growth rss_growth_pct rss_monotonic protected', + defaults=(0, 0, '', '', 0, 0, 0, 0, 0, 0, False)) +ServiceTrend = namedtuple('ServiceTrend', 'unit failed_now preexisting fails_last_hour auto_restarts_last_hour') +Anomaly = namedtuple('Anomaly', 'metric baseline hm now mean sd z') + +class Analysis: + def __init__(self): + self.when, self.health, self.grade, self.disk_basis = 0, 100, 'A', '' + self.reasons, self.capacity, self.findings, self.anomalies = [], [], [], [] + self.disk_full_days, self.disk_slope_per_day, self.mem_slope_per_hour, self.mem_trend_r2 = -1, 0, 0, 0 + self.up, self.down, self.cpu30, self.mem30 = [NAN] * 3, [0] * 3, Stats(), Stats() # 24 h, 7 d, 30 d: availability %, seconds offline + self.heat = [[[NAN] * 24 for _ in range(7)] for _ in range(2)] # weekly pattern: 0 = CPU, 1 = memory + self.heat_n = [[0] * 24 for _ in range(7)] + +def analyze(st, m, ap, procs, svcs, online): + a = Analysis() + now = a.when = int(time.time()) + minute, hour, cores = st.tiers[1], st.tiers[2], max(1, m.cpu_count) + + def add(key, sev, cat, title, detail, advice, action='', arg='', label='', auto=False): + a.findings.append(Finding(key, sev, cat, title, detail, advice, action, arg, label, bool(auto))) + + def sev(crit, warn): return 'critical' if crit else 'warning' if warn else 'info' + + # availability + spans = (86400, 7 * 86400, 30 * 86400) + for i, span in enumerate(spans): + p = st.span(now - span, now)[0] + n, up = sum(p.n), sum(p.up) + 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 + if a.up[0] < 99: + add('avail24', sev(a.up[0] < 95, True), 'Availability', f'Availability last 24 h is {pct(a.up[0], 2)}', + f'The server could not be reached for about {duration(a.down[0])} in the last day.', + 'Check network stability, power and whether the machine rebooted (uptime).') + w30, w7 = st.range(now - spans[2], now, 2), st.range(now - spans[1], now, 1) + a.cpu30, a.mem30 = (stats(w30 if len(w30) >= 24 else w7, k) for k in (CPU, MEM)) + + # disk forecast: regression over 7 d of hours, or 24 h of minutes, whichever fits better + slope = r2 = 0.0 + week, day = st.range(now - spans[1], now, 2), st.range(now - 86400, now, 1) + if len(week) >= 48: (slope, r2), a.disk_basis = regression(week, DISK), 'hourly averages, last 7 days' + if len(day) >= 120: + s2, r2b = regression(day, DISK) + if len(week) < 48 or r2b > r2: slope, r2, a.disk_basis = s2, r2b, 'minute averages, last 24 hours' + a.disk_slope_per_day = slope * 86400 + 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 + if 0 <= a.disk_full_days < 30: + add('diskfull', sev(a.disk_full_days < ap.diskForecastDays, a.disk_full_days < 14), 'Disk', + f'Disk {m.fullest_mount} will be full in {duration(a.disk_full_days * 86400)}', + 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}).', + 'Clean logs/caches, rotate or move data, or grow the volume.', 'disk_cleanup', '', 'Run cleanup', + ap.diskCleanup and a.disk_full_days < ap.diskForecastDays) + if m.max_disk_pct >= ap.diskCleanupAt: + add('diskhigh', sev(m.max_disk_pct >= 97, True), 'Disk', f'Disk {m.fullest_mount} is {pct(m.max_disk_pct)} full', + f'Above the cleanup threshold of {pct(ap.diskCleanupAt, 0)}.', 'Free space soon: services fail when the disk is full.', + 'disk_cleanup', '', 'Run cleanup', ap.diskCleanup) + + # whole-machine memory trend over 6 h + six = st.range(now - 6 * 3600, now, 1) + if len(six) >= 90: + slope, a.mem_trend_r2 = regression(six, MEM) + a.mem_slope_per_hour = slope * 3600 + left = (100 - m.mem_pct) / max(0.01, a.mem_slope_per_hour) + if a.mem_slope_per_hour > 1 and a.mem_trend_r2 > 0.8 and m.mem_pct > 40: + add('memtrend', sev(False, left < 12), 'Memory', f'Memory keeps growing (+{a.mem_slope_per_hour:.1f} points/hour)', + f'Steady growth over 6 h (R² {a.mem_trend_r2:.2f}). At this rate memory is exhausted in about {duration(left * 3600)}.', + 'Look for a leaking process (Processes tab, sort by RSS).') + + # processes: leaks and runaways + for p in procs: + if p.protected: continue + who = f'{p.name} (PID {p.pid})' + if p.minutes >= 30 and p.rss_growth_pct >= 25 and p.rss_growth >= 100e6 and p.rss_monotonic >= 0.8: + add(f'leak:{p.pid}', sev(m.mem_pct >= ap.leakMemPressure, True), 'Process', 'Possible memory leak: ' + who, + f'RSS grew {fmt_bytes(p.rss_growth)} (+{pct(p.rss_growth_pct, 0)}) in {p.minutes} min and rose in ' + f'{rnd(p.rss_monotonic * 100)}% of the minutes; now {fmt_bytes(p.rss_now)}.', + 'Restart the program/service at a quiet time and report the leak upstream.', 'kill_pid', str(p.pid), 'Terminate', + ap.leakMode == 'terminate' and m.mem_pct >= ap.leakMemPressure) + if p.high_cpu_minutes >= ap.runawayMinutes: + term = ap.runawayMode == 'terminate' + add(f'runaway:{p.pid}', 'warning', 'Process', 'Runaway process: ' + who, + f'Above {pct(ap.runawayCpu, 0)} CPU for {rnd(p.high_cpu_minutes)} min (now {pct(p.cpu_now)}, user {p.user}).', + plat.TEXT['renice_advice'], 'kill_pid' if term else 'renice', str(p.pid), 'Terminate' if term else plat.TEXT['renice'], + ap.runawayMode != 'none') + + # services: failures and flapping + for s in svcs: + flap = s.fails_last_hour >= 3 or s.auto_restarts_last_hour >= ap.maxRestartsPerHour + if s.failed_now: + add('svc:' + s.unit, sev(flap, True), 'Service', f'Service {s.unit} ' + ('keeps failing' if flap else 'has failed'), + 'It was already failed when monitoring started, so the autopilot leaves it alone (it may be failed on purpose).' if s.preexisting + else f'Failed {s.fails_last_hour}× in the last hour; autopilot restarted it {s.auto_restarts_last_hour}×.', + 'Automatic restarts were stopped. Read the logs (Services tab → Logs) and fix the cause.' if flap else 'Restart it and check the logs.', + 'restart_service', s.unit, 'Restart', ap.restartFailed and not s.preexisting and s.auto_restarts_last_hour < ap.maxRestartsPerHour) + elif s.fails_last_hour >= 3: + add('flap:' + s.unit, 'warning', 'Service', f'Service {s.unit} is unstable', + f'It failed {s.fails_last_hour} times within the last hour.', 'Inspect its logs and resource limits.') + + # overload and swap thrashing + last15 = st.range(now - 900, now, 1) + load15, io15, cpu15, busy15 = (stats(last15, k).avg for k in (LOAD, IOWAIT, CPU, DISKIO)) + if online and load15 / cores > 1.5: + add('load', sev(load15 / cores > 3, True), 'CPU', f'CPU is overloaded (load {load15:.1f} on {cores} cores)', + f'15-minute average load is {load15 / cores:.1f}× the number of cores; tasks are waiting for CPU.', + 'Find the busiest processes, spread work over time, or add CPU.') + thrash = plat.thrashing(io15, m.mem_pct, busy15) + if online and m.swap_pct > 50 and thrash: + add('thrash', 'critical', 'Memory', 'Swap thrashing', f'Swap {pct(m.swap_pct)} used{thrash}.', 'Stop memory-hungry processes or add RAM.') + + # anomalies: last 10 min vs same weekday+hour over 8 weeks (fallback: last 24 h) + raw = st.range(now - 600, now, 0) + 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)] + recent = range(bisect_left(minute.ts, now - 86400), bisect_left(minute.ts, now - 900)) + checks = [(CPU, 5.0, False), (MEM, 3.0, False), (LOAD, 0.25 * cores, False), (IOWAIT, 3.0, False), (RX, 256e3, True), (TX, 256e3, True)] + for hm, floor, down in checks if online and len(raw) >= 10 else (): # (metric, smallest deviation unit, alert on drops) + if hm == IOWAIT and not plat.POSIX_CPU: continue + cur, basis = stats(raw, hm).avg, 'same weekday & hour, last 8 weeks' + v = [hour.avg[hm][i] for i in same if hour.up[i] and hour.avg[hm][i] == hour.avg[hm][i]] + if len(v) < 3: + 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' + if len(v) < 360: continue + mean = sum(v) / len(v) + sd = math.sqrt(sum((x - mean) ** 2 for x in v) / len(v)) + z = (cur - mean) / max(sd, floor) + a.anomalies.append(Anomaly(NAMES[hm], basis, hm, cur, mean, sd, z)) + hi, lo = z >= ap.anomalyZ, down and mean > 1e6 and cur < mean * 0.1 + if ap.anomalyAlerts and (hi or lo): + add('anomaly:' + KEYS[hm], sev(False, z >= ap.anomalyZ * 2), 'Anomaly', f'Unusually {"high" if hi else "low"} {NAMES[hm].lower()}', + f'Last 10 min {fmt_metric(hm, cur)}, usually {fmt_metric(hm, mean)} ± {fmt_metric(hm, sd)} ({basis}); {z:.1f}σ.', + 'Check what changed: deploys, cron jobs, traffic, attacks.' if hi else 'Traffic dropped sharply - check the service is still serving.') + + # weekly heatmaps from 4 weeks of hours + total = [[[0.0] * 24 for _ in range(7)] for _ in range(2)] + for i in range(bisect_left(hour.ts, now - 28 * 86400), len(hour)): + cpu, mem = hour.avg[CPU][i], hour.avg[MEM][i] + if not hour.up[i] or cpu != cpu: continue + d, h = slot(hour.ts[i]) + a.heat_n[d][h] += 1 + for k, v in enumerate((cpu, mem if mem == mem else 0)): + total[k][d][h] += v + a.heat[k][d][h] = total[k][d][h] / a.heat_n[d][h] + + # capacity advice + 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'), + (a.mem30, 'Memory', 30, 85, 'is under-used', 'is tight - add RAM or reduce caches/limits')): + 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)}).') + if a.disk_full_days >= 0: + a.capacity.append(f'Disk grows {a.disk_slope_per_day:.2f} points/day - full in about {duration(a.disk_full_days * 86400)}.') + elif a.disk_basis: + a.capacity.append('Disk usage is stable.') + if not a.capacity: a.capacity.append('Collecting history - capacity advice appears after about an hour of data.') + + # health score + score = 100.0 + + def pen(when, p, why): + nonlocal score + if when and p > 0.5: + score -= p + a.reasons.append(f'−{rnd(p)} {why}') + + cpu = m.cpu_usage if cpu15 != cpu15 else cpu15 + pen(not online, 60, 'server unreachable') + pen(cpu > 70, min(24, (cpu - 70) * 0.8), f'CPU busy ({pct(cpu)})') + pen(m.mem_pct > 80, min(30, (m.mem_pct - 80) * 1.5), f'memory high ({pct(m.mem_pct)})') + pen(m.max_disk_pct > 80, min(40, (m.max_disk_pct - 80) * 2), f'disk high ({pct(m.max_disk_pct)})') + pen(m.swap_pct > 50, 10, 'heavy swap use') + pen(m.max_temp > 80, min(20, (m.max_temp - 80) * 2), f'hot ({temp(m.max_temp)})') + pen(a.up[0] < 100, min(30, (100 - a.up[0]) * 5), 'downtime in last 24 h') + pen(True, min(50, sum(0 if f.category == 'Availability' else {'critical': 15, 'warning': 7}.get(f.severity, 2) for f in a.findings)), + f'{len(a.findings)} finding(s)') + a.health = min(max(rnd(score), 0), 100) + a.grade = 'FDCBA'[sum(a.health >= x for x in (40, 60, 75, 90))] + a.findings.sort(key=lambda f: {'critical': 0, 'warning': 1}.get(f.severity, 2)) + return a diff --git a/Server Monitor(python-window)/main.py b/Server Monitor(python-window)/main.py new file mode 100644 index 0000000000000000000000000000000000000000..d6fa04eaa83e384697799a41ff0a16c1f8cf39c4 --- /dev/null +++ b/Server Monitor(python-window)/main.py @@ -0,0 +1,13 @@ +"""Server Monitor - entry point.""" +import tkinter as tk + +from session import Manager +from ui import MainWindow + +def main(): + root, mgr = tk.Tk(), Manager() + MainWindow(root, mgr) + mgr.load() + root.mainloop() + +if __name__ == '__main__': main() diff --git a/Server Monitor(python-window)/metrics.py b/Server Monitor(python-window)/metrics.py new file mode 100644 index 0000000000000000000000000000000000000000..69e4708f016f1776f6d4b5f3d5bd10ec0ae26bd1 --- /dev/null +++ b/Server Monitor(python-window)/metrics.py @@ -0,0 +1,84 @@ +"""One parsed sample (Metrics) and the frame helpers shared by the platform parsers.""" +from collections import namedtuple + +Core = namedtuple('Core', 'usage mhz') +Mount = namedtuple('Mount', 'device type mount total used avail pct') +Disk = namedtuple('Disk', 'name read_bps write_bps read_iops write_iops util total_read total_written') +Net = namedtuple('Net', 'name state speed virt rx_bps tx_bps rx_pps tx_pps rx_bytes tx_bytes errors drops') +Proc = namedtuple('Proc', 'pid ppid threads nice name user state cpu mem_pct rss vsz age') # cpu: % of one core +Service = namedtuple('Service', 'unit load active sub description') +Temp = namedtuple('Temp', 'name celsius') +Gpu = namedtuple('Gpu', 'index name util mem_used mem_total temp power fan') + +class Metrics: + TEXTS = 'hostname os kernel arch cpu_model virt fullest_mount busiest_disk' + NUMBERS = ('cpu_count logged_users procs_running procs_blocked threads_total sockets_used services_failed services_running ' + 'uptime load1 load5 load15 cpu_usage cpu_user cpu_system cpu_iowait cpu_steal cpu_irq ctxt_per_sec intr_per_sec ' + 'forks_per_sec avg_mhz mem_total mem_free mem_available mem_used buffers cached shared slab dirty swap_total ' + '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') + LISTS = 'cores mounts disks nets procs services temps gpus' + def __init__(self, timestamp=0): + self.valid, self.timestamp, self.tcp = False, timestamp, {} # tcp: state name -> connections + for names, value in ((self.TEXTS, ''), (self.NUMBERS, 0)): + for k in names.split(): setattr(self, k, value) + for k in self.LISTS.split(): setattr(self, k, []) + def gpu_max(self, temp=False): return max((g.temp if temp else g.util for g in self.gpus), default=0) + +def num(s): + """Number from text; 0 when missing or malformed.""" + try: return float(s) + except (TypeError, ValueError): return 0.0 + +def to_int(s, base=10): + try: return int(str(s).strip(), base) + except ValueError: return 0 + +def sections(frame): + """Splits a collector frame into {section name: lines}.""" + sec, cur = {}, None + for line in frame.replace('\r', '').split('\n'): + if line.startswith('@@S '): cur = sec.setdefault(line[4:].strip(), []) + elif cur is not None and not line.startswith('@@'): cur.append(line) + return sec + +def rates(state, dt): + """Returns delta(key, counters) -> per-second rates against the previous frame; remembers the new counters.""" + prev, state['counters'] = state.get('counters', {}), {} + + def delta(key, v): + p = prev.get(key, ()) + state['counters'][key] = v + 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) + return delta + +def add_disk(m, d, physical=True): + """Lists a disk; physical ones count towards the totals and the busiest-disk figure.""" + m.disks.append(d) + if physical: + m.disk_read_bps += d.read_bps + m.disk_write_bps += d.write_bps + if d.util >= m.max_disk_util: m.max_disk_util, m.busiest_disk = d.util, d.name + +def add_mount(m, mt): + m.mounts.append(mt) + if mt.pct >= m.max_disk_pct: m.max_disk_pct, m.fullest_mount = mt.pct, mt.mount + +def finish(m, sec, state, temp_unit): + """What every platform shares: percentages, totals, sensors (value / temp_unit = Celsius), cached GPUs and services, ordering.""" + m.mem_pct = m.mem_used * 100 / m.mem_total if m.mem_total > 0 else 0 + m.swap_pct = m.swap_used * 100 / m.swap_total if m.swap_total > 0 else 0 + 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')) + m.threads_total = sum(p.threads for p in m.procs) + if 'gpu' in sec: # nvidia-smi CSV; like the services it arrives every few samples: keep the last list + 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] + m.gpus, m.services = state.get('gpus', []), state.get('services', []) + m.services_failed = sum(s.active == 'failed' for s in m.services) + m.services_running = sum(s.sub == 'running' for s in m.services) + for line in sec.get('thermal', ()): + name, _, value = line.rpartition('|') + t = Temp(name.strip(), num(value) / temp_unit) + if name and 0 < t.celsius <= 150 and all(t.name != x.name for x in m.temps): m.temps.append(t) + m.max_temp = max((t.celsius for t in m.temps), default=0) + m.nets.sort(key=lambda n: (n.virt, n.name)) + m.procs.sort(key=lambda p: (-p.cpu, -p.rss)) + return m diff --git a/Server Monitor(python-window)/model.py b/Server Monitor(python-window)/model.py new file mode 100644 index 0000000000000000000000000000000000000000..a6c3f05c0a8c4c0523d4564ca98e2a4227eae409 --- /dev/null +++ b/Server Monitor(python-window)/model.py @@ -0,0 +1,117 @@ +"""Server configuration, alert rules, autopilot policy and text formatting.""" +import base64, binascii, math, uuid +from dataclasses import asdict, dataclass, field, fields + +import plat +from metrics import to_int + +# ---- formatting ------------------------------------------------------------- +def fmt_bytes(b, prec=1): + i = 0 + while abs(b) >= 1024 and i < 5: b, i = b / 1024, i + 1 + return f'{b:.{prec if i else 0}f} ' + 'B KB MB GB TB PB'.split()[i] + +def rate(b): return fmt_bytes(b) + '/s' +def pct(p, prec=1): return f'{p:.{prec}f}%' +def temp(c): return f'{c:.0f} °C' + +def count(v): + a = abs(v) + 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}' + +def duration(sec): + s = int(sec) + d, h, m = s // 86400, s % 86400 // 3600, s % 3600 // 60 + 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' + +def rnd(x): + """Rounds half up (Python's round() rounds half to even).""" + return math.floor(x + 0.5) + +def command(template, q='', n=None): + """Fills a platform command template: {q} = quoted argument, {n} = integer argument (default: q as a number).""" + return template.replace('{q}', plat.quote(str(q))).replace('{n}', str(to_int(q if n is None else n))) + +# ---- catalogues: (key, label, unit) and (key, label, argument hint) ------------ +RULE_METRICS = [d for d in ( + ('cpu', 'CPU usage', '%'), ('iowait', 'CPU I/O wait', '%'), ('load', 'Load (1 min) per core', '%'), ('mem', 'Memory usage', '%'), + ('swap', 'Swap usage', '%'), ('disk', 'Fullest disk usage', '%'), ('diskio', 'Busiest disk utilisation', '%'), + ('temp', 'Hottest sensor', '°C'), ('rx', 'Network download', 'MB/s'), ('tx', 'Network upload', 'MB/s'), ('failed', 'Failed services', ''), + ('procs', 'Process count', ''), ('gpu', 'GPU usage (max)', '%'), ('gputemp', 'GPU temperature (max)', '°C')) if plat.POSIX_CPU or d[0] != 'iowait'] +RULE_ACTIONS = [(k, text, plat.HINTS.get(k, '')) for k, text in ( + ('notify', 'Notify only'), ('restart_failed', 'Restart failed services'), ('restart_service', 'Restart a service'), + ('kill_top_cpu', 'Terminate top CPU process'), ('kill_top_mem', 'Terminate top memory process'), + ('drop_caches', 'Sync + drop page cache'), ('command', 'Run a command')) if k != 'drop_caches' or k in plat.CMD] + +def catalogue(defs, key, col=1): + """Label (col 1) or unit / hint (col 2) of a rule metric or action.""" + return next((d[col] for d in defs if d[0] == key), key if col == 1 else '') + +# ---- configuration (field names = servers.json keys) --------------------------- +@dataclass +class Rule: + """When for s -> (), again after s.""" + id: str = ''; metric: str = 'cpu'; op: str = '>'; action: str = 'notify'; arg: str = ''; severity: str = 'warning' + enabled: bool = True; value: float = 90.0; duration: int = 60; cooldown: int = 300 + def condition(self): + unit = catalogue(RULE_METRICS, self.metric, 2) + return (f'{catalogue(RULE_METRICS, self.metric)} {self.op} {self.value:g}' + (f' {unit}' if unit else '') + + (f' for {self.duration} s' if self.duration else '')) + def action_text(self): return catalogue(RULE_ACTIONS, self.action) + (f': {self.arg}' if self.arg else '') + +@dataclass +class AutopilotConfig: + """History-driven automatic control (evaluated by the analyzer every minute).""" + enabled: bool = True; dryRun: bool = False; restartFailed: bool = True; diskCleanup: bool = False; anomalyAlerts: bool = True + maxRestartsPerHour: int = 3; runawayMinutes: int = 10; diskForecastDays: int = 3 + runawayCpu: float = 90.0; diskCleanupAt: float = 92.0; leakMemPressure: float = 90.0; anomalyZ: float = 3.0 + runawayMode: str = 'renice'; leakMode: str = 'notify' # none|renice|terminate, none|notify|terminate + diskCleanupCommand: str = plat.CLEANUP + +def new_id(): return str(uuid.uuid4())[:12] + +def default_rules(): + return [Rule(new_id(), m, value=float(v), duration=d, severity=s) for m, v, d, s in ( + ('cpu', 90, 60, 'warning'), ('mem', 90, 60, 'warning'), ('swap', 80, 120, 'warning'), ('disk', 90, 0, 'critical'), + ('temp', 85, 30, 'critical'), ('load', 150, 120, 'warning'), ('failed', 0, 0, 'warning'))] + +def load(cls, o): + """Dataclass from a JSON object: known scalar fields only, converted to the declared type.""" + c = cls() + for f in fields(cls): + if f.type in (str, int, float, bool) and o.get(f.name) is not None: + try: setattr(c, f.name, f.type(o[f.name])) + except (TypeError, ValueError): pass + return c + +def xor_b64(s, encode): + """Light obfuscation of saved passwords (NOT encryption).""" + key = b'ServerMonitor/obfuscation/v1' + try: b = s.encode() if encode else base64.b64decode(s) + except binascii.Error: return '' + b = bytes(x ^ key[i % len(key)] for i, x in enumerate(b)) + return base64.b64encode(b).decode() if encode else b.decode('utf-8', 'replace') + +@dataclass +class ServerConfig: + id: str = ''; name: str = ''; group: str = ''; host: str = ''; user: str = ''; keyFile: str = ''; password: str = ''; notes: str = '' + transport: int = 1; port: int = 22; interval: int = plat.INTERVAL; useSudo: bool = False; enabled: bool = True # transport: 0 Local, 1 SSH + rules: list = field(default_factory=default_rules) + autopilot: AutopilotConfig = field(default_factory=AutopilotConfig) + def address(self): + if not self.transport: return 'this machine' + return (f'{self.user}@' if self.user else '') + self.host + (f':{self.port}' if self.port != 22 else '') + def to_json(self): return {**asdict(self), 'password': xor_b64(self.password, True)} + @classmethod + def from_json(cls, o): + c = load(cls, o) + c.autopilot = load(AutopilotConfig, o.get('autopilot', {})) + if 'rules' in o: c.rules = [load(Rule, r) for r in o['rules']] + for r in c.rules: r.id = r.id or new_id() + c.transport = 0 if o.get('transport', 1) == 0 else 1 + c.password = xor_b64(o.get('password', ''), False) + c.interval = min(max(c.interval, 1), 300) + c.id = c.id or new_id() + return c + +TRANSPORTS = ('Local', 'SSH') diff --git a/Server Monitor(python-window)/plat.py b/Server Monitor(python-window)/plat.py new file mode 100644 index 0000000000000000000000000000000000000000..5e2fc17e6da54780e871a73e8e794a74f420b26d --- /dev/null +++ b/Server Monitor(python-window)/plat.py @@ -0,0 +1,301 @@ +"""Platform module (Windows): everything OS-specific - collector script, process spawning, frame parser, +command tables and the texts that differ between the editions.""" +import atexit, functools, math, os, re, tempfile + +from metrics import Core, Disk, Metrics, Mount, Net, Proc, Service, add_disk, add_mount, finish, num, rates, sections, to_int + +NAME, HAS_SUDO, POSIX_CPU, INTERVAL = 'Windows', False, False, 3 # POSIX_CPU: I/O wait and steal exist; INTERVAL: default sample seconds +SPAWN = {'creationflags': 0x08000000} if os.name == 'nt' else {} # extra subprocess.Popen arguments: CREATE_NO_WINDOW +# PowerShell runs whatever script arrives on stdin: -EncodedCommand is "iex (@($input) -join [char]10)", so nothing needs quoting +PS_ARGS = ('-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -OutputFormat Text -EncodedCommand ' + 'aQBlAHgAIAAoAEAAKAAkAGkAbgBwAHUAdAApACAALQBqAG8AaQBuACAAWwBjAGgAYQByAF0AMQAwACkA').split() + +def config_dir(): return os.path.join(os.environ.get('APPDATA') or os.path.expanduser('~'), 'ServerMonitorPy') +def open_folder(path): os.startfile(path) + +def shell(interval=None): + """Command line that runs the script arriving on stdin (locally, or joined by spaces as the ssh remote command).""" + return ['powershell'] + PS_ARGS + +def collector(interval): + """Stdin for the collector process.""" + return f'$iv = {interval}; $once = $false\n' + COLLECTOR + +def kill(p): p.kill() +def quote(s): return "'" + s.replace("'", "''") + "'" + +def wrap(cmd, privileged, sudo): + """Stdin for a one-shot command (there is no sudo: run the app elevated for privileged actions).""" + return ("[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false; $ProgressPreference = 'SilentlyContinue'; " + '$Error.Clear(); $global:LASTEXITCODE = 0\n& {\n' + cmd + '\n} 2>&1 | Out-String -Width 250 -Stream\n' + 'if ($LASTEXITCODE) { exit $LASTEXITCODE }\n' # text a program writes to stderr is not a failure; its exit code or a failing cmdlet is + "if ($Error | Where-Object { $_.FullyQualifiedErrorId -notlike 'NativeCommandError*' }) { exit 1 }; exit 0\n") + +@functools.lru_cache(None) +def askpass(): + """Helper script that answers ssh's password prompt from %SERVERMONITOR_ASKPASS%; removed on exit.""" + fd, path = tempfile.mkstemp(prefix='servermonitor-askpass-', suffix='.cmd') + os.write(fd, b'@echo off\r\nsetlocal EnableDelayedExpansion\r\necho(!SERVERMONITOR_ASKPASS!\r\n') + os.close(fd) + atexit.register(os.remove, path) + return path + +def protected(p): + """Processes that are never killed automatically and get no leak / runaway findings.""" + return p.pid <= 4 or p.rss <= 0 or p.name in PROTECTED + +def thrashing(iowait, mem, disk_busy): + """Rest of the sentence "Swap … used" when heavy swap use is thrashing ('' = it is not); iowait and disk_busy are 15-minute averages.""" + return f', memory {mem:.1f}% full and disks {disk_busy:.1f}% busy' if mem > 90 and disk_busy > 50 else '' + +def priority_level(priority): + """How the priority column value compares with normal: > 0 raised, < 0 lowered.""" + return priority - 8 + +def cpu_tile(m): + """(value, sub text, warn) of the CPU tab tile TEXT['cpu_tile'].""" + return f'{m.cpu_irq:.1f}%', 'hardware interrupts and deferred calls', m.cpu_irq > 15 + +# ---- command tables (PowerShell): {q} = quoted argument, {n} = integer argument ---------------- +PROTECTED = {'System', 'Registry', 'Memory Compression', 'smss.exe', 'csrss.exe', 'wininit.exe', 'winlogon.exe', 'services.exe', 'lsass.exe', + 'svchost.exe', 'sshd.exe', 'dwm.exe'} +FAILED = "Get-CimInstance Win32_Service | Where-Object { $_.StartMode -eq 'Auto' -and $_.State -eq 'Stopped' -and $_.ExitCode -notin 0, 1077 }" +CMD = { + 'kill_pid': 'Stop-Process -Id {n} -Force', 'renice': "(Get-Process -Id {n}).PriorityClass = 'Idle'", + 'restart_service': 'Restart-Service -Name {q} -Force', + 'restart_failed': FAILED + ' | ForEach-Object { "restart $($_.Name)"; Start-Service -Name $_.Name }'} +CLEANUP = ('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') +HINTS = {'restart_service': 'Spooler', 'command': 'Clear-DnsClientCache'} # rule-argument placeholders +POWER = {'Reboot': 'shutdown /r /t 5', 'Shut down': 'shutdown /s /t 5'} +# (label, command, flags): b = toolbar button, c = ask first, d = dangerous +PROC_ACTIONS = [('End task', 'taskkill /PID {n}', 'bc'), ('Kill', 'taskkill /F /PID {n}', 'bcd'), ('Kill tree', 'taskkill /F /T /PID {n}', 'bcd')] +PRIORITIES = {v: v for v in ('Idle', 'BelowNormal', 'Normal', 'AboveNormal', 'High')} +PRIORITY_CMD = "(Get-Process -Id {n}).PriorityClass = '{v}'" +SERVICE_VERBS = { + 'start': 'Start-Service -Name {q}', 'stop': 'Stop-Service -Name {q} -Force', 'restart': 'Restart-Service -Name {q} -Force', + 'enable': 'Set-Service -Name {q} -StartupType Automatic', 'disable': 'Set-Service -Name {q} -StartupType Disabled'} +SERVICE_LOGS = ('$s = Get-CimInstance Win32_Service | Where-Object Name -eq {q}; $s | Format-List Name, DisplayName, State, StartMode, ExitCode, ProcessId, PathName; ' + "Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Service Control Manager' } -MaxEvents 3000 -ErrorAction Ignore | " + "Where-Object { $_.Message -like ('*' + $s.DisplayName + '*') } | Select-Object -First {n} | " + 'Format-Table TimeCreated, LevelDisplayName, Message -Wrap') +QUICK = [ # console: quick diagnostics + ('Disk usage', "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"), + ('Largest folders in C:\\', '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'), + ('Memory', 'Get-CimInstance Win32_OperatingSystem | Format-List TotalVisibleMemorySize, FreePhysicalMemory, TotalVirtualMemorySize, FreeVirtualMemory'), + ('Top CPU processes', "Get-Process | Sort-Object CPU -Descending | Select-Object -First 20 Id, ProcessName, CPU, " + "@{ n = 'MemMB'; e = { [int]($_.WorkingSet64 / 1MB) } }, StartTime"), + ('Listening ports', 'Get-NetTCPConnection -State Listen | Sort-Object LocalPort | Format-Table LocalAddress, LocalPort, OwningProcess'), + ('System errors', "Get-WinEvent -FilterHashtable @{ LogName = 'System'; Level = 1, 2 } -MaxEvents 40 | Format-Table TimeCreated, ProviderName, Message -Wrap"), + ('Application errors', "Get-WinEvent -FilterHashtable @{ LogName = 'Application'; Level = 1, 2 } -MaxEvents 40 | Format-Table TimeCreated, ProviderName, Message -Wrap"), + ('Failed services', FAILED + ' | Format-Table Name, ExitCode, DisplayName'), + ('Logged-in users', 'quser'), + ('Last boots', "Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = 6005, 6006, 1074 } -MaxEvents 15 | Format-Table TimeCreated, Id, Message -Wrap")] +ACTIONS = [ # console: system actions (confirmed, privileged); the POWER ones are shown as dangerous + ('Clean temp files', CLEANUP), ('Flush DNS cache', "Clear-DnsClientCache; 'done'"), ('Restart failed services', CMD['restart_failed']), + ('Reboot', POWER['Reboot']), ('Shut down', POWER['Shut down'])] +TEXT = { + 'cpu_tile': 'Interrupts + DPC', 'priority': 'Priority', 'kernel': 'build ', + 'renice': 'Set priority to Idle', 'renice_mode': 'Lower priority (Idle class)', 'renice_advice': 'Lower its priority or stop it if it is stuck.', + 'ssh_hint': 'Uses your system ssh client. The server needs the OpenSSH Server feature and PowerShell; nothing else is installed. ' + "For key login, add your public key to the server's authorized_keys.", + 'key_hint': 'default keys / ssh-agent (%USERPROFILE%\\.ssh\\id_*)', + 'console_hint': 'Type a PowerShell command and press Enter (↑/↓ history)'} + +# ---- collector frame parser ------------------------------------------------------------------- +VIRTUAL_IF = re.compile(r'virtual ethernet|virtualbox|vmware virtual|vethernet|loopback|pseudo|tap-|bluetooth|wan miniport|wsl|docker', re.I) +TCP_STATES = {'Established': 'ESTABLISHED', 'Listen': 'LISTEN', 'TimeWait': 'TIME_WAIT', 'CloseWait': 'CLOSE_WAIT'} + +def parse(frame, st, now): + """Collector frame -> Metrics; st keeps the counters of the previous frame (rates), the load averages and the slow sections.""" + sec, m = sections(frame), Metrics(now) + + def rows(name, fields): # |-separated rows of a section with at least that many fields + return [f for f in (l.split('|') for l in sec.get(name, ())) if len(f) >= fields] + + def values(name): # key=value section -> number lookup (missing or empty = 0) + kv = dict(l.split('=', 1) for l in sec.get(name, ()) if '=' in l) + return lambda k: num(kv.get(k)) + + if 'info' in sec: st['info'] = dict(l.split('=', 1) for l in sec['info'] if '=' in l) + if 'users' in sec: st['users'] = {to_int(f[0]): f[1] for f in rows('users', 2)} + info, osv, sysv, mem = st.get('info', {}), values('os'), values('sys'), values('mem') + m.hostname, m.os, m.kernel, m.arch, m.cpu_model, m.virt = (info.get(k, '').strip() for k in ('hostname', 'os', 'kernel', 'arch', 'cpumodel', 'virt')) + m.uptime = osv('uptime') + if m.uptime <= 0: return m + ts = osv('ts') or now + dt = max(0.0, (ts - st['ts']) / 1000) if 'ts' in st else 0.0 + live, delta = dt > 0.05, rates(st, dt) + + # CPU: name|total%|user%|privileged%|irq%|interrupts/s; "_Total" is the machine, the other names are cores + mhz, cores = num(info.get('mhz')), [] + for f in rows('cpu', 2): + total, user, privileged, irq, interrupts = (num(x) for x in (f[1:6] + [''] * 5)[:5]) + if f[0] == '_Total': + m.cpu_usage, m.cpu_user, m.cpu_irq, m.cpu_system, m.intr_per_sec = total, user, irq, max(0.0, privileged - irq), interrupts + else: + cores.append((to_int(f[0]), Core(total, mhz))) + m.cores, m.avg_mhz = [c for _, c in sorted(cores)], mhz + m.cpu_count = max(1, len(cores)) + # load average with the Unix meaning: running + waiting tasks, as 1 / 5 / 15 minute exponential moving averages + queue = sysv('queue') + instant = m.cpu_usage / 100 * m.cpu_count + queue + st['load'] = [l + (instant - l) * (1 - math.exp(-dt / t)) for l, t in zip(st['load'], (60, 300, 900))] if 'load' in st else [instant] * 3 + m.load1, m.load5, m.load15 = st['load'] + m.procs_running, m.procs_blocked, m.ctxt_per_sec = math.floor(m.cpu_usage / 100 * m.cpu_count + 0.5), int(queue), sysv('ctxt') + + # memory + m.mem_total, m.swap_total, m.mem_available, m.mem_free = osv('memtotal'), osv('swaptotal'), mem('avail'), mem('free') + m.cached, m.slab, m.dirty = mem('standby') + mem('syscache'), mem('pool'), mem('modified') + m.mem_used, m.swap_used = max(0.0, m.mem_total - m.mem_available), m.swap_total - osv('swapfree') + + # network: name|status|speedMbps|type|rxBytes|txBytes|rxPkts|txPkts|errors|drops|description + for f in rows('net', 10): + rx, tx = num(f[4]), num(f[5]) + virtual = f[3] in ('Loopback', 'Tunnel') or bool(VIRTUAL_IF.search(' '.join([f[0]] + f[10:]))) + m.nets.append(Net(f[0], f[1].lower(), to_int(f[2]), virtual, *delta('net:' + f[0], [rx, tx, num(f[6]), num(f[7])]), rx, tx, num(f[8]), num(f[9]))) + for f in map(str.split, sec.get('tcp', ())): + if len(f) > 1: + name = TCP_STATES.get(f[0], f[0].upper()) + m.tcp[name] = m.tcp.get(name, 0) + to_int(f[1]) + m.sockets_used = sum(m.tcp.values()) + + # disks: name|readBps|writeBps|readIops|writeIops|idle% file systems: mount|label|fs|total|free + for f in rows('disk', 5): + idle = ''.join(f[5:6]).strip() + add_disk(m, Disk(f[0], num(f[1]), num(f[2]), num(f[3]), num(f[4]), min(max(100 - num(idle), 0.0), 100.0) if idle else 0.0, 0.0, 0.0)) + for f in rows('df', 5): + total, free = num(f[3]), num(f[4]) + if total > 0: add_mount(m, Mount(f[1], f[2], f[0], total, total - free, free, (total - free) * 100 / total)) + + # processes: pid|ppid|cpuTime100ns|priority|threads|createdUnixSec|vsz|rss|name + old, users, ticks = st.get('ticks', {}), st.get('users', {}), {} + for f in rows('procs', 9): + pid, born, rss = to_int(f[0]), num(f[5]), num(f[7]) + if not pid: continue + ticks[pid] = num(f[2]) + cpu = min(max((ticks[pid] - old[pid]) / 1e7 / dt * 100, 0.0), 100.0 * m.cpu_count) if live and pid in old else 0.0 + m.procs.append(Proc(pid, to_int(f[1]), to_int(f[4]), to_int(f[3]), '|'.join(f[8:]), users.get(pid) or '—', 'R' if cpu > 0.5 else 'S', cpu, + rss * 100 / m.mem_total if m.mem_total > 0 else 0, rss, num(f[6]), max(0.0, ts / 1000 - born) if born else 0.0)) + m.forks_per_sec = sum(pid not in old for pid in ticks) / dt if live and old else 0.0 + + if 'services' in sec: # name|state|startmode|exitcode|display + st['services'] = [Service(f[0], f[2], 'failed' if f[2] == 'Auto' and f[1] == 'Stopped' and to_int(f[3]) not in (0, 1077) + else 'active' if f[1] == 'Running' else 'inactive', f[1].lower(), '|'.join(f[4:])) for f in rows('services', 4)] + m.logged_users = to_int(''.join(sec.get('sessions', [])[:1])) + st['ticks'], st['ts'] = ticks, ts + m.valid = live # the first sample has no rates yet + return finish(m, sec, st, 1) + +COLLECTOR = r'''# Server Monitor collector for Windows (PowerShell 5.1+, ASCII only). +# The caller prepends "$iv = ; $once = $false". One frame per interval: +# "@@SNAP_BEGIN", "@@S
" + rows (key=value or |-separated), "@@SNAP_END". +$ErrorActionPreference = 'SilentlyContinue' +$ProgressPreference = 'SilentlyContinue' +[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false +function Cim($class, $ns = 'root/cimv2') { Get-CimInstance -ClassName $class -Namespace $ns } +function Clean($s) { ("$s" -replace '[|\r\n]', ' ').Trim() } +$epoch = [DateTime]'1970-01-01' +$smi = Get-Command nvidia-smi.exe | Select-Object -First 1 -ExpandProperty Path +# Console.Out reports no error when the pipe is closed, so the collector also ends when its parent process is gone. +$parent = Get-Process -Id (Get-CimInstance Win32_Process -Filter "ProcessId = $PID").ParentProcessId +$n = 0 +while ($true) { + $t0 = Get-Date + $out = New-Object System.Collections.Generic.List[string] + $out.Add('@@SNAP_BEGIN') + $os = Cim Win32_OperatingSystem + if ($n % 15 -eq 0) { + $cs = Cim Win32_ComputerSystem + $cpu = @(Cim Win32_Processor)[0] + $virt = Clean ($cs.Manufacturer + ' ' + $cs.Model) + $admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) + $out.Add('@@S info') + $out.Add("hostname=$($cs.Name)") + $out.Add("os=$(Clean $os.Caption)") + $out.Add("kernel=$($os.Version)") + $out.Add("arch=$($os.OSArchitecture)") + $out.Add("cpumodel=$(Clean $cpu.Name)") + $out.Add("mhz=$($cpu.MaxClockSpeed)") + $out.Add("virt=$virt") + $out.Add("admin=$([int]$admin)") + if ($admin) { + $out.Add('@@S users') + Get-Process -IncludeUserName | ForEach-Object { $out.Add("$($_.Id)|$($_.UserName)") } + } + } + $out.Add('@@S os') + $out.Add("ts=$([long](([DateTime]::UtcNow - $epoch).TotalMilliseconds))") + $out.Add("uptime=$([long](((Get-Date) - $os.LastBootUpTime).TotalSeconds))") + $out.Add("memtotal=$([long]$os.TotalVisibleMemorySize * 1024)") + $out.Add("swaptotal=$([long]$os.SizeStoredInPagingFiles * 1024)") + $out.Add("swapfree=$([long]$os.FreeSpaceInPagingFiles * 1024)") + $out.Add('@@S cpu') + Cim Win32_PerfFormattedData_PerfOS_Processor | ForEach-Object { + $out.Add("$($_.Name)|$($_.PercentProcessorTime)|$($_.PercentUserTime)|$($_.PercentPrivilegedTime)|$([long]$_.PercentInterruptTime + [long]$_.PercentDPCTime)|$($_.InterruptsPersec)") + } + $sys = Cim Win32_PerfFormattedData_PerfOS_System + $out.Add('@@S sys') + $out.Add("queue=$($sys.ProcessorQueueLength)") + $out.Add("ctxt=$($sys.ContextSwitchesPersec)") + $out.Add("threads=$($sys.Threads)") + $pm = Cim Win32_PerfFormattedData_PerfOS_Memory + $out.Add('@@S mem') + $out.Add("avail=$($pm.AvailableBytes)") + $out.Add("free=$($pm.FreeAndZeroPageListBytes)") + $out.Add("standby=$([long]$pm.StandbyCacheCoreBytes + [long]$pm.StandbyCacheNormalPriorityBytes + [long]$pm.StandbyCacheReserveBytes)") + $out.Add("syscache=$($pm.CacheBytes)") + $out.Add("modified=$($pm.ModifiedPageListBytes)") + $out.Add("pool=$([long]$pm.PoolPagedBytes + [long]$pm.PoolNonpagedBytes)") + $out.Add("commit=$($pm.CommittedBytes)") + $out.Add("commitlimit=$($pm.CommitLimit)") + $out.Add("pages=$($pm.PagesPersec)") + $out.Add('@@S net') + [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | ForEach-Object { + $s = $null + $s = $_.GetIPStatistics() + 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)") } + } + $ip = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties() + $out.Add('@@S tcp') + $ip.GetActiveTcpConnections() | Group-Object State | ForEach-Object { $out.Add("$($_.Name) $($_.Count)") } + $out.Add("Listen $(@($ip.GetActiveTcpListeners()).Count)") + $out.Add('@@S disk') + Cim Win32_PerfFormattedData_PerfDisk_PhysicalDisk | Where-Object { $_.Name -ne '_Total' } | ForEach-Object { + $out.Add("$(Clean $_.Name)|$($_.DiskReadBytesPersec)|$($_.DiskWriteBytesPersec)|$($_.DiskReadsPersec)|$($_.DiskWritesPersec)|$($_.PercentIdleTime)") + } + $out.Add('@@S df') + [System.IO.DriveInfo]::GetDrives() | Where-Object { $_.IsReady -and $_.DriveType -eq 'Fixed' } | ForEach-Object { + $out.Add("$($_.Name)|$(Clean $_.VolumeLabel)|$($_.DriveFormat)|$($_.TotalSize)|$($_.AvailableFreeSpace)") + } + $sessions = @{} + $out.Add('@@S procs') + Cim Win32_Process | ForEach-Object { + $born = 0 + if ($_.CreationDate) { $born = [long](($_.CreationDate.ToUniversalTime() - $epoch).TotalSeconds) } + if ($_.Name -eq 'explorer.exe') { $sessions[$_.SessionId] = 1 } + $out.Add("$($_.ProcessId)|$($_.ParentProcessId)|$([long]$_.KernelModeTime + [long]$_.UserModeTime)|$($_.Priority)|$($_.ThreadCount)|$born|$($_.VirtualSize)|$($_.WorkingSetSize)|$(Clean $_.Name)") + } + $out.Add('@@S sessions') + $out.Add("$($sessions.Count)") + if ($n % 5 -eq 0) { + $out.Add('@@S services') + Cim Win32_Service | ForEach-Object { $out.Add("$($_.Name)|$($_.State)|$($_.StartMode)|$($_.ExitCode)|$(Clean $_.DisplayName)") } + } + $out.Add('@@S thermal') + Cim MSAcpi_ThermalZoneTemperature 'root/wmi' | ForEach-Object { $out.Add("$(Clean $_.InstanceName)|$(($_.CurrentTemperature - 2732) / 10)") } + if ($smi -and $n % 3 -eq 0) { + $out.Add('@@S gpu') + & $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("$_") } + } + $out.Add('@@SNAP_END') + try { [Console]::Out.Write(($out -join "`n") + "`n"); [Console]::Out.Flush() } catch { exit } + if ($once -or $parent.HasExited) { break } + $n++ + $left = $iv * 1000 - ((Get-Date) - $t0).TotalMilliseconds + if ($left -gt 0) { Start-Sleep -Milliseconds ([int]$left) } +} +''' diff --git a/Server Monitor(python-window)/run.bat b/Server Monitor(python-window)/run.bat new file mode 100644 index 0000000000000000000000000000000000000000..c4f7ebb3737488804f13f98d580ab246753ac49f --- /dev/null +++ b/Server Monitor(python-window)/run.bat @@ -0,0 +1,3 @@ +@echo off +rem Start Server Monitor without a console window (needs Python 3.8+ from python.org). +where pythonw >nul 2>nul && (start "" pythonw "%~dp0main.py" %*) || (start "" pyw "%~dp0main.py" %*) diff --git a/Server Monitor(python-window)/session.py b/Server Monitor(python-window)/session.py new file mode 100644 index 0000000000000000000000000000000000000000..8938a2107fc333a6c2794a782cd8182d32fbf528 --- /dev/null +++ b/Server Monitor(python-window)/session.py @@ -0,0 +1,411 @@ +"""Connection to one machine (local shell or system ssh), the per-server session +(metrics, live history, rules, autopilot) and the manager of all sessions.""" +import json, os, queue, shutil, subprocess, threading, time +from collections import namedtuple +from datetime import datetime +from types import SimpleNamespace + +import plat +from history import Analysis, ProcTrend, ServiceTrend, Store, analyze +from metrics import Metrics +from model import RULE_METRICS, ServerConfig, catalogue, command, new_id + +PIPE = subprocess.PIPE +SSH_OPTIONS = ['ConnectTimeout=10', 'ServerAliveInterval=10', 'ServerAliveCountMax=3', 'StrictHostKeyChecking=accept-new', 'LogLevel=ERROR'] +STATUS = ('Disabled', 'Connecting', 'Online', 'Offline') +DISABLED, CONNECTING, ONLINE, OFFLINE = range(4) +AlertEvent = namedtuple('AlertEvent', 'time server severity message') # severity: info|warning|critical|resolved|action + +# ---- UI-thread dispatch ----------------------------------------------------------------- +class Loop: + """Hands work to the UI thread: worker threads post() calls, timers are due in pump(), which the UI calls often.""" + def __init__(self): self.calls, self.timers = queue.SimpleQueue(), set() + def post(self, fn, *args): self.calls.put((fn, args)) + def pump(self): + while not self.calls.empty(): + fn, args = self.calls.get() + fn(*args) + now = time.monotonic() + for t in [t for t in self.timers if t.due <= now]: + if t in self.timers: # not stopped by a call that ran just before + t.start() if t.every else t.stop() + t.fn() + +loop = Loop() + +class Timer: + """Restartable timer on the loop; with every (seconds) it repeats.""" + def __init__(self, fn, every=0): + self.fn, self.every = fn, every + if every: self.start() + def start(self, seconds=None): + self.due = time.monotonic() + (seconds or self.every) + loop.timers.add(self) + def stop(self): loop.timers.discard(self) + +class Signal(list): + """List of listeners; calling it calls them all.""" + def __call__(self, *args): + for fn in list(self): fn(*args) + +# ---- Link --------------------------------------------------------------------------------- +class Link: + """Streams collector frames and runs one-shot commands on one machine. close() kills everything.""" + def __init__(self, cfg, on_frame, on_lost): + self.cfg, self.on_frame, self.on_lost, self.procs, self.pending, self.closed = cfg, on_frame, on_lost, set(), {}, False + def spawn(self, interval=None, **kw): + c, argv, env = self.cfg, plat.shell(interval), None + if c.transport: + options = SSH_OPTIONS + (['NumberOfPasswordPrompts=1'] if c.password else ['BatchMode=yes']) + if c.password: # a helper script answers ssh's password prompt + env = {'DISPLAY': ':0', **os.environ, 'SSH_ASKPASS': plat.askpass(), 'SSH_ASKPASS_REQUIRE': 'force', 'SERVERMONITOR_ASKPASS': c.password} + argv = ['ssh', *(x for o in options for x in ('-o', o)), *(['-i', os.path.expanduser(c.keyFile)] if c.keyFile else []), + *(['-p', str(c.port)] if c.port != 22 else []), '-T', f'{c.user}@{c.host}' if c.user else c.host, ' '.join(argv)] + try: p = subprocess.Popen(argv, stdin=PIPE, stdout=PIPE, env=env, **plat.SPAWN, **kw) + except OSError as e: raise OSError(f'cannot start {argv[0]}: {e.strerror}') from e + self.procs.add(p) + return p + def post(self, fn, *args): # results reach the UI thread, unless the link was closed meanwhile + loop.post(lambda: self.closed or fn(*args)) + def start(self): + try: p = self.spawn(self.cfg.interval, stderr=PIPE) + except OSError as e: return self.post(self.on_lost, str(e)) + threading.Thread(target=self.stream, args=(p,), daemon=True).start() + def stream(self, p): # worker thread: frames out of stdout, the last error line out of stderr + buf, err = b'', [b''] + + def errors(): + for chunk in iter(lambda: p.stderr.read1(4096), b''): err[0] = (err[0] + chunk)[-4096:] + + reader = threading.Thread(target=errors, daemon=True) + reader.start() + try: + p.stdin.write(plat.collector(self.cfg.interval).encode()) + p.stdin.close() + for chunk in iter(lambda: p.stdout.read1(1 << 16), b''): + buf += chunk + while b'@@SNAP_END' in buf: + end = buf.find(b'@@SNAP_END') + begin = buf.rfind(b'@@SNAP_BEGIN', 0, end) + if begin >= 0 and loop.calls.qsize() < 100: # a stalled UI must not pile up frames + self.post(self.on_frame, buf[begin:end].decode('utf-8', 'replace')) + buf = buf[end + 10:] + if len(buf) > 8 << 20: buf = b'' + except (OSError, ValueError): + pass # killed while writing or reading + code = p.wait() + reader.join(2) + lines = err[0].decode('utf-8', 'replace').split('\n') + self.post(self.on_lost, next((l.strip() for l in reversed(lines) if l.strip()), f'connection closed (exit code {code})')) + def exec(self, script, timeout, done=None): + """Runs a script; done(code, output) is called on the UI thread (code -1: killed, timed out or not started).""" + try: p = self.spawn(stderr=subprocess.STDOUT) + except OSError as e: return done and self.post(done, -1, str(e)) + self.pending[p] = done + + def work(): + try: + out, code = p.communicate(script.encode(), timeout)[0], p.returncode + except subprocess.TimeoutExpired: + plat.kill(p) + try: out, code = p.communicate(timeout=2)[0], -1 + except subprocess.TimeoutExpired: out, code = b'', -1 # something it started still holds the pipe + 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 '')) + + threading.Thread(target=work, daemon=True).start() + def finished(self, p, code, out): + self.procs.discard(p) + done = self.pending.pop(p) + if done: done(code, out) + def close(self, reason='connection stopped'): + self.closed = True + for p in self.procs: plat.kill(p) + for done in self.pending.values(): + if done: done(-1, reason) + +# ---- live history ----------------------------------------------------------------------- +class Live: + """The last hour of samples in memory, for the live charts.""" + KEYS, CAP = 'cpu user sys iowait steal mem cache swap rx tx rd wr load'.split(), 1800 + def __init__(self): self.t, self.s, self.if_rx, self.if_tx = [], {k: [] for k in self.KEYS}, {}, {} + def push(self, m): + n = len(self.t) + + def add(v, x): + v[:0] = [0.0] * (n - len(v)) # align series that appeared later + v.append(x) + del v[:-self.CAP] + + add(self.t, m.timestamp) + values = (m.cpu_usage, m.cpu_user, m.cpu_system + m.cpu_irq, m.cpu_iowait, m.cpu_steal, m.mem_pct, + (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, + m.disk_read_bps, m.disk_write_bps, m.load1) + for k, x in zip(self.KEYS, values): add(self.s[k], x) + for i in m.nets: + add(self.if_rx.setdefault(i.name, []), i.rx_bps) + add(self.if_tx.setdefault(i.name, []), i.tx_bps) + +# ---- session ---------------------------------------------------------------------------- +class Session: + def __init__(self, cfg): + self.cfg, self.status, self.err, self.link, self.engine = cfg, DISABLED, '', None, {} + self.m, self.live, self.an = Metrics(), Live(), Analysis() + self.store = Store(os.path.join(Manager.config_dir(), 'history', cfg.id)) + self.retries, self.paused, self.offline_alerted = 0, False, False + self.reported, self.dry, self.cooldown, self.rules, self.procs, self.svcs = set(), set(), {}, {}, {}, {} # analyzer / rule / tracking state + self.updated, self.analysis_updated, self.alert = Signal(), Signal(), Signal() + self.retry, self.watchdog, first = Timer(self.start), Timer(lambda: self.lost('no data received (timeout)')), Timer(self.analyze) + self.offline = Timer(self.down, cfg.interval) # downtime -> availability: one sample per interval, like uptime + self.timers = [self.retry, self.watchdog, first, self.offline, Timer(self.analyze, 60)] + first.start(3) + def online(self): return self.status == ONLINE and self.m.valid + def down(self): + if self.status == OFFLINE or (self.status == CONNECTING and self.retries): self.record(False) + def set_config(self, c): + old, self.cfg, self.offline.every = self.cfg, c, c.interval + if any(getattr(c, k) != getattr(old, k) for k in ('transport', 'host', 'port', 'user', 'keyFile', 'password', 'interval', 'enabled')): + self.live, self.m, self.procs, self.svcs = Live(), Metrics(), {}, {} # may be another machine now + self.start() if c.enabled else self.stop() + self.updated() + def set_paused(self, paused): + self.paused = paused + self.updated() + def reconnect(self): + self.retries, self.paused = 0, False + self.start() + def drop_link(self, reason): + self.retry.stop() + self.watchdog.stop() + link, self.link = self.link, None + if link: link.close(reason) + def start(self): + self.drop_link('connection restarted') + if not self.cfg.enabled: return self.set_status(DISABLED) + self.engine, self.m.valid = {}, False # online() only again with a fresh sample + self.link = Link(self.cfg, self.frame, self.lost) + self.set_status(CONNECTING) + self.watchdog.start(25) + self.link.start() + def stop(self): + self.drop_link('connection stopped') + self.set_status(OFFLINE if self.cfg.enabled else DISABLED) + def close(self): + self.stop() + for t in self.timers: t.stop() + def set_status(self, status, err=''): + if err or status == ONLINE: self.err = err + if status != self.status: + self.status = status + self.updated() + def frame(self, raw): + now = time.time() * 1000 + self.watchdog.start(max(15, self.cfg.interval * 5 + 10)) + m = plat.parse(raw, self.engine, now) + if m.uptime <= 0: return + if self.status != ONLINE: + self.retries = 0 + if self.offline_alerted: self.raise_alert('resolved', 'Server is back online') + self.offline_alerted = False + self.set_status(ONLINE) + if not m.valid or self.paused: # the first sample has no rates yet + return + if m.uptime < self.m.uptime: self.procs = {} # rebooted: PIDs start again, old trends would be blamed on new processes + first, self.m = not self.m.valid, m + self.live.push(m) + self.record(True) + self.track(now) + self.evaluate_rules() + if first: self.analyze() # first sample of this connection: the last analysis saw "unreachable" + self.updated() + def lost(self, why): + was = self.status == ONLINE + self.drop_link('connection lost: ' + why) + self.set_status(OFFLINE, why) + if (was or self.retries == 1) and not self.offline_alerted: + self.raise_alert('critical', 'Server is unreachable: ' + why) + self.offline_alerted = True + if self.cfg.enabled: + self.retry.start((3, 5, 10, 20, 30, 60)[min(self.retries, 5)]) # back-off + self.retries += 1 + def exec(self, cmd, privileged, done=None, timeout=60): + """Runs a command on the machine; privileged ones go through sudo when the server is set up for it.""" + if self.link and self.status == ONLINE: self.link.exec(plat.wrap(cmd, privileged, self.cfg.useSudo), timeout, done) + elif done: loop.post(done, -1, 'server is not connected') + def metric_value(self, key): + m = self.m + 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, + '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, + 'failed': m.services_failed, 'procs': len(m.procs), 'gpu': m.gpu_max(), 'gputemp': m.gpu_max(True)}.get(key, 0) + def active_alerts(self): + down = ['Unreachable: ' + self.err] if self.status == OFFLINE else [] + return down + [r.condition() for r in self.cfg.rules if r.id in self.rules and self.rules[r.id].active] + def raise_alert(self, severity, message): self.alert(AlertEvent(datetime.now(), self.cfg.name, severity, message)) + def record(self, up): + m, nan = self.m, float('nan') + self.store.add(int(time.time()), ( + 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, + 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), + m.gpu_max() if m.gpus else nan, m.services_failed), up) + def track(self, now): + """Per-process CPU streaks and RSS per minute; service failure transitions.""" + procs = {} + for p in self.m.procs: + t = self.procs.get(p.pid) + if not t or t.name != p.name: # new, or the pid was reused + t = SimpleNamespace(name=p.name, high_since=0, last_minute=0, rss=[]) + t.protected = plat.protected(p) + t.high_since = 0 if p.cpu < self.cfg.autopilot.runawayCpu else t.high_since or now + if now - t.last_minute >= 60000: t.last_minute, t.rss = now, t.rss[-59:] + [p.rss] + procs[p.pid] = t + self.procs, svcs = procs, {} + for s in self.m.services: + t, failed = self.svcs.get(s.unit) or SimpleNamespace(last='', preexisting=False, fails=[], restarts=[]), s.active == 'failed' + svcs[s.unit] = t + if not t.last: + t.preexisting = failed # failed before monitoring started: leave it alone + elif failed and t.last != 'failed': + t.fails.append(now) + t.preexisting = False + elif not failed: + t.preexisting = False + t.last = s.active + t.fails, t.restarts = ([x for x in v if now - x <= 3600000] for v in (t.fails, t.restarts)) + if svcs: self.svcs = svcs # forgets removed services; a sample without a service list changes nothing + def evaluate_rules(self): + now, m = time.time() * 1000, self.m + for r in self.cfg.rules: + st = self.rules.setdefault(r.id, SimpleNamespace(since=0, last_fire=0, active=False)) + v = self.metric_value(r.metric) + idle = not r.enabled or (r.metric in ('gpu', 'gputemp') and not m.gpus) or (r.metric == 'temp' and not m.temps) + if idle or (v >= r.value if r.op == '<' else v <= r.value): + if st.active and not idle: self.raise_alert('resolved', f'Recovered: {r.condition()} (now {v:.1f})') + del self.rules[r.id] + continue + st.since = st.since or now + if now - st.since < r.duration * 1000 or (st.active and (r.action == 'notify' or now - st.last_fire < r.cooldown * 1000)): continue + unit = catalogue(RULE_METRICS, r.metric, 2) + if not st.active: self.raise_alert(r.severity, f'{r.condition()} (now {v:.1f}' + (f' {unit}' if unit else '') + ')') + st.active, st.last_fire = True, now + action, arg = r.action, r.arg + if action.startswith('kill_top'): # heaviest process that is not protected + 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) + action, arg = ('kill_pid', str(best.pid)) if best else ('notify', '') + if action != 'notify': self.run(action, arg, f'Automation "{r.condition()}": {r.action_text()}') + def run(self, action, arg, what, done=None): + cmds = {'command': arg, 'disk_cleanup': self.cfg.autopilot.diskCleanupCommand, **{k: command(v, arg) for k, v in plat.CMD.items()}} + if not cmds.get(action): return done and done(-1, 'nothing to do') + + def report(code, out): + tail = ' '.join(out.split())[-300:] # one line: events are lines in alerts.log + self.raise_alert('action', f'{what} -> ' + (f'failed ({code})' if code else 'OK') + (f' | {tail}' if tail else '')) + if done: done(code, out) + + self.exec(cmds[action], True, report, 300) + def run_finding(self, f, automatic, done=None): + if automatic and f.action == 'restart_service': self.svcs[f.arg].restarts.append(time.time() * 1000) + self.run(f.action, '' if f.action == 'disk_cleanup' else f.arg, ('Autopilot: ' if automatic else 'Manual fix: ') + f'{f.label} ({f.title})', done) + def analyze(self): + now, trends, ap = time.time() * 1000, [], self.cfg.autopilot + for p in self.m.procs: + t = self.procs.get(p.pid) + rss = t.rss if t else [] + growth = rss[-1] - rss[0] if len(rss) >= 2 else 0 + 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, + growth * 100 / rss[0] if growth and rss[0] > 0 else 0, + 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)) + if pt.high_cpu_minutes > 0 or pt.minutes >= 30: trends.append(pt) + svcs = [ServiceTrend(unit, t.last == 'failed', t.preexisting, len(t.fails), len(t.restarts)) + for unit, t in self.svcs.items() if t.last == 'failed' or t.fails] + self.an = analyze(self.store, self.m, ap, trends, svcs, self.online()) + + for f in self.an.findings: # announce each new finding once + if f.key not in self.reported and f.category != 'Availability': self.raise_alert(f.severity, f'Insight: {f.title} - {f.detail}') + self.reported = {f.key for f in self.an.findings} + + dry = set() # act on eligible findings, with cooldowns; a dry run says once what it would do + for f in self.an.findings if ap.enabled and self.online() else (): + if not f.auto: continue + if ap.dryRun: + dry.add(f.key) + if f.key not in self.dry: self.raise_alert('action', f'Autopilot (dry run) would: {f.label} - {f.title}') + elif now - self.cooldown.get(f.key, 0) >= {'disk_cleanup': 6 * 3600000, 'restart_service': 120000}.get(f.action, 900000): + self.cooldown[f.key] = now + self.run_finding(f, True) + self.dry = dry + self.analysis_updated() + +# ---- manager ---------------------------------------------------------------------------- +class Manager: + def __init__(self): + self.sessions, self.alerts = [], [] + self.changed, self.alert, self.cleared = Signal(), Signal(), Signal() # server list changed, alert raised, alerts cleared + @staticmethod + def config_dir(): + os.makedirs(plat.config_dir(), exist_ok=True) + return plat.config_dir() + def path(self, name): return os.path.join(self.config_dir(), name) + def session(self, server_id): return next((s for s in self.sessions if s.cfg.id == server_id), None) + def attach(self, cfg): + s = Session(cfg) + s.alert.append(self.on_alert) + self.sessions.append(s) + return s + def on_alert(self, e): + self.alerts[:0] = [e] + del self.alerts[2000:] + log = self.path('alerts.log') + try: + with open(log, 'w' if os.path.exists(log) and os.path.getsize(log) > 5 << 20 else 'a', encoding='utf-8') as f: + f.write(f'{e.time.isoformat(timespec="seconds")}\t{e.severity}\t{e.server}\t{e.message}\n') + except OSError: + pass # the event still reaches the window + self.alert(e) + def load(self): + try: + with open(self.path('servers.json'), encoding='utf-8') as f: + for o in json.load(f)['servers']: self.attach(ServerConfig.from_json(o)) + except FileNotFoundError: # first start: monitor this machine + self.attach(ServerConfig(new_id(), 'This computer', 'Local', transport=0)) + self.save() + except (OSError, ValueError, LookupError, TypeError, AttributeError): + pass # unreadable or damaged file: start with the servers read so far + for s in self.sessions: s.start() + self.changed() + def save(self): + tmp = self.path('servers.json.tmp') + with open(os.open(tmp, os.O_WRONLY | os.O_CREAT | os.O_TRUNC, 0o600), 'w', encoding='utf-8') as f: + json.dump({'version': 1, 'servers': [s.cfg.to_json() for s in self.sessions]}, f, indent=4) + os.replace(tmp, self.path('servers.json')) + def add(self, cfg): + s = self.attach(cfg) + self.save() + s.start() + self.changed() + return s + def update(self, cfg): + s = self.session(cfg.id) + if s: + s.set_config(cfg) + self.save() + self.changed() + def remove(self, server_id, delete_history): + s = self.session(server_id) + if not s: return + self.sessions.remove(s) + s.alert.clear() + s.close() + if delete_history: shutil.rmtree(s.store.dir, ignore_errors=True) + self.save() + self.changed() + def move(self, server_id, delta): + i = self.sessions.index(self.session(server_id)) + j = min(max(i + delta, 0), len(self.sessions) - 1) + if i != j: + self.sessions.insert(j, self.sessions.pop(i)) + self.save() + self.changed() + def clear_alerts(self): + self.alerts.clear() + self.cleared() + def close(self): + for s in self.sessions: s.close() diff --git a/Server Monitor(python-window)/tabs.py b/Server Monitor(python-window)/tabs.py new file mode 100644 index 0000000000000000000000000000000000000000..9b4520ec421bb4a806046a3286ec174e30dd6a2d --- /dev/null +++ b/Server Monitor(python-window)/tabs.py @@ -0,0 +1,654 @@ +"""Detail-page tabs: each one shows an aspect of the bound server session.""" +import copy, math, time, tkinter as tk +from datetime import datetime +from tkinter import filedialog + +import plat +from history import (CPU, DISK, DISKIO, GPU, IOWAIT, KEYS, LOAD, MEM, NAMES, PROCS, RD, RX, STEP, SWAP, TEMP, TIER_NAMES, TX, WR, fmt_metric, + stats) +from model import (RULE_ACTIONS, RULE_METRICS, TRANSPORTS, Rule, catalogue, command, count, default_rules, duration, fmt_bytes, new_id, pct, rate, + temp) +from widgets import (C, Cell as X, Chart, CoreGrid, Dialog, Entry, F, Gauge, Heatmap, KeyValues, Scroll, SegmentBar, Spin, Table, ask, box, + button, check, choose, combo, decimals, down, field, health, label, level, mix, panel, pct0, popup, press, right, severity, + spread, textbox, tiles, tip, write) + +class Tab(tk.Frame): + """One aspect of the bound session s. save(config) persists config edits.""" + span = 15 * 60000 # live chart window + def __init__(self, parent, save): + super().__init__(parent, bg=C.bg) + self.s, self.save = None, save + self.build() + def page(self, scroll=True): + """Padded root for the content; scrolls when the tab is taller than the window.""" + if scroll: return down(box(down(Scroll(self), 0, fill='both', expand=True).body), 0, fill='both', expand=True, padx=(4, 10), pady=16) + return down(box(self), 0, fill='both', expand=True, padx=4, pady=(16, 12)) + def attach(self, s): self.s = s + def refresh(self): """A new sample arrived (called only while the tab is visible).""" + def analysis(self): """The analyzer ran.""" + def run(self, cmd, status): + """Runs a command and reports the result in a status label.""" + status.config(text='Running: ' + cmd, fg=C.muted) + self.s.exec(cmd, True, lambda code, out: status.winfo_exists() and status.config( + text=f'✗ {cmd}: {out.strip()[:300]}' if code else f'✓ {cmd}', fg=C.red if code else C.green)) + +def io_wait(live): return [('I/O wait', C.amber, live.s['iowait'])] if plat.POSIX_CPU else [] + +# ============================================================================ Overview +class Overview(Tab): + def build(self): + b = self.page() + gauges = down(panel(b)) + self.g = [Gauge(gauges, name, 85 if name == 'Temperature' else 90) for name in ('CPU', 'Memory', 'Fullest disk', 'Swap', 'Temperature', 'Health')] + spread(self.g, gap=0) # equal widths: all six stay visible in a narrow window + self.t = tiles(b, [('Load average', C.accent), ('Processes', C.violet), ('TCP connections', C.teal), ('Services', C.green), ('Uptime', C.amber)]) + mid = down(box(b), 0) + system = panel(mid, 'System', 330) + system.pack(side='right', fill='y') + self.info = down(KeyValues(system)) + charts = right(box(mid), 14, True) + self.cpu, self.mem = Chart(charts, 'CPU', pct0, 100, stacked=True), Chart(charts, 'Memory', pct0, 100) + self.net, self.io = Chart(charts, 'Network', rate), Chart(charts, 'Disk I/O', rate) + spread([self.cpu, self.mem, self.net, self.io], 2) + def refresh(self): + 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 + g[0].set(m.cpu_usage, sub=f'{m.cpu_count} cores') + g[1].set(m.mem_pct, sub=f'{fmt_bytes(m.mem_used)} / {fmt_bytes(m.mem_total)}') + g[2].set(m.max_disk_pct, sub=m.fullest_mount) + 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') + 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') + g[5].set(a.health, str(a.health), 'grade ' + a.grade, health(a.health)) + 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)) + t[1].set(str(len(m.procs)), f'{m.threads_total} threads · {m.procs_running} running') + t[2].set(str(tcp.get('ESTABLISHED', 0)), f'{tcp.get("LISTEN", 0)} listening · {tcp.get("TIME_WAIT", 0)} time-wait') + 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) + t[4].set(duration(m.uptime), f'{m.logged_users} user(s) logged in') + self.cpu.set(h.t, [('User', C.accent, h.s['user']), ('System', C.violet, h.s['sys'])] + io_wait(h), self.span) + 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) + self.net.set(h.t, [('Down', C.teal, h.s['rx']), ('Up', C.pink, h.s['tx'])], self.span) + self.io.set(h.t, [('Read', C.blue, h.s['rd']), ('Write', C.orange, h.s['wr'])], self.span) + self.info.set([('Hostname', m.hostname), ('OS', m.os), ('Kernel', f'{m.kernel} {m.arch}'), ('CPU', m.cpu_model), + ('Cores', str(m.cpu_count) + (f' @ {m.avg_mhz / 1000:.2f} GHz' if m.avg_mhz > 0 else '')), ('Memory', fmt_bytes(m.mem_total)), + ('Swap', fmt_bytes(m.swap_total) if m.swap_total > 0 else 'none'), ('Virtualisation', m.virt), + ('Disks', f'{len(m.mounts)} mounted file systems'), ('Interfaces', str(len(m.nets))), ('GPU', m.gpus[0].name if m.gpus else 'none'), + ('Connection', f'{c.address()} ({TRANSPORTS[c.transport]})'), ('Sample interval', f'{c.interval} s')]) + +# ============================================================================ CPU +class CpuTab(Tab): + def build(self): + b = self.page() + self.model = down(label(b, kind='H2')) + self.t = tiles(b, [('Usage', C.accent), ('Load 1 / 5 / 15', C.violet), ('Avg frequency', C.teal), (plat.TEXT['cpu_tile'], C.orange), + ('Context switches', C.blue), ('Interrupts', C.pink), ('New processes', C.green), ('Running / blocked', C.amber)], 4) + r = down(box(b)) + self.chart, self.load = Chart(r, 'CPU time breakdown', pct0, 100, 260, True), Chart(r, 'Load average (1 min)', decimals(1), height=260) + spread([self.chart, self.load], weights=(3, 2)) + self.cores = down(CoreGrid(down(panel(b, 'Per core'))), 0) + r = down(box(b), 0) + temps, self.gpu_panel = right(panel(r, 'Temperatures'), 0, True), panel(r, 'GPUs') + self.temps = down(Table(temps, ['Sensor', 'Temperature'], [300], [1]), 0) + self.gpus = down(Table(self.gpu_panel, ['#', 'Name', 'Usage', 'Memory', 'Temp', 'Power', 'Fan'], [40, 220, 120, 160], [2, 3]), 0) + def refresh(self): + m, h, t = self.s.m, self.s.live, self.t + self.model.config(text=m.cpu_model or 'Processor') + 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 ''), + level(m.cpu_usage)) + 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') + t[2].set(f'{m.avg_mhz / 1000:.2f} GHz' if m.avg_mhz > 0 else 'n/a') + value, sub, warn = plat.cpu_tile(m) + t[3].set(value, sub, C.amber if warn else None) + t[4].set(count(m.ctxt_per_sec) + '/s') + t[5].set(count(m.intr_per_sec) + '/s') + t[6].set(f'{m.forks_per_sec:.1f}/s') + t[7].set(f'{m.procs_running} / {m.procs_blocked}', 'blocked = waiting for ' + ('I/O' if plat.POSIX_CPU else 'a CPU'), + C.amber if m.procs_blocked > m.cpu_count else None) + self.chart.set(h.t, [('User', C.accent, h.s['user']), ('System', C.violet, h.s['sys'])] + io_wait(h) + + ([('Steal', C.red, h.s['steal'])] if plat.POSIX_CPU else []), self.span) + self.load.set(h.t, [('Load', C.violet, h.s['load']), ('Cores', C.faint, [m.cpu_count] * len(h.t), False, True)], self.span) + self.cores.set(m.cores) + self.temps.set([[x.name, X(temp(x.celsius), pct=min(100, x.celsius))] for x in m.temps] + or [[X('No temperature sensors exposed (common on VMs)', C.muted)]]) + if bool(m.gpus) != bool(self.gpu_panel.winfo_manager()): + right(self.gpu_panel, 0, True, padx=(14, 0)) if m.gpus else self.gpu_panel.pack_forget() + self.gpus.set([[str(g.index), g.name, X(pct(g.util, 0), pct=g.util), + 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), + X(temp(g.temp), level(g.temp, 75, 88)), f'{g.power:g} W', pct(g.fan, 0)] for g in m.gpus]) + +# ============================================================================ Memory +class MemoryTab(Tab): + def build(self): + b = self.page() + self.t = tiles(b, [('Used', C.violet), ('Available', C.green), ('Cache + buffers', C.blue), ('Swap used', C.pink)]) + composition = down(panel(b, 'Composition')) + self.bar = down(SegmentBar(composition), 10) + down(label(composition, 'SWAP', 'Section'), 10) + self.swap = down(SegmentBar(composition), 0) + r = down(box(b)) + details = panel(r, 'Details', 300) + details.pack(side='right', fill='y') + self.detail = down(KeyValues(details)) + self.chart = right(Chart(r, 'Memory usage', pct0, 100, 280), 14, True) + self.top = down(Table(down(panel(b, 'Top memory consumers'), 0), ['PID', 'Process', 'User', 'RSS', 'Memory %', 'Virtual'], + [80, 220, 120, 110, 160], [4], height=360), 0) + def refresh(self): + m, h, t, free = self.s.m, self.s.live, self.t, mix(C.grid, '#ffffff', .18) + t[0].set(fmt_bytes(m.mem_used), f'{pct(m.mem_pct)} of {fmt_bytes(m.mem_total)}', level(m.mem_pct)) + t[1].set(fmt_bytes(m.mem_available), 'free ' + fmt_bytes(m.mem_free)) + t[2].set(fmt_bytes(m.cached + m.buffers), 'reclaimable when needed') + 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 '', + level(m.swap_pct, 40, 80)) + self.bar.set([(max(0.0, m.mem_total - m.mem_free - m.cached - m.buffers), C.violet, 'Applications'), (m.shared, C.pink, 'Shared'), + (m.buffers, C.teal, 'Buffers'), (max(0.0, m.cached - m.shared), C.blue, 'Cache'), (m.mem_free, free, 'Free')], m.mem_total) + self.swap.set([(m.swap_used, C.pink, 'Used'), (m.swap_total - m.swap_used, free, 'Free')], m.swap_total) + 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) + self.detail.set([(k, fmt_bytes(v)) for k, v in ( + ('Total', m.mem_total), ('Used', m.mem_used), ('Available', m.mem_available), ('Free', m.mem_free), ('Buffers', m.buffers), + ('Cached', m.cached), ('Shared', m.shared), ('Slab', m.slab), ('Dirty', m.dirty), ('Swap total', m.swap_total), ('Swap used', m.swap_used))]) + 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)), + X(fmt_bytes(p.vsz), C.muted, True)] for p in sorted(m.procs, key=lambda p: -p.rss)[:15]]) + +# ============================================================================ Storage +class StorageTab(Tab): + def build(self): + b = self.page() + self.t = tiles(b, [('Fullest file system', C.amber), ('Read', C.blue), ('Write', C.orange), ('Busiest disk', C.red)]) + self.mounts = down(Table(down(panel(b, 'File systems')), ['Mount point', 'Device', 'Type', 'Size', 'Used', 'Free', 'Usage'], + [260, 140, 80, 110, 110, 110], [6]), 0) + self.io = down(Chart(b, 'Disk throughput', rate, height=260)) + self.disks = down(Table(down(panel(b, 'Block devices'), 0), ['Device', 'Read/s', 'Write/s', 'Read IOPS', 'Write IOPS', 'Busy', 'Total read', + 'Total written'], [110, 110, 110, 100, 100, 150, 120], [5], height=200), 0) + def refresh(self): + m, h, t = self.s.m, self.s.live, self.t + t[0].set(pct(m.max_disk_pct), m.fullest_mount, level(m.max_disk_pct, 80, 90)) + t[1].set(rate(m.disk_read_bps)) + t[2].set(rate(m.disk_write_bps)) + t[3].set(pct(m.max_disk_util), m.busiest_disk, level(m.max_disk_util, 60, 90)) + self.io.set(h.t, [('Read', C.blue, h.s['rd']), ('Write', C.orange, h.s['wr'])], self.span) + 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), + X(fmt_bytes(x.avail), right=True), X(pct(x.pct), pct=x.pct)] for x in m.mounts]) + 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), + 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), + X(fmt_bytes(d.total_written), C.muted, True)] for d in m.disks]) + +# ============================================================================ Network +class NetworkTab(Tab): + def build(self): + b = self.page() + self.t = tiles(b, [('Download', C.teal), ('Upload', C.pink), ('Established', C.accent), ('Listening', C.green), + ('Time-wait / close-wait', C.amber), ('Sockets in use', C.violet)]) + r = down(box(b)) + right(label(r, 'Interface', 'Muted')) + self.iface = right(combo(r, ['All physical (total)'], 28, self.refresh), fill='none') + self.chart = down(Chart(b, 'Traffic', rate, height=280)) + self.tbl = down(Table(down(panel(b, 'Interfaces'), 0), ['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], height=240), 0) + def refresh(self): + m, h, t, tcp = self.s.m, self.s.live, self.t, self.s.m.tcp + t[0].set(rate(m.net_rx_bps), 'physical interfaces') + t[1].set(rate(m.net_tx_bps)) + t[2].set(str(tcp.get('ESTABLISHED', 0)), 'TCP') + t[3].set(str(tcp.get('LISTEN', 0)), 'open TCP ports') + t[4].set(f'{tcp.get("TIME_WAIT", 0)} / {tcp.get("CLOSE_WAIT", 0)}', 'many close-wait = app not closing sockets', + C.amber if tcp.get('CLOSE_WAIT', 0) > 100 else None) + t[5].set(str(m.sockets_used)) + names = ['All physical (total)'] + [n.name for n in m.nets] + if list(self.iface['values']) != names: + current = self.iface.get() + self.iface.config(values=names) + self.iface.current(names.index(current) if current in names else 0) + name, total = self.iface.get(), self.iface.current() <= 0 + self.chart.title = 'Traffic — ' + ('all physical interfaces' if total else name) + self.chart.set(h.t, [('Down', C.teal, h.s['rx'] if total else h.if_rx.get(name, [])), + ('Up', C.pink, h.s['tx'] if total else h.if_tx.get(name, []))], self.span) + + def row(x): + dim = C.muted if x.virt else '' + return [X(x.name + (' (virtual)' if x.virt else ''), dim), X(x.state, {'up': C.green, 'down': C.red}.get(x.state, C.muted)), + 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), + 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), + 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)] + self.tbl.set([row(x) for x in m.nets]) + +# ============================================================================ list tabs (processes, services) +class ListTab(Tab): + """Filterable, sortable table that keeps the selection across refreshes; rows are lists of Cell.""" + def build_list(self, headers, widths, bars, hint, sort): + b = self.page(False) + self.bar, self.rows = down(box(b), 10), [] + self.actions = box(self.bar) # packed first: in a narrow window the summary gives way, not the buttons + self.actions.pack(side='right') + self.filter = right(Entry(self.bar, hint=hint, width=26)) + self.filter.bind('', lambda e: self.show()) + self.bar.bind('', lambda e: self.filter.config(width=26 if e.width > 1000 else 12)) + self.summary = right(label(self.bar, kind='Muted')) + self.tbl = down(Table(b, headers, widths, bars, sort), 8, fill='both', expand=True) + self.status = down(label(b, kind='Muted'), 0) + def accept(self, row): return True + def show(self, rows=None): + self.rows = self.rows if rows is None else rows + needle = self.filter.text().lower() + self.tbl.set([r for r in self.rows if self.accept(r) and any(needle in c.text.lower() for c in r)]) + +STATES = {'R': ('Running', C.green), 'S': ('Sleeping', C.muted), 'D': ('Disk wait', C.amber), 'Z': ('Zombie', C.red), 'T': ('Stopped', C.red), + 'I': ('Idle', C.muted)} + +class ProcessTab(ListTab): + def build(self): + self.build_list(['PID', 'Name', 'User', 'State', 'CPU', 'Memory', 'RSS', 'Threads', plat.TEXT['priority'], 'Running for'], + [80, 230, 120, 100, 130, 130, 100, 80, 70], [4, 5], 'Filter by name, user or PID…', (4, True)) + self.freeze = check(self.bar, 'Freeze list') + tip(self.freeze, "Stop refreshing so rows don't move while you pick one").pack(side='left', after=self.filter, padx=(0, 10)) + menu = [] + for verb, cmd, flags in plat.PROC_ACTIONS: + menu.append((verb, lambda verb=verb, cmd=cmd, flags=flags: self.signal(verb, cmd, 'c' in flags))) + if 'b' in flags: right(button(self.actions, verb, menu[-1][1], 'Danger' if 'd' in flags else None), 6) + right(button(self.actions, 'Priority…', self.priority), 0) + self.tbl.on_menu = lambda e: popup(self, e, menu + [None, ('Change priority…', self.priority)]) + def attach(self, s): + if s is not self.s: self.freeze.var.set(False) # a frozen list would show the other server's PIDs + self.s = s + def refresh(self): + if self.freeze.var.get(): return + m = self.s.m + + def row(p): + state, color = STATES.get(p.state, (p.state, C.muted)) + raised = plat.priority_level(p.nice) + 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), + 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), + 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)] + self.show([row(p) for p in m.procs]) + self.summary.config(text=f'{len(m.procs)} processes · {sum(p.state == "R" for p in m.procs)} running · {m.threads_total} threads') + def selected(self): + """(pid, 'name (pid)') of the selected process, or None after a hint in the status line.""" + row = self.tbl.row() + if row: return row[0].text, f'{row[1].text} ({row[0].text})' + self.status.config(text='Select a process first.', fg=C.muted) + def signal(self, verb, cmd, confirm): + sel = self.selected() + 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) + def priority(self): + sel = self.selected() + choice = sel and choose(self, 'Change priority', f'Priority for {sel[1]}:', [(k, None) for k in plat.PRIORITIES] + [('Cancel', 'Flat')]) + if choice in plat.PRIORITIES: self.run(command(plat.PRIORITY_CMD.replace('{v}', str(plat.PRIORITIES[choice])), sel[0]), self.status) + +class ServiceTab(ListTab): + def build(self): + self.build_list(['Service', 'Active', 'State', 'Load', 'Description'], [300, 100, 100, 90], [], 'Filter services…', (0, False)) + self.state, self.shown = combo(self.bar, ['All', 'Running', 'Failed', 'Not running'], 12, self.show), None + self.state.pack(side='left', after=self.filter, padx=(0, 10)) + menu = [(verb.capitalize(), lambda verb=verb: self.act(verb)) for verb in plat.SERVICE_VERBS] + for text, act in menu: right(button(self.actions, text, act, 'Danger' if text in ('Stop', 'Disable') else None), 6) + right(button(self.actions, 'Logs', self.logs, 'Primary'), 0) + self.tbl.on_open = self.logs + self.tbl.on_menu = lambda e: popup(self, e, menu + [None, ('Show logs', self.logs)]) + def attach(self, s): self.s, self.shown = s, None + def accept(self, row): + active, sub, state = row[1].text, row[2].text, self.state.current() + return state == 0 or (state == 1 and sub == 'running') or (state == 2 and active == 'failed') or (state == 3 and sub != 'running' and active != 'failed') + def refresh(self): + m = self.s.m + shown = [(x.unit, x.active, x.sub) for x in m.services] + if shown == self.shown: # unchanged: keep the list still + return + self.shown = shown + + def row(x): + c = C.red if x.active == 'failed' else C.green if x.sub == 'running' else C.teal if x.active == 'active' else C.muted + return [X(x.unit), X(x.active, c), X(x.sub, c), X(x.load, C.muted), X(x.description, C.muted)] + self.show([row(x) for x in m.services]) + self.summary.config(text=f'{len(m.services)} services · {m.services_running} running · {m.services_failed} failed' if m.services + else 'No services reported by this machine') + def act(self, verb): + unit = self.tbl.row() and self.tbl.selected + if not unit: return self.status.config(text='Select a service first.', fg=C.muted) + if verb not in ('stop', 'disable', 'restart') or ask(self, 'Confirm', f'{verb.capitalize()} {unit} on {self.s.cfg.name}?'): + self.run(command(plat.SERVICE_VERBS[verb], unit), self.status) + def logs(self): + s, unit = self.s, self.tbl.row() and self.tbl.selected + if not unit: return + d = Dialog(self, f'Logs — {unit} — {s.cfg.name}') + d.geometry('1000x640') + text = textbox(d) + write(text, 'Loading…') + down(text.frame, 12, fill='both', expand=True) + r = down(box(d), 0) + lines = right(Spin(r, 50, 5000, 300), 6) + right(label(r, 'lines', 'Muted')) + + def load(): + s.exec(command(plat.SERVICE_LOGS, unit, lines.value()), True, lambda code, out: text.winfo_exists() and write(text, out, clear=True)) + right(button(r, 'Reload', load)) + button(r, 'Close', d.close).pack(side='right') + load() + +# ============================================================================ Console +class ConsoleTab(Tab): + def build(self): + b = self.page(False) + side = Scroll(b) # the command lists scroll in a low window + side.cv.config(width=288) + side.pack(side='right', fill='y', padx=(14, 0)) + self.out, self.history, self.pos = textbox(b), [], 0 + down(self.out.frame, 10, fill='both', expand=True) + r = down(box(b), 0) + right(label(r, '$', fg=C.accent, font=F(15, True))) + self.cmd = right(Entry(r, hint=plat.TEXT['console_hint'], mono=True), grow=True) + self.privileged = check(r, 'privileged') + if plat.HAS_SUDO: right(tip(self.privileged, plat.TEXT['privileged_tip'])) + right(button(r, 'Run', self.enter, 'Primary')) + right(button(r, 'Clear', lambda: write(self.out, '', clear=True)), 0) + for key, handler in (('', self.enter), ('', lambda: self.recall(-1)), ('', lambda: self.recall(1))): + self.cmd.bind(key, lambda e, handler=handler: handler()) + for title, items, system in (('Quick diagnostics', plat.QUICK, False), ('System actions', plat.ACTIONS, True)): + p = down(panel(side.body, title, 270)) + for text, cmd in items: + tip(down(button(p, text, lambda text=text, cmd=cmd, system=system: self.quick(text, cmd, system), + 'Danger' if text in plat.POWER else 'Side', pady=3), 6), cmd) + def attach(self, s): + if s is self.s: return + self.s = s + write(self.out, '', clear=True) + 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) + def enter(self): + cmd = self.cmd.text().strip() + if cmd: + if self.history[-1:] != [cmd]: self.history.append(cmd) + self.pos = len(self.history) + self.cmd.put('') + self.exec(cmd, self.privileged.var.get()) + def recall(self, step): + if self.history: + self.pos = min(max(self.pos + step, 0), len(self.history)) + self.cmd.put((self.history + [''])[self.pos]) + def quick(self, text, cmd, system): + danger = text in plat.POWER + question = f'{text} on {self.s.cfg.name}?' + ('\n\nThe machine will be unavailable until it comes back.' if danger else '') + if not system or ask(self, text, question, danger): self.exec(cmd, system) + def exec(self, cmd, privileged): + out, t0 = self.out, time.monotonic() + write(out, f'\n{time.strftime("%H:%M:%S")} $ ', C.accent) + write(out, cmd + '\n') + + def done(code, text): + if out.winfo_exists(): + write(out, text.rstrip('\n') + '\n' if text else '') + write(out, f'[exit {code} · {(time.monotonic() - t0) * 1000:.0f} ms]\n', C.red if code else C.green) + self.s.exec(cmd, privileged, done, 120) + +# ============================================================================ Alert rules +class RulesTab(Tab): + def build(self): + b = self.page(False) + 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; ' + 'if it is still true after the cooldown the action runs again. History-based automation lives in the Insights tab.', 'Muted', True), 10) + r = down(box(b), 10) + right(button(r, '+ Add rule', lambda: self.edit(-1), 'Primary')) + right(button(r, 'Edit', lambda: self.edit(self.index()))) + 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')) + button(r, 'Reset to defaults', lambda: ask(self, 'Reset rules', 'Replace all rules with the defaults?') and self.store(default_rules())).pack(side='right') + self.rules = down(Table(b, ['On', 'Condition', 'Severity', 'Action', 'Cooldown', 'Live value'], [50, 380, 100, 330, 100]), 10, fill='both', expand=True) + self.active = down(Table(b, ['Active problems'], height=128), 0) + self.rules.on_open = lambda: self.edit(self.index()) + self.rules.on_click = lambda i, col: col == 0 and self.toggle(i) + def attach(self, s): + self.s = s + if s: self.refresh() + def index(self): + """Index of the selected rule, -1 without a selection.""" + return self.rules.selected if self.rules.row() else -1 + def store(self, rules): + c = copy.copy(self.s.cfg) + c.rules = rules + self.save(c) + self.refresh() + def toggle(self, i): + rules = copy.deepcopy(self.s.cfg.rules) + rules[i].enabled = not rules[i].enabled + self.store(rules) + def refresh(self): + s, rows = self.s, [] + for i, r in enumerate(s.cfg.rules): + v = s.metric_value(r.metric) + hit = v < r.value if r.op == '<' else v > r.value + 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), + X(r.severity, severity(r.severity)), + X(r.action_text(), C.muted if r.action == 'notify' else C.violet), X(f'{r.cooldown} s', C.muted), + X(f'{v:.1f} {catalogue(RULE_METRICS, r.metric, 2)}', C.red if hit else C.green)]) + self.rules.set(rows) + self.active.set([[X('⚠ ' + a, C.red)] for a in s.active_alerts()] or [[X('✓ No rule is currently triggered', C.green)]]) + def edit(self, i): + rules = copy.deepcopy(self.s.cfg.rules) + r = rules[i] if 0 <= i < len(rules) else Rule(new_id()) + d = Dialog(self, 'Edit rule' if r in rules else 'New rule') + f = down(box(d)) + metric = field(f, 'When', combo(f, [m[1] + (f' ({m[2]})' if m[2] else '') for m in RULE_METRICS], 34)) + condition = field(f, 'is', box(f)) + op, value = right(combo(condition, ['>', '<'], 3)), right(Spin(condition, -1e9, 1e9, r.value, .5), 0, True) + hold = field(f, 'for at least (s)', Spin(f, 0, 86400, r.duration)) + level_ = field(f, 'Severity', combo(f, ['info', 'warning', 'critical'])) + action = field(f, 'Then', combo(f, [a[1] for a in RULE_ACTIONS], 34, lambda: sync())) + arg = field(f, 'Argument', Entry(f, r.arg)) + cooldown = field(f, 'Repeat after (s)', Spin(f, 10, 86400, r.cooldown)) + enabled = field(f, '', check(f, 'Enabled', r.enabled)) + 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), + (op, ['>', '<'], r.op), (level_, ['info', 'warning', 'critical'], r.severity)): + w.current(values.index(current) if current in values else 0) + + def sync(): # only some actions take an argument + hint = RULE_ACTIONS[action.current()][2] + arg.config(state='normal') + arg.put(arg.text(), hint) + arg.config(state='normal' if hint else 'disabled') + + def ok(): + r.metric, r.op, r.severity, r.action = RULE_METRICS[metric.current()][0], op.get(), level_.get(), RULE_ACTIONS[action.current()][0] + r.value, r.duration, r.cooldown, r.enabled = float(value.value()), hold.value(), cooldown.value(), enabled.var.get() + r.arg = arg.text().strip() if RULE_ACTIONS[action.current()][2] else '' + d.close(True) + + sync() + d.buttons(('Cancel', d.close), ('OK', ok, 'Primary')) + if d.run(): self.store(rules if r in rules else rules + [r]) + +# ============================================================================ History +RANGES = (('1 h', 3600), ('6 h', 21600), ('24 h', 86400), ('7 d', 604800), ('30 d', 2592000), ('90 d', 7776000), ('1 y', 31536000), ('All', 0)) +# chart series: (metric, peak instead of average); metric -1 = availability +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)) + +class HistoryTab(Tab): + def build(self): + b = self.page() + r = down(box(b)) + self.range, self.loaded, self.pts = 86400, 0, None + button(r, 'Export CSV…', self.export).pack(side='right', anchor='n') # packed first: in a narrow window the summary wraps instead + self.ranges = {sec: right(button(r, text, lambda sec=sec: self.pick(sec)), 6, fill='none', anchor='n') for text, sec in RANGES} + press(self.ranges[self.range], True) + self.res = right(label(r, kind='Muted', wrap=True), 0, True, padx=8) + g = down(box(b)) + self.charts = [Chart(g, title, fmt, ymax, 240, empty='No history for this range yet') for title, fmt, ymax in ( + ('CPU', pct0, 100), ('Memory & swap', pct0, 100), ('Disk usage (fullest)', pct0, 100), ('Disk throughput', rate, 0), ('Network', rate, 0), + ('Load average', decimals(1), 0), ('Temperature', lambda v: f'{v:.0f}°', 0), ('Availability', pct0, 100))] + spread(self.charts, 2) + self.stats = down(Table(down(panel(b, 'Statistics for the selected range'), 0), ['Metric', 'Minimum', 'Average', '95th percentile', 'Peak', 'Points'], + [200, 150, 150, 150, 150], height=14 * 30 + 34), 0) + def attach(self, s): self.s, self.loaded = s, 0 + def pick(self, sec): + press(self.ranges[self.range], False) + self.range = sec + press(self.ranges[sec], True) + self.reload() + def refresh(self): + if time.time() - self.loaded >= (5 if 0 < self.range <= 21600 else 60): self.reload() + def reload(self): + s, self.loaded = self.s, time.time() + now = int(self.loaded) + frm = now - self.range if self.range else max(1, s.store.first_ts()) + p, tier = s.store.span(frm, now) + self.pts = p + step, t, v = max(STEP[tier], s.cfg.interval), [], [[] for _ in SERIES] + + def push(ts, i=None): # without a point index: a gap + t.append(ts * 1000) + for col, (m, peak) in zip(v, SERIES): + 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) + + for i, ts in enumerate(p.ts): + if t and ts * 1000 - t[-1] > step * 3000: # the app was not running + push(t[-1] // 1000 + step) + push(ts, i) + if t and now * 1000 - t[-1] > step * 3000: push(now) + cpu, cpu_max, mem, swap, disk, rd, wr, rx, tx, rx_max, load, temp_, temp_max, avail = v + 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)] + cpu_peak, rx_peak, temp_peak = peak if tier else ([], [], []) # aggregated tiers also show the peaks + data = ([('Average', C.accent, cpu)] + cpu_peak, [('Memory', C.violet, mem), ('Swap', C.pink, swap, False)], [('Usage', C.amber, disk)], + [('Read', C.blue, rd), ('Write', C.orange, wr)], [('Down', C.teal, rx), ('Up', C.pink, tx)] + rx_peak, [('Load', C.violet, load)], + [('Average', C.orange, temp_)] + temp_peak, [('Online', C.green, avail)]) + for chart, series in zip(self.charts, data): + chart.subtitle = f'avg per {TIER_NAMES[tier]}' if tier else '' + chart.set(t, series, (now - frm) * 1000) + n, up = sum(p.n), sum(p.up) + self.res.config(text=f'Resolution: {TIER_NAMES[tier]} · {len(p)} points · availability {pct(up * 100 / n, 2) if n else "—"}' + f' · stored {fmt_bytes(s.store.disk_bytes())}') + + def row(m): + x = stats(p, m) + 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), + X(fmt_metric(m, x.max), C.red, True), X(str(x.count), C.muted, True)] + 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]) + def export(self): + name = filedialog.asksaveasfilename(parent=self, title='Export history', initialfile=f'{self.s.cfg.name}-history.csv', filetypes=[('CSV', '*.csv')], + defaultextension='.csv') + if not name or self.pts is None: return + with open(name, 'w', encoding='utf-8', newline='\n') as f: + f.write('time,samples,online_pct' + ''.join(f',{k}_avg,{k}_max' for k in KEYS)) + for ts, n, up, *values in self.pts.rows(): + cells = [(values[m], values[len(KEYS) + m]) for m in range(len(KEYS))] + f.write(f'\n{datetime.fromtimestamp(ts).isoformat()},{n},{up * 100 / n if n else 0:g}' + + ''.join(',' + ','.join('' if x != x else f'{x:.3f}' for x in pair) for pair in cells)) + +# ============================================================================ Insights & Autopilot +class InsightsTab(Tab): + def build(self): + b, self.binds, self.loading = self.page(), [], False # binds: (config field, widget getter, widget setter) + top = down(box(b)) + hp = right(panel(top, 'Health', 330), 14) + self.health = down(Gauge(hp, 'Health score'), 10) + self.reasons = down(label(hp, kind='Muted', wrap=296), 10) + down(button(hp, 'Analyze now', lambda: self.s.analyze()), 0) + side = right(box(top), 0, True) + self.t = tiles(side, [('Disk full forecast', C.amber), ('Memory trend (6 h)', C.violet), ('CPU / memory p95 (30 d)', C.accent), + ('Availability 24 h', C.green), ('Availability 7 d', C.green), ('Availability 30 d', C.green)], 3) + self.capacity = down(label(down(panel(side, 'Capacity planning'), 0, fill='both', expand=True), wrap=True), 0) + + mid = down(box(b)) + ap = panel(mid, 'Autopilot — automatic control', 430) + ap.pack(side='right', anchor='n') + 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) + form = down(box(ap), 0) + self.findings = down(box(right(panel(mid, 'Findings from history analysis'), 14, True)), 0) + + def line(*parts): # form row: the first part in the left column, the others side by side in the right one + r, cell = form.grid_size()[1], box(form) + for i, part in enumerate(parts): + w = label(cell if i else form, part, 'Muted') if isinstance(part, str) else part(cell if i else form) + right(w, 6) if i else w.grid(row=r, column=0, sticky='w', padx=(0, 10), pady=4) + cell.grid(row=r, column=1, sticky='w', pady=4) + + tie = self.tie + line(tie('enabled', check, 'Autopilot enabled'), tie('dryRun', check, 'Dry run (only report)')) + line(tie('restartFailed', check, 'Restart failed services'), tie('maxRestartsPerHour', Spin, 1, 20), '/ hour max') + line('Runaway processes', tie('runawayMode', combo, ['Ignore', plat.TEXT['renice_mode'], 'Terminate'], 26, keys=['none', 'renice', 'terminate'])) + line('', '≥', tie('runawayCpu', Spin, 10, 6400), '% for', tie('runawayMinutes', Spin, 1, 1440), 'min') + line('Memory leaks', tie('leakMode', combo, ['Ignore', 'Notify', 'Terminate under pressure'], 26, keys=['none', 'notify', 'terminate'])) + line(' pressure ≥', tie('leakMemPressure', Spin, 50, 100), '% memory') + line(tie('diskCleanup', check, 'Disk cleanup'), 'full in <', tie('diskForecastDays', Spin, 1, 60), 'days') + line('', 'or usage ≥', tie('diskCleanupAt', Spin, 50, 100), '%') + line(' command', tie('diskCleanupCommand', Entry, width=34, mono=True)) + line(tie('anomalyAlerts', check, 'Anomaly alerts'), 'z ≥', tie('anomalyZ', Spin, 1.5, 10, step=.5), 'σ') + + bottom = down(box(b), 0) + weekly, usual = panel(bottom, 'Weekly pattern (last 4 weeks, hourly averages)'), panel(bottom, 'Now vs. normal (baselines)') + self.heat_metric = down(combo(weekly, ['CPU', 'Memory'], 12, self.analysis), 10, fill='none', anchor='w') + self.heat = down(Heatmap(weekly), 0, fill='both', expand=True) + self.anomalies = down(Table(usual, ['Metric', 'Last 10 min', 'Usual', 'Deviation', 'Baseline'], [110, 110, 160, 90], height=230), 0) + spread([weekly, usual], weights=(3, 2)) + def tie(self, name, make, *args, keys=None, **kw): + """Factory for a form widget bound to an AutopilotConfig field; every change is stored.""" + def create(parent): + if make is Entry: + w = Entry(parent, **kw) + w.bind('', lambda e: self.store(), add='+') + w.bind('', lambda e: self.store()) + self.binds.append((name, lambda: w.text().strip(), w.put)) + else: + w = make(parent, *args, command=self.store, **kw) + self.binds.append((name, w.var.get, w.var.set) if make is check else (name, w.value, w.put) if make is Spin + else (name, lambda: keys[w.current()], lambda v: w.current(keys.index(v) if v in keys else 0))) + return w + return create + def attach(self, s): + self.s = s + if s: + self.loading = True + for name, _, put in self.binds: put(getattr(s.cfg.autopilot, name)) + self.loading = False + def store(self): + if self.loading or not self.s: return + c = copy.deepcopy(self.s.cfg) + for name, get, _ in self.binds: setattr(c.autopilot, name, type(getattr(c.autopilot, name))(get())) + if c.autopilot != self.s.cfg.autopilot: self.save(c) + def analysis(self): + s, a, t, hi = self.s, self.s.an, self.t, self.heat_metric.current() + self.health.set(a.health, str(a.health), 'grade ' + a.grade, health(a.health)) + self.reasons.config(text=('\n'.join(a.reasons) or 'No deductions — everything looks healthy.') + + (f'\n\nAnalyzed {time.strftime("%H:%M:%S", time.localtime(a.when))}' if a.when else '')) + if a.disk_full_days >= 0: + t[0].set(duration(a.disk_full_days * 86400), f'+{a.disk_slope_per_day:.2f} pts/day · {a.disk_basis}', + C.red if a.disk_full_days < 7 else C.amber if a.disk_full_days < 30 else None) + else: + 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) + if a.mem_trend_r2 > 0: + 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) + else: + t[1].set('—', 'needs ~90 min of history') + 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)}') + else: t[2].set('—', 'collecting') + for tile, up, off in zip(t[3:], a.up, a.down): + if up != up: tile.set('—', 'no data yet') + 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) + self.capacity.config(text='\n\n'.join('• ' + c for c in a.capacity)) + self.heat.set(a.heat[hi], a.heat_n, '% memory' if hi else '% CPU', C.violet if hi else C.accent) + 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), + 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)] + for x in a.anomalies]) + + for w in self.findings.winfo_children(): # rebuild the finding cards + w.destroy() + if not a.findings: + down(label(self.findings, '✓ No problems found in the history. The analyzer checks disk forecasts, memory trends, leaks, runaway processes, ' + 'service failures, overload and anomalies every minute.', wrap=True, fg=C.green), 0) + ap = s.cfg.autopilot + for f in a.findings: + color = severity(f.severity) + card = down(tk.Frame(self.findings, bg=C.card, highlightthickness=1, highlightbackground=C.border), 10) + right(tk.Frame(card, bg=color, width=4), 0) + if f.action: + b = button(card, f.label, kind='Danger' if f.action == 'kill_pid' else 'Primary') + b.config(command=lambda f=f, b=b: self.fix(f, b)) + b.pack(side='right', padx=12) + text = right(box(card), 0, True, padx=12, pady=10) + down(label(text, f'{f.severity.upper()} · {f.category.upper()}', fg=color, font=F(11, True)), 2) + down(label(text, f.title, wrap=True, font=F(14, True)), 2) + down(label(text, f.detail, wrap=True), 2) + down(label(text, '→ ' + f.advice, 'Muted', True), 0) + if f.auto and ap.enabled: + down(label(text, 'Autopilot (dry run) would act on this' if ap.dryRun else 'Autopilot handles this automatically', 'Small', fg=C.violet), 0) + def fix(self, f, b): + if ask(self, f.label, f'{f.label} on {self.s.cfg.name}?\n\n{f.title}', f.action == 'kill_pid'): + if b.winfo_exists(): # the card may have been rebuilt while the question was open + b.config(state='disabled', text='Working…') + self.s.run_finding(f, False, lambda code, out: b.winfo_exists() and b.config(text='✗ Failed' if code else '✓ Done')) + +TABS = (('Overview', Overview), ('CPU', CpuTab), ('Memory', MemoryTab), ('Storage', StorageTab), ('Network', NetworkTab), ('Processes', ProcessTab), + ('Services', ServiceTab), ('History', HistoryTab), ('Insights & Autopilot', InsightsTab), ('Alert rules', RulesTab), ('Console', ConsoleTab)) diff --git a/Server Monitor(python-window)/ui.py b/Server Monitor(python-window)/ui.py new file mode 100644 index 0000000000000000000000000000000000000000..c5af8f8d1dc853b81754b600abf6fa3c131400a7 --- /dev/null +++ b/Server Monitor(python-window)/ui.py @@ -0,0 +1,474 @@ +"""Main window: sidebar, dashboard with server cards, server detail page, events page, add / edit dialog.""" +import copy, json, os, time, tkinter as tk +from tkinter import filedialog + +import plat +from model import ServerConfig, TRANSPORTS, duration, fmt_bytes, new_id, pct, rate +from session import DISABLED, OFFLINE, STATUS, Link, Timer, loop +from tabs import TABS +from widgets import (C, Cell, Chips, Dialog, Entry, F, FIELD, Paint, Scroll, Spin, Table, Tabs, app_icon, ask, box, button, check, choose, combo, down, + elide, field, health, label, level, mix, on_wheel, panel, popup, press, right, severity, textbox, theme, tiles, write) + +STATUS_COLORS = (C.faint, C.amber, C.green, C.red) # disabled, connecting, online, offline + +# ============================================================================ dashboard cards +class Card(Paint): + def __init__(self, parent, on_click): + super().__init__(parent, 340, 262, cursor='hand2') + self.over = False + self.bind('', lambda e: self.hover(True)) + self.bind('', lambda e: self.hover(False)) + self.bind('', lambda e: on_click()) + def hover(self, over): + self.over = over + self.redraw() + +class ServerCard(Card): + def __init__(self, parent, s, win): + super().__init__(parent, lambda: win.open(s.cfg.id)) + self.s = s + for signal in (s.updated, s.analysis_updated): + signal.append(self.redraw) + self.bind('', lambda e, signal=signal: signal.remove(self.redraw), add='+') + self.bind('', lambda e: popup(self, e, [('Open details', lambda: win.open(s.cfg.id)), ('Reconnect', s.reconnect), None, + ('Edit…', lambda: win.edit(s.cfg.id)), ('Remove…', lambda: win.remove(s.cfg.id))])) + def draw(self): + s, c, m, an, w = self.s, self.s.cfg, self.s.m, self.s.an, self.w + live, sc, bg = s.online(), STATUS_COLORS[s.status], C.hover if self.over else C.card + self.rrect(1, 1, w - 1, self.h - 1, 14, bg, C.accent if self.over else C.border) + for i in range(12): # status strip fading out to the right + self.create_rectangle(10 + i * w / 20, 2, 11 + (i + 1) * w / 20, 6, width=0, fill=mix(sc, bg, i / 12)) + self.create_oval(17, 23, 27, 33, fill=sc, width=0) + self.text(36, 28, elide(c.name, F(16, True), w - 120), px=16, bold=True) + self.text(36, 47, elide(c.address() + (f' · {m.os}' if m.os else ''), F(11), w - 60), C.muted, 11) + if live: # health badge + self.ring(w - 62, 12, 44, an.health, health(an.health), 4, False) + self.text(w - 40, 34, an.grade, health(an.health), 15, True, 'center') + else: + chip = STATUS[s.status].upper() + cw = F(10, True).measure(chip) + 18 + self.rrect(w - cw - 16, 18, w - 16, 38, 10, mix(bg, sc, .16), sc) + self.text(w - 16 - cw / 2, 28, chip, sc, 10, True, 'center') + hot = bool(m.temps) # four gauges; the last one shows the temperature when there are sensors + gw = (w - 32) / 4 + gs = min(gw - 14, 70) + last = ('Temp', m.max_temp) if hot else ('Swap', m.swap_pct) + for i, (name, v) in enumerate((('CPU', m.cpu_usage), ('Memory', m.mem_pct), ('Disk', m.max_disk_pct), last)): + cx, color = 16 + gw * i + gw / 2, level(v, 70, 85) if hot and i == 3 else level(v) + self.ring(cx - gs / 2, 66, gs, min(100, v) if live else 0, color if live else C.faint, 6, live) + self.text(cx, 66 + gs / 2, f'{v:.0f}' + ('°' if hot and i == 3 else '%') if live else '—', C.text if live else C.faint, 14, True, 'center') + self.text(cx, 70 + gs, name, C.muted, 11, anchor='center') + x0, y0, x1, y1 = 16, 166, w - 16, 210 # CPU + memory sparkline (last 5 min) + spark = mix(bg, '#000000', .16) + self.rrect(x0, y0, x1, y1, 8, spark) + for key, color in (('mem', C.violet), ('cpu', C.accent)): + v = s.live.s[key][-150:] + if len(v) > 1: + line = [(x1 - 4 - (x1 - x0 - 8) * (len(v) - 1 - i) / 149, y1 - 4 - min(max(x, 0), 100) / 100 * (y1 - y0 - 8)) for i, x in enumerate(v)] + self.create_polygon(line + [(line[-1][0], y1 - 2), (line[0][0], y1 - 2)], fill=mix(spark, color, .16), width=0) + self.create_line(line, fill=color, width=1.5) + self.text(x0 + 8, y0 + 10, 'CPU', C.accent, 10) + self.text(x0 + 36, y0 + 10, 'MEM', C.violet, 10) + if not live: + state = {DISABLED: 'Monitoring disabled', OFFLINE: 'Unreachable: ' + s.err}.get(s.status, 'Waiting for data…') + return self.text(16, 218, state, C.red if s.status == OFFLINE else C.muted, 11, anchor='nw', width=w - 32) + self.text(16, 226, '↓ ' + rate(m.net_rx_bps), C.teal, 11) + self.text(116, 226, '↑ ' + rate(m.net_tx_bps), C.pink, 11) + self.text(w - 16, 226, f'load {m.load1:.2f} · up {duration(m.uptime)}', C.muted, 11, anchor='e') + pilot = (' · autopilot (dry run)' if c.autopilot.dryRun else ' · autopilot on') if c.autopilot.enabled else '' + self.text(16, 242, f'{m.cpu_count} cores · {len(m.procs)} procs{pilot}', C.muted, 11) + rules = len(s.active_alerts()) + if rules + len(an.findings): + badge, color = f'⚠ {rules + len(an.findings)}', C.red if rules or any(f.severity == 'critical' for f in an.findings) else C.amber + bw = F(11).measure(badge) + 14 + self.rrect(w - 16 - bw, 233, w - 16, 250, 8, mix(bg, color, .18)) + self.text(w - 16 - bw / 2, 242, badge, color, 11, anchor='center') + +class AddCard(Card): + def draw(self): + color, cx, cy = C.accent if self.over else C.muted, self.w / 2, self.h / 2 - 14 + self.rrect(2, 2, self.w - 2, self.h - 2, 14, mix(C.bg, C.accent, .07) if self.over else '', C.accent if self.over else C.border, width=1.5, dash=(5, 4)) + self.create_line(cx - 14, cy, cx + 14, cy, fill=color, width=3, capstyle='round') + self.create_line(cx, cy - 14, cx, cy + 14, fill=color, width=3, capstyle='round') + self.text(cx, cy + 37, 'Add server', color, 14, True, 'center') + self.text(cx, cy + 57, 'This machine · SSH', C.faint, 11, anchor='center') + +class Flow(tk.Frame): + """Lays its cards out in equally wide columns.""" + def __init__(self, parent): + super().__init__(parent, bg=parent['bg']) + self.cards = [] + self.bind('', lambda e: self.arrange()) + def arrange(self): + gap, width = 16, self.winfo_width() + cols = max(1, (width + gap) // (320 + gap)) + cw = (width - (cols - 1) * gap) // cols + for i, card in enumerate(self.cards): card.place(x=i % cols * (cw + gap), y=i // cols * (262 + gap), width=cw, height=262) + self.config(height=max(1, -(-len(self.cards) // cols) * (262 + gap))) + +# ============================================================================ dashboard +class Dashboard(tk.Frame): + def __init__(self, parent, mgr, win): + super().__init__(parent, bg=C.bg, padx=28, pady=20) + self.mgr, self.win, self.cards = mgr, win, [] + head = down(box(self)) + button(head, '+ Add server', win.add, 'Primary').pack(side='right') + self.search = Entry(head, hint='Search servers…', width=28) + self.search.pack(side='right', padx=10) + self.search.bind('', lambda e: self.filter()) + down(label(head, 'Dashboard', 'H1'), 2) + self.subtitle = down(label(head, kind='Muted'), 0) + self.t = tiles(self, [('Servers online', C.green), ('Avg health', C.teal), ('Active problems', C.red), ('Avg CPU', C.accent), + ('Avg memory', C.violet), ('Total network', C.pink)]) + events = panel(self, 'Recent events', 330) + events.pack(side='right', fill='y') + self.events = textbox(events, False, bg=C.panel, wrap='word', padx=0, pady=0, spacing3=8) + down(self.events.frame, 0, fill='both', expand=True) + self.flow = down(Flow(right(Scroll(self), 14, True).body), 0) + self.add_card = AddCard(self.flow, win.add) + mgr.changed.append(self.rebuild) + mgr.alert.append(lambda e: self.list_events()) + mgr.cleared.append(self.list_events) + def list_events(self): + write(self.events, '', clear=True) + for e in self.mgr.alerts[:200]: write(self.events, f'{e.time:%H:%M:%S} · {e.server}\n{e.message}\n', severity(e.severity)) + self.events.yview_moveto(0) + def rebuild(self): + for card in self.cards: # not destroyed at once: a card's own menu may have caused this + card.place_forget() + card.after_idle(card.destroy) + self.cards = [ServerCard(self.flow, s, self.win) for s in self.mgr.sessions] + self.filter() + self.refresh() + def filter(self): + needle = self.search.text().lower() + for card in self.cards + [self.add_card]: card.place_forget() + self.flow.cards = [c for c in self.cards if needle in ' '.join((c.s.cfg.name, c.s.cfg.host, c.s.cfg.group, c.s.m.hostname)).lower()] + [self.add_card] + self.flow.arrange() + def refresh(self): + t, enabled = self.t, [s for s in self.mgr.sessions if s.cfg.enabled] + up = [s for s in enabled if s.online()] + problems = sum(len(s.active_alerts()) for s in enabled) + sum(f.severity != 'info' for s in up for f in s.an.findings) + self.subtitle.config(text=f'{len(self.mgr.sessions)} server(s) monitored · updated {time.strftime("%H:%M:%S")}') + t[0].set(f'{len(up)} / {len(enabled)}', f'{len(enabled) - len(up)} unreachable' if len(enabled) > len(up) else 'all reachable', + C.green if len(up) == len(enabled) else C.amber) + t[2].set(str(problems), 'alerts + insights' if problems else 'all clear', C.red if problems else C.green) + if not up: + for i in (1, 3, 4, 5): t[i].set('—') + return + score, cpu, mem = (sum(v) / len(up) for v in zip(*((s.an.health, s.m.cpu_usage, s.m.mem_pct) for s in up))) + rx, tx = sum(s.m.net_rx_bps for s in up), sum(s.m.net_tx_bps for s in up) + t[1].set(f'{score:.0f}', 'score 0–100', health(score)) + t[3].set(pct(cpu), color=level(cpu)) + t[4].set(pct(mem), color=level(mem)) + t[5].set(rate(rx + tx), f'↓ {rate(rx)} ↑ {rate(tx)}') + +# ============================================================================ detail page +class Detail(tk.Frame): + def __init__(self, parent, mgr, win): + super().__init__(parent, bg=C.bg, padx=28, pady=16) + self.s, self.win = None, win + head = down(box(self), 6) + actions = box(head) + actions.pack(side='right', anchor='s') + window = right(box(actions)) + down(label(window, 'LIVE WINDOW', 'Section'), 4) + self.span = down(combo(window, ['Last 5 minutes', 'Last 15 minutes', 'Last 30 minutes', 'Last hour'], 16, lambda: self.refresh(False)), 0) + self.span.current(1) + right(button(actions, '⟳ Reconnect', lambda: self.s.reconnect()), anchor='s', fill='none') + self.pause = right(button(actions, '❚❚ Pause', lambda: self.s.set_paused(not self.s.paused)), anchor='s', fill='none') + right(button(actions, 'Edit', lambda: win.edit(self.s.cfg.id)), anchor='s', fill='none') + power = right(button(actions, '⏻ Power', kind='Danger'), 0, anchor='s', fill='none') + power.bind('', lambda e: popup(self, e, [(f'{text}…', lambda text=text, cmd=cmd: self.power(text, cmd)) for text, cmd in plat.POWER.items()] + + [None, ('Remove from monitor…', lambda: win.remove(self.s.cfg.id))])) + down(button(head, '‹ Dashboard', win.show_dashboard, 'Flat', padx=0), 2, fill='none', anchor='w') + names = down(box(head), 2) + self.name, self.state = right(label(names, kind='H1')), right(label(names, font=F(12, True))) + self.sub = down(label(head, kind='Muted', wrap=True), 6) + self.chips = down(Chips(head), 0) + self.tabs = down(Tabs(self, lambda: self.refresh(True)), 0, fill='both', expand=True) + for title, make in TABS: self.tabs.add(title, make(self.tabs, mgr.update)) + def power(self, text, cmd): + if ask(self, f'{text}…', f'{text} {self.s.cfg.name} now?', True): self.s.exec(cmd, True) + def attach(self, s): + if self.s: + self.s.updated.remove(self.update_sample) + self.s.analysis_updated.remove(self.update_analysis) + self.s = s + for tab in self.tabs.pages: tab.attach(s) + if s: + s.updated.append(self.update_sample) + s.analysis_updated.append(self.update_analysis) + self.header() + self.tabs.show(self.tabs.current) + def refresh(self, with_analysis): + tab = self.tabs.pages[self.tabs.current] + if self.s: + tab.span = (5, 15, 30, 60)[self.span.current()] * 60000 + tab.refresh() + if with_analysis: tab.analysis() + def update_sample(self): + if self.winfo_ismapped(): + self.header() + self.refresh(False) + def update_analysis(self): + if self.winfo_ismapped(): + self.header() + self.tabs.pages[self.tabs.current].analysis() + def header(self): + s, c, m, a = self.s, self.s.cfg, self.s.m, self.s.an + self.name.config(text=c.name) + self.state.config(text='● ' + ('PAUSED' if s.paused else STATUS[s.status].upper()), fg=C.amber if s.paused else STATUS_COLORS[s.status]) + self.sub.config(text=f'{c.address()} · {TRANSPORTS[c.transport]}' + (f' · host {m.hostname}' if m.hostname else '') + + (f' · up {duration(m.uptime)}' if s.online() else f' · {s.err}' if s.status == OFFLINE else '')) + chips = [(m.os, ''), (plat.TEXT['kernel'] + m.kernel if m.kernel else '', ''), (f'{m.cpu_count} cores' if m.cpu_count else '', ''), + (f'{fmt_bytes(m.mem_total)} RAM' if m.mem_total > 0 else '', ''), (c.group, '#7dd3fc'), + (f'health {a.health} ({a.grade})' if s.online() else '', health(a.health)), + (('autopilot: dry run' if c.autopilot.dryRun else 'autopilot: on') if c.autopilot.enabled else '', C.violet)] + self.chips.set([(text, color or '#b9c3d8') for text, color in chips if text.strip()]) + self.pause.config(text='▶ Resume' if s.paused else '❚❚ Pause') + +# ============================================================================ add / edit dialog +class ServerDialog(Dialog): + """Edits a copy of a server configuration; run() returns it, or None when cancelled.""" + def __init__(self, parent, cfg, groups): + super().__init__(parent, f'Edit server — {cfg.name}' if cfg.name else 'Add server') + self.cfg, self.link, self.timeout = cfg, None, Timer(lambda: self.tested('✗ Timed out after 20 s', C.red)) + down(label(self, 'Edit server' if cfg.name else 'Add a server', 'H2')) + f = down(box(self)) + self.name = field(f, 'Name', Entry(f, cfg.name, 'e.g. web-01', 50)) + self.group = field(f, 'Group', combo(f, groups, edit=True)) + self.group.set(cfg.group) + self.via = field(f, 'Connect via', combo(f, ['This machine (local)', 'SSH — nothing to install on the server'], command=self.sync)) + self.via.current(cfg.transport) + address, key = field(f, 'Address', box(f)), box(f) + self.host = right(Entry(address, cfg.host, 'hostname or IP address'), grow=True) + right(label(address, 'port', 'Muted'), 6) + self.port = right(Spin(address, 1, 65535, cfg.port), 0) + self.user = field(f, 'User', Entry(f, cfg.user, 'default: your local user name')) + self.key = right(Entry(field(f, 'Private key', key), cfg.keyFile, plat.TEXT['key_hint']), grow=True) + self.browse = right(button(key, 'Browse…', lambda: self.key.put(filedialog.askopenfilename( + parent=self, title='Private key', initialdir=os.path.expanduser('~/.ssh')) or self.key.text())), 0) + self.password = field(f, 'Password', Entry(f, cfg.password, 'optional — keys are recommended', show='•')) + every = field(f, 'Sample every', box(f)) + self.interval = right(Spin(every, 1, 300, cfg.interval), 6) + right(label(every, 's', 'Muted')) + self.sudo = check(f, plat.TEXT.get('sudo', ''), cfg.useSudo) + if plat.HAS_SUDO: field(f, '', self.sudo) + self.enabled = field(f, '', check(f, 'Monitoring enabled', cfg.enabled)) + self.notes = field(f, 'Notes', tk.Text(f, height=3, width=1, font=F(13), **FIELD)) + self.notes.insert('1.0', cfg.notes) + self.hint = down(label(self, kind='Muted', wrap=600)) + r = down(box(self)) + self.test = right(button(r, 'Test connection', self.run_test)) + self.outcome = right(label(r, wrap=440), 0, True) # not .result: that is what run() returns + self.buttons(('Cancel', self.close), ('Save', self.save, 'Primary')) + self.sync() + def collect(self): + c, ssh = copy.deepcopy(self.cfg), self.via.current() + c.name, c.group, c.transport, c.port = self.name.text().strip(), self.group.get().strip(), ssh, self.port.value() + c.host = self.host.text().strip() if ssh else '' + c.user, c.keyFile, c.password, c.interval = self.user.text().strip(), self.key.text().strip(), self.password.text(), self.interval.value() + c.useSudo, c.enabled, c.notes = self.sudo.var.get(), self.enabled.var.get(), self.notes.get('1.0', 'end-1c') + return c + def sync(self): + ssh = self.via.current() == 1 + for w in (self.host, self.port, self.user, self.key, self.browse, self.password): w.config(state='normal' if ssh else 'disabled') + self.hint.config(text=plat.TEXT['ssh_hint'] if ssh else 'Monitors the computer this program runs on. No setup needed.') + if not ssh and not self.name.text(): self.name.put('This computer') + def show(self, text, color): self.outcome.config(text=text, fg=color) + def save(self): + c = self.collect() + if not c.name or (c.transport and not c.host): return self.show('Please enter a name and an address.', C.red) + self.close(c) + def run_test(self): + """Two frames prove that data and rates work.""" + c, state, frames, t0 = self.collect(), {}, [], time.monotonic() + c.interval = 1 + + def frame(raw): + frames.append(plat.parse(raw, state, time.time() * 1000)) + if len(frames) == 2: + m = frames[1] + self.tested(f'✓ Connected in {(time.monotonic() - t0) * 1000:.0f} ms — {m.hostname} · {m.os} · {m.cpu_count} cores · ' + f'{fmt_bytes(m.mem_total)} RAM · CPU {pct(m.cpu_usage, 0)}', C.green) + + self.stop_test() + self.link = Link(c, frame, lambda why: self.tested('✗ ' + why, C.red)) + self.test.config(state='disabled') + self.show('Connecting…', C.amber) + self.timeout.start(20) + self.link.start() + def stop_test(self): + self.timeout.stop() + if self.link: + self.link.close() + self.link = None + def tested(self, text, color): + self.stop_test() + self.show(text, color) + self.test.config(state='normal') + def destroy(self): # also when the app quits while the dialog is open + self.stop_test() + super().destroy() + +# ============================================================================ main window +class ServerList(Paint): + """Sidebar list: one row per server with status dot, name, alert count and mini CPU / memory bars.""" + ROW = 58 + def __init__(self, parent, mgr, win): + super().__init__(parent, 220, 200) + self.mgr, self.current, self.over, self.top = mgr, None, None, 0 + self.bind('', lambda e: self.hover(self.at(e))) + self.bind('', lambda e: self.hover(None)) + self.bind('', lambda e: self.at(e) and win.open(self.at(e).cfg.id)) + self.bind('', lambda e: self.at(e) and popup(self, e, self.menu(self.at(e).cfg.id, win))) + def menu(self, sid, win): + return [('Open', lambda: win.open(sid)), ('Reconnect', lambda: self.mgr.session(sid).reconnect()), None, + ('Move up', lambda: self.mgr.move(sid, -1)), ('Move down', lambda: self.mgr.move(sid, 1)), None, + ('Edit…', lambda: win.edit(sid)), ('Remove…', lambda: win.remove(sid))] + def at(self, e): + i = self.top + e.y // self.ROW + return self.mgr.sessions[i] if i < len(self.mgr.sessions) else None + def hover(self, s): + if s is not self.over: + self.over = s + self.redraw() + def scroll(self, step): + top = min(max(self.top + (step > 0) - (step < 0), 0), max(0, len(self.mgr.sessions) - self.h // self.ROW)) + moved, self.top = top != self.top, top + self.redraw() + return moved + def draw(self): + w = self.w + for i, s in enumerate(self.mgr.sessions[self.top:]): + y, m, alerts = i * self.ROW + 2, s.m, len(s.active_alerts()) + if s.cfg.id == self.current or s is self.over: self.rrect(6, y, w - 6, y + 54, 8, C.select if s.cfg.id == self.current else C.card) + self.create_oval(15.5, y + 13.5, 24.5, y + 22.5, fill=STATUS_COLORS[s.status], width=0) + self.text(32, y + 18, elide(s.cfg.name, F(13, True), w - 82), bold=True) + if alerts: + self.rrect(w - 32, y + 10, w - 12, y + 26, 8, C.red) + self.text(w - 22, y + 18, str(alerts), '#ffffff', 10, True, 'center') + for k, (name, v) in enumerate((('CPU', m.cpu_usage), ('MEM', m.mem_pct))): + by = y + 34 + k * 11 + self.text(32, by, name, C.faint, 9) + self.rrect(62, by - 2, w - 20, by + 2, 2, C.grid) + if s.online() and v >= 1: self.rrect(62, by - 2, 62 + (w - 82) * min(v, 100) / 100, by + 2, 2, level(v)) + +class MainWindow: + def __init__(self, root, mgr): + self.root, self.mgr, self.unseen = root, mgr, 0 + theme(root) + try: + with open(mgr.path('window.json')) as f: geometry = json.load(f)['geometry'] + except (OSError, ValueError, KeyError): + geometry = '1500x940' + root.title('Server Monitor') + root.geometry(geometry) + root.minsize(1100, 700) + self.icons = app_icon(64), app_icon(34) + root.iconphoto(True, self.icons[0]) + root.protocol('WM_DELETE_WINDOW', self.quit) + for event in ('', '', ''): root.bind_all(event, on_wheel) + + side = tk.Frame(root, bg=C.side, width=260, padx=12, pady=16) + side.pack(side='left', fill='y') + side.pack_propagate(False) + brand = down(box(side), 18) + right(tk.Label(brand, image=self.icons[1], bg=C.side)) + down(label(brand, 'Server Monitor', font=F(16, True)), 0) + down(label(brand, 'monitor · analyze · control', 'Small'), 0) + self.nav_dash = down(button(side, '▦ Dashboard', self.show_dashboard, 'Nav', pady=8), 4) + row = down(box(side), 14) + self.badge = tk.Label(row, bg=C.red, fg='#ffffff', font=F(11, True), padx=7) + self.nav_events = right(button(row, '◉ Events & alerts', self.show_events, 'Nav', pady=8), 6, True) + down(label(side, ' SERVERS', 'Section'), 6) + buttons = box(side) + buttons.pack(side='bottom', fill='x') + self.list = down(ServerList(side, mgr, self), 8, fill='both', expand=True) + for i, (text, command, kind) in enumerate((('+ Add', self.add, 'Primary'), ('Edit', lambda: self.edit(self.list.current), None), + ('Remove', lambda: self.remove(self.list.current), 'Danger'))): + button(buttons, text, command, kind, padx=4).grid(row=0, column=i, sticky='ew', padx=(6 if i else 0, 0)) + buttons.columnconfigure(i, weight=1, uniform='buttons') + + self.dash, self.detail, self.events_page = Dashboard(root, mgr, self), Detail(root, mgr, self), tk.Frame(root, bg=C.bg, padx=28, pady=20) + head = down(box(self.events_page)) + button(head, 'Clear list', mgr.clear_alerts).pack(side='right') + button(head, 'Open log folder', lambda: plat.open_folder(mgr.config_dir())).pack(side='right', padx=10) + self.event_filter = combo(head, ['All events', 'critical', 'warning', 'info', 'resolved', 'action'], 12, self.list_events) + self.event_filter.pack(side='right') + down(label(head, 'Events & alerts', 'H1'), 2) + down(label(head, 'Alerts, recoveries, insights and every automatic or manual action, newest first. Also written to alerts.log.', 'Muted'), 0) + self.events = down(Table(self.events_page, ['Time', 'Server', 'Type', 'Message'], [170, 180, 100]), 0, fill='both', expand=True) + self.page = self.dash + + mgr.changed.append(self.list.redraw) + mgr.cleared.append(self.list_events) + mgr.alert.append(self.on_alert) + Timer(self.tick, 1) + self.show_dashboard() + self.pump() + def pump(self): # worker-thread results and timers run on the UI thread + self.root.after(20, self.pump) + loop.pump() + def tick(self): # sidebar bars + dashboard tiles + self.list.redraw() + if self.page is self.dash: self.dash.refresh() + def show(self, page): + self.page.pack_forget() + self.page = page + page.pack(side='left', fill='both', expand=True) + press(self.nav_dash, page is self.dash) + press(self.nav_events, page is self.events_page) + if page is not self.detail: self.list.current = None + self.list.redraw() + def show_dashboard(self): + self.show(self.dash) + self.dash.refresh() + def show_events(self): + self.show(self.events_page) + self.unseen = 0 + self.badge.pack_forget() + self.list_events() + def list_events(self): + kind = self.event_filter.get() if self.event_filter.current() else None + self.events.set([[Cell(f'{e.time:%Y-%m-%d %H:%M:%S}', C.muted, key=i), e.server, Cell(e.severity.upper(), severity(e.severity)), + e.message.replace('\n', ' ')] for i, e in enumerate(self.mgr.alerts) if kind in (None, e.severity)]) + def on_alert(self, e): + if self.page is self.events_page: + self.list_events() + elif e.severity in ('critical', 'warning', 'action'): + self.unseen += 1 + self.badge.config(text=str(self.unseen)) + self.badge.pack(side='left') + def open(self, sid): + if self.mgr.session(sid): + self.detail.attach(self.mgr.session(sid)) + self.show(self.detail) + self.list.current = sid + self.list.redraw() + def dialog(self, cfg): + groups = list(dict.fromkeys(s.cfg.group for s in self.mgr.sessions if s.cfg.group)) + return ServerDialog(self.root, cfg, groups).run() + def add(self): + cfg = self.dialog(ServerConfig(new_id())) + if cfg: self.open(self.mgr.add(cfg).cfg.id) + def edit(self, sid): + cfg = self.mgr.session(sid) and self.dialog(self.mgr.session(sid).cfg) + if cfg: self.mgr.update(cfg) + def remove(self, sid): + s = self.mgr.session(sid) + choice = s and choose(self.root, 'Remove server', f'Stop monitoring "{s.cfg.name}" and remove it from the list?', + [('Cancel', None), ('Remove, keep history files', None), ('Remove + delete history', 'Danger')]) + if choice and choice != 'Cancel': + if self.detail.s is s: + self.detail.attach(None) + self.show_dashboard() + self.mgr.remove(sid, 'delete' in choice) + def quit(self): + try: + with open(self.mgr.path('window.json'), 'w') as f: json.dump({'geometry': self.root.geometry()}, f) + except OSError: + pass + self.mgr.close() + self.root.destroy() diff --git a/Server Monitor(python-window)/widgets.py b/Server Monitor(python-window)/widgets.py new file mode 100644 index 0000000000000000000000000000000000000000..d3584f3d849526d172f845f8a5683afdb598bfcf --- /dev/null +++ b/Server Monitor(python-window)/widgets.py @@ -0,0 +1,711 @@ +"""Theme, hand-drawn widgets (gauges, time charts, bars, tiles, core grid, weekly heatmap, table) +and small builders for labels, buttons, panels, forms and dialogs.""" +import functools, math, time, tkinter as tk +from bisect import bisect_left, bisect_right +from collections import namedtuple +from tkinter import font as tkfont, ttk +from types import SimpleNamespace + +from metrics import num +from model import fmt_bytes + +C = SimpleNamespace( # palette + bg='#0d111c', side='#10151f', panel='#161c2b', card='#1a2133', hover='#20293f', border='#27314a', line='#232c41', grid='#242d42', + field='#111727', select='#17304a', text='#e6ebf5', muted='#8b95ab', faint='#5a657d', accent='#38bdf8', green='#22c55e', amber='#f59e0b', + red='#ef4444', violet='#a78bfa', pink='#f472b6', teal='#2dd4bf', orange='#fb923c', blue='#60a5fa') + +def level(p, warn=70, crit=90): return C.red if p >= crit else C.amber if p >= warn else C.green +def severity(s): return {'critical': C.red, 'warning': C.amber, 'resolved': C.green, 'action': C.violet}.get(s, C.accent) +def health(h): return C.green if h >= 90 else C.teal if h >= 75 else C.amber if h >= 60 else C.orange if h >= 40 else C.red + +def mix(a, b, t): + """Colour between a and b (t = 0..1). A Tk canvas has no transparency, so tints are mixed with the background.""" + t = min(max(t, 0), 1) + return '#%02x%02x%02x' % tuple(round(int(a[i:i + 2], 16) * (1 - t) + int(b[i:i + 2], 16) * t) for i in (1, 3, 5)) + +@functools.lru_cache(None) +def F(px, bold=False, mono=False): + """Font by pixel size.""" + family = tkfont.nametofont('TkFixedFont' if mono else 'TkDefaultFont').actual('family') + return tkfont.Font(family=family, size=-px, weight='bold' if bold else 'normal') + +def elide(s, font, width): + """Text shortened to fit the width.""" + if font.measure(s) <= width: return s + s = s[:int(len(s) * width / font.measure(s)) + 2] + while s and font.measure(s + '…') > width: s = s[:-1] + return s + '…' + +def pct0(v): return f'{v:.0f}%' +def decimals(prec): return lambda v: f'{v:.{prec}f}' + +def theme(root): + """Dark colours for the classic and the ttk widgets.""" + root.configure(bg=C.bg) + for k, v in {'*font': F(13), '*background': C.bg, '*foreground': C.text, '*selectBackground': '#0e7ab8', '*selectForeground': C.text, + '*Menu.background': C.panel, '*Menu.activeBackground': C.select, '*Menu.activeForeground': C.text, '*Menu.borderWidth': 1, + '*Menu.activeBorderWidth': 0, '*Menu.relief': 'flat', '*TCombobox*Listbox.background': C.panel, '*TCombobox*Listbox.font': F(13), + '*TCombobox*Listbox.selectBackground': C.select}.items(): + root.option_add(k, v) + s, edge = ttk.Style(root), '#2a3449' + s.theme_use('clam') + s.configure('.', font=F(13), background=C.bg, foreground=C.text) + s.configure('TCombobox', fieldbackground=C.field, background=C.card, foreground=C.text, arrowcolor=C.muted, bordercolor=edge, + lightcolor=C.field, darkcolor=C.field, padding=5) + s.map('TCombobox', fieldbackground=[('readonly', C.field)], selectbackground=[('readonly', C.field)], selectforeground=[('readonly', C.text)], + bordercolor=[('focus', C.accent)], background=[('active', C.hover)]) + s.layout('Vertical.TScrollbar', [('Vertical.Scrollbar.trough', {'sticky': 'ns', 'children': [('Vertical.Scrollbar.thumb', {'expand': '1', 'sticky': 'nswe'})]})]) + trough = mix(C.bg, C.panel, .5) + s.configure('TScrollbar', troughcolor=trough, bordercolor=trough, gripcount=0, width=9) + for part in ('background', 'lightcolor', 'darkcolor'): # the thumb; invisible while there is nothing to scroll + s.map('TScrollbar', **{part: [('disabled', trough), ('active', '#3b4866'), ('', edge)]}) + +# ---- hand-drawn widgets --------------------------------------------------------------------- +class Paint(tk.Canvas): + """Canvas that repaints itself in draw() after a resize or a redraw() call.""" + def __init__(self, parent, width, height, bg=None, **kw): + super().__init__(parent, width=width, height=height, bg=bg or parent['bg'], highlightthickness=0, bd=0, **kw) + self.bind('', lambda e: self.redraw()) + def redraw(self): + self.w, self.h = self.winfo_width(), self.winfo_height() + if self.w > 1: + self.delete('all') + self.draw() + def need_height(self, h): # for widgets whose height follows their content + if h != self.winfo_reqheight(): self.config(height=h) + def rrect(self, x0, y0, x1, y1, r, fill='', outline='', **kw): + """Rounded rectangle.""" + r = max(0, min(r, (x1 - x0) / 2, (y1 - y0) / 2)) + p = (x0 + r, y0, x0 + r, y0, x1 - r, y0, x1 - r, y0, x1, y0, x1, y0 + r, x1, y0 + r, x1, y1 - r, x1, y1 - r, x1, y1, + x1 - r, y1, x1 - r, y1, x0 + r, y1, x0 + r, y1, x0, y1, x0, y1 - r, x0, y1 - r, x0, y0 + r, x0, y0 + r, x0, y0) + return self.create_polygon(p, smooth=True, fill=fill, outline=outline, **kw) + def text(self, x, y, s, fill=C.text, px=13, bold=False, anchor='w', **kw): + return self.create_text(x, y, text=s, fill=fill, font=F(px, bold), anchor=anchor, **kw) + def ring(self, x, y, size, pct, color, thick, glow=True): + """270-degree gauge arc with round ends inside the square at (x, y).""" + r, cx, cy = (size - thick) / 2, x + size / 2, y + size / 2 + + def arc(extent, c, width): + self.create_arc(cx - r, cy - r, cx + r, cy + r, start=225, extent=-extent, style='arc', outline=c, width=width) + for angle in (225, 225 - extent): + ex, ey = cx + r * math.cos(math.radians(angle)), cy - r * math.sin(math.radians(angle)) + self.create_oval(ex - width / 2, ey - width / 2, ex + width / 2, ey + width / 2, fill=c, width=0) + + arc(270, C.grid, thick) + extent = 270 * min(max(pct, 0), 100) / 100 + if extent > 0.2: + if glow: arc(extent, mix(self['bg'], color, .2), thick * 2) + arc(extent, color, thick) + +class Gauge(Paint): + """Ring gauge with a centre value, a sub text and a title; glides to new values.""" + def __init__(self, parent, title, crit=90): + super().__init__(parent, 150, 190) + self.title, self.crit, self.target, self.shown, self.center, self.sub, self.color, self.gliding = title, crit, 0, 0, '', '', None, False + def set(self, pct, center='', sub='', color=None): + self.center, self.sub, self.color = center, sub, color + pct = 0 if pct != pct else pct + if abs(pct - self.target) > 0.05: + self.target, self.start, self.t0 = pct, self.shown, time.monotonic() + if not self.gliding: self.glide() + self.redraw() + def glide(self): + k = min(1, (time.monotonic() - self.t0) / .45) + self.shown = self.start + (self.target - self.start) * (1 - (1 - k) ** 3) + self.gliding = k < 1 + self.redraw() + if self.gliding: self.after(30, self.glide) + def draw(self): + s = min(self.w - 8, self.h - 28) + x, mid = (self.w - s) / 2, self.w / 2 + self.ring(x, 4, s, self.shown, self.color or level(self.target, 70, self.crit), max(7, s * .085)) + self.text(mid, 4 + s * .43, self.center or f'{self.shown:.0f}%', px=int(s * .2), bold=True, anchor='center') + sub = F(max(10, int(s * .075))) + self.create_text(mid, 4 + s * .63, text=elide(self.sub, sub, s * .76), fill=C.muted, font=sub) + self.text(mid, s + 15, self.title, bold=True, anchor='center') + +class Chart(Paint): + """Time chart: grid, legend with the latest values, stacked or overlaid areas, gaps where data is missing, hover read-out.""" + def __init__(self, parent, title, fmt=pct0, ymax=0, height=230, stacked=False, empty='Waiting for data…'): # ymax 0 = auto + super().__init__(parent, 260, height) + self.title, self.fmt, self.ymax, self.stacked, self.empty, self.subtitle = title, fmt, ymax, stacked, empty, '' + self.t, self.series, self.span, self.hover, self.geo = [], [], 0, -1, None + self.bind('', lambda e: self.point(e.x)) + self.bind('', lambda e: self.point(-1)) + def set(self, t, series, span=0): + """t: times in ms; series: (name, colour, values[, fill[, dashed]]); span: visible ms before the last time, 0 = all.""" + n = len(t) + self.t, self.span = list(t), span + self.series = [(s[0], s[1], (list(s[2]) + [math.nan] * n)[:n], *s[3:], *(True, False)[len(s) - 3:]) for s in series] + self.redraw() + def draw(self): + w, h, fmt, t, self.geo = self.w, self.h, self.fmt, self.t, None + self.rrect(.5, .5, w - 1, h - 1, 12, C.panel, C.border) + self.text(16, 20, self.title, bold=True) + title_w = F(13, True).measure(self.title) + lx = w - 16 + for name, color, v, *_ in reversed(self.series): # legend with the latest values, right-aligned + last = next((x for x in v[:-6:-1] if x == x), None) + label = name if last is None else f'{name} {fmt(last)}' + lx -= F(11).measure(label) + if lx < 40 + title_w: break + self.text(lx, 20, label, C.muted, 11) + self.rrect(lx - 14, 16, lx - 5, 25, 2, color) + lx -= 28 + if 24 + title_w + F(11).measure(self.subtitle) < lx: self.text(24 + title_w, 20, self.subtitle, C.muted, 11) # where the legend leaves room + n = len(t) + first = bisect_left(t, t[-1] - self.span) if n and self.span else 0 + left, top, right, bottom = 56, 40, w - 16, h - 30 + if n - first < 2 or bottom - top < 20: return self.text((left + right) / 2, (top + bottom) / 2, self.empty, C.faint, anchor='center') + + ymax = self.ymax + if ymax <= 0: + clean = [[x if x == x else 0 for x in v[first:]] for _, _, v, *_ in self.series] + ymax = nice_ceil(max(map(sum if self.stacked else max, zip(*clean)), default=0) * 1.12) + left = max(40, max(F(10).measure(fmt(ymax * g / 4)) for g in range(5)) + 18) + t1 = t[-1] + t0 = t1 - self.span if self.span else t[first] + tr = max(1, t1 - t0) + + def X(ms): return left + (ms - t0) / tr * (right - left) + def Y(v): return bottom - min(max(v, 0), ymax) / ymax * (bottom - top) + + when = '%H:%M' if tr <= 72e5 else '%a %H:%M' if tr <= 2.6e8 else '%d %b' if tr <= 3.5e10 else '%b %Y' + for g in range(5): # grid, y labels, time labels + y, at = Y(ymax * g / 4), t0 + tr * g / 4 + self.create_line(left, y, right, y, fill=C.grid, dash=(4, 3) if g else '') + self.text(left - 8, y, fmt(ymax * g / 4), C.faint, 10, anchor='e') + self.text(X(at), bottom + 14, time.strftime(when, time.localtime(at / 1000)), C.faint, 10, anchor=('w', 'center', 'center', 'center', 'e')[g]) + step = max(1, (n - first) // max(50, int((right - left) * 1.5))) # about 1.5 points per pixel + base, lines = [0.0] * n, [] + for name, color, v, fill, dashed in self.series: + runs = [[]] # (x, y, y of the base) runs, split at gaps + for i in range(first, n, step): + ok = [(x, b) for x, b in zip(v[i:i + step], base[i:i + step]) if x == x] + if ok: + b = sum(b for _, b in ok) / len(ok) + runs[-1].append((X(t[min(n - 1, i + step // 2)]), Y(sum(x for x, _ in ok) / len(ok) + b), Y(b))) + elif runs[-1]: + runs.append([]) + if self.stacked: base = [b + (x if x == x else 0) for b, x in zip(base, v)] + for run in runs: + if len(run) < 2: continue + if fill: + area = [(x, y) for x, y, _ in run] + [(x, yb) for x, _, yb in reversed(run)] + self.create_polygon(area, fill=mix(C.panel, color, .38 if self.stacked else .16), width=0) + lines.append(([(x, y) for x, y, _ in run], color, dashed)) + for points, color, dashed in lines: # lines above all areas: an area must not hide another series + self.create_line(points, fill=color, width=1.3 if dashed else 2, dash=(5, 3) if dashed else '', joinstyle='round', capstyle='round') + self.geo = (left, top, right, bottom, t0, tr, X, Y, first) + self.mark() + def point(self, x): + self.hover = x + self.delete('hover') + self.mark() + def mark(self): + """Crosshair and values at the hovered time.""" + if not self.geo or not self.geo[0] <= self.hover <= self.geo[2]: return + left, top, right, bottom, t0, tr, X, Y, first = self.geo + t = self.t + best = min(bisect_left(t, t0 + (self.hover - left) / (right - left) * tr, first), len(t) - 1) + x, stack = X(t[best]), 0 + self.create_line(x, top, x, bottom, fill='#565b68', dash=(4, 3), tags='hover') + rows = [time.strftime('%a %d %b %H:%M' if tr > 864e5 else '%H:%M:%S', time.localtime(t[best] / 1000))] + for name, color, v, *_ in self.series: + rows.append(f'{name}: ' + ('—' if v[best] != v[best] else self.fmt(v[best]))) + if v[best] == v[best]: + stack = stack + v[best] if self.stacked else v[best] + self.create_oval(x - 4, Y(stack) - 4, x + 4, Y(stack) + 4, fill=color, outline=C.panel, width=2, tags='hover') + width = max(F(11).measure(r) for r in rows) + tx = min(x + 12, right - width - 20) + self.rrect(tx, top + 4, tx + width + 18, top + 14 + len(rows) * 16, 7, C.bg, C.border, tags='hover') + for i, r in enumerate(rows): self.text(tx + 9, top + 17 + i * 16, r, C.text if i else C.muted, 11, tags='hover') + +def nice_ceil(v): + if v <= 0: return 1 + e = 10 ** math.floor(math.log10(v)) + return next((k for k in (1, 2, 2.5, 5) if v / e <= k), 10) * e + +class SegmentBar(Paint): + """Stacked horizontal bar with a legend: (value, colour, label) segments of a total, in bytes.""" + def __init__(self, parent): + super().__init__(parent, 300, 58) + self.segments, self.total = [], 1 + def set(self, segments, total): + self.segments, self.total = segments, total if total > 0 else 1 + self.redraw() + def draw(self): + x = lx = 0 + ly, f = 26, F(11) + self.create_rectangle(0, 2, self.w, 16, fill=C.grid, width=0) + for value, color, _ in self.segments: + width = max(0, value / self.total * self.w) + self.create_rectangle(x, 2, x + width, 16, fill=color, width=0) + x += width + self.rrect(-3, -1, self.w + 3, 19, 10, outline=self['bg'], width=6) # rounds the ends of the bar + for value, color, name in self.segments: + label = f'{name} {fmt_bytes(value)}' + if lx + f.measure(label) + 26 > self.w: lx, ly = 0, ly + 18 + self.rrect(lx, ly + 3, lx + 9, ly + 12, 2, color) + self.text(lx + 14, ly + 8, label, C.muted, 11) + lx += f.measure(label) + 26 + +class Tile(Paint): + """Stat tile: title, large value, sub text and an accent stripe.""" + def __init__(self, parent, title, accent): + super().__init__(parent, 150, 84) + self.title, self.accent, self.shown = title.upper(), accent, ('—', '', None) + def set(self, value, sub='', color=None): + if (value, sub, color) != self.shown: + self.shown = (value, sub, color) + self.redraw() + def draw(self): + value, sub, color = self.shown + self.rrect(.5, .5, self.w - 1, self.h - 1, 12, C.card, C.border) + self.rrect(0, 14, 4, self.h - 14, 2, self.accent) + self.text(16, 20, elide(self.title, F(11, True), self.w - 28), C.muted, 11, True) + px = next((p for p in (21, 17, 14) if F(p, True).measure(value) <= self.w - 28), 14) # a narrow tile gets smaller digits + self.text(16, 44 if sub else 50, elide(value, F(px, True), self.w - 28), color or C.text, px, True) + self.text(16, 68, elide(sub, F(11), self.w - 28), C.muted, 11) + +class CoreGrid(Paint): + """One cell per CPU core: usage, bar and frequency.""" + def __init__(self, parent): + super().__init__(parent, 300, 66) + self.cores = [] + def set(self, cores): + self.cores = cores + self.redraw() + def draw(self): + cols = max(1, self.w // 92) + cw = self.w / cols + self.need_height(-(-max(1, len(self.cores)) // cols) * 66) + for i, core in enumerate(self.cores): + u, c, x, y = core.usage, level(core.usage, 60, 85), cw * (i % cols) + 3, i // cols * 66 + 3 + self.rrect(x, y, x + cw - 6, y + 60, 8, mix(C.card, c, u / 420), mix(C.border, c, u / 160)) + self.rrect(x + 8, y + 50, x + cw - 14, y + 54, 2, C.grid) + if u >= 1: self.rrect(x + 8, y + 50, x + 8 + (cw - 22) * u / 100, y + 54, 2, c) + self.text(x + 8, y + 12, f'CPU {i}', C.muted, 10) + if core.mhz > 0: self.text(x + cw - 14, y + 12, f'{core.mhz / 1000:.1f}G', C.muted, 10, anchor='e') + self.text(x + 8, y + 32, f'{u:.0f}%', px=16, bold=True) + +class Heatmap(Paint): + """Weekly pattern: average value per weekday and hour, with a tooltip.""" + DAYS = ('Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday') + def __init__(self, parent): + super().__init__(parent, 560, 230) + self.v, self.n, self.unit, self.hot, self.at = [[math.nan] * 24] * 7, [[0] * 24] * 7, '', C.accent, None + self.bind('', lambda e: self.point(int((e.y - 6) // ((self.h - 30) / 7)), int((e.x - 40) // ((self.w - 44) / 24)))) + self.bind('', lambda e: self.point(-1, -1)) + def set(self, v, n, unit, hot): + self.v, self.n, self.unit, self.hot = v, n, unit, hot + self.redraw() + def cell(self, d, h): + cw, ch = (self.w - 44) / 24, (self.h - 30) / 7 + return 40 + h * cw + 1.5, 6 + d * ch + 1.5, 40 + (h + 1) * cw - 1.5, 6 + (d + 1) * ch - 1.5 + def draw(self): + for d in range(7): + self.text(34, (self.cell(d, 0)[1] + self.cell(d, 0)[3]) / 2, self.DAYS[d][:3], C.muted, 10, anchor='e') + for h in range(24): + v = self.v[d][h] + self.rrect(*self.cell(d, h), 3, C.card if v != v else mix('#1b2a44', self.hot, .15 + .85 * min(max(v / 100, 0), 1))) + for h in range(0, 24, 3): self.text(self.cell(6, h)[0] - 4, self.cell(6, h)[3] + 11, f'{h:02d}:00', C.faint, 10) + if all(v != v for row in self.v for v in row): + x0, y0, x1, y1 = self.cell(2, 3)[:2] + self.cell(4, 20)[2:] + self.create_rectangle(x0, y0, x1, y1, fill=C.bg, width=0) + self.text((x0 + x1) / 2, (y0 + y1) / 2, 'Collecting hourly history… the weekly pattern fills in over time', px=12, anchor='center') + def point(self, d, h): + at = (d, h) if 0 <= d < 7 and 0 <= h < 24 else None + if at != self.at: + self.at, v = at, at and self.v[d][h] + show_tip(self, at and f'{self.DAYS[d]} {h}:00 — ' + ('no data' if v != v else f'avg {v:.1f}{self.unit} ({self.n[d][h]} samples)')) + +class KeyValues(Paint): + """List of (key, value) rows; long values wrap.""" + def __init__(self, parent, key_width=110): + super().__init__(parent, 200, 20) + self.rows, self.key_width = [], key_width + def set(self, rows): + if rows != self.rows: + self.rows = rows + self.redraw() + def draw(self): + y = 2 + for key, value in self.rows: + self.text(0, y, key, C.muted, anchor='nw') + y = self.bbox(self.text(self.key_width, y, value or ' ', anchor='nw', width=max(60, self.w - self.key_width)))[3] + 7 + self.need_height(y) + +class Chips(Paint): + """Row of small rounded (text, colour) labels that wraps.""" + def __init__(self, parent): + super().__init__(parent, 200, 22) + self.chips = [] + def set(self, chips): + if chips != self.chips: + self.chips = chips + self.redraw() + def draw(self): + x = y = 0 + for label, color in self.chips: + width = F(12).measure(label) + 18 + if x and x + width > self.w: x, y = 0, y + 26 + self.rrect(x, y, x + width, y + 22, 6, '#1f2a40') + self.text(x + 9, y + 11, label, color, 12) + x += width + 8 + self.need_height(y + 22) + +Cell = namedtuple('Cell', 'text color right pct key', defaults=('', False, -1, None)) # pct = bar, key = sort value + +class Table(tk.Frame): + """Hand-drawn table: coloured cells, bar cells, sortable columns and a selected row; only the visible rows are drawn. + A row is a list of cells (Cell or text); its first cell identifies it (by key, or else by text).""" + ROW, HEAD = 30, 32 + def __init__(self, parent, headers, widths=(), bars=(), sort=None, height=220): # sort: (column, descending), None = keep the order + super().__init__(parent, bg=C.line, padx=1, pady=1) + self.headers, self.widths, self.bars, self.sort, self.rows, self.top, self.selected = headers, widths, bars, sort, [], 0, None + self.on_open = self.on_menu = self.on_click = None # double click, right click (event), click (row index, column) + self.bar = ttk.Scrollbar(self, command=self.drag) + self.cv = Paint(self, 200, height, bg='#131929') + self.cv.draw = self.draw + self.cv.pack(side='left', fill='both', expand=True) + self.cv.bind('', self.click) + self.cv.bind('', lambda e: e.y > self.HEAD and self.on_open and self.on_open()) + self.cv.bind('', lambda e: self.click(e) or (self.on_menu and self.row() and self.on_menu(e))) + def set(self, rows): + self.rows = [[c if isinstance(c, Cell) else Cell(c) for c in r] for r in rows] + if not self.row(): self.selected = None # its entry is gone: the selection must not pass to a later one with the same key + if self.sort: + self.rows.sort(key=lambda r: r[self.sort[0]].text.lower() if r[self.sort[0]].key is None else r[self.sort[0]].key, reverse=self.sort[1]) + self.cv.redraw() + @staticmethod + def ident(row): return row[0].text if row[0].key is None else row[0].key + def row(self): + """The selected row, if it is still listed.""" + return next((r for r in self.rows if self.ident(r) == self.selected), None) + def visible(self): return max(1, (self.cv.winfo_height() - self.HEAD) // self.ROW) + def scroll(self, step, to=None): + """Scrolls by rows (or to a row); False when it cannot move any further.""" + top = min(max(self.top + step if to is None else to, 0), max(0, len(self.rows) - self.visible())) + moved, self.top = top != self.top, top + if moved: self.cv.redraw() + return moved + def drag(self, kind, value, unit=None): # scrollbar: ('moveto', fraction) or ('scroll', n, 'units' | 'pages') + if kind == 'moveto': self.scroll(0, round(float(value) * len(self.rows))) + else: self.scroll(int(value) * (self.visible() if unit == 'pages' else 1)) + def edges(self): + """Column x positions: given widths (100 when not given), the last column takes the rest; all shrink in a narrow table.""" + ws = [self.widths[i] if i < len(self.widths) else 100 for i in range(len(self.headers) - 1)] + xs, k = [0], min(1, self.cv.w / (sum(ws) + 90)) + for w in ws: xs.append(xs[-1] + w * k) + return xs + [self.cv.w] + def click(self, e): + col, i = bisect_right(self.edges(), e.x) - 1, self.top + (e.y - self.HEAD) // self.ROW + if e.y < self.HEAD: + if self.sort is not None and e.num == 1: + self.sort = (col, self.sort[0] == col and not self.sort[1]) + self.set(self.rows) + elif i < len(self.rows): + self.selected = self.ident(self.rows[i]) + self.cv.redraw() + if self.on_click and e.num == 1: self.on_click(i, col) + def draw(self): + cv, xs, n, shown = self.cv, self.edges(), len(self.rows), self.visible() + self.top = min(self.top, max(0, n - shown)) + for i in range(self.top, min(n, self.top + shown + 1)): + row, y = self.rows[i], self.HEAD + (i - self.top) * self.ROW + self.ROW / 2 + cv.create_rectangle(0, y - 15, cv.w, y + 15, width=0, fill=C.select if self.ident(row) == self.selected else '#161d2e' if i % 2 else '#131929') + for c, cell in enumerate(row): + x0, x1 = xs[c] + 8, (xs[c + 1] if len(row) > 1 else cv.w) - 8 + if c in self.bars and cell.pct >= 0: + p = min(max(cell.pct, 0), 100) + cv.rrect(x0 - 2, y - 7, x1 + 2, y + 7, 4, C.grid) + if p >= 1: cv.rrect(x0 - 2, y - 7, x0 - 2 + (x1 - x0 + 4) * p / 100, y + 7, 4, mix(C.grid, level(p), .78)) + cv.text((x0 + x1) / 2, y, cell.text, px=11, bold=True, anchor='center') + else: + cv.text(x1 if cell.right else x0, y, elide(cell.text, F(13), x1 - x0), cell.color or C.text, anchor='e' if cell.right else 'w') + cv.create_rectangle(0, 0, cv.w, self.HEAD, fill='#182033', width=0) + cv.create_line(0, self.HEAD, cv.w, self.HEAD, fill=C.border) + for c, title in enumerate(self.headers): + arrow = (' ▾' if self.sort[1] else ' ▴') if self.sort and self.sort[0] == c else '' + cv.text(xs[c] + 8, self.HEAD / 2, title + arrow, C.muted, 12, True) + self.bar.set(self.top / max(1, n), min(1, (self.top + shown) / max(1, n))) + if (n > shown) != bool(self.bar.winfo_manager()): self.bar.pack(side='right', fill='y', before=cv) if n > shown else self.bar.pack_forget() + +# ---- containers ------------------------------------------------------------------------------ +class Scroll(tk.Frame): + """Vertically scrollable area; the content goes into .body.""" + def __init__(self, parent): + super().__init__(parent, bg=parent['bg']) + self.cv = tk.Canvas(self, bg=parent['bg'], highlightthickness=0, yscrollincrement=20) + bar = ttk.Scrollbar(self, command=self.cv.yview) + self.body = tk.Frame(self.cv, bg=parent['bg']) + window = self.cv.create_window(0, 0, window=self.body, anchor='nw') + self.cv.config(yscrollcommand=bar.set) + bar.pack(side='right', fill='y') + self.cv.pack(side='left', fill='both', expand=True) + self.body.bind('', lambda e: self.cv.config(scrollregion=(0, 0, e.width, e.height))) + self.cv.bind('', lambda e: self.cv.itemconfig(window, width=e.width)) + def scroll(self, step): + before = self.cv.yview() + self.cv.yview_scroll(step, 'units') + return self.cv.yview() != before + +def on_wheel(e): + """Mouse wheel: scrolls the innermost Table / Scroll under the pointer that can still move.""" + w, step = e.widget, -3 if e.num == 4 or e.delta > 0 else 3 + while isinstance(w, tk.Misc) and not isinstance(w, tk.Text): + if hasattr(w, 'scroll') and w.scroll(step): break + w = w.master + +class Tabs(tk.Frame): + """Tab bar (the current tab is underlined) above a stack of pages; pages are created with the Tabs as parent.""" + def __init__(self, parent, on_change): + super().__init__(parent, bg=parent['bg']) + self.bar, self.pages, self.marks, self.current, self.on_change = down(box(self), 0), [], [], 0, on_change + down(tk.Frame(self, bg=C.line, height=1), 0) + self.bind('', lambda e: self.fit(e.width)) + def fit(self, width): # a narrow window gets tighter tabs + pad = min(13, max(2, (width - sum(F(13, True).measure(text['text']) for text, _ in self.marks)) // (2 * len(self.marks)) - 1)) + for text, _ in self.marks: text.config(padx=pad) + def add(self, title, page): + i, f = len(self.pages), right(box(self.bar), 0) + text = down(tk.Label(f, text=title, bg=self['bg'], fg=C.muted, font=F(13, True), padx=13, pady=9, cursor='hand2'), 0) + text.bind('', lambda e: self.show(i)) + self.marks.append((text, down(tk.Frame(f, height=2, bg=self['bg']), 0))) + self.pages.append(page) + def show(self, i): + self.pages[self.current].pack_forget() + self.current = i + self.pages[i].pack(fill='both', expand=True) + for k, (text, underline) in enumerate(self.marks): + text.config(fg='#7dd3fc' if k == i else C.muted) + underline.config(bg=C.accent if k == i else self['bg']) + self.on_change() + +# ---- small builders ---------------------------------------------------------------------------- +def down(w, gap=14, **kw): + """Packs w below its siblings (full width, gap underneath) and returns it.""" + w.pack(**{'side': 'top', 'fill': 'x', 'pady': (0, gap), **kw}) + return w + +def right(w, gap=10, grow=False, **kw): + """Packs w to the right of its siblings (gap after it) and returns it.""" + w.pack(**{'side': 'left', 'fill': 'both', 'expand': grow, 'padx': (0, gap), **kw}) + return w + +def spread(widgets, cols=99, weights=None, gap=14): + """Grids the children of one frame into columns of equal (or weighted) width.""" + for i, w in enumerate(widgets): + w.grid(row=i // cols, column=i % cols, sticky='nsew', padx=(gap if i % cols else 0, 0), pady=(gap if i >= cols else 0, 0)) + w.master.columnconfigure(i % cols, weight=weights[i] if weights else 1, uniform='columns') + +def box(parent, **kw): return tk.Frame(parent, bg=parent['bg'], **kw) + +def panel(parent, title='', width=0): + """Bordered panel with an optional title and minimum width.""" + f = tk.Frame(parent, bg=C.panel, padx=16, pady=14, highlightthickness=1, highlightbackground=C.line) + if width: tk.Frame(f, bg=C.panel, width=width - 34, height=0).pack() + if title: down(label(f, title.upper(), 'Section'), 10) + return f + +def tiles(parent, defs, cols=99): + """Row(s) of stat tiles from (title, colour) pairs.""" + f = down(box(parent)) + made = [Tile(f, *d) for d in defs] + spread(made, cols) + return made + +STYLES = {'H1': (22, True, C.text), 'H2': (16, True, C.text), 'Muted': (13, False, C.muted), 'Section': (11, True, C.muted), 'Small': (11, False, C.muted)} + +def label(parent, text='', kind=None, wrap=0, **kw): + """Text label; wrap = pixels, or True to wrap at the width the layout gives it.""" + px, bold, color = STYLES.get(kind, (13, False, C.text)) + w = tk.Label(parent, **{'text': text, 'bg': parent['bg'], 'fg': color, 'font': F(px, bold), 'justify': 'left', 'anchor': 'w', + 'wraplength': 300 if wrap is True else wrap, **kw}) + if wrap is True: w.bind('', lambda e: w.config(wraplength=e.width)) + return w + +# background, text, hover background, border (None = like the parent) +BUTTONS = {None: ('#1d2538', C.text, '#253049', '#2c3650'), 'Primary': ('#0e7ab8', '#ffffff', '#1190d8', C.accent), + 'Danger': ('#3a1820', '#ffb4bd', '#55202b', '#7f2a36'), 'Side': ('#1d2538', C.text, '#253049', '#2c3650'), + 'Flat': (None, C.muted, None, None), 'Nav': (None, C.text, C.card, None)} + +def button(parent, text, command=None, kind=None, **kw): + bg, fg, over, border = (x or parent['bg'] for x in BUTTONS[kind]) + b = tk.Button(parent, **{'text': text, 'command': command, 'bg': bg, 'fg': fg, 'activebackground': over, 'cursor': 'hand2', + 'activeforeground': C.text if kind == 'Flat' else fg, 'disabledforeground': C.faint, 'relief': 'flat', 'bd': 0, + 'highlightthickness': 1, 'highlightbackground': border, 'padx': 13, 'pady': 5, 'takefocus': 0, + 'font': F(14 if kind == 'Nav' else 13, kind in (None, 'Primary', 'Danger')), + 'anchor': 'w' if kind in ('Nav', 'Side') else 'center', **kw}) + b.kind, b.colors = kind, (bg, fg) + b.bind('', lambda e: b['state'] != 'disabled' and b.config(bg=b['activebackground'])) + b.bind('', lambda e: b.config(bg=b.colors[0])) + return b + +def press(b, on): + """Shows a button as checked or not.""" + normal = [x or b.master['bg'] for x in BUTTONS[b.kind][:2]] + b.colors = ((C.select, '#7dd3fc') if b.kind == 'Nav' else BUTTONS['Primary'][:2]) if on else normal + b.config(bg=b.colors[0], fg=b.colors[1]) + +FIELD = {'bg': C.field, 'fg': C.text, 'insertbackground': C.text, 'relief': 'flat', 'bd': 5, 'highlightthickness': 1, + 'highlightbackground': '#2a3449', 'highlightcolor': C.accent} +OFF = {'disabledbackground': C.bg, 'disabledforeground': C.faint} # look of disabled entry fields + +class Entry(tk.Entry): + """Text field with a placeholder (hint); text() is '' while the hint shows.""" + def __init__(self, parent, text='', hint='', width=20, show='', mono=False): + super().__init__(parent, width=width, font=F(13, mono=mono), **FIELD, **OFF) + self.hint, self.mask, self.hinting = hint, show, False + self.insert(0, text) + self.bind('', lambda e: self.blur(False)) + self.bind('', lambda e: self.blur(True)) + self.blur(True) + def blur(self, away): + if self.hinting and not away: + self.hinting = False + self.delete(0, 'end') + elif away and not self.get() and self.hint: + self.hinting = True + self.insert(0, self.hint) + self.config(fg=C.faint if self.hinting else C.text, show='' if self.hinting else self.mask) + def text(self): return '' if self.hinting else self.get() + def put(self, text, hint=None): + self.blur(False) + self.hint = self.hint if hint is None else hint + self.delete(0, 'end') + self.insert(0, text) + self.blur(self.focus_get() is not self) + +class Spin(tk.Spinbox): + """Number field; value() is clamped to the range (an int when the step is whole).""" + def __init__(self, parent, lo, hi, value=0, step=1, width=7, command=None): + super().__init__(parent, from_=lo, to=hi, increment=step, width=width, font=F(13), buttonbackground=C.card, command=command, **FIELD, **OFF) + self.lo, self.hi, self.step = lo, hi, step + self.put(value) + if command: + self.bind('', lambda e: command()) + self.bind('', lambda e: command()) + def put(self, value): + self.delete(0, 'end') + self.insert(0, f'{value:.12g}') + def value(self): + v = min(max(num(self.get()), self.lo), self.hi) + return v if self.step % 1 else int(v) + +def combo(parent, values, width=18, command=None, edit=False): + c = ttk.Combobox(parent, values=values, width=width, state='normal' if edit else 'readonly', font=F(13)) + if values and not edit: c.current(0) + c.bind('<>', lambda e: (c.selection_clear(), command and command())) + return c + +def check(parent, text, on=False, command=None): + """Check box; .var holds the state.""" + var = tk.BooleanVar(value=on) + c = tk.Checkbutton(parent, text=text, variable=var, command=command, bg=parent['bg'], fg=C.text, activebackground=parent['bg'], + activeforeground=C.text, selectcolor=C.field, anchor='w', font=F(13), cursor='hand2', highlightthickness=0, bd=0) + c.var = var + return c + +def textbox(parent, mono=True, **kw): + """Read-only text area with a scrollbar; pack its .frame. Fill it with write().""" + frame = box(parent) + t = tk.Text(frame, **{'bg': '#080b12', 'fg': '#cfe3ff', 'font': F(12, mono=mono), 'relief': 'flat', 'bd': 0, 'padx': 10, 'pady': 10, 'wrap': 'none', + 'state': 'disabled', 'width': 1, 'height': 1, 'highlightthickness': 0, **kw}) + bar = ttk.Scrollbar(frame, command=t.yview) + t.config(yscrollcommand=bar.set) + bar.pack(side='right', fill='y') + t.pack(side='left', fill='both', expand=True) + t.frame = frame + return t + +def write(t, text, color=None, clear=False): + """Appends text (optionally coloured) to a read-only text area and scrolls to the end.""" + t.config(state='normal') + if clear: t.delete('1.0', 'end') + t.insert('end', text, color or ()) + t.delete('1.0', 'end - 20000 lines') + if color: t.tag_config(color, foreground=color) + t.config(state='disabled') + t.see('end') + +def field(form, text, widget): + """Adds a labelled row to a form frame and returns the widget.""" + r = form.grid_size()[1] + label(form, text, 'Muted').grid(row=r, column=0, sticky='w', padx=(0, 14), pady=5) + widget.grid(row=r, column=1, sticky='ew', pady=5) + form.columnconfigure(1, weight=1) + return widget + +def popup(widget, event, items): + """Context menu from (text, command) pairs; None = separator.""" + if getattr(popup, 'menu', None): popup.menu.destroy() # the previous one + popup.menu = m = tk.Menu(widget, tearoff=0) + for item in items: m.add_command(label=item[0], command=item[1]) if item else m.add_separator() + m.tk_popup(event.x_root, event.y_root) + +def show_tip(widget, text): + """Shows a tooltip near the pointer; an empty text hides it.""" + tip = getattr(show_tip, 'window', None) + if tip: tip.destroy() + show_tip.window = None + if text: + show_tip.window = tip = tk.Toplevel(widget, bg=C.accent, padx=1, pady=1) + tip.overrideredirect(True) + tk.Label(tip, text=text, bg=C.card, fg=C.text, padx=8, pady=5, justify='left', wraplength=560, font=F(11)).pack() + tip.geometry(f'+{widget.winfo_pointerx() + 14}+{widget.winfo_pointery() + 18}') + +def tip(widget, text): + widget.bind('', lambda e: show_tip(widget, text), add='+') + widget.bind('', lambda e: show_tip(widget, ''), add='+') + return widget + +class Dialog(tk.Toplevel): + """Dark dialog window; run() shows it modally and returns what close() was given.""" + def __init__(self, parent, title): + super().__init__(parent, bg=C.bg, padx=24, pady=20) + self.title(title) + self.transient(parent.winfo_toplevel()) + self.result = None + self.protocol('WM_DELETE_WINDOW', self.close) + self.bind('', lambda e: self.close()) + def buttons(self, *defs): + """Row of (text, command[, kind]) buttons at the bottom right.""" + row = down(box(self), 0) + for d in reversed(defs): button(row, *d).pack(side='right', padx=(8, 0)) + def close(self, result=None): + self.result = result + self.destroy() + def run(self): + self.update_idletasks() + top = self.master.winfo_toplevel() + self.geometry(f'+{top.winfo_rootx() + max(0, (top.winfo_width() - self.winfo_reqwidth()) // 2)}+{top.winfo_rooty() + 120}') + self.wait_visibility() + self.grab_set() + self.wait_window() + return self.result + +def choose(parent, title, text, options): + """Modal question with (text, kind) buttons; returns the text of the chosen one, None when dismissed.""" + d = Dialog(parent, title) + down(label(d, text, wrap=460), 18) + d.buttons(*((name, lambda name=name: d.close(name), kind) for name, kind in options)) + return d.run() + +def ask(parent, title, text, danger=False): return choose(parent, title, text, [('No', None), ('Yes', 'Danger' if danger else 'Primary')]) == 'Yes' + +def app_icon(size): + """App icon: gradient tile with a pulse line.""" + line = [(.12, .56), (.34, .56), (.44, .28), (.56, .78), (.66, .48), (.88, .48)] + + def near(x, y, a, b): # distance from (x, y) to the segment a-b + (ax, ay), (bx, by) = a, b + k = min(max(((x - ax) * (bx - ax) + (y - ay) * (by - ay)) / ((bx - ax) ** 2 + (by - ay) ** 2), 0), 1) + return math.hypot(x - ax - k * (bx - ax), y - ay - k * (by - ay)) + + image = tk.PhotoImage(width=size, height=size) + cells = [[(x + .5) / size, (y + .5) / size] for y in range(size) for x in range(size)] + colors = ['#ffffff' if min(near(x, y, a, b) for a, b in zip(line, line[1:])) < .042 else mix('#0ea5e9', '#7c3aed', (x + y) / 2) for x, y in cells] + image.put(' '.join('{' + ' '.join(colors[r * size:(r + 1) * size]) + '}' for r in range(size))) + return image diff --git a/Server Monitor(web-linux)/README.md b/Server Monitor(web-linux)/README.md new file mode 100644 index 0000000000000000000000000000000000000000..78a7ad20c6d5c27684e287a137f4dfd91dde6d81 --- /dev/null +++ b/Server Monitor(web-linux)/README.md @@ -0,0 +1,72 @@ +# Server Monitor (web) — Linux edition + +Watches Linux machines in detail from a browser: this computer, and remote servers over the system `ssh` client. It keeps their history from seconds to years, analyzes it with plain statistics (no AI) and fixes common problems automatically. A small Node.js server does the monitoring; the page is plain HTML, CSS and JavaScript with hand-drawn charts and gauges. No npm packages, no build step. + +It is a port of the C++/Qt desktop app "Server Monitor" and uses the same `servers.json` schema and the same binary history files. + +## Requirements + +- Node.js 22 or newer (only built-in modules are used). +- A current browser (Chrome, Edge, Firefox or Safari). +- For remote servers: the OpenSSH client (`ssh`) on this computer. Nothing is installed on the servers; they need a POSIX `sh` and `/proc`. + +## Run + +```sh +./run.sh # starts the server and opens the page +# or +node server.js # then open http://127.0.0.1:8765 +``` + +`PORT=9000 node server.js` uses another port. Stop it with Ctrl+C. Monitoring, history, alert rules and the autopilot run as long as the server runs, with or without an open page. Up to five browser tabs can show the monitor at the same time: each tab holds one live connection and browsers allow six per site. + +## How it connects + +- **This machine:** no setup. The collector script (`core/collector.sh`) is piped into `sh`. +- **SSH:** the same script is piped through `ssh user@host sh -s`. Keys are recommended (`ssh-copy-id user@host`); a password also works and is handed to ssh through `SSH_ASKPASS`. + +The script prints the raw contents of `/proc` and `/sys` once per interval; all calculations happen in the Node.js server. Control actions (signals, `systemctl`, console commands, autopilot) run as the login user. Tick **sudo -n** for a server to wrap privileged actions in `sudo -n` (needs passwordless sudo). + +## Features + +- **Dashboard:** a live card per server (gauges, sparklines, health grade), totals, recent events, search. +- **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. +- **History:** every sample for 6 h, 1-minute averages and peaks for 30 days, hourly for 2 years, daily for 20 years; downtime is stored too. Ranges from 1 h to all time with min / average / 95th percentile / peak and CSV export. +- **Analysis (every minute):** disk-full forecast, memory growth, per-process leaks, runaway processes, failed or flapping services, overload, swap thrashing, anomalies against the same weekday and hour, availability, capacity advice, a health score (0–100, grade A–F) and a weekly heatmap. +- **Autopilot:** acts on the findings with cooldowns and limits; **dry run** only reports what it would do. +- **Alert rules:** "CPU > 90 % for 60 s → warning → restart a service". Events go to the Events page, to `alerts.log` and, if switched on, to browser notifications. + +## Where data is stored + +`~/.config/ServerMonitorWeb` (or `$XDG_CONFIG_HOME/ServerMonitorWeb`), created for your user only (mode 700): + +- `servers.json` — servers, rules and autopilot settings (file mode 600). Saved SSH passwords are only lightly disguised, not encrypted, so prefer keys. +- `history//{raw,minute,hour,day}.bin` — the history. +- `alerts.log` — every event, tab-separated; starts over at 5 MB. + +## Security model + +The page can run shell commands on your servers, so the server only talks to this computer: + +- It listens on `127.0.0.1` only. For access from elsewhere use an SSH tunnel (`ssh -L 8765:127.0.0.1:8765 this-computer`). +- Requests whose `Host` header is not `127.0.0.1:` or `localhost:` are refused (DNS rebinding), and so are requests with a foreign `Origin`. +- Everything that changes state is a `POST` with `Content-Type: application/json` and the header `X-SM: 1`. No CORS headers are ever sent, so other web pages can neither send such requests nor read any reply. +- Stored SSH passwords are never sent to the browser; the page only learns that one exists. +- Data from servers is inserted into the page as text only, and a Content-Security-Policy allows scripts from this server alone. + +There is no login: every local user who can reach the port can use the monitor. Do not run it on a shared computer. + +## Code + +``` +server.js HTTP server, live updates (Server-Sent Events), JSON API +core/platform.js everything Linux-specific: shell, frame parser, command tables, texts +core/collector.sh collector script that runs on the monitored machine +core/metrics.js one parsed sample + parser helpers +core/model.js server config, rules +core/history.js history store + analyzer +core/session.js ssh/local link, per-server session (rules, autopilot), manager +public/ the page: index.html, style.css, app.js, shared.js (formatting used by both sides) +``` + +The Windows edition differs only in `core/platform.js`, its collector script, this README and the launcher. diff --git a/Server Monitor(web-linux)/core/collector.sh b/Server Monitor(web-linux)/core/collector.sh new file mode 100644 index 0000000000000000000000000000000000000000..89cb4b20caeb8a3c5b99d699515910bf9debdebd --- /dev/null +++ b/Server Monitor(web-linux)/core/collector.sh @@ -0,0 +1,77 @@ +sm_main() { +iv="${1:-2}" once="${2:-0}" n=0 +export LC_ALL=C +while :; do + echo "@@SNAP_BEGIN" + if [ $((n % 15)) -eq 0 ]; then + echo "@@S info" + echo "hostname=$(cat /proc/sys/kernel/hostname 2>/dev/null)" + echo "kernel=$(uname -r 2>/dev/null)" + echo "arch=$(uname -m 2>/dev/null)" + echo "os=$(sed -n 's/^PRETTY_NAME=//p' /etc/os-release 2>/dev/null | tr -d '"')" + echo "cpumodel=$(grep -m1 -E '^(model name|Hardware|Processor|cpu model)' /proc/cpuinfo 2>/dev/null | cut -d: -f2- | sed 's/^ *//')" + echo "clk=$(getconf CLK_TCK 2>/dev/null || echo 100)" + echo "page=$(getconf PAGESIZE 2>/dev/null || echo 4096)" + echo "virt=$(systemd-detect-virt 2>/dev/null || echo unknown)" + echo "@@S passwd"; cut -d: -f1,3 /etc/passwd 2>/dev/null + fi + echo "@@S uptime"; cat /proc/uptime + echo "@@S loadavg"; cat /proc/loadavg + echo "@@S stat" + grep -E '^(cpu|ctxt|processes|procs_)' /proc/stat + awk '/^intr/ {print "intr", $2}' /proc/stat + echo "@@S meminfo"; cat /proc/meminfo + echo "@@S netdev"; cat /proc/net/dev + echo "@@S netstate" + for i in /sys/class/net/*; do + [ -e "$i" ] || continue + echo "${i##*/} $(cat "$i/operstate" 2>/dev/null || echo unknown) $(cat "$i/speed" 2>/dev/null || echo -1)" + done + echo "@@S diskstats"; cat /proc/diskstats + echo "@@S df"; df -P -T -k 2>/dev/null || df -P -k 2>/dev/null + echo "@@S sockstat"; cat /proc/net/sockstat 2>/dev/null + echo "@@S tcp" + 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]}' + echo "@@S thermal" + for z in /sys/class/thermal/thermal_zone*; do + [ -r "$z/temp" ] && echo "$(cat "$z/type" 2>/dev/null)|$(cat "$z/temp" 2>/dev/null)" + done + for h in /sys/class/hwmon/hwmon*; do + [ -d "$h" ] || continue + hn=$(cat "$h/name" 2>/dev/null) + for t in "$h"/temp*_input; do + [ -r "$t" ] || continue + l=$(cat "${t%_input}_label" 2>/dev/null) + echo "$hn ${l:-${t##*/}}|$(cat "$t" 2>/dev/null)" + done + done + echo "@@S freq" + for c in /sys/devices/system/cpu/cpu[0-9]*; do + f=$(cat "$c/cpufreq/scaling_cur_freq" 2>/dev/null) && echo "${c##*/cpu} $f" + done + echo "@@S procs" + cat /proc/[0-9]*/stat 2>/dev/null | awk '{ + if (!match($0, /\(.*\)/)) next + comm = substr($0, RSTART + 1, RLENGTH - 2) + rest = substr($0, RSTART + RLENGTH + 1) + k = split(rest, r, " ") + if (k < 22) next + print $1, r[1], r[2], r[12] + r[13], r[17], r[18], r[20], r[21], r[22], comm + }' + echo "@@S uids"; ls -ln /proc 2>/dev/null | awk '$NF ~ /^[0-9]+$/ {print $NF, $3}' + if [ $((n % 5)) -eq 0 ]; then + echo "@@S services" + systemctl list-units --type=service --all --no-legend --no-pager --plain 2>/dev/null | head -n 600 + fi + if [ $((n % 3)) -eq 0 ] && command -v nvidia-smi >/dev/null 2>&1; then + echo "@@S gpu" + 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 + fi + echo "@@S users"; who 2>/dev/null | wc -l + echo "@@SNAP_END" || exit 0 + [ "$once" = "once" ] && break + n=$((n + 1)) + sleep "$iv" +done +} +sm_main "$@" diff --git a/Server Monitor(web-linux)/core/history.js b/Server Monitor(web-linux)/core/history.js new file mode 100644 index 0000000000000000000000000000000000000000..df6f9748dfc284cce3dfddb04aaf0d5b6b30f323 --- /dev/null +++ b/Server Monitor(web-linux)/core/history.js @@ -0,0 +1,307 @@ +// Persistent multi-resolution history (raw 6 h, minute 30 d, hour 2 y, day 20 y) in the binary format every edition +// shares, and the statistics-only analyzer that feeds the autopilot. +const fs = require('fs'), path = require('path'); +const plat = require('./platform'); +const { Fmt, H, hNames, fmtMetric } = require('../public/shared'); + +const N = H.length, REC = 16 + 8 * N, I = Object.fromEntries(H.map((k, i) => [k, i])); +const HEADER = Buffer.from([...Buffer.from('SMH1'), N, 0, REC & 255, REC >> 8]); +const FILES = ['raw', 'minute', 'hour', 'day'], TIERS = ['every sample', '1 minute', '1 hour', '1 day']; +const STEP = [1, 60, 3600, 86400], KEEP = [6 * 3600, 30 * 86400, 732 * 86400, 7320 * 86400]; +const nowSec = () => Math.floor(Date.now() / 1000); +const fileSize = f => fs.statSync(f, { throwIfNoEntry: false })?.size || 0; + +// a point: { ts (s; bucket start for aggregates), n samples, nUp online samples, avg[N], max[N] }, NaN = no value +// file record: int64 ts, uint32 n, uint32 nUp, float32 avg[N], float32 max[N], little-endian +function encode(pts) { + const b = Buffer.alloc(pts.length * REC); + pts.forEach((p, i) => { + const o = i * REC; + b.writeBigInt64LE(BigInt(p.ts), o), b.writeUInt32LE(p.n, o + 8), b.writeUInt32LE(p.nUp, o + 12); + for (let k = 0; k < N; ++k) b.writeFloatLE(p.avg[k], o + 16 + 4 * k), b.writeFloatLE(p.max[k], o + 16 + 4 * (N + k)); + }); + return b; +} +function decode(b, o) { + const p = { ts: Number(b.readBigInt64LE(o)), n: b.readUInt32LE(o + 8), nUp: b.readUInt32LE(o + 12), avg: new Float32Array(N), max: new Float32Array(N) }; + for (let k = 0; k < N; ++k) p.avg[k] = b.readFloatLE(o + 16 + 4 * k), p.max[k] = b.readFloatLE(o + 16 + 4 * (N + k)); + return p; +} + +class Acc { // accumulates points into one bucket + constructor(bucket) { this.bucket = bucket, this.n = this.nUp = 0, this.cnt = new Float64Array(N), this.sum = new Float64Array(N), this.mx = new Float32Array(N).fill(NaN); } + add(p) { + this.n += p.n, this.nUp += p.nUp; + if (!p.nUp) return; + for (let i = 0; i < N; ++i) { + if (isNaN(p.avg[i])) continue; + this.sum[i] += p.avg[i] * p.nUp, this.cnt[i] += p.nUp; + if (isNaN(this.mx[i]) || p.max[i] > this.mx[i]) this.mx[i] = p.max[i]; + } + } + point() { return { ts: this.bucket, n: this.n, nUp: this.nUp, avg: Float32Array.from(this.sum, (s, i) => this.cnt[i] ? s / this.cnt[i] : NaN), max: this.mx.slice() }; } +} + +class HistoryStore { + constructor(dir) { this.dir = dir, this.load(); } + file(t) { return path.join(this.dir, FILES[t] + '.bin'); } + bucketOf(t, ts) { return t === 3 ? Math.floor((ts + this.tz) / 86400) * 86400 - this.tz : Math.floor(ts / STEP[t]) * STEP[t]; } // days at local midnight + + load() { + fs.mkdirSync(this.dir, { recursive: true }); + const now = nowSec(); + this.tz = -new Date().getTimezoneOffset() * 60, this.t = [[], [], [], []], this.acc = [], this.appends = [0, 0, 0, 0]; + for (let t = 0; t < 4; ++t) { + const f = this.file(t), v = this.t[t]; + if (!fileSize(f)) continue; + const d = fs.readFileSync(f); + if (!d.subarray(0, 8).equals(HEADER)) { fs.renameSync(f, f + '.old'); continue; } + let bad = (d.length - 8) % REC; // a cut-off record would misalign everything appended after it + for (let off = 8; off + REC <= d.length; off += REC) { + const p = decode(d, off); + if (p.ts < now - KEEP[t] || p.ts > now + 86400 || (v.length && p.ts <= v.at(-1).ts)) ++bad; + else v.push(p); + } + if (bad) this.rewrite(t); + } + for (let t = 1; t < 4; ++t) { // rebuild from finer data what is not stored yet: buckets the last run left open, and the current one + const stored = this.t[t].at(-1)?.ts ?? -1; + this.acc[t] = new Acc(-1); + for (const p of [...this.t[t - 1], ...(this.acc[t - 1]?.n ? [this.acc[t - 1].point()] : [])]) { + const b = this.bucketOf(t, p.ts); + if (b <= stored) continue; + if (b !== this.acc[t].bucket) { + if (this.acc[t].n) this.append(t, this.acc[t].point()); + this.acc[t] = new Acc(b); + } + this.acc[t].add(p); + } + } + } + + rewrite(t) { + const f = this.file(t); + fs.writeFileSync(f + '.tmp', Buffer.concat([HEADER, encode(this.t[t])])), fs.renameSync(f + '.tmp', f); + } + + append(t, p) { + const v = this.t[t], f = this.file(t); + if (v.length && p.ts <= v.at(-1).ts) return; + v.push(p); + try { + if (fileSize(f) < 8) fs.writeFileSync(f, HEADER); + fs.appendFileSync(f, encode([p])); + if (++this.appends[t] % 500) return; // trim expired points now and then + const keep = v.findIndex(x => x.ts >= p.ts - KEEP[t]); + if (keep > 0) v.splice(0, keep), this.rewrite(t); + } catch { /* disk full or not writable: monitoring goes on with the points in memory */ } + } + + add(ts, val, up) { // up = false records downtime only + const raw = { ts, n: 1, nUp: +up, avg: Float32Array.from(val, x => up ? x : NaN) }; + raw.max = raw.avg, this.append(0, raw); + for (let t = 1; t < 4; ++t) { // every coarser tier accumulates every raw sample + const b = this.bucketOf(t, ts); + if (this.acc[t].bucket !== b) { + if (this.acc[t].n && this.acc[t].bucket < b) this.append(t, this.acc[t].point()); + this.acc[t] = new Acc(b); + } + this.acc[t].add(raw); + } + } + + tierFor(from, to) { // finest tier covering the range + const now = nowSec(), maxSpan = [6 * 3600, 8 * 86400, 400 * 86400]; + let t = 0; + while (t < 3 && (from < now - KEEP[t] || to - from > maxSpan[t])) ++t; + return t; + } + range(from, to, t = this.tierFor(from, to)) { // includes the open bucket + const out = this.t[t].filter(p => p.ts >= from && p.ts <= to), a = this.acc[t]; + if (t && a.n && a.bucket >= from && a.bucket <= to && !(out.at(-1)?.ts >= a.bucket)) out.push(a.point()); + return out; + } + + removeFiles() { fs.rmSync(this.dir, { recursive: true, force: true }), this.load(); } + firstTs() { return Math.min(...this.t.filter(v => v.length).map(v => v[0].ts), Infinity) % Infinity || 0; } // 0 when empty + diskBytes() { return FILES.reduce((b, _, t) => b + fileSize(this.file(t)), 0); } +} + +function stats(pts, m) { // max = peak of max[] + const s = { min: NaN, avg: NaN, p95: NaN, max: NaN, count: 0 }, v = []; + let sum = 0, w = 0; + for (const p of pts) { + if (!p.nUp || isNaN(p.avg[m])) continue; + v.push(p.avg[m]), sum += p.avg[m] * p.nUp, w += p.nUp; + if (isNaN(s.max) || p.max[m] > s.max) s.max = p.max[m]; + } + if (!v.length) return s; + v.sort((a, b) => a - b); + return Object.assign(s, { count: v.length, avg: sum / w, min: v[0], p95: v[Math.min(v.length - 1, Math.floor(v.length * 0.95))] }); +} + +function regression(pts, m) { // [slope per second, R²] + let n = 0, sx = 0, sy = 0, sxx = 0, sxy = 0, syy = 0; + for (const p of pts) { + if (!p.nUp || isNaN(p.avg[m])) continue; + const x = p.ts - pts[0].ts, y = p.avg[m]; + n++, sx += x, sy += y, sxx += x * x, sxy += x * y, syy += y * y; + } + const den = n * sxx - sx * sx, num = n * sxy - sx * sy, vy = n * syy - sy * sy, ok = n >= 3 && den > 0; + return [ok ? num / den : 0, ok && vy > 1e-9 ? num * num / (den * vy) : 0]; // squared correlation +} + +const grid = fill => Array.from({ length: 7 }, () => Array(24).fill(fill)); +const blankAnalysis = () => ({ + when: 0, health: 100, grade: 'A', diskBasis: '', healthReasons: [], capacity: [], findings: [], anomalies: [], + diskFullDays: -1, diskSlopePerDay: 0, memSlopePerHour: 0, memTrendR2: 0, up: [NaN, NaN, NaN], down: [0, 0, 0], // 24 h, 7 d, 30 d: availability %, seconds offline + cpu30: stats([]), mem30: stats([]), heat: [grid(NaN), grid(NaN)], heatN: grid(0), // weekly pattern: 0 = CPU, 1 = memory +}); + +// finding.action: disk_cleanup | restart_service | renice | kill_pid; procs / svcs are the trends tracked by the session +function analyze(st, m, ap, procs, svcs, online) { + const a = blankAnalysis(), now = a.when = nowSec(), [, minute, hour] = st.t, f1 = v => Fmt.fix(v, 1), f2 = v => Fmt.fix(v, 2); + const add = (key, severity, category, title, detail, advice, action = '', actionArg = '', actionLabel = '', autoEligible = false) => + a.findings.push({ key, severity, category, title, detail, advice, action, actionArg, actionLabel, autoEligible }); + const sev = (crit, warn) => crit ? 'critical' : warn ? 'warning' : 'info'; + const localHour = ts => { const d = new Date(ts * 1000); return [(d.getDay() + 6) % 7, d.getHours()]; }; // Monday = 0 + + // availability + const spans = [86400, 7 * 86400, 30 * 86400]; + spans.forEach((s, i) => { + let n = 0, up = 0; + for (const p of st.range(now - s, now)) n += p.n, up += p.nUp; + if (n) a.up[i] = up * 100 / n, a.down[i] = (n - up) / n * Math.min(s, now - st.firstTs()); // share of the monitored part of the window + }); + if (a.up[0] < 99) + add('avail24', sev(a.up[0] < 95, true), 'Availability', `Availability last 24 h is ${Fmt.pct(a.up[0], 2)}`, + `The server could not be reached for about ${Fmt.duration(a.down[0])} in the last day.`, + 'Check network stability, power and whether the machine rebooted (uptime).'); + const w30 = st.range(now - spans[2], now, 2), long = w30.length >= 24 ? w30 : st.range(now - spans[1], now, 1); + a.cpu30 = stats(long, I.cpu), a.mem30 = stats(long, I.mem); + + // disk forecast: regression over 7 d of hours, or 24 h of minutes, whichever fits better + const week = st.range(now - spans[1], now, 2), day = st.range(now - 86400, now, 1); + let [slope, r2] = [0, 0]; + if (week.length >= 48) [slope, r2] = regression(week, I.disk), a.diskBasis = 'hourly averages, last 7 days'; + if (day.length >= 120) { + const [s2, r2b] = regression(day, I.disk); + if (week.length < 48 || r2b > r2) slope = s2, r2 = r2b, a.diskBasis = 'minute averages, last 24 hours'; + } + a.diskSlopePerDay = slope * 86400; + if (a.diskSlopePerDay > 0.05 && r2 >= 0.3 && m.maxDiskPct > 0) a.diskFullDays = (100 - m.maxDiskPct) / a.diskSlopePerDay; + if (a.diskFullDays >= 0 && a.diskFullDays < 30) + add('diskfull', sev(a.diskFullDays < ap.diskForecastDays, a.diskFullDays < 14), 'Disk', `Disk ${m.fullestMount} will be full in ${Fmt.duration(a.diskFullDays * 86400)}`, + `Usage ${Fmt.pct(m.maxDiskPct)}, growing ${f2(a.diskSlopePerDay)} points/day (trend from ${a.diskBasis}, fit R² ${f2(r2)}).`, + 'Clean logs/caches, rotate or move data, or grow the volume.', 'disk_cleanup', '', 'Run cleanup', ap.diskCleanup && a.diskFullDays < ap.diskForecastDays); + if (m.maxDiskPct >= ap.diskCleanupAt) + add('diskhigh', sev(m.maxDiskPct >= 97, true), 'Disk', `Disk ${m.fullestMount} is ${Fmt.pct(m.maxDiskPct)} full`, + `Above the cleanup threshold of ${Fmt.pct(ap.diskCleanupAt, 0)}.`, 'Free space soon: services fail when the disk is full.', + 'disk_cleanup', '', 'Run cleanup', ap.diskCleanup); + + // whole-machine memory trend over 6 h + const six = st.range(now - 6 * 3600, now, 1); + if (six.length >= 90) { + const [s, fit] = regression(six, I.mem), left = (100 - m.memPct) / Math.max(0.01, s * 3600); + a.memSlopePerHour = s * 3600, a.memTrendR2 = fit; + if (a.memSlopePerHour > 1 && fit > 0.8 && m.memPct > 40) + add('memtrend', sev(false, left < 12), 'Memory', `Memory keeps growing (+${f1(a.memSlopePerHour)} points/hour)`, + `Steady growth over 6 h (R² ${f2(fit)}). At this rate memory is exhausted in about ${Fmt.duration(left * 3600)}.`, + 'Look for a leaking process (Processes tab, sort by RSS).'); + } + + // processes: leaks and runaways + for (const p of procs) { + if (p.kernel) continue; + const who = `${p.name} (PID ${p.pid})`, pid = String(p.pid), term = ap.runawayMode === 'terminate'; + if (p.minutesTracked >= 30 && p.rssGrowthPct >= 25 && p.rssGrowth >= 100e6 && p.rssMonotonic >= 0.8) + add('leak:' + pid, sev(m.memPct >= ap.leakMemPressure, true), 'Process', 'Possible memory leak: ' + who, + `RSS grew ${Fmt.bytes(p.rssGrowth)} (+${Fmt.pct(p.rssGrowthPct, 0)}) in ${p.minutesTracked} min and rose in ${Math.round(p.rssMonotonic * 100)}% of the minutes; now ${Fmt.bytes(p.rssNow)}.`, + 'Restart the program/service at a quiet time and report the leak upstream.', 'kill_pid', pid, 'Terminate', + ap.leakMode === 'terminate' && m.memPct >= ap.leakMemPressure); + if (p.highCpuMinutes >= ap.runawayMinutes) + add('runaway:' + pid, 'warning', 'Process', 'Runaway process: ' + who, + `Above ${Fmt.pct(ap.runawayCpu, 0)} CPU for ${Math.round(p.highCpuMinutes)} min (now ${Fmt.pct(p.cpuNow)}, user ${p.user}).`, + 'Lower its priority (renice) or stop it if it is stuck.', term ? 'kill_pid' : 'renice', pid, term ? 'Terminate' : 'Renice to 19', ap.runawayMode !== 'none'); + } + + // services: failures and flapping + for (const s of svcs) { + const flap = s.failsLastHour >= 3 || s.autoRestartsLastHour >= ap.maxRestartsPerHour; + if (s.failedNow) + add('svc:' + s.unit, sev(flap, true), 'Service', `Service ${s.unit} ${flap ? 'keeps failing' : 'has failed'}`, + s.preexisting ? 'It was already failed when monitoring started, so the autopilot leaves it alone (it may be failed on purpose).' + : `Failed ${s.failsLastHour}× in the last hour; autopilot restarted it ${s.autoRestartsLastHour}×.`, + flap ? 'Automatic restarts were stopped. Read the logs (Services tab → Logs) and fix the cause.' : 'Restart it and check the logs.', + 'restart_service', s.unit, 'Restart', ap.restartFailed && !s.preexisting && s.autoRestartsLastHour < ap.maxRestartsPerHour); + else if (s.failsLastHour >= 3) + add('flap:' + s.unit, 'warning', 'Service', `Service ${s.unit} is unstable`, `It failed ${s.failsLastHour} times within the last hour.`, 'Inspect its logs and resource limits.'); + } + + // overload and swap thrashing (without an I/O wait counter: memory full now + busy disks) + const last15 = st.range(now - 900, now, 1), avg15 = k => stats(last15, I[k]).avg, load15 = avg15('load'), perCore = load15 / m.cpuCount; + if (online && perCore > 1.5) + add('load', sev(perCore > 3, true), 'CPU', `CPU is overloaded (load ${f1(load15)} on ${m.cpuCount} cores)`, + `15-minute average load is ${f1(perCore)}× the number of cores; tasks are waiting for CPU.`, 'Find the busiest processes, spread work over time, or add CPU.'); + if (online && m.swapPct > 50 && (plat.ui.posixCpu ? avg15('iowait') > 20 : m.memPct > 90 && avg15('diskio') > 50)) + add('thrash', 'critical', 'Memory', 'Swap thrashing', plat.ui.posixCpu ? `Swap ${Fmt.pct(m.swapPct)} used and CPU waits on I/O ${Fmt.pct(avg15('iowait'))} of the time.` + : `Swap ${Fmt.pct(m.swapPct)} used, memory ${Fmt.pct(m.memPct)} full and disks ${Fmt.pct(avg15('diskio'))} busy.`, 'Stop memory-hungry processes or add RAM.'); + + // anomalies: last 10 min vs same weekday+hour over 8 weeks (fallback: last 24 h) + const raw = st.range(now - 600, now, 0), [today, thisHour] = localHour(now); + for (const [k, floor, down] of [['cpu', 5], ['mem', 3], ['load', 0.25 * Math.max(1, m.cpuCount)], ['iowait', 3], ['rx', 256e3, true], ['tx', 256e3, true]]) { + if (!online || raw.length < 10 || (k === 'iowait' && !plat.ui.posixCpu)) continue; + const hm = I[k], cur = stats(raw, hm).avg, ok = p => p.nUp && !isNaN(p.avg[hm]), name = hNames[hm]; + let basis = 'same weekday & hour, last 8 weeks'; + let v = hour.filter(p => ok(p) && now - p.ts < 56 * 86400 && now - p.ts > 3600 && localHour(p.ts).join() === [today, thisHour].join()); + if (v.length < 3) { + v = minute.filter(p => ok(p) && now - p.ts <= 86400 && now - p.ts > 900), basis = 'last 24 hours'; + if (v.length < 360) continue; + } + const mean = v.reduce((s, p) => s + p.avg[hm] / v.length, 0), sd = Math.sqrt(v.reduce((s, p) => s + (p.avg[hm] - mean) ** 2 / v.length, 0)); + const z = (cur - mean) / Math.max(sd, floor), hi = z >= ap.anomalyZ, lo = down && mean > 1e6 && cur < mean * 0.1; + a.anomalies.push({ metric: name, baseline: basis, hm, now: cur, mean, sd, z }); + if (ap.anomalyAlerts && (hi || lo)) + add('anomaly:' + k, sev(false, z >= ap.anomalyZ * 2), 'Anomaly', `Unusually ${hi ? 'high' : 'low'} ${name.toLowerCase()}`, + `Last 10 min ${fmtMetric(hm, cur)}, usually ${fmtMetric(hm, mean)} ± ${fmtMetric(hm, sd)} (${basis}); ${f1(z)}σ.`, + hi ? 'Check what changed: deploys, cron jobs, traffic, attacks.' : 'Traffic dropped sharply - check the service is still serving.'); + } + + // weekly heatmaps from 4 weeks of hours + const sum = [grid(0), grid(0)]; + for (const p of hour) { + if (now - p.ts > 28 * 86400 || !p.nUp || isNaN(p.avg[I.cpu])) continue; + const [d, h] = localHour(p.ts), n = ++a.heatN[d][h]; + sum[0][d][h] += p.avg[I.cpu], sum[1][d][h] += p.avg[I.mem] || 0; + a.heat[0][d][h] = sum[0][d][h] / n, a.heat[1][d][h] = sum[1][d][h] / n; + } + + // capacity advice + for (const [s, name, lo, hi, loTxt, hiTxt] of [[a.cpu30, 'CPU', 15, 80, 'is mostly idle', 'is often saturated - add cores or move work away'], + [a.mem30, 'Memory', 30, 85, 'is under-used', 'is tight - add RAM or reduce caches/limits']]) + if (s.count >= 60) a.capacity.push(`${name} ${s.p95 < lo ? loTxt : s.p95 > hi ? hiTxt : 'headroom is healthy'} (p95 ${Fmt.pct(s.p95)}).`); + if (a.diskFullDays >= 0) a.capacity.push(`Disk grows ${f2(a.diskSlopePerDay)} points/day - full in about ${Fmt.duration(a.diskFullDays * 86400)}.`); + else if (a.diskBasis) a.capacity.push('Disk usage is stable.'); + if (!a.capacity.length) a.capacity.push('Collecting history - capacity advice appears after about an hour of data.'); + + // health score + let score = 100; + const pen = (when, p, why) => { if (when && p > 0.5) score -= p, a.healthReasons.push(`−${Math.round(p)} ${why}`); }; + const cpu15 = avg15('cpu'), cpu = isNaN(cpu15) ? m.cpuUsage : cpu15; + const fp = a.findings.reduce((s, f) => s + (f.category === 'Availability' ? 0 : f.severity === 'critical' ? 15 : f.severity === 'warning' ? 7 : 2), 0); + pen(!online, 60, 'server unreachable'); + pen(cpu > 70, Math.min(24, (cpu - 70) * 0.8), `CPU busy (${Fmt.pct(cpu)})`); + pen(m.memPct > 80, Math.min(30, (m.memPct - 80) * 1.5), `memory high (${Fmt.pct(m.memPct)})`); + pen(m.maxDiskPct > 80, Math.min(40, (m.maxDiskPct - 80) * 2), `disk high (${Fmt.pct(m.maxDiskPct)})`); + pen(m.swapPct > 50, 10, 'heavy swap use'); + pen(m.maxTemp > 80, Math.min(20, (m.maxTemp - 80) * 2), `hot (${Fmt.temp(m.maxTemp)})`); + pen(a.up[0] < 100, Math.min(30, (100 - a.up[0]) * 5), 'downtime in last 24 h'); + pen(true, Math.min(50, fp), `${a.findings.length} finding(s)`); + a.health = Math.min(100, Math.max(0, Math.round(score))); + a.grade = 'FDCBA'[a.health >= 90 ? 4 : a.health >= 75 ? 3 : a.health >= 60 ? 2 : a.health >= 40 ? 1 : 0]; + const rank = f => ['critical', 'warning'].indexOf(f.severity) & 3; // critical 0, warning 1, others 3 + a.findings.sort((x, y) => rank(x) - rank(y)); + return a; +} + +module.exports = { I, TIERS, STEP, HistoryStore, stats, analyze, blankAnalysis, nowSec }; diff --git a/Server Monitor(web-linux)/core/metrics.js b/Server Monitor(web-linux)/core/metrics.js new file mode 100644 index 0000000000000000000000000000000000000000..c4f93fce8636f1ec3b8022e45107f510acff2db8 --- /dev/null +++ b/Server Monitor(web-linux)/core/metrics.js @@ -0,0 +1,77 @@ +// One parsed sample (Metrics) and the frame helpers shared by the platform parsers. +const num = s => +s || 0; +const ZERO = ('cpuCount loggedUsers procsRunning procsBlocked threadsTotal socketsUsed servicesFailed servicesRunning uptime load1 load5 load15 ' + + 'cpuUsage cpuUser cpuSystem cpuIowait cpuSteal cpuIrq ctxtPerSec intrPerSec forksPerSec avgMhz memTotal memFree memAvailable memUsed buffers cached ' + + 'shared slab dirty swapTotal swapUsed memPct swapPct diskReadBps diskWriteBps maxDiskPct maxDiskUtil netRxBps netTxBps maxTemp').split(' '); + +const blank = now => ({ + valid: false, timestamp: now, hostname: '', os: '', kernel: '', arch: '', cpuModel: '', virt: '', fullestMount: '', busiestDisk: '', + ...Object.fromEntries(ZERO.map(k => [k, 0])), cores: [], mounts: [], disks: [], nets: [], tcp: {}, procs: [], services: [], temps: [], gpus: [], +}); + +// "@@S
" + rows -> { section: [rows] } +function sections(frame) { + const sec = {}; + let cur; + for (const raw of frame.split('\n')) { + const l = raw.replace(/\r$/, ''); + if (l.startsWith('@@S ')) cur = sec[l.slice(4).trim()] ??= []; + else if (cur && l && !l.startsWith('@@')) cur.push(l); + } + return sec; +} + +const kv = (lines = [], into = {}) => { + for (const l of lines) { + const e = l.indexOf('='); + if (e > 0) into[l.slice(0, e)] = l.slice(e + 1).trim(); + } + return into; +}; + +// per-second rates of counter vectors ("net:eth0" -> [rx, tx, ...]); the frame's counters replace the previous ones +function rater(st, dt) { + const prev = st.ctr || {}, next = st.ctr = {}; + return (key, v) => { + const p = prev[key]; + next[key] = v; + return v.map((x, i) => dt > 0.05 && p?.length === v.length ? Math.max(0, (x - p[i]) / dt) : 0); + }; +} + +function addDisk(m, d, counted) { + if (counted) { + m.diskReadBps += d.readBps, m.diskWriteBps += d.writeBps; + if (d.util >= m.maxDiskUtil) m.maxDiskUtil = d.util, m.busiestDisk = d.name; + } + m.disks.push(d); +} + +function addMount(m, mt) { + mt.pct = mt.used + mt.avail > 0 ? mt.used * 100 / (mt.used + mt.avail) : 0; + if (mt.pct >= m.maxDiskPct) m.maxDiskPct = mt.pct, m.fullestMount = mt.mount; + m.mounts.push(mt); +} + +// what both parsers do last: derived values, sorting, cached GPU / service lists, temperatures ("name|value", value × scale = °C) +function finish(m, st, sec, tempScale) { + m.memUsed = Math.max(0, m.memTotal - m.memAvailable); + m.memPct = m.memTotal > 0 ? m.memUsed * 100 / m.memTotal : 0; + m.swapPct = m.swapTotal > 0 ? m.swapUsed * 100 / m.swapTotal : 0; + m.nets.sort((a, b) => a.virt - b.virt || (a.name < b.name ? -1 : +(a.name > b.name))); + for (const n of m.nets) if (!n.virt) m.netRxBps += n.rxBps, m.netTxBps += n.txBps; + for (const p of m.procs) p.memPct = m.memTotal > 0 ? p.rss * 100 / m.memTotal : 0, m.threadsTotal += p.threads; + m.procs.sort((a, b) => b.cpu - a.cpu || b.rss - a.rss); + if (sec.gpu) + st.gpus = sec.gpu.map(l => l.split(',').map(x => x.trim())).filter(f => f.length >= 8) + .map(f => ({ index: Math.trunc(num(f[0])), name: f[1], util: num(f[2]), memUsed: num(f[3]), memTotal: num(f[4]), temp: num(f[5]), power: num(f[6]), fan: num(f[7]) })); + m.gpus = st.gpus || [], m.services = st.services || []; + for (const s of m.services) m.servicesFailed += s.active === 'failed', m.servicesRunning += s.sub === 'running'; + for (const l of sec.thermal || []) { + const bar = l.lastIndexOf('|'), name = l.slice(0, Math.max(0, bar)).trim(), celsius = num(l.slice(bar + 1)) * tempScale; + if (bar <= 0 || celsius <= 0 || celsius > 150 || m.temps.some(t => t.name === name)) continue; + m.temps.push({ name, celsius }), m.maxTemp = Math.max(m.maxTemp, celsius); + } +} + +module.exports = { num, blank, sections, kv, rater, addDisk, addMount, finish }; diff --git a/Server Monitor(web-linux)/core/model.js b/Server Monitor(web-linux)/core/model.js new file mode 100644 index 0000000000000000000000000000000000000000..aaa8d29cc5b71d5e5c04eb952939b9edcbd2f701 --- /dev/null +++ b/Server Monitor(web-linux)/core/model.js @@ -0,0 +1,47 @@ +// Server configuration (servers.json has the same schema in every edition), rules and the values rules look at. +const crypto = require('crypto'); +const plat = require('./platform'); + +const RULE = { id: '', metric: 'cpu', op: '>', action: 'notify', arg: '', severity: 'warning', enabled: true, value: 90, duration: 60, cooldown: 300 }; +const AUTOPILOT = { // history-driven automatic control (evaluated by the analyzer every minute) + enabled: true, dryRun: false, restartFailed: true, diskCleanup: false, anomalyAlerts: true, maxRestartsPerHour: 3, runawayMinutes: 10, diskForecastDays: 3, + runawayCpu: 90, diskCleanupAt: 92, leakMemPressure: 90, anomalyZ: 3, runawayMode: 'renice', leakMode: 'notify', diskCleanupCommand: plat.cleanup, +}; +const SERVER = { id: '', name: '', group: '', host: '', user: '', keyFile: '', notes: '', port: 22, interval: plat.ui.interval, useSudo: false, enabled: true }; + +const newId = () => crypto.randomUUID().slice(0, 12); +const defaultRules = () => [['cpu', 90, 60, 'warning'], ['mem', 90, 60, 'warning'], ['swap', 80, 120, 'warning'], ['disk', 90, 0, 'critical'], + ['temp', 85, 30, 'critical'], ['load', 150, 120, 'warning'], ['failed', 0, 0, 'warning']] + .map(([metric, value, duration, severity]) => ({ ...RULE, id: newId(), metric, value, duration, severity })); + +// the fields of `def`, taken from `o` where present and converted to the default's type (strings trimmed) +const pick = (def, o = {}) => Object.fromEntries(Object.entries(def).map(([k, d]) => [k, o[k] == null ? d + : typeof d === 'number' ? (Number.isFinite(+o[k]) ? +o[k] : d) : typeof d === 'boolean' ? !!o[k] : String(o[k]).trim()])); + +// a complete ServerConfig from any object (stored JSON or a form sent by the page); the password is kept in clear in memory +function make(o, password) { + const c = { ...pick(SERVER, o), transport: o.transport === 0 ? 0 : 1, password, autopilot: pick(AUTOPILOT, o.autopilot) }; // 0 Local, 1 SSH + c.rules = Array.isArray(o.rules) ? o.rules.map(r => pick(RULE, r)) : defaultRules(); + for (const r of c.rules) r.id ||= newId(); + c.interval = Math.min(300, Math.max(1, Math.round(c.interval))), c.id ||= newId(); + return c; +} + +const KEY = Buffer.from('ServerMonitor/obfuscation/v1'); +const xor = (s, enc) => Buffer.from(Buffer.from(s, enc ? 'utf8' : 'base64').map((b, i) => b ^ KEY[i % KEY.length])).toString(enc ? 'base64' : 'utf8'); // NOT encryption + +const gpuMax = (m, k) => Math.max(0, ...m.gpus.map(g => g[k])); + +module.exports = { + RULE, make, defaultRules, + fromJson: o => make(o, xor(String(o.password || ''), false)), + toJson: c => ({ ...c, password: xor(c.password, true) }), + forPage: c => ({ ...c, password: undefined, hasPassword: !!c.password }), // stored passwords never leave the server + address: c => c.transport === 0 ? 'this machine' : (c.user && c.user + '@') + c.host + (c.port !== 22 ? ':' + c.port : ''), + gpuMax, + metricValues: m => ({ + cpu: m.cpuUsage, iowait: m.cpuIowait, load: m.load1 * 100 / Math.max(1, m.cpuCount), mem: m.memPct, swap: m.swapPct, disk: m.maxDiskPct, + diskio: m.maxDiskUtil, temp: m.maxTemp, rx: m.netRxBps / 1e6, tx: m.netTxBps / 1e6, failed: m.servicesFailed, procs: m.procs.length, + gpu: gpuMax(m, 'util'), gputemp: gpuMax(m, 'temp'), + }), +}; diff --git a/Server Monitor(web-linux)/core/platform.js b/Server Monitor(web-linux)/core/platform.js new file mode 100644 index 0000000000000000000000000000000000000000..0e7a0ec89c97bb286cc2667fd8e9b5aaa2e37f62 --- /dev/null +++ b/Server Monitor(web-linux)/core/platform.js @@ -0,0 +1,182 @@ +// Everything that depends on the operating system (Linux edition): where the config lives, how to start a shell, +// the collector script with its frame parser, the control commands and the texts the page shows for them. +// The Windows edition replaces this file and the collector script; every other file is identical. +const fs = require('fs'), os = require('os'), path = require('path'); +const { num, blank, sections, kv, rater, addDisk, addMount, finish } = require('./metrics'); + +const collector = fs.readFileSync(path.join(__dirname, 'collector.sh'), 'utf8'); // POSIX sh, reads /proc and /sys +const quote = s => "'" + s.replace(/'/g, "'\\''") + "'"; +const restartFailed = "for u in $(systemctl list-units --type=service --state=failed --no-legend --plain | awk '{print $1}'); do echo restart $u; systemctl restart $u; done"; +const cleanup = 'journalctl --vacuum-time=7d 2>/dev/null; apt-get clean 2>/dev/null; dnf clean all 2>/dev/null; ' + + 'find /tmp /var/tmp -xdev -type f -atime +7 -delete 2>/dev/null; true'; +// rows: label, command ({n} = pid, {q} = quoted name), danger, confirm, has a button +const cmds = rows => rows.map(([label, cmd, danger = false, confirm = true, button = true]) => ({ label, cmd, danger, confirm, button })); + +// ---- collector frame parser: raw /proc text in, Metrics out; `st` keeps counters between frames ---- +const F = l => l.trim().split(/\s+/); +const VIRT = /^(lo|veth|docker|br-|virbr|cni|flannel|cali|vxlan|kube|tun|tap)/; +const WHOLE = /^(sd[a-z]+|vd[a-z]+|xvd[a-z]+|hd[a-z]+|nvme\d+n\d+|mmcblk\d+|md\d+)$/; +const TCP = ['', 'ESTABLISHED', 'SYN_SENT', 'SYN_RECV', 'FIN_WAIT1', 'FIN_WAIT2', 'TIME_WAIT', 'CLOSE', 'CLOSE_WAIT', 'LAST_ACK', 'LISTEN', 'CLOSING']; +const SKIP_FS = new Set(['tmpfs', 'devtmpfs', 'squashfs', 'overlay', 'efivarfs', 'ramfs', 'proc', 'sysfs', 'autofs', 'nsfs', 'devfs', 'cgroup', 'cgroup2', + 'fuse.snapfuse', 'fuse.portal']); + +function parse(frame, st, now) { + const sec = sections(frame), L = k => sec[k] || [], first = k => F(L(k)[0] || ''); + const m = blank(now), info = kv(sec.info, st.info ??= {}); + if (sec.passwd) { + st.users = {}; + for (const l of sec.passwd) { + const c = l.lastIndexOf(':'); + if (c > 0) st.users[parseInt(l.slice(c + 1))] = l.slice(0, c); + } + } + m.hostname = info.hostname || '', m.os = info.os || '', m.kernel = info.kernel || '', m.arch = info.arch || ''; + m.cpuModel = info.cpumodel || '', m.virt = info.virt || ''; + const clk = Math.max(1, parseInt(info.clk ?? 100) || 0), page = Math.max(512, parseInt(info.page ?? 4096) || 0); + [m.load1, m.load5, m.load15] = first('loadavg').map(num); + m.load5 ||= 0, m.load15 ||= 0, m.uptime = num(first('uptime')[0]); + if (m.uptime <= 0) return m; + const dt = st.upt > 0 ? m.uptime - st.upt : 0, rates = dt > 0.05, delta = rater(st, dt); + + // CPU + const cpu = [], stat = [0, 0, 0]; + for (const f of L('stat').map(F)) { + if (f[0].startsWith('cpu')) cpu.push(f.slice(1, 9).map(num)); + else if (f[0] === 'ctxt') stat[0] = num(f[1]); + else if (f[0] === 'intr') stat[1] = num(f[1]); + else if (f[0] === 'processes') stat[2] = num(f[1]); + else if (f[0] === 'procs_running') m.procsRunning = num(f[1]); + else if (f[0] === 'procs_blocked') m.procsBlocked = num(f[1]); + } + m.cpuCount = Math.max(1, cpu.length - 1); + m.cores = Array.from({ length: m.cpuCount }, () => ({ usage: 0, mhz: 0 })); + let jiffies = 0; + if (rates && st.cpu?.length === cpu.length) + cpu.forEach((t, i) => { + const d = Array.from({ length: 8 }, (_, k) => (t[k] || 0) - (st.cpu[i][k] || 0)), tot = d.reduce((a, b) => a + b, 0); + if (tot <= 0) return; + const p = k => Math.min(100, Math.max(0, d[k] * 100 / tot)); // user nice system idle iowait irq softirq steal + const use = Math.min(100, Math.max(0, 100 - p(3) - p(4))); + if (i) m.cores[i - 1].usage = use; + 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); + }); + st.cpu = cpu; + [m.ctxtPerSec, m.intrPerSec, m.forksPerSec] = delta('stat', stat); + let nf = 0; + for (const f of L('freq').map(F)) { + const c = m.cores[parseInt(f[0])]; + if (c) m.avgMhz += c.mhz = num(f[1]) / 1000, ++nf; + } + m.avgMhz = nf ? m.avgMhz / nf : 0; + + // memory + const mi = {}, mem = k => mi[k] || 0; + for (const l of L('meminfo')) { + const c = l.indexOf(':'); + if (c > 0) mi[l.slice(0, c)] = num(F(l.slice(c + 1))[0]) * 1024; + } + m.memTotal = mem('MemTotal'), m.memFree = mem('MemFree'), m.buffers = mem('Buffers'), m.cached = mem('Cached') + mem('SReclaimable'); + m.memAvailable = 'MemAvailable' in mi ? mi.MemAvailable : m.memFree + m.buffers + m.cached; + m.shared = mem('Shmem'), m.slab = mem('Slab'), m.dirty = mem('Dirty'), m.swapTotal = mem('SwapTotal'); + m.swapUsed = Math.max(0, m.swapTotal - mem('SwapFree')); + + // network + const state = Object.fromEntries(L('netstate').map(l => [F(l)[0], F(l)])); + for (const l of L('netdev')) { + const c = l.indexOf(':'), f = F(l.slice(c + 1)).map(num), name = l.slice(0, Math.max(0, c)).trim(); + if (c <= 0 || f.length < 16) continue; + const [rxBps, txBps, rxPps, txPps] = delta('net:' + name, [f[0], f[8], f[1], f[9]]); + m.nets.push({ name, virt: VIRT.test(name), state: state[name]?.[1] ?? 'unknown', speed: parseInt(state[name]?.[2] ?? -1) || 0, + rxBps, txBps, rxPps, txPps, rxBytes: f[0], txBytes: f[8], errors: f[2] + f[10], drops: f[3] + f[11] }); + } + for (const f of L('tcp').map(F)) { + const name = TCP[parseInt(f[0], 16)] ?? '?'; + m.tcp[name] = (m.tcp[name] || 0) + num(f[1]); + } + for (const l of L('sockstat')) if (l.startsWith('sockets:')) m.socketsUsed = num(F(l)[2]); + + // disks: whole devices + device-mapper; totals over physical disks only + for (const f of L('diskstats').map(F)) { + const name = f[2], whole = WHOLE.test(name); + if (f.length < 14 || (!whole && !name.startsWith('dm-'))) continue; + const totalRead = num(f[5]) * 512, totalWritten = num(f[9]) * 512; + const [readIops, readBps, writeIops, writeBps, busy] = delta('disk:' + name, [num(f[3]), totalRead, num(f[7]), totalWritten, num(f[12])]); + addDisk(m, { name, readBps, writeBps, readIops, writeIops, util: Math.min(100, busy / 10), totalRead, totalWritten }, whole && !name.startsWith('md')); + } + const df = L('df'), b = df[0]?.includes('Type') ? 1 : 0, seen = new Set(); + for (const f of df.slice(1).map(F)) { + if (f.length < 6 + b) continue; + const mt = { device: f[0], type: b ? f[1] : '', mount: f.slice(5 + b).join(' '), total: num(f[1 + b]) * 1024, used: num(f[2 + b]) * 1024, avail: num(f[3 + b]) * 1024 }; + const key = mt.device + mt.total; + if (SKIP_FS.has(b ? mt.type : mt.device) || mt.total <= 0 || mt.mount.startsWith('/snap/') || (mt.device.startsWith('/') && seen.has(key))) continue; + seen.add(key), addMount(m, mt); + } + + // processes: "pid state ppid ticks nice threads start vsize rss comm..." + const uid = Object.fromEntries(L('uids').map(l => F(l).map(num))), ticks = {}; + const perCore = jiffies > 0 ? jiffies / m.cpuCount : rates ? dt * clk : 0; + for (const l of L('procs')) { + const f = l.split(' '), pid = parseInt(f[0]); + if (f.length < 10 || !(pid > 0)) continue; + ticks[pid] = num(f[3]); + m.procs.push({ pid, ppid: num(f[2]), threads: num(f[5]), nice: num(f[4]), name: f.slice(9).join(' '), state: f[1][0] || '?', + user: pid in uid ? st.users?.[uid[pid]] ?? String(uid[pid]) : '?', + cpu: perCore > 0 && st.ticks && pid in st.ticks ? Math.min(100 * m.cpuCount, Math.max(0, (ticks[pid] - st.ticks[pid]) * 100 / perCore)) : 0, + rss: num(f[8]) * page, vsz: num(f[7]), age: Math.max(0, m.uptime - num(f[6]) / clk) }); + } + + // services arrive every few samples: keep the last list + if (sec.services) + st.services = sec.services.map(F).filter(f => f.length >= 4 && f[0].endsWith('.service')) + .map(f => ({ unit: f[0], load: f[1], active: f[2], sub: f[3], description: f.slice(4).join(' ') })); + m.loggedUsers = num(first('users')[0]); + finish(m, st, sec, 0.001); + + st.ticks = ticks, st.upt = m.uptime; + m.valid = rates; // the first sample has no rates yet + return m; +} + +module.exports = { + quote, parse, cleanup, + configDir: () => path.join(process.env.XDG_CONFIG_HOME || path.join(os.homedir(), '.config'), 'ServerMonitorWeb'), + shell: interval => interval ? ['sh', '-s', '--', String(interval)] : ['sh', '-s'], // argv of a shell that runs a script from stdin + collector: () => collector, // stdin for the collector + wrap: (cmd, sudo) => (sudo ? 'sudo -n sh -c ' + quote(cmd) : cmd) + '\n', // stdin for a one-shot command + askpass: ['askpass.sh', '#!/bin/sh\nprintf \'%s\\n\' "$SERVERMONITOR_ASKPASS"\n'], // answers ssh's password prompt + command: (action, arg) => ({ + kill_pid: `kill -TERM ${parseInt(arg) || 0}`, renice: `renice -n 19 -p ${parseInt(arg) || 0}`, drop_caches: 'sync && echo 3 > /proc/sys/vm/drop_caches', + restart_service: `systemctl reset-failed ${quote(arg)} 2>/dev/null; systemctl restart ${quote(arg)}`, restart_failed: restartFailed, + })[action], + serviceLogs: (unit, lines) => `systemctl status --no-pager -l ${quote(unit)} 2>&1 | head -n 15; echo; echo '==== journal ===='; journalctl -u ${quote(unit)} -n ${lines} --no-pager 2>&1`, + power: reboot => `(sleep 2; systemctl ${reboot ? 'reboot' : 'poweroff'}) >/dev/null 2>&1 &`, + detached: true, // every child leads its own process group, so that kill() also ends what its shell started + kill: p => { try { process.kill(-p.pid, 'SIGKILL'); } catch { /* not started or already gone */ } }, + // told "+pid" / "-pid" on stdin; when stdin closes (the monitor is gone, even killed) it ends the process groups still listed + reaper: ['sh', '-c', 'p=" "; while read -r l; do x=${l#?}; case $l in +*) p="$p$x ";; -*) p="${p%% $x *} ${p#* $x }";; esac; done; for x in $p; do kill -KILL -$x; done 2>/dev/null'], + // never killed automatically, no leak / runaway findings: init, kernel threads, ssh + isProtected: p => p.pid <= 2 || p.ppid === 2 || p.rss <= 0 || p.name === 'sshd' || p.name === 'systemd', + + ui: { // sent to the page + name: 'Linux', sudo: true, posixCpu: true, interval: 2, prioLabel: 'Nice', normalPrio: 0, kernelPrefix: 'Linux ', + sshHint: 'Uses your system ssh client; nothing is installed on the server. Set up key login once with: ssh-copy-id user@host', + keyHint: 'default keys / ssh-agent (~/.ssh/id_*)', + ruleActions: [['notify', 'Notify only', ''], ['restart_failed', 'Restart failed services', ''], ['restart_service', 'Restart a service', 'nginx.service'], + ['kill_top_cpu', 'Terminate top CPU process', ''], ['kill_top_mem', 'Terminate top memory process', ''], ['drop_caches', 'Sync + drop page cache', ''], + ['command', 'Run a command', 'find /tmp -mtime +7 -delete']], + procActions: cmds([['Terminate', 'kill -TERM {n}'], ['Kill', 'kill -KILL {n}', true], ['Hang up', 'kill -HUP {n}', false, true, false], + ['Suspend', 'kill -STOP {n}'], ['Resume', 'kill -CONT {n}', false, false]]), + priorities: cmds([['-20 (highest)', -20], ['-10', -10], ['0 (normal)', 0], ['10', 10], ['19 (lowest)', 19]].map(([label, v]) => [label, `renice -n ${v} -p {n}`])), + serviceActions: cmds([['Start', 'systemctl start {q}', false, false], ['Stop', 'systemctl stop {q}', true], ['Restart', 'systemctl restart {q}'], + ['Reload', 'systemctl reload {q}', false, false], ['Enable', 'systemctl enable {q}', false, false], ['Disable', 'systemctl disable {q}', true]]), + diagnostics: cmds([['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'], + ['Memory', 'free -h; echo; vmstat 1 3'], ['Top CPU processes', 'ps -eo pid,user,pcpu,pmem,rss,etime,comm --sort=-pcpu | head -n 20'], + ['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'], + ['Errors in journal', 'journalctl -p err -n 60 --no-pager'], ['Failed services', 'systemctl --failed --no-pager'], ['Logged-in users', 'w'], + ['Last reboots', 'last -x reboot shutdown 2>/dev/null | head -n 15']]), + systemActions: cmds([['Sync + drop page cache', 'sync && echo 3 > /proc/sys/vm/drop_caches && echo done'], ['Vacuum journal to 200 MB', 'journalctl --vacuum-size=200M'], + ['Clean package cache', '(apt-get clean || dnf clean all || yum clean all) 2>&1'], ['Restart failed services', restartFailed + '; echo done'], + ['Reboot', "(sleep 2; systemctl reboot) >/dev/null 2>&1 & echo 'reboot scheduled'", true], + ['Shut down', "(sleep 2; systemctl poweroff) >/dev/null 2>&1 & echo 'shutdown scheduled'", true]]), + }, +}; diff --git a/Server Monitor(web-linux)/core/session.js b/Server Monitor(web-linux)/core/session.js new file mode 100644 index 0000000000000000000000000000000000000000..9bc943426c7ddfb6ba0c6e124f863e301e46910b --- /dev/null +++ b/Server Monitor(web-linux)/core/session.js @@ -0,0 +1,355 @@ +// Connection to one machine (local shell or the system ssh), the per-server session (metrics, live rows, rules, +// autopilot) and the manager of all sessions. +const { spawn } = require('child_process'), { EventEmitter } = require('events'); +const fs = require('fs'), os = require('os'), path = require('path'); +const plat = require('./platform'), model = require('./model'); +const { blank } = require('./metrics'); +const { HistoryStore, analyze, blankAnalysis, nowSec } = require('./history'); +const { Fmt, ruleMetrics, def, conditionText, actionText } = require('../public/shared'); + +// ---- link: streams collector frames and runs one-shot commands; close() kills everything ---- +const SSH_OPTS = ['ConnectTimeout=10', 'ServerAliveInterval=10', 'ServerAliveCountMax=3', 'StrictHostKeyChecking=accept-new', 'LogLevel=ERROR']; +const links = new Set(); // every open link: closing them ends every child process +let askpass; // helper script that answers ssh's password prompt, created on first use and removed on exit +let reaper; // platform helper that ends the children if this process is killed without a chance to do it +function reap(sign, pid) { // "+pid" when a child starts, "-pid" when it has ended + if (!plat.reaper || !pid) return; + if (!reaper) (reaper = spawn(plat.reaper[0], plat.reaper.slice(1), { stdio: ['pipe', 'ignore', 'ignore'], detached: true })).on('error', () => {}), reaper.stdin.on('error', () => {}); + reaper.stdin.write(sign + pid + '\n'); +} +function askpassFile() { + if (askpass) return askpass; + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sm-')); + process.on('exit', () => fs.rmSync(dir, { recursive: true, force: true })); + fs.writeFileSync(askpass = path.join(dir, plat.askpass[0]), plat.askpass[1], { mode: 0o700 }); + return askpass; +} + +class Link { + constructor(cfg) { this.c = cfg, this.procs = new Set(), this.closed = '', links.add(this); } + + spawn(argv, input) { + const c = this.c, env = { ...process.env }; + let cmd = argv[0], args = argv.slice(1); + if (c.transport) { + args = SSH_OPTS.flatMap(o => ['-o', o]), cmd = 'ssh'; + if (!c.password) args.push('-o', 'BatchMode=yes'); + else { + args.push('-o', 'NumberOfPasswordPrompts=1'); + Object.assign(env, { SSH_ASKPASS: askpassFile(), SSH_ASKPASS_REQUIRE: 'force', SERVERMONITOR_ASKPASS: c.password, DISPLAY: env.DISPLAY || ':0' }); + } + if (c.keyFile) args.push('-i', c.keyFile.startsWith('~/') ? os.homedir() + c.keyFile.slice(1) : c.keyFile); + if (c.port !== 22) args.push('-p', String(c.port)); + args.push('-T', (c.user && c.user + '@') + c.host, argv.join(' ')); + } + const p = spawn(cmd, args, { env, windowsHide: true, detached: plat.detached }); + this.procs.add(p), reap('+', p.pid); + p.on('exit', () => (this.procs.delete(p), reap('-', p.pid), setTimeout(() => (p.stdout.destroy(), p.stderr.destroy()), 300))); // a grandchild may keep the pipes open + p.stdin.on('error', () => {}); // the process may end before it reads its input + p.stdin.end(input); + for (const s of [p.stdout, p.stderr]) s.setEncoding('utf8'); + return p; + } + + start(onFrame, onLost) { + const p = this.spawn(plat.shell(this.c.interval), plat.collector(this.c.interval)); + let buf = '', err = ''; + const lost = why => this.closed || onLost(why); + p.stdout.on('data', d => { + buf += d; + for (let end; !this.closed && (end = buf.indexOf('@@SNAP_END')) >= 0; buf = buf.slice(end + 10)) { + const begin = buf.lastIndexOf('@@SNAP_BEGIN', end); + if (begin >= 0) onFrame(buf.slice(begin, end)); + } + if (buf.length > 8 << 20) buf = ''; + }); + p.stderr.on('data', d => err = (err + d).slice(-4096)); + p.on('error', e => lost(`cannot start ${p.spawnfile}: ${e.message}`)); + p.on('close', code => lost(err.split('\n').filter(l => l.trim()).pop()?.trim() || `connection closed (exit code ${code})`)); + } + + exec(input, timeoutMs) { // -> { code, out }; code -1 = could not run, killed or timed out + return new Promise(resolve => { + const p = this.spawn(plat.shell(), input), stop = () => (killed = true, p.stdout.destroy(), p.stderr.destroy(), plat.kill(p)), timer = setTimeout(stop, timeoutMs); + let out = '', killed = false; + const done = r => (clearTimeout(timer), resolve(r)); + for (const s of [p.stdout, p.stderr]) s.on('data', d => (out += d).length > 4 << 20 && stop()); // endless output must not fill the memory + p.on('error', e => done({ code: -1, out: e.message })); + p.on('close', (code, signal) => done(this.closed ? { code: -1, out: this.closed } : killed || signal ? { code: -1, out: out + '\n[killed or timed out]' } : { code, out })); + }); + } + + close(why) { + this.closed = why, links.delete(this); + for (const p of this.procs) plat.kill(p); + } +} + +// two frames prove that data and rates work +function testConnection(cfg) { + return new Promise(resolve => { + const link = new Link({ ...cfg, interval: 1 }), engine = {}, t0 = Date.now(); + let frames = 0; + const finish = (ok, text) => (clearTimeout(timer), link.close('done'), resolve({ ok, text })); + const timer = setTimeout(() => finish(false, '✗ Timed out after 20 s'), 20000); + link.start(raw => { + const m = plat.parse(raw, engine, Date.now()); + if (++frames === 2) finish(true, `✓ Connected in ${Date.now() - t0} ms — ${m.hostname} · ${m.os} · ${m.cpuCount} cores · ${Fmt.bytes(m.memTotal)} RAM · CPU ${Fmt.pct(m.cpuUsage, 0)}`); + }, why => finish(false, '✗ ' + why)); + }); +} + +// ---- session ---- +// one row of the live charts (the last hour is kept in memory); the page reads v[] by position +const r2 = x => Math.round(x * 100) / 100; +const liveRow = m => ({ + t: m.timestamp, + v: [m.cpuUsage, m.cpuUser, m.cpuSystem + m.cpuIrq, m.cpuIowait, m.cpuSteal, m.memPct, m.memTotal > 0 ? (m.cached + m.buffers) * 100 / m.memTotal : 0, + m.swapPct, m.netRxBps, m.netTxBps, m.diskReadBps, m.diskWriteBps, m.load1].map(r2), + net: Object.fromEntries(m.nets.map(n => [n.name, [Math.round(n.rxBps), Math.round(n.txBps)]])), +}); + +class Session extends EventEmitter { // events: updated, sample(row), analysis, alert(event) + constructor(cfg, dir) { + super(); + Object.assign(this, { cfg, status: 'Disabled', err: '', m: blank(0), live: [], retries: 0, paused: false, offlineAlerted: false, an: blankAnalysis(), + store: new HistoryStore(path.join(dir, 'history', cfg.id)), reported: new Set(), dry: new Set(), cooldown: {}, rules: {}, procs: new Map(), svcs: new Map() }); + this.timers = [setInterval(() => this.analyzeNow(), 60000), setTimeout(() => this.analyzeNow(), 3000)]; + this.tick(); + } + destroy() { this.stop(), [...this.timers, this.offlineTick].forEach(clearTimeout), this.removeAllListeners(); } + tick() { // downtime -> availability: one sample per interval, like uptime + clearInterval(this.offlineTick); + this.offlineTick = setInterval(() => (this.status === 'Offline' || (this.status === 'Connecting' && this.retries)) && this.record(false), this.cfg.interval * 1000); + } + + get online() { return this.status === 'Online' && this.m.valid; } + setPaused(p) { this.paused = p, this.emit('updated'); } + reconnect() { this.retries = 0, this.paused = false, this.start(); } + + setConfig(c) { + const old = this.cfg, reconnect = ['transport', 'host', 'port', 'user', 'keyFile', 'password', 'interval', 'enabled'].some(k => c[k] !== old[k]); + this.cfg = c, this.tick(); + if (reconnect) this.live = [], this.m = blank(0), this.procs.clear(), this.svcs.clear(), c.enabled ? this.start() : this.stop(); // may be another machine now + this.emit('updated'); + } + + drop(why) { clearTimeout(this.retry), clearTimeout(this.watchdog), this.link?.close(why), this.link = null; } + watch(sec) { clearTimeout(this.watchdog), this.watchdog = setTimeout(() => this.onLost('no data received (timeout)'), sec * 1000); } + + start() { + this.drop('connection restarted'); + if (!this.cfg.enabled) return this.setStatus('Disabled'); + this.engine = {}, this.m.valid = false, this.link = new Link(this.cfg); // online only again with a fresh sample + this.setStatus('Connecting'), this.watch(25); + this.link.start(raw => this.onFrame(raw), why => this.onLost(why)); + } + + stop() { this.drop('connection stopped'), this.setStatus(this.cfg.enabled ? 'Offline' : 'Disabled'); } + + setStatus(s, err = '') { + if (err || s === 'Online') this.err = err; + if (s !== this.status) this.status = s, this.emit('updated'); + } + + onFrame(raw) { + const now = Date.now(), m = plat.parse(raw, this.engine, now); + this.watch(Math.max(15, this.cfg.interval * 5 + 10)); + if (m.uptime <= 0) return; + if (this.status !== 'Online') { + this.retries = 0; + if (this.offlineAlerted) this.offlineAlerted = false, this.raise('resolved', 'Server is back online'); + this.setStatus('Online'); + } + if (!m.valid || this.paused) return; // the first sample has no rates yet + if (m.uptime < this.m.uptime) this.procs.clear(); // rebooted: PIDs start again, old trends would be blamed on new processes + const first = !this.m.valid; // first sample of this connection: analyze at once, the last analysis saw "unreachable" + this.m = m, this.live.push(liveRow(m)); + if (this.live.length > 1800) this.live.shift(); + this.record(true), this.track(now), this.evaluateRules(); + if (first) this.analyzeNow(); + this.emit('sample', this.live.at(-1)); + } + + onLost(why) { + const was = this.status === 'Online'; + this.drop('connection lost: ' + why), this.setStatus('Offline', why); + if ((was || this.retries === 1) && !this.offlineAlerted) this.raise('critical', 'Server is unreachable: ' + why), this.offlineAlerted = true; + if (this.cfg.enabled) this.retry = setTimeout(() => this.start(), [3, 5, 10, 20, 30, 60][Math.min(this.retries++, 5)] * 1000); // back-off + } + + // privileged + "useSudo" wraps the command in sudo -n + exec(cmd, privileged, timeoutMs = 60000) { + if (!this.link || this.status !== 'Online') return Promise.resolve({ code: -1, out: 'server is not connected' }); + return this.link.exec(plat.wrap(cmd, privileged && this.cfg.useSudo), timeoutMs); + } + + activeAlerts() { + return [...(this.status === 'Offline' ? ['Unreachable: ' + this.err] : []), ...this.cfg.rules.filter(r => this.rules[r.id]?.active).map(conditionText)]; + } + + raise(severity, message) { this.emit('alert', { time: Date.now(), serverName: this.cfg.name, severity, message }); } // info|warning|critical|resolved|action + + record(up) { + const m = this.m, or = (has, x) => has ? x : NaN; // in the order of the history record + this.store.add(nowSec(), [m.cpuUsage, m.cpuIowait, m.load1, m.memPct, or(m.swapTotal > 0, m.swapPct), or(m.mounts.length, m.maxDiskPct), m.maxDiskUtil, m.netRxBps, + m.netTxBps, m.diskReadBps, m.diskWriteBps, or(m.temps.length, m.maxTemp), m.procs.length, or(m.gpus.length, model.gpuMax(m, 'util')), m.servicesFailed], up); + } + + // per-process CPU streaks + RSS per minute; service failure transitions + track(now) { + const procs = new Map(); + for (const p of this.m.procs) { + let t = this.procs.get(p.pid); + if (t?.name !== p.name) t = { name: p.name, highSince: 0, lastMinute: 0, rss: [] }; // new or pid reused + t.kernel = plat.isProtected(p); + t.highSince = p.cpu < this.cfg.autopilot.runawayCpu ? 0 : t.highSince || now; + if (now - t.lastMinute >= 60000) t.lastMinute = now, t.rss.push(p.rss); + if (t.rss.length > 60) t.rss.shift(); + procs.set(p.pid, t); + } + this.procs = procs; + const svcs = new Map(); + for (const s of this.m.services) { + const failed = s.active === 'failed'; + let t = this.svcs.get(s.unit); + if (!t) t = { last: '', preexisting: failed, fails: [], restarts: [] }; // failed before monitoring started: leave it alone + else if (failed && t.last !== 'failed') t.fails.push(now), t.preexisting = false; + else if (!failed) t.preexisting = false; + t.last = s.active, svcs.set(s.unit, t); + for (const v of [t.fails, t.restarts]) while (now - v[0] > 3600000) v.shift(); + } + if (svcs.size) this.svcs = svcs; // forgets removed services; a sample without a service list changes nothing + } + + evaluateRules() { + const now = Date.now(), m = this.m, vals = model.metricValues(m); + for (const r of this.cfg.rules) { + const st = this.rules[r.id] ??= {}, v = vals[r.metric] ?? 0, now1 = Fmt.fix(v, 1), unit = def(ruleMetrics, r.metric)[2]; + const off = !r.enabled || (r.metric.startsWith('gpu') && !m.gpus.length) || (r.metric === 'temp' && !m.temps.length); + if (off || (r.op === '<' ? v >= r.value : v <= r.value)) { + if (!off && st.active) this.raise('resolved', `Recovered: ${conditionText(r)} (now ${now1})`); + this.rules[r.id] = {}; + continue; + } + st.since ||= now; + if (now - st.since < r.duration * 1000) continue; + if (st.active && (r.action === 'notify' || now - st.lastFire < r.cooldown * 1000)) continue; + if (!st.active) this.raise(r.severity, `${conditionText(r)} (now ${now1}${unit && ' ' + unit})`); + st.active = true, st.lastFire = now; + if (r.action === 'notify') continue; + let action = r.action, arg = r.arg; + if (action.startsWith('kill_top')) { // heaviest user process, never a protected one + const k = action === 'kill_top_mem' ? 'rss' : 'cpu', best = m.procs.filter(p => !plat.isProtected(p)).reduce((a, p) => !a || p[k] > a[k] ? p : a, null); + if (!best) continue; + action = 'kill_pid', arg = String(best.pid); + } + this.run(action, arg, `Automation "${conditionText(r)}": ${actionText(plat.ui.ruleActions, r)}`); + } + } + + async run(action, arg, what) { + const cmd = action === 'command' ? arg : action === 'disk_cleanup' ? this.cfg.autopilot.diskCleanupCommand : plat.command(action, arg); + if (!cmd) return { code: -1, out: 'nothing to do' }; + const r = await this.exec(cmd, true, 300000), tail = r.out.trim().replace(/\s+/g, ' ').slice(-300); // one line: events are lines in alerts.log + this.raise('action', `${what} -> ${r.code ? `failed (${r.code})` : 'OK'}${tail && ' | ' + tail}`); + return r; + } + + runFinding(f, automatic) { + if (automatic && f.action === 'restart_service') this.svcs.get(f.actionArg)?.restarts.push(Date.now()); + return this.run(f.action, f.action === 'disk_cleanup' ? '' : f.actionArg, `${automatic ? 'Autopilot' : 'Manual fix'}: ${f.actionLabel} (${f.title})`); + } + + analyzeNow() { + const now = Date.now(), ap = this.cfg.autopilot, procs = [], svcs = []; + for (const p of this.m.procs) { + const t = this.procs.get(p.pid) || { rss: [] }, n = t.rss.length, growth = n >= 2 ? t.rss[n - 1] - t.rss[0] : 0; + const highCpuMinutes = t.highSince ? (now - t.highSince) / 60000 : 0; + if (highCpuMinutes > 0 || n >= 30) + procs.push({ pid: p.pid, minutesTracked: n, name: p.name, user: p.user, cpuNow: p.cpu, highCpuMinutes, rssNow: p.rss, kernel: t.kernel, rssGrowth: growth, + rssGrowthPct: t.rss[0] > 0 ? growth * 100 / t.rss[0] : 0, rssMonotonic: n >= 2 ? t.rss.filter((x, i) => i && x > t.rss[i - 1]).length / (n - 1) : 0 }); + } + for (const [unit, t] of this.svcs) + if (t.last === 'failed' || t.fails.length) + svcs.push({ unit, failedNow: t.last === 'failed', preexisting: t.preexisting, failsLastHour: t.fails.length, autoRestartsLastHour: t.restarts.length }); + this.an = analyze(this.store, this.m, ap, procs, svcs, this.online); + + for (const f of this.an.findings) // announce each new finding once + if (!this.reported.has(f.key) && f.category !== 'Availability') this.raise(f.severity, `Insight: ${f.title} - ${f.detail}`); + this.reported = new Set(this.an.findings.map(f => f.key)); + + const dry = new Set(); // act on eligible findings, with cooldowns; a dry run says once what it would do + for (const f of ap.enabled && this.online ? this.an.findings.filter(f => f.autoEligible) : []) { + const cd = f.action === 'disk_cleanup' ? 6 * 3600000 : f.action === 'restart_service' ? 120000 : 900000; + if (ap.dryRun) dry.add(f.key), this.dry.has(f.key) || this.raise('action', `Autopilot (dry run) would: ${f.actionLabel} - ${f.title}`); + else if (now - (this.cooldown[f.key] || 0) >= cd) this.cooldown[f.key] = now, this.runFinding(f, true); + } + this.dry = dry, this.emit('analysis'); + } + + deleteHistory() { this.store.removeFiles(), this.an = blankAnalysis(), this.emit('analysis'); } +} + +// ---- manager ---- +class Manager extends EventEmitter { // events: updated(session), sample(session, row), analysis(session), alert(event) + constructor() { + super(); + this.dir = plat.configDir(), this.sessions = [], this.alerts = []; + fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 }); // alerts.log holds command output + } + session(id) { return this.sessions.find(s => s.cfg.id === id); } + + attach(cfg) { + const s = new Session(cfg, this.dir); + for (const ev of ['updated', 'sample', 'analysis']) s.on(ev, x => this.emit(ev, s, x)); + s.on('alert', e => { + const log = path.join(this.dir, 'alerts.log'); + this.alerts.unshift(e), this.alerts.length = Math.min(this.alerts.length, 2000); + try { // starts over at 5 MB + fs.appendFileSync(log, `${Fmt.iso(e.time)}\t${e.severity}\t${e.serverName}\t${e.message}\n`, { flag: fs.statSync(log, { throwIfNoEntry: false })?.size > 5 << 20 ? 'w' : 'a' }); + } catch { /* disk full or not writable: the event still reaches the page */ } + this.emit('alert', e); + }); + this.sessions.push(s); + return s; + } + + load() { + const file = path.join(this.dir, 'servers.json'); + if (fs.existsSync(file)) { + let servers = []; + try { servers = JSON.parse(fs.readFileSync(file, 'utf8')).servers; } catch { fs.copyFileSync(file, file + '.bad'); } // not JSON: start empty; the next save replaces the file, so keep a copy + for (const o of Array.isArray(servers) ? servers : []) if (o && typeof o === 'object') this.attach(model.fromJson(o)); + } else { // first start: monitor this machine + this.attach(model.make({ name: 'This computer', group: 'Local', transport: 0 }, '')); + this.save(); + } + for (const s of this.sessions) s.start(); + } + + save() { + const file = path.join(this.dir, 'servers.json'); + fs.writeFileSync(file + '.tmp', JSON.stringify({ version: 1, servers: this.sessions.map(s => model.toJson(s.cfg)) }, null, 4), { mode: 0o600 }); + fs.renameSync(file + '.tmp', file); + } + + add(cfg) { this.attach(cfg).start(), this.save(); } + update(cfg) { this.session(cfg.id).setConfig(cfg), this.save(); } + remove(id, deleteHistory) { + const s = this.session(id); + this.sessions.splice(this.sessions.indexOf(s), 1), s.destroy(); + if (deleteHistory) fs.rmSync(s.store.dir, { recursive: true, force: true }); + this.save(); + } + move(id, d) { + const v = this.sessions, i = v.indexOf(this.session(id)), j = Math.min(v.length - 1, Math.max(0, i + d)); + if (i >= 0 && i !== j) v.splice(j, 0, v.splice(i, 1)[0]), this.save(); + } + close() { // ends every child process, also those of connection tests + for (const s of this.sessions) s.destroy(); + for (const l of links) l.close('monitor stopped'); + } +} + +module.exports = { Manager, testConnection }; diff --git a/Server Monitor(web-linux)/public/app.js b/Server Monitor(web-linux)/public/app.js new file mode 100644 index 0000000000000000000000000000000000000000..4d8b2416b0c3caa30ff999af63370e211b2816d3 --- /dev/null +++ b/Server Monitor(web-linux)/public/app.js @@ -0,0 +1,854 @@ +// Server Monitor page: sidebar, dashboard, server tabs and events. Plain DOM + canvas, no libraries. +// Data arrives over Server-Sent Events, actions go to the JSON API; server data only ever enters the page as text. +'use strict'; +const { Fmt, hNames, fmtMetric, ruleMetrics, def, conditionText, actionText } = SM; + +// ---- small helpers ---- +const css = getComputedStyle(document.documentElement), FONT = css.fontFamily; // the palette lives in style.css +const C = Object.fromEntries(['panel', 'card', 'border', 'grid', 'text', 'muted', 'faint', 'accent', 'green', 'amber', 'red', 'violet', 'pink', 'teal', 'orange', 'blue'] + .map(k => [k, css.getPropertyValue('--' + k).trim()])); +const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v)), ok = v => v != null && !isNaN(v); +const rgb = hex => [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16)); +const tint = (hex, alpha) => `rgba(${rgb(hex)},${alpha / 255})`; +const mix = (a, b, t) => `rgb(${rgb(a).map((x, i) => Math.round(x + (rgb(b)[i] - x) * clamp(t, 0, 1)))})`; +const level = (pct, warn = 70, crit = 90) => pct >= crit ? C.red : pct >= warn ? C.amber : C.green; +const sevColor = s => ({ critical: C.red, warning: C.amber, resolved: C.green, action: C.violet })[s] || C.accent; +const healthColor = v => v >= 90 ? C.green : v >= 75 ? C.teal : v >= 60 ? C.amber : v >= 40 ? C.orange : C.red; +const statusColor = s => ({ Online: C.green, Connecting: C.amber, Offline: C.red })[s.status] || C.faint; +const pctFmt = v => Fmt.fix(v) + '%', numFmt = prec => v => Fmt.fix(v, prec); +const pad = n => String(n).padStart(2, '0'); +function tf(ms, format) { // date formatting with Qt-style patterns + const d = new Date(ms), part = { yyyy: d.getFullYear(), MMM: d.toLocaleString('en', { month: 'short' }), MM: pad(d.getMonth() + 1), ddd: d.toLocaleString('en', { weekday: 'short' }), + dd: pad(d.getDate()), HH: pad(d.getHours()), mm: pad(d.getMinutes()), ss: pad(d.getSeconds()) }; + return format.replace(/yyyy|MMM|MM|ddd|dd|HH|mm|ss/g, k => part[k]); +} + +// h('tag.class.class', { property | onevent | style: {} }, ...children): children are elements or text +function h(tag, props, ...kids) { + const [name, ...cls] = tag.split('.'), el = document.createElement(name); + el.className = cls.join(' '); + for (const [k, v] of Object.entries(props || {})) { + if (k === 'style') for (const [p, x] of Object.entries(v)) el.style.setProperty(p, x ?? ''); + else if (k.startsWith('on')) el.addEventListener(k.slice(2), v); + else el[k] = v; + } + el.append(...kids.flat(2).filter(k => k != null && k !== false && k !== '')); + return el; +} + +async function api(path, body) { // GET without a body, POST with one + const r = await fetch('/api/' + path, body && { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-SM': '1' }, body: JSON.stringify(body) }); + const j = await r.json(); + if (!r.ok) throw new Error(j.error); + return j; +} +addEventListener('unhandledrejection', e => { // a failed request that nobody handled: show it briefly + const note = document.body.appendChild(h('div.toast', null, String(e.reason?.message || e.reason))); + setTimeout(() => note.remove(), 6000); +}); + +// ---- hand-drawn widgets ---- +const font = (ctx, px, bold) => ctx.font = `${bold ? 700 : 400} ${px}px ${FONT}`; +function text(ctx, s, x, y, px, color, align = 'left', bold = false, maxW = 0) { // vertically centred on y; maxW elides + font(ctx, px, bold), ctx.fillStyle = color, ctx.textAlign = align, ctx.textBaseline = 'middle'; + let out = String(s); + for (let n = out.length; maxW && n > 1 && ctx.measureText(out).width > maxW;) out = String(s).slice(0, --n) + '…'; + ctx.fillText(out, x, y); + return ctx.measureText(out).width; +} +function box(ctx, x, y, w, hh, r, fill, stroke) { + ctx.beginPath(), ctx.roundRect(x, y, w, hh, r), ctx.fillStyle = fill, ctx.fill(); + if (stroke) ctx.strokeStyle = stroke, ctx.lineWidth = 1, ctx.setLineDash([]), ctx.stroke(); +} +function line(ctx, pts, color, width, dash = []) { + ctx.beginPath(), pts.forEach(p => ctx.lineTo(p[0], p[1])); + ctx.strokeStyle = color, ctx.lineWidth = width, ctx.lineCap = ctx.lineJoin = 'round', ctx.setLineDash(dash), ctx.stroke(); +} +function ring(ctx, x, y, s, pct, color, thick, glow = true) { // 270° arc in the square (x, y, s) + const arc = (angle, c, w) => { ctx.beginPath(), ctx.arc(x + s / 2, y + s / 2, (s - thick) / 2, Math.PI * .75, Math.PI * .75 + angle), ctx.strokeStyle = c, ctx.lineWidth = w, ctx.lineCap = 'round', ctx.setLineDash([]), ctx.stroke(); }; + const a = Math.PI * 1.5 * clamp(pct, 0, 100) / 100; + arc(Math.PI * 1.5, C.grid, thick); + if (a > .003) glow && arc(a, tint(color, 45), thick * 2), arc(a, color, thick); +} + +// a canvas that fills its box and repaints when resized; draw(ctx, width, height) works in CSS pixels +function canvas(cls, draw) { + const cv = h('canvas'), el = h('div.cv.' + cls, null, cv), ctx = cv.getContext('2d'); + el.redraw = () => { + const w = el.clientWidth, hh = el.clientHeight, r = devicePixelRatio || 1; + if (!w || !hh) return; + if (cv.width !== Math.round(w * r) || cv.height !== Math.round(hh * r)) cv.width = Math.round(w * r), cv.height = Math.round(hh * r); + ctx.setTransform(r, 0, 0, r, 0, 0), ctx.clearRect(0, 0, w, hh), draw(ctx, w, hh); + }; + new ResizeObserver(el.redraw).observe(el); + return el; +} + +function gauge(title, warn = 70, crit = 90) { // ring gauge; set(percent, centre text, text below, colour) + let target = 0, shown = 0, from = 0, t0 = 0, center = '', sub = '', color; + const el = canvas('gauge', (ctx, w, hh) => { + const s = Math.min(w - 8, hh - 28), x = (w - s) / 2; + ring(ctx, x, 4, s, shown, color || level(target, warn, crit), Math.max(7, s * .085)); + text(ctx, center || Fmt.fix(shown) + '%', w / 2, 4 + s * .43, s * .2, C.text, 'center', true); + text(ctx, sub, w / 2, 4 + s * .63, Math.max(10, s * .075), C.muted, 'center', false, s * .76); + text(ctx, title, w / 2, 4 + s * .94 + 9, 13, C.text, 'center', true); + }); + const step = now => { // 450 ms ease-out + const k = Math.min(1, (now - t0) / 450); + shown = from + (target - from) * (1 - (1 - k) ** 3), el.redraw(); + if (k < 1) requestAnimationFrame(step); + }; + el.set = (pct, c = '', s = '', col) => { + center = c, sub = s, color = col, pct ||= 0; + if (Math.abs(pct - target) > .05) from = shown, target = pct, t0 = performance.now(), requestAnimationFrame(step); + else el.redraw(); + }; + return el; +} + +const ser = (name, color, v, fill = true, dashed = false) => ({ name, color, v, fill, dashed }); +function niceCeil(v) { + if (v <= 0) return 1; + const e = 10 ** Math.floor(Math.log10(v)), f = v / e; + return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * e; +} +// time chart: grid, legend with latest values, hover value, stacked areas, gaps where a value is missing +function chart(title, fmt = pctFmt, yFixed = 0, stacked = false, empty = 'Waiting for data…') { // yFixed 0 = auto scale + let T = [], S = [], span = 0, hover = -1; + const el = canvas('chart.panel', (ctx, w, hh) => { + const titleW = text(ctx, el.head, 16, 20, 13, C.text, 'left', true), plot = { l: 56, t: 40, r: w - 16, b: hh - 30 }, n = T.length; + text(ctx, el.sub, 24 + titleW, 20, 11, C.muted); + let lx = w - 16, first = 0; // legend, right-aligned + for (const s of [...S].reverse()) { + const last = s.v.slice(-5).findLast(ok), label = s.name + (ok(last) ? ' ' + fmt(last) : ''); + if ((lx -= ctx.measureText(label).width) < 40 + titleW) break; + text(ctx, label, lx, 20, 11, C.muted), box(ctx, lx -= 14, 16, 9, 9, 2, s.color), lx -= 14; + } + if (span) while (first < n && T[first] < T[n - 1] - span) ++first; + if (n - first < 2 || plot.b - plot.t < 20) return text(ctx, empty, (plot.l + plot.r) / 2, (plot.t + plot.b) / 2, 13, C.faint, 'center'); + + let yMax = yFixed; + if (yMax <= 0) { + for (let i = first; i < n; ++i) yMax = Math.max(yMax, S.reduce((sum, s) => !ok(s.v[i]) ? sum : stacked ? sum + s.v[i] : Math.max(sum, s.v[i]), 0)); + yMax = niceCeil(yMax * 1.12); + } + font(ctx, 10), plot.l = Math.max(40, ...[0, 1, 2, 3, 4].map(g => ctx.measureText(fmt(yMax * g / 4)).width + 18)); + const pw = plot.r - plot.l, ph = plot.b - plot.t, t1 = T[n - 1], t0 = span ? t1 - span : T[first], tr = Math.max(1, t1 - t0); + const X = t => plot.l + (t - t0) / tr * pw, Y = v => plot.b - clamp(v, 0, yMax) / yMax * ph; + const stamp = tr <= 72e5 ? 'HH:mm' : tr <= 2.6e8 ? 'ddd HH:mm' : tr <= 3.5e10 ? 'dd MMM' : 'MMM yyyy'; + for (let g = 0; g <= 4; ++g) { // grid, y labels, time labels + const y = Y(yMax * g / 4), t = t0 + tr * g / 4; + line(ctx, [[plot.l, y], [plot.r, y]], C.grid, 1, g ? [4, 3] : []); + text(ctx, fmt(yMax * g / 4), plot.l - 8, y, 10, C.faint, 'right'); + text(ctx, tf(t, stamp), X(t), plot.b + 14, 10, C.faint, ['left', 'center', 'center', 'center', 'right'][g]); + } + const step = Math.max(1, Math.floor((n - first) / Math.max(50, pw * 1.5))), base = new Array(n).fill(0); // ~1.5 points per pixel + ctx.save(), ctx.beginPath(), ctx.rect(plot.l - 2, plot.t - 4, pw + 4, ph + 6), ctx.clip(); + for (const s of S) { + const runs = [[]]; // [x, top, bottom] points, split at gaps + for (let i = first; i < n; i += step) { + let sum = 0, bs = 0, c = 0; + for (let k = i; k < Math.min(n, i + step); ++k) if (ok(s.v[k])) sum += s.v[k], bs += base[k], ++c; + if (c) runs.at(-1).push([X(T[Math.min(n - 1, i + (step >> 1))]), Y(sum / c + (stacked ? bs / c : 0)), Y(stacked ? bs / c : 0)]); + else if (runs.at(-1).length) runs.push([]); + } + if (stacked) for (let k = first; k < n; ++k) base[k] += ok(s.v[k]) ? s.v[k] : 0; + for (const r of runs.filter(r => r.length > 1)) { + if (s.fill) { + const g = ctx.createLinearGradient(0, plot.t, 0, plot.b); + g.addColorStop(0, tint(s.color, stacked ? 120 : 95)), g.addColorStop(1, tint(s.color, stacked ? 60 : 4)); + ctx.beginPath(), r.forEach(p => ctx.lineTo(p[0], p[1])), r.toReversed().forEach(p => ctx.lineTo(p[0], p[2])), ctx.fillStyle = g, ctx.fill(); + } + line(ctx, r, s.color, s.dashed ? 1.3 : 2, s.dashed ? [4, 3] : []); + } + } + ctx.restore(); + if (hover < plot.l || hover > plot.r) return; + const at = t0 + (hover - plot.l) / pw * tr, found = T.findIndex((t, i) => i >= first && t >= at), best = found < 0 ? n - 1 : found; // crosshair + tooltip + const x = X(T[best]), lines = [tf(T[best], tr > 864e5 ? 'ddd dd MMM HH:mm' : 'HH:mm:ss'), ...S.map(s => `${s.name}: ${ok(s.v[best]) ? fmt(s.v[best]) : '—'}`)]; + let stack = 0; + line(ctx, [[x, plot.t], [x, plot.b]], 'rgba(255,255,255,.27)', 1, [4, 3]); + for (const s of S.filter(s => ok(s.v[best]))) { + stack = stacked ? stack + s.v[best] : s.v[best]; + ctx.beginPath(), ctx.arc(x, Y(stack), 4, 0, 7), ctx.fillStyle = s.color, ctx.fill(), ctx.strokeStyle = C.panel, ctx.lineWidth = 2, ctx.setLineDash([]), ctx.stroke(); + } + font(ctx, 11); + const tw = Math.max(...lines.map(l => ctx.measureText(l).width)), tx = Math.min(x + 12, plot.r - tw - 20); + box(ctx, tx, plot.t + 4, tw + 18, lines.length * 16 + 10, 7, 'rgba(13,17,28,.92)', C.border); + lines.forEach((l, i) => text(ctx, l, tx + 9, plot.t + 17 + i * 16, 11, i ? C.text : C.muted)); + }); + el.head = title, el.sub = ''; + el.set = (t, s, sp = 0) => (T = t, S = s, span = sp, el.redraw()); // times in ms, series from ser(), span 0 = everything + el.addEventListener('mousemove', e => (hover = e.offsetX, el.redraw())); + el.addEventListener('mouseleave', () => (hover = -1, el.redraw())); + return el; +} + +// stat tiles with an accent stripe; set(index, value, text below, colour) +function tiles(defs, cols = defs.length) { + const els = defs.map(([title, color]) => h('div.tile', { style: { '--stripe': C[color] } }, h('div.section', null, title), h('b', null, '—'), h('small'))); + const el = h('div.tiles', { style: { 'grid-template-columns': `repeat(${cols}, 1fr)` } }, els); + el.set = (i, value, sub = '', color = '') => { const [, v, s] = els[i].children; v.textContent = value, v.style.color = color, s.textContent = sub; }; + return el; +} +function segbar() { // segment bar with a legend; set([[bytes, colour, label]], total) + const bar = h('div.seg'), legend = h('div.legend'), el = h('div', null, bar, legend); + el.set = (segs, total) => { + bar.replaceChildren(...segs.map(([v, color]) => h('i', { style: { width: Math.max(0, v) / (total > 0 ? total : 1) * 100 + '%', background: color } }))); + legend.replaceChildren(...segs.map(([v, color, label]) => h('span', null, h('i', { style: { background: color } }), `${label} ${Fmt.bytes(v)}`))); + }; + return el; +} +const panel = (title, ...content) => h('div.panel', null, title && h('div.section', null, title), content); +const kv = rows => h('table.kv', null, rows.map(([k, v]) => h('tr', null, h('td', null, k), h('td', null, String(v))))); + +// table(headers, { widths, sort: [column, descending], sortable, select, empty: [text, colour] }) -> element with fill(rows), render(), sel, +// selRow(), accept(row) and menu(). A cell is text or { t: text, c: colour, r: right-aligned, pct: bar 0–100, k: sort key, el: element }; +// a row's key is row.key or its first cell's text. +const cellText = c => String(c?.t ?? c ?? ''), rowKey = r => r.key ?? cellText(r[0]); +function setCell(td, c) { + const t = cellText(c); + td.className = c.r ? 'r' : '', td.style.color = c.c || ''; + if (c.el) return td.firstChild === c.el || td.replaceChildren(c.el); + if (c.pct == null) return td.textContent === t && !td.firstElementChild || (td.textContent = t); + if (!td.firstElementChild) td.replaceChildren(h('div.bar', null, h('i'), h('span'))); + const [fill, label] = td.firstElementChild.children, p = clamp(c.pct, 0, 100); + fill.style.width = p + '%', fill.style.background = tint(level(p), 200), label.textContent = t; +} +function table(headers, opt = {}) { + let rows = [], sort = opt.sort; + const body = h('tbody'), sortKey = r => r[sort[0]]?.k ?? cellText(r[sort[0]]); + const heads = headers.map((t, i) => h('th', { style: { width: opt.widths?.[i] && opt.widths[i] + 'px' }, onclick: () => opt.sortable && (sort = [i, sort?.[0] === i && !sort[1]], el.render()) }, t)); + const el = h('div.table', null, h('table', null, h('thead', null, h('tr', null, heads)), body)); + el.render = () => { + const list = sort ? rows.toSorted((a, b) => (sortKey(a) < sortKey(b) ? -1 : +(sortKey(a) > sortKey(b))) * (sort[1] ? -1 : 1)) : rows; + if (body.rows[0]?.cells.length !== headers.length) body.replaceChildren(); + if (!list.length && opt.empty) return body.replaceChildren(h('tr', null, h('td', { colSpan: headers.length, style: { color: opt.empty[1] } }, opt.empty[0]))); + while (body.rows.length > list.length) body.lastChild.remove(); + list.forEach((r, i) => { + const tr = body.rows[i] || body.appendChild(h('tr', null, headers.map(() => h('td')))); + tr.row = r, tr.hidden = !!el.accept && !el.accept(r), tr.classList.toggle('sel', !!opt.select && rowKey(r) === el.sel); + headers.forEach((_, j) => setCell(tr.cells[j], r[j] ?? '')); + }); + heads.forEach((th, i) => th.dataset.sort = sort?.[0] !== i ? '' : sort[1] ? ' ▾' : ' ▴'); + }; + el.fill = r => (rows = r, rows.some(x => rowKey(x) === el.sel) || (el.sel = undefined), el.render()); // the selection goes with its entry + el.selRow = () => rows.find(r => rowKey(r) === el.sel && (!el.accept || el.accept(r))); // a filtered-out row is not a selection + const pick = e => { // mousedown, so a refresh between press and release cannot lose the selection + const tr = e.target.closest('tr'); + if (tr?.row && opt.select && el.sel !== rowKey(tr.row)) el.sel = rowKey(tr.row), el.render(); + return tr?.row; + }; + body.addEventListener('mousedown', pick); + body.addEventListener('contextmenu', e => pick(e) && el.menu && menu(e, el.menu())); + return el; +} + +// context menu at the pointer; items are [label, action] or null for a separator +function menu(e, items) { + e.preventDefault(); + const m = document.body.appendChild(h('div.menu', null, items.map(it => it ? h('button', { onclick: it[1] }, it[0]) : h('hr')))); + m.style.left = Math.min(e.clientX, innerWidth - m.offsetWidth - 4) + 'px', m.style.top = Math.min(e.clientY, innerHeight - m.offsetHeight - 4) + 'px'; + for (const type of ['click', 'contextmenu']) addEventListener(type, () => m.remove(), { once: true, capture: true }); // the next one, not the event being handled +} + +// modal dialog; buttons are [label, class, action]: the dialog closes with the action's result unless that is undefined +function dialog(title, content, buttons, cls = '') { + return new Promise(resolve => { + const d = h('dialog' + cls, { onclose: () => (d.remove(), resolve(d.result)) }, h('h2', null, title), content, + h('div.row.end', null, buttons.map(([label, c, action]) => h('button' + c, { onclick: async () => (d.result = await action()) !== undefined && d.close() }, label)))); + document.body.append(d), d.showModal(); + }); +} +const ask = (title, question, danger) => dialog(title, h('p.pre', null, question), [['Yes', danger ? '.danger' : '.primary', () => true], ['No', '', () => false]]); + +// inputs bound to o[key]; `changed` runs after every edit +function fields(o, changed = () => {}) { + const bind = (el, k, get) => (el.addEventListener('change', () => (o[k] = get(el), changed())), el); + return { + text: (k, props) => bind(h('input', { value: o[k], ...props }), k, el => el.value), + num: (k, min, max, step = 1) => bind(h('input', { type: 'number', min, max, step, value: o[k] }), k, el => +(el.value = clamp(+el.value || 0, min, max))), + check: (k, label) => h('label.check', null, bind(h('input', { type: 'checkbox', checked: o[k] }), k, el => el.checked), label), + select: (k, options) => bind(h('select', null, options.map(([v, label]) => h('option', { value: v, selected: v === o[k] }, label))), k, el => typeof o[k] === 'number' ? +el.value : el.value), + }; +} +const form = rows => h('div.form', null, rows.map(([label, field]) => [h('div', null, label), h('div.row', null, field)])); // [label, field(s)] rows + +// keeps one child per server (matched by id) so elements survive updates; `tail` elements follow +function keyed(parent, make, tail = []) { + const old = new Map([...parent.children].map(el => [el.dataset.id, el])); + const els = S.servers.map(s => { + const el = old.get(s.cfg.id) || make(s.cfg.id); + el.dataset.id = s.cfg.id; + return el; + }); + if ([...els, ...tail].some((el, i) => parent.children[i] !== el) || parent.children.length !== els.length + tail.length) parent.replaceChildren(...els, ...tail); + els.forEach((el, i) => el.update(S.servers[i])); +} + +// ---- state ---- +// plat: platform tables from the server; id: server shown on the detail page; live, m, vals, an: its live rows, metrics, rule values, analysis +const S = { plat: null, dir: '', rule: null, defaultRules: [], servers: [], alerts: [], page: '', id: null, tab: '', span: 15, live: [], m: null, vals: {}, an: null, unseen: 0 }; +const cur = () => S.servers.find(s => s.cfg.id === S.id); +const go = (...parts) => location.hash = '#/' + parts.map(encodeURIComponent).join('/'); +const [, USER, SYS, IOWAIT, STEAL, MEM, CACHE, SWAP, RX, TX, RD, WR, LOAD] = Array(13).keys(); // positions in a live row (liveRow in core/session.js) +const col = k => S.live.map(r => r.v[k]), times = () => S.live.map(r => r.t), spanMs = () => S.span * 60000; +const cpuSeries = steal => [ser('User', C.accent, col(USER)), ser('System', C.violet, col(SYS)), + ...(S.plat.posixCpu ? [ser('I/O wait', C.amber, col(IOWAIT)), ...(steal ? [ser('Steal', C.red, col(STEAL))] : [])] : [])]; + +// ---- server actions ---- +const serverMenu = (id, first) => [first, ['Reconnect', () => api('server/reconnect', { id })], null]; +async function editServer(id) { // id undefined = add + const P = S.plat, s = S.servers.find(x => x.cfg.id === id), groups = [...new Set(S.servers.map(x => x.cfg.group).filter(Boolean))]; + if (id && !s) return; + const c = s ? { ...s.cfg, password: '' } : { name: '', group: '', transport: 1, host: '', port: 22, user: '', keyFile: '', password: '', interval: P.interval, useSudo: false, enabled: true, notes: '' }; + const f = fields(c, () => sync()), hint = h('div.muted'), result = h('span.grow'), name = f.text('name', { placeholder: 'e.g. web-01' }); + const ssh = [f.text('host', { placeholder: 'hostname or IP address', className: 'grow' }), f.num('port', 1, 65535), f.text('user', { placeholder: 'default: your local user name' }), + f.text('keyFile', { placeholder: P.keyHint }), f.text('password', { type: 'password', autocomplete: 'new-password', placeholder: s?.cfg.hasPassword ? 'stored — leave empty to keep it' : 'optional — keys are recommended' })]; + const group = f.text('group', { className: 'grow' }), show = (t, color) => void (result.textContent = t, result.style.color = color); + group.setAttribute('list', 'groups'); + const sync = () => { + ssh.forEach(el => el.disabled = !c.transport); + hint.textContent = c.transport ? P.sshHint : 'Monitors the computer this program runs on. No setup needed.'; + if (!c.transport && !c.name) c.name = name.value = 'This computer'; + }; + const test = h('button', { onclick: async () => { + test.disabled = true, show('Connecting…', C.amber); + const r = await api('server/test', c).catch(e => ({ text: '✗ ' + e.message })); + test.disabled = false, show(r.text, r.ok ? C.green : C.red); + } }, 'Test connection'); + sync(); + const saved = await dialog(s ? 'Edit server' : 'Add a server', h('div.col', null, form([['Name', name], ['Group', [group, h('datalist', { id: 'groups' }, groups.map(g => h('option', { value: g })))]], + ['Connect via', f.select('transport', [[0, 'This machine (local)'], [1, 'SSH — nothing to install on the server']])], ['Address', [ssh[0], 'port', ssh[1]]], ['User', ssh[2]], ['Private key', ssh[3]], + ['Password', [ssh[4], s?.cfg.hasPassword && f.check('clearPassword', 'remove stored')]], ['Sample every', [f.num('interval', 1, 300), 's']], + ...(P.sudo ? [['', f.check('useSudo', 'Run control commands with sudo -n (needs passwordless sudo)')]] : []), ['', f.check('enabled', 'Monitoring enabled')], ['Notes', f.text('notes', { className: 'grow' })]]), + hint, h('div.row', null, test, result)), [['Save', '.primary', () => api(s ? 'server/update' : 'server/add', c).catch(e => show(e.message, C.red))], ['Cancel', '', () => false]], '.wide'); + if (saved?.id) go('server', saved.id); + else if (saved && id === S.id) listen(); +} +async function removeServer(id) { + const s = S.servers.find(x => x.cfg.id === id); + const how = s && await dialog('Remove server', h('p', null, `Stop monitoring "${s.cfg.name}" and remove it from the list?`), + [['Remove + delete history', '.danger', () => ({ deleteHistory: true })], ['Remove, keep history files', '', () => ({})], ['Cancel', '', () => false]]); + if (!how) return; + if (id === S.id) go('dashboard'); + api('server/remove', { id, ...how }); +} + +// ---- sidebar ---- +const badge = h('span.badge', { hidden: true }), sideList = h('div.list.grow'); +const nav = { dashboard: h('button.nav', { onclick: () => go('dashboard') }, '▦ Dashboard'), events: h('button.nav', { onclick: () => go('events') }, '◉ Events & alerts', badge) }; +const sidebar = h('aside', null, h('div.brand', null, h('img', { src: 'icon.svg', alt: '' }), h('div', null, h('b', null, 'Server Monitor'), h('small', null, 'monitor · analyze · control'))), + nav.dashboard, nav.events, h('div.section', null, 'Servers'), sideList, + h('div.row', null, h('button.primary.grow', { onclick: () => editServer() }, '+ Add'), h('button.grow', { onclick: () => S.id && editServer(S.id) }, 'Edit'), h('button.danger.grow', { onclick: () => removeServer(S.id) }, 'Remove'))); +function sideItem(id) { // dot, name, alert count, mini CPU / memory bars + const dot = h('i.dot'), name = h('b.grow'), count = h('span.badge'), bars = ['CPU', 'MEM'].map(l => h('div.mini', null, h('small', null, l), h('div.track', null, h('i')))); + const el = h('div.item', { onclick: () => go('server', id), oncontextmenu: e => menu(e, [...serverMenu(id, ['Open', () => go('server', id)]), + ['Move up', () => api('server/move', { id, delta: -1 })], ['Move down', () => api('server/move', { id, delta: 1 })], null, ['Edit…', () => editServer(id)], ['Remove…', () => removeServer(id)]]) }, + h('div.row', null, dot, name, count), bars); + el.update = s => { + dot.style.background = statusColor(s), name.textContent = s.cfg.name, count.textContent = s.alerts.length, count.hidden = !s.alerts.length; + el.classList.toggle('sel', id === S.id); + [s.m.cpuUsage, s.m.memPct].forEach((v, i) => Object.assign(bars[i].lastChild.firstChild.style, { width: (s.online ? clamp(v, 0, 100) : 0) + '%', background: level(v) })); + }; + return el; +} + +// ---- dashboard ---- +function card(id) { // header, four ring gauges, CPU + memory sparkline (last 5 min), net rates, alert badge + let s; + const dot = h('i.dot'), name = h('b'), addr = h('small'), chip = h('span.chip'), foot = h('div.foot'); + const grade = canvas('grade', (ctx, w) => (ring(ctx, 0, 0, w, s.health, healthColor(s.health), 4, false), text(ctx, s.grade, w / 2, w / 2, 15, healthColor(s.health), 'center', true))); + const body = canvas('rings', (ctx, w, hh) => { + const m = s.m, on = s.online, temp = m.temps > 0, gw = w / 4, gs = Math.min(gw - 14, 70), top = hh - 44; + [[m.cpuUsage, 'CPU'], [m.memPct, 'Memory'], [m.maxDiskPct, 'Disk'], temp ? [m.maxTemp, 'Temp'] : [m.swapPct, 'Swap']].forEach(([v, label], i) => { + const cx = gw * i + gw / 2, hot = i === 3 && temp; + ring(ctx, cx - gs / 2, 2, gs, on ? Math.min(100, v) : 0, !on ? C.faint : hot ? level(v, 70, 85) : level(v), 6, on); + text(ctx, on ? Fmt.fix(v) + (hot ? '°' : '%') : '—', cx, 2 + gs / 2, 14, on ? C.text : C.faint, 'center', true); + text(ctx, label, cx, gs + 6, 11, C.muted, 'center'); + }); + box(ctx, 0, top, w, 44, 8, 'rgba(0,0,0,.16)'); + for (const [v, color] of [[s.spark[1], C.violet], [s.spark[0], C.accent]]) { + if (v.length < 2) continue; + const pts = v.map((y, i) => [w - 4 - (w - 8) * (v.length - 1 - i) / 149, hh - 4 - clamp(y, 0, 100) / 100 * 36]); + ctx.beginPath(), [...pts, [pts.at(-1)[0], hh - 2], [pts[0][0], hh - 2]].forEach(p => ctx.lineTo(...p)), ctx.fillStyle = tint(color, 40), ctx.fill(); + line(ctx, pts, color, 1.5); + } + text(ctx, 'CPU', 8, top + 10, 10, C.accent), text(ctx, 'MEM', 36, top + 10, 10, C.violet); + }); + const el = h('div.card', { onclick: () => go('server', id), oncontextmenu: e => menu(e, [...serverMenu(id, ['Open details', () => go('server', id)]), ['Edit…', () => editServer(id)], ['Remove…', () => removeServer(id)]]) }, + h('div.row', null, dot, h('div.grow', null, name, addr), grade, chip), body, foot); + el.update = x => { + s = x; + const m = s.m, ap = s.cfg.autopilot, n = s.alerts.length + s.findings.length, crit = s.alerts.length || s.findings.includes('critical'); + el.style.setProperty('--status', statusColor(s)), name.textContent = s.cfg.name, addr.textContent = s.address + (m.os && ' · ' + m.os); + grade.hidden = !s.online, chip.hidden = s.online, chip.textContent = s.status, grade.redraw(), body.redraw(); + foot.replaceChildren(...(!s.online ? [h('span', { style: { color: s.status === 'Offline' ? C.red : C.muted } }, s.status === 'Disabled' ? 'Monitoring disabled' : s.status === 'Offline' ? 'Unreachable: ' + s.err : 'Waiting for data…')] : [ + h('div.row', null, h('span', { style: { color: C.teal } }, '↓ ' + Fmt.rate(m.netRxBps)), h('span.grow', { style: { color: C.pink } }, '↑ ' + Fmt.rate(m.netTxBps)), + `load ${Fmt.fix(m.load1, 2)} · up ${Fmt.duration(m.uptime)}`), + h('div.row', null, h('span.grow', null, `${m.cpuCount} cores · ${m.procs} procs` + (ap.enabled ? ap.dryRun ? ' · autopilot (dry run)' : ' · autopilot on' : '')), + n > 0 && h('span.warn', { style: { color: crit ? C.red : C.amber, background: tint(crit ? C.red : C.amber, 45) } }, '⚠ ' + n))])); + }; + return el; +} +const dash = (() => { + const sub = h('div.muted'), search = h('input', { type: 'search', placeholder: 'Search servers…', oninput: () => el.update() }), cards = h('div.cards'), events = h('div.events'); + const t = tiles([['Servers online', 'green'], ['Avg health', 'teal'], ['Active problems', 'red'], ['Avg CPU', 'accent'], ['Avg memory', 'violet'], ['Total network', 'pink']]); + const add = h('div.card.add', { onclick: () => editServer() }, h('i', null, '+'), h('b', null, 'Add server'), h('small', null, 'This machine · SSH')); + const el = h('section', null, h('div.row', null, h('div.grow', null, h('h1', null, 'Dashboard'), sub), search, h('button.primary', { onclick: () => editServer() }, '+ Add server')), t, + h('div.row.stretch.fill', null, h('div.scroll.grow', null, cards), h('div.side', null, panel('Recent events', events)))); + el.update = () => { + const on = S.servers.filter(s => s.cfg.enabled), live = on.filter(s => s.online), n = live.length, sum = f => live.reduce((a, s) => a + f(s), 0); + const problems = on.reduce((a, s) => a + s.alerts.length + (s.online && s.findings.filter(f => f !== 'info').length), 0), health = Math.round(sum(s => s.health) / n); + keyed(cards, card, [add]); + S.servers.forEach((s, i) => cards.children[i].hidden = ![s.cfg.name, s.cfg.host, s.cfg.group, s.m.hostname].join(' ').toLowerCase().includes(search.value.toLowerCase())); + sub.textContent = `${S.servers.length} server(s) monitored · updated ${tf(Date.now(), 'HH:mm:ss')}`; + t.set(0, `${n} / ${on.length}`, on.length > n ? `${on.length - n} unreachable` : 'all reachable', n === on.length ? C.green : C.amber); + t.set(2, problems, problems ? 'alerts + insights' : 'all clear', problems ? C.red : C.green); + if (!n) return [1, 3, 4, 5].forEach(i => t.set(i, '—')); + t.set(1, health, 'score 0–100', healthColor(health)); + t.set(3, Fmt.pct(sum(s => s.m.cpuUsage) / n), '', level(sum(s => s.m.cpuUsage) / n)), t.set(4, Fmt.pct(sum(s => s.m.memPct) / n), '', level(sum(s => s.m.memPct) / n)); + t.set(5, Fmt.rate(sum(s => s.m.netRxBps + s.m.netTxBps)), `↓ ${Fmt.rate(sum(s => s.m.netRxBps))} ↑ ${Fmt.rate(sum(s => s.m.netTxBps))}`); + }; + el.events = () => events.replaceChildren(...S.alerts.slice(0, 200).map(e => h('div', { style: { color: sevColor(e.severity) } }, `${tf(e.time, 'HH:mm:ss')} · ${e.serverName}`, h('br'), e.message))); + return el; +})(); + +// ---- server tabs: each builder returns an element with refresh() (new sample) and optionally analysis() ---- +function overviewTab() { + const g = ['CPU', 'Memory', 'Fullest disk', 'Swap', 'Temperature', 'Health'].map((n, i) => gauge(n, 70, i === 4 ? 85 : 90)), info = h('div'); + const t = tiles([['Load average', 'accent'], ['Processes', 'violet'], ['TCP connections', 'teal'], ['Services', 'green'], ['Uptime', 'amber']]); + const cpu = chart('CPU', pctFmt, 100, true), mem = chart('Memory', pctFmt, 100), net = chart('Network', Fmt.rate), io = chart('Disk I/O', Fmt.rate); + const el = h('div.tab.scroll', null, h('div.panel.gauges', null, g), t, h('div.row.top', null, h('div.grid2.grow', null, cpu, mem, net, io), h('div.side', null, panel('System', info)))); + el.refresh = () => { + const m = S.m, a = S.an, s = cur(), T = times(), sp = spanMs(), tcp = k => m.tcp[k] || 0; + g[0].set(m.cpuUsage, '', m.cpuCount + ' cores'), g[1].set(m.memPct, '', `${Fmt.bytes(m.memUsed)} / ${Fmt.bytes(m.memTotal)}`), g[2].set(m.maxDiskPct, '', m.fullestMount); + g[3].set(m.swapPct, '', m.swapTotal > 0 ? `${Fmt.bytes(m.swapUsed)} / ${Fmt.bytes(m.swapTotal)}` : 'no swap'); + g[4].set(Math.min(100, m.maxTemp), m.temps.length ? Fmt.temp(m.maxTemp) : '—', m.temps.length ? m.temps.length + ' sensors' : 'no sensors'); + g[5].set(a.health, String(a.health), 'grade ' + a.grade, healthColor(a.health)); + t.set(0, Fmt.fix(m.load1, 2), `5m ${Fmt.fix(m.load5, 2)} · 15m ${Fmt.fix(m.load15, 2)}`, level(m.load1 * 100 / Math.max(1, m.cpuCount), 80, 150)); + t.set(1, m.procs.length, `${m.threadsTotal} threads · ${m.procsRunning} running`); + t.set(2, tcp('ESTABLISHED'), `${tcp('LISTEN')} listening · ${tcp('TIME_WAIT')} time-wait`); + t.set(3, m.servicesRunning, m.servicesFailed ? m.servicesFailed + ' failed' : 'running · none failed', m.servicesFailed ? C.red : ''); + t.set(4, Fmt.duration(m.uptime), m.loggedUsers + ' user(s) logged in'); + cpu.set(T, cpuSeries(false), sp), mem.set(T, [ser('Used', C.violet, col(MEM)), ser('Cache', C.blue, col(CACHE), false, true), ser('Swap', C.pink, col(SWAP), false)], sp); + net.set(T, [ser('Down', C.teal, col(RX)), ser('Up', C.pink, col(TX))], sp), io.set(T, [ser('Read', C.blue, col(RD)), ser('Write', C.orange, col(WR))], sp); + info.replaceChildren(kv([['Hostname', m.hostname], ['OS', m.os], ['Kernel', m.kernel + ' ' + m.arch], ['CPU', m.cpuModel], + ['Cores', m.cpuCount + (m.avgMhz > 0 ? ` @ ${Fmt.fix(m.avgMhz / 1000, 2)} GHz` : '')], ['Memory', Fmt.bytes(m.memTotal)], ['Swap', m.swapTotal > 0 ? Fmt.bytes(m.swapTotal) : 'none'], + ['Virtualisation', m.virt], ['Disks', m.mounts.length + ' mounted file systems'], ['Interfaces', m.nets.length], ['GPU', m.gpus[0]?.name || 'none'], + ['Connection', `${s.address} (${s.cfg.transport ? 'SSH' : 'Local'})`], ['Sample interval', s.cfg.interval + ' s']])); + }; + return el; +} + +function cpuTab() { + const P = S.plat, model = h('h2'), cores = h('div.cores'); + const t = tiles([['Usage', 'accent'], ['Load 1 / 5 / 15', 'violet'], ['Avg frequency', 'teal'], [P.posixCpu ? 'Steal / IRQ' : 'Interrupts + DPC', 'orange'], ['Context switches', 'blue'], + ['Interrupts', 'pink'], ['New processes', 'green'], ['Running / blocked', 'amber']], 4); + const usage = chart('CPU time breakdown', pctFmt, 100, true), load = chart('Load average (1 min)', numFmt(1)); + const temps = table(['Sensor', 'Temperature'], { widths: [300], empty: ['No temperature sensors exposed (common on VMs)', C.muted] }); + const gpus = table(['#', 'Name', 'Usage', 'Memory', 'Temp', 'Power', 'Fan'], { widths: [40, 220, 120, 160] }), gpuPanel = panel('GPUs', gpus); + const el = h('div.tab.scroll', null, model, t, h('div.row.top', null, h('div.grow3', null, usage), h('div.grow2', null, load)), panel('Per core', cores), + h('div.grid2', null, panel('Temperatures', temps), gpuPanel)); + el.refresh = () => { + const m = S.m, T = times(), f2 = v => Fmt.fix(v, 2); + model.textContent = m.cpuModel || 'Processor'; + t.set(0, Fmt.pct(m.cpuUsage), `user ${Fmt.pct(m.cpuUser)} · system ${Fmt.pct(m.cpuSystem)}` + (P.posixCpu ? ` · iowait ${Fmt.pct(m.cpuIowait)}` : ''), level(m.cpuUsage)); + t.set(1, `${f2(m.load1)} / ${f2(m.load5)} / ${f2(m.load15)}`, `${Math.round(m.load1 * 100 / Math.max(1, m.cpuCount))}% of ${m.cpuCount} cores`); + t.set(2, m.avgMhz > 0 ? f2(m.avgMhz / 1000) + ' GHz' : 'n/a'); + if (P.posixCpu) t.set(3, `${Fmt.pct(m.cpuSteal)} / ${Fmt.pct(m.cpuIrq)}`, 'steal > 5% = noisy neighbours', m.cpuSteal > 5 ? C.amber : ''); + else t.set(3, Fmt.pct(m.cpuIrq), 'hardware interrupts and deferred calls', m.cpuIrq > 15 ? C.amber : ''); + t.set(4, Fmt.count(m.ctxtPerSec) + '/s'), t.set(5, Fmt.count(m.intrPerSec) + '/s'), t.set(6, Fmt.fix(m.forksPerSec, 1) + '/s'); + t.set(7, `${m.procsRunning} / ${m.procsBlocked}`, P.posixCpu ? 'blocked = waiting for I/O' : 'blocked = waiting for a CPU', m.procsBlocked > m.cpuCount ? C.amber : ''); + usage.set(T, cpuSeries(true), spanMs()), load.set(T, [ser('Load', C.violet, col(LOAD)), ser('Cores', C.faint, T.map(() => m.cpuCount), false, true)], spanMs()); + cores.replaceChildren(...m.cores.map((c, i) => { + const color = level(c.usage, 60, 85); + return h('div', { style: { background: mix(C.card, color, c.usage / 420), 'border-color': mix(C.border, color, c.usage / 160) } }, + h('small', null, 'CPU ' + i, c.mhz > 0 && h('span', null, Fmt.fix(c.mhz / 1000, 1) + 'G')), h('b', null, pctFmt(c.usage)), h('div.track', null, h('i', { style: { width: c.usage + '%', background: color } }))); + })); + temps.fill(m.temps.map(x => [x.name, { t: Fmt.temp(x.celsius), pct: Math.min(100, x.celsius) }])); + gpuPanel.hidden = !m.gpus.length; + gpus.fill(m.gpus.map(x => [x.index, x.name, { t: Fmt.pct(x.util, 0), pct: x.util }, { t: `${Fmt.num(x.memUsed)} / ${Fmt.num(x.memTotal)} MiB`, pct: x.memTotal > 0 ? x.memUsed * 100 / x.memTotal : 0 }, + { t: Fmt.temp(x.temp), c: level(x.temp, 75, 88) }, Fmt.num(x.power) + ' W', Fmt.pct(x.fan, 0)])); + }; + return el; +} + +function memoryTab() { + const t = tiles([['Used', 'violet'], ['Available', 'green'], ['Cache + buffers', 'blue'], ['Swap used', 'pink']]), bar = segbar(), swap = segbar(), detail = h('div'); + const usage = chart('Memory usage', pctFmt, 100), top = table(['PID', 'Process', 'User', 'RSS', 'Memory %', 'Virtual'], { widths: [80, 220, 120, 110, 160] }); + const el = h('div.tab.scroll', null, t, panel('Composition', bar, h('div.section', null, 'Swap'), swap), h('div.row.top', null, h('div.grow', null, usage), h('div.side', null, panel('Details', detail))), + panel('Top memory consumers', top)); + el.refresh = () => { + const m = S.m, free = '#364463'; + t.set(0, Fmt.bytes(m.memUsed), `${Fmt.pct(m.memPct)} of ${Fmt.bytes(m.memTotal)}`, level(m.memPct)), t.set(1, Fmt.bytes(m.memAvailable), 'free ' + Fmt.bytes(m.memFree)); + t.set(2, Fmt.bytes(m.cached + m.buffers), 'reclaimable when needed'); + t.set(3, m.swapTotal > 0 ? Fmt.bytes(m.swapUsed) : 'no swap', m.swapTotal > 0 ? `${Fmt.pct(m.swapPct)} of ${Fmt.bytes(m.swapTotal)}` : '', level(m.swapPct, 40, 80)); + bar.set([[Math.max(0, m.memTotal - m.memFree - m.cached - m.buffers), C.violet, 'Applications'], [m.shared, C.pink, 'Shared'], [m.buffers, C.teal, 'Buffers'], + [Math.max(0, m.cached - m.shared), C.blue, 'Cache'], [m.memFree, free, 'Free']], m.memTotal); + swap.set([[m.swapUsed, C.pink, 'Used'], [m.swapTotal - m.swapUsed, free, 'Free']], m.swapTotal); + usage.set(times(), [ser('Used', C.violet, col(MEM)), ser('Cache', C.blue, col(CACHE), false, true), ser('Swap', C.pink, col(SWAP))], spanMs()); + detail.replaceChildren(kv([['Total', m.memTotal], ['Used', m.memUsed], ['Available', m.memAvailable], ['Free', m.memFree], ['Buffers', m.buffers], ['Cached', m.cached], ['Shared', m.shared], + ['Slab', m.slab], ['Dirty', m.dirty], ['Swap total', m.swapTotal], ['Swap used', m.swapUsed]].map(([k, v]) => [k, Fmt.bytes(v)]))); + top.fill(m.procs.toSorted((a, b) => b.rss - a.rss).slice(0, 15).map(p => [{ t: p.pid, c: C.muted }, p.name, { t: p.user, c: C.muted }, { t: Fmt.bytes(p.rss), r: 1 }, + { t: Fmt.pct(p.memPct), pct: Math.min(100, p.memPct * 2) }, { t: Fmt.bytes(p.vsz), c: C.muted, r: 1 }])); + }; + return el; +} + +function storageTab() { + const t = tiles([['Fullest file system', 'amber'], ['Read', 'blue'], ['Write', 'orange'], ['Busiest disk', 'red']]), io = chart('Disk throughput', Fmt.rate); + const mounts = table(['Mount point', 'Device', 'Type', 'Size', 'Used', 'Free', 'Usage'], { widths: [260, 140, 80, 110, 110, 110] }); + const disks = table(['Device', 'Read/s', 'Write/s', 'Read IOPS', 'Write IOPS', 'Busy', 'Total read', 'Total written'], { widths: [110, 110, 110, 100, 100, 150, 120] }); + const el = h('div.tab.scroll', null, t, panel('File systems', mounts), io, panel('Block devices', disks)); + el.refresh = () => { + const m = S.m, right = (t, c) => ({ t, c, r: 1 }); + t.set(0, Fmt.pct(m.maxDiskPct), m.fullestMount, level(m.maxDiskPct, 80, 90)), t.set(1, Fmt.rate(m.diskReadBps)), t.set(2, Fmt.rate(m.diskWriteBps)); + t.set(3, Fmt.pct(m.maxDiskUtil), m.busiestDisk, level(m.maxDiskUtil, 60, 90)); + io.set(times(), [ser('Read', C.blue, col(RD)), ser('Write', C.orange, col(WR))], spanMs()); + mounts.fill(m.mounts.map(x => [x.mount, { t: x.device, c: C.muted }, { t: x.type, c: C.muted }, right(Fmt.bytes(x.total)), right(Fmt.bytes(x.used)), right(Fmt.bytes(x.avail)), { t: Fmt.pct(x.pct), pct: x.pct }])); + disks.fill(m.disks.map(d => [d.name, right(Fmt.rate(d.readBps), C.blue), right(Fmt.rate(d.writeBps), C.orange), right(Fmt.fix(d.readIops)), right(Fmt.fix(d.writeIops)), + { t: Fmt.pct(d.util, 0), pct: d.util }, right(Fmt.bytes(d.totalRead), C.muted), right(Fmt.bytes(d.totalWritten), C.muted)])); + }; + return el; +} + +function networkTab() { + const t = tiles([['Download', 'teal'], ['Upload', 'pink'], ['Established', 'accent'], ['Listening', 'green'], ['Time-wait / close-wait', 'amber'], ['Sockets in use', 'violet']]); + const iface = h('select', { onchange: () => el.refresh() }), traffic = chart('Traffic', Fmt.rate); + const nets = table(['Interface', 'State', 'Speed', 'Down/s', 'Up/s', 'Pkts in/s', 'Pkts out/s', 'Received', 'Sent', 'Errors', 'Drops'], { widths: [160, 80, 90, 110, 110, 90, 90, 110, 110, 70] }); + const el = h('div.tab.scroll', null, t, h('div.row', null, h('span.muted', null, 'Interface'), iface), traffic, panel('Interfaces', nets)); + el.refresh = () => { + const m = S.m, tcp = k => m.tcp[k] || 0, names = ['All physical (total)', ...m.nets.map(n => n.name)], right = (t, c) => ({ t, c, r: 1 }); + t.set(0, Fmt.rate(m.netRxBps), 'physical interfaces'), t.set(1, Fmt.rate(m.netTxBps)), t.set(2, tcp('ESTABLISHED'), 'TCP'), t.set(3, tcp('LISTEN'), 'open TCP ports'); + t.set(4, `${tcp('TIME_WAIT')} / ${tcp('CLOSE_WAIT')}`, 'many close-wait = app not closing sockets', tcp('CLOSE_WAIT') > 100 ? C.amber : ''), t.set(5, m.socketsUsed); + if ([...iface.options].map(o => o.text).join('\n') !== names.join('\n')) { + const was = iface.value; + iface.replaceChildren(...names.map(n => h('option', null, n))), iface.selectedIndex = Math.max(0, names.indexOf(was)); + } + const all = iface.selectedIndex <= 0, own = k => S.live.map(r => r.net[iface.value]?.[k] ?? 0); + traffic.head = 'Traffic — ' + (all ? 'all physical interfaces' : iface.value); + traffic.set(times(), [ser('Down', C.teal, all ? col(RX) : own(0)), ser('Up', C.pink, all ? col(TX) : own(1))], spanMs()); + nets.fill(m.nets.map(x => { + const dim = x.virt ? C.muted : ''; + return [{ t: x.name + (x.virt ? ' (virtual)' : ''), c: dim }, { t: x.state, c: x.state === 'up' ? C.green : x.state === 'down' ? C.red : C.muted }, { t: x.speed > 0 ? x.speed + ' Mb/s' : '—', c: C.muted }, + right(Fmt.rate(x.rxBps), C.teal), right(Fmt.rate(x.txBps), C.pink), right(Fmt.fix(x.rxPps), dim), right(Fmt.fix(x.txPps), dim), right(Fmt.bytes(x.rxBytes), dim), right(Fmt.bytes(x.txBytes), dim), + right(x.errors, x.errors ? C.amber : dim), right(x.drops, x.drops ? C.amber : dim)]; + })); + }; + return el; +} + +// filterable, sortable list that keeps its selection across refreshes (processes, services) +function listTab(headers, widths, sort, hint) { + const filter = h('input', { type: 'search', placeholder: hint, oninput: () => tbl.render() }), summary = h('span.muted.grow'), status = h('div.muted'); + const tbl = table(headers, { widths, sort, sortable: true, select: true }), bar = h('div.row', null, filter, summary), el = h('div.tab.col', null, bar, tbl, status); + tbl.accept = r => r.some(c => cellText(c).toLowerCase().includes(filter.value.toLowerCase())); + el.report = async (label, path, body) => { // run a command and show the result in the status line + status.textContent = 'Running: ' + label, status.style.color = ''; + const r = await api(path, { id: S.id, ...body }); + status.textContent = r.code ? `✗ ${r.cmd}: ${r.out.trim().slice(0, 300)}` : '✓ ' + r.cmd, status.style.color = r.code ? C.red : C.green; + }; + el.selected = what => tbl.selRow() ? tbl.sel : void (status.textContent = `Select a ${what} first.`, status.style.color = ''); + return Object.assign(el, { tbl, bar, summary }); +} + +function processTab() { + const P = S.plat, freeze = h('input', { type: 'checkbox' }); + const el = listTab(['PID', 'Name', 'User', 'State', 'CPU', 'Memory', 'RSS', 'Threads', P.prioLabel, 'Running for'], [80, 230, 120, 100, 130, 130, 100, 80, 70], [4, true], 'Filter by name, user or PID…'); + const STATES = { R: ['Running', C.green], S: ['Sleeping', C.muted], D: ['Disk wait', C.amber], Z: ['Zombie', C.red], T: ['Stopped', C.red], I: ['Idle', C.muted] }; + const picked = () => el.selected('process') && { pid: el.tbl.sel, who: `${cellText(el.tbl.selRow()[1])} (${el.tbl.sel})` }; // read before a question: the list keeps refreshing behind it + const send = (list, i, label, p) => el.report(`${label} ${p.who}`, 'run', { list, i, arg: p.pid }); + const run = (c, i) => async () => { + const p = picked(); + if (p && (!c.confirm || await ask(c.label, `${c.label} ${p.who} on ${cur().cfg.name}?`, c.danger))) send('procActions', i, c.label, p); + }; + const renice = async () => { + const p = picked(), pick = h('select', null, P.priorities.map(c => h('option', null, c.label))); + pick.selectedIndex = P.priorities.length >> 1; + if (p && await dialog('Change priority', h('div.col', null, `Priority for ${p.who}:`, pick), [['OK', '.primary', () => true], ['Cancel', '', () => false]])) send('priorities', pick.selectedIndex, 'Priority', p); + }; + const acts = P.procActions.map((c, i) => [c, run(c, i)]); + el.bar.firstChild.after(h('label.check', { title: "Stop refreshing so rows don't move while you pick one" }, freeze, 'Freeze list')); + el.bar.append(...acts.filter(([c]) => c.button).map(([c, fn]) => h('button' + (c.danger ? '.danger' : ''), { onclick: fn }, c.label)), h('button', { onclick: renice }, 'Priority…')); + el.tbl.menu = () => [...acts.map(([c, fn]) => [c.label, fn]), null, ['Change priority…', renice]]; + el.refresh = () => { + const m = S.m, num = (v, c) => ({ t: v, k: v, c, r: 1 }); + if (freeze.checked) return; + el.tbl.fill(m.procs.map(p => [num(p.pid, C.muted), p.name, { t: p.user, c: C.muted }, { t: (STATES[p.state] || [p.state])[0], c: (STATES[p.state] || [0, C.muted])[1] }, + { t: Fmt.pct(p.cpu), pct: Math.min(100, p.cpu), k: p.cpu }, { t: Fmt.pct(p.memPct), pct: p.memPct, k: p.memPct }, { ...num(p.rss), t: Fmt.bytes(p.rss) }, num(p.threads), + num(p.nice, p.nice === P.normalPrio ? '' : C.teal), { ...num(p.age, C.muted), t: Fmt.duration(p.age) }])); + el.summary.textContent = `${m.procs.length} processes · ${m.procs.filter(p => p.state === 'R').length} running · ${m.threadsTotal} threads`; + }; + return el; +} + +function serviceTab() { + const P = S.plat, el = listTab(['Service', 'Active', 'State', 'Load', 'Description'], [300, 100, 100, 90], [0, false], 'Filter services…'), matches = el.tbl.accept; + const state = h('select', { onchange: () => el.tbl.render() }, ['All', 'Running', 'Failed', 'Not running'].map(t => h('option', null, t))); + const act = (c, i) => async () => { + const unit = el.selected('service'); + if (unit && (!c.confirm || await ask('Confirm', `${c.label} ${unit} on ${cur().cfg.name}?`, c.danger))) el.report(`${c.label} ${unit}`, 'run', { list: 'serviceActions', i, arg: unit }); + }; + const logs = () => { + const unit = el.tbl.selRow() && el.tbl.sel, id = S.id, out = h('pre.log', null, 'Loading…'), lines = h('input', { type: 'number', min: 50, max: 5000, value: 300 }); + const load = async () => (out.textContent = (await api('logs', { id, unit, lines: lines.value })).out, out.scrollTop = out.scrollHeight); + if (unit) load(), dialog(`Logs — ${unit} — ${cur().cfg.name}`, h('div.col', null, out, h('div.row', null, lines, 'lines', h('button', { onclick: load }, 'Reload'))), [['Close', '', () => true]], '.wide'); + }; + const acts = P.serviceActions.map((c, i) => [c.label, act(c, i), c.danger]); + let shown; + el.tbl.accept = r => { + const [, active, sub] = r.map(cellText), i = state.selectedIndex; + return (!i || (i === 1 && sub === 'running') || (i === 2 && active === 'failed') || (i === 3 && sub !== 'running' && active !== 'failed')) && matches(r); + }; + el.bar.firstChild.after(state); + el.bar.append(...acts.map(([label, fn, danger]) => h('button' + (danger ? '.danger' : ''), { onclick: fn }, label)), h('button.primary', { onclick: logs }, 'Logs')); + el.tbl.menu = () => [...acts, null, ['Show logs', logs]]; + el.tbl.addEventListener('dblclick', logs); + el.refresh = () => { + const m = S.m, sig = m.services.map(x => x.unit + x.active + x.sub).join(); + if (sig === shown) return; // unchanged: keep the list still + shown = sig; + el.tbl.fill(m.services.map(x => { + const c = x.active === 'failed' ? C.red : x.sub === 'running' ? C.green : x.active === 'active' ? C.teal : C.muted; + return [x.unit, { t: x.active, c }, { t: x.sub, c }, { t: x.load, c: C.muted }, { t: x.description, c: C.muted }]; + })); + el.summary.textContent = m.services.length ? `${m.services.length} services · ${m.servicesRunning} running · ${m.servicesFailed} failed` : 'No services reported by this machine'; + }; + return el; +} + +function historyTab() { + const P = S.plat, id = S.id, RANGES = [['1 h', 3600], ['6 h', 21600], ['24 h', 86400], ['7 d', 604800], ['30 d', 2592000], ['90 d', 7776000], ['1 y', 31536000], ['All', 0]]; + let range = 86400, loaded = 0; + const res = h('span.muted.grow'), csv = h('a.button', null, 'Export CSV…'), buttons = RANGES.map(([t, sec]) => h('button', { onclick: () => (range = sec, reload()) }, t)); + const charts = [['CPU', pctFmt, 100], ['Memory & swap', pctFmt, 100], ['Disk usage (fullest)', pctFmt, 100], ['Disk throughput', Fmt.rate], ['Network', Fmt.rate], ['Load average', numFmt(1)], + ['Temperature', v => Fmt.fix(v) + '°'], ['Availability', pctFmt, 100]].map(([t, fmt, max]) => chart(t, fmt, max, false, 'No history for this range yet')); + const st = table(['Metric', 'Minimum', 'Average', '95th percentile', 'Peak', 'Points'], { widths: [200, 150, 150, 150, 150] }); + const el = h('div.tab.scroll', null, h('div.row', null, buttons, res, csv), h('div.grid2', null, charts), panel('Statistics for the selected range', st)); + async function reload() { + const query = `?id=${encodeURIComponent(id)}&range=${range}`, right = (t, c) => ({ t, c, r: 1 }); + loaded = Date.now(), csv.href = '/api/history.csv' + query, buttons.forEach((b, i) => b.classList.toggle('on', RANGES[i][1] === range)); + const d = await api('history' + query), v = d.v, peak = (name, color, data) => d.aggregated ? [ser(name, color, data, false, true)] : []; + const data = [[ser('Average', C.accent, v.cpu), ...peak('Peak', C.red, v.cpuMax)], [ser('Memory', C.violet, v.mem), ser('Swap', C.pink, v.swap, false)], [ser('Usage', C.amber, v.disk)], + [ser('Read', C.blue, v.rd), ser('Write', C.orange, v.wr)], [ser('Down', C.teal, v.rx), ser('Up', C.pink, v.tx), ...peak('Peak down', '#60ffeb', v.rxMax)], [ser('Load', C.violet, v.load)], + [ser('Average', C.orange, v.temp), ...peak('Peak', C.red, v.tempMax)], [ser('Online', C.green, v.avail)]]; + charts.forEach((c, i) => (c.sub = d.aggregated ? 'avg per ' + d.tier : '', c.set(d.t, data[i], d.span))); + res.textContent = `Resolution: ${d.tier} · ${d.points} points · availability ${ok(d.availability) ? Fmt.pct(d.availability, 2) : '—'} · stored ${Fmt.bytes(d.bytes)}`; + st.fill(d.stats.map((x, m) => [hNames[m], right(fmtMetric(m, x.min), C.muted), right(fmtMetric(m, x.avg)), right(fmtMetric(m, x.p95), C.amber), right(fmtMetric(m, x.max), C.red), right(x.count, C.muted)]) + .filter((_, m) => m < 14 && (P.posixCpu || m !== 1))); + } + el.refresh = () => Date.now() - loaded >= (range && range <= 21600 ? 5000 : 60000) && reload(); + return el; +} + +function insightsTab() { + const id = S.id, ap = { ...cur().cfg.autopilot }, f = fields(ap, () => api('server/update', { id, autopilot: ap })); + const health = gauge('Health score'), reasons = h('div.muted.pre'), capacity = h('div.col'), findings = h('div.col'), heat = h('div.heat'); + const t = tiles([['Disk full forecast', 'amber'], ['Memory trend (6 h)', 'violet'], ['CPU / memory p95 (30 d)', 'accent'], ['Availability 24 h', 'green'], ['Availability 7 d', 'green'], ['Availability 30 d', 'green']], 3); + const heatMetric = h('select', { onchange: () => el.analysis() }, h('option', null, 'CPU'), h('option', null, 'Memory')); + const anomalies = table(['Metric', 'Last 10 min', 'Usual', 'Deviation', 'Baseline'], { widths: [110, 110, 160, 90] }); + const autopilot = panel('Autopilot — automatic control', h('div.muted', null, 'Acts on the findings once a minute, using statistics over the stored history. Every action is logged as an event.'), form([ + [f.check('enabled', 'Autopilot enabled'), f.check('dryRun', 'Dry run (only report)')], + [f.check('restartFailed', 'Restart failed services'), [f.num('maxRestartsPerHour', 1, 20), '/ hour max']], + ['Runaway processes', f.select('runawayMode', [['none', 'Ignore'], ['renice', 'Lower priority (renice 19)'], ['terminate', 'Terminate']])], + ['', ['≥', f.num('runawayCpu', 10, 6400), '% for', f.num('runawayMinutes', 1, 1440), 'min']], + ['Memory leaks', f.select('leakMode', [['none', 'Ignore'], ['notify', 'Notify'], ['terminate', 'Terminate under pressure']])], [' pressure ≥', [f.num('leakMemPressure', 50, 100), '% memory']], + [f.check('diskCleanup', 'Disk cleanup'), ['full in <', f.num('diskForecastDays', 1, 60), 'days']], ['', ['or usage ≥', f.num('diskCleanupAt', 50, 100), '%']], + [' command', f.text('diskCleanupCommand', { className: 'mono grow' })], [f.check('anomalyAlerts', 'Anomaly alerts'), ['z ≥', f.num('anomalyZ', 1.5, 10, .5), 'σ']]])); + const el = h('div.tab.scroll', null, + h('div.row.top', null, h('div.side', null, panel('Health', health, reasons, h('button', { onclick: () => api('server/analyze', { id }) }, 'Analyze now'))), h('div.col.grow', null, t, panel('Capacity planning', capacity))), + h('div.row.top', null, h('div.grow', null, panel('Findings from history analysis', findings)), h('div.side.wide', null, autopilot)), + h('div.row.top', null, h('div.grow3', null, panel('Weekly pattern (last 4 weeks, hourly averages)', heatMetric, heat)), h('div.grow2', null, panel('Now vs. normal (baselines)', anomalies)))); + el.analysis = () => { + const a = S.an, s = cur(), hi = heatMetric.selectedIndex, f2 = v => Fmt.fix(v, 2), days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; + health.set(a.health, String(a.health), 'grade ' + a.grade, healthColor(a.health)); + reasons.textContent = (a.healthReasons.join('\n') || 'No deductions — everything looks healthy.') + (a.when ? '\n\nAnalyzed ' + tf(a.when * 1000, 'HH:mm:ss') : ''); + if (a.diskFullDays >= 0) t.set(0, Fmt.duration(a.diskFullDays * 86400), `+${f2(a.diskSlopePerDay)} pts/day · ${a.diskBasis}`, a.diskFullDays < 7 ? C.red : a.diskFullDays < 30 ? C.amber : ''); + else t.set(0, 'Not filling', a.diskBasis ? `trend ${f2(a.diskSlopePerDay)} pts/day` : 'needs ~2 h of history', C.green); + if (a.memTrendR2 > 0) t.set(1, `${a.memSlopePerHour >= 0 ? '+' : ''}${f2(a.memSlopePerHour)} pts/h`, 'fit R² ' + f2(a.memTrendR2), a.memSlopePerHour > 1 && a.memTrendR2 > .8 ? C.amber : ''); + else t.set(1, '—', 'needs ~90 min of history'); + if (a.cpu30.count) t.set(2, `${Fmt.pct(a.cpu30.p95, 0)} / ${Fmt.pct(a.mem30.p95, 0)}`, `avg ${Fmt.pct(a.cpu30.avg, 0)} / ${Fmt.pct(a.mem30.avg, 0)}`); + else t.set(2, '—', 'collecting'); + a.up.forEach((up, i) => ok(up) ? t.set(3 + i, Fmt.pct(up, up >= 99.995 ? 0 : 2), `≈ ${Fmt.duration(a.down[i])} offline`, up >= 99.9 ? C.green : up >= 99 ? C.amber : C.red) + : t.set(3 + i, '—', 'no data yet')); + capacity.replaceChildren(...a.capacity.map(line => h('div', null, '• ' + line))); + heat.replaceChildren(...days.flatMap((day, d) => [h('small', null, day.slice(0, 3)), ...a.heat[hi][d].map((v, hour) => h('i', { + title: `${day} ${hour}:00 — ` + (ok(v) ? `avg ${Fmt.fix(v, 1)}${hi ? '% memory' : '% CPU'} (${a.heatN[d][hour]} samples)` : 'no data'), + style: { background: ok(v) ? mix('#1b2a44', hi ? C.violet : C.accent, .15 + .85 * v / 100) : C.card } }))]), + h('small'), ...Array.from({ length: 24 }, (_, hour) => h('small', null, hour % 3 ? '' : pad(hour) + ':00')), + ...(a.heatN.flat().some(Boolean) ? [] : [h('p', null, 'Collecting hourly history… the weekly pattern fills in over time')])); + anomalies.fill(a.anomalies.map(x => [x.metric, { t: fmtMetric(x.hm, x.now), r: 1 }, { t: `${fmtMetric(x.hm, x.mean)} ± ${fmtMetric(x.hm, x.sd)}`, c: C.muted, r: 1 }, + { t: `${x.z >= 0 ? '+' : ''}${Fmt.fix(x.z, 1)}σ`, c: Math.abs(x.z) >= 3 ? C.red : Math.abs(x.z) >= 2 ? C.amber : C.green, r: 1 }, { t: x.baseline, c: C.muted }])); + findings.replaceChildren(...a.findings.map(x => { + const color = sevColor(x.severity), auto = x.autoEligible && s.cfg.autopilot.enabled; + const fix = x.action && h('button' + (x.action === 'kill_pid' ? '.danger' : '.primary'), { onclick: async () => { // the card may be rebuilt while the question is open + if (!await ask(x.actionLabel, `${x.actionLabel} on ${s.cfg.name}?\n\n${x.title}`, x.action === 'kill_pid')) return; + fix.disabled = true, fix.textContent = 'Working…'; + fix.textContent = (await api('finding', { id, key: x.key })).code ? '✗ Failed' : '✓ Done'; + } }, x.actionLabel); + return h('div.finding', { style: { 'border-left-color': color } }, h('div.grow', null, h('small', { style: { color } }, `${x.severity} · ${x.category}`), h('b', null, x.title), h('div', null, x.detail), + h('div.muted', null, '→ ' + x.advice), auto && h('small', { style: { color: C.violet } }, s.cfg.autopilot.dryRun ? 'Autopilot (dry run) would act on this' : 'Autopilot handles this automatically')), fix); + })); + if (!a.findings.length) findings.append(h('div', { style: { color: C.green } }, + '✓ No problems found in the history. The analyzer checks disk forecasts, memory trends, leaks, runaway processes, service failures, overload and anomalies every minute.')); + }; + return el; +} + +function rulesTab() { + const P = S.plat, id = S.id, metrics = ruleMetrics.filter(d => P.posixCpu || d[0] !== 'iowait'), store = rules => api('server/update', { id, rules }); + const list = table(['On', 'Condition', 'Severity', 'Action', 'Cooldown', 'Live value'], { widths: [50, 380, 100, 330, 100], select: true }); + const active = table(['Active problems'], { empty: ['✓ No rule is currently triggered', C.green] }); + const edit = async old => { + const rs = cur().cfg.rules, r = { ...(old || S.rule) }, f = fields(r, () => sync()), arg = f.text('arg', { className: 'grow' }); + const sync = () => (arg.placeholder = def(P.ruleActions, r.action)[2], arg.disabled = !arg.placeholder); + sync(); + if (!await dialog(old ? 'Edit rule' : 'New rule', form([['When', f.select('metric', metrics.map(([k, label, unit]) => [k, label + (unit && ` (${unit})`)]))], + ['is', [f.select('op', [['>', '>'], ['<', '<']]), f.num('value', -1e9, 1e9, 'any')]], ['for at least', [f.num('duration', 0, 86400), 's']], + ['Severity', f.select('severity', ['info', 'warning', 'critical'].map(x => [x, x]))], ['Then', f.select('action', P.ruleActions)], ['Argument', arg], + ['Repeat after', [f.num('cooldown', 10, 86400), 's']], ['', f.check('enabled', 'Enabled')]]), [['OK', '.primary', () => true], ['Cancel', '', () => false]])) return; + if (arg.disabled) r.arg = ''; + store(old ? rs.map(x => x === old ? r : x) : [...rs, r]); + }; + const selected = () => cur().cfg.rules.find(r => r.id === list.sel); + const el = h('div.tab.col', null, h('div.muted', null, 'Threshold rules are checked on every sample. When a condition holds for its duration an alert is raised and the action runs; ' + + 'if it is still true after the cooldown the action runs again. History-based automation lives in the Insights tab.'), + h('div.row', null, h('button.primary', { onclick: () => edit() }, '+ Add rule'), h('button', { onclick: () => selected() && edit(selected()) }, 'Edit'), + h('button.danger', { onclick: () => selected() && store(cur().cfg.rules.filter(r => r.id !== list.sel)) }, 'Delete'), h('span.grow'), + h('button', { onclick: async () => await ask('Reset rules', 'Replace all rules with the defaults?') && store(S.defaultRules) }, 'Reset to defaults')), list, active); + let shown, boxes; + list.addEventListener('dblclick', () => selected() && edit(selected())); + el.refresh = () => { + const s = cur(), rs = s.cfg.rules; + if (shown !== (shown = JSON.stringify(rs))) boxes = rs.map(r => h('input', { type: 'checkbox', checked: r.enabled, onchange: e => store(rs.map(x => x === r ? { ...r, enabled: e.target.checked } : x)) })); + list.fill(rs.map((r, i) => { + const v = S.vals[r.metric] ?? 0; + return Object.assign([{ el: boxes[i] }, { t: conditionText(r), c: r.enabled ? '' : C.faint }, { t: r.severity, c: sevColor(r.severity) }, { t: actionText(P.ruleActions, r), c: r.action === 'notify' ? C.muted : C.violet }, + { t: r.cooldown + ' s', c: C.muted }, { t: `${Fmt.fix(v, 1)} ${def(ruleMetrics, r.metric)[2]}`, c: (r.op === '<' ? v < r.value : v > r.value) ? C.red : C.green }], { key: r.id }); + })); + active.fill(s.alerts.map(a => [{ t: '⚠ ' + a, c: C.red }])); + }; + return el; +} + +function consoleTab() { + const P = S.plat, s = cur(), id = S.id, out = h('div.console.mono'), sudo = h('input', { type: 'checkbox' }), past = []; + let pos = 0; + const say = (cls, ...parts) => { // keeps the last 2000 blocks + out.append(h('div' + cls, null, parts)), out.childElementCount > 2000 && out.firstChild.remove(), out.scrollTop = out.scrollHeight; + }; + const exec = async (cmd, privileged) => { + const t0 = Date.now(); + say('.cmd', h('b', null, tf(t0, 'HH:mm:ss') + ' $ '), cmd); + const r = await api('exec', { id, cmd, privileged }); + if (r.out) say('', r.out.replace(/\n$/, '')); + say(r.code ? '.bad' : '.good', `[exit ${r.code} · ${Date.now() - t0} ms]`); + }; + const run = () => { + const c = input.value.trim(); + if (!c) return; + if (past.at(-1) !== c) past.push(c); + pos = past.length, input.value = '', exec(c, sudo.checked); + }; + const input = h('input.mono.grow', { placeholder: 'Type a shell command and press Enter (↑/↓ history)', onkeydown: e => { + if (e.key === 'Enter') return run(); + if (!past.length || !['ArrowUp', 'ArrowDown'].includes(e.key)) return; + e.preventDefault(), pos = clamp(pos + (e.key === 'ArrowUp' ? -1 : 1), 0, past.length), input.value = past[pos] || ''; + } }); + const group = (title, items, system) => panel(title, items.map(q => h('button.left' + (q.danger ? '.danger' : ''), { title: q.cmd, onclick: async () => { + if (!system || await ask(q.label, `${q.label} on ${s.cfg.name}?` + (q.danger ? '\n\nThe machine will be unavailable until it comes back.' : ''), q.danger)) exec(q.cmd, system); + } }, q.label))); + say('.muted', `Console for ${s.cfg.name} (${s.address}). Commands run non-interactively with a 120 s timeout.`); + return h('div.tab.row.stretch', null, h('div.col.grow', null, out, h('div.row', null, h('b.prompt', null, '$'), input, + P.sudo && h('label.check', { title: "Wrap in sudo -n when the server has 'Run control commands with sudo' enabled" }, sudo, 'privileged'), + h('button.primary', { onclick: run }, 'Run'), h('button', { onclick: () => out.replaceChildren() }, 'Clear'))), + h('div.side.col.scroll', null, group('Quick diagnostics', P.diagnostics, false), group('System actions', P.systemActions, true))); +} + +// ---- server page ---- +const TABS = { overview: ['Overview', overviewTab], cpu: ['CPU', cpuTab], memory: ['Memory', memoryTab], storage: ['Storage', storageTab], network: ['Network', networkTab], + processes: ['Processes', processTab], services: ['Services', serviceTab], history: ['History', historyTab], insights: ['Insights & Autopilot', insightsTab], + rules: ['Alert rules', rulesTab], console: ['Console', consoleTab] }; +let feed, built = {}, builtFor; // the open live stream; tab elements of the server they were built for +const detail = (() => { + const name = h('h1'), state = h('b.state'), sub = h('div.muted'), chips = h('div.chips'), holder = h('div.fill'); + const act = (path, extra) => api(path, { id: S.id, ...extra }); + const pause = h('button', { onclick: () => act('server/pause', { paused: !cur().paused }) }); + const power = reboot => async () => await ask(reboot ? 'Reboot…' : 'Shut down…', `${reboot ? 'Reboot' : 'Shut down'} ${cur().cfg.name} now?`, true) && act('power', { reboot }); + const span = h('select', { onchange: () => (S.span = +span.value, el.refresh()) }, [5, 15, 30, 60].map(min => h('option', { value: min, selected: min === S.span }, min === 60 ? 'Last hour' : `Last ${min} minutes`))); + const bar = h('div.tabbar', null, Object.entries(TABS).map(([key, [title]]) => h('button', { onclick: () => go('server', S.id, key) }, title))); + const el = h('section', null, h('div.row.end', null, h('div.grow', null, h('button.flat', { onclick: () => go('dashboard') }, '‹ Dashboard'), h('div.row', null, name, state), sub, chips), + h('label.col', null, h('div.section', null, 'Live window'), span), h('button', { onclick: () => act('server/reconnect') }, '⟳ Reconnect'), pause, h('button', { onclick: () => editServer(S.id) }, 'Edit'), + h('button.danger', { onclick: e => menu(e, [['Reboot…', power(true)], ['Shut down…', power(false)], null, ['Remove from monitor…', () => removeServer(S.id)]]) }, '⏻ Power')), bar, holder); + el.refresh = withAnalysis => { // header, then the visible tab + const s = cur(), c = s?.cfg, m = s?.m; + if (!s) return; + name.textContent = c.name, state.textContent = '● ' + (s.paused ? 'Paused' : s.status), state.style.color = s.paused ? C.amber : statusColor(s); + sub.textContent = [s.address, c.transport ? 'SSH' : 'Local', m.hostname && 'host ' + m.hostname, s.online ? 'up ' + Fmt.duration(m.uptime) : s.status === 'Offline' && s.err].filter(Boolean).join(' · '); + chips.replaceChildren(...[[m.os], [m.kernel && S.plat.kernelPrefix + m.kernel], [m.cpuCount && m.cpuCount + ' cores'], [m.memTotal > 0 && Fmt.bytes(m.memTotal) + ' RAM'], [c.group, '#7dd3fc'], + [s.online && `health ${s.health} (${s.grade})`, healthColor(s.health)], [c.autopilot.enabled && (c.autopilot.dryRun ? 'autopilot: dry run' : 'autopilot: on'), C.violet]] + .filter(([t]) => t).map(([t, color]) => h('span.chip', { style: { color } }, t))); + pause.textContent = s.paused ? '▶ Resume' : '❚❚ Pause'; + [...bar.children].forEach((b, i) => b.classList.toggle('on', Object.keys(TABS)[i] === S.tab)); + if (!S.m) return holder.replaceChildren(); // the first event of the stream brings the data + const tab = built[S.tab] ??= (withAnalysis = true, TABS[S.tab][1]()); + if (holder.firstChild !== tab) holder.replaceChildren(tab), withAnalysis = true; + tab.refresh?.(), withAnalysis && tab.analysis?.(); + }; + return el; +})(); +function listen() { // (re)opens the live stream: server list and events, plus the samples of the server on the detail page + feed?.close(), S.m = null; + feed = new EventSource('/api/events' + (S.id ? '?id=' + encodeURIComponent(S.id) : '')); + const on = (event, fn) => feed.addEventListener(event, e => fn(JSON.parse(e.data))); + on('hello', d => { + const missed = S.plat ? d.alerts.filter(a => a.time > (S.alerts[0]?.time || 0)).reverse() : []; // raised while the stream was being reopened + Object.assign(S, d), document.title = `Server Monitor (${d.plat.name})`, route(); + missed.length ? missed.forEach(alertsChanged) : alertsChanged(); + }); + on('state', d => (S.servers = d, cur() || S.page !== 'server' ? stateChanged() : route())); + on('alert', d => (S.alerts.unshift(d), S.alerts.length = Math.min(S.alerts.length, 2000), alertsChanged(d))); + on('alerts', d => (S.alerts = d, S.unseen = 0, alertsChanged())); + on('live', d => (Object.assign(S, { live: d.rows, m: d.m, vals: d.vals, an: d.an }), detail.refresh(true))); + on('sample', d => (S.m = d.m, S.vals = d.vals, S.live.push(d.row), S.live.length > 1800 && S.live.shift(), detail.refresh())); + on('analysis', d => (S.an = d, detail.refresh(true))); +} + +// ---- events page ---- +const eventsPage = (() => { + const list = table(['Time', 'Server', 'Type', 'Message'], { widths: [170, 180, 100] }), kind = h('select', { onchange: () => el.update() }, ['All events', 'critical', 'warning', 'info', 'resolved', 'action'].map(t => h('option', null, t))); + const where = h('div.muted'), notify = h('input', { type: 'checkbox', checked: localStorage.notify === '1', onchange: async () => localStorage.notify = +(notify.checked &&= await Notification.requestPermission() === 'granted') }); + const el = h('section', null, h('div.row', null, h('div.grow', null, h('h1', null, 'Events & alerts'), where), h('label.check', null, notify, 'Browser notifications'), kind, + h('a.button', { href: '/api/alerts.log' }, 'Download alerts.log'), h('button', { onclick: () => api('alerts/clear', {}) }, 'Clear list')), list); + el.update = () => { + where.textContent = `Alerts, recoveries, insights and every automatic or manual action, newest first. Also written to alerts.log in ${S.dir}`; + list.fill(S.alerts.filter(e => !kind.selectedIndex || e.severity === kind.value).map(e => [{ t: tf(e.time, 'yyyy-MM-dd HH:mm:ss'), c: C.muted }, e.serverName, { t: e.severity.toUpperCase(), c: sevColor(e.severity) }, e.message])); + }; + return el; +})(); +function alertsChanged(latest) { // latest = the event that just arrived, if any + const important = ['critical', 'warning', 'action'].includes(latest?.severity); + if (S.page === 'events') S.unseen = 0; + else if (important) ++S.unseen; + if (important && localStorage.notify === '1' && Notification.permission === 'granted') new Notification(`${latest.serverName} — ${latest.severity}`, { body: latest.message, icon: 'icon.svg' }); + badge.textContent = S.unseen, badge.hidden = !S.unseen, dash.events(), eventsPage.update(); +} + +// ---- pages and routing: #/dashboard, #/events, #/server// ---- +const pages = { dashboard: dash, server: detail, events: eventsPage }; +function route() { + const [page, ref, tab] = location.hash.replace(/^#\/?/, '').split('/').map(decodeURIComponent), s = S.servers.find(x => x.cfg.id === ref) || S.servers[+ref]; + const id = page === 'server' && s ? s.cfg.id : null; + S.page = id ? 'server' : page === 'events' ? 'events' : 'dashboard', S.tab = tab in TABS ? tab : 'overview'; + if (id && id !== builtFor) built = {}, builtFor = id; + if (id !== S.id) S.id = id, listen(); + for (const [k, el] of Object.entries(pages)) el.hidden = k !== S.page, nav[k]?.classList.toggle('on', k === S.page); + stateChanged(), S.page === 'events' && alertsChanged(); +} +function stateChanged() { + keyed(sideList, sideItem), S.page === 'dashboard' ? dash.update() : detail.refresh(); +} + +document.body.append(sidebar, h('main', null, Object.values(pages))); +listen(), addEventListener('hashchange', route); diff --git a/Server Monitor(web-linux)/public/icon.svg b/Server Monitor(web-linux)/public/icon.svg new file mode 100644 index 0000000000000000000000000000000000000000..106afbd504968423bd683610e537cb5f336ad54f --- /dev/null +++ b/Server Monitor(web-linux)/public/icon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Server Monitor(web-linux)/public/index.html b/Server Monitor(web-linux)/public/index.html new file mode 100644 index 0000000000000000000000000000000000000000..fcb9ce4e98381464097d823e2de581fe4f3718f5 --- /dev/null +++ b/Server Monitor(web-linux)/public/index.html @@ -0,0 +1,14 @@ + + + + + +Server Monitor + + + + + + + + diff --git a/Server Monitor(web-linux)/public/shared.js b/Server Monitor(web-linux)/public/shared.js new file mode 100644 index 0000000000000000000000000000000000000000..d058f879780aefff3ed069d7f1f2b54d34790ebe --- /dev/null +++ b/Server Monitor(web-linux)/public/shared.js @@ -0,0 +1,47 @@ +// Formatting and catalogues used by both the server (core/*.js) and the page (app.js). +const SM = (() => { + const fix = (v, prec = 0) => (+v).toFixed(prec); + const bytes = (b, prec = 1) => { + let i = 0; + for (; Math.abs(b) >= 1024 && i < 5; ++i) b /= 1024; + return fix(b, i ? prec : 0) + ' ' + ['B', 'KB', 'MB', 'GB', 'TB', 'PB'][i]; + }; + const Fmt = { + fix, bytes, + rate: b => bytes(b) + '/s', + pct: (p, prec = 1) => fix(p, prec) + '%', + temp: c => fix(c) + ' °C', + num: v => String(+(+v).toPrecision(6)), + iso: ms => new Date(ms - new Date(ms).getTimezoneOffset() * 60000).toISOString().slice(0, 19), // local time + count(v) { + const a = Math.abs(v); + return a >= 1e9 ? fix(v / 1e9, 1) + 'G' : a >= 1e6 ? fix(v / 1e6, 1) + 'M' : a >= 1e4 ? fix(v / 1e3, 1) + 'K' : fix(v); + }, + duration(sec) { + const s = Math.trunc(sec), d = Math.trunc(s / 86400), h = Math.trunc(s % 86400 / 3600), m = Math.trunc(s % 3600 / 60); + return d ? `${d}d ${h}h ${m}m` : h ? `${h}h ${m}m` : m ? `${m}m ${s % 60}s` : `${s}s`; + }, + }; + + // history metrics, in the order of the binary record + const H = ['cpu', 'iowait', 'load', 'mem', 'swap', 'disk', 'diskio', 'rx', 'tx', 'rd', 'wr', 'temp', 'procs', 'gpu', 'failed']; + const hNames = ['CPU', 'I/O wait', 'Load (1m)', 'Memory', 'Swap', 'Disk usage', 'Disk busy', 'Net download', 'Net upload', 'Disk read', 'Disk write', + 'Temperature', 'Processes', 'GPU', 'Failed services']; + const fmtMetric = (m, v) => v == null || isNaN(v) ? '—' : m >= 7 && m <= 10 ? Fmt.rate(v) : m === 2 ? fix(v, 2) : m === 11 ? Fmt.temp(v) + : m === 12 || m === 14 ? fix(v) : Fmt.pct(v); + + // rule catalogue rows: key, label, unit (metrics) or argument hint (actions, defined per platform) + const ruleMetrics = [['cpu', 'CPU usage', '%'], ['iowait', 'CPU I/O wait', '%'], ['load', 'Load (1 min) per core', '%'], ['mem', 'Memory usage', '%'], + ['swap', 'Swap usage', '%'], ['disk', 'Fullest disk usage', '%'], ['diskio', 'Busiest disk utilisation', '%'], ['temp', 'Hottest sensor', '°C'], + ['rx', 'Network download', 'MB/s'], ['tx', 'Network upload', 'MB/s'], ['failed', 'Failed services', ''], ['procs', 'Process count', ''], + ['gpu', 'GPU usage (max)', '%'], ['gputemp', 'GPU temperature (max)', '°C']]; + const def = (list, key) => list.find(d => d[0] === key) || [key, key, '']; + const conditionText = r => { + const [, label, unit] = def(ruleMetrics, r.metric); + return `${label} ${r.op} ${Fmt.num(r.value)}${unit && ' ' + unit}` + (r.duration ? ` for ${r.duration} s` : ''); + }; + const actionText = (actions, r) => def(actions, r.action)[1] + (r.arg ? ': ' + r.arg : ''); + + return { Fmt, H, hNames, fmtMetric, ruleMetrics, def, conditionText, actionText }; +})(); +if (typeof module === 'object') module.exports = SM; diff --git a/Server Monitor(web-linux)/public/style.css b/Server Monitor(web-linux)/public/style.css new file mode 100644 index 0000000000000000000000000000000000000000..81aa4923b7f40471d28cc8f8b63a6fa96bc091a9 --- /dev/null +++ b/Server Monitor(web-linux)/public/style.css @@ -0,0 +1,110 @@ +/* Server Monitor: dark theme. app.js reads the palette from these variables for its canvas drawing. */ +:root { + --bg: #0d111c; --panel: #161c2b; --card: #1a2133; --border: #27314a; --grid: #242d42; --text: #e6ebf5; --muted: #8b95ab; --faint: #5a657d; + --accent: #38bdf8; --green: #22c55e; --amber: #f59e0b; --red: #ef4444; --violet: #a78bfa; --pink: #f472b6; --teal: #2dd4bf; --orange: #fb923c; --blue: #60a5fa; + --line: #232c41; --input: #111727; --select: #17304a; + font: 13px/1.4 system-ui, "Segoe UI", Roboto, "Noto Sans", sans-serif; color: var(--text); color-scheme: dark; +} +* { box-sizing: border-box; } +[hidden] { display: none !important; } +body { margin: 0; height: 100vh; min-width: 1100px; display: flex; background: var(--bg); } +h1 { margin: 0; font-size: 22px; } h2 { margin: 0; font-size: 16px; font-weight: 600; } p { margin: 0; } +small { font-size: 11px; color: var(--muted); } +::-webkit-scrollbar { width: 10px; height: 10px; } ::-webkit-scrollbar-thumb { background: #2a3449; border-radius: 5px; border: 2px solid transparent; background-clip: content-box; } + +/* layout helpers */ +.row { display: flex; gap: 10px; align-items: center; } .col { display: flex; flex-direction: column; gap: 10px; } +.top { align-items: flex-start; } .end { align-items: flex-end; } .stretch { align-items: stretch; } +.grow { flex: 1; min-width: 0; } .grow2 { flex: 2; min-width: 0; } .grow3 { flex: 3; min-width: 0; } .fill { flex: 1; min-height: 0; } +.scroll { overflow: hidden auto; } .side { width: 330px; flex: none; } .side.wide { width: 460px; } +.grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; } +.muted { color: var(--muted); } .pre { white-space: pre-wrap; } .mono { font-family: ui-monospace, "DejaVu Sans Mono", Consolas, monospace; } +.section { color: var(--muted); font-size: 11px; font-weight: 700; letter-spacing: 1px; text-transform: uppercase; } +.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px; display: flex; flex-direction: column; gap: 10px; } +.side > .panel:only-child { height: 100%; } + +/* controls */ +button, .button { background: #1d2538; border: 1px solid #2c3650; border-radius: 8px; padding: 7px 14px; font: inherit; font-weight: 600; color: var(--text); cursor: pointer; text-decoration: none; white-space: nowrap; } +button:hover, .button:hover { background: #253049; border-color: var(--accent); } button:disabled { color: var(--faint); border-color: #222a3c; } +button.primary, button.on { background: #0e7ab8; border-color: var(--accent); color: #fff; } button.primary:hover { background: #1190d8; } +button.danger { background: #3a1820; border-color: #7f2a36; color: #ffb4bd; } button.danger:hover { background: #55202b; border-color: var(--red); } +button.flat { background: none; border: none; padding: 4px 8px 4px 0; color: var(--muted); } button.flat:hover { color: var(--text); } +button.left { text-align: left; padding: 6px 12px; } +input, select { background: var(--input); border: 1px solid #2a3449; border-radius: 7px; padding: 6px 8px; font: inherit; color: var(--text); min-width: 0; } +input:focus, select:focus { border-color: var(--accent); outline: none; } input:disabled { color: var(--faint); } +input[type=number] { width: 86px; } input[type=search] { width: 240px; } input[type=checkbox] { accent-color: #0ea5e9; width: 16px; height: 16px; margin: 0; } +.check { display: inline-flex; gap: 7px; align-items: center; white-space: nowrap; } +.form { display: grid; grid-template-columns: auto 1fr; gap: 9px 14px; align-items: center; } .form > div:nth-child(odd) { color: var(--muted); white-space: pre; } +.form .row { gap: 7px; white-space: nowrap; min-width: 0; } .form input[type=number] { width: 68px; } +.form input:not([type=number], [type=checkbox]), .form select { flex: 1; } +dialog { background: var(--bg); color: var(--text); border: 1px solid var(--border); border-radius: 14px; padding: 20px 24px; min-width: 380px; max-width: 92vw; } +dialog::backdrop { background: rgba(0, 0, 0, .55); } dialog.wide { width: 720px; } +dialog[open] { display: flex; flex-direction: column; gap: 14px; } dialog > .row:last-child { justify-content: flex-end; } +.menu { position: fixed; z-index: 9; background: var(--panel); border: 1px solid #2a3449; border-radius: 8px; padding: 6px; display: flex; flex-direction: column; box-shadow: 0 8px 24px rgba(0, 0, 0, .5); } +.menu button { background: none; border: none; text-align: left; font-weight: 400; padding: 7px 22px; border-radius: 5px; } .menu button:hover { background: var(--select); } +.menu hr { border: none; border-top: 1px solid var(--border); margin: 4px 8px; } +.toast { position: fixed; right: 20px; bottom: 20px; z-index: 10; background: #3a1820; border: 1px solid var(--red); border-radius: 8px; padding: 10px 14px; max-width: 480px; } +.badge { background: var(--red); color: #fff; border-radius: 9px; padding: 1px 7px; font-size: 11px; font-weight: 700; } +.chip { background: #1f2a40; color: #b9c3d8; padding: 2px 9px; border-radius: 4px; white-space: nowrap; } +.dot { width: 10px; height: 10px; border-radius: 50%; flex: none; } +.track { height: 4px; border-radius: 2px; background: var(--grid); overflow: hidden; } .track i { display: block; height: 100%; border-radius: 2px; } + +/* sidebar */ +aside { width: 260px; flex: none; background: #10151f; border-right: 1px solid #1f2738; padding: 18px 12px 14px; display: flex; flex-direction: column; gap: 6px; } +.brand { display: flex; gap: 10px; align-items: center; margin-bottom: 14px; } .brand img { width: 34px; } .brand b { font-size: 16px; font-weight: 800; display: block; } +.nav { text-align: left; padding: 10px 14px; border: none; background: none; font-size: 14px; display: flex; justify-content: space-between; } +.nav:hover { background: var(--card); } .nav.on { background: var(--select); color: #7dd3fc; } +aside > .section { margin: 12px 0 0 8px; } +.list { overflow-y: auto; } .item { padding: 8px 10px; border-radius: 8px; cursor: pointer; } .item:hover { background: var(--card); } .item.sel { background: var(--select); } +.item b { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.mini { display: flex; align-items: center; margin: 3px 0 0 20px; } .mini small { width: 30px; font-size: 9px; color: var(--faint); } .mini .track { flex: 1; } + +/* pages */ +main { flex: 1; min-width: 0; } main > section { height: 100%; padding: 22px 28px 18px; display: flex; flex-direction: column; gap: 14px; } +.tiles { display: grid; gap: 14px; } +.tile { background: linear-gradient(135deg, var(--card), var(--panel)); border: 1px solid var(--border); border-radius: 12px; padding: 12px 14px 12px 16px; min-height: 84px; position: relative; display: flex; flex-direction: column; gap: 2px; min-width: 0; } +.tile::before { content: ""; position: absolute; left: 0; top: 14px; bottom: 14px; width: 4px; border-radius: 2px; background: var(--stripe); } +.tile b { font-size: 21px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .tile .section, .tile small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.cv { position: relative; min-width: 0; } .cv canvas { position: absolute; inset: 0; width: 100%; height: 100%; } +.chart { height: 240px; padding: 0; } .gauge { height: 190px; } .gauges { flex-direction: row; } .gauges .gauge { flex: 1; height: auto; aspect-ratio: 17 / 19; max-height: 210px; } +.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 16px; padding-right: 6px; } +.card { background: linear-gradient(var(--card), var(--panel)); border: 1px solid var(--border); border-radius: 14px; padding: 14px 16px 12px; height: 262px; cursor: pointer; position: relative; overflow: hidden; + display: flex; flex-direction: column; gap: 8px; } +.card::before { content: ""; position: absolute; left: 0; right: 0; top: 0; height: 6px; background: linear-gradient(90deg, var(--status), transparent 60%); } +.card:hover { border-color: var(--accent); background: linear-gradient(#20293f, var(--panel)); } +.card .dot { background: var(--status); align-self: flex-start; margin-top: 7px; } .card b { font-size: 16px; } .card b, .card small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.card .chip { color: var(--status); background: color-mix(in srgb, var(--status) 16%, transparent); border: 1px solid var(--status); border-radius: 10px; font-size: 10px; font-weight: 700; text-transform: uppercase; } +.grade { width: 44px; height: 44px; flex: none; } .rings { flex: 1; } +.foot { font-size: 11px; color: var(--muted); min-height: 32px; } .foot .row { gap: 14px; } .warn { border-radius: 8px; padding: 0 7px; } +.card.add { border: 1.5px dashed var(--border); background: none; align-items: center; justify-content: center; gap: 4px; color: var(--muted); } +.card.add::before { display: none; } .card.add i { font: 300 44px/1 system-ui; } .card.add b { font-size: 14px; } .card.add:hover { color: var(--accent); background: rgba(56, 189, 248, .07); } +.events { overflow-y: auto; flex: 1; min-height: 0; } .events div { padding: 6px 2px; border-bottom: 1px solid #1f2738; overflow-wrap: anywhere; } + +/* tables */ +.table { background: #131929; border: 1px solid var(--line); border-radius: 10px; overflow: auto; } +table { border-collapse: collapse; width: 100%; } th, td { padding: 0 8px; height: 30px; text-align: left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 520px; } +th { position: sticky; top: 0; z-index: 1; background: #182033; color: var(--muted); font-size: 12px; border-bottom: 1px solid var(--border); user-select: none; } +th[data-sort]::after { content: attr(data-sort); color: var(--accent); } +tbody tr:nth-child(even) { background: #161d2e; } tbody tr.sel { background: var(--select); } td.r { text-align: right; } +.bar { position: relative; height: 16px; min-width: 90px; border-radius: 4px; background: var(--grid); overflow: hidden; } +.bar i { position: absolute; left: 0; top: 0; bottom: 0; border-radius: 4px; } .bar span { position: relative; display: block; text-align: center; font-size: 11px; font-weight: 700; line-height: 16px; color: var(--text); } +.kv { width: auto; } .kv td { height: auto; padding: 3px 18px 3px 0; white-space: normal; overflow-wrap: anywhere; } .kv td:first-child { color: var(--muted); white-space: nowrap; } + +/* server page */ +.state { font-size: 12px; text-transform: uppercase; } .chips { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 6px; min-height: 22px; } +.tabbar { display: flex; flex-wrap: wrap; border-bottom: 1px solid var(--line); } +.tabbar button { background: none; border: none; border-bottom: 2px solid transparent; border-radius: 0; color: var(--muted); padding: 9px 13px; } +.tabbar button:hover { color: var(--text); } .tabbar button.on { color: #7dd3fc; border-bottom-color: var(--accent); background: none; } +.tab { height: 100%; padding: 8px 4px 0; } .tab.scroll { display: flex; flex-direction: column; gap: 16px; padding-right: 10px; } .tab.scroll > * { flex: none; } +.tab.col > .table { flex: 1; min-height: 0; } .tab.col > .table + .table { flex: none; max-height: 160px; } .tab > .row, .tab .row.top { gap: 14px; } .tab > .row { flex-wrap: wrap; } +.seg { display: flex; height: 14px; border-radius: 7px; background: var(--grid); overflow: hidden; } .legend { display: flex; flex-wrap: wrap; gap: 4px 22px; margin-top: 8px; color: var(--muted); font-size: 11px; white-space: pre; } +.legend i { display: inline-block; width: 9px; height: 9px; border-radius: 2px; margin-right: 6px; } +.cores { display: grid; grid-template-columns: repeat(auto-fill, minmax(86px, 1fr)); gap: 6px; } +.cores > div { border: 1px solid; border-radius: 8px; padding: 5px 8px 6px; } .cores small { display: flex; justify-content: space-between; font-size: 10px; } .cores b { font-size: 16px; display: block; margin: 1px 0 5px; } +.heat { display: grid; grid-template-columns: 34px repeat(24, 1fr); gap: 3px; position: relative; } .heat i { height: 24px; border-radius: 3px; } .heat small { font-size: 10px; align-self: center; white-space: nowrap; } +.heat p { position: absolute; inset: 30% 12%; display: grid; place-items: center; background: rgba(13, 17, 28, .8); } +.finding { display: flex; gap: 12px; align-items: center; background: var(--card); border: 1px solid var(--border); border-left: 4px solid; border-radius: 10px; padding: 10px 14px; } +.finding small { font-weight: 700; text-transform: uppercase; display: block; } .finding b { font-size: 14px; font-weight: 600; } +.console { flex: 1; min-height: 0; overflow: auto; background: #080b12; color: #cfe3ff; border-radius: 10px; padding: 10px; white-space: pre-wrap; overflow-wrap: anywhere; } +.console .cmd { margin-top: 12px; } .console .cmd b, .prompt { color: var(--accent); } .console .good { color: var(--green); } .console .bad { color: var(--red); } .prompt { font-size: 15px; } +.log { margin: 0; height: 60vh; overflow: auto; background: #080b12; color: #cfe3ff; border-radius: 10px; padding: 10px; font-size: 12px; } diff --git a/Server Monitor(web-linux)/run.sh b/Server Monitor(web-linux)/run.sh new file mode 100755 index 0000000000000000000000000000000000000000..a7af30000d198f0ddc1aa05c8f277628b5754169 --- /dev/null +++ b/Server Monitor(web-linux)/run.sh @@ -0,0 +1,6 @@ +#!/bin/sh +# Starts Server Monitor (web) and opens the page. Another port: PORT=9000 ./run.sh +cd "$(dirname "$0")" || exit 1 +export PORT="${PORT:-8765}" +(sleep 1; xdg-open "http://127.0.0.1:$PORT" >/dev/null 2>&1) & +exec node server.js diff --git a/Server Monitor(web-linux)/server.js b/Server Monitor(web-linux)/server.js new file mode 100644 index 0000000000000000000000000000000000000000..8d4e3a602a8ad92678088bc6c2811c788a2c0048 --- /dev/null +++ b/Server Monitor(web-linux)/server.js @@ -0,0 +1,155 @@ +// Server Monitor (web): HTTP server for the page, live updates over Server-Sent Events and a small JSON API. +// Only reachable from this computer; see README.md for the security model. +const http = require('http'), fs = require('fs'), path = require('path'); +const plat = require('./core/platform'), model = require('./core/model'); +const { Manager, testConnection } = require('./core/session'); +const { I, TIERS, STEP, stats, nowSec } = require('./core/history'); +const { Fmt, H } = require('./public/shared'); + +const PORT = +process.env.PORT || 8765, ORIGINS = [`127.0.0.1:${PORT}`, `localhost:${PORT}`]; +const PUBLIC = path.join(__dirname, 'public'), MIME = { html: 'text/html', js: 'text/javascript', css: 'text/css', svg: 'image/svg+xml' }; +const FILES = Object.fromEntries(fs.readdirSync(PUBLIC).map(f => ['/' + f.replace(/^index\.html$/, ''), f])); +const HEADERS = { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Cross-Origin-Resource-Policy': 'same-origin', + 'Content-Security-Policy': "default-src 'self'; frame-ancestors 'none'" }; +const mgr = new Manager(); + +const fail = (message, status = 400) => { throw Object.assign(new Error(message), { status }); }; +const sess = id => mgr.session(id) || fail('unknown server', 404); +const send = (res, status, body, type = 'application/json', extra) => + res.writeHead(status, { ...HEADERS, 'Content-Type': type + '; charset=utf-8', ...extra }).end(type === 'application/json' ? JSON.stringify(body) : body); + +// ---- what the page sees ---- +const SUMMARY = ['hostname', 'os', 'kernel', 'cpuCount', 'memTotal', 'cpuUsage', 'memPct', 'maxDiskPct', 'swapPct', 'maxTemp', 'netRxBps', 'netTxBps', 'load1', 'uptime']; +const summary = s => ({ // sidebar row, dashboard card and detail header of one server + cfg: model.forPage(s.cfg), address: model.address(s.cfg), status: s.status, err: s.err, paused: s.paused, online: s.online, alerts: s.activeAlerts(), + m: { ...Object.fromEntries(SUMMARY.map(k => [k, s.m[k]])), procs: s.m.procs.length, temps: s.m.temps.length }, + health: s.an.health, grade: s.an.grade, findings: s.an.findings.map(f => f.severity), spark: [0, 5].map(k => s.live.slice(-150).map(r => r.v[k])), // CPU, memory +}); +const servers = () => mgr.sessions.map(summary); +const snapshot = () => ({ plat: plat.ui, dir: mgr.dir, rule: model.RULE, defaultRules: model.defaultRules(), alerts: mgr.alerts, servers: servers() }); +const sample = (s, row) => ({ m: s.m, vals: model.metricValues(s.m), row }); + +// the stored points of a range (seconds back from now, 0 = everything) in the finest tier that covers it +function points(s, range) { + const now = nowSec(), from = +range ? now - range : Math.max(1, s.store.firstTs()), tier = s.store.tierFor(from, now); + return { now, from, tier, pts: s.store.range(from, now, tier) }; +} + +// History tab: chart series with gaps where nothing was recorded, statistics per metric +const SERIES = ['cpu', 'cpuMax', 'mem', 'swap', 'disk', 'rd', 'wr', 'rx', 'tx', 'rxMax', 'load', 'temp', 'tempMax', 'avail']; +function history(s, range) { + const { now, from, tier, pts } = points(s, range), step = Math.max(STEP[tier], s.cfg.interval), t = [], v = Object.fromEntries(SERIES.map(k => [k, []])); + const online = p => p.n ? p.nUp * 100 / p.n : 0, r2 = x => Math.round(x * 100) / 100; + let n = 0, up = 0; + const push = (ts, p) => { // p = null inserts a gap + t.push(ts * 1000); + for (const k of SERIES) v[k].push(!p ? null : k === 'avail' ? r2(online(p)) : !p.nUp ? null : r2((k.endsWith('Max') ? p.max : p.avg)[I[k.replace('Max', '')]])); + }; + for (const p of pts) { + if (t.length && p.ts * 1000 - t.at(-1) > step * 3000) push(t.at(-1) / 1000 + step, null); // the monitor was not running + push(p.ts, p), n += p.n, up += p.nUp; + } + if (t.length && now * 1000 - t.at(-1) > step * 3000) push(now, null); + return { t, v, tier: TIERS[tier], aggregated: tier > 0, span: (now - from) * 1000, points: pts.length, availability: n ? up * 100 / n : null, + bytes: s.store.diskBytes(), stats: H.map((_, m) => stats(pts, m)) }; +} +function csv(s, range) { + const num = x => isNaN(x) ? '' : x.toFixed(3), online = p => p.n ? p.nUp * 100 / p.n : 0; + return ['time,samples,online_pct' + H.map(k => `,${k}_avg,${k}_max`).join(''), + ...points(s, range).pts.map(p => [Fmt.iso(p.ts * 1000), p.n, Fmt.num(online(p)), ...H.flatMap((_, m) => [num(p.avg[m]), num(p.max[m])])].join(','))].join('\n'); +} + +// ---- live updates: one stream per page (browsers allow six connections per site) with the server list and events, +// plus the samples of the server whose id the page asked for ---- +const clients = new Set(); +function cast(id, event, make) { + let msg; + for (const c of clients) { + if (id && c.id !== id) continue; + if (c.res.writableLength > 8 << 20) c.res.destroy(); // the client stopped reading: drop it instead of buffering for ever (the page reconnects) + else c.res.write(msg ??= `event: ${event}\ndata: ${JSON.stringify(make())}\n\n`); + } +} +function subscribe(res, id) { + const c = { id, res }, s = mgr.session(id); + res.writeHead(200, { ...HEADERS, 'Content-Type': 'text/event-stream' }); + res.write(`event: hello\ndata: ${JSON.stringify(snapshot())}\n\n` + (s ? `event: live\ndata: ${JSON.stringify({ ...sample(s), rows: s.live, an: s.an })}\n\n` : '')); + clients.add(c), res.on('close', () => clients.delete(c)); +} +let dirty = false; // the server list goes out at most once a second +const pushState = () => (dirty = false, cast('', 'state', servers)); +setInterval(() => dirty && pushState(), 1000); +mgr.on('updated', () => dirty = true); +mgr.on('sample', (s, row) => (dirty = true, cast(s.cfg.id, 'sample', () => sample(s, row)))); +mgr.on('analysis', s => (dirty = true, cast(s.cfg.id, 'analysis', () => s.an))); +mgr.on('alert', e => cast('', 'alert', () => e)); + +// ---- API ---- +// a config sent by the page, on top of the stored one; an empty password keeps the stored password +function config(b) { + const old = b.id ? sess(b.id).cfg : {}, c = model.make({ ...old, ...b }, b.clearPassword ? '' : String(b.password || old.password || '')); + if (!c.name || (c.transport && !c.host)) fail('Please enter a name and an address.'); + if (c.host.startsWith('-') || c.user.startsWith('-')) fail('Address and user must not start with "-".'); + return c; +} +const GET = { + '/api/state': () => snapshot(), + '/api/history': q => history(sess(q.id), q.range), + '/api/history.csv': (q, res) => send(res, 200, csv(sess(q.id), q.range), 'text/csv', { 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(sess(q.id).cfg.name)}-history.csv` }), + '/api/alerts.log': (q, res) => send(res, 200, fs.readFileSync(path.join(mgr.dir, 'alerts.log'), { flag: 'a+' }), 'text/plain', { 'Content-Disposition': 'attachment; filename="alerts.log"' }), + '/api/events': (q, res) => subscribe(res, q.id), +}; +const POST = { // every handler gets the JSON body; servers are addressed by b.id + '/api/server/add': b => { const c = config({ ...b, id: '' }); mgr.add(c); return { id: c.id }; }, + '/api/server/update': b => mgr.update(config({ ...b, id: sess(b.id).cfg.id })), + '/api/server/remove': b => mgr.remove(sess(b.id).cfg.id, !!b.deleteHistory), + '/api/server/move': b => mgr.move(b.id, b.delta < 0 ? -1 : 1), + '/api/server/test': b => testConnection(config(b)), + '/api/server/reconnect': b => sess(b.id).reconnect(), + '/api/server/pause': b => sess(b.id).setPaused(!!b.paused), + '/api/server/analyze': b => sess(b.id).analyzeNow(), + '/api/exec': b => sess(b.id).exec(String(b.cmd), !!b.privileged, 120000), // console + '/api/run': b => { // a process / priority / service action from the platform tables; b.arg = pid or service name + const tpl = ['procActions', 'priorities', 'serviceActions'].includes(b.list) && plat.ui[b.list][b.i]?.cmd || fail('unknown command'); + if (tpl.includes('{n}') && !(/^\d+$/.test(b.arg) && +b.arg > 0)) fail('not a process id'); // pid 0 or -1 would address whole process groups + const cmd = tpl.replace('{n}', +b.arg).replace('{q}', () => plat.quote(String(b.arg))); + return sess(b.id).exec(cmd, true).then(r => ({ ...r, cmd })); + }, + '/api/logs': b => sess(b.id).exec(plat.serviceLogs(String(b.unit), Math.min(5000, Math.max(50, parseInt(b.lines) || 300))), true), + '/api/power': b => sess(b.id).exec(plat.power(!!b.reboot), true), + '/api/finding': b => { const s = sess(b.id); return s.runFinding(s.an.findings.find(f => f.key === b.key) || fail('this finding is gone', 404), false); }, + '/api/alerts/clear': () => (mgr.alerts = [], cast('', 'alerts', () => [])), +}; + +function body(req) { // JSON object, at most 1 MB + return new Promise((resolve, reject) => { + let s = ''; + req.setEncoding('utf8').on('data', d => (s += d).length > 1 << 20 && req.destroy()).on('error', reject).on('end', () => { + try { resolve(Object(JSON.parse(s))); } catch { reject(Object.assign(new Error('invalid JSON'), { status: 400 })); } + }); + }); +} + +http.createServer(async (req, res) => { + try { + const url = new URL(req.url, 'http://x'), route = url.pathname, origin = req.headers.origin; + // DNS rebinding: the browser must have addressed this computer by name; other sites cannot send the header or read replies (no CORS) + if (!ORIGINS.includes(req.headers.host) || (origin && !ORIGINS.includes(origin.replace('http://', '')))) return send(res, 403, { error: 'forbidden host or origin' }); + if (req.method === 'GET') { + if (FILES[route]) return send(res, 200, fs.readFileSync(path.join(PUBLIC, FILES[route])), MIME[path.extname(FILES[route]).slice(1)]); + const r = GET[route] ? await GET[route](Object.fromEntries(url.searchParams), res) : fail('not found', 404); + return res.headersSent || send(res, 200, r); + } + if (req.method !== 'POST' || !POST[route]) fail('not found', 404); + if (req.headers['x-sm'] !== '1' || !/^application\/json\b/.test(req.headers['content-type'])) fail('state-changing requests need Content-Type: application/json and X-SM: 1', 403); + send(res, 200, await POST[route](await body(req)) ?? { ok: true }); + pushState(); + } catch (e) { + res.headersSent ? res.end() : send(res, e.status || 500, { error: e.message }); + } +}).listen(PORT, '127.0.0.1', () => { + mgr.load(); + console.log(`Server Monitor (${plat.ui.name}) is running: http://127.0.0.1:${PORT} - config: ${mgr.dir}`); +}).on('error', e => (console.error(`Cannot listen on 127.0.0.1:${PORT} (is the monitor already running?): ${e.message}`), process.exit(1))); +process.on('exit', () => mgr.close()); // however this process ends, its child processes end with it +for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(sig, () => process.exit(0)); diff --git a/Server Monitor(web-window)/README.md b/Server Monitor(web-window)/README.md new file mode 100644 index 0000000000000000000000000000000000000000..1bc48bb948adaeac6721b0662fce5706390da454 --- /dev/null +++ b/Server Monitor(web-window)/README.md @@ -0,0 +1,75 @@ +# Server Monitor (web) — Windows edition + +Watches Windows machines in detail from a browser: this computer, and remote servers over the system `ssh` client. It keeps their history from seconds to years, analyzes it with plain statistics (no AI) and fixes common problems automatically. A small Node.js server does the monitoring; the page is plain HTML, CSS and JavaScript with hand-drawn charts and gauges. No npm packages, no build step. + +It is a port of the C++/Qt desktop app "Server Monitor" and uses the same `servers.json` schema and the same binary history files. + +## Requirements + +- Node.js 22 or newer (only built-in modules are used). +- A current browser (Edge, Chrome or Firefox). +- Windows PowerShell 5.1 or newer on every monitored machine (part of Windows). +- For remote servers: the OpenSSH client (`ssh.exe`, part of Windows 10/11 and Server 2019+) on this computer and the **OpenSSH Server** feature on the servers. Nothing else is installed there. + +## Run + +```bat +run.bat rem starts the server and opens the page +rem or +node server.js rem then open http://127.0.0.1:8765 +``` + +`set PORT=9000` before starting uses another port. Stop it with Ctrl+C. Monitoring, history, alert rules and the autopilot run as long as the server runs, with or without an open page. Up to five browser tabs can show the monitor at the same time: each tab holds one live connection and browsers allow six per site. + +## How it connects + +- **This machine:** no setup. The collector script (`core/collector.ps1`) is piped into `powershell`. +- **SSH:** the same script is piped through `ssh user@host powershell …`. Keys are recommended (add your public key to the server's `authorized_keys`); a password also works and is handed to ssh through `SSH_ASKPASS`. + +PowerShell is started with a fixed encoded command that runs whatever script arrives on standard input, so no quoting problems can occur in cmd.exe, PowerShell or ssh. The script prints counters from CIM and .NET once per interval; all calculations happen in the Node.js server. Control actions (ending processes, services, console commands, autopilot) run as the user of the monitor (or the SSH login user). There is no sudo on Windows: start the monitor from an elevated prompt, or log in as an administrator over SSH, when you need privileged actions and the owners of all processes. + +## Features + +- **Dashboard:** a live card per server (gauges, sparklines, health grade), totals, recent events, search. +- **Server tabs:** Overview, CPU (per core, temperatures, GPUs), Memory, Storage, Network, Processes (end task, kill, priority), Services (start, stop, restart, enable, disable, event log), History, Insights & Autopilot, Alert rules, Console (PowerShell). +- **History:** every sample for 6 h, 1-minute averages and peaks for 30 days, hourly for 2 years, daily for 20 years; downtime is stored too. Ranges from 1 h to all time with min / average / 95th percentile / peak and CSV export. +- **Analysis (every minute):** disk-full forecast, memory growth, per-process leaks, runaway processes, failed or flapping services, overload, swap thrashing, anomalies against the same weekday and hour, availability, capacity advice, a health score (0–100, grade A–F) and a weekly heatmap. +- **Autopilot:** acts on the findings with cooldowns and limits; **dry run** only reports what it would do. +- **Alert rules:** "CPU > 90 % for 60 s → warning → restart a service". Events go to the Events page, to `alerts.log` and, if switched on, to browser notifications. + +The load average is computed like the Unix one (busy cores + processor queue, averaged over 1, 5 and 15 minutes). A service counts as failed when it starts automatically, is stopped and ended with an error. + +## Where data is stored + +`%APPDATA%\ServerMonitorWeb`: + +- `servers.json` — servers, rules and autopilot settings. Saved SSH passwords are only lightly disguised, not encrypted, so prefer keys. +- `history\\{raw,minute,hour,day}.bin` — the history. +- `alerts.log` — every event, tab-separated; starts over at 5 MB. + +## Security model + +The page can run PowerShell commands on your servers, so the server only talks to this computer: + +- It listens on `127.0.0.1` only. For access from elsewhere use an SSH tunnel (`ssh -L 8765:127.0.0.1:8765 this-computer`). +- Requests whose `Host` header is not `127.0.0.1:` or `localhost:` are refused (DNS rebinding), and so are requests with a foreign `Origin`. +- Everything that changes state is a `POST` with `Content-Type: application/json` and the header `X-SM: 1`. No CORS headers are ever sent, so other web pages can neither send such requests nor read any reply. +- Stored SSH passwords are never sent to the browser; the page only learns that one exists. +- Data from servers is inserted into the page as text only, and a Content-Security-Policy allows scripts from this server alone. + +There is no login: every local user who can reach the port can use the monitor. Do not run it on a shared computer. + +## Code + +``` +server.js HTTP server, live updates (Server-Sent Events), JSON API +core/platform.js everything Windows-specific: shell, frame parser, command tables, texts +core/collector.ps1 collector script that runs on the monitored machine +core/metrics.js one parsed sample + parser helpers +core/model.js server config, rules +core/history.js history store + analyzer +core/session.js ssh/local link, per-server session (rules, autopilot), manager +public/ the page: index.html, style.css, app.js, shared.js (formatting used by both sides) +``` + +The Linux edition differs only in `core/platform.js`, its collector script, this README and the launcher. diff --git a/Server Monitor(web-window)/core/collector.ps1 b/Server Monitor(web-window)/core/collector.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..4b087b283517d929a2302e16b16452e5ec87ebb4 --- /dev/null +++ b/Server Monitor(web-window)/core/collector.ps1 @@ -0,0 +1,108 @@ +# Server Monitor collector for Windows (PowerShell 5.1+, ASCII only). +# The caller prepends "$iv = ; $once = $false". One frame per interval: +# "@@SNAP_BEGIN", "@@S
" + rows (key=value or |-separated), "@@SNAP_END". +$ErrorActionPreference = 'SilentlyContinue' +$ProgressPreference = 'SilentlyContinue' +[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false +function Cim($class, $ns = 'root/cimv2') { Get-CimInstance -ClassName $class -Namespace $ns } +function Clean($s) { ("$s" -replace '[|\r\n]', ' ').Trim() } +$epoch = [DateTime]'1970-01-01' +$smi = Get-Command nvidia-smi.exe | Select-Object -First 1 -ExpandProperty Path +# Console.Out reports no error when the pipe is closed, so the collector also ends when its parent process is gone. +$parent = Get-Process -Id (Get-CimInstance Win32_Process -Filter "ProcessId = $PID").ParentProcessId +$n = 0 +while ($true) { + $t0 = Get-Date + $out = New-Object System.Collections.Generic.List[string] + $out.Add('@@SNAP_BEGIN') + $os = Cim Win32_OperatingSystem + if ($n % 15 -eq 0) { + $cs = Cim Win32_ComputerSystem + $cpu = @(Cim Win32_Processor)[0] + $virt = Clean ($cs.Manufacturer + ' ' + $cs.Model) + $admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) + $out.Add('@@S info') + $out.Add("hostname=$($cs.Name)") + $out.Add("os=$(Clean $os.Caption)") + $out.Add("kernel=$($os.Version)") + $out.Add("arch=$($os.OSArchitecture)") + $out.Add("cpumodel=$(Clean $cpu.Name)") + $out.Add("mhz=$($cpu.MaxClockSpeed)") + $out.Add("virt=$virt") + $out.Add("admin=$([int]$admin)") + if ($admin) { + $out.Add('@@S users') + Get-Process -IncludeUserName | ForEach-Object { $out.Add("$($_.Id)|$($_.UserName)") } + } + } + $out.Add('@@S os') + $out.Add("ts=$([long](([DateTime]::UtcNow - $epoch).TotalMilliseconds))") + $out.Add("uptime=$([long](((Get-Date) - $os.LastBootUpTime).TotalSeconds))") + $out.Add("memtotal=$([long]$os.TotalVisibleMemorySize * 1024)") + $out.Add("swaptotal=$([long]$os.SizeStoredInPagingFiles * 1024)") + $out.Add("swapfree=$([long]$os.FreeSpaceInPagingFiles * 1024)") + $out.Add('@@S cpu') + Cim Win32_PerfFormattedData_PerfOS_Processor | ForEach-Object { + $out.Add("$($_.Name)|$($_.PercentProcessorTime)|$($_.PercentUserTime)|$($_.PercentPrivilegedTime)|$([long]$_.PercentInterruptTime + [long]$_.PercentDPCTime)|$($_.InterruptsPersec)") + } + $sys = Cim Win32_PerfFormattedData_PerfOS_System + $out.Add('@@S sys') + $out.Add("queue=$($sys.ProcessorQueueLength)") + $out.Add("ctxt=$($sys.ContextSwitchesPersec)") + $out.Add("threads=$($sys.Threads)") + $pm = Cim Win32_PerfFormattedData_PerfOS_Memory + $out.Add('@@S mem') + $out.Add("avail=$($pm.AvailableBytes)") + $out.Add("free=$($pm.FreeAndZeroPageListBytes)") + $out.Add("standby=$([long]$pm.StandbyCacheCoreBytes + [long]$pm.StandbyCacheNormalPriorityBytes + [long]$pm.StandbyCacheReserveBytes)") + $out.Add("syscache=$($pm.CacheBytes)") + $out.Add("modified=$($pm.ModifiedPageListBytes)") + $out.Add("pool=$([long]$pm.PoolPagedBytes + [long]$pm.PoolNonpagedBytes)") + $out.Add("commit=$($pm.CommittedBytes)") + $out.Add("commitlimit=$($pm.CommitLimit)") + $out.Add("pages=$($pm.PagesPersec)") + $out.Add('@@S net') + [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | ForEach-Object { + $s = $null + $s = $_.GetIPStatistics() + 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)") } + } + $ip = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties() + $out.Add('@@S tcp') + $ip.GetActiveTcpConnections() | Group-Object State | ForEach-Object { $out.Add("$($_.Name) $($_.Count)") } + $out.Add("Listen $(@($ip.GetActiveTcpListeners()).Count)") + $out.Add('@@S disk') + Cim Win32_PerfFormattedData_PerfDisk_PhysicalDisk | Where-Object { $_.Name -ne '_Total' } | ForEach-Object { + $out.Add("$(Clean $_.Name)|$($_.DiskReadBytesPersec)|$($_.DiskWriteBytesPersec)|$($_.DiskReadsPersec)|$($_.DiskWritesPersec)|$($_.PercentIdleTime)") + } + $out.Add('@@S df') + [System.IO.DriveInfo]::GetDrives() | Where-Object { $_.IsReady -and $_.DriveType -eq 'Fixed' } | ForEach-Object { + $out.Add("$($_.Name)|$(Clean $_.VolumeLabel)|$($_.DriveFormat)|$($_.TotalSize)|$($_.AvailableFreeSpace)") + } + $sessions = @{} + $out.Add('@@S procs') + Cim Win32_Process | ForEach-Object { + $born = 0 + if ($_.CreationDate) { $born = [long](($_.CreationDate.ToUniversalTime() - $epoch).TotalSeconds) } + if ($_.Name -eq 'explorer.exe') { $sessions[$_.SessionId] = 1 } + $out.Add("$($_.ProcessId)|$($_.ParentProcessId)|$([long]$_.KernelModeTime + [long]$_.UserModeTime)|$($_.Priority)|$($_.ThreadCount)|$born|$($_.VirtualSize)|$($_.WorkingSetSize)|$(Clean $_.Name)") + } + $out.Add('@@S sessions') + $out.Add("$($sessions.Count)") + if ($n % 5 -eq 0) { + $out.Add('@@S services') + Cim Win32_Service | ForEach-Object { $out.Add("$($_.Name)|$($_.State)|$($_.StartMode)|$($_.ExitCode)|$(Clean $_.DisplayName)") } + } + $out.Add('@@S thermal') + Cim MSAcpi_ThermalZoneTemperature 'root/wmi' | ForEach-Object { $out.Add("$(Clean $_.InstanceName)|$(($_.CurrentTemperature - 2732) / 10)") } + if ($smi -and $n % 3 -eq 0) { + $out.Add('@@S gpu') + & $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("$_") } + } + $out.Add('@@SNAP_END') + try { [Console]::Out.Write(($out -join "`n") + "`n"); [Console]::Out.Flush() } catch { exit } + if ($once -or $parent.HasExited) { break } + $n++ + $left = $iv * 1000 - ((Get-Date) - $t0).TotalMilliseconds + if ($left -gt 0) { Start-Sleep -Milliseconds ([int]$left) } +} diff --git a/Server Monitor(web-window)/core/history.js b/Server Monitor(web-window)/core/history.js new file mode 100644 index 0000000000000000000000000000000000000000..df6f9748dfc284cce3dfddb04aaf0d5b6b30f323 --- /dev/null +++ b/Server Monitor(web-window)/core/history.js @@ -0,0 +1,307 @@ +// Persistent multi-resolution history (raw 6 h, minute 30 d, hour 2 y, day 20 y) in the binary format every edition +// shares, and the statistics-only analyzer that feeds the autopilot. +const fs = require('fs'), path = require('path'); +const plat = require('./platform'); +const { Fmt, H, hNames, fmtMetric } = require('../public/shared'); + +const N = H.length, REC = 16 + 8 * N, I = Object.fromEntries(H.map((k, i) => [k, i])); +const HEADER = Buffer.from([...Buffer.from('SMH1'), N, 0, REC & 255, REC >> 8]); +const FILES = ['raw', 'minute', 'hour', 'day'], TIERS = ['every sample', '1 minute', '1 hour', '1 day']; +const STEP = [1, 60, 3600, 86400], KEEP = [6 * 3600, 30 * 86400, 732 * 86400, 7320 * 86400]; +const nowSec = () => Math.floor(Date.now() / 1000); +const fileSize = f => fs.statSync(f, { throwIfNoEntry: false })?.size || 0; + +// a point: { ts (s; bucket start for aggregates), n samples, nUp online samples, avg[N], max[N] }, NaN = no value +// file record: int64 ts, uint32 n, uint32 nUp, float32 avg[N], float32 max[N], little-endian +function encode(pts) { + const b = Buffer.alloc(pts.length * REC); + pts.forEach((p, i) => { + const o = i * REC; + b.writeBigInt64LE(BigInt(p.ts), o), b.writeUInt32LE(p.n, o + 8), b.writeUInt32LE(p.nUp, o + 12); + for (let k = 0; k < N; ++k) b.writeFloatLE(p.avg[k], o + 16 + 4 * k), b.writeFloatLE(p.max[k], o + 16 + 4 * (N + k)); + }); + return b; +} +function decode(b, o) { + const p = { ts: Number(b.readBigInt64LE(o)), n: b.readUInt32LE(o + 8), nUp: b.readUInt32LE(o + 12), avg: new Float32Array(N), max: new Float32Array(N) }; + for (let k = 0; k < N; ++k) p.avg[k] = b.readFloatLE(o + 16 + 4 * k), p.max[k] = b.readFloatLE(o + 16 + 4 * (N + k)); + return p; +} + +class Acc { // accumulates points into one bucket + constructor(bucket) { this.bucket = bucket, this.n = this.nUp = 0, this.cnt = new Float64Array(N), this.sum = new Float64Array(N), this.mx = new Float32Array(N).fill(NaN); } + add(p) { + this.n += p.n, this.nUp += p.nUp; + if (!p.nUp) return; + for (let i = 0; i < N; ++i) { + if (isNaN(p.avg[i])) continue; + this.sum[i] += p.avg[i] * p.nUp, this.cnt[i] += p.nUp; + if (isNaN(this.mx[i]) || p.max[i] > this.mx[i]) this.mx[i] = p.max[i]; + } + } + point() { return { ts: this.bucket, n: this.n, nUp: this.nUp, avg: Float32Array.from(this.sum, (s, i) => this.cnt[i] ? s / this.cnt[i] : NaN), max: this.mx.slice() }; } +} + +class HistoryStore { + constructor(dir) { this.dir = dir, this.load(); } + file(t) { return path.join(this.dir, FILES[t] + '.bin'); } + bucketOf(t, ts) { return t === 3 ? Math.floor((ts + this.tz) / 86400) * 86400 - this.tz : Math.floor(ts / STEP[t]) * STEP[t]; } // days at local midnight + + load() { + fs.mkdirSync(this.dir, { recursive: true }); + const now = nowSec(); + this.tz = -new Date().getTimezoneOffset() * 60, this.t = [[], [], [], []], this.acc = [], this.appends = [0, 0, 0, 0]; + for (let t = 0; t < 4; ++t) { + const f = this.file(t), v = this.t[t]; + if (!fileSize(f)) continue; + const d = fs.readFileSync(f); + if (!d.subarray(0, 8).equals(HEADER)) { fs.renameSync(f, f + '.old'); continue; } + let bad = (d.length - 8) % REC; // a cut-off record would misalign everything appended after it + for (let off = 8; off + REC <= d.length; off += REC) { + const p = decode(d, off); + if (p.ts < now - KEEP[t] || p.ts > now + 86400 || (v.length && p.ts <= v.at(-1).ts)) ++bad; + else v.push(p); + } + if (bad) this.rewrite(t); + } + for (let t = 1; t < 4; ++t) { // rebuild from finer data what is not stored yet: buckets the last run left open, and the current one + const stored = this.t[t].at(-1)?.ts ?? -1; + this.acc[t] = new Acc(-1); + for (const p of [...this.t[t - 1], ...(this.acc[t - 1]?.n ? [this.acc[t - 1].point()] : [])]) { + const b = this.bucketOf(t, p.ts); + if (b <= stored) continue; + if (b !== this.acc[t].bucket) { + if (this.acc[t].n) this.append(t, this.acc[t].point()); + this.acc[t] = new Acc(b); + } + this.acc[t].add(p); + } + } + } + + rewrite(t) { + const f = this.file(t); + fs.writeFileSync(f + '.tmp', Buffer.concat([HEADER, encode(this.t[t])])), fs.renameSync(f + '.tmp', f); + } + + append(t, p) { + const v = this.t[t], f = this.file(t); + if (v.length && p.ts <= v.at(-1).ts) return; + v.push(p); + try { + if (fileSize(f) < 8) fs.writeFileSync(f, HEADER); + fs.appendFileSync(f, encode([p])); + if (++this.appends[t] % 500) return; // trim expired points now and then + const keep = v.findIndex(x => x.ts >= p.ts - KEEP[t]); + if (keep > 0) v.splice(0, keep), this.rewrite(t); + } catch { /* disk full or not writable: monitoring goes on with the points in memory */ } + } + + add(ts, val, up) { // up = false records downtime only + const raw = { ts, n: 1, nUp: +up, avg: Float32Array.from(val, x => up ? x : NaN) }; + raw.max = raw.avg, this.append(0, raw); + for (let t = 1; t < 4; ++t) { // every coarser tier accumulates every raw sample + const b = this.bucketOf(t, ts); + if (this.acc[t].bucket !== b) { + if (this.acc[t].n && this.acc[t].bucket < b) this.append(t, this.acc[t].point()); + this.acc[t] = new Acc(b); + } + this.acc[t].add(raw); + } + } + + tierFor(from, to) { // finest tier covering the range + const now = nowSec(), maxSpan = [6 * 3600, 8 * 86400, 400 * 86400]; + let t = 0; + while (t < 3 && (from < now - KEEP[t] || to - from > maxSpan[t])) ++t; + return t; + } + range(from, to, t = this.tierFor(from, to)) { // includes the open bucket + const out = this.t[t].filter(p => p.ts >= from && p.ts <= to), a = this.acc[t]; + if (t && a.n && a.bucket >= from && a.bucket <= to && !(out.at(-1)?.ts >= a.bucket)) out.push(a.point()); + return out; + } + + removeFiles() { fs.rmSync(this.dir, { recursive: true, force: true }), this.load(); } + firstTs() { return Math.min(...this.t.filter(v => v.length).map(v => v[0].ts), Infinity) % Infinity || 0; } // 0 when empty + diskBytes() { return FILES.reduce((b, _, t) => b + fileSize(this.file(t)), 0); } +} + +function stats(pts, m) { // max = peak of max[] + const s = { min: NaN, avg: NaN, p95: NaN, max: NaN, count: 0 }, v = []; + let sum = 0, w = 0; + for (const p of pts) { + if (!p.nUp || isNaN(p.avg[m])) continue; + v.push(p.avg[m]), sum += p.avg[m] * p.nUp, w += p.nUp; + if (isNaN(s.max) || p.max[m] > s.max) s.max = p.max[m]; + } + if (!v.length) return s; + v.sort((a, b) => a - b); + return Object.assign(s, { count: v.length, avg: sum / w, min: v[0], p95: v[Math.min(v.length - 1, Math.floor(v.length * 0.95))] }); +} + +function regression(pts, m) { // [slope per second, R²] + let n = 0, sx = 0, sy = 0, sxx = 0, sxy = 0, syy = 0; + for (const p of pts) { + if (!p.nUp || isNaN(p.avg[m])) continue; + const x = p.ts - pts[0].ts, y = p.avg[m]; + n++, sx += x, sy += y, sxx += x * x, sxy += x * y, syy += y * y; + } + const den = n * sxx - sx * sx, num = n * sxy - sx * sy, vy = n * syy - sy * sy, ok = n >= 3 && den > 0; + return [ok ? num / den : 0, ok && vy > 1e-9 ? num * num / (den * vy) : 0]; // squared correlation +} + +const grid = fill => Array.from({ length: 7 }, () => Array(24).fill(fill)); +const blankAnalysis = () => ({ + when: 0, health: 100, grade: 'A', diskBasis: '', healthReasons: [], capacity: [], findings: [], anomalies: [], + diskFullDays: -1, diskSlopePerDay: 0, memSlopePerHour: 0, memTrendR2: 0, up: [NaN, NaN, NaN], down: [0, 0, 0], // 24 h, 7 d, 30 d: availability %, seconds offline + cpu30: stats([]), mem30: stats([]), heat: [grid(NaN), grid(NaN)], heatN: grid(0), // weekly pattern: 0 = CPU, 1 = memory +}); + +// finding.action: disk_cleanup | restart_service | renice | kill_pid; procs / svcs are the trends tracked by the session +function analyze(st, m, ap, procs, svcs, online) { + const a = blankAnalysis(), now = a.when = nowSec(), [, minute, hour] = st.t, f1 = v => Fmt.fix(v, 1), f2 = v => Fmt.fix(v, 2); + const add = (key, severity, category, title, detail, advice, action = '', actionArg = '', actionLabel = '', autoEligible = false) => + a.findings.push({ key, severity, category, title, detail, advice, action, actionArg, actionLabel, autoEligible }); + const sev = (crit, warn) => crit ? 'critical' : warn ? 'warning' : 'info'; + const localHour = ts => { const d = new Date(ts * 1000); return [(d.getDay() + 6) % 7, d.getHours()]; }; // Monday = 0 + + // availability + const spans = [86400, 7 * 86400, 30 * 86400]; + spans.forEach((s, i) => { + let n = 0, up = 0; + for (const p of st.range(now - s, now)) n += p.n, up += p.nUp; + if (n) a.up[i] = up * 100 / n, a.down[i] = (n - up) / n * Math.min(s, now - st.firstTs()); // share of the monitored part of the window + }); + if (a.up[0] < 99) + add('avail24', sev(a.up[0] < 95, true), 'Availability', `Availability last 24 h is ${Fmt.pct(a.up[0], 2)}`, + `The server could not be reached for about ${Fmt.duration(a.down[0])} in the last day.`, + 'Check network stability, power and whether the machine rebooted (uptime).'); + const w30 = st.range(now - spans[2], now, 2), long = w30.length >= 24 ? w30 : st.range(now - spans[1], now, 1); + a.cpu30 = stats(long, I.cpu), a.mem30 = stats(long, I.mem); + + // disk forecast: regression over 7 d of hours, or 24 h of minutes, whichever fits better + const week = st.range(now - spans[1], now, 2), day = st.range(now - 86400, now, 1); + let [slope, r2] = [0, 0]; + if (week.length >= 48) [slope, r2] = regression(week, I.disk), a.diskBasis = 'hourly averages, last 7 days'; + if (day.length >= 120) { + const [s2, r2b] = regression(day, I.disk); + if (week.length < 48 || r2b > r2) slope = s2, r2 = r2b, a.diskBasis = 'minute averages, last 24 hours'; + } + a.diskSlopePerDay = slope * 86400; + if (a.diskSlopePerDay > 0.05 && r2 >= 0.3 && m.maxDiskPct > 0) a.diskFullDays = (100 - m.maxDiskPct) / a.diskSlopePerDay; + if (a.diskFullDays >= 0 && a.diskFullDays < 30) + add('diskfull', sev(a.diskFullDays < ap.diskForecastDays, a.diskFullDays < 14), 'Disk', `Disk ${m.fullestMount} will be full in ${Fmt.duration(a.diskFullDays * 86400)}`, + `Usage ${Fmt.pct(m.maxDiskPct)}, growing ${f2(a.diskSlopePerDay)} points/day (trend from ${a.diskBasis}, fit R² ${f2(r2)}).`, + 'Clean logs/caches, rotate or move data, or grow the volume.', 'disk_cleanup', '', 'Run cleanup', ap.diskCleanup && a.diskFullDays < ap.diskForecastDays); + if (m.maxDiskPct >= ap.diskCleanupAt) + add('diskhigh', sev(m.maxDiskPct >= 97, true), 'Disk', `Disk ${m.fullestMount} is ${Fmt.pct(m.maxDiskPct)} full`, + `Above the cleanup threshold of ${Fmt.pct(ap.diskCleanupAt, 0)}.`, 'Free space soon: services fail when the disk is full.', + 'disk_cleanup', '', 'Run cleanup', ap.diskCleanup); + + // whole-machine memory trend over 6 h + const six = st.range(now - 6 * 3600, now, 1); + if (six.length >= 90) { + const [s, fit] = regression(six, I.mem), left = (100 - m.memPct) / Math.max(0.01, s * 3600); + a.memSlopePerHour = s * 3600, a.memTrendR2 = fit; + if (a.memSlopePerHour > 1 && fit > 0.8 && m.memPct > 40) + add('memtrend', sev(false, left < 12), 'Memory', `Memory keeps growing (+${f1(a.memSlopePerHour)} points/hour)`, + `Steady growth over 6 h (R² ${f2(fit)}). At this rate memory is exhausted in about ${Fmt.duration(left * 3600)}.`, + 'Look for a leaking process (Processes tab, sort by RSS).'); + } + + // processes: leaks and runaways + for (const p of procs) { + if (p.kernel) continue; + const who = `${p.name} (PID ${p.pid})`, pid = String(p.pid), term = ap.runawayMode === 'terminate'; + if (p.minutesTracked >= 30 && p.rssGrowthPct >= 25 && p.rssGrowth >= 100e6 && p.rssMonotonic >= 0.8) + add('leak:' + pid, sev(m.memPct >= ap.leakMemPressure, true), 'Process', 'Possible memory leak: ' + who, + `RSS grew ${Fmt.bytes(p.rssGrowth)} (+${Fmt.pct(p.rssGrowthPct, 0)}) in ${p.minutesTracked} min and rose in ${Math.round(p.rssMonotonic * 100)}% of the minutes; now ${Fmt.bytes(p.rssNow)}.`, + 'Restart the program/service at a quiet time and report the leak upstream.', 'kill_pid', pid, 'Terminate', + ap.leakMode === 'terminate' && m.memPct >= ap.leakMemPressure); + if (p.highCpuMinutes >= ap.runawayMinutes) + add('runaway:' + pid, 'warning', 'Process', 'Runaway process: ' + who, + `Above ${Fmt.pct(ap.runawayCpu, 0)} CPU for ${Math.round(p.highCpuMinutes)} min (now ${Fmt.pct(p.cpuNow)}, user ${p.user}).`, + 'Lower its priority (renice) or stop it if it is stuck.', term ? 'kill_pid' : 'renice', pid, term ? 'Terminate' : 'Renice to 19', ap.runawayMode !== 'none'); + } + + // services: failures and flapping + for (const s of svcs) { + const flap = s.failsLastHour >= 3 || s.autoRestartsLastHour >= ap.maxRestartsPerHour; + if (s.failedNow) + add('svc:' + s.unit, sev(flap, true), 'Service', `Service ${s.unit} ${flap ? 'keeps failing' : 'has failed'}`, + s.preexisting ? 'It was already failed when monitoring started, so the autopilot leaves it alone (it may be failed on purpose).' + : `Failed ${s.failsLastHour}× in the last hour; autopilot restarted it ${s.autoRestartsLastHour}×.`, + flap ? 'Automatic restarts were stopped. Read the logs (Services tab → Logs) and fix the cause.' : 'Restart it and check the logs.', + 'restart_service', s.unit, 'Restart', ap.restartFailed && !s.preexisting && s.autoRestartsLastHour < ap.maxRestartsPerHour); + else if (s.failsLastHour >= 3) + add('flap:' + s.unit, 'warning', 'Service', `Service ${s.unit} is unstable`, `It failed ${s.failsLastHour} times within the last hour.`, 'Inspect its logs and resource limits.'); + } + + // overload and swap thrashing (without an I/O wait counter: memory full now + busy disks) + const last15 = st.range(now - 900, now, 1), avg15 = k => stats(last15, I[k]).avg, load15 = avg15('load'), perCore = load15 / m.cpuCount; + if (online && perCore > 1.5) + add('load', sev(perCore > 3, true), 'CPU', `CPU is overloaded (load ${f1(load15)} on ${m.cpuCount} cores)`, + `15-minute average load is ${f1(perCore)}× the number of cores; tasks are waiting for CPU.`, 'Find the busiest processes, spread work over time, or add CPU.'); + if (online && m.swapPct > 50 && (plat.ui.posixCpu ? avg15('iowait') > 20 : m.memPct > 90 && avg15('diskio') > 50)) + add('thrash', 'critical', 'Memory', 'Swap thrashing', plat.ui.posixCpu ? `Swap ${Fmt.pct(m.swapPct)} used and CPU waits on I/O ${Fmt.pct(avg15('iowait'))} of the time.` + : `Swap ${Fmt.pct(m.swapPct)} used, memory ${Fmt.pct(m.memPct)} full and disks ${Fmt.pct(avg15('diskio'))} busy.`, 'Stop memory-hungry processes or add RAM.'); + + // anomalies: last 10 min vs same weekday+hour over 8 weeks (fallback: last 24 h) + const raw = st.range(now - 600, now, 0), [today, thisHour] = localHour(now); + for (const [k, floor, down] of [['cpu', 5], ['mem', 3], ['load', 0.25 * Math.max(1, m.cpuCount)], ['iowait', 3], ['rx', 256e3, true], ['tx', 256e3, true]]) { + if (!online || raw.length < 10 || (k === 'iowait' && !plat.ui.posixCpu)) continue; + const hm = I[k], cur = stats(raw, hm).avg, ok = p => p.nUp && !isNaN(p.avg[hm]), name = hNames[hm]; + let basis = 'same weekday & hour, last 8 weeks'; + let v = hour.filter(p => ok(p) && now - p.ts < 56 * 86400 && now - p.ts > 3600 && localHour(p.ts).join() === [today, thisHour].join()); + if (v.length < 3) { + v = minute.filter(p => ok(p) && now - p.ts <= 86400 && now - p.ts > 900), basis = 'last 24 hours'; + if (v.length < 360) continue; + } + const mean = v.reduce((s, p) => s + p.avg[hm] / v.length, 0), sd = Math.sqrt(v.reduce((s, p) => s + (p.avg[hm] - mean) ** 2 / v.length, 0)); + const z = (cur - mean) / Math.max(sd, floor), hi = z >= ap.anomalyZ, lo = down && mean > 1e6 && cur < mean * 0.1; + a.anomalies.push({ metric: name, baseline: basis, hm, now: cur, mean, sd, z }); + if (ap.anomalyAlerts && (hi || lo)) + add('anomaly:' + k, sev(false, z >= ap.anomalyZ * 2), 'Anomaly', `Unusually ${hi ? 'high' : 'low'} ${name.toLowerCase()}`, + `Last 10 min ${fmtMetric(hm, cur)}, usually ${fmtMetric(hm, mean)} ± ${fmtMetric(hm, sd)} (${basis}); ${f1(z)}σ.`, + hi ? 'Check what changed: deploys, cron jobs, traffic, attacks.' : 'Traffic dropped sharply - check the service is still serving.'); + } + + // weekly heatmaps from 4 weeks of hours + const sum = [grid(0), grid(0)]; + for (const p of hour) { + if (now - p.ts > 28 * 86400 || !p.nUp || isNaN(p.avg[I.cpu])) continue; + const [d, h] = localHour(p.ts), n = ++a.heatN[d][h]; + sum[0][d][h] += p.avg[I.cpu], sum[1][d][h] += p.avg[I.mem] || 0; + a.heat[0][d][h] = sum[0][d][h] / n, a.heat[1][d][h] = sum[1][d][h] / n; + } + + // capacity advice + for (const [s, name, lo, hi, loTxt, hiTxt] of [[a.cpu30, 'CPU', 15, 80, 'is mostly idle', 'is often saturated - add cores or move work away'], + [a.mem30, 'Memory', 30, 85, 'is under-used', 'is tight - add RAM or reduce caches/limits']]) + if (s.count >= 60) a.capacity.push(`${name} ${s.p95 < lo ? loTxt : s.p95 > hi ? hiTxt : 'headroom is healthy'} (p95 ${Fmt.pct(s.p95)}).`); + if (a.diskFullDays >= 0) a.capacity.push(`Disk grows ${f2(a.diskSlopePerDay)} points/day - full in about ${Fmt.duration(a.diskFullDays * 86400)}.`); + else if (a.diskBasis) a.capacity.push('Disk usage is stable.'); + if (!a.capacity.length) a.capacity.push('Collecting history - capacity advice appears after about an hour of data.'); + + // health score + let score = 100; + const pen = (when, p, why) => { if (when && p > 0.5) score -= p, a.healthReasons.push(`−${Math.round(p)} ${why}`); }; + const cpu15 = avg15('cpu'), cpu = isNaN(cpu15) ? m.cpuUsage : cpu15; + const fp = a.findings.reduce((s, f) => s + (f.category === 'Availability' ? 0 : f.severity === 'critical' ? 15 : f.severity === 'warning' ? 7 : 2), 0); + pen(!online, 60, 'server unreachable'); + pen(cpu > 70, Math.min(24, (cpu - 70) * 0.8), `CPU busy (${Fmt.pct(cpu)})`); + pen(m.memPct > 80, Math.min(30, (m.memPct - 80) * 1.5), `memory high (${Fmt.pct(m.memPct)})`); + pen(m.maxDiskPct > 80, Math.min(40, (m.maxDiskPct - 80) * 2), `disk high (${Fmt.pct(m.maxDiskPct)})`); + pen(m.swapPct > 50, 10, 'heavy swap use'); + pen(m.maxTemp > 80, Math.min(20, (m.maxTemp - 80) * 2), `hot (${Fmt.temp(m.maxTemp)})`); + pen(a.up[0] < 100, Math.min(30, (100 - a.up[0]) * 5), 'downtime in last 24 h'); + pen(true, Math.min(50, fp), `${a.findings.length} finding(s)`); + a.health = Math.min(100, Math.max(0, Math.round(score))); + a.grade = 'FDCBA'[a.health >= 90 ? 4 : a.health >= 75 ? 3 : a.health >= 60 ? 2 : a.health >= 40 ? 1 : 0]; + const rank = f => ['critical', 'warning'].indexOf(f.severity) & 3; // critical 0, warning 1, others 3 + a.findings.sort((x, y) => rank(x) - rank(y)); + return a; +} + +module.exports = { I, TIERS, STEP, HistoryStore, stats, analyze, blankAnalysis, nowSec }; diff --git a/Server Monitor(web-window)/core/metrics.js b/Server Monitor(web-window)/core/metrics.js new file mode 100644 index 0000000000000000000000000000000000000000..c4f93fce8636f1ec3b8022e45107f510acff2db8 --- /dev/null +++ b/Server Monitor(web-window)/core/metrics.js @@ -0,0 +1,77 @@ +// One parsed sample (Metrics) and the frame helpers shared by the platform parsers. +const num = s => +s || 0; +const ZERO = ('cpuCount loggedUsers procsRunning procsBlocked threadsTotal socketsUsed servicesFailed servicesRunning uptime load1 load5 load15 ' + + 'cpuUsage cpuUser cpuSystem cpuIowait cpuSteal cpuIrq ctxtPerSec intrPerSec forksPerSec avgMhz memTotal memFree memAvailable memUsed buffers cached ' + + 'shared slab dirty swapTotal swapUsed memPct swapPct diskReadBps diskWriteBps maxDiskPct maxDiskUtil netRxBps netTxBps maxTemp').split(' '); + +const blank = now => ({ + valid: false, timestamp: now, hostname: '', os: '', kernel: '', arch: '', cpuModel: '', virt: '', fullestMount: '', busiestDisk: '', + ...Object.fromEntries(ZERO.map(k => [k, 0])), cores: [], mounts: [], disks: [], nets: [], tcp: {}, procs: [], services: [], temps: [], gpus: [], +}); + +// "@@S
" + rows -> { section: [rows] } +function sections(frame) { + const sec = {}; + let cur; + for (const raw of frame.split('\n')) { + const l = raw.replace(/\r$/, ''); + if (l.startsWith('@@S ')) cur = sec[l.slice(4).trim()] ??= []; + else if (cur && l && !l.startsWith('@@')) cur.push(l); + } + return sec; +} + +const kv = (lines = [], into = {}) => { + for (const l of lines) { + const e = l.indexOf('='); + if (e > 0) into[l.slice(0, e)] = l.slice(e + 1).trim(); + } + return into; +}; + +// per-second rates of counter vectors ("net:eth0" -> [rx, tx, ...]); the frame's counters replace the previous ones +function rater(st, dt) { + const prev = st.ctr || {}, next = st.ctr = {}; + return (key, v) => { + const p = prev[key]; + next[key] = v; + return v.map((x, i) => dt > 0.05 && p?.length === v.length ? Math.max(0, (x - p[i]) / dt) : 0); + }; +} + +function addDisk(m, d, counted) { + if (counted) { + m.diskReadBps += d.readBps, m.diskWriteBps += d.writeBps; + if (d.util >= m.maxDiskUtil) m.maxDiskUtil = d.util, m.busiestDisk = d.name; + } + m.disks.push(d); +} + +function addMount(m, mt) { + mt.pct = mt.used + mt.avail > 0 ? mt.used * 100 / (mt.used + mt.avail) : 0; + if (mt.pct >= m.maxDiskPct) m.maxDiskPct = mt.pct, m.fullestMount = mt.mount; + m.mounts.push(mt); +} + +// what both parsers do last: derived values, sorting, cached GPU / service lists, temperatures ("name|value", value × scale = °C) +function finish(m, st, sec, tempScale) { + m.memUsed = Math.max(0, m.memTotal - m.memAvailable); + m.memPct = m.memTotal > 0 ? m.memUsed * 100 / m.memTotal : 0; + m.swapPct = m.swapTotal > 0 ? m.swapUsed * 100 / m.swapTotal : 0; + m.nets.sort((a, b) => a.virt - b.virt || (a.name < b.name ? -1 : +(a.name > b.name))); + for (const n of m.nets) if (!n.virt) m.netRxBps += n.rxBps, m.netTxBps += n.txBps; + for (const p of m.procs) p.memPct = m.memTotal > 0 ? p.rss * 100 / m.memTotal : 0, m.threadsTotal += p.threads; + m.procs.sort((a, b) => b.cpu - a.cpu || b.rss - a.rss); + if (sec.gpu) + st.gpus = sec.gpu.map(l => l.split(',').map(x => x.trim())).filter(f => f.length >= 8) + .map(f => ({ index: Math.trunc(num(f[0])), name: f[1], util: num(f[2]), memUsed: num(f[3]), memTotal: num(f[4]), temp: num(f[5]), power: num(f[6]), fan: num(f[7]) })); + m.gpus = st.gpus || [], m.services = st.services || []; + for (const s of m.services) m.servicesFailed += s.active === 'failed', m.servicesRunning += s.sub === 'running'; + for (const l of sec.thermal || []) { + const bar = l.lastIndexOf('|'), name = l.slice(0, Math.max(0, bar)).trim(), celsius = num(l.slice(bar + 1)) * tempScale; + if (bar <= 0 || celsius <= 0 || celsius > 150 || m.temps.some(t => t.name === name)) continue; + m.temps.push({ name, celsius }), m.maxTemp = Math.max(m.maxTemp, celsius); + } +} + +module.exports = { num, blank, sections, kv, rater, addDisk, addMount, finish }; diff --git a/Server Monitor(web-window)/core/model.js b/Server Monitor(web-window)/core/model.js new file mode 100644 index 0000000000000000000000000000000000000000..aaa8d29cc5b71d5e5c04eb952939b9edcbd2f701 --- /dev/null +++ b/Server Monitor(web-window)/core/model.js @@ -0,0 +1,47 @@ +// Server configuration (servers.json has the same schema in every edition), rules and the values rules look at. +const crypto = require('crypto'); +const plat = require('./platform'); + +const RULE = { id: '', metric: 'cpu', op: '>', action: 'notify', arg: '', severity: 'warning', enabled: true, value: 90, duration: 60, cooldown: 300 }; +const AUTOPILOT = { // history-driven automatic control (evaluated by the analyzer every minute) + enabled: true, dryRun: false, restartFailed: true, diskCleanup: false, anomalyAlerts: true, maxRestartsPerHour: 3, runawayMinutes: 10, diskForecastDays: 3, + runawayCpu: 90, diskCleanupAt: 92, leakMemPressure: 90, anomalyZ: 3, runawayMode: 'renice', leakMode: 'notify', diskCleanupCommand: plat.cleanup, +}; +const SERVER = { id: '', name: '', group: '', host: '', user: '', keyFile: '', notes: '', port: 22, interval: plat.ui.interval, useSudo: false, enabled: true }; + +const newId = () => crypto.randomUUID().slice(0, 12); +const defaultRules = () => [['cpu', 90, 60, 'warning'], ['mem', 90, 60, 'warning'], ['swap', 80, 120, 'warning'], ['disk', 90, 0, 'critical'], + ['temp', 85, 30, 'critical'], ['load', 150, 120, 'warning'], ['failed', 0, 0, 'warning']] + .map(([metric, value, duration, severity]) => ({ ...RULE, id: newId(), metric, value, duration, severity })); + +// the fields of `def`, taken from `o` where present and converted to the default's type (strings trimmed) +const pick = (def, o = {}) => Object.fromEntries(Object.entries(def).map(([k, d]) => [k, o[k] == null ? d + : typeof d === 'number' ? (Number.isFinite(+o[k]) ? +o[k] : d) : typeof d === 'boolean' ? !!o[k] : String(o[k]).trim()])); + +// a complete ServerConfig from any object (stored JSON or a form sent by the page); the password is kept in clear in memory +function make(o, password) { + const c = { ...pick(SERVER, o), transport: o.transport === 0 ? 0 : 1, password, autopilot: pick(AUTOPILOT, o.autopilot) }; // 0 Local, 1 SSH + c.rules = Array.isArray(o.rules) ? o.rules.map(r => pick(RULE, r)) : defaultRules(); + for (const r of c.rules) r.id ||= newId(); + c.interval = Math.min(300, Math.max(1, Math.round(c.interval))), c.id ||= newId(); + return c; +} + +const KEY = Buffer.from('ServerMonitor/obfuscation/v1'); +const xor = (s, enc) => Buffer.from(Buffer.from(s, enc ? 'utf8' : 'base64').map((b, i) => b ^ KEY[i % KEY.length])).toString(enc ? 'base64' : 'utf8'); // NOT encryption + +const gpuMax = (m, k) => Math.max(0, ...m.gpus.map(g => g[k])); + +module.exports = { + RULE, make, defaultRules, + fromJson: o => make(o, xor(String(o.password || ''), false)), + toJson: c => ({ ...c, password: xor(c.password, true) }), + forPage: c => ({ ...c, password: undefined, hasPassword: !!c.password }), // stored passwords never leave the server + address: c => c.transport === 0 ? 'this machine' : (c.user && c.user + '@') + c.host + (c.port !== 22 ? ':' + c.port : ''), + gpuMax, + metricValues: m => ({ + cpu: m.cpuUsage, iowait: m.cpuIowait, load: m.load1 * 100 / Math.max(1, m.cpuCount), mem: m.memPct, swap: m.swapPct, disk: m.maxDiskPct, + diskio: m.maxDiskUtil, temp: m.maxTemp, rx: m.netRxBps / 1e6, tx: m.netTxBps / 1e6, failed: m.servicesFailed, procs: m.procs.length, + gpu: gpuMax(m, 'util'), gputemp: gpuMax(m, 'temp'), + }), +}; diff --git a/Server Monitor(web-window)/core/platform.js b/Server Monitor(web-window)/core/platform.js new file mode 100644 index 0000000000000000000000000000000000000000..37121dbdcb6e05aa5eb50cc8f212ea2bec1100e8 --- /dev/null +++ b/Server Monitor(web-window)/core/platform.js @@ -0,0 +1,140 @@ +// Everything that depends on the operating system (Windows edition): where the config lives, how to start a shell, +// the collector script with its frame parser, the control commands and the texts the page shows for them. +// The Linux edition replaces this file and the collector script; every other file is identical. +const fs = require('fs'), os = require('os'), path = require('path'), { spawn } = require('child_process'); +const { num, blank, sections, kv, rater, addDisk, addMount, finish } = require('./metrics'); + +const collector = fs.readFileSync(path.join(__dirname, 'collector.ps1'), 'utf8'); // PowerShell 5.1+, reads CIM / .NET counters +const quote = s => "'" + s.replace(/['\u2018-\u201b]/g, '$&$&') + "'"; // PowerShell also takes typographic quotes as string ends +// PowerShell runs whatever script arrives on stdin: the encoded command is iex (@($input) -join [char]10) +const SHELL = ['powershell', '-NoLogo', '-NoProfile', '-NonInteractive', '-ExecutionPolicy', 'Bypass', '-OutputFormat', 'Text', '-EncodedCommand', + 'aQBlAHgAIAAoAEAAKAAkAGkAbgBwAHUAdAApACAALQBqAG8AaQBuACAAWwBjAGgAYQByAF0AMQAwACkA']; +const failed = "Get-CimInstance Win32_Service | Where-Object { $_.StartMode -eq 'Auto' -and $_.State -eq 'Stopped' -and $_.ExitCode -notin 0, 1077 }"; +const restartFailed = failed + ' | ForEach-Object { "restart $($_.Name)"; Start-Service -Name $_.Name }'; +const cleanup = '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'; +const events = (filter, max, columns) => `Get-WinEvent -FilterHashtable @{ LogName = ${filter} } -MaxEvents ${max} | Format-Table TimeCreated, ${columns}, Message -Wrap`; +// rows: label, command ({n} = pid, {q} = quoted name), danger, confirm, has a button +const cmds = rows => rows.map(([label, cmd, danger = false, confirm = true, button = true]) => ({ label, cmd, danger, confirm, button })); + +// ---- collector frame parser: |-separated rows in, Metrics out; `st` keeps counters between frames ---- +const VIRT = /virtual ethernet|virtualbox|vmware virtual|vethernet|loopback|pseudo|tap-|bluetooth|wan miniport|wsl|docker/i; // a VM's own NIC counts as physical +const TCP = { Established: 'ESTABLISHED', Listen: 'LISTEN', TimeWait: 'TIME_WAIT', CloseWait: 'CLOSE_WAIT' }; +const PROTECTED = new Set(['System', 'Registry', 'Memory Compression', 'smss.exe', 'csrss.exe', 'wininit.exe', 'winlogon.exe', 'services.exe', 'lsass.exe', 'svchost.exe', + 'sshd.exe', 'dwm.exe']); +const rows = lines => (lines || []).map(l => l.split('|')); + +function parse(frame, st, now) { + const sec = sections(frame), m = blank(now), info = kv(sec.info, st.info ??= {}), sys = kv(sec.os, kv(sec.sys, kv(sec.mem))), v = k => num(sys[k]); + if (sec.users) st.users = Object.fromEntries(rows(sec.users)); // only sent when the collector runs elevated + m.hostname = info.hostname || '', m.os = info.os || '', m.kernel = info.kernel || '', m.arch = info.arch || ''; + m.cpuModel = info.cpumodel || '', m.virt = info.virt || '', m.uptime = v('uptime'); + if (m.uptime <= 0) return m; + const ts = v('ts'), dt = st.ts ? Math.max(0, ts - st.ts) / 1000 : 0, rates = dt > 0.05, delta = rater(st, dt); + + // CPU: "_Total" is the machine, the other rows are cores; the load average is derived like the Unix one + const cpu = rows(sec.cpu), [, total, user, privileged, irq, interrupts] = cpu.find(r => r[0] === '_Total') || []; + m.cores = cpu.filter(r => r[0] !== '_Total').sort((a, b) => num(a[0]) - num(b[0])).map(r => ({ usage: num(r[1]), mhz: num(info.mhz) })); + m.cpuCount = Math.max(1, m.cores.length), m.avgMhz = num(info.mhz); + m.cpuUsage = num(total), m.cpuUser = num(user), m.cpuIrq = num(irq), m.cpuSystem = Math.max(0, num(privileged) - m.cpuIrq), m.intrPerSec = num(interrupts); + const busy = m.cpuUsage / 100 * m.cpuCount, instant = busy + v('queue'); + st.load = st.load ? st.load.map((l, i) => l + (instant - l) * (1 - Math.exp(-dt / [60, 300, 900][i]))) : [instant, instant, instant]; + [m.load1, m.load5, m.load15] = st.load; + m.procsRunning = Math.round(busy), m.procsBlocked = v('queue'), m.ctxtPerSec = v('ctxt'); + + // memory + m.memTotal = v('memtotal'), m.memAvailable = v('avail'), m.memFree = v('free'), m.cached = v('standby') + v('syscache'), m.slab = v('pool'), m.dirty = v('modified'); + m.swapTotal = v('swaptotal'), m.swapUsed = Math.max(0, m.swapTotal - v('swapfree')); + + // network: cumulative counters -> rates + for (const [name, status = '', speed, type, rx, tx, rxPkts, txPkts, errors, drops, description] of rows(sec.net)) { + const [rxBps, txBps, rxPps, txPps] = delta('net:' + name, [rx, tx, rxPkts, txPkts].map(num)); + m.nets.push({ name, virt: type === 'Loopback' || type === 'Tunnel' || VIRT.test(name + ' ' + description), state: status.toLowerCase(), speed: num(speed), + rxBps, txBps, rxPps, txPps, rxBytes: num(rx), txBytes: num(tx), errors: num(errors), drops: num(drops) }); + } + for (const [state, count] of (sec.tcp || []).map(l => l.trim().split(/\s+/))) { + const name = TCP[state] || state.toUpperCase(); + m.tcp[name] = (m.tcp[name] || 0) + num(count), m.socketsUsed += num(count); + } + + // disks and volumes + for (const [name, readBps, writeBps, readIops, writeIops, idle] of rows(sec.disk)) + addDisk(m, { name, readBps: num(readBps), writeBps: num(writeBps), readIops: num(readIops), writeIops: num(writeIops), + util: idle ? Math.min(100, Math.max(0, 100 - num(idle))) : 0, totalRead: 0, totalWritten: 0 }, true); + for (const [mount, label, type, size, free] of rows(sec.df)) + if (num(size) > 0) addMount(m, { device: label, type, mount, total: num(size), used: num(size) - num(free), avail: num(free) }); + + // processes: "pid|ppid|cpuTime100ns|priority|threads|createdUnixSec|vsz|rss|name" + const times = {}; + let started = 0; + for (const [pid, ppid, cpuTime, priority, threads, created, vsz, rss, name = ''] of rows(sec.procs)) { + if (!num(pid)) continue; + const known = st.times && pid in st.times; + times[pid] = num(cpuTime), started += !known; + const cpu = rates && known ? Math.min(100 * m.cpuCount, Math.max(0, (times[pid] - st.times[pid]) / 1e7 / dt * 100)) : 0; // % of one core + m.procs.push({ pid: num(pid), ppid: num(ppid), threads: num(threads), nice: num(priority), name, state: cpu > 0.5 ? 'R' : 'S', user: st.users?.[pid] || '—', + cpu, rss: num(rss), vsz: num(vsz), age: num(created) ? Math.max(0, ts / 1000 - num(created)) : 0 }); + } + m.forksPerSec = rates && st.times ? started / dt : 0; + + // services arrive every few samples: keep the last list + if (sec.services) + st.services = rows(sec.services).map(([unit, state = '', mode, exitCode, description = '']) => ({ unit, load: mode, sub: state.toLowerCase(), description, + active: mode === 'Auto' && state === 'Stopped' && ![0, 1077].includes(num(exitCode)) ? 'failed' : state === 'Running' ? 'active' : 'inactive' })); + m.loggedUsers = num(sec.sessions?.[0]); + finish(m, st, sec, 1); + + st.times = times, st.ts = ts; + m.valid = rates; // the first sample has no rates yet + return m; +} + +module.exports = { + quote, parse, cleanup, + configDir: () => path.join(process.env.APPDATA || path.join(os.homedir(), 'AppData', 'Roaming'), 'ServerMonitorWeb'), + shell: () => SHELL, // argv of a shell that runs a script from stdin + collector: interval => `$iv = ${interval}; $once = $false\n` + collector, // stdin for the collector + wrap: cmd => "[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false; $ProgressPreference = 'SilentlyContinue'; $Error.Clear(); $global:LASTEXITCODE = 0\n" + + `& {\n${cmd}\n} 2>&1 | Out-String -Width 250 -Stream\nif ($LASTEXITCODE) { exit $LASTEXITCODE }\n` + // no sudo: run the monitor elevated + "if ($Error | Where-Object { $_.FullyQualifiedErrorId -notlike 'NativeCommandError*' }) { exit 1 }; exit 0\n", // stderr text of a program is not a failure + askpass: ['askpass.cmd', '@echo off\r\nsetlocal EnableDelayedExpansion\r\necho(!SERVERMONITOR_ASKPASS!\r\n'], // answers ssh's password prompt + command: (action, arg) => ({ + kill_pid: `Stop-Process -Id ${parseInt(arg) || 0} -Force`, renice: `(Get-Process -Id ${parseInt(arg) || 0}).PriorityClass = 'Idle'`, + restart_service: `Restart-Service -Name ${quote(arg)} -Force`, restart_failed: restartFailed, + })[action], + serviceLogs: (unit, lines) => `$s = Get-CimInstance Win32_Service | Where-Object Name -eq ${quote(unit)}; $s | Format-List Name, DisplayName, State, StartMode, ExitCode, ProcessId, PathName; ` + + "Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Service Control Manager' } -MaxEvents 3000 -ErrorAction Ignore | " + + `Where-Object { $_.Message -like ('*' + $s.DisplayName + '*') } | Select-Object -First ${lines} | Format-Table TimeCreated, LevelDisplayName, Message -Wrap`, + power: reboot => `shutdown /${reboot ? 'r' : 's'} /t 5`, + detached: false, + kill: p => { // with everything it started + if (p.pid && !spawn('taskkill', ['/PID', String(p.pid), '/T', '/F'], { windowsHide: true, stdio: 'ignore' }).on('error', () => {}).pid) p.kill(); + }, + reaper: null, // nothing to end children when the monitor is killed outright: the collector ends by itself when its parent is gone + // never killed automatically, no leak / runaway findings: the system's own processes + isProtected: p => p.pid <= 4 || p.rss <= 0 || PROTECTED.has(p.name), + + ui: { // sent to the page + name: 'Windows', sudo: false, posixCpu: false, interval: 3, prioLabel: 'Priority', normalPrio: 8, kernelPrefix: 'build ', + sshHint: 'Uses your system ssh client. The server needs the OpenSSH Server feature and PowerShell; nothing else is installed. ' + + "For key login, add your public key to the server's authorized_keys.", + keyHint: 'default keys / ssh-agent (%USERPROFILE%\\.ssh\\id_*)', + ruleActions: [['notify', 'Notify only', ''], ['restart_failed', 'Restart failed services', ''], ['restart_service', 'Restart a service', 'Spooler'], + ['kill_top_cpu', 'Terminate top CPU process', ''], ['kill_top_mem', 'Terminate top memory process', ''], ['command', 'Run a command', 'Clear-DnsClientCache']], + procActions: cmds([['End task', 'taskkill /PID {n}'], ['Kill', 'taskkill /F /PID {n}', true], ['Kill tree', 'taskkill /F /T /PID {n}', true]]), + priorities: cmds(['Idle', 'BelowNormal', 'Normal', 'AboveNormal', 'High'].map(p => [p, `(Get-Process -Id {n}).PriorityClass = '${p}'`])), + serviceActions: cmds([['Start', 'Start-Service -Name {q}', false, false], ['Stop', 'Stop-Service -Name {q} -Force', true], ['Restart', 'Restart-Service -Name {q} -Force'], + ['Enable', 'Set-Service -Name {q} -StartupType Automatic', false, false], ['Disable', 'Set-Service -Name {q} -StartupType Disabled', true]]), + diagnostics: cmds([ + ['Disk usage', "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"], + ['Largest folders in C:\\', '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'], + ['Memory', 'Get-CimInstance Win32_OperatingSystem | Format-List TotalVisibleMemorySize, FreePhysicalMemory, TotalVirtualMemorySize, FreeVirtualMemory'], + ['Top CPU processes', "Get-Process | Sort-Object CPU -Descending | Select-Object -First 20 Id, ProcessName, CPU, @{ n = 'MemMB'; e = { [int]($_.WorkingSet64 / 1MB) } }, StartTime"], + ['Listening ports', 'Get-NetTCPConnection -State Listen | Sort-Object LocalPort | Format-Table LocalAddress, LocalPort, OwningProcess'], + ['System errors', events("'System'; Level = 1, 2", 40, 'ProviderName')], ['Application errors', events("'Application'; Level = 1, 2", 40, 'ProviderName')], + ['Failed services', failed + ' | Format-Table Name, ExitCode, DisplayName'], ['Logged-in users', 'quser'], ['Last boots', events("'System'; Id = 6005, 6006, 1074", 15, 'Id')]]), + systemActions: cmds([['Clean temp files', cleanup], ['Flush DNS cache', "Clear-DnsClientCache; 'done'"], ['Restart failed services', restartFailed], + ['Reboot', 'shutdown /r /t 5', true], ['Shut down', 'shutdown /s /t 5', true]]), + }, +}; diff --git a/Server Monitor(web-window)/core/session.js b/Server Monitor(web-window)/core/session.js new file mode 100644 index 0000000000000000000000000000000000000000..9bc943426c7ddfb6ba0c6e124f863e301e46910b --- /dev/null +++ b/Server Monitor(web-window)/core/session.js @@ -0,0 +1,355 @@ +// Connection to one machine (local shell or the system ssh), the per-server session (metrics, live rows, rules, +// autopilot) and the manager of all sessions. +const { spawn } = require('child_process'), { EventEmitter } = require('events'); +const fs = require('fs'), os = require('os'), path = require('path'); +const plat = require('./platform'), model = require('./model'); +const { blank } = require('./metrics'); +const { HistoryStore, analyze, blankAnalysis, nowSec } = require('./history'); +const { Fmt, ruleMetrics, def, conditionText, actionText } = require('../public/shared'); + +// ---- link: streams collector frames and runs one-shot commands; close() kills everything ---- +const SSH_OPTS = ['ConnectTimeout=10', 'ServerAliveInterval=10', 'ServerAliveCountMax=3', 'StrictHostKeyChecking=accept-new', 'LogLevel=ERROR']; +const links = new Set(); // every open link: closing them ends every child process +let askpass; // helper script that answers ssh's password prompt, created on first use and removed on exit +let reaper; // platform helper that ends the children if this process is killed without a chance to do it +function reap(sign, pid) { // "+pid" when a child starts, "-pid" when it has ended + if (!plat.reaper || !pid) return; + if (!reaper) (reaper = spawn(plat.reaper[0], plat.reaper.slice(1), { stdio: ['pipe', 'ignore', 'ignore'], detached: true })).on('error', () => {}), reaper.stdin.on('error', () => {}); + reaper.stdin.write(sign + pid + '\n'); +} +function askpassFile() { + if (askpass) return askpass; + const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sm-')); + process.on('exit', () => fs.rmSync(dir, { recursive: true, force: true })); + fs.writeFileSync(askpass = path.join(dir, plat.askpass[0]), plat.askpass[1], { mode: 0o700 }); + return askpass; +} + +class Link { + constructor(cfg) { this.c = cfg, this.procs = new Set(), this.closed = '', links.add(this); } + + spawn(argv, input) { + const c = this.c, env = { ...process.env }; + let cmd = argv[0], args = argv.slice(1); + if (c.transport) { + args = SSH_OPTS.flatMap(o => ['-o', o]), cmd = 'ssh'; + if (!c.password) args.push('-o', 'BatchMode=yes'); + else { + args.push('-o', 'NumberOfPasswordPrompts=1'); + Object.assign(env, { SSH_ASKPASS: askpassFile(), SSH_ASKPASS_REQUIRE: 'force', SERVERMONITOR_ASKPASS: c.password, DISPLAY: env.DISPLAY || ':0' }); + } + if (c.keyFile) args.push('-i', c.keyFile.startsWith('~/') ? os.homedir() + c.keyFile.slice(1) : c.keyFile); + if (c.port !== 22) args.push('-p', String(c.port)); + args.push('-T', (c.user && c.user + '@') + c.host, argv.join(' ')); + } + const p = spawn(cmd, args, { env, windowsHide: true, detached: plat.detached }); + this.procs.add(p), reap('+', p.pid); + p.on('exit', () => (this.procs.delete(p), reap('-', p.pid), setTimeout(() => (p.stdout.destroy(), p.stderr.destroy()), 300))); // a grandchild may keep the pipes open + p.stdin.on('error', () => {}); // the process may end before it reads its input + p.stdin.end(input); + for (const s of [p.stdout, p.stderr]) s.setEncoding('utf8'); + return p; + } + + start(onFrame, onLost) { + const p = this.spawn(plat.shell(this.c.interval), plat.collector(this.c.interval)); + let buf = '', err = ''; + const lost = why => this.closed || onLost(why); + p.stdout.on('data', d => { + buf += d; + for (let end; !this.closed && (end = buf.indexOf('@@SNAP_END')) >= 0; buf = buf.slice(end + 10)) { + const begin = buf.lastIndexOf('@@SNAP_BEGIN', end); + if (begin >= 0) onFrame(buf.slice(begin, end)); + } + if (buf.length > 8 << 20) buf = ''; + }); + p.stderr.on('data', d => err = (err + d).slice(-4096)); + p.on('error', e => lost(`cannot start ${p.spawnfile}: ${e.message}`)); + p.on('close', code => lost(err.split('\n').filter(l => l.trim()).pop()?.trim() || `connection closed (exit code ${code})`)); + } + + exec(input, timeoutMs) { // -> { code, out }; code -1 = could not run, killed or timed out + return new Promise(resolve => { + const p = this.spawn(plat.shell(), input), stop = () => (killed = true, p.stdout.destroy(), p.stderr.destroy(), plat.kill(p)), timer = setTimeout(stop, timeoutMs); + let out = '', killed = false; + const done = r => (clearTimeout(timer), resolve(r)); + for (const s of [p.stdout, p.stderr]) s.on('data', d => (out += d).length > 4 << 20 && stop()); // endless output must not fill the memory + p.on('error', e => done({ code: -1, out: e.message })); + p.on('close', (code, signal) => done(this.closed ? { code: -1, out: this.closed } : killed || signal ? { code: -1, out: out + '\n[killed or timed out]' } : { code, out })); + }); + } + + close(why) { + this.closed = why, links.delete(this); + for (const p of this.procs) plat.kill(p); + } +} + +// two frames prove that data and rates work +function testConnection(cfg) { + return new Promise(resolve => { + const link = new Link({ ...cfg, interval: 1 }), engine = {}, t0 = Date.now(); + let frames = 0; + const finish = (ok, text) => (clearTimeout(timer), link.close('done'), resolve({ ok, text })); + const timer = setTimeout(() => finish(false, '✗ Timed out after 20 s'), 20000); + link.start(raw => { + const m = plat.parse(raw, engine, Date.now()); + if (++frames === 2) finish(true, `✓ Connected in ${Date.now() - t0} ms — ${m.hostname} · ${m.os} · ${m.cpuCount} cores · ${Fmt.bytes(m.memTotal)} RAM · CPU ${Fmt.pct(m.cpuUsage, 0)}`); + }, why => finish(false, '✗ ' + why)); + }); +} + +// ---- session ---- +// one row of the live charts (the last hour is kept in memory); the page reads v[] by position +const r2 = x => Math.round(x * 100) / 100; +const liveRow = m => ({ + t: m.timestamp, + v: [m.cpuUsage, m.cpuUser, m.cpuSystem + m.cpuIrq, m.cpuIowait, m.cpuSteal, m.memPct, m.memTotal > 0 ? (m.cached + m.buffers) * 100 / m.memTotal : 0, + m.swapPct, m.netRxBps, m.netTxBps, m.diskReadBps, m.diskWriteBps, m.load1].map(r2), + net: Object.fromEntries(m.nets.map(n => [n.name, [Math.round(n.rxBps), Math.round(n.txBps)]])), +}); + +class Session extends EventEmitter { // events: updated, sample(row), analysis, alert(event) + constructor(cfg, dir) { + super(); + Object.assign(this, { cfg, status: 'Disabled', err: '', m: blank(0), live: [], retries: 0, paused: false, offlineAlerted: false, an: blankAnalysis(), + store: new HistoryStore(path.join(dir, 'history', cfg.id)), reported: new Set(), dry: new Set(), cooldown: {}, rules: {}, procs: new Map(), svcs: new Map() }); + this.timers = [setInterval(() => this.analyzeNow(), 60000), setTimeout(() => this.analyzeNow(), 3000)]; + this.tick(); + } + destroy() { this.stop(), [...this.timers, this.offlineTick].forEach(clearTimeout), this.removeAllListeners(); } + tick() { // downtime -> availability: one sample per interval, like uptime + clearInterval(this.offlineTick); + this.offlineTick = setInterval(() => (this.status === 'Offline' || (this.status === 'Connecting' && this.retries)) && this.record(false), this.cfg.interval * 1000); + } + + get online() { return this.status === 'Online' && this.m.valid; } + setPaused(p) { this.paused = p, this.emit('updated'); } + reconnect() { this.retries = 0, this.paused = false, this.start(); } + + setConfig(c) { + const old = this.cfg, reconnect = ['transport', 'host', 'port', 'user', 'keyFile', 'password', 'interval', 'enabled'].some(k => c[k] !== old[k]); + this.cfg = c, this.tick(); + if (reconnect) this.live = [], this.m = blank(0), this.procs.clear(), this.svcs.clear(), c.enabled ? this.start() : this.stop(); // may be another machine now + this.emit('updated'); + } + + drop(why) { clearTimeout(this.retry), clearTimeout(this.watchdog), this.link?.close(why), this.link = null; } + watch(sec) { clearTimeout(this.watchdog), this.watchdog = setTimeout(() => this.onLost('no data received (timeout)'), sec * 1000); } + + start() { + this.drop('connection restarted'); + if (!this.cfg.enabled) return this.setStatus('Disabled'); + this.engine = {}, this.m.valid = false, this.link = new Link(this.cfg); // online only again with a fresh sample + this.setStatus('Connecting'), this.watch(25); + this.link.start(raw => this.onFrame(raw), why => this.onLost(why)); + } + + stop() { this.drop('connection stopped'), this.setStatus(this.cfg.enabled ? 'Offline' : 'Disabled'); } + + setStatus(s, err = '') { + if (err || s === 'Online') this.err = err; + if (s !== this.status) this.status = s, this.emit('updated'); + } + + onFrame(raw) { + const now = Date.now(), m = plat.parse(raw, this.engine, now); + this.watch(Math.max(15, this.cfg.interval * 5 + 10)); + if (m.uptime <= 0) return; + if (this.status !== 'Online') { + this.retries = 0; + if (this.offlineAlerted) this.offlineAlerted = false, this.raise('resolved', 'Server is back online'); + this.setStatus('Online'); + } + if (!m.valid || this.paused) return; // the first sample has no rates yet + if (m.uptime < this.m.uptime) this.procs.clear(); // rebooted: PIDs start again, old trends would be blamed on new processes + const first = !this.m.valid; // first sample of this connection: analyze at once, the last analysis saw "unreachable" + this.m = m, this.live.push(liveRow(m)); + if (this.live.length > 1800) this.live.shift(); + this.record(true), this.track(now), this.evaluateRules(); + if (first) this.analyzeNow(); + this.emit('sample', this.live.at(-1)); + } + + onLost(why) { + const was = this.status === 'Online'; + this.drop('connection lost: ' + why), this.setStatus('Offline', why); + if ((was || this.retries === 1) && !this.offlineAlerted) this.raise('critical', 'Server is unreachable: ' + why), this.offlineAlerted = true; + if (this.cfg.enabled) this.retry = setTimeout(() => this.start(), [3, 5, 10, 20, 30, 60][Math.min(this.retries++, 5)] * 1000); // back-off + } + + // privileged + "useSudo" wraps the command in sudo -n + exec(cmd, privileged, timeoutMs = 60000) { + if (!this.link || this.status !== 'Online') return Promise.resolve({ code: -1, out: 'server is not connected' }); + return this.link.exec(plat.wrap(cmd, privileged && this.cfg.useSudo), timeoutMs); + } + + activeAlerts() { + return [...(this.status === 'Offline' ? ['Unreachable: ' + this.err] : []), ...this.cfg.rules.filter(r => this.rules[r.id]?.active).map(conditionText)]; + } + + raise(severity, message) { this.emit('alert', { time: Date.now(), serverName: this.cfg.name, severity, message }); } // info|warning|critical|resolved|action + + record(up) { + const m = this.m, or = (has, x) => has ? x : NaN; // in the order of the history record + this.store.add(nowSec(), [m.cpuUsage, m.cpuIowait, m.load1, m.memPct, or(m.swapTotal > 0, m.swapPct), or(m.mounts.length, m.maxDiskPct), m.maxDiskUtil, m.netRxBps, + m.netTxBps, m.diskReadBps, m.diskWriteBps, or(m.temps.length, m.maxTemp), m.procs.length, or(m.gpus.length, model.gpuMax(m, 'util')), m.servicesFailed], up); + } + + // per-process CPU streaks + RSS per minute; service failure transitions + track(now) { + const procs = new Map(); + for (const p of this.m.procs) { + let t = this.procs.get(p.pid); + if (t?.name !== p.name) t = { name: p.name, highSince: 0, lastMinute: 0, rss: [] }; // new or pid reused + t.kernel = plat.isProtected(p); + t.highSince = p.cpu < this.cfg.autopilot.runawayCpu ? 0 : t.highSince || now; + if (now - t.lastMinute >= 60000) t.lastMinute = now, t.rss.push(p.rss); + if (t.rss.length > 60) t.rss.shift(); + procs.set(p.pid, t); + } + this.procs = procs; + const svcs = new Map(); + for (const s of this.m.services) { + const failed = s.active === 'failed'; + let t = this.svcs.get(s.unit); + if (!t) t = { last: '', preexisting: failed, fails: [], restarts: [] }; // failed before monitoring started: leave it alone + else if (failed && t.last !== 'failed') t.fails.push(now), t.preexisting = false; + else if (!failed) t.preexisting = false; + t.last = s.active, svcs.set(s.unit, t); + for (const v of [t.fails, t.restarts]) while (now - v[0] > 3600000) v.shift(); + } + if (svcs.size) this.svcs = svcs; // forgets removed services; a sample without a service list changes nothing + } + + evaluateRules() { + const now = Date.now(), m = this.m, vals = model.metricValues(m); + for (const r of this.cfg.rules) { + const st = this.rules[r.id] ??= {}, v = vals[r.metric] ?? 0, now1 = Fmt.fix(v, 1), unit = def(ruleMetrics, r.metric)[2]; + const off = !r.enabled || (r.metric.startsWith('gpu') && !m.gpus.length) || (r.metric === 'temp' && !m.temps.length); + if (off || (r.op === '<' ? v >= r.value : v <= r.value)) { + if (!off && st.active) this.raise('resolved', `Recovered: ${conditionText(r)} (now ${now1})`); + this.rules[r.id] = {}; + continue; + } + st.since ||= now; + if (now - st.since < r.duration * 1000) continue; + if (st.active && (r.action === 'notify' || now - st.lastFire < r.cooldown * 1000)) continue; + if (!st.active) this.raise(r.severity, `${conditionText(r)} (now ${now1}${unit && ' ' + unit})`); + st.active = true, st.lastFire = now; + if (r.action === 'notify') continue; + let action = r.action, arg = r.arg; + if (action.startsWith('kill_top')) { // heaviest user process, never a protected one + const k = action === 'kill_top_mem' ? 'rss' : 'cpu', best = m.procs.filter(p => !plat.isProtected(p)).reduce((a, p) => !a || p[k] > a[k] ? p : a, null); + if (!best) continue; + action = 'kill_pid', arg = String(best.pid); + } + this.run(action, arg, `Automation "${conditionText(r)}": ${actionText(plat.ui.ruleActions, r)}`); + } + } + + async run(action, arg, what) { + const cmd = action === 'command' ? arg : action === 'disk_cleanup' ? this.cfg.autopilot.diskCleanupCommand : plat.command(action, arg); + if (!cmd) return { code: -1, out: 'nothing to do' }; + const r = await this.exec(cmd, true, 300000), tail = r.out.trim().replace(/\s+/g, ' ').slice(-300); // one line: events are lines in alerts.log + this.raise('action', `${what} -> ${r.code ? `failed (${r.code})` : 'OK'}${tail && ' | ' + tail}`); + return r; + } + + runFinding(f, automatic) { + if (automatic && f.action === 'restart_service') this.svcs.get(f.actionArg)?.restarts.push(Date.now()); + return this.run(f.action, f.action === 'disk_cleanup' ? '' : f.actionArg, `${automatic ? 'Autopilot' : 'Manual fix'}: ${f.actionLabel} (${f.title})`); + } + + analyzeNow() { + const now = Date.now(), ap = this.cfg.autopilot, procs = [], svcs = []; + for (const p of this.m.procs) { + const t = this.procs.get(p.pid) || { rss: [] }, n = t.rss.length, growth = n >= 2 ? t.rss[n - 1] - t.rss[0] : 0; + const highCpuMinutes = t.highSince ? (now - t.highSince) / 60000 : 0; + if (highCpuMinutes > 0 || n >= 30) + procs.push({ pid: p.pid, minutesTracked: n, name: p.name, user: p.user, cpuNow: p.cpu, highCpuMinutes, rssNow: p.rss, kernel: t.kernel, rssGrowth: growth, + rssGrowthPct: t.rss[0] > 0 ? growth * 100 / t.rss[0] : 0, rssMonotonic: n >= 2 ? t.rss.filter((x, i) => i && x > t.rss[i - 1]).length / (n - 1) : 0 }); + } + for (const [unit, t] of this.svcs) + if (t.last === 'failed' || t.fails.length) + svcs.push({ unit, failedNow: t.last === 'failed', preexisting: t.preexisting, failsLastHour: t.fails.length, autoRestartsLastHour: t.restarts.length }); + this.an = analyze(this.store, this.m, ap, procs, svcs, this.online); + + for (const f of this.an.findings) // announce each new finding once + if (!this.reported.has(f.key) && f.category !== 'Availability') this.raise(f.severity, `Insight: ${f.title} - ${f.detail}`); + this.reported = new Set(this.an.findings.map(f => f.key)); + + const dry = new Set(); // act on eligible findings, with cooldowns; a dry run says once what it would do + for (const f of ap.enabled && this.online ? this.an.findings.filter(f => f.autoEligible) : []) { + const cd = f.action === 'disk_cleanup' ? 6 * 3600000 : f.action === 'restart_service' ? 120000 : 900000; + if (ap.dryRun) dry.add(f.key), this.dry.has(f.key) || this.raise('action', `Autopilot (dry run) would: ${f.actionLabel} - ${f.title}`); + else if (now - (this.cooldown[f.key] || 0) >= cd) this.cooldown[f.key] = now, this.runFinding(f, true); + } + this.dry = dry, this.emit('analysis'); + } + + deleteHistory() { this.store.removeFiles(), this.an = blankAnalysis(), this.emit('analysis'); } +} + +// ---- manager ---- +class Manager extends EventEmitter { // events: updated(session), sample(session, row), analysis(session), alert(event) + constructor() { + super(); + this.dir = plat.configDir(), this.sessions = [], this.alerts = []; + fs.mkdirSync(this.dir, { recursive: true, mode: 0o700 }); // alerts.log holds command output + } + session(id) { return this.sessions.find(s => s.cfg.id === id); } + + attach(cfg) { + const s = new Session(cfg, this.dir); + for (const ev of ['updated', 'sample', 'analysis']) s.on(ev, x => this.emit(ev, s, x)); + s.on('alert', e => { + const log = path.join(this.dir, 'alerts.log'); + this.alerts.unshift(e), this.alerts.length = Math.min(this.alerts.length, 2000); + try { // starts over at 5 MB + fs.appendFileSync(log, `${Fmt.iso(e.time)}\t${e.severity}\t${e.serverName}\t${e.message}\n`, { flag: fs.statSync(log, { throwIfNoEntry: false })?.size > 5 << 20 ? 'w' : 'a' }); + } catch { /* disk full or not writable: the event still reaches the page */ } + this.emit('alert', e); + }); + this.sessions.push(s); + return s; + } + + load() { + const file = path.join(this.dir, 'servers.json'); + if (fs.existsSync(file)) { + let servers = []; + try { servers = JSON.parse(fs.readFileSync(file, 'utf8')).servers; } catch { fs.copyFileSync(file, file + '.bad'); } // not JSON: start empty; the next save replaces the file, so keep a copy + for (const o of Array.isArray(servers) ? servers : []) if (o && typeof o === 'object') this.attach(model.fromJson(o)); + } else { // first start: monitor this machine + this.attach(model.make({ name: 'This computer', group: 'Local', transport: 0 }, '')); + this.save(); + } + for (const s of this.sessions) s.start(); + } + + save() { + const file = path.join(this.dir, 'servers.json'); + fs.writeFileSync(file + '.tmp', JSON.stringify({ version: 1, servers: this.sessions.map(s => model.toJson(s.cfg)) }, null, 4), { mode: 0o600 }); + fs.renameSync(file + '.tmp', file); + } + + add(cfg) { this.attach(cfg).start(), this.save(); } + update(cfg) { this.session(cfg.id).setConfig(cfg), this.save(); } + remove(id, deleteHistory) { + const s = this.session(id); + this.sessions.splice(this.sessions.indexOf(s), 1), s.destroy(); + if (deleteHistory) fs.rmSync(s.store.dir, { recursive: true, force: true }); + this.save(); + } + move(id, d) { + const v = this.sessions, i = v.indexOf(this.session(id)), j = Math.min(v.length - 1, Math.max(0, i + d)); + if (i >= 0 && i !== j) v.splice(j, 0, v.splice(i, 1)[0]), this.save(); + } + close() { // ends every child process, also those of connection tests + for (const s of this.sessions) s.destroy(); + for (const l of links) l.close('monitor stopped'); + } +} + +module.exports = { Manager, testConnection }; diff --git a/Server Monitor(web-window)/public/app.js b/Server Monitor(web-window)/public/app.js new file mode 100644 index 0000000000000000000000000000000000000000..4d8b2416b0c3caa30ff999af63370e211b2816d3 --- /dev/null +++ b/Server Monitor(web-window)/public/app.js @@ -0,0 +1,854 @@ +// Server Monitor page: sidebar, dashboard, server tabs and events. Plain DOM + canvas, no libraries. +// Data arrives over Server-Sent Events, actions go to the JSON API; server data only ever enters the page as text. +'use strict'; +const { Fmt, hNames, fmtMetric, ruleMetrics, def, conditionText, actionText } = SM; + +// ---- small helpers ---- +const css = getComputedStyle(document.documentElement), FONT = css.fontFamily; // the palette lives in style.css +const C = Object.fromEntries(['panel', 'card', 'border', 'grid', 'text', 'muted', 'faint', 'accent', 'green', 'amber', 'red', 'violet', 'pink', 'teal', 'orange', 'blue'] + .map(k => [k, css.getPropertyValue('--' + k).trim()])); +const clamp = (v, lo, hi) => Math.min(hi, Math.max(lo, v)), ok = v => v != null && !isNaN(v); +const rgb = hex => [1, 3, 5].map(i => parseInt(hex.slice(i, i + 2), 16)); +const tint = (hex, alpha) => `rgba(${rgb(hex)},${alpha / 255})`; +const mix = (a, b, t) => `rgb(${rgb(a).map((x, i) => Math.round(x + (rgb(b)[i] - x) * clamp(t, 0, 1)))})`; +const level = (pct, warn = 70, crit = 90) => pct >= crit ? C.red : pct >= warn ? C.amber : C.green; +const sevColor = s => ({ critical: C.red, warning: C.amber, resolved: C.green, action: C.violet })[s] || C.accent; +const healthColor = v => v >= 90 ? C.green : v >= 75 ? C.teal : v >= 60 ? C.amber : v >= 40 ? C.orange : C.red; +const statusColor = s => ({ Online: C.green, Connecting: C.amber, Offline: C.red })[s.status] || C.faint; +const pctFmt = v => Fmt.fix(v) + '%', numFmt = prec => v => Fmt.fix(v, prec); +const pad = n => String(n).padStart(2, '0'); +function tf(ms, format) { // date formatting with Qt-style patterns + const d = new Date(ms), part = { yyyy: d.getFullYear(), MMM: d.toLocaleString('en', { month: 'short' }), MM: pad(d.getMonth() + 1), ddd: d.toLocaleString('en', { weekday: 'short' }), + dd: pad(d.getDate()), HH: pad(d.getHours()), mm: pad(d.getMinutes()), ss: pad(d.getSeconds()) }; + return format.replace(/yyyy|MMM|MM|ddd|dd|HH|mm|ss/g, k => part[k]); +} + +// h('tag.class.class', { property | onevent | style: {} }, ...children): children are elements or text +function h(tag, props, ...kids) { + const [name, ...cls] = tag.split('.'), el = document.createElement(name); + el.className = cls.join(' '); + for (const [k, v] of Object.entries(props || {})) { + if (k === 'style') for (const [p, x] of Object.entries(v)) el.style.setProperty(p, x ?? ''); + else if (k.startsWith('on')) el.addEventListener(k.slice(2), v); + else el[k] = v; + } + el.append(...kids.flat(2).filter(k => k != null && k !== false && k !== '')); + return el; +} + +async function api(path, body) { // GET without a body, POST with one + const r = await fetch('/api/' + path, body && { method: 'POST', headers: { 'Content-Type': 'application/json', 'X-SM': '1' }, body: JSON.stringify(body) }); + const j = await r.json(); + if (!r.ok) throw new Error(j.error); + return j; +} +addEventListener('unhandledrejection', e => { // a failed request that nobody handled: show it briefly + const note = document.body.appendChild(h('div.toast', null, String(e.reason?.message || e.reason))); + setTimeout(() => note.remove(), 6000); +}); + +// ---- hand-drawn widgets ---- +const font = (ctx, px, bold) => ctx.font = `${bold ? 700 : 400} ${px}px ${FONT}`; +function text(ctx, s, x, y, px, color, align = 'left', bold = false, maxW = 0) { // vertically centred on y; maxW elides + font(ctx, px, bold), ctx.fillStyle = color, ctx.textAlign = align, ctx.textBaseline = 'middle'; + let out = String(s); + for (let n = out.length; maxW && n > 1 && ctx.measureText(out).width > maxW;) out = String(s).slice(0, --n) + '…'; + ctx.fillText(out, x, y); + return ctx.measureText(out).width; +} +function box(ctx, x, y, w, hh, r, fill, stroke) { + ctx.beginPath(), ctx.roundRect(x, y, w, hh, r), ctx.fillStyle = fill, ctx.fill(); + if (stroke) ctx.strokeStyle = stroke, ctx.lineWidth = 1, ctx.setLineDash([]), ctx.stroke(); +} +function line(ctx, pts, color, width, dash = []) { + ctx.beginPath(), pts.forEach(p => ctx.lineTo(p[0], p[1])); + ctx.strokeStyle = color, ctx.lineWidth = width, ctx.lineCap = ctx.lineJoin = 'round', ctx.setLineDash(dash), ctx.stroke(); +} +function ring(ctx, x, y, s, pct, color, thick, glow = true) { // 270° arc in the square (x, y, s) + const arc = (angle, c, w) => { ctx.beginPath(), ctx.arc(x + s / 2, y + s / 2, (s - thick) / 2, Math.PI * .75, Math.PI * .75 + angle), ctx.strokeStyle = c, ctx.lineWidth = w, ctx.lineCap = 'round', ctx.setLineDash([]), ctx.stroke(); }; + const a = Math.PI * 1.5 * clamp(pct, 0, 100) / 100; + arc(Math.PI * 1.5, C.grid, thick); + if (a > .003) glow && arc(a, tint(color, 45), thick * 2), arc(a, color, thick); +} + +// a canvas that fills its box and repaints when resized; draw(ctx, width, height) works in CSS pixels +function canvas(cls, draw) { + const cv = h('canvas'), el = h('div.cv.' + cls, null, cv), ctx = cv.getContext('2d'); + el.redraw = () => { + const w = el.clientWidth, hh = el.clientHeight, r = devicePixelRatio || 1; + if (!w || !hh) return; + if (cv.width !== Math.round(w * r) || cv.height !== Math.round(hh * r)) cv.width = Math.round(w * r), cv.height = Math.round(hh * r); + ctx.setTransform(r, 0, 0, r, 0, 0), ctx.clearRect(0, 0, w, hh), draw(ctx, w, hh); + }; + new ResizeObserver(el.redraw).observe(el); + return el; +} + +function gauge(title, warn = 70, crit = 90) { // ring gauge; set(percent, centre text, text below, colour) + let target = 0, shown = 0, from = 0, t0 = 0, center = '', sub = '', color; + const el = canvas('gauge', (ctx, w, hh) => { + const s = Math.min(w - 8, hh - 28), x = (w - s) / 2; + ring(ctx, x, 4, s, shown, color || level(target, warn, crit), Math.max(7, s * .085)); + text(ctx, center || Fmt.fix(shown) + '%', w / 2, 4 + s * .43, s * .2, C.text, 'center', true); + text(ctx, sub, w / 2, 4 + s * .63, Math.max(10, s * .075), C.muted, 'center', false, s * .76); + text(ctx, title, w / 2, 4 + s * .94 + 9, 13, C.text, 'center', true); + }); + const step = now => { // 450 ms ease-out + const k = Math.min(1, (now - t0) / 450); + shown = from + (target - from) * (1 - (1 - k) ** 3), el.redraw(); + if (k < 1) requestAnimationFrame(step); + }; + el.set = (pct, c = '', s = '', col) => { + center = c, sub = s, color = col, pct ||= 0; + if (Math.abs(pct - target) > .05) from = shown, target = pct, t0 = performance.now(), requestAnimationFrame(step); + else el.redraw(); + }; + return el; +} + +const ser = (name, color, v, fill = true, dashed = false) => ({ name, color, v, fill, dashed }); +function niceCeil(v) { + if (v <= 0) return 1; + const e = 10 ** Math.floor(Math.log10(v)), f = v / e; + return (f <= 1 ? 1 : f <= 2 ? 2 : f <= 2.5 ? 2.5 : f <= 5 ? 5 : 10) * e; +} +// time chart: grid, legend with latest values, hover value, stacked areas, gaps where a value is missing +function chart(title, fmt = pctFmt, yFixed = 0, stacked = false, empty = 'Waiting for data…') { // yFixed 0 = auto scale + let T = [], S = [], span = 0, hover = -1; + const el = canvas('chart.panel', (ctx, w, hh) => { + const titleW = text(ctx, el.head, 16, 20, 13, C.text, 'left', true), plot = { l: 56, t: 40, r: w - 16, b: hh - 30 }, n = T.length; + text(ctx, el.sub, 24 + titleW, 20, 11, C.muted); + let lx = w - 16, first = 0; // legend, right-aligned + for (const s of [...S].reverse()) { + const last = s.v.slice(-5).findLast(ok), label = s.name + (ok(last) ? ' ' + fmt(last) : ''); + if ((lx -= ctx.measureText(label).width) < 40 + titleW) break; + text(ctx, label, lx, 20, 11, C.muted), box(ctx, lx -= 14, 16, 9, 9, 2, s.color), lx -= 14; + } + if (span) while (first < n && T[first] < T[n - 1] - span) ++first; + if (n - first < 2 || plot.b - plot.t < 20) return text(ctx, empty, (plot.l + plot.r) / 2, (plot.t + plot.b) / 2, 13, C.faint, 'center'); + + let yMax = yFixed; + if (yMax <= 0) { + for (let i = first; i < n; ++i) yMax = Math.max(yMax, S.reduce((sum, s) => !ok(s.v[i]) ? sum : stacked ? sum + s.v[i] : Math.max(sum, s.v[i]), 0)); + yMax = niceCeil(yMax * 1.12); + } + font(ctx, 10), plot.l = Math.max(40, ...[0, 1, 2, 3, 4].map(g => ctx.measureText(fmt(yMax * g / 4)).width + 18)); + const pw = plot.r - plot.l, ph = plot.b - plot.t, t1 = T[n - 1], t0 = span ? t1 - span : T[first], tr = Math.max(1, t1 - t0); + const X = t => plot.l + (t - t0) / tr * pw, Y = v => plot.b - clamp(v, 0, yMax) / yMax * ph; + const stamp = tr <= 72e5 ? 'HH:mm' : tr <= 2.6e8 ? 'ddd HH:mm' : tr <= 3.5e10 ? 'dd MMM' : 'MMM yyyy'; + for (let g = 0; g <= 4; ++g) { // grid, y labels, time labels + const y = Y(yMax * g / 4), t = t0 + tr * g / 4; + line(ctx, [[plot.l, y], [plot.r, y]], C.grid, 1, g ? [4, 3] : []); + text(ctx, fmt(yMax * g / 4), plot.l - 8, y, 10, C.faint, 'right'); + text(ctx, tf(t, stamp), X(t), plot.b + 14, 10, C.faint, ['left', 'center', 'center', 'center', 'right'][g]); + } + const step = Math.max(1, Math.floor((n - first) / Math.max(50, pw * 1.5))), base = new Array(n).fill(0); // ~1.5 points per pixel + ctx.save(), ctx.beginPath(), ctx.rect(plot.l - 2, plot.t - 4, pw + 4, ph + 6), ctx.clip(); + for (const s of S) { + const runs = [[]]; // [x, top, bottom] points, split at gaps + for (let i = first; i < n; i += step) { + let sum = 0, bs = 0, c = 0; + for (let k = i; k < Math.min(n, i + step); ++k) if (ok(s.v[k])) sum += s.v[k], bs += base[k], ++c; + if (c) runs.at(-1).push([X(T[Math.min(n - 1, i + (step >> 1))]), Y(sum / c + (stacked ? bs / c : 0)), Y(stacked ? bs / c : 0)]); + else if (runs.at(-1).length) runs.push([]); + } + if (stacked) for (let k = first; k < n; ++k) base[k] += ok(s.v[k]) ? s.v[k] : 0; + for (const r of runs.filter(r => r.length > 1)) { + if (s.fill) { + const g = ctx.createLinearGradient(0, plot.t, 0, plot.b); + g.addColorStop(0, tint(s.color, stacked ? 120 : 95)), g.addColorStop(1, tint(s.color, stacked ? 60 : 4)); + ctx.beginPath(), r.forEach(p => ctx.lineTo(p[0], p[1])), r.toReversed().forEach(p => ctx.lineTo(p[0], p[2])), ctx.fillStyle = g, ctx.fill(); + } + line(ctx, r, s.color, s.dashed ? 1.3 : 2, s.dashed ? [4, 3] : []); + } + } + ctx.restore(); + if (hover < plot.l || hover > plot.r) return; + const at = t0 + (hover - plot.l) / pw * tr, found = T.findIndex((t, i) => i >= first && t >= at), best = found < 0 ? n - 1 : found; // crosshair + tooltip + const x = X(T[best]), lines = [tf(T[best], tr > 864e5 ? 'ddd dd MMM HH:mm' : 'HH:mm:ss'), ...S.map(s => `${s.name}: ${ok(s.v[best]) ? fmt(s.v[best]) : '—'}`)]; + let stack = 0; + line(ctx, [[x, plot.t], [x, plot.b]], 'rgba(255,255,255,.27)', 1, [4, 3]); + for (const s of S.filter(s => ok(s.v[best]))) { + stack = stacked ? stack + s.v[best] : s.v[best]; + ctx.beginPath(), ctx.arc(x, Y(stack), 4, 0, 7), ctx.fillStyle = s.color, ctx.fill(), ctx.strokeStyle = C.panel, ctx.lineWidth = 2, ctx.setLineDash([]), ctx.stroke(); + } + font(ctx, 11); + const tw = Math.max(...lines.map(l => ctx.measureText(l).width)), tx = Math.min(x + 12, plot.r - tw - 20); + box(ctx, tx, plot.t + 4, tw + 18, lines.length * 16 + 10, 7, 'rgba(13,17,28,.92)', C.border); + lines.forEach((l, i) => text(ctx, l, tx + 9, plot.t + 17 + i * 16, 11, i ? C.text : C.muted)); + }); + el.head = title, el.sub = ''; + el.set = (t, s, sp = 0) => (T = t, S = s, span = sp, el.redraw()); // times in ms, series from ser(), span 0 = everything + el.addEventListener('mousemove', e => (hover = e.offsetX, el.redraw())); + el.addEventListener('mouseleave', () => (hover = -1, el.redraw())); + return el; +} + +// stat tiles with an accent stripe; set(index, value, text below, colour) +function tiles(defs, cols = defs.length) { + const els = defs.map(([title, color]) => h('div.tile', { style: { '--stripe': C[color] } }, h('div.section', null, title), h('b', null, '—'), h('small'))); + const el = h('div.tiles', { style: { 'grid-template-columns': `repeat(${cols}, 1fr)` } }, els); + el.set = (i, value, sub = '', color = '') => { const [, v, s] = els[i].children; v.textContent = value, v.style.color = color, s.textContent = sub; }; + return el; +} +function segbar() { // segment bar with a legend; set([[bytes, colour, label]], total) + const bar = h('div.seg'), legend = h('div.legend'), el = h('div', null, bar, legend); + el.set = (segs, total) => { + bar.replaceChildren(...segs.map(([v, color]) => h('i', { style: { width: Math.max(0, v) / (total > 0 ? total : 1) * 100 + '%', background: color } }))); + legend.replaceChildren(...segs.map(([v, color, label]) => h('span', null, h('i', { style: { background: color } }), `${label} ${Fmt.bytes(v)}`))); + }; + return el; +} +const panel = (title, ...content) => h('div.panel', null, title && h('div.section', null, title), content); +const kv = rows => h('table.kv', null, rows.map(([k, v]) => h('tr', null, h('td', null, k), h('td', null, String(v))))); + +// table(headers, { widths, sort: [column, descending], sortable, select, empty: [text, colour] }) -> element with fill(rows), render(), sel, +// selRow(), accept(row) and menu(). A cell is text or { t: text, c: colour, r: right-aligned, pct: bar 0–100, k: sort key, el: element }; +// a row's key is row.key or its first cell's text. +const cellText = c => String(c?.t ?? c ?? ''), rowKey = r => r.key ?? cellText(r[0]); +function setCell(td, c) { + const t = cellText(c); + td.className = c.r ? 'r' : '', td.style.color = c.c || ''; + if (c.el) return td.firstChild === c.el || td.replaceChildren(c.el); + if (c.pct == null) return td.textContent === t && !td.firstElementChild || (td.textContent = t); + if (!td.firstElementChild) td.replaceChildren(h('div.bar', null, h('i'), h('span'))); + const [fill, label] = td.firstElementChild.children, p = clamp(c.pct, 0, 100); + fill.style.width = p + '%', fill.style.background = tint(level(p), 200), label.textContent = t; +} +function table(headers, opt = {}) { + let rows = [], sort = opt.sort; + const body = h('tbody'), sortKey = r => r[sort[0]]?.k ?? cellText(r[sort[0]]); + const heads = headers.map((t, i) => h('th', { style: { width: opt.widths?.[i] && opt.widths[i] + 'px' }, onclick: () => opt.sortable && (sort = [i, sort?.[0] === i && !sort[1]], el.render()) }, t)); + const el = h('div.table', null, h('table', null, h('thead', null, h('tr', null, heads)), body)); + el.render = () => { + const list = sort ? rows.toSorted((a, b) => (sortKey(a) < sortKey(b) ? -1 : +(sortKey(a) > sortKey(b))) * (sort[1] ? -1 : 1)) : rows; + if (body.rows[0]?.cells.length !== headers.length) body.replaceChildren(); + if (!list.length && opt.empty) return body.replaceChildren(h('tr', null, h('td', { colSpan: headers.length, style: { color: opt.empty[1] } }, opt.empty[0]))); + while (body.rows.length > list.length) body.lastChild.remove(); + list.forEach((r, i) => { + const tr = body.rows[i] || body.appendChild(h('tr', null, headers.map(() => h('td')))); + tr.row = r, tr.hidden = !!el.accept && !el.accept(r), tr.classList.toggle('sel', !!opt.select && rowKey(r) === el.sel); + headers.forEach((_, j) => setCell(tr.cells[j], r[j] ?? '')); + }); + heads.forEach((th, i) => th.dataset.sort = sort?.[0] !== i ? '' : sort[1] ? ' ▾' : ' ▴'); + }; + el.fill = r => (rows = r, rows.some(x => rowKey(x) === el.sel) || (el.sel = undefined), el.render()); // the selection goes with its entry + el.selRow = () => rows.find(r => rowKey(r) === el.sel && (!el.accept || el.accept(r))); // a filtered-out row is not a selection + const pick = e => { // mousedown, so a refresh between press and release cannot lose the selection + const tr = e.target.closest('tr'); + if (tr?.row && opt.select && el.sel !== rowKey(tr.row)) el.sel = rowKey(tr.row), el.render(); + return tr?.row; + }; + body.addEventListener('mousedown', pick); + body.addEventListener('contextmenu', e => pick(e) && el.menu && menu(e, el.menu())); + return el; +} + +// context menu at the pointer; items are [label, action] or null for a separator +function menu(e, items) { + e.preventDefault(); + const m = document.body.appendChild(h('div.menu', null, items.map(it => it ? h('button', { onclick: it[1] }, it[0]) : h('hr')))); + m.style.left = Math.min(e.clientX, innerWidth - m.offsetWidth - 4) + 'px', m.style.top = Math.min(e.clientY, innerHeight - m.offsetHeight - 4) + 'px'; + for (const type of ['click', 'contextmenu']) addEventListener(type, () => m.remove(), { once: true, capture: true }); // the next one, not the event being handled +} + +// modal dialog; buttons are [label, class, action]: the dialog closes with the action's result unless that is undefined +function dialog(title, content, buttons, cls = '') { + return new Promise(resolve => { + const d = h('dialog' + cls, { onclose: () => (d.remove(), resolve(d.result)) }, h('h2', null, title), content, + h('div.row.end', null, buttons.map(([label, c, action]) => h('button' + c, { onclick: async () => (d.result = await action()) !== undefined && d.close() }, label)))); + document.body.append(d), d.showModal(); + }); +} +const ask = (title, question, danger) => dialog(title, h('p.pre', null, question), [['Yes', danger ? '.danger' : '.primary', () => true], ['No', '', () => false]]); + +// inputs bound to o[key]; `changed` runs after every edit +function fields(o, changed = () => {}) { + const bind = (el, k, get) => (el.addEventListener('change', () => (o[k] = get(el), changed())), el); + return { + text: (k, props) => bind(h('input', { value: o[k], ...props }), k, el => el.value), + num: (k, min, max, step = 1) => bind(h('input', { type: 'number', min, max, step, value: o[k] }), k, el => +(el.value = clamp(+el.value || 0, min, max))), + check: (k, label) => h('label.check', null, bind(h('input', { type: 'checkbox', checked: o[k] }), k, el => el.checked), label), + select: (k, options) => bind(h('select', null, options.map(([v, label]) => h('option', { value: v, selected: v === o[k] }, label))), k, el => typeof o[k] === 'number' ? +el.value : el.value), + }; +} +const form = rows => h('div.form', null, rows.map(([label, field]) => [h('div', null, label), h('div.row', null, field)])); // [label, field(s)] rows + +// keeps one child per server (matched by id) so elements survive updates; `tail` elements follow +function keyed(parent, make, tail = []) { + const old = new Map([...parent.children].map(el => [el.dataset.id, el])); + const els = S.servers.map(s => { + const el = old.get(s.cfg.id) || make(s.cfg.id); + el.dataset.id = s.cfg.id; + return el; + }); + if ([...els, ...tail].some((el, i) => parent.children[i] !== el) || parent.children.length !== els.length + tail.length) parent.replaceChildren(...els, ...tail); + els.forEach((el, i) => el.update(S.servers[i])); +} + +// ---- state ---- +// plat: platform tables from the server; id: server shown on the detail page; live, m, vals, an: its live rows, metrics, rule values, analysis +const S = { plat: null, dir: '', rule: null, defaultRules: [], servers: [], alerts: [], page: '', id: null, tab: '', span: 15, live: [], m: null, vals: {}, an: null, unseen: 0 }; +const cur = () => S.servers.find(s => s.cfg.id === S.id); +const go = (...parts) => location.hash = '#/' + parts.map(encodeURIComponent).join('/'); +const [, USER, SYS, IOWAIT, STEAL, MEM, CACHE, SWAP, RX, TX, RD, WR, LOAD] = Array(13).keys(); // positions in a live row (liveRow in core/session.js) +const col = k => S.live.map(r => r.v[k]), times = () => S.live.map(r => r.t), spanMs = () => S.span * 60000; +const cpuSeries = steal => [ser('User', C.accent, col(USER)), ser('System', C.violet, col(SYS)), + ...(S.plat.posixCpu ? [ser('I/O wait', C.amber, col(IOWAIT)), ...(steal ? [ser('Steal', C.red, col(STEAL))] : [])] : [])]; + +// ---- server actions ---- +const serverMenu = (id, first) => [first, ['Reconnect', () => api('server/reconnect', { id })], null]; +async function editServer(id) { // id undefined = add + const P = S.plat, s = S.servers.find(x => x.cfg.id === id), groups = [...new Set(S.servers.map(x => x.cfg.group).filter(Boolean))]; + if (id && !s) return; + const c = s ? { ...s.cfg, password: '' } : { name: '', group: '', transport: 1, host: '', port: 22, user: '', keyFile: '', password: '', interval: P.interval, useSudo: false, enabled: true, notes: '' }; + const f = fields(c, () => sync()), hint = h('div.muted'), result = h('span.grow'), name = f.text('name', { placeholder: 'e.g. web-01' }); + const ssh = [f.text('host', { placeholder: 'hostname or IP address', className: 'grow' }), f.num('port', 1, 65535), f.text('user', { placeholder: 'default: your local user name' }), + f.text('keyFile', { placeholder: P.keyHint }), f.text('password', { type: 'password', autocomplete: 'new-password', placeholder: s?.cfg.hasPassword ? 'stored — leave empty to keep it' : 'optional — keys are recommended' })]; + const group = f.text('group', { className: 'grow' }), show = (t, color) => void (result.textContent = t, result.style.color = color); + group.setAttribute('list', 'groups'); + const sync = () => { + ssh.forEach(el => el.disabled = !c.transport); + hint.textContent = c.transport ? P.sshHint : 'Monitors the computer this program runs on. No setup needed.'; + if (!c.transport && !c.name) c.name = name.value = 'This computer'; + }; + const test = h('button', { onclick: async () => { + test.disabled = true, show('Connecting…', C.amber); + const r = await api('server/test', c).catch(e => ({ text: '✗ ' + e.message })); + test.disabled = false, show(r.text, r.ok ? C.green : C.red); + } }, 'Test connection'); + sync(); + const saved = await dialog(s ? 'Edit server' : 'Add a server', h('div.col', null, form([['Name', name], ['Group', [group, h('datalist', { id: 'groups' }, groups.map(g => h('option', { value: g })))]], + ['Connect via', f.select('transport', [[0, 'This machine (local)'], [1, 'SSH — nothing to install on the server']])], ['Address', [ssh[0], 'port', ssh[1]]], ['User', ssh[2]], ['Private key', ssh[3]], + ['Password', [ssh[4], s?.cfg.hasPassword && f.check('clearPassword', 'remove stored')]], ['Sample every', [f.num('interval', 1, 300), 's']], + ...(P.sudo ? [['', f.check('useSudo', 'Run control commands with sudo -n (needs passwordless sudo)')]] : []), ['', f.check('enabled', 'Monitoring enabled')], ['Notes', f.text('notes', { className: 'grow' })]]), + hint, h('div.row', null, test, result)), [['Save', '.primary', () => api(s ? 'server/update' : 'server/add', c).catch(e => show(e.message, C.red))], ['Cancel', '', () => false]], '.wide'); + if (saved?.id) go('server', saved.id); + else if (saved && id === S.id) listen(); +} +async function removeServer(id) { + const s = S.servers.find(x => x.cfg.id === id); + const how = s && await dialog('Remove server', h('p', null, `Stop monitoring "${s.cfg.name}" and remove it from the list?`), + [['Remove + delete history', '.danger', () => ({ deleteHistory: true })], ['Remove, keep history files', '', () => ({})], ['Cancel', '', () => false]]); + if (!how) return; + if (id === S.id) go('dashboard'); + api('server/remove', { id, ...how }); +} + +// ---- sidebar ---- +const badge = h('span.badge', { hidden: true }), sideList = h('div.list.grow'); +const nav = { dashboard: h('button.nav', { onclick: () => go('dashboard') }, '▦ Dashboard'), events: h('button.nav', { onclick: () => go('events') }, '◉ Events & alerts', badge) }; +const sidebar = h('aside', null, h('div.brand', null, h('img', { src: 'icon.svg', alt: '' }), h('div', null, h('b', null, 'Server Monitor'), h('small', null, 'monitor · analyze · control'))), + nav.dashboard, nav.events, h('div.section', null, 'Servers'), sideList, + h('div.row', null, h('button.primary.grow', { onclick: () => editServer() }, '+ Add'), h('button.grow', { onclick: () => S.id && editServer(S.id) }, 'Edit'), h('button.danger.grow', { onclick: () => removeServer(S.id) }, 'Remove'))); +function sideItem(id) { // dot, name, alert count, mini CPU / memory bars + const dot = h('i.dot'), name = h('b.grow'), count = h('span.badge'), bars = ['CPU', 'MEM'].map(l => h('div.mini', null, h('small', null, l), h('div.track', null, h('i')))); + const el = h('div.item', { onclick: () => go('server', id), oncontextmenu: e => menu(e, [...serverMenu(id, ['Open', () => go('server', id)]), + ['Move up', () => api('server/move', { id, delta: -1 })], ['Move down', () => api('server/move', { id, delta: 1 })], null, ['Edit…', () => editServer(id)], ['Remove…', () => removeServer(id)]]) }, + h('div.row', null, dot, name, count), bars); + el.update = s => { + dot.style.background = statusColor(s), name.textContent = s.cfg.name, count.textContent = s.alerts.length, count.hidden = !s.alerts.length; + el.classList.toggle('sel', id === S.id); + [s.m.cpuUsage, s.m.memPct].forEach((v, i) => Object.assign(bars[i].lastChild.firstChild.style, { width: (s.online ? clamp(v, 0, 100) : 0) + '%', background: level(v) })); + }; + return el; +} + +// ---- dashboard ---- +function card(id) { // header, four ring gauges, CPU + memory sparkline (last 5 min), net rates, alert badge + let s; + const dot = h('i.dot'), name = h('b'), addr = h('small'), chip = h('span.chip'), foot = h('div.foot'); + const grade = canvas('grade', (ctx, w) => (ring(ctx, 0, 0, w, s.health, healthColor(s.health), 4, false), text(ctx, s.grade, w / 2, w / 2, 15, healthColor(s.health), 'center', true))); + const body = canvas('rings', (ctx, w, hh) => { + const m = s.m, on = s.online, temp = m.temps > 0, gw = w / 4, gs = Math.min(gw - 14, 70), top = hh - 44; + [[m.cpuUsage, 'CPU'], [m.memPct, 'Memory'], [m.maxDiskPct, 'Disk'], temp ? [m.maxTemp, 'Temp'] : [m.swapPct, 'Swap']].forEach(([v, label], i) => { + const cx = gw * i + gw / 2, hot = i === 3 && temp; + ring(ctx, cx - gs / 2, 2, gs, on ? Math.min(100, v) : 0, !on ? C.faint : hot ? level(v, 70, 85) : level(v), 6, on); + text(ctx, on ? Fmt.fix(v) + (hot ? '°' : '%') : '—', cx, 2 + gs / 2, 14, on ? C.text : C.faint, 'center', true); + text(ctx, label, cx, gs + 6, 11, C.muted, 'center'); + }); + box(ctx, 0, top, w, 44, 8, 'rgba(0,0,0,.16)'); + for (const [v, color] of [[s.spark[1], C.violet], [s.spark[0], C.accent]]) { + if (v.length < 2) continue; + const pts = v.map((y, i) => [w - 4 - (w - 8) * (v.length - 1 - i) / 149, hh - 4 - clamp(y, 0, 100) / 100 * 36]); + ctx.beginPath(), [...pts, [pts.at(-1)[0], hh - 2], [pts[0][0], hh - 2]].forEach(p => ctx.lineTo(...p)), ctx.fillStyle = tint(color, 40), ctx.fill(); + line(ctx, pts, color, 1.5); + } + text(ctx, 'CPU', 8, top + 10, 10, C.accent), text(ctx, 'MEM', 36, top + 10, 10, C.violet); + }); + const el = h('div.card', { onclick: () => go('server', id), oncontextmenu: e => menu(e, [...serverMenu(id, ['Open details', () => go('server', id)]), ['Edit…', () => editServer(id)], ['Remove…', () => removeServer(id)]]) }, + h('div.row', null, dot, h('div.grow', null, name, addr), grade, chip), body, foot); + el.update = x => { + s = x; + const m = s.m, ap = s.cfg.autopilot, n = s.alerts.length + s.findings.length, crit = s.alerts.length || s.findings.includes('critical'); + el.style.setProperty('--status', statusColor(s)), name.textContent = s.cfg.name, addr.textContent = s.address + (m.os && ' · ' + m.os); + grade.hidden = !s.online, chip.hidden = s.online, chip.textContent = s.status, grade.redraw(), body.redraw(); + foot.replaceChildren(...(!s.online ? [h('span', { style: { color: s.status === 'Offline' ? C.red : C.muted } }, s.status === 'Disabled' ? 'Monitoring disabled' : s.status === 'Offline' ? 'Unreachable: ' + s.err : 'Waiting for data…')] : [ + h('div.row', null, h('span', { style: { color: C.teal } }, '↓ ' + Fmt.rate(m.netRxBps)), h('span.grow', { style: { color: C.pink } }, '↑ ' + Fmt.rate(m.netTxBps)), + `load ${Fmt.fix(m.load1, 2)} · up ${Fmt.duration(m.uptime)}`), + h('div.row', null, h('span.grow', null, `${m.cpuCount} cores · ${m.procs} procs` + (ap.enabled ? ap.dryRun ? ' · autopilot (dry run)' : ' · autopilot on' : '')), + n > 0 && h('span.warn', { style: { color: crit ? C.red : C.amber, background: tint(crit ? C.red : C.amber, 45) } }, '⚠ ' + n))])); + }; + return el; +} +const dash = (() => { + const sub = h('div.muted'), search = h('input', { type: 'search', placeholder: 'Search servers…', oninput: () => el.update() }), cards = h('div.cards'), events = h('div.events'); + const t = tiles([['Servers online', 'green'], ['Avg health', 'teal'], ['Active problems', 'red'], ['Avg CPU', 'accent'], ['Avg memory', 'violet'], ['Total network', 'pink']]); + const add = h('div.card.add', { onclick: () => editServer() }, h('i', null, '+'), h('b', null, 'Add server'), h('small', null, 'This machine · SSH')); + const el = h('section', null, h('div.row', null, h('div.grow', null, h('h1', null, 'Dashboard'), sub), search, h('button.primary', { onclick: () => editServer() }, '+ Add server')), t, + h('div.row.stretch.fill', null, h('div.scroll.grow', null, cards), h('div.side', null, panel('Recent events', events)))); + el.update = () => { + const on = S.servers.filter(s => s.cfg.enabled), live = on.filter(s => s.online), n = live.length, sum = f => live.reduce((a, s) => a + f(s), 0); + const problems = on.reduce((a, s) => a + s.alerts.length + (s.online && s.findings.filter(f => f !== 'info').length), 0), health = Math.round(sum(s => s.health) / n); + keyed(cards, card, [add]); + S.servers.forEach((s, i) => cards.children[i].hidden = ![s.cfg.name, s.cfg.host, s.cfg.group, s.m.hostname].join(' ').toLowerCase().includes(search.value.toLowerCase())); + sub.textContent = `${S.servers.length} server(s) monitored · updated ${tf(Date.now(), 'HH:mm:ss')}`; + t.set(0, `${n} / ${on.length}`, on.length > n ? `${on.length - n} unreachable` : 'all reachable', n === on.length ? C.green : C.amber); + t.set(2, problems, problems ? 'alerts + insights' : 'all clear', problems ? C.red : C.green); + if (!n) return [1, 3, 4, 5].forEach(i => t.set(i, '—')); + t.set(1, health, 'score 0–100', healthColor(health)); + t.set(3, Fmt.pct(sum(s => s.m.cpuUsage) / n), '', level(sum(s => s.m.cpuUsage) / n)), t.set(4, Fmt.pct(sum(s => s.m.memPct) / n), '', level(sum(s => s.m.memPct) / n)); + t.set(5, Fmt.rate(sum(s => s.m.netRxBps + s.m.netTxBps)), `↓ ${Fmt.rate(sum(s => s.m.netRxBps))} ↑ ${Fmt.rate(sum(s => s.m.netTxBps))}`); + }; + el.events = () => events.replaceChildren(...S.alerts.slice(0, 200).map(e => h('div', { style: { color: sevColor(e.severity) } }, `${tf(e.time, 'HH:mm:ss')} · ${e.serverName}`, h('br'), e.message))); + return el; +})(); + +// ---- server tabs: each builder returns an element with refresh() (new sample) and optionally analysis() ---- +function overviewTab() { + const g = ['CPU', 'Memory', 'Fullest disk', 'Swap', 'Temperature', 'Health'].map((n, i) => gauge(n, 70, i === 4 ? 85 : 90)), info = h('div'); + const t = tiles([['Load average', 'accent'], ['Processes', 'violet'], ['TCP connections', 'teal'], ['Services', 'green'], ['Uptime', 'amber']]); + const cpu = chart('CPU', pctFmt, 100, true), mem = chart('Memory', pctFmt, 100), net = chart('Network', Fmt.rate), io = chart('Disk I/O', Fmt.rate); + const el = h('div.tab.scroll', null, h('div.panel.gauges', null, g), t, h('div.row.top', null, h('div.grid2.grow', null, cpu, mem, net, io), h('div.side', null, panel('System', info)))); + el.refresh = () => { + const m = S.m, a = S.an, s = cur(), T = times(), sp = spanMs(), tcp = k => m.tcp[k] || 0; + g[0].set(m.cpuUsage, '', m.cpuCount + ' cores'), g[1].set(m.memPct, '', `${Fmt.bytes(m.memUsed)} / ${Fmt.bytes(m.memTotal)}`), g[2].set(m.maxDiskPct, '', m.fullestMount); + g[3].set(m.swapPct, '', m.swapTotal > 0 ? `${Fmt.bytes(m.swapUsed)} / ${Fmt.bytes(m.swapTotal)}` : 'no swap'); + g[4].set(Math.min(100, m.maxTemp), m.temps.length ? Fmt.temp(m.maxTemp) : '—', m.temps.length ? m.temps.length + ' sensors' : 'no sensors'); + g[5].set(a.health, String(a.health), 'grade ' + a.grade, healthColor(a.health)); + t.set(0, Fmt.fix(m.load1, 2), `5m ${Fmt.fix(m.load5, 2)} · 15m ${Fmt.fix(m.load15, 2)}`, level(m.load1 * 100 / Math.max(1, m.cpuCount), 80, 150)); + t.set(1, m.procs.length, `${m.threadsTotal} threads · ${m.procsRunning} running`); + t.set(2, tcp('ESTABLISHED'), `${tcp('LISTEN')} listening · ${tcp('TIME_WAIT')} time-wait`); + t.set(3, m.servicesRunning, m.servicesFailed ? m.servicesFailed + ' failed' : 'running · none failed', m.servicesFailed ? C.red : ''); + t.set(4, Fmt.duration(m.uptime), m.loggedUsers + ' user(s) logged in'); + cpu.set(T, cpuSeries(false), sp), mem.set(T, [ser('Used', C.violet, col(MEM)), ser('Cache', C.blue, col(CACHE), false, true), ser('Swap', C.pink, col(SWAP), false)], sp); + net.set(T, [ser('Down', C.teal, col(RX)), ser('Up', C.pink, col(TX))], sp), io.set(T, [ser('Read', C.blue, col(RD)), ser('Write', C.orange, col(WR))], sp); + info.replaceChildren(kv([['Hostname', m.hostname], ['OS', m.os], ['Kernel', m.kernel + ' ' + m.arch], ['CPU', m.cpuModel], + ['Cores', m.cpuCount + (m.avgMhz > 0 ? ` @ ${Fmt.fix(m.avgMhz / 1000, 2)} GHz` : '')], ['Memory', Fmt.bytes(m.memTotal)], ['Swap', m.swapTotal > 0 ? Fmt.bytes(m.swapTotal) : 'none'], + ['Virtualisation', m.virt], ['Disks', m.mounts.length + ' mounted file systems'], ['Interfaces', m.nets.length], ['GPU', m.gpus[0]?.name || 'none'], + ['Connection', `${s.address} (${s.cfg.transport ? 'SSH' : 'Local'})`], ['Sample interval', s.cfg.interval + ' s']])); + }; + return el; +} + +function cpuTab() { + const P = S.plat, model = h('h2'), cores = h('div.cores'); + const t = tiles([['Usage', 'accent'], ['Load 1 / 5 / 15', 'violet'], ['Avg frequency', 'teal'], [P.posixCpu ? 'Steal / IRQ' : 'Interrupts + DPC', 'orange'], ['Context switches', 'blue'], + ['Interrupts', 'pink'], ['New processes', 'green'], ['Running / blocked', 'amber']], 4); + const usage = chart('CPU time breakdown', pctFmt, 100, true), load = chart('Load average (1 min)', numFmt(1)); + const temps = table(['Sensor', 'Temperature'], { widths: [300], empty: ['No temperature sensors exposed (common on VMs)', C.muted] }); + const gpus = table(['#', 'Name', 'Usage', 'Memory', 'Temp', 'Power', 'Fan'], { widths: [40, 220, 120, 160] }), gpuPanel = panel('GPUs', gpus); + const el = h('div.tab.scroll', null, model, t, h('div.row.top', null, h('div.grow3', null, usage), h('div.grow2', null, load)), panel('Per core', cores), + h('div.grid2', null, panel('Temperatures', temps), gpuPanel)); + el.refresh = () => { + const m = S.m, T = times(), f2 = v => Fmt.fix(v, 2); + model.textContent = m.cpuModel || 'Processor'; + t.set(0, Fmt.pct(m.cpuUsage), `user ${Fmt.pct(m.cpuUser)} · system ${Fmt.pct(m.cpuSystem)}` + (P.posixCpu ? ` · iowait ${Fmt.pct(m.cpuIowait)}` : ''), level(m.cpuUsage)); + t.set(1, `${f2(m.load1)} / ${f2(m.load5)} / ${f2(m.load15)}`, `${Math.round(m.load1 * 100 / Math.max(1, m.cpuCount))}% of ${m.cpuCount} cores`); + t.set(2, m.avgMhz > 0 ? f2(m.avgMhz / 1000) + ' GHz' : 'n/a'); + if (P.posixCpu) t.set(3, `${Fmt.pct(m.cpuSteal)} / ${Fmt.pct(m.cpuIrq)}`, 'steal > 5% = noisy neighbours', m.cpuSteal > 5 ? C.amber : ''); + else t.set(3, Fmt.pct(m.cpuIrq), 'hardware interrupts and deferred calls', m.cpuIrq > 15 ? C.amber : ''); + t.set(4, Fmt.count(m.ctxtPerSec) + '/s'), t.set(5, Fmt.count(m.intrPerSec) + '/s'), t.set(6, Fmt.fix(m.forksPerSec, 1) + '/s'); + t.set(7, `${m.procsRunning} / ${m.procsBlocked}`, P.posixCpu ? 'blocked = waiting for I/O' : 'blocked = waiting for a CPU', m.procsBlocked > m.cpuCount ? C.amber : ''); + usage.set(T, cpuSeries(true), spanMs()), load.set(T, [ser('Load', C.violet, col(LOAD)), ser('Cores', C.faint, T.map(() => m.cpuCount), false, true)], spanMs()); + cores.replaceChildren(...m.cores.map((c, i) => { + const color = level(c.usage, 60, 85); + return h('div', { style: { background: mix(C.card, color, c.usage / 420), 'border-color': mix(C.border, color, c.usage / 160) } }, + h('small', null, 'CPU ' + i, c.mhz > 0 && h('span', null, Fmt.fix(c.mhz / 1000, 1) + 'G')), h('b', null, pctFmt(c.usage)), h('div.track', null, h('i', { style: { width: c.usage + '%', background: color } }))); + })); + temps.fill(m.temps.map(x => [x.name, { t: Fmt.temp(x.celsius), pct: Math.min(100, x.celsius) }])); + gpuPanel.hidden = !m.gpus.length; + gpus.fill(m.gpus.map(x => [x.index, x.name, { t: Fmt.pct(x.util, 0), pct: x.util }, { t: `${Fmt.num(x.memUsed)} / ${Fmt.num(x.memTotal)} MiB`, pct: x.memTotal > 0 ? x.memUsed * 100 / x.memTotal : 0 }, + { t: Fmt.temp(x.temp), c: level(x.temp, 75, 88) }, Fmt.num(x.power) + ' W', Fmt.pct(x.fan, 0)])); + }; + return el; +} + +function memoryTab() { + const t = tiles([['Used', 'violet'], ['Available', 'green'], ['Cache + buffers', 'blue'], ['Swap used', 'pink']]), bar = segbar(), swap = segbar(), detail = h('div'); + const usage = chart('Memory usage', pctFmt, 100), top = table(['PID', 'Process', 'User', 'RSS', 'Memory %', 'Virtual'], { widths: [80, 220, 120, 110, 160] }); + const el = h('div.tab.scroll', null, t, panel('Composition', bar, h('div.section', null, 'Swap'), swap), h('div.row.top', null, h('div.grow', null, usage), h('div.side', null, panel('Details', detail))), + panel('Top memory consumers', top)); + el.refresh = () => { + const m = S.m, free = '#364463'; + t.set(0, Fmt.bytes(m.memUsed), `${Fmt.pct(m.memPct)} of ${Fmt.bytes(m.memTotal)}`, level(m.memPct)), t.set(1, Fmt.bytes(m.memAvailable), 'free ' + Fmt.bytes(m.memFree)); + t.set(2, Fmt.bytes(m.cached + m.buffers), 'reclaimable when needed'); + t.set(3, m.swapTotal > 0 ? Fmt.bytes(m.swapUsed) : 'no swap', m.swapTotal > 0 ? `${Fmt.pct(m.swapPct)} of ${Fmt.bytes(m.swapTotal)}` : '', level(m.swapPct, 40, 80)); + bar.set([[Math.max(0, m.memTotal - m.memFree - m.cached - m.buffers), C.violet, 'Applications'], [m.shared, C.pink, 'Shared'], [m.buffers, C.teal, 'Buffers'], + [Math.max(0, m.cached - m.shared), C.blue, 'Cache'], [m.memFree, free, 'Free']], m.memTotal); + swap.set([[m.swapUsed, C.pink, 'Used'], [m.swapTotal - m.swapUsed, free, 'Free']], m.swapTotal); + usage.set(times(), [ser('Used', C.violet, col(MEM)), ser('Cache', C.blue, col(CACHE), false, true), ser('Swap', C.pink, col(SWAP))], spanMs()); + detail.replaceChildren(kv([['Total', m.memTotal], ['Used', m.memUsed], ['Available', m.memAvailable], ['Free', m.memFree], ['Buffers', m.buffers], ['Cached', m.cached], ['Shared', m.shared], + ['Slab', m.slab], ['Dirty', m.dirty], ['Swap total', m.swapTotal], ['Swap used', m.swapUsed]].map(([k, v]) => [k, Fmt.bytes(v)]))); + top.fill(m.procs.toSorted((a, b) => b.rss - a.rss).slice(0, 15).map(p => [{ t: p.pid, c: C.muted }, p.name, { t: p.user, c: C.muted }, { t: Fmt.bytes(p.rss), r: 1 }, + { t: Fmt.pct(p.memPct), pct: Math.min(100, p.memPct * 2) }, { t: Fmt.bytes(p.vsz), c: C.muted, r: 1 }])); + }; + return el; +} + +function storageTab() { + const t = tiles([['Fullest file system', 'amber'], ['Read', 'blue'], ['Write', 'orange'], ['Busiest disk', 'red']]), io = chart('Disk throughput', Fmt.rate); + const mounts = table(['Mount point', 'Device', 'Type', 'Size', 'Used', 'Free', 'Usage'], { widths: [260, 140, 80, 110, 110, 110] }); + const disks = table(['Device', 'Read/s', 'Write/s', 'Read IOPS', 'Write IOPS', 'Busy', 'Total read', 'Total written'], { widths: [110, 110, 110, 100, 100, 150, 120] }); + const el = h('div.tab.scroll', null, t, panel('File systems', mounts), io, panel('Block devices', disks)); + el.refresh = () => { + const m = S.m, right = (t, c) => ({ t, c, r: 1 }); + t.set(0, Fmt.pct(m.maxDiskPct), m.fullestMount, level(m.maxDiskPct, 80, 90)), t.set(1, Fmt.rate(m.diskReadBps)), t.set(2, Fmt.rate(m.diskWriteBps)); + t.set(3, Fmt.pct(m.maxDiskUtil), m.busiestDisk, level(m.maxDiskUtil, 60, 90)); + io.set(times(), [ser('Read', C.blue, col(RD)), ser('Write', C.orange, col(WR))], spanMs()); + mounts.fill(m.mounts.map(x => [x.mount, { t: x.device, c: C.muted }, { t: x.type, c: C.muted }, right(Fmt.bytes(x.total)), right(Fmt.bytes(x.used)), right(Fmt.bytes(x.avail)), { t: Fmt.pct(x.pct), pct: x.pct }])); + disks.fill(m.disks.map(d => [d.name, right(Fmt.rate(d.readBps), C.blue), right(Fmt.rate(d.writeBps), C.orange), right(Fmt.fix(d.readIops)), right(Fmt.fix(d.writeIops)), + { t: Fmt.pct(d.util, 0), pct: d.util }, right(Fmt.bytes(d.totalRead), C.muted), right(Fmt.bytes(d.totalWritten), C.muted)])); + }; + return el; +} + +function networkTab() { + const t = tiles([['Download', 'teal'], ['Upload', 'pink'], ['Established', 'accent'], ['Listening', 'green'], ['Time-wait / close-wait', 'amber'], ['Sockets in use', 'violet']]); + const iface = h('select', { onchange: () => el.refresh() }), traffic = chart('Traffic', Fmt.rate); + const nets = table(['Interface', 'State', 'Speed', 'Down/s', 'Up/s', 'Pkts in/s', 'Pkts out/s', 'Received', 'Sent', 'Errors', 'Drops'], { widths: [160, 80, 90, 110, 110, 90, 90, 110, 110, 70] }); + const el = h('div.tab.scroll', null, t, h('div.row', null, h('span.muted', null, 'Interface'), iface), traffic, panel('Interfaces', nets)); + el.refresh = () => { + const m = S.m, tcp = k => m.tcp[k] || 0, names = ['All physical (total)', ...m.nets.map(n => n.name)], right = (t, c) => ({ t, c, r: 1 }); + t.set(0, Fmt.rate(m.netRxBps), 'physical interfaces'), t.set(1, Fmt.rate(m.netTxBps)), t.set(2, tcp('ESTABLISHED'), 'TCP'), t.set(3, tcp('LISTEN'), 'open TCP ports'); + t.set(4, `${tcp('TIME_WAIT')} / ${tcp('CLOSE_WAIT')}`, 'many close-wait = app not closing sockets', tcp('CLOSE_WAIT') > 100 ? C.amber : ''), t.set(5, m.socketsUsed); + if ([...iface.options].map(o => o.text).join('\n') !== names.join('\n')) { + const was = iface.value; + iface.replaceChildren(...names.map(n => h('option', null, n))), iface.selectedIndex = Math.max(0, names.indexOf(was)); + } + const all = iface.selectedIndex <= 0, own = k => S.live.map(r => r.net[iface.value]?.[k] ?? 0); + traffic.head = 'Traffic — ' + (all ? 'all physical interfaces' : iface.value); + traffic.set(times(), [ser('Down', C.teal, all ? col(RX) : own(0)), ser('Up', C.pink, all ? col(TX) : own(1))], spanMs()); + nets.fill(m.nets.map(x => { + const dim = x.virt ? C.muted : ''; + return [{ t: x.name + (x.virt ? ' (virtual)' : ''), c: dim }, { t: x.state, c: x.state === 'up' ? C.green : x.state === 'down' ? C.red : C.muted }, { t: x.speed > 0 ? x.speed + ' Mb/s' : '—', c: C.muted }, + right(Fmt.rate(x.rxBps), C.teal), right(Fmt.rate(x.txBps), C.pink), right(Fmt.fix(x.rxPps), dim), right(Fmt.fix(x.txPps), dim), right(Fmt.bytes(x.rxBytes), dim), right(Fmt.bytes(x.txBytes), dim), + right(x.errors, x.errors ? C.amber : dim), right(x.drops, x.drops ? C.amber : dim)]; + })); + }; + return el; +} + +// filterable, sortable list that keeps its selection across refreshes (processes, services) +function listTab(headers, widths, sort, hint) { + const filter = h('input', { type: 'search', placeholder: hint, oninput: () => tbl.render() }), summary = h('span.muted.grow'), status = h('div.muted'); + const tbl = table(headers, { widths, sort, sortable: true, select: true }), bar = h('div.row', null, filter, summary), el = h('div.tab.col', null, bar, tbl, status); + tbl.accept = r => r.some(c => cellText(c).toLowerCase().includes(filter.value.toLowerCase())); + el.report = async (label, path, body) => { // run a command and show the result in the status line + status.textContent = 'Running: ' + label, status.style.color = ''; + const r = await api(path, { id: S.id, ...body }); + status.textContent = r.code ? `✗ ${r.cmd}: ${r.out.trim().slice(0, 300)}` : '✓ ' + r.cmd, status.style.color = r.code ? C.red : C.green; + }; + el.selected = what => tbl.selRow() ? tbl.sel : void (status.textContent = `Select a ${what} first.`, status.style.color = ''); + return Object.assign(el, { tbl, bar, summary }); +} + +function processTab() { + const P = S.plat, freeze = h('input', { type: 'checkbox' }); + const el = listTab(['PID', 'Name', 'User', 'State', 'CPU', 'Memory', 'RSS', 'Threads', P.prioLabel, 'Running for'], [80, 230, 120, 100, 130, 130, 100, 80, 70], [4, true], 'Filter by name, user or PID…'); + const STATES = { R: ['Running', C.green], S: ['Sleeping', C.muted], D: ['Disk wait', C.amber], Z: ['Zombie', C.red], T: ['Stopped', C.red], I: ['Idle', C.muted] }; + const picked = () => el.selected('process') && { pid: el.tbl.sel, who: `${cellText(el.tbl.selRow()[1])} (${el.tbl.sel})` }; // read before a question: the list keeps refreshing behind it + const send = (list, i, label, p) => el.report(`${label} ${p.who}`, 'run', { list, i, arg: p.pid }); + const run = (c, i) => async () => { + const p = picked(); + if (p && (!c.confirm || await ask(c.label, `${c.label} ${p.who} on ${cur().cfg.name}?`, c.danger))) send('procActions', i, c.label, p); + }; + const renice = async () => { + const p = picked(), pick = h('select', null, P.priorities.map(c => h('option', null, c.label))); + pick.selectedIndex = P.priorities.length >> 1; + if (p && await dialog('Change priority', h('div.col', null, `Priority for ${p.who}:`, pick), [['OK', '.primary', () => true], ['Cancel', '', () => false]])) send('priorities', pick.selectedIndex, 'Priority', p); + }; + const acts = P.procActions.map((c, i) => [c, run(c, i)]); + el.bar.firstChild.after(h('label.check', { title: "Stop refreshing so rows don't move while you pick one" }, freeze, 'Freeze list')); + el.bar.append(...acts.filter(([c]) => c.button).map(([c, fn]) => h('button' + (c.danger ? '.danger' : ''), { onclick: fn }, c.label)), h('button', { onclick: renice }, 'Priority…')); + el.tbl.menu = () => [...acts.map(([c, fn]) => [c.label, fn]), null, ['Change priority…', renice]]; + el.refresh = () => { + const m = S.m, num = (v, c) => ({ t: v, k: v, c, r: 1 }); + if (freeze.checked) return; + el.tbl.fill(m.procs.map(p => [num(p.pid, C.muted), p.name, { t: p.user, c: C.muted }, { t: (STATES[p.state] || [p.state])[0], c: (STATES[p.state] || [0, C.muted])[1] }, + { t: Fmt.pct(p.cpu), pct: Math.min(100, p.cpu), k: p.cpu }, { t: Fmt.pct(p.memPct), pct: p.memPct, k: p.memPct }, { ...num(p.rss), t: Fmt.bytes(p.rss) }, num(p.threads), + num(p.nice, p.nice === P.normalPrio ? '' : C.teal), { ...num(p.age, C.muted), t: Fmt.duration(p.age) }])); + el.summary.textContent = `${m.procs.length} processes · ${m.procs.filter(p => p.state === 'R').length} running · ${m.threadsTotal} threads`; + }; + return el; +} + +function serviceTab() { + const P = S.plat, el = listTab(['Service', 'Active', 'State', 'Load', 'Description'], [300, 100, 100, 90], [0, false], 'Filter services…'), matches = el.tbl.accept; + const state = h('select', { onchange: () => el.tbl.render() }, ['All', 'Running', 'Failed', 'Not running'].map(t => h('option', null, t))); + const act = (c, i) => async () => { + const unit = el.selected('service'); + if (unit && (!c.confirm || await ask('Confirm', `${c.label} ${unit} on ${cur().cfg.name}?`, c.danger))) el.report(`${c.label} ${unit}`, 'run', { list: 'serviceActions', i, arg: unit }); + }; + const logs = () => { + const unit = el.tbl.selRow() && el.tbl.sel, id = S.id, out = h('pre.log', null, 'Loading…'), lines = h('input', { type: 'number', min: 50, max: 5000, value: 300 }); + const load = async () => (out.textContent = (await api('logs', { id, unit, lines: lines.value })).out, out.scrollTop = out.scrollHeight); + if (unit) load(), dialog(`Logs — ${unit} — ${cur().cfg.name}`, h('div.col', null, out, h('div.row', null, lines, 'lines', h('button', { onclick: load }, 'Reload'))), [['Close', '', () => true]], '.wide'); + }; + const acts = P.serviceActions.map((c, i) => [c.label, act(c, i), c.danger]); + let shown; + el.tbl.accept = r => { + const [, active, sub] = r.map(cellText), i = state.selectedIndex; + return (!i || (i === 1 && sub === 'running') || (i === 2 && active === 'failed') || (i === 3 && sub !== 'running' && active !== 'failed')) && matches(r); + }; + el.bar.firstChild.after(state); + el.bar.append(...acts.map(([label, fn, danger]) => h('button' + (danger ? '.danger' : ''), { onclick: fn }, label)), h('button.primary', { onclick: logs }, 'Logs')); + el.tbl.menu = () => [...acts, null, ['Show logs', logs]]; + el.tbl.addEventListener('dblclick', logs); + el.refresh = () => { + const m = S.m, sig = m.services.map(x => x.unit + x.active + x.sub).join(); + if (sig === shown) return; // unchanged: keep the list still + shown = sig; + el.tbl.fill(m.services.map(x => { + const c = x.active === 'failed' ? C.red : x.sub === 'running' ? C.green : x.active === 'active' ? C.teal : C.muted; + return [x.unit, { t: x.active, c }, { t: x.sub, c }, { t: x.load, c: C.muted }, { t: x.description, c: C.muted }]; + })); + el.summary.textContent = m.services.length ? `${m.services.length} services · ${m.servicesRunning} running · ${m.servicesFailed} failed` : 'No services reported by this machine'; + }; + return el; +} + +function historyTab() { + const P = S.plat, id = S.id, RANGES = [['1 h', 3600], ['6 h', 21600], ['24 h', 86400], ['7 d', 604800], ['30 d', 2592000], ['90 d', 7776000], ['1 y', 31536000], ['All', 0]]; + let range = 86400, loaded = 0; + const res = h('span.muted.grow'), csv = h('a.button', null, 'Export CSV…'), buttons = RANGES.map(([t, sec]) => h('button', { onclick: () => (range = sec, reload()) }, t)); + const charts = [['CPU', pctFmt, 100], ['Memory & swap', pctFmt, 100], ['Disk usage (fullest)', pctFmt, 100], ['Disk throughput', Fmt.rate], ['Network', Fmt.rate], ['Load average', numFmt(1)], + ['Temperature', v => Fmt.fix(v) + '°'], ['Availability', pctFmt, 100]].map(([t, fmt, max]) => chart(t, fmt, max, false, 'No history for this range yet')); + const st = table(['Metric', 'Minimum', 'Average', '95th percentile', 'Peak', 'Points'], { widths: [200, 150, 150, 150, 150] }); + const el = h('div.tab.scroll', null, h('div.row', null, buttons, res, csv), h('div.grid2', null, charts), panel('Statistics for the selected range', st)); + async function reload() { + const query = `?id=${encodeURIComponent(id)}&range=${range}`, right = (t, c) => ({ t, c, r: 1 }); + loaded = Date.now(), csv.href = '/api/history.csv' + query, buttons.forEach((b, i) => b.classList.toggle('on', RANGES[i][1] === range)); + const d = await api('history' + query), v = d.v, peak = (name, color, data) => d.aggregated ? [ser(name, color, data, false, true)] : []; + const data = [[ser('Average', C.accent, v.cpu), ...peak('Peak', C.red, v.cpuMax)], [ser('Memory', C.violet, v.mem), ser('Swap', C.pink, v.swap, false)], [ser('Usage', C.amber, v.disk)], + [ser('Read', C.blue, v.rd), ser('Write', C.orange, v.wr)], [ser('Down', C.teal, v.rx), ser('Up', C.pink, v.tx), ...peak('Peak down', '#60ffeb', v.rxMax)], [ser('Load', C.violet, v.load)], + [ser('Average', C.orange, v.temp), ...peak('Peak', C.red, v.tempMax)], [ser('Online', C.green, v.avail)]]; + charts.forEach((c, i) => (c.sub = d.aggregated ? 'avg per ' + d.tier : '', c.set(d.t, data[i], d.span))); + res.textContent = `Resolution: ${d.tier} · ${d.points} points · availability ${ok(d.availability) ? Fmt.pct(d.availability, 2) : '—'} · stored ${Fmt.bytes(d.bytes)}`; + st.fill(d.stats.map((x, m) => [hNames[m], right(fmtMetric(m, x.min), C.muted), right(fmtMetric(m, x.avg)), right(fmtMetric(m, x.p95), C.amber), right(fmtMetric(m, x.max), C.red), right(x.count, C.muted)]) + .filter((_, m) => m < 14 && (P.posixCpu || m !== 1))); + } + el.refresh = () => Date.now() - loaded >= (range && range <= 21600 ? 5000 : 60000) && reload(); + return el; +} + +function insightsTab() { + const id = S.id, ap = { ...cur().cfg.autopilot }, f = fields(ap, () => api('server/update', { id, autopilot: ap })); + const health = gauge('Health score'), reasons = h('div.muted.pre'), capacity = h('div.col'), findings = h('div.col'), heat = h('div.heat'); + const t = tiles([['Disk full forecast', 'amber'], ['Memory trend (6 h)', 'violet'], ['CPU / memory p95 (30 d)', 'accent'], ['Availability 24 h', 'green'], ['Availability 7 d', 'green'], ['Availability 30 d', 'green']], 3); + const heatMetric = h('select', { onchange: () => el.analysis() }, h('option', null, 'CPU'), h('option', null, 'Memory')); + const anomalies = table(['Metric', 'Last 10 min', 'Usual', 'Deviation', 'Baseline'], { widths: [110, 110, 160, 90] }); + const autopilot = panel('Autopilot — automatic control', h('div.muted', null, 'Acts on the findings once a minute, using statistics over the stored history. Every action is logged as an event.'), form([ + [f.check('enabled', 'Autopilot enabled'), f.check('dryRun', 'Dry run (only report)')], + [f.check('restartFailed', 'Restart failed services'), [f.num('maxRestartsPerHour', 1, 20), '/ hour max']], + ['Runaway processes', f.select('runawayMode', [['none', 'Ignore'], ['renice', 'Lower priority (renice 19)'], ['terminate', 'Terminate']])], + ['', ['≥', f.num('runawayCpu', 10, 6400), '% for', f.num('runawayMinutes', 1, 1440), 'min']], + ['Memory leaks', f.select('leakMode', [['none', 'Ignore'], ['notify', 'Notify'], ['terminate', 'Terminate under pressure']])], [' pressure ≥', [f.num('leakMemPressure', 50, 100), '% memory']], + [f.check('diskCleanup', 'Disk cleanup'), ['full in <', f.num('diskForecastDays', 1, 60), 'days']], ['', ['or usage ≥', f.num('diskCleanupAt', 50, 100), '%']], + [' command', f.text('diskCleanupCommand', { className: 'mono grow' })], [f.check('anomalyAlerts', 'Anomaly alerts'), ['z ≥', f.num('anomalyZ', 1.5, 10, .5), 'σ']]])); + const el = h('div.tab.scroll', null, + h('div.row.top', null, h('div.side', null, panel('Health', health, reasons, h('button', { onclick: () => api('server/analyze', { id }) }, 'Analyze now'))), h('div.col.grow', null, t, panel('Capacity planning', capacity))), + h('div.row.top', null, h('div.grow', null, panel('Findings from history analysis', findings)), h('div.side.wide', null, autopilot)), + h('div.row.top', null, h('div.grow3', null, panel('Weekly pattern (last 4 weeks, hourly averages)', heatMetric, heat)), h('div.grow2', null, panel('Now vs. normal (baselines)', anomalies)))); + el.analysis = () => { + const a = S.an, s = cur(), hi = heatMetric.selectedIndex, f2 = v => Fmt.fix(v, 2), days = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']; + health.set(a.health, String(a.health), 'grade ' + a.grade, healthColor(a.health)); + reasons.textContent = (a.healthReasons.join('\n') || 'No deductions — everything looks healthy.') + (a.when ? '\n\nAnalyzed ' + tf(a.when * 1000, 'HH:mm:ss') : ''); + if (a.diskFullDays >= 0) t.set(0, Fmt.duration(a.diskFullDays * 86400), `+${f2(a.diskSlopePerDay)} pts/day · ${a.diskBasis}`, a.diskFullDays < 7 ? C.red : a.diskFullDays < 30 ? C.amber : ''); + else t.set(0, 'Not filling', a.diskBasis ? `trend ${f2(a.diskSlopePerDay)} pts/day` : 'needs ~2 h of history', C.green); + if (a.memTrendR2 > 0) t.set(1, `${a.memSlopePerHour >= 0 ? '+' : ''}${f2(a.memSlopePerHour)} pts/h`, 'fit R² ' + f2(a.memTrendR2), a.memSlopePerHour > 1 && a.memTrendR2 > .8 ? C.amber : ''); + else t.set(1, '—', 'needs ~90 min of history'); + if (a.cpu30.count) t.set(2, `${Fmt.pct(a.cpu30.p95, 0)} / ${Fmt.pct(a.mem30.p95, 0)}`, `avg ${Fmt.pct(a.cpu30.avg, 0)} / ${Fmt.pct(a.mem30.avg, 0)}`); + else t.set(2, '—', 'collecting'); + a.up.forEach((up, i) => ok(up) ? t.set(3 + i, Fmt.pct(up, up >= 99.995 ? 0 : 2), `≈ ${Fmt.duration(a.down[i])} offline`, up >= 99.9 ? C.green : up >= 99 ? C.amber : C.red) + : t.set(3 + i, '—', 'no data yet')); + capacity.replaceChildren(...a.capacity.map(line => h('div', null, '• ' + line))); + heat.replaceChildren(...days.flatMap((day, d) => [h('small', null, day.slice(0, 3)), ...a.heat[hi][d].map((v, hour) => h('i', { + title: `${day} ${hour}:00 — ` + (ok(v) ? `avg ${Fmt.fix(v, 1)}${hi ? '% memory' : '% CPU'} (${a.heatN[d][hour]} samples)` : 'no data'), + style: { background: ok(v) ? mix('#1b2a44', hi ? C.violet : C.accent, .15 + .85 * v / 100) : C.card } }))]), + h('small'), ...Array.from({ length: 24 }, (_, hour) => h('small', null, hour % 3 ? '' : pad(hour) + ':00')), + ...(a.heatN.flat().some(Boolean) ? [] : [h('p', null, 'Collecting hourly history… the weekly pattern fills in over time')])); + anomalies.fill(a.anomalies.map(x => [x.metric, { t: fmtMetric(x.hm, x.now), r: 1 }, { t: `${fmtMetric(x.hm, x.mean)} ± ${fmtMetric(x.hm, x.sd)}`, c: C.muted, r: 1 }, + { t: `${x.z >= 0 ? '+' : ''}${Fmt.fix(x.z, 1)}σ`, c: Math.abs(x.z) >= 3 ? C.red : Math.abs(x.z) >= 2 ? C.amber : C.green, r: 1 }, { t: x.baseline, c: C.muted }])); + findings.replaceChildren(...a.findings.map(x => { + const color = sevColor(x.severity), auto = x.autoEligible && s.cfg.autopilot.enabled; + const fix = x.action && h('button' + (x.action === 'kill_pid' ? '.danger' : '.primary'), { onclick: async () => { // the card may be rebuilt while the question is open + if (!await ask(x.actionLabel, `${x.actionLabel} on ${s.cfg.name}?\n\n${x.title}`, x.action === 'kill_pid')) return; + fix.disabled = true, fix.textContent = 'Working…'; + fix.textContent = (await api('finding', { id, key: x.key })).code ? '✗ Failed' : '✓ Done'; + } }, x.actionLabel); + return h('div.finding', { style: { 'border-left-color': color } }, h('div.grow', null, h('small', { style: { color } }, `${x.severity} · ${x.category}`), h('b', null, x.title), h('div', null, x.detail), + h('div.muted', null, '→ ' + x.advice), auto && h('small', { style: { color: C.violet } }, s.cfg.autopilot.dryRun ? 'Autopilot (dry run) would act on this' : 'Autopilot handles this automatically')), fix); + })); + if (!a.findings.length) findings.append(h('div', { style: { color: C.green } }, + '✓ No problems found in the history. The analyzer checks disk forecasts, memory trends, leaks, runaway processes, service failures, overload and anomalies every minute.')); + }; + return el; +} + +function rulesTab() { + const P = S.plat, id = S.id, metrics = ruleMetrics.filter(d => P.posixCpu || d[0] !== 'iowait'), store = rules => api('server/update', { id, rules }); + const list = table(['On', 'Condition', 'Severity', 'Action', 'Cooldown', 'Live value'], { widths: [50, 380, 100, 330, 100], select: true }); + const active = table(['Active problems'], { empty: ['✓ No rule is currently triggered', C.green] }); + const edit = async old => { + const rs = cur().cfg.rules, r = { ...(old || S.rule) }, f = fields(r, () => sync()), arg = f.text('arg', { className: 'grow' }); + const sync = () => (arg.placeholder = def(P.ruleActions, r.action)[2], arg.disabled = !arg.placeholder); + sync(); + if (!await dialog(old ? 'Edit rule' : 'New rule', form([['When', f.select('metric', metrics.map(([k, label, unit]) => [k, label + (unit && ` (${unit})`)]))], + ['is', [f.select('op', [['>', '>'], ['<', '<']]), f.num('value', -1e9, 1e9, 'any')]], ['for at least', [f.num('duration', 0, 86400), 's']], + ['Severity', f.select('severity', ['info', 'warning', 'critical'].map(x => [x, x]))], ['Then', f.select('action', P.ruleActions)], ['Argument', arg], + ['Repeat after', [f.num('cooldown', 10, 86400), 's']], ['', f.check('enabled', 'Enabled')]]), [['OK', '.primary', () => true], ['Cancel', '', () => false]])) return; + if (arg.disabled) r.arg = ''; + store(old ? rs.map(x => x === old ? r : x) : [...rs, r]); + }; + const selected = () => cur().cfg.rules.find(r => r.id === list.sel); + const el = h('div.tab.col', null, h('div.muted', null, 'Threshold rules are checked on every sample. When a condition holds for its duration an alert is raised and the action runs; ' + + 'if it is still true after the cooldown the action runs again. History-based automation lives in the Insights tab.'), + h('div.row', null, h('button.primary', { onclick: () => edit() }, '+ Add rule'), h('button', { onclick: () => selected() && edit(selected()) }, 'Edit'), + h('button.danger', { onclick: () => selected() && store(cur().cfg.rules.filter(r => r.id !== list.sel)) }, 'Delete'), h('span.grow'), + h('button', { onclick: async () => await ask('Reset rules', 'Replace all rules with the defaults?') && store(S.defaultRules) }, 'Reset to defaults')), list, active); + let shown, boxes; + list.addEventListener('dblclick', () => selected() && edit(selected())); + el.refresh = () => { + const s = cur(), rs = s.cfg.rules; + if (shown !== (shown = JSON.stringify(rs))) boxes = rs.map(r => h('input', { type: 'checkbox', checked: r.enabled, onchange: e => store(rs.map(x => x === r ? { ...r, enabled: e.target.checked } : x)) })); + list.fill(rs.map((r, i) => { + const v = S.vals[r.metric] ?? 0; + return Object.assign([{ el: boxes[i] }, { t: conditionText(r), c: r.enabled ? '' : C.faint }, { t: r.severity, c: sevColor(r.severity) }, { t: actionText(P.ruleActions, r), c: r.action === 'notify' ? C.muted : C.violet }, + { t: r.cooldown + ' s', c: C.muted }, { t: `${Fmt.fix(v, 1)} ${def(ruleMetrics, r.metric)[2]}`, c: (r.op === '<' ? v < r.value : v > r.value) ? C.red : C.green }], { key: r.id }); + })); + active.fill(s.alerts.map(a => [{ t: '⚠ ' + a, c: C.red }])); + }; + return el; +} + +function consoleTab() { + const P = S.plat, s = cur(), id = S.id, out = h('div.console.mono'), sudo = h('input', { type: 'checkbox' }), past = []; + let pos = 0; + const say = (cls, ...parts) => { // keeps the last 2000 blocks + out.append(h('div' + cls, null, parts)), out.childElementCount > 2000 && out.firstChild.remove(), out.scrollTop = out.scrollHeight; + }; + const exec = async (cmd, privileged) => { + const t0 = Date.now(); + say('.cmd', h('b', null, tf(t0, 'HH:mm:ss') + ' $ '), cmd); + const r = await api('exec', { id, cmd, privileged }); + if (r.out) say('', r.out.replace(/\n$/, '')); + say(r.code ? '.bad' : '.good', `[exit ${r.code} · ${Date.now() - t0} ms]`); + }; + const run = () => { + const c = input.value.trim(); + if (!c) return; + if (past.at(-1) !== c) past.push(c); + pos = past.length, input.value = '', exec(c, sudo.checked); + }; + const input = h('input.mono.grow', { placeholder: 'Type a shell command and press Enter (↑/↓ history)', onkeydown: e => { + if (e.key === 'Enter') return run(); + if (!past.length || !['ArrowUp', 'ArrowDown'].includes(e.key)) return; + e.preventDefault(), pos = clamp(pos + (e.key === 'ArrowUp' ? -1 : 1), 0, past.length), input.value = past[pos] || ''; + } }); + const group = (title, items, system) => panel(title, items.map(q => h('button.left' + (q.danger ? '.danger' : ''), { title: q.cmd, onclick: async () => { + if (!system || await ask(q.label, `${q.label} on ${s.cfg.name}?` + (q.danger ? '\n\nThe machine will be unavailable until it comes back.' : ''), q.danger)) exec(q.cmd, system); + } }, q.label))); + say('.muted', `Console for ${s.cfg.name} (${s.address}). Commands run non-interactively with a 120 s timeout.`); + return h('div.tab.row.stretch', null, h('div.col.grow', null, out, h('div.row', null, h('b.prompt', null, '$'), input, + P.sudo && h('label.check', { title: "Wrap in sudo -n when the server has 'Run control commands with sudo' enabled" }, sudo, 'privileged'), + h('button.primary', { onclick: run }, 'Run'), h('button', { onclick: () => out.replaceChildren() }, 'Clear'))), + h('div.side.col.scroll', null, group('Quick diagnostics', P.diagnostics, false), group('System actions', P.systemActions, true))); +} + +// ---- server page ---- +const TABS = { overview: ['Overview', overviewTab], cpu: ['CPU', cpuTab], memory: ['Memory', memoryTab], storage: ['Storage', storageTab], network: ['Network', networkTab], + processes: ['Processes', processTab], services: ['Services', serviceTab], history: ['History', historyTab], insights: ['Insights & Autopilot', insightsTab], + rules: ['Alert rules', rulesTab], console: ['Console', consoleTab] }; +let feed, built = {}, builtFor; // the open live stream; tab elements of the server they were built for +const detail = (() => { + const name = h('h1'), state = h('b.state'), sub = h('div.muted'), chips = h('div.chips'), holder = h('div.fill'); + const act = (path, extra) => api(path, { id: S.id, ...extra }); + const pause = h('button', { onclick: () => act('server/pause', { paused: !cur().paused }) }); + const power = reboot => async () => await ask(reboot ? 'Reboot…' : 'Shut down…', `${reboot ? 'Reboot' : 'Shut down'} ${cur().cfg.name} now?`, true) && act('power', { reboot }); + const span = h('select', { onchange: () => (S.span = +span.value, el.refresh()) }, [5, 15, 30, 60].map(min => h('option', { value: min, selected: min === S.span }, min === 60 ? 'Last hour' : `Last ${min} minutes`))); + const bar = h('div.tabbar', null, Object.entries(TABS).map(([key, [title]]) => h('button', { onclick: () => go('server', S.id, key) }, title))); + const el = h('section', null, h('div.row.end', null, h('div.grow', null, h('button.flat', { onclick: () => go('dashboard') }, '‹ Dashboard'), h('div.row', null, name, state), sub, chips), + h('label.col', null, h('div.section', null, 'Live window'), span), h('button', { onclick: () => act('server/reconnect') }, '⟳ Reconnect'), pause, h('button', { onclick: () => editServer(S.id) }, 'Edit'), + h('button.danger', { onclick: e => menu(e, [['Reboot…', power(true)], ['Shut down…', power(false)], null, ['Remove from monitor…', () => removeServer(S.id)]]) }, '⏻ Power')), bar, holder); + el.refresh = withAnalysis => { // header, then the visible tab + const s = cur(), c = s?.cfg, m = s?.m; + if (!s) return; + name.textContent = c.name, state.textContent = '● ' + (s.paused ? 'Paused' : s.status), state.style.color = s.paused ? C.amber : statusColor(s); + sub.textContent = [s.address, c.transport ? 'SSH' : 'Local', m.hostname && 'host ' + m.hostname, s.online ? 'up ' + Fmt.duration(m.uptime) : s.status === 'Offline' && s.err].filter(Boolean).join(' · '); + chips.replaceChildren(...[[m.os], [m.kernel && S.plat.kernelPrefix + m.kernel], [m.cpuCount && m.cpuCount + ' cores'], [m.memTotal > 0 && Fmt.bytes(m.memTotal) + ' RAM'], [c.group, '#7dd3fc'], + [s.online && `health ${s.health} (${s.grade})`, healthColor(s.health)], [c.autopilot.enabled && (c.autopilot.dryRun ? 'autopilot: dry run' : 'autopilot: on'), C.violet]] + .filter(([t]) => t).map(([t, color]) => h('span.chip', { style: { color } }, t))); + pause.textContent = s.paused ? '▶ Resume' : '❚❚ Pause'; + [...bar.children].forEach((b, i) => b.classList.toggle('on', Object.keys(TABS)[i] === S.tab)); + if (!S.m) return holder.replaceChildren(); // the first event of the stream brings the data + const tab = built[S.tab] ??= (withAnalysis = true, TABS[S.tab][1]()); + if (holder.firstChild !== tab) holder.replaceChildren(tab), withAnalysis = true; + tab.refresh?.(), withAnalysis && tab.analysis?.(); + }; + return el; +})(); +function listen() { // (re)opens the live stream: server list and events, plus the samples of the server on the detail page + feed?.close(), S.m = null; + feed = new EventSource('/api/events' + (S.id ? '?id=' + encodeURIComponent(S.id) : '')); + const on = (event, fn) => feed.addEventListener(event, e => fn(JSON.parse(e.data))); + on('hello', d => { + const missed = S.plat ? d.alerts.filter(a => a.time > (S.alerts[0]?.time || 0)).reverse() : []; // raised while the stream was being reopened + Object.assign(S, d), document.title = `Server Monitor (${d.plat.name})`, route(); + missed.length ? missed.forEach(alertsChanged) : alertsChanged(); + }); + on('state', d => (S.servers = d, cur() || S.page !== 'server' ? stateChanged() : route())); + on('alert', d => (S.alerts.unshift(d), S.alerts.length = Math.min(S.alerts.length, 2000), alertsChanged(d))); + on('alerts', d => (S.alerts = d, S.unseen = 0, alertsChanged())); + on('live', d => (Object.assign(S, { live: d.rows, m: d.m, vals: d.vals, an: d.an }), detail.refresh(true))); + on('sample', d => (S.m = d.m, S.vals = d.vals, S.live.push(d.row), S.live.length > 1800 && S.live.shift(), detail.refresh())); + on('analysis', d => (S.an = d, detail.refresh(true))); +} + +// ---- events page ---- +const eventsPage = (() => { + const list = table(['Time', 'Server', 'Type', 'Message'], { widths: [170, 180, 100] }), kind = h('select', { onchange: () => el.update() }, ['All events', 'critical', 'warning', 'info', 'resolved', 'action'].map(t => h('option', null, t))); + const where = h('div.muted'), notify = h('input', { type: 'checkbox', checked: localStorage.notify === '1', onchange: async () => localStorage.notify = +(notify.checked &&= await Notification.requestPermission() === 'granted') }); + const el = h('section', null, h('div.row', null, h('div.grow', null, h('h1', null, 'Events & alerts'), where), h('label.check', null, notify, 'Browser notifications'), kind, + h('a.button', { href: '/api/alerts.log' }, 'Download alerts.log'), h('button', { onclick: () => api('alerts/clear', {}) }, 'Clear list')), list); + el.update = () => { + where.textContent = `Alerts, recoveries, insights and every automatic or manual action, newest first. Also written to alerts.log in ${S.dir}`; + list.fill(S.alerts.filter(e => !kind.selectedIndex || e.severity === kind.value).map(e => [{ t: tf(e.time, 'yyyy-MM-dd HH:mm:ss'), c: C.muted }, e.serverName, { t: e.severity.toUpperCase(), c: sevColor(e.severity) }, e.message])); + }; + return el; +})(); +function alertsChanged(latest) { // latest = the event that just arrived, if any + const important = ['critical', 'warning', 'action'].includes(latest?.severity); + if (S.page === 'events') S.unseen = 0; + else if (important) ++S.unseen; + if (important && localStorage.notify === '1' && Notification.permission === 'granted') new Notification(`${latest.serverName} — ${latest.severity}`, { body: latest.message, icon: 'icon.svg' }); + badge.textContent = S.unseen, badge.hidden = !S.unseen, dash.events(), eventsPage.update(); +} + +// ---- pages and routing: #/dashboard, #/events, #/server// ---- +const pages = { dashboard: dash, server: detail, events: eventsPage }; +function route() { + const [page, ref, tab] = location.hash.replace(/^#\/?/, '').split('/').map(decodeURIComponent), s = S.servers.find(x => x.cfg.id === ref) || S.servers[+ref]; + const id = page === 'server' && s ? s.cfg.id : null; + S.page = id ? 'server' : page === 'events' ? 'events' : 'dashboard', S.tab = tab in TABS ? tab : 'overview'; + if (id && id !== builtFor) built = {}, builtFor = id; + if (id !== S.id) S.id = id, listen(); + for (const [k, el] of Object.entries(pages)) el.hidden = k !== S.page, nav[k]?.classList.toggle('on', k === S.page); + stateChanged(), S.page === 'events' && alertsChanged(); +} +function stateChanged() { + keyed(sideList, sideItem), S.page === 'dashboard' ? dash.update() : detail.refresh(); +} + +document.body.append(sidebar, h('main', null, Object.values(pages))); +listen(), addEventListener('hashchange', route); diff --git a/Server Monitor(web-window)/public/icon.svg b/Server Monitor(web-window)/public/icon.svg new file mode 100644 index 0000000000000000000000000000000000000000..106afbd504968423bd683610e537cb5f336ad54f --- /dev/null +++ b/Server Monitor(web-window)/public/icon.svg @@ -0,0 +1,5 @@ + + + + + diff --git a/Server Monitor(web-window)/public/index.html b/Server Monitor(web-window)/public/index.html new file mode 100644 index 0000000000000000000000000000000000000000..fcb9ce4e98381464097d823e2de581fe4f3718f5 --- /dev/null +++ b/Server Monitor(web-window)/public/index.html @@ -0,0 +1,14 @@ + + + + + +Server Monitor + + + + + + + + diff --git a/Server Monitor(web-window)/public/shared.js b/Server Monitor(web-window)/public/shared.js new file mode 100644 index 0000000000000000000000000000000000000000..d058f879780aefff3ed069d7f1f2b54d34790ebe --- /dev/null +++ b/Server Monitor(web-window)/public/shared.js @@ -0,0 +1,47 @@ +// Formatting and catalogues used by both the server (core/*.js) and the page (app.js). +const SM = (() => { + const fix = (v, prec = 0) => (+v).toFixed(prec); + const bytes = (b, prec = 1) => { + let i = 0; + for (; Math.abs(b) >= 1024 && i < 5; ++i) b /= 1024; + return fix(b, i ? prec : 0) + ' ' + ['B', 'KB', 'MB', 'GB', 'TB', 'PB'][i]; + }; + const Fmt = { + fix, bytes, + rate: b => bytes(b) + '/s', + pct: (p, prec = 1) => fix(p, prec) + '%', + temp: c => fix(c) + ' °C', + num: v => String(+(+v).toPrecision(6)), + iso: ms => new Date(ms - new Date(ms).getTimezoneOffset() * 60000).toISOString().slice(0, 19), // local time + count(v) { + const a = Math.abs(v); + return a >= 1e9 ? fix(v / 1e9, 1) + 'G' : a >= 1e6 ? fix(v / 1e6, 1) + 'M' : a >= 1e4 ? fix(v / 1e3, 1) + 'K' : fix(v); + }, + duration(sec) { + const s = Math.trunc(sec), d = Math.trunc(s / 86400), h = Math.trunc(s % 86400 / 3600), m = Math.trunc(s % 3600 / 60); + return d ? `${d}d ${h}h ${m}m` : h ? `${h}h ${m}m` : m ? `${m}m ${s % 60}s` : `${s}s`; + }, + }; + + // history metrics, in the order of the binary record + const H = ['cpu', 'iowait', 'load', 'mem', 'swap', 'disk', 'diskio', 'rx', 'tx', 'rd', 'wr', 'temp', 'procs', 'gpu', 'failed']; + const hNames = ['CPU', 'I/O wait', 'Load (1m)', 'Memory', 'Swap', 'Disk usage', 'Disk busy', 'Net download', 'Net upload', 'Disk read', 'Disk write', + 'Temperature', 'Processes', 'GPU', 'Failed services']; + const fmtMetric = (m, v) => v == null || isNaN(v) ? '—' : m >= 7 && m <= 10 ? Fmt.rate(v) : m === 2 ? fix(v, 2) : m === 11 ? Fmt.temp(v) + : m === 12 || m === 14 ? fix(v) : Fmt.pct(v); + + // rule catalogue rows: key, label, unit (metrics) or argument hint (actions, defined per platform) + const ruleMetrics = [['cpu', 'CPU usage', '%'], ['iowait', 'CPU I/O wait', '%'], ['load', 'Load (1 min) per core', '%'], ['mem', 'Memory usage', '%'], + ['swap', 'Swap usage', '%'], ['disk', 'Fullest disk usage', '%'], ['diskio', 'Busiest disk utilisation', '%'], ['temp', 'Hottest sensor', '°C'], + ['rx', 'Network download', 'MB/s'], ['tx', 'Network upload', 'MB/s'], ['failed', 'Failed services', ''], ['procs', 'Process count', ''], + ['gpu', 'GPU usage (max)', '%'], ['gputemp', 'GPU temperature (max)', '°C']]; + const def = (list, key) => list.find(d => d[0] === key) || [key, key, '']; + const conditionText = r => { + const [, label, unit] = def(ruleMetrics, r.metric); + return `${label} ${r.op} ${Fmt.num(r.value)}${unit && ' ' + unit}` + (r.duration ? ` for ${r.duration} s` : ''); + }; + const actionText = (actions, r) => def(actions, r.action)[1] + (r.arg ? ': ' + r.arg : ''); + + return { Fmt, H, hNames, fmtMetric, ruleMetrics, def, conditionText, actionText }; +})(); +if (typeof module === 'object') module.exports = SM; diff --git a/Server Monitor(web-window)/public/style.css b/Server Monitor(web-window)/public/style.css new file mode 100644 index 0000000000000000000000000000000000000000..81aa4923b7f40471d28cc8f8b63a6fa96bc091a9 --- /dev/null +++ b/Server Monitor(web-window)/public/style.css @@ -0,0 +1,110 @@ +/* Server Monitor: dark theme. app.js reads the palette from these variables for its canvas drawing. */ +:root { + --bg: #0d111c; --panel: #161c2b; --card: #1a2133; --border: #27314a; --grid: #242d42; --text: #e6ebf5; --muted: #8b95ab; --faint: #5a657d; + --accent: #38bdf8; --green: #22c55e; --amber: #f59e0b; --red: #ef4444; --violet: #a78bfa; --pink: #f472b6; --teal: #2dd4bf; --orange: #fb923c; --blue: #60a5fa; + --line: #232c41; --input: #111727; --select: #17304a; + font: 13px/1.4 system-ui, "Segoe UI", Roboto, "Noto Sans", sans-serif; color: var(--text); color-scheme: dark; +} +* { box-sizing: border-box; } +[hidden] { display: none !important; } +body { margin: 0; height: 100vh; min-width: 1100px; display: flex; background: var(--bg); } +h1 { margin: 0; font-size: 22px; } h2 { margin: 0; font-size: 16px; font-weight: 600; } p { margin: 0; } +small { font-size: 11px; color: var(--muted); } +::-webkit-scrollbar { width: 10px; height: 10px; } ::-webkit-scrollbar-thumb { background: #2a3449; border-radius: 5px; border: 2px solid transparent; background-clip: content-box; } + +/* layout helpers */ +.row { display: flex; gap: 10px; align-items: center; } .col { display: flex; flex-direction: column; gap: 10px; } +.top { align-items: flex-start; } .end { align-items: flex-end; } .stretch { align-items: stretch; } +.grow { flex: 1; min-width: 0; } .grow2 { flex: 2; min-width: 0; } .grow3 { flex: 3; min-width: 0; } .fill { flex: 1; min-height: 0; } +.scroll { overflow: hidden auto; } .side { width: 330px; flex: none; } .side.wide { width: 460px; } +.grid2 { display: grid; grid-template-columns: 1fr 1fr; gap: 14px; } +.muted { color: var(--muted); } .pre { white-space: pre-wrap; } .mono { font-family: ui-monospace, "DejaVu Sans Mono", Consolas, monospace; } +.section { color: var(--muted); font-size: 11px; font-weight: 700; letter-spacing: 1px; text-transform: uppercase; } +.panel { background: var(--panel); border: 1px solid var(--line); border-radius: 12px; padding: 14px 16px; display: flex; flex-direction: column; gap: 10px; } +.side > .panel:only-child { height: 100%; } + +/* controls */ +button, .button { background: #1d2538; border: 1px solid #2c3650; border-radius: 8px; padding: 7px 14px; font: inherit; font-weight: 600; color: var(--text); cursor: pointer; text-decoration: none; white-space: nowrap; } +button:hover, .button:hover { background: #253049; border-color: var(--accent); } button:disabled { color: var(--faint); border-color: #222a3c; } +button.primary, button.on { background: #0e7ab8; border-color: var(--accent); color: #fff; } button.primary:hover { background: #1190d8; } +button.danger { background: #3a1820; border-color: #7f2a36; color: #ffb4bd; } button.danger:hover { background: #55202b; border-color: var(--red); } +button.flat { background: none; border: none; padding: 4px 8px 4px 0; color: var(--muted); } button.flat:hover { color: var(--text); } +button.left { text-align: left; padding: 6px 12px; } +input, select { background: var(--input); border: 1px solid #2a3449; border-radius: 7px; padding: 6px 8px; font: inherit; color: var(--text); min-width: 0; } +input:focus, select:focus { border-color: var(--accent); outline: none; } input:disabled { color: var(--faint); } +input[type=number] { width: 86px; } input[type=search] { width: 240px; } input[type=checkbox] { accent-color: #0ea5e9; width: 16px; height: 16px; margin: 0; } +.check { display: inline-flex; gap: 7px; align-items: center; white-space: nowrap; } +.form { display: grid; grid-template-columns: auto 1fr; gap: 9px 14px; align-items: center; } .form > div:nth-child(odd) { color: var(--muted); white-space: pre; } +.form .row { gap: 7px; white-space: nowrap; min-width: 0; } .form input[type=number] { width: 68px; } +.form input:not([type=number], [type=checkbox]), .form select { flex: 1; } +dialog { background: var(--bg); color: var(--text); border: 1px solid var(--border); border-radius: 14px; padding: 20px 24px; min-width: 380px; max-width: 92vw; } +dialog::backdrop { background: rgba(0, 0, 0, .55); } dialog.wide { width: 720px; } +dialog[open] { display: flex; flex-direction: column; gap: 14px; } dialog > .row:last-child { justify-content: flex-end; } +.menu { position: fixed; z-index: 9; background: var(--panel); border: 1px solid #2a3449; border-radius: 8px; padding: 6px; display: flex; flex-direction: column; box-shadow: 0 8px 24px rgba(0, 0, 0, .5); } +.menu button { background: none; border: none; text-align: left; font-weight: 400; padding: 7px 22px; border-radius: 5px; } .menu button:hover { background: var(--select); } +.menu hr { border: none; border-top: 1px solid var(--border); margin: 4px 8px; } +.toast { position: fixed; right: 20px; bottom: 20px; z-index: 10; background: #3a1820; border: 1px solid var(--red); border-radius: 8px; padding: 10px 14px; max-width: 480px; } +.badge { background: var(--red); color: #fff; border-radius: 9px; padding: 1px 7px; font-size: 11px; font-weight: 700; } +.chip { background: #1f2a40; color: #b9c3d8; padding: 2px 9px; border-radius: 4px; white-space: nowrap; } +.dot { width: 10px; height: 10px; border-radius: 50%; flex: none; } +.track { height: 4px; border-radius: 2px; background: var(--grid); overflow: hidden; } .track i { display: block; height: 100%; border-radius: 2px; } + +/* sidebar */ +aside { width: 260px; flex: none; background: #10151f; border-right: 1px solid #1f2738; padding: 18px 12px 14px; display: flex; flex-direction: column; gap: 6px; } +.brand { display: flex; gap: 10px; align-items: center; margin-bottom: 14px; } .brand img { width: 34px; } .brand b { font-size: 16px; font-weight: 800; display: block; } +.nav { text-align: left; padding: 10px 14px; border: none; background: none; font-size: 14px; display: flex; justify-content: space-between; } +.nav:hover { background: var(--card); } .nav.on { background: var(--select); color: #7dd3fc; } +aside > .section { margin: 12px 0 0 8px; } +.list { overflow-y: auto; } .item { padding: 8px 10px; border-radius: 8px; cursor: pointer; } .item:hover { background: var(--card); } .item.sel { background: var(--select); } +.item b { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.mini { display: flex; align-items: center; margin: 3px 0 0 20px; } .mini small { width: 30px; font-size: 9px; color: var(--faint); } .mini .track { flex: 1; } + +/* pages */ +main { flex: 1; min-width: 0; } main > section { height: 100%; padding: 22px 28px 18px; display: flex; flex-direction: column; gap: 14px; } +.tiles { display: grid; gap: 14px; } +.tile { background: linear-gradient(135deg, var(--card), var(--panel)); border: 1px solid var(--border); border-radius: 12px; padding: 12px 14px 12px 16px; min-height: 84px; position: relative; display: flex; flex-direction: column; gap: 2px; min-width: 0; } +.tile::before { content: ""; position: absolute; left: 0; top: 14px; bottom: 14px; width: 4px; border-radius: 2px; background: var(--stripe); } +.tile b { font-size: 21px; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } .tile .section, .tile small { overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.cv { position: relative; min-width: 0; } .cv canvas { position: absolute; inset: 0; width: 100%; height: 100%; } +.chart { height: 240px; padding: 0; } .gauge { height: 190px; } .gauges { flex-direction: row; } .gauges .gauge { flex: 1; height: auto; aspect-ratio: 17 / 19; max-height: 210px; } +.cards { display: grid; grid-template-columns: repeat(auto-fill, minmax(320px, 1fr)); gap: 16px; padding-right: 6px; } +.card { background: linear-gradient(var(--card), var(--panel)); border: 1px solid var(--border); border-radius: 14px; padding: 14px 16px 12px; height: 262px; cursor: pointer; position: relative; overflow: hidden; + display: flex; flex-direction: column; gap: 8px; } +.card::before { content: ""; position: absolute; left: 0; right: 0; top: 0; height: 6px; background: linear-gradient(90deg, var(--status), transparent 60%); } +.card:hover { border-color: var(--accent); background: linear-gradient(#20293f, var(--panel)); } +.card .dot { background: var(--status); align-self: flex-start; margin-top: 7px; } .card b { font-size: 16px; } .card b, .card small { display: block; overflow: hidden; text-overflow: ellipsis; white-space: nowrap; } +.card .chip { color: var(--status); background: color-mix(in srgb, var(--status) 16%, transparent); border: 1px solid var(--status); border-radius: 10px; font-size: 10px; font-weight: 700; text-transform: uppercase; } +.grade { width: 44px; height: 44px; flex: none; } .rings { flex: 1; } +.foot { font-size: 11px; color: var(--muted); min-height: 32px; } .foot .row { gap: 14px; } .warn { border-radius: 8px; padding: 0 7px; } +.card.add { border: 1.5px dashed var(--border); background: none; align-items: center; justify-content: center; gap: 4px; color: var(--muted); } +.card.add::before { display: none; } .card.add i { font: 300 44px/1 system-ui; } .card.add b { font-size: 14px; } .card.add:hover { color: var(--accent); background: rgba(56, 189, 248, .07); } +.events { overflow-y: auto; flex: 1; min-height: 0; } .events div { padding: 6px 2px; border-bottom: 1px solid #1f2738; overflow-wrap: anywhere; } + +/* tables */ +.table { background: #131929; border: 1px solid var(--line); border-radius: 10px; overflow: auto; } +table { border-collapse: collapse; width: 100%; } th, td { padding: 0 8px; height: 30px; text-align: left; white-space: nowrap; overflow: hidden; text-overflow: ellipsis; max-width: 520px; } +th { position: sticky; top: 0; z-index: 1; background: #182033; color: var(--muted); font-size: 12px; border-bottom: 1px solid var(--border); user-select: none; } +th[data-sort]::after { content: attr(data-sort); color: var(--accent); } +tbody tr:nth-child(even) { background: #161d2e; } tbody tr.sel { background: var(--select); } td.r { text-align: right; } +.bar { position: relative; height: 16px; min-width: 90px; border-radius: 4px; background: var(--grid); overflow: hidden; } +.bar i { position: absolute; left: 0; top: 0; bottom: 0; border-radius: 4px; } .bar span { position: relative; display: block; text-align: center; font-size: 11px; font-weight: 700; line-height: 16px; color: var(--text); } +.kv { width: auto; } .kv td { height: auto; padding: 3px 18px 3px 0; white-space: normal; overflow-wrap: anywhere; } .kv td:first-child { color: var(--muted); white-space: nowrap; } + +/* server page */ +.state { font-size: 12px; text-transform: uppercase; } .chips { display: flex; gap: 6px; flex-wrap: wrap; margin-top: 6px; min-height: 22px; } +.tabbar { display: flex; flex-wrap: wrap; border-bottom: 1px solid var(--line); } +.tabbar button { background: none; border: none; border-bottom: 2px solid transparent; border-radius: 0; color: var(--muted); padding: 9px 13px; } +.tabbar button:hover { color: var(--text); } .tabbar button.on { color: #7dd3fc; border-bottom-color: var(--accent); background: none; } +.tab { height: 100%; padding: 8px 4px 0; } .tab.scroll { display: flex; flex-direction: column; gap: 16px; padding-right: 10px; } .tab.scroll > * { flex: none; } +.tab.col > .table { flex: 1; min-height: 0; } .tab.col > .table + .table { flex: none; max-height: 160px; } .tab > .row, .tab .row.top { gap: 14px; } .tab > .row { flex-wrap: wrap; } +.seg { display: flex; height: 14px; border-radius: 7px; background: var(--grid); overflow: hidden; } .legend { display: flex; flex-wrap: wrap; gap: 4px 22px; margin-top: 8px; color: var(--muted); font-size: 11px; white-space: pre; } +.legend i { display: inline-block; width: 9px; height: 9px; border-radius: 2px; margin-right: 6px; } +.cores { display: grid; grid-template-columns: repeat(auto-fill, minmax(86px, 1fr)); gap: 6px; } +.cores > div { border: 1px solid; border-radius: 8px; padding: 5px 8px 6px; } .cores small { display: flex; justify-content: space-between; font-size: 10px; } .cores b { font-size: 16px; display: block; margin: 1px 0 5px; } +.heat { display: grid; grid-template-columns: 34px repeat(24, 1fr); gap: 3px; position: relative; } .heat i { height: 24px; border-radius: 3px; } .heat small { font-size: 10px; align-self: center; white-space: nowrap; } +.heat p { position: absolute; inset: 30% 12%; display: grid; place-items: center; background: rgba(13, 17, 28, .8); } +.finding { display: flex; gap: 12px; align-items: center; background: var(--card); border: 1px solid var(--border); border-left: 4px solid; border-radius: 10px; padding: 10px 14px; } +.finding small { font-weight: 700; text-transform: uppercase; display: block; } .finding b { font-size: 14px; font-weight: 600; } +.console { flex: 1; min-height: 0; overflow: auto; background: #080b12; color: #cfe3ff; border-radius: 10px; padding: 10px; white-space: pre-wrap; overflow-wrap: anywhere; } +.console .cmd { margin-top: 12px; } .console .cmd b, .prompt { color: var(--accent); } .console .good { color: var(--green); } .console .bad { color: var(--red); } .prompt { font-size: 15px; } +.log { margin: 0; height: 60vh; overflow: auto; background: #080b12; color: #cfe3ff; border-radius: 10px; padding: 10px; font-size: 12px; } diff --git a/Server Monitor(web-window)/run.bat b/Server Monitor(web-window)/run.bat new file mode 100644 index 0000000000000000000000000000000000000000..1128b439b4390eabb2c94b38380f5dfc9e6b0a7e --- /dev/null +++ b/Server Monitor(web-window)/run.bat @@ -0,0 +1,7 @@ +@echo off +rem Starts Server Monitor (web) and opens the page. Another port: set PORT=9000 before running. +cd /d "%~dp0" +if not defined PORT set PORT=8765 +start "" /b powershell -NoProfile -Command "Start-Sleep 2; Start-Process http://127.0.0.1:%PORT%" +node server.js +if errorlevel 1 pause diff --git a/Server Monitor(web-window)/server.js b/Server Monitor(web-window)/server.js new file mode 100644 index 0000000000000000000000000000000000000000..8d4e3a602a8ad92678088bc6c2811c788a2c0048 --- /dev/null +++ b/Server Monitor(web-window)/server.js @@ -0,0 +1,155 @@ +// Server Monitor (web): HTTP server for the page, live updates over Server-Sent Events and a small JSON API. +// Only reachable from this computer; see README.md for the security model. +const http = require('http'), fs = require('fs'), path = require('path'); +const plat = require('./core/platform'), model = require('./core/model'); +const { Manager, testConnection } = require('./core/session'); +const { I, TIERS, STEP, stats, nowSec } = require('./core/history'); +const { Fmt, H } = require('./public/shared'); + +const PORT = +process.env.PORT || 8765, ORIGINS = [`127.0.0.1:${PORT}`, `localhost:${PORT}`]; +const PUBLIC = path.join(__dirname, 'public'), MIME = { html: 'text/html', js: 'text/javascript', css: 'text/css', svg: 'image/svg+xml' }; +const FILES = Object.fromEntries(fs.readdirSync(PUBLIC).map(f => ['/' + f.replace(/^index\.html$/, ''), f])); +const HEADERS = { 'Cache-Control': 'no-store', 'X-Content-Type-Options': 'nosniff', 'Cross-Origin-Resource-Policy': 'same-origin', + 'Content-Security-Policy': "default-src 'self'; frame-ancestors 'none'" }; +const mgr = new Manager(); + +const fail = (message, status = 400) => { throw Object.assign(new Error(message), { status }); }; +const sess = id => mgr.session(id) || fail('unknown server', 404); +const send = (res, status, body, type = 'application/json', extra) => + res.writeHead(status, { ...HEADERS, 'Content-Type': type + '; charset=utf-8', ...extra }).end(type === 'application/json' ? JSON.stringify(body) : body); + +// ---- what the page sees ---- +const SUMMARY = ['hostname', 'os', 'kernel', 'cpuCount', 'memTotal', 'cpuUsage', 'memPct', 'maxDiskPct', 'swapPct', 'maxTemp', 'netRxBps', 'netTxBps', 'load1', 'uptime']; +const summary = s => ({ // sidebar row, dashboard card and detail header of one server + cfg: model.forPage(s.cfg), address: model.address(s.cfg), status: s.status, err: s.err, paused: s.paused, online: s.online, alerts: s.activeAlerts(), + m: { ...Object.fromEntries(SUMMARY.map(k => [k, s.m[k]])), procs: s.m.procs.length, temps: s.m.temps.length }, + health: s.an.health, grade: s.an.grade, findings: s.an.findings.map(f => f.severity), spark: [0, 5].map(k => s.live.slice(-150).map(r => r.v[k])), // CPU, memory +}); +const servers = () => mgr.sessions.map(summary); +const snapshot = () => ({ plat: plat.ui, dir: mgr.dir, rule: model.RULE, defaultRules: model.defaultRules(), alerts: mgr.alerts, servers: servers() }); +const sample = (s, row) => ({ m: s.m, vals: model.metricValues(s.m), row }); + +// the stored points of a range (seconds back from now, 0 = everything) in the finest tier that covers it +function points(s, range) { + const now = nowSec(), from = +range ? now - range : Math.max(1, s.store.firstTs()), tier = s.store.tierFor(from, now); + return { now, from, tier, pts: s.store.range(from, now, tier) }; +} + +// History tab: chart series with gaps where nothing was recorded, statistics per metric +const SERIES = ['cpu', 'cpuMax', 'mem', 'swap', 'disk', 'rd', 'wr', 'rx', 'tx', 'rxMax', 'load', 'temp', 'tempMax', 'avail']; +function history(s, range) { + const { now, from, tier, pts } = points(s, range), step = Math.max(STEP[tier], s.cfg.interval), t = [], v = Object.fromEntries(SERIES.map(k => [k, []])); + const online = p => p.n ? p.nUp * 100 / p.n : 0, r2 = x => Math.round(x * 100) / 100; + let n = 0, up = 0; + const push = (ts, p) => { // p = null inserts a gap + t.push(ts * 1000); + for (const k of SERIES) v[k].push(!p ? null : k === 'avail' ? r2(online(p)) : !p.nUp ? null : r2((k.endsWith('Max') ? p.max : p.avg)[I[k.replace('Max', '')]])); + }; + for (const p of pts) { + if (t.length && p.ts * 1000 - t.at(-1) > step * 3000) push(t.at(-1) / 1000 + step, null); // the monitor was not running + push(p.ts, p), n += p.n, up += p.nUp; + } + if (t.length && now * 1000 - t.at(-1) > step * 3000) push(now, null); + return { t, v, tier: TIERS[tier], aggregated: tier > 0, span: (now - from) * 1000, points: pts.length, availability: n ? up * 100 / n : null, + bytes: s.store.diskBytes(), stats: H.map((_, m) => stats(pts, m)) }; +} +function csv(s, range) { + const num = x => isNaN(x) ? '' : x.toFixed(3), online = p => p.n ? p.nUp * 100 / p.n : 0; + return ['time,samples,online_pct' + H.map(k => `,${k}_avg,${k}_max`).join(''), + ...points(s, range).pts.map(p => [Fmt.iso(p.ts * 1000), p.n, Fmt.num(online(p)), ...H.flatMap((_, m) => [num(p.avg[m]), num(p.max[m])])].join(','))].join('\n'); +} + +// ---- live updates: one stream per page (browsers allow six connections per site) with the server list and events, +// plus the samples of the server whose id the page asked for ---- +const clients = new Set(); +function cast(id, event, make) { + let msg; + for (const c of clients) { + if (id && c.id !== id) continue; + if (c.res.writableLength > 8 << 20) c.res.destroy(); // the client stopped reading: drop it instead of buffering for ever (the page reconnects) + else c.res.write(msg ??= `event: ${event}\ndata: ${JSON.stringify(make())}\n\n`); + } +} +function subscribe(res, id) { + const c = { id, res }, s = mgr.session(id); + res.writeHead(200, { ...HEADERS, 'Content-Type': 'text/event-stream' }); + res.write(`event: hello\ndata: ${JSON.stringify(snapshot())}\n\n` + (s ? `event: live\ndata: ${JSON.stringify({ ...sample(s), rows: s.live, an: s.an })}\n\n` : '')); + clients.add(c), res.on('close', () => clients.delete(c)); +} +let dirty = false; // the server list goes out at most once a second +const pushState = () => (dirty = false, cast('', 'state', servers)); +setInterval(() => dirty && pushState(), 1000); +mgr.on('updated', () => dirty = true); +mgr.on('sample', (s, row) => (dirty = true, cast(s.cfg.id, 'sample', () => sample(s, row)))); +mgr.on('analysis', s => (dirty = true, cast(s.cfg.id, 'analysis', () => s.an))); +mgr.on('alert', e => cast('', 'alert', () => e)); + +// ---- API ---- +// a config sent by the page, on top of the stored one; an empty password keeps the stored password +function config(b) { + const old = b.id ? sess(b.id).cfg : {}, c = model.make({ ...old, ...b }, b.clearPassword ? '' : String(b.password || old.password || '')); + if (!c.name || (c.transport && !c.host)) fail('Please enter a name and an address.'); + if (c.host.startsWith('-') || c.user.startsWith('-')) fail('Address and user must not start with "-".'); + return c; +} +const GET = { + '/api/state': () => snapshot(), + '/api/history': q => history(sess(q.id), q.range), + '/api/history.csv': (q, res) => send(res, 200, csv(sess(q.id), q.range), 'text/csv', { 'Content-Disposition': `attachment; filename*=UTF-8''${encodeURIComponent(sess(q.id).cfg.name)}-history.csv` }), + '/api/alerts.log': (q, res) => send(res, 200, fs.readFileSync(path.join(mgr.dir, 'alerts.log'), { flag: 'a+' }), 'text/plain', { 'Content-Disposition': 'attachment; filename="alerts.log"' }), + '/api/events': (q, res) => subscribe(res, q.id), +}; +const POST = { // every handler gets the JSON body; servers are addressed by b.id + '/api/server/add': b => { const c = config({ ...b, id: '' }); mgr.add(c); return { id: c.id }; }, + '/api/server/update': b => mgr.update(config({ ...b, id: sess(b.id).cfg.id })), + '/api/server/remove': b => mgr.remove(sess(b.id).cfg.id, !!b.deleteHistory), + '/api/server/move': b => mgr.move(b.id, b.delta < 0 ? -1 : 1), + '/api/server/test': b => testConnection(config(b)), + '/api/server/reconnect': b => sess(b.id).reconnect(), + '/api/server/pause': b => sess(b.id).setPaused(!!b.paused), + '/api/server/analyze': b => sess(b.id).analyzeNow(), + '/api/exec': b => sess(b.id).exec(String(b.cmd), !!b.privileged, 120000), // console + '/api/run': b => { // a process / priority / service action from the platform tables; b.arg = pid or service name + const tpl = ['procActions', 'priorities', 'serviceActions'].includes(b.list) && plat.ui[b.list][b.i]?.cmd || fail('unknown command'); + if (tpl.includes('{n}') && !(/^\d+$/.test(b.arg) && +b.arg > 0)) fail('not a process id'); // pid 0 or -1 would address whole process groups + const cmd = tpl.replace('{n}', +b.arg).replace('{q}', () => plat.quote(String(b.arg))); + return sess(b.id).exec(cmd, true).then(r => ({ ...r, cmd })); + }, + '/api/logs': b => sess(b.id).exec(plat.serviceLogs(String(b.unit), Math.min(5000, Math.max(50, parseInt(b.lines) || 300))), true), + '/api/power': b => sess(b.id).exec(plat.power(!!b.reboot), true), + '/api/finding': b => { const s = sess(b.id); return s.runFinding(s.an.findings.find(f => f.key === b.key) || fail('this finding is gone', 404), false); }, + '/api/alerts/clear': () => (mgr.alerts = [], cast('', 'alerts', () => [])), +}; + +function body(req) { // JSON object, at most 1 MB + return new Promise((resolve, reject) => { + let s = ''; + req.setEncoding('utf8').on('data', d => (s += d).length > 1 << 20 && req.destroy()).on('error', reject).on('end', () => { + try { resolve(Object(JSON.parse(s))); } catch { reject(Object.assign(new Error('invalid JSON'), { status: 400 })); } + }); + }); +} + +http.createServer(async (req, res) => { + try { + const url = new URL(req.url, 'http://x'), route = url.pathname, origin = req.headers.origin; + // DNS rebinding: the browser must have addressed this computer by name; other sites cannot send the header or read replies (no CORS) + if (!ORIGINS.includes(req.headers.host) || (origin && !ORIGINS.includes(origin.replace('http://', '')))) return send(res, 403, { error: 'forbidden host or origin' }); + if (req.method === 'GET') { + if (FILES[route]) return send(res, 200, fs.readFileSync(path.join(PUBLIC, FILES[route])), MIME[path.extname(FILES[route]).slice(1)]); + const r = GET[route] ? await GET[route](Object.fromEntries(url.searchParams), res) : fail('not found', 404); + return res.headersSent || send(res, 200, r); + } + if (req.method !== 'POST' || !POST[route]) fail('not found', 404); + if (req.headers['x-sm'] !== '1' || !/^application\/json\b/.test(req.headers['content-type'])) fail('state-changing requests need Content-Type: application/json and X-SM: 1', 403); + send(res, 200, await POST[route](await body(req)) ?? { ok: true }); + pushState(); + } catch (e) { + res.headersSent ? res.end() : send(res, e.status || 500, { error: e.message }); + } +}).listen(PORT, '127.0.0.1', () => { + mgr.load(); + console.log(`Server Monitor (${plat.ui.name}) is running: http://127.0.0.1:${PORT} - config: ${mgr.dir}`); +}).on('error', e => (console.error(`Cannot listen on 127.0.0.1:${PORT} (is the monitor already running?): ${e.message}`), process.exit(1))); +process.on('exit', () => mgr.close()); // however this process ends, its child processes end with it +for (const sig of ['SIGINT', 'SIGTERM', 'SIGHUP']) process.on(sig, () => process.exit(0)); diff --git a/dev/README.md b/dev/README.md new file mode 100644 index 0000000000000000000000000000000000000000..a2aec98b1f38857cb096d4631d1ebbcb5b0ef549 --- /dev/null +++ b/dev/README.md @@ -0,0 +1,21 @@ +# Developer kit + +- `SPEC.md` — the specification all six editions follow: platform-module contract, Windows frame format, command + tables, data formats, test rules. Read it first. +- `collector.sh`, `collector.ps1` — the collector scripts. Every edition embeds or ships them unchanged. +- `fakewin/powershell` — a stand-in for `powershell.exe` (Python). With `PATH=/fakewin:$PATH` a Windows edition + runs on Linux: the stand-in emits realistic Windows frames and only echoes one-shot commands. +- `pytk` — starts `python3` with a locally unpacked tkinter (for machines without root; see `requirements/`). +- `tests/cqt` — analyzer reference test (`analysis_test.cpp`, expected output, build script), the offscreen click + test (`click_test.cpp`, `build_click.sh`) and a scratch settings folder. +- `tests/python` — `t_core.py` (store, link, rules, autopilot), `t_spec.py` (Windows commands against the spec), + `uitest.py` and `ui2.py` (UI drives under `xvfb-run`), `analysis_test.py`. +- `tests/web` — API, security, session, history, parser, child-process and browser tests (`apitest2.js`, `t_*.js`, + `uitest.js`), with stand-ins for `ssh`, `powershell` and `taskkill`. + +The scripts are working tools, not a polished suite. They expect this folder at `~/.local/share/sm-dev`, the six +projects on `~/Desktop`, and (C++ tests) a Qt 5 SDK in `~/.local/share/qt5-sdk/root`; some write their scratch files +next to themselves or under `~/.local/share/sm-dev/tmp`. + +Rules for every test: a scratch settings folder (`XDG_CONFIG_HOME`, `APPDATA` for the Windows editions) whose servers +have `autopilot.dryRun = true`, and never confirm an action that kills, restarts, cleans, reboots or shuts down. diff --git a/dev/SPEC.md b/dev/SPEC.md new file mode 100644 index 0000000000000000000000000000000000000000..754b979ca13f8ec7f379e933aff686d38d1da2ad --- /dev/null +++ b/dev/SPEC.md @@ -0,0 +1,237 @@ +# Server Monitor — shared spec for all six editions + +Six stand-alone projects, one per (language × OS). Each edition runs on its OS **and monitors machines of that OS** +(the local machine, plus remote ones over the system `ssh` client). + +| Folder (on ~/Desktop) | Language / UI | OS | +|-----------------------------------|---------------------------------------|---------| +| `Server Monitor(cqt-linux)` | C++17 / Qt 5 Widgets | Linux | +| `Server Monitor(cqt-window)` | C++17 / Qt 5 Widgets | Windows | +| `Server Monitor(python-linux)` | Python 3 stdlib only (tkinter) | Linux | +| `Server Monitor(python-window)` | Python 3 stdlib only (tkinter) | Windows | +| `Server Monitor(web-linux)` | Node.js stdlib server + vanilla JS UI | Linux | +| `Server Monitor(web-window)` | Node.js stdlib server + vanilla JS UI | Windows | + +Rules for every edition +- **No third-party libraries.** Qt only / Python standard library only / Node built-ins + plain browser JS only. +- **Compact code.** The owner wants minimal, short, readable code: no dead code, no speculative options, shared helpers + instead of repetition. Dense but readable (not minified). Short comments only where the reason is not obvious. +- **One platform module per project.** Everything OS-specific lives in a single file (`Platform.cpp` / `plat.py` / + `platform.js`). All other files of a language are byte-identical between its Linux and Windows edition. +- **Reference implementation:** `~/Desktop/Server Monitor(cqt-linux)/src` (C++). Port its behaviour: same features, same numbers, + same texts, same thresholds. When unsure, read the C++. +- Analysis and autopilot are plain statistics. No AI, no LLM, no agent installed on servers. + +## 1. Features (parity list) + +- Servers: add / edit / remove / reorder, groups, enable, pause, reconnect, test connection (wait for 2 frames). + First start creates "This computer" (local transport). Transports: Local, SSH (key or password). +- Dashboard: card per server (4 ring gauges, CPU+MEM sparkline, health grade, net rates, alert badge), totals row, + recent events, search. +- Server page tabs: Overview, CPU (per core, temperatures, GPUs), Memory, Storage, Network, Processes (filter, sort, + signals, priority), Services (filter, state filter, verbs, logs), History, Insights & Autopilot, Alert rules, Console. +- History: 4 round-robin tiers — raw 6 h, minute 30 d, hour 732 d, day 7320 d; avg + max per metric, n / nUp for + availability; open buckets rebuilt on load; ranges 1 h … All; stats (min / avg / p95 / peak); CSV export. +- Analyzer (every 60 s, first run after 3 s): availability 24 h/7 d/30 d, disk-full forecast (regression over 7 d of + hours or 24 h of minutes, whichever fits better), memory trend 6 h, per-process leaks and runaways, failed / flapping + services, overload, swap thrashing, z-score anomalies vs same weekday+hour over 8 weeks (fallback last 24 h), + weekly heatmap (4 weeks), capacity advice (30-day p95), health score 0–100 and grade A–F. +- Autopilot: acts on findings marked auto-eligible, per-action cooldowns (disk cleanup 6 h, restart 2 min, others + 15 min), max restarts per hour, **dry run**, never restarts services that were already failed when monitoring started. +- Alert rules: metric op value for duration → severity → action, with cooldown; events list + `alerts.log`. +- Console: run a command, history with ↑/↓, quick diagnostics, system actions (confirmations), privileged checkbox. + +## 2. Data formats (identical in all editions, so files can be copied between them) + +Config dir: C++ `QStandardPaths::AppConfigLocation` (app + org name `ServerMonitor`); +Python `~/.config/ServerMonitorPy` (Windows `%APPDATA%\ServerMonitorPy`); Web `~/.config/ServerMonitorWeb` +(Windows `%APPDATA%\ServerMonitorWeb`). Honour `XDG_CONFIG_HOME` on Linux (tests use a scratch dir). + +- `servers.json` (mode 600): `{"version":1,"servers":[ServerConfig…]}` — field names exactly as in C++ + `Model.cpp` (`each(ServerConfig)`, `each(Rule)`, `each(AutopilotConfig)`), plus `transport` (0 Local, 1 SSH), + `password` (XOR with key `ServerMonitor/obfuscation/v1`, then base64), `rules` [], `autopilot` {}. +- `history//{raw,minute,hour,day}.bin`: header `"SMH1"`, byte H_COUNT (15), byte 0, uint16 LE record size + (136); then packed little-endian records `int64 ts, uint32 n, uint32 nUp, float32 avg[15], float32 max[15]`. + Metric order: cpu, iowait, load, mem, swap, disk, diskio, rx, tx, rd, wr, temp, procs, gpu, failed. NaN = no value. +- `alerts.log`: `ISO-time \t severity \t server \t message`, truncated at 5 MB. + +## 3. Platform module contract + +Each platform module provides (names adapted to the language): + +| Item | Linux | Windows | +|---|---|---| +| local spawn | `sh -s -- ` / `sh -s` | `powershell` + `PS_ARGS` (below) | +| remote spawn | `ssh [-i key] [-p port] -T user@host ""` | same, command line = `powershell` + `PS_ARGS` joined by spaces | +| collector stdin | `collector.sh` | `"$iv = ; $once = $false\n"` + `collector.ps1` | +| one-shot stdin `wrap(cmd, privileged, useSudo)` | `cmd + "\n"`; privileged+sudo → `sudo -n sh -c ` | see below (no sudo: run the app elevated) | +| `quote(s)` | `'…'` with `'` → `'\''` | `'…'` with `'` → `''` | +| `parse(frame, state)` | §4 | §5 | +| command tables | §6 | §6 | +| `hasSudo`, `posixCpu` (iowait + steal exist) | true, true | false, false | + +ssh options (both): `-o ConnectTimeout=10 -o ServerAliveInterval=10 -o ServerAliveCountMax=3 +-o StrictHostKeyChecking=accept-new -o LogLevel=ERROR`, plus `-o BatchMode=yes` without a password, or with one: +`-o NumberOfPasswordPrompts=1` and env `SSH_ASKPASS=`, `SSH_ASKPASS_REQUIRE=force`, +`SERVERMONITOR_ASKPASS=`, `DISPLAY=:0` if unset. The helper prints `$SERVERMONITOR_ASKPASS` (C++: the app +itself; Python/Web: a tiny temp script, `.cmd` on Windows, removed on exit). + +`PS_ARGS` = `-NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -OutputFormat Text -EncodedCommand +aQBlAHgAIAAoAEAAKAAkAGkAbgBwAHUAdAApACAALQBqAG8AaQBuACAAWwBjAGgAYQByAF0AMQAwACkA` +(UTF-16LE base64 of `iex (@($input) -join [char]10)`: PowerShell runs whatever script arrives on stdin, so no quoting +problems in cmd.exe, PowerShell or ssh). Always write the script to stdin, then close stdin. Keep scripts ASCII. + +Windows `wrap(cmd)`: +``` +[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false; $ProgressPreference = 'SilentlyContinue'; $Error.Clear(); $global:LASTEXITCODE = 0 +& { + +} 2>&1 | Out-String -Width 250 -Stream +if ($LASTEXITCODE) { exit $LASTEXITCODE } +if ($Error | Where-Object { $_.FullyQualifiedErrorId -notlike 'NativeCommandError*' }) { exit 1 }; exit 0 +``` +(Text a program writes to stderr is not a failure; only its exit code or a failing cmdlet is.) +Built-in Windows commands use `-ErrorAction Ignore` (not `SilentlyContinue`) where failure is fine. + +Frames (both): `@@SNAP_BEGIN`, then `@@S
` + rows, then `@@SNAP_END`. Split on `\n`, strip `\r`. +A frame is taken from the **last** `@@SNAP_BEGIN` before each `@@SNAP_END`. The first frame has no rates → `valid=false` +(the session shows Online but records nothing until the second frame). + +## 4. Linux frame + +Exactly what `MetricsEngine::process` in the C++ `Model.cpp` parses. Port it line for line. + +## 5. Windows frame (`collector.ps1`) → Metrics + +Values are bytes / per-second rates unless noted. Missing or empty fields count as 0. + +- `info` (every 15th frame, cached): `hostname, os, kernel, arch, cpumodel, mhz, virt, admin`. +- `users` (every 15th, only when elevated; cached): `pid|DOMAIN\user`. Unknown → user `—`. +- `os`: `ts` (ms since epoch, used for dt), `uptime` s, `memtotal`, `swaptotal`, `swapfree`. +- `cpu`: `name|total%|user%|privileged%|irq%|interrupts/s`; `_Total` is the machine, other names are cores (sort by + number). cpuUsage=total, cpuUser=user, cpuIrq=irq, cpuSystem=max(0, privileged−irq), iowait=steal=0, + intrPerSec from `_Total`. cpuCount = number of cores (≥1). Every core `mhz` = info `mhz`, avgMhz likewise. +- `sys`: `queue` (processor queue length), `ctxt` per s, `threads`. + **Load average (same meaning as Unix):** instant = cpuUsage/100 × cpuCount + queue; keep three exponential moving + averages in the parser state: `load_k += (instant − load_k) × (1 − exp(−dt/T_k))`, T = 60, 300, 900 s + (first frame: all three = instant). procsRunning = round(cpuUsage/100 × cpuCount), procsBlocked = queue. +- `mem`: `avail, free, standby, syscache, modified, pool, commit, commitlimit, pages`. + memAvailable=avail, memFree=free, cached=standby+syscache, buffers=0, shared=0, slab=pool, dirty=modified, + memUsed=max(0, memtotal−avail), memPct, swapUsed=swaptotal−swapfree, swapPct. +- `net`: `name|status|speedMbps|type|rxBytes|txBytes|rxPkts|txPkts|errors|drops|description` (cumulative counters → + per-second deltas like Linux). state = `up` / `down` / lower-cased status. virt = type is `Loopback` or `Tunnel`, or + name+description matches `/virtual ethernet|virtualbox|vmware virtual|vethernet|loopback|pseudo|tap-|bluetooth|wan miniport|wsl|docker/i` + (a VM's own NIC, e.g. "Microsoft Hyper-V Network Adapter", must count as physical). + Totals (netRxBps/netTxBps) over non-virtual interfaces. Sort: physical first, then by name. +- `tcp`: `State count`. Map `Established→ESTABLISHED, Listen→LISTEN, TimeWait→TIME_WAIT, CloseWait→CLOSE_WAIT`, + others upper-cased. socketsUsed = sum of all. +- `disk`: `name|readBps|writeBps|readIops|writeIops|idle%`; util = clamp(100 − idle, 0, 100) when idle is present, + else 0. totalRead/totalWritten = 0. Sums and busiest disk as on Linux. +- `df`: `mount|label|fs|total|free`; device=label, used=total−free, avail=free, pct=used×100/total. +- `procs`: `pid|ppid|cpuTime100ns|priority|threads|createdUnixSec|vsz|rss|name`. Skip pid 0. + cpu% (of one core) = Δ(cpuTime)/1e7/dt×100, clamped to 0…100×cpuCount; age = now − created (0 if created=0); + nice = priority; state = `R` if cpu > 0.5 else `S`; threadsTotal = sum; forksPerSec = (pids not seen in the previous + frame)/dt. Sort by cpu desc, then rss desc. +- `sessions`: one number → loggedUsers. +- `services` (every 5th, cached): `name|state|startmode|exitcode|display`. unit=name, description=display, + load=startmode, sub=lower(state); active = `failed` when startmode `Auto` and state `Stopped` and exitcode not in + {0, 1077}; else `active` when state `Running`; else `inactive`. +- `thermal`: `name|celsius` (keep 0 < t ≤ 150, unique names). Usually empty on Windows. +- `gpu` (every 3rd, cached): same nvidia-smi CSV as Linux. + +## 6. Command tables + +`{q}` = quote(arg), `{n}` = integer argument. Windows commands are PowerShell. + +| Key | Linux | Windows | +|---|---|---| +| kill_pid | `kill -TERM {n}` | `Stop-Process -Id {n} -Force` | +| renice (autopilot) | `renice -n 19 -p {n}` | `(Get-Process -Id {n}).PriorityClass = 'Idle'` | +| restart_service | `systemctl reset-failed {q} 2>/dev/null; systemctl restart {q}` | `Restart-Service -Name {q} -Force` | +| restart_failed | (C++ `Session.cpp`) | `Get-CimInstance Win32_Service \| Where-Object { $_.StartMode -eq 'Auto' -and $_.State -eq 'Stopped' -and $_.ExitCode -notin 0, 1077 } \| ForEach-Object { "restart $($_.Name)"; Start-Service -Name $_.Name }` | +| drop_caches | `sync && echo 3 > /proc/sys/vm/drop_caches` | — (not offered) | +| default disk cleanup | (C++ `Model.h`) | `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` | +| reboot / shut down | `(sleep 2; systemctl reboot) >/dev/null 2>&1 &` / `… poweroff …` | `shutdown /r /t 5` / `shutdown /s /t 5` | +| rule actions offered | notify, restart_failed, restart_service, kill_top_cpu, kill_top_mem, drop_caches, command | same without drop_caches | +| protected processes (never killed automatically, no leak / runaway findings) | pid ≤ 2, ppid = 2, rss ≤ 0, name `sshd` or `systemd` | pid ≤ 4, rss ≤ 0, name in `System, Registry, Memory Compression, smss.exe, csrss.exe, wininit.exe, winlogon.exe, services.exe, lsass.exe, svchost.exe, sshd.exe, dwm.exe` | + +Processes tab +| | Linux | Windows | +|---|---|---| +| buttons / menu | Terminate `kill -TERM`, Kill `kill -KILL` (danger), Hang up `kill -HUP` (menu only), Suspend `kill -STOP`, Resume `kill -CONT` (no confirmation) | End task `taskkill /PID {n}`, Kill `taskkill /F /PID {n}` (danger), Kill tree `taskkill /F /T /PID {n}` (danger) | +| priority choices (label → command) | `-20 (highest)`, `-10`, `0 (normal)`, `10`, `19 (lowest)` → `renice -n -p {n}` | `Idle, BelowNormal, Normal, AboveNormal, High` → `(Get-Process -Id {n}).PriorityClass = ''` | +| priority column | header `Nice`, normal = 0 | header `Priority`, normal = 8 | + +Services tab +| | Linux | Windows | +|---|---|---| +| verbs | start, stop, restart, reload, enable, disable → `systemctl {q}` | start `Start-Service -Name {q}`, stop `Stop-Service -Name {q} -Force`, restart `Restart-Service -Name {q} -Force`, enable `Set-Service -Name {q} -StartupType Automatic`, disable `Set-Service -Name {q} -StartupType Disabled` | +| confirm | stop, disable, restart | same | +| logs (N lines) | (C++ `Tabs.cpp`) | `$s = Get-CimInstance Win32_Service \| Where-Object Name -eq {q}; $s \| Format-List Name, DisplayName, State, StartMode, ExitCode, ProcessId, PathName; Get-WinEvent -FilterHashtable @{ LogName = 'System'; ProviderName = 'Service Control Manager' } -MaxEvents 3000 -ErrorAction Ignore \| Where-Object { $_.Message -like ('*' + $s.DisplayName + '*') } \| Select-Object -First {n} \| Format-Table TimeCreated, LevelDisplayName, Message -Wrap` | + +Console quick diagnostics (label → command); Linux list is in C++ `Tabs.cpp`. Windows: +- Disk usage → `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` +- Largest folders in C:\ → `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` +- Memory → `Get-CimInstance Win32_OperatingSystem | Format-List TotalVisibleMemorySize, FreePhysicalMemory, TotalVirtualMemorySize, FreeVirtualMemory` +- Top CPU processes → `Get-Process | Sort-Object CPU -Descending | Select-Object -First 20 Id, ProcessName, CPU, @{ n = 'MemMB'; e = { [int]($_.WorkingSet64 / 1MB) } }, StartTime` +- Listening ports → `Get-NetTCPConnection -State Listen | Sort-Object LocalPort | Format-Table LocalAddress, LocalPort, OwningProcess` +- System errors → `Get-WinEvent -FilterHashtable @{ LogName = 'System'; Level = 1, 2 } -MaxEvents 40 | Format-Table TimeCreated, ProviderName, Message -Wrap` +- Application errors → `Get-WinEvent -FilterHashtable @{ LogName = 'Application'; Level = 1, 2 } -MaxEvents 40 | Format-Table TimeCreated, ProviderName, Message -Wrap` +- Failed services → `Get-CimInstance Win32_Service | Where-Object { $_.StartMode -eq 'Auto' -and $_.State -eq 'Stopped' -and $_.ExitCode -notin 0, 1077 } | Format-Table Name, ExitCode, DisplayName` +- Logged-in users → `quser` +- Last boots → `Get-WinEvent -FilterHashtable @{ LogName = 'System'; Id = 6005, 6006, 1074 } -MaxEvents 15 | Format-Table TimeCreated, Id, Message -Wrap` + +Console system actions (all ask for confirmation, run privileged). Linux list is in C++ `Tabs.cpp`. Windows: +- Clean temp files → the default disk cleanup command +- Flush DNS cache → `Clear-DnsClientCache; 'done'` +- Restart failed services → the restart_failed command +- Reboot (danger) → `shutdown /r /t 5` +- Shut down (danger) → `shutdown /s /t 5` + +Labels that differ: process priority column (above); CPU tab tile 4 is `Steal / IRQ` on Linux and `Interrupts + DPC` +(value: cpuIrq) on Windows; CPU charts show the `I/O wait` and `Steal` series only when `posixCpu`; the rule metric +`iowait` and the anomaly check on iowait exist only when `posixCpu`; swap thrashing = swap > 50 % and (Linux) 15-min +iowait > 20 %, (Windows) current memory > 90 % and 15-min disk busy > 50 %; the sudo checkbox exists only with +`hasSudo`; kernel chip text is `Linux ` / `build `; add-dialog hint and placeholders name the right OS. +Default sample interval: 2 s on Linux, 3 s on Windows (the PowerShell collector is heavier). + +## 7. Look + +Dark theme, hand-drawn widgets (ring gauges with a 270° arc, time charts with grid, legend, hover value, stacked +areas and NaN gaps, segment bars, stat tiles with an accent stripe, per-core grid, weekly heatmap, table bars). +Palette: bg `#0d111c`, panel `#161c2b`, card `#1a2133`, border `#27314a`, grid `#242d42`, text `#e6ebf5`, +muted `#8b95ab`, faint `#5a657d`, accent `#38bdf8`, green `#22c55e`, amber `#f59e0b`, red `#ef4444`, violet `#a78bfa`, +pink `#f472b6`, teal `#2dd4bf`, orange `#fb923c`, blue `#60a5fa`. Levels: green < 70 ≤ amber < 90 ≤ red. + +## 8. Testing on this machine (Linux, no root) + +- Never let a test act on this machine: use a scratch config dir (`XDG_CONFIG_HOME=`) whose servers have + `autopilot.dryRun = true`. Do not run kill / restart / cleanup / reboot commands for real. +- Python with tkinter: `~/.local/share/sm-dev/pytk script.py` (tkinter is not installed system-wide); headless display: + `xvfb-run -a …`. +- Windows editions: there is no Windows and no real PowerShell here. `~/.local/share/sm-dev/fakewin/powershell` is a + stand-in that emits realistic Windows frames (and echoes one-shot commands). Run a Windows edition with + `PATH=~/.local/share/sm-dev/fakewin:$PATH`. This tests parser + app, **not** `collector.ps1` itself — keep that file + exactly as given. +- Collectors: `~/.local/share/sm-dev/collector.sh`, `~/.local/share/sm-dev/collector.ps1` (copy verbatim). + +## 9. Changes after the first review of the C++ reference (all editions must match) + +- Availability: while a server is not reachable (Offline **or** reconnecting after a failure) one downtime sample is recorded + per sample interval (not one per 10 s). `Analysis.down[3]` = offline seconds per window = (n − nUp) × interval-weighted share of the + monitored part of the window; texts say "offline for about " from that, never from (100 − up) × window. +- History load: everything after the last stored bucket of a tier is rebuilt from the finer tier (not only the current bucket); + a file whose size is not header + whole records is rewritten on load; an existing `.old` is removed before renaming a bad file. +- Analysis also runs on the first valid sample of a connection. Metrics are marked invalid when a link (re)starts; the autopilot + acts only while the session is online with valid data. +- Process trends are cleared when uptime goes backwards (reboot) or the server address changes; service trends too on an address + change. A service missing from a new service list is forgotten; a sample without a service list changes nothing. +- Pending one-shot commands are failed ("connection stopped" / lost) whenever the link is dropped, including Reconnect and config change. +- The tail of command output in an event / `alerts.log` line is made one line. +- Lists (processes, services): the selection is cleared when its key disappears; a filtered-out row is not a selection; the pid / + unit is read **before** a confirmation is shown; "Freeze list" is switched off when another server is opened. +- Windows parser: empty service exit code counts as 0; empty user name shows `—`; negative dt (clock set back) is treated as no dt. +- Labels: CPU tab "Running / blocked" tile says "blocked = waiting for a CPU" when not `posixCpu`; a card of an online server + without data says "Waiting for data…"; the Network tab rebuilds its interface list when the names change, not only the count. +- Autopilot dry run: "Autopilot (dry run) would: …" is raised once per finding while it stays eligible (not again every cooldown). +- Windows `wrap()` trailer changed (see §3): stderr text of a native program no longer forces exit code 1. diff --git a/dev/collector.ps1 b/dev/collector.ps1 new file mode 100644 index 0000000000000000000000000000000000000000..4b087b283517d929a2302e16b16452e5ec87ebb4 --- /dev/null +++ b/dev/collector.ps1 @@ -0,0 +1,108 @@ +# Server Monitor collector for Windows (PowerShell 5.1+, ASCII only). +# The caller prepends "$iv = ; $once = $false". One frame per interval: +# "@@SNAP_BEGIN", "@@S
" + rows (key=value or |-separated), "@@SNAP_END". +$ErrorActionPreference = 'SilentlyContinue' +$ProgressPreference = 'SilentlyContinue' +[Console]::OutputEncoding = New-Object System.Text.UTF8Encoding $false +function Cim($class, $ns = 'root/cimv2') { Get-CimInstance -ClassName $class -Namespace $ns } +function Clean($s) { ("$s" -replace '[|\r\n]', ' ').Trim() } +$epoch = [DateTime]'1970-01-01' +$smi = Get-Command nvidia-smi.exe | Select-Object -First 1 -ExpandProperty Path +# Console.Out reports no error when the pipe is closed, so the collector also ends when its parent process is gone. +$parent = Get-Process -Id (Get-CimInstance Win32_Process -Filter "ProcessId = $PID").ParentProcessId +$n = 0 +while ($true) { + $t0 = Get-Date + $out = New-Object System.Collections.Generic.List[string] + $out.Add('@@SNAP_BEGIN') + $os = Cim Win32_OperatingSystem + if ($n % 15 -eq 0) { + $cs = Cim Win32_ComputerSystem + $cpu = @(Cim Win32_Processor)[0] + $virt = Clean ($cs.Manufacturer + ' ' + $cs.Model) + $admin = ([Security.Principal.WindowsPrincipal][Security.Principal.WindowsIdentity]::GetCurrent()).IsInRole([Security.Principal.WindowsBuiltInRole]::Administrator) + $out.Add('@@S info') + $out.Add("hostname=$($cs.Name)") + $out.Add("os=$(Clean $os.Caption)") + $out.Add("kernel=$($os.Version)") + $out.Add("arch=$($os.OSArchitecture)") + $out.Add("cpumodel=$(Clean $cpu.Name)") + $out.Add("mhz=$($cpu.MaxClockSpeed)") + $out.Add("virt=$virt") + $out.Add("admin=$([int]$admin)") + if ($admin) { + $out.Add('@@S users') + Get-Process -IncludeUserName | ForEach-Object { $out.Add("$($_.Id)|$($_.UserName)") } + } + } + $out.Add('@@S os') + $out.Add("ts=$([long](([DateTime]::UtcNow - $epoch).TotalMilliseconds))") + $out.Add("uptime=$([long](((Get-Date) - $os.LastBootUpTime).TotalSeconds))") + $out.Add("memtotal=$([long]$os.TotalVisibleMemorySize * 1024)") + $out.Add("swaptotal=$([long]$os.SizeStoredInPagingFiles * 1024)") + $out.Add("swapfree=$([long]$os.FreeSpaceInPagingFiles * 1024)") + $out.Add('@@S cpu') + Cim Win32_PerfFormattedData_PerfOS_Processor | ForEach-Object { + $out.Add("$($_.Name)|$($_.PercentProcessorTime)|$($_.PercentUserTime)|$($_.PercentPrivilegedTime)|$([long]$_.PercentInterruptTime + [long]$_.PercentDPCTime)|$($_.InterruptsPersec)") + } + $sys = Cim Win32_PerfFormattedData_PerfOS_System + $out.Add('@@S sys') + $out.Add("queue=$($sys.ProcessorQueueLength)") + $out.Add("ctxt=$($sys.ContextSwitchesPersec)") + $out.Add("threads=$($sys.Threads)") + $pm = Cim Win32_PerfFormattedData_PerfOS_Memory + $out.Add('@@S mem') + $out.Add("avail=$($pm.AvailableBytes)") + $out.Add("free=$($pm.FreeAndZeroPageListBytes)") + $out.Add("standby=$([long]$pm.StandbyCacheCoreBytes + [long]$pm.StandbyCacheNormalPriorityBytes + [long]$pm.StandbyCacheReserveBytes)") + $out.Add("syscache=$($pm.CacheBytes)") + $out.Add("modified=$($pm.ModifiedPageListBytes)") + $out.Add("pool=$([long]$pm.PoolPagedBytes + [long]$pm.PoolNonpagedBytes)") + $out.Add("commit=$($pm.CommittedBytes)") + $out.Add("commitlimit=$($pm.CommitLimit)") + $out.Add("pages=$($pm.PagesPersec)") + $out.Add('@@S net') + [System.Net.NetworkInformation.NetworkInterface]::GetAllNetworkInterfaces() | ForEach-Object { + $s = $null + $s = $_.GetIPStatistics() + 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)") } + } + $ip = [System.Net.NetworkInformation.IPGlobalProperties]::GetIPGlobalProperties() + $out.Add('@@S tcp') + $ip.GetActiveTcpConnections() | Group-Object State | ForEach-Object { $out.Add("$($_.Name) $($_.Count)") } + $out.Add("Listen $(@($ip.GetActiveTcpListeners()).Count)") + $out.Add('@@S disk') + Cim Win32_PerfFormattedData_PerfDisk_PhysicalDisk | Where-Object { $_.Name -ne '_Total' } | ForEach-Object { + $out.Add("$(Clean $_.Name)|$($_.DiskReadBytesPersec)|$($_.DiskWriteBytesPersec)|$($_.DiskReadsPersec)|$($_.DiskWritesPersec)|$($_.PercentIdleTime)") + } + $out.Add('@@S df') + [System.IO.DriveInfo]::GetDrives() | Where-Object { $_.IsReady -and $_.DriveType -eq 'Fixed' } | ForEach-Object { + $out.Add("$($_.Name)|$(Clean $_.VolumeLabel)|$($_.DriveFormat)|$($_.TotalSize)|$($_.AvailableFreeSpace)") + } + $sessions = @{} + $out.Add('@@S procs') + Cim Win32_Process | ForEach-Object { + $born = 0 + if ($_.CreationDate) { $born = [long](($_.CreationDate.ToUniversalTime() - $epoch).TotalSeconds) } + if ($_.Name -eq 'explorer.exe') { $sessions[$_.SessionId] = 1 } + $out.Add("$($_.ProcessId)|$($_.ParentProcessId)|$([long]$_.KernelModeTime + [long]$_.UserModeTime)|$($_.Priority)|$($_.ThreadCount)|$born|$($_.VirtualSize)|$($_.WorkingSetSize)|$(Clean $_.Name)") + } + $out.Add('@@S sessions') + $out.Add("$($sessions.Count)") + if ($n % 5 -eq 0) { + $out.Add('@@S services') + Cim Win32_Service | ForEach-Object { $out.Add("$($_.Name)|$($_.State)|$($_.StartMode)|$($_.ExitCode)|$(Clean $_.DisplayName)") } + } + $out.Add('@@S thermal') + Cim MSAcpi_ThermalZoneTemperature 'root/wmi' | ForEach-Object { $out.Add("$(Clean $_.InstanceName)|$(($_.CurrentTemperature - 2732) / 10)") } + if ($smi -and $n % 3 -eq 0) { + $out.Add('@@S gpu') + & $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("$_") } + } + $out.Add('@@SNAP_END') + try { [Console]::Out.Write(($out -join "`n") + "`n"); [Console]::Out.Flush() } catch { exit } + if ($once -or $parent.HasExited) { break } + $n++ + $left = $iv * 1000 - ((Get-Date) - $t0).TotalMilliseconds + if ($left -gt 0) { Start-Sleep -Milliseconds ([int]$left) } +} diff --git a/dev/collector.sh b/dev/collector.sh new file mode 100644 index 0000000000000000000000000000000000000000..89cb4b20caeb8a3c5b99d699515910bf9debdebd --- /dev/null +++ b/dev/collector.sh @@ -0,0 +1,77 @@ +sm_main() { +iv="${1:-2}" once="${2:-0}" n=0 +export LC_ALL=C +while :; do + echo "@@SNAP_BEGIN" + if [ $((n % 15)) -eq 0 ]; then + echo "@@S info" + echo "hostname=$(cat /proc/sys/kernel/hostname 2>/dev/null)" + echo "kernel=$(uname -r 2>/dev/null)" + echo "arch=$(uname -m 2>/dev/null)" + echo "os=$(sed -n 's/^PRETTY_NAME=//p' /etc/os-release 2>/dev/null | tr -d '"')" + echo "cpumodel=$(grep -m1 -E '^(model name|Hardware|Processor|cpu model)' /proc/cpuinfo 2>/dev/null | cut -d: -f2- | sed 's/^ *//')" + echo "clk=$(getconf CLK_TCK 2>/dev/null || echo 100)" + echo "page=$(getconf PAGESIZE 2>/dev/null || echo 4096)" + echo "virt=$(systemd-detect-virt 2>/dev/null || echo unknown)" + echo "@@S passwd"; cut -d: -f1,3 /etc/passwd 2>/dev/null + fi + echo "@@S uptime"; cat /proc/uptime + echo "@@S loadavg"; cat /proc/loadavg + echo "@@S stat" + grep -E '^(cpu|ctxt|processes|procs_)' /proc/stat + awk '/^intr/ {print "intr", $2}' /proc/stat + echo "@@S meminfo"; cat /proc/meminfo + echo "@@S netdev"; cat /proc/net/dev + echo "@@S netstate" + for i in /sys/class/net/*; do + [ -e "$i" ] || continue + echo "${i##*/} $(cat "$i/operstate" 2>/dev/null || echo unknown) $(cat "$i/speed" 2>/dev/null || echo -1)" + done + echo "@@S diskstats"; cat /proc/diskstats + echo "@@S df"; df -P -T -k 2>/dev/null || df -P -k 2>/dev/null + echo "@@S sockstat"; cat /proc/net/sockstat 2>/dev/null + echo "@@S tcp" + 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]}' + echo "@@S thermal" + for z in /sys/class/thermal/thermal_zone*; do + [ -r "$z/temp" ] && echo "$(cat "$z/type" 2>/dev/null)|$(cat "$z/temp" 2>/dev/null)" + done + for h in /sys/class/hwmon/hwmon*; do + [ -d "$h" ] || continue + hn=$(cat "$h/name" 2>/dev/null) + for t in "$h"/temp*_input; do + [ -r "$t" ] || continue + l=$(cat "${t%_input}_label" 2>/dev/null) + echo "$hn ${l:-${t##*/}}|$(cat "$t" 2>/dev/null)" + done + done + echo "@@S freq" + for c in /sys/devices/system/cpu/cpu[0-9]*; do + f=$(cat "$c/cpufreq/scaling_cur_freq" 2>/dev/null) && echo "${c##*/cpu} $f" + done + echo "@@S procs" + cat /proc/[0-9]*/stat 2>/dev/null | awk '{ + if (!match($0, /\(.*\)/)) next + comm = substr($0, RSTART + 1, RLENGTH - 2) + rest = substr($0, RSTART + RLENGTH + 1) + k = split(rest, r, " ") + if (k < 22) next + print $1, r[1], r[2], r[12] + r[13], r[17], r[18], r[20], r[21], r[22], comm + }' + echo "@@S uids"; ls -ln /proc 2>/dev/null | awk '$NF ~ /^[0-9]+$/ {print $NF, $3}' + if [ $((n % 5)) -eq 0 ]; then + echo "@@S services" + systemctl list-units --type=service --all --no-legend --no-pager --plain 2>/dev/null | head -n 600 + fi + if [ $((n % 3)) -eq 0 ] && command -v nvidia-smi >/dev/null 2>&1; then + echo "@@S gpu" + 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 + fi + echo "@@S users"; who 2>/dev/null | wc -l + echo "@@SNAP_END" || exit 0 + [ "$once" = "once" ] && break + n=$((n + 1)) + sleep "$iv" +done +} +sm_main "$@" diff --git a/dev/fakewin/powershell b/dev/fakewin/powershell new file mode 100755 index 0000000000000000000000000000000000000000..fd9c31b09071700b54fb862350a8ce4a1d186181 --- /dev/null +++ b/dev/fakewin/powershell @@ -0,0 +1,47 @@ +#!/usr/bin/env python3 +"""Stand-in for powershell.exe so the Windows editions can be run on Linux. +Collector script on stdin -> emits synthetic Windows-format frames; anything else -> echoes the command.""" +import math, random, re, sys, time +src = sys.stdin.read() +if '@@SNAP_BEGIN' not in src: + cmd = src.strip().splitlines() + print('[fake powershell] would run:'); print('\n'.join(cmd[-6:])); sys.exit(0) +iv = float((re.search(r'\$iv\s*=\s*([\d.]+)', src) or [0, 2])[1]); once = '$once = $true' in src +GB = 1 << 30; n = 0; rx = tx = 5e9; cput = {4: 9e9, 620: 1e8, 1200: 5e9, 2040: 3e9, 3311: 1e9, 4100: 2e8, 5000: 7e8} +names = {4: 'System', 620: 'svchost.exe', 1200: 'sqlservr.exe', 2040: 'chrome.exe', 3311: 'explorer.exe', 4100: 'powershell.exe', 5000: 'w3wp.exe'} +boot = time.time() - 4 * 86400 - 3600 +while True: + t = time.time(); L = ['@@SNAP_BEGIN'] + if n % 15 == 0: + L += ['@@S info', 'hostname=WIN-FAKE01', 'os=Microsoft Windows Server 2022 Standard', 'kernel=10.0.20348', 'arch=64-bit', + 'cpumodel=Intel(R) Xeon(R) Gold 6248 CPU @ 2.50GHz', 'mhz=2500', 'virt=Microsoft Corporation Virtual Machine', 'admin=1', + '@@S users'] + [f'{p}|{"NT AUTHORITY\\SYSTEM" if p < 2000 else "WIN-FAKE01\\admin"}' for p in names] + cpu = 35 + 30 * math.sin(t / 20) + random.uniform(-5, 5) + L += ['@@S os', f'ts={int(t * 1000)}', f'uptime={int(t - boot)}', f'memtotal={16 * GB}', f'swaptotal={8 * GB}', f'swapfree={int(6.5 * GB)}', '@@S cpu'] + for c in ['_Total', '0', '1', '2', '3']: + v = max(0, min(100, cpu + (0 if c == '_Total' else random.uniform(-15, 15)))) + L.append(f'{c}|{v:.0f}|{v * .7:.0f}|{v * .3:.0f}|{v * .03:.0f}|{int(3000 + v * 40)}') + L += ['@@S sys', f'queue={int(max(0, cpu - 50) / 10)}', f'ctxt={int(8000 + cpu * 100)}', 'threads=1832', + '@@S mem', f'avail={int((6 + math.sin(t / 60)) * GB)}', f'free={2 * GB}', f'standby={4 * GB}', f'syscache={GB // 2}', f'modified={GB // 8}', + f'pool={GB}', f'commit={11 * GB}', f'commitlimit={24 * GB}', f'pages={int(random.uniform(0, 40))}', '@@S net'] + rx += random.uniform(2e5, 9e5) * iv; tx += random.uniform(5e4, 3e5) * iv + L += [f'Ethernet|Up|10000|Ethernet|{int(rx)}|{int(tx)}|{int(rx / 900)}|{int(tx / 700)}|0|3|Microsoft Hyper-V Network Adapter', + 'Loopback Pseudo-Interface 1|Up|1073|Loopback|0|0|0|0|0|0|Software Loopback Interface 1', + 'vEthernet (WSL)|Down|0|Ethernet|1200|900|10|9|0|0|Hyper-V Virtual Ethernet Adapter', + '@@S tcp', 'Established 42', 'TimeWait 3', 'CloseWait 1', 'Listen 27', '@@S disk', + f'0 C:|{int(random.uniform(0, 4e6))}|{int(random.uniform(0, 9e6))}|{int(random.uniform(0, 80))}|{int(random.uniform(0, 200))}|{int(random.uniform(60, 100))}', + f'1 D:|0|{int(random.uniform(0, 1e5))}|0|2|99', '@@S df', f'C:\\|Windows|NTFS|{127 * GB}|{int(21.5 * GB)}', f'D:\\|Data|NTFS|{500 * GB}|{310 * GB}', '@@S procs', + f'0|0|{int((t - boot) * 4e7)}|0|4|0|8192|8192|System Idle Process'] + for p, nm in names.items(): + cput[p] += (random.uniform(0, .02) + (.6 if p == 1200 else .05 if p == 2040 else 0) * (1 + math.sin(t / 15))) * iv * 1e7 + L.append(f'{p}|{4 if p > 4 else 0}|{int(cput[p])}|{8 if p != 4100 else 6}|{12 + p % 40}|{int(boot + p)}|{(2 + p % 5) * GB}|{int((.05 + (p % 7) * .11) * GB)}|{nm}') + L += ['@@S sessions', '1'] + if n % 5 == 0: + L += ['@@S services', 'Spooler|Running|Auto|0|Print Spooler', 'W3SVC|Running|Auto|0|World Wide Web Publishing Service', 'MSSQLSERVER|Running|Auto|0|SQL Server (MSSQLSERVER)', + 'BrokenSvc|Stopped|Auto|1067|Broken Demo Service', 'gupdate|Stopped|Auto|0|Google Update Service', 'RemoteRegistry|Stopped|Disabled|1077|Remote Registry', + 'wuauserv|Stopped|Manual|0|Windows Update', 'WinDefend|Running|Auto|0|Microsoft Defender Antivirus Service'] + L += ['@@S thermal', f'ACPI\\ThermalZone\\TZ00_0|{45 + cpu / 5:.1f}', '@@SNAP_END'] + try: sys.stdout.write('\n'.join(L) + '\n'); sys.stdout.flush() + except OSError: sys.exit(0) + if once: break + n += 1; time.sleep(iv) diff --git a/dev/pytk b/dev/pytk new file mode 100755 index 0000000000000000000000000000000000000000..d047dada91b7caa3bab17cb80a1f18f88b099862 --- /dev/null +++ b/dev/pytk @@ -0,0 +1,7 @@ +#!/bin/sh +# python3 with a locally unpacked tkinter (no root): pytk script.py ... +T="$HOME/.local/share/sm-dev/tk/root" +export PYTHONPATH="$T/usr/lib/python3.14:$T/usr/lib/python3.14/lib-dynload${PYTHONPATH:+:$PYTHONPATH}" +export LD_LIBRARY_PATH="$T/usr/lib/x86_64-linux-gnu${LD_LIBRARY_PATH:+:$LD_LIBRARY_PATH}" +[ -d "$T/usr/share/tcltk/tk8.6" ] && export TK_LIBRARY="$T/usr/share/tcltk/tk8.6" +exec python3 "$@" diff --git a/dev/tests/cqt/analysis_expected.txt b/dev/tests/cqt/analysis_expected.txt new file mode 100644 index 0000000000000000000000000000000000000000..7373facc0e53ed70bd10f29a352eef7a60077186 --- /dev/null +++ b/dev/tests/cqt/analysis_expected.txt @@ -0,0 +1,12 @@ +reloaded raw=720 minute=4320 hour=72 day=3 bytes=695672 +range 7d -> 1 minute, 4321 pts +health=33 grade=F diskFullDays=3.00 slope/day=5.00 memSlope/h=2.00 r2=1.00 up24=97.99 up7=99.32 + [critical] Disk / will be full in 3d 0h 0m | auto=1 action=disk_cleanup + [warning] Availability last 24 h is 97.99% | auto=0 action= + [warning] Possible memory leak: leaky (PID 4242) | auto=0 action=kill_pid 4242 + [warning] Runaway process: spinner (PID 777) | auto=1 action=renice 777 + [warning] Service web.service has failed | auto=1 action=restart_service web.service + [warning] Service old.service has failed | auto=0 action=restart_service old.service + [info] Memory keeps growing (+2.0 points/hour) | auto=0 action= + [info] Unusually high memory | auto=0 action= +disk stats min=70.0 avg=77.5 p95=84.3 max=85.0 n=4292; capacity: CPU headroom is healthy (p95 30.0%). | Memory headroom is healthy (p95 56.4%). | Disk grows 5.00 points/day - full in about 3d 0h 0m. diff --git a/dev/tests/cqt/analysis_test.cpp b/dev/tests/cqt/analysis_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..96b4c88f3ce4abb6938855b6722a20d224dc817d --- /dev/null +++ b/dev/tests/cqt/analysis_test.cpp @@ -0,0 +1,38 @@ +// Synthetic 3-day history -> store reload + analyzer. Expected output: analysis_expected.txt (availability may differ by 0.05). +#include "core/History.h" +#include +#include +#include +#include +int main(int argc, char **argv) { + QCoreApplication app(argc, argv); + const QString dir = argv[1]; + QDir(dir).removeRecursively(); + const qint64 now = QDateTime::currentSecsSinceEpoch(), start = now - 3 * 86400; + { + HistoryStore st(dir); + for (qint64 t = start; t <= now; t += 30) { + float v[H_COUNT] = {}; + const double days = (t - start) / 86400.0; + v[H_CPU] = 20 + 10 * ((t / 3600) % 24 > 8 && (t / 3600) % 24 < 18); + v[H_DISK] = 70 + 5 * days; + v[H_MEM] = (now - t < 6 * 3600) ? 50 + 2.0 * (6 - (now - t) / 3600.0) : 50; + v[H_LOAD] = 1; v[H_RX] = 1e6; v[H_TX] = 5e5; + st.add(t, v, !(t > now - 86400 && t < now - 86400 + 1800)); + } + } + HistoryStore st(dir); + printf("reloaded raw=%d minute=%d hour=%d day=%d bytes=%lld\n", st.tier(Tier::Raw).size(), st.tier(Tier::Minute).size(), st.tier(Tier::Hour).size(), st.tier(Tier::Day).size(), st.diskBytes()); + Tier used; auto r = st.range(now - 7 * 86400, now, &used); + printf("range 7d -> %s, %d pts\n", qPrintable(tierName(used)), r.size()); + Metrics m; m.valid = true; m.cpuCount = 4; m.memPct = 62; m.maxDiskPct = 85; m.fullestMount = "/"; + AutopilotConfig ap; ap.diskCleanup = true; ap.diskForecastDays = 5; + ProcTrend p; p.pid = 4242; p.name = "leaky"; p.minutesTracked = 45; p.rssNow = 900e6; p.rssGrowth = 400e6; p.rssGrowthPct = 80; p.rssMonotonic = 0.95; + ProcTrend q; q.pid = 777; q.name = "spinner"; q.cpuNow = 99; q.highCpuMinutes = 12; + ServiceTrend s1{"web.service", true, false, 1, 0}, s2{"old.service", true, true, 0, 0}; + Analysis a = analyze(st, m, ap, {p, q}, {s1, s2}, true); + printf("health=%d grade=%s diskFullDays=%.2f slope/day=%.2f memSlope/h=%.2f r2=%.2f up24=%.2f up7=%.2f\n", a.health, qPrintable(a.grade), a.diskFullDays, a.diskSlopePerDay, a.memSlopePerHour, a.memTrendR2, a.up[0], a.up[1]); + for (const auto &f : a.findings) printf(" [%s] %s | auto=%d action=%s %s\n", qPrintable(f.severity), qPrintable(f.title), f.autoEligible, qPrintable(f.action), qPrintable(f.actionArg)); + Stats s = stats(r, H_DISK); + printf("disk stats min=%.1f avg=%.1f p95=%.1f max=%.1f n=%d; capacity: %s\n", s.min, s.avg, s.p95, s.max, s.count, qPrintable(a.capacity.join(" | "))); +} diff --git a/dev/tests/cqt/build_analysis_test.sh b/dev/tests/cqt/build_analysis_test.sh new file mode 100755 index 0000000000000000000000000000000000000000..9f4618df3e27e8f70f41e69d7bf1765c9ebd395a --- /dev/null +++ b/dev/tests/cqt/build_analysis_test.sh @@ -0,0 +1,5 @@ +#!/bin/sh +# usage: build_analysis_test.sh "" [extra .cpp ...] (C++ editions only) +P="$1"; O="$2"; shift 2; SDK=$HOME/.local/share/qt5-sdk/root; I=$SDK/usr/include/x86_64-linux-gnu/qt5 +g++ -std=c++17 -O1 -fPIC -I$I -I$I/QtCore -I$SDK/usr/include -I$SDK/usr/lib/x86_64-linux-gnu/qt5/mkspecs/linux-g++ -I"$P/src" \ + "$(dirname "$0")/analysis_test.cpp" "$P/src/core/Model.cpp" "$P/src/core/History.cpp" "$@" -o "$O" -L/usr/lib/x86_64-linux-gnu -l:libQt5Core.so.5 diff --git a/dev/tests/cqt/build_click.sh b/dev/tests/cqt/build_click.sh new file mode 100755 index 0000000000000000000000000000000000000000..72fea5c69a5334074d0479b0b10d6dc63c14bc79 --- /dev/null +++ b/dev/tests/cqt/build_click.sh @@ -0,0 +1,6 @@ +#!/bin/bash +# usage: build_click.sh +set -e; P="$1"; O="$2"; OUT="$3"; SDK=$HOME/.local/share/qt5-sdk/root; I=$SDK/usr/include/x86_64-linux-gnu/qt5 +OBJS=(); for o in "$O"/*.o; do [[ $(basename "$o") == main.o ]] || OBJS+=("$o"); done +g++ -std=c++17 -O1 -fPIC -DQT_NO_DEBUG -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++ -I"$P/src" \ + "$(dirname "$0")/click_test.cpp" "${OBJS[@]}" -o "$OUT" -L/usr/lib/x86_64-linux-gnu -l:libQt5Widgets.so.5 -l:libQt5Gui.so.5 -l:libQt5Core.so.5 -lpthread diff --git a/dev/tests/cqt/click_test.cpp b/dev/tests/cqt/click_test.cpp new file mode 100644 index 0000000000000000000000000000000000000000..d100263ef3b375e5900487f86ea96f48f9b9334f --- /dev/null +++ b/dev/tests/cqt/click_test.cpp @@ -0,0 +1,232 @@ +// Offscreen click test: drives the real main window through its widgets. Scratch config only; every confirmation is answered "No". +#include "ui/Widgets.h" +#include "ui/Windows.h" +#include +#include + +static int fails = 0; +static void wait(int ms) { QEventLoop l; QTimer::singleShot(ms, &l, &QEventLoop::quit); l.exec(); } +static bool waitFor(const std::function &c, int ms) { QElapsedTimer t; t.start(); while (!c() && t.elapsed() < ms) wait(100); return c(); } +static void check(bool ok, const QString &what) { printf("%s %s\n", ok ? "PASS" : "FAIL", qPrintable(what)); fflush(stdout); fails += !ok; } +static void note(const QString &s) { printf(" %s\n", qPrintable(s)); fflush(stdout); } +static QAbstractButton *btn(QWidget *root, const QString &text) +{ + for (auto *b : root->findChildren()) if (b->text() == text) return b; + printf("FAIL button '%s' not found\n", qPrintable(text)); ++fails; + return nullptr; +} +// answers the next modal dialog +static void onModal(const std::function &f, int ms = 500) { QTimer::singleShot(ms, qApp, [f] { f(QApplication::activeModalWidget()); }); } +static QString asked; // text of the last question that was answered "No" +static void sayNo() +{ + asked.clear(); + onModal([](QWidget *m) { + if (auto *box = qobject_cast(m)) asked = box->text(), (box->button(QMessageBox::No) ? box->button(QMessageBox::No) : box->button(QMessageBox::Cancel))->click(); + else if (auto *d = qobject_cast(m)) asked = "dialog: " + d->windowTitle(), d->reject(); + }); +} +static QJsonObject serverJson(int i) +{ + QFile f(ServerManager::configDir() + "/servers.json"); + f.open(QIODevice::ReadOnly); + return QJsonDocument::fromJson(f.readAll())["servers"].toArray()[i].toObject(); +} +static int visibleRows(QTableWidget *t) { int n = 0; for (int r = 0; r < t->rowCount(); ++r) n += !t->isRowHidden(r); return n; } +static int rowOf(QTableWidget *t, const QString &key) { for (int r = 0; r < t->rowCount(); ++r) if (t->item(r, 0) && t->item(r, 0)->text() == key) return r; return -1; } + +int main(int argc, char **argv) +{ + QApplication app(argc, argv); + QApplication::setApplicationName("ServerMonitor"), QApplication::setOrganizationName("ServerMonitor"), QApplication::setQuitOnLastWindowClosed(false); + app.setStyleSheet(C::styleSheet()); + QElapsedTimer run; run.start(); + if (!ServerManager::configDir().contains("/review-cpp/")) return puts("refusing to run: XDG_CONFIG_HOME is not a scratch dir"), 2; + ServerManager mgr; + MainWindow w(&mgr); + mgr.load(); + w.show(); + auto *tabs = w.findChild(); + auto *sideW = w.findChild("Sidebar"); + auto *side = sideW->findChild(); + auto *stack = w.findChild(); + auto tab = [&](const QString &n) -> QWidget * { + for (int i = 0; i < tabs->count(); ++i) if (tabs->tabText(i).startsWith(n)) { tabs->setCurrentIndex(i), wait(400); return tabs->widget(i); } + return nullptr; + }; + auto open = [&](int row) { side->setCurrentRow(row); emit side->itemClicked(side->item(row)); wait(400); }; + check(mgr.sessions().size() == 2 && mgr.sessions()[0]->config().autopilot.dryRun && mgr.sessions()[1]->config().autopilot.dryRun, "scratch config loaded: 2 servers, autopilot in dry run"); + ServerSession *local = mgr.sessions()[0]; + const bool on = waitFor([&] { return local->online(); }, 20000); + check(on, QString("local server online after %1 ms (needs 2 frames)").arg(run.elapsed())); + check(local->analysis().when > 0 && !local->analysis().healthReasons.join(' ').contains("unreachable"), "analyzed with the first sample: health " + QString::number(local->analysis().health)); + + // ---- open a server, visit every tab + open(0); + check(tabs->isVisible() && stack->currentWidget()->findChild("H1")->text() == "This computer", "open server: detail page shows 'This computer'"); + QStringList names; + for (int i = 0; i < tabs->count(); ++i) tabs->setCurrentIndex(i), wait(300), names << tabs->tabText(i); + check(names.size() == 11, "all tabs opened: " + names.join(", ")); + + // ---- processes: filter, hidden selection, question answered No + QWidget *pt = tab("Processes"); + auto *ptbl = pt->findChild(); + auto *flt = pt->findChild(); + auto status = [](QWidget *t) { QStringList l; for (auto *x : t->findChildren()) if (x->text().startsWith("Select") || x->text().startsWith("Running") || x->text().startsWith(u8"✓") || x->text().startsWith(u8"✗")) l << x->text(); return l.join(" / "); }; + const int total = ptbl->rowCount(); + pt->findChild()->setChecked(true); // freeze so the rows hold still + const QString word = ptbl->item(0, 1)->text().left(5); + flt->setText(word), wait(100); + bool all = visibleRows(ptbl) > 0; + for (int r = 0; r < ptbl->rowCount(); ++r) { + bool hit = false; + for (int c = 0; c < ptbl->columnCount(); ++c) hit |= ptbl->item(r, c)->text().contains(word, Qt::CaseInsensitive); + all &= hit == !ptbl->isRowHidden(r); + } + check(total > 3 && all, QString("process filter '%1': %2 of %3 rows shown, exactly the matching ones").arg(word).arg(visibleRows(ptbl)).arg(total)); + flt->setText("zz-no-such-process"), wait(100); + check(visibleRows(ptbl) == 0, "process filter without match hides all rows"); + ptbl->setCurrentCell(0, 0); + sayNo(), btn(pt, "Kill")->click(), wait(700); + check(asked.isEmpty() && status(pt) == "Select a process first.", "Kill with the selected row filtered out: no question, status '" + status(pt) + "'"); + flt->clear(), wait(100); + check(visibleRows(ptbl) == total, "clearing the filter shows all rows again"); + ptbl->setCurrentCell(1, 0); + const QString pid = ptbl->item(1, 0)->text(), pname = ptbl->item(1, 1)->text(); + sayNo(), btn(pt, "Kill")->click(), wait(700); + check(asked.contains(pid) && asked.contains(pname) && asked.contains("This computer") && !status(pt).contains("Running"), "Kill asks first (answered No, nothing ran): '" + asked + "'"); + sayNo(), btn(pt, u8"Priority…")->click(), wait(700); + check(asked == "dialog: Change priority" && !status(pt).contains("Running"), "Priority… opens its dialog (cancelled)"); + open(1), open(0), pt = tab("Processes"); + check(!pt->findChild()->isChecked(), "Freeze list is switched off when another server is opened"); + pt->findChild()->setChecked(false); + if (P::posixCpu) { // a selected process that ends must not hand its selection to another row + QProcess child; + child.start("sleep", {"600"}); + child.waitForStarted(); + const QString cp = QString::number(child.processId()); + check(waitFor([&] { return rowOf(ptbl, cp) >= 0; }, 10000), "test's own 'sleep' child (PID " + cp + ") appears in the list"); + ptbl->setCurrentCell(rowOf(ptbl, cp), 0), wait(2500); + check(ptbl->currentRow() == rowOf(ptbl, cp) && ptbl->currentRow() >= 0, "selection follows the process across refreshes"); + child.kill(), child.waitForFinished(); + waitFor([&] { return rowOf(ptbl, cp) < 0; }, 10000), wait(300); + const QString now = ptbl->currentRow() >= 0 ? ptbl->item(ptbl->currentRow(), 0)->text() + " " + ptbl->item(ptbl->currentRow(), 1)->text() : "nothing"; + check(ptbl->currentRow() < 0 && ptbl->selectedItems().isEmpty(), "after the selected process ended the selection is: " + now); + sayNo(), btn(pt, "Terminate")->click(), wait(700); + check(asked.isEmpty(), "Terminate afterwards asks nothing" + (asked.isEmpty() ? QString() : " - BUT ASKED: " + asked)); + } + + // ---- services: logs dialog, question answered No + QWidget *st = tab("Services"); + auto *stbl = st->findChild(); + check(stbl->rowCount() > 0, QString("services listed: %1").arg(stbl->rowCount())); + QPointer logs; + if (stbl->rowCount()) { + stbl->setCurrentCell(0, 0); + const QString unit = stbl->item(0, 0)->text(); + btn(st, "Logs")->click(), wait(200); + logs = st->findChild(); + auto *txt = logs ? logs->findChild() : nullptr; + check(txt && logs->isVisible() && waitFor([&] { return txt->toPlainText() != u8"Loading…"; }, 20000), "logs dialog for " + unit + " loaded"); + if (txt) note(txt->toPlainText().left(160).replace('\n', " | ")); + sayNo(), btn(st, "Stop")->click(), wait(700); + check(asked.contains("Stop " + unit) && !status(st).contains("Running"), "Stop asks first (answered No, nothing ran): '" + asked + "'"); + } + + // ---- alert rules: add and delete + QWidget *rt = tab("Alert rules"); + QTableWidget *rules = nullptr; + for (auto *t : rt->findChildren()) if (t->columnCount() == 6) rules = t; + const int n0 = rules->rowCount(); + onModal([](QWidget *m) { + for (auto *c : m->findChildren()) if (c->findData("notify") >= 0) c->setCurrentIndex(c->findData("notify")); // never an action + m->findChild()->button(QDialogButtonBox::Ok)->click(); + }); + btn(rt, "+ Add rule")->click(), wait(200); + check(n0 == 7 && rules->rowCount() == 8 && serverJson(0)["rules"].toArray().size() == 8 && serverJson(0)["rules"].toArray()[7].toObject()["action"] == "notify", "rule added: table 8 rows, servers.json 8 rules, new one is notify-only: " + rules->item(7, 1)->text()); + rules->setCurrentCell(7, 1), btn(rt, "Delete")->click(), wait(200); + check(rules->rowCount() == 7 && serverJson(0)["rules"].toArray().size() == 7, "rule deleted: table 7 rows, servers.json 7 rules"); + + // ---- autopilot setting + QWidget *it = tab("Insights"); + for (auto *sp : it->findChildren()) if (sp->suffix() == " / hour max") sp->setValue(5); + wait(200); + check(serverJson(0)["autopilot"].toObject()["maxRestartsPerHour"].toInt() == 5 && serverJson(0)["autopilot"].toObject()["dryRun"].toBool() && local->config().autopilot.maxRestartsPerHour == 5, "autopilot 'max restarts per hour' = 5 saved to servers.json, dry run still on"); + btn(it, "Analyze now")->click(), wait(300); + check(local->analysis().when > 0, QString("Analyze now ran: health %1, %2 finding(s)").arg(local->analysis().health).arg(local->analysis().findings.size())); + + // ---- console + QWidget *ct = tab("Console"); + auto *in = ct->findChild(); + auto *out = ct->findChild(); + in->setText("echo sm-click-test"), emit in->returnPressed(); + check(waitFor([&] { return out->toPlainText().contains("[exit"); }, 15000) && out->toPlainText().contains(QRegularExpression("\\n.*sm-click-test.*\\n(.|\\n)*\\[exit 0")), "console 'echo sm-click-test' printed its output and exit 0"); + note(out->toPlainText().section('\n', -3).replace('\n', " | ")); + btn(ct, "Disk usage")->click(); + check(waitFor([&] { return out->toPlainText().count("[exit") == 2; }, 20000), "quick diagnostic 'Disk usage' finished"); + const int blocks = out->document()->blockCount(); + sayNo(), btn(ct, "Reboot")->click(), wait(700); + check(asked.contains("Reboot on This computer?") && out->document()->blockCount() == blocks, "Reboot asks first (answered No, nothing ran): '" + asked.section('\n', 0, 0) + "'"); + in->setText(P::posixCpu ? "sleep 30" : "Start-Sleep 30"), emit in->returnPressed(); + wait(1000), btn(&w, u8"⟳ Reconnect")->click(); + const bool told = waitFor([&] { return out->toPlainText().contains("[exit -1"); }, 4000); + check(told || !P::posixCpu, // the stand-in powershell returns at once, so nothing is pending there + "Reconnect while a command runs: the console is told (" + out->toPlainText().section('\n', -2).replace('\n', " | ") + ")"); + check(waitFor([&] { return local->online(); }, 20000) && !local->analysis().healthReasons.join(' ').contains("unreachable"), "online again after Reconnect, analysis is fresh: " + local->analysis().healthReasons.join(", ")); + open(0), tab("Console"); + check(out->toPlainText().count("Console for") == 1, QString("opening the same server again: 'Console for' header appears %1 time(s)").arg(out->toPlainText().count("Console for"))); + + // ---- add-server dialog with Test connection (cancelled) + onModal([](QWidget *m) { + auto *d = qobject_cast(m); + QComboBox *via = nullptr; + for (auto *c : d->findChildren()) if (!c->isEditable()) via = c; + auto result = [d] { for (auto *l : d->findChildren()) if (l->text().startsWith(u8"✓") || l->text().startsWith(u8"✗")) return l->text(); return QString(); }; + via->setCurrentIndex(0); + btn(d, "Test connection")->click(); + waitFor([&] { return !result().isEmpty(); }, 15000); + check(result().startsWith(u8"✓"), "Test connection, this machine: " + result()); + via->setCurrentIndex(1); + for (auto *e : d->findChildren()) if (e->placeholderText().startsWith("hostname")) e->setText("127.0.0.1"); + for (auto *sp : d->findChildren()) if (sp->prefix() == "port ") sp->setValue(1); + btn(d, "Test connection")->click(), wait(200); + waitFor([&] { return result().startsWith(u8"✗"); }, 25000); + check(result().startsWith(u8"✗"), "Test connection, SSH to a closed port: " + result()); + d->reject(); + }); + btn(sideW, "+ Add")->click(), wait(300); + check(mgr.sessions().size() == 2, "add-server dialog cancelled: still 2 servers"); + + // ---- offline host: every tab, downtime samples + open(1); + for (int i = 0; i < tabs->count(); ++i) tabs->setCurrentIndex(i), wait(250); + ServerSession *off = mgr.sessions()[1]; + btn(tab("Insights"), "Analyze now")->click(), wait(800), w.grab().save(qEnvironmentVariable("SM_SHOTS") + "/offline-insights.png"); + tab("History"), wait(500), w.grab().save(qEnvironmentVariable("SM_SHOTS") + "/offline-history.png"); + const int down = off->store().tier(Tier::Raw).size(); + check(off->status() != Status::Online && down >= run.elapsed() / 2000 * 0.6, QString("offline host: all tabs opened; %1 downtime samples in %2 s at a 2 s interval").arg(down).arg(run.elapsed() / 1000)); + + // ---- events page + for (auto *b : sideW->findChildren()) if (b->text().contains("Events")) b->click(); + wait(300); + QTableWidget *ev = stack->currentWidget()->findChild(); + check(ev && ev->columnCount() == 4 && ev->rowCount() > 0, QString("events page lists %1 event(s)").arg(ev ? ev->rowCount() : -1)); + for (int r = 0; ev && r < qMin(4, ev->rowCount()); ++r) note(ev->item(r, 2)->text() + " " + ev->item(r, 1)->text() + " " + ev->item(r, 3)->text().left(110)); + auto *ef = stack->currentWidget()->findChild(); + ef->setCurrentIndex(ef->findText("critical")), wait(100); + bool crit = true; + for (int r = 0; r < ev->rowCount(); ++r) crit &= ev->item(r, 2)->text() == "CRITICAL"; + check(crit, QString("event filter 'critical': %1 row(s), all critical").arg(ev->rowCount())); + + // ---- remove the server while its logs dialog is open (scratch config) + open(0); + check(!logs.isNull() && logs->isVisible(), "logs dialog still open"); + onModal([](QWidget *m) { btn(m, "Remove + delete history")->click(); }); + side->setCurrentRow(0), btn(sideW, "Remove")->click(), wait(500); + check(mgr.sessions().size() == 1 && !tabs->isVisible() && !QDir(ServerManager::configDir() + "/history/local1").exists(), "server removed with its history folder, dashboard shown"); + if (logs) btn(logs, "Reload")->click(), wait(500), btn(logs, "Close")->click(), wait(200); + check(logs.isNull(), "Reload + Close in the orphaned logs dialog: no crash"); + wait(500); + printf("%s (%d failed) in %lld s\n", fails ? "FAILED" : "ALL PASSED", fails, run.elapsed() / 1000); + return fails != 0; +} diff --git a/dev/tests/cqt/scratch-config/ServerMonitor/ServerMonitor/servers.json b/dev/tests/cqt/scratch-config/ServerMonitor/ServerMonitor/servers.json new file mode 100644 index 0000000000000000000000000000000000000000..47bde7414ab9fa9f609fa45071f459a98da37337 --- /dev/null +++ b/dev/tests/cqt/scratch-config/ServerMonitor/ServerMonitor/servers.json @@ -0,0 +1,3 @@ +{"version":1,"servers":[ + {"id":"local1","name":"This computer","group":"Local","transport":0,"interval":2,"enabled":true,"autopilot":{"enabled":true,"dryRun":true}}, + {"id":"ssh1","name":"Unreachable box","group":"Test","transport":1,"host":"127.0.0.1","port":1,"user":"nobody","interval":2,"enabled":true,"autopilot":{"enabled":true,"dryRun":true}}]} diff --git a/dev/tests/python/analysis_test.py b/dev/tests/python/analysis_test.py new file mode 100644 index 0000000000000000000000000000000000000000..d3006d89ce48f2e3f051a0b7ed8dc15fed5650d3 --- /dev/null +++ b/dev/tests/python/analysis_test.py @@ -0,0 +1,44 @@ +"""Python port of ref/analysis_test.cpp: synthetic 3-day history -> store reload + analyzer.""" +import os, shutil, sys, time +sys.dont_write_bytecode = True +sys.path.insert(0, sys.argv[1]) +from history import * +from metrics import Metrics +from model import AutopilotConfig + +d = sys.argv[2] +shutil.rmtree(d, ignore_errors=True) +now = int(time.time()); start = now - 3 * 86400 +st = Store(d) +t0 = time.time() +for t in range(start, now + 1, 30): + v = [0.0] * H_COUNT + days = (t - start) / 86400.0 + v[CPU] = 20 + 10 * (8 < (t // 3600) % 24 < 18) + v[DISK] = 70 + 5 * days + v[MEM] = 50 + 2.0 * (6 - (now - t) / 3600.0) if now - t < 6 * 3600 else 50 + v[LOAD] = 1; v[RX] = 1e6; v[TX] = 5e5 + st.add(t, v, not (now - 86400 < t < now - 86400 + 1800)) +t1 = time.time() +st = Store(d) +print('reloaded raw=%d minute=%d hour=%d day=%d bytes=%d' % (*map(len, st.tiers), st.disk_bytes())) +r, used = st.span(now - 7 * 86400, now) +print('range 7d -> %s, %d pts' % (TIER_NAMES[used], len(r))) +m = Metrics(); m.valid = True; m.cpu_count = 4; m.mem_pct = 62; m.max_disk_pct = 85; m.fullest_mount = '/' +ap = AutopilotConfig(); ap.diskCleanup = True; ap.diskForecastDays = 5 +p = ProcTrend(pid=4242, name='leaky', minutes=45, rss_now=900e6, rss_growth=400e6, rss_growth_pct=80, rss_monotonic=0.95) +q = ProcTrend(pid=777, name='spinner', cpu_now=99, high_cpu_minutes=12) +s1, s2 = ServiceTrend('web.service', True, False, 1, 0), ServiceTrend('old.service', True, True, 0, 0) +t2 = time.time() +a = analyze(st, m, ap, [p, q], [s1, s2], True) +t3 = time.time() +print('health=%d grade=%s diskFullDays=%.2f slope/day=%.2f memSlope/h=%.2f r2=%.2f up24=%.2f up7=%.2f' % (a.health, a.grade, a.disk_full_days, a.disk_slope_per_day, a.mem_slope_per_hour, a.mem_trend_r2, a.up[0], a.up[1])) +for f in a.findings: + print(' [%s] %s | auto=%d action=%s %s' % (f.severity, f.title, f.auto, f.action, f.arg)) +s = stats(r, DISK) +print('disk stats min=%.1f avg=%.1f p95=%.1f max=%.1f n=%d; capacity: %s' % (s.min, s.avg, s.p95, s.max, s.count, ' | '.join(a.capacity))) +print('# timing: write %.2fs analyze %.3fs' % (t1 - t0, t3 - t2), file=sys.stderr) +for t, name in enumerate(TIERS): + size = os.path.getsize(os.path.join(d, name + '.bin')) + assert open(os.path.join(d, name + '.bin'), 'rb').read(8) == b'SMH1\x0f\x00\x88\x00' and (size - 8) % 136 == 0 and (size - 8) // 136 == len(st.tiers[t]), name +print('# file layout ok: header 8 bytes + 136 bytes per record', file=sys.stderr) diff --git a/dev/tests/python/mkcfg.sh b/dev/tests/python/mkcfg.sh new file mode 100755 index 0000000000000000000000000000000000000000..86e084236ceda4a970fa98408bf69994cb0dabe5 --- /dev/null +++ b/dev/tests/python/mkcfg.sh @@ -0,0 +1,9 @@ +#!/bin/sh +# scratch config: this computer + one unreachable ssh host, autopilot in dry run usage: mkcfg.sh +rm -rf "$1"; mkdir -p "$1/ServerMonitorPy" +cat > "$1/ServerMonitorPy/servers.json" <<'JSON' +{"version": 1, "servers": [ + {"id": "local0000001", "name": "This computer", "group": "Local", "transport": 0, "autopilot": {"dryRun": true}}, + {"id": "dead00000001", "name": "Unreachable box", "group": "Test", "transport": 1, "host": "127.0.0.1", "port": 1, "user": "nobody", "autopilot": {"dryRun": true}} +]} +JSON diff --git a/dev/tests/python/t_core.py b/dev/tests/python/t_core.py new file mode 100644 index 0000000000000000000000000000000000000000..5bab92b1b20e506d34b4eefd9a3af13e7b39f181 --- /dev/null +++ b/dev/tests/python/t_core.py @@ -0,0 +1,141 @@ +"""Core checks without a UI: t_core.py . Scratch config only; nothing here controls the machine.""" +import os, shutil, struct, subprocess, sys, time +sys.dont_write_bytecode = True +proj = sys.argv[1] +sys.path.insert(0, proj) +scratch = os.path.join(os.path.dirname(os.path.abspath(__file__)), 'scratch-core') +shutil.rmtree(scratch, ignore_errors=True) +os.environ['XDG_CONFIG_HOME'] = os.environ['APPDATA'] = scratch +import plat, session, history +from history import Store, REC, HEADER, H_COUNT +from model import ServerConfig +from metrics import Metrics, Service, Proc +res = [] +def check(name, ok, info=''): + res.append(ok); print(('PASS ' if ok else 'FAIL ') + name + (f' [{info}]' if info else ''), flush=True) +def pump(sec, until=lambda: False): + end = time.time() + sec + while time.time() < end and not until(): + session.loop.pump(); time.sleep(0.02) + +# ---- 1. store: buckets left open by the last run are rebuilt ------------------------------- +d = os.path.join(scratch, 'h1') +now = int(time.time()) +st = Store(d) +t_end = now - 3 * 3600 - 1800 # the "previous run" stopped 3.5 h ago, after 2 h of samples +for t in range(t_end - 7200, t_end, 10): st.add(t, [5.0] * H_COUNT, True) +m_before, h_before = len(st.tiers[1]), len(st.tiers[2]) +st = Store(d) +st.add(now, [5.0] * H_COUNT, True) # the new run's first sample closes the old buckets +lm, lh = (t_end - 10) // 60 * 60, (t_end - 10) // 3600 * 3600 +check('reload keeps the minute bucket the last run left open', lm in st.tiers[1].ts, f'minute pts {m_before}->{len(st.tiers[1])}') +check('reload keeps the hour bucket the last run left open', lh in st.tiers[2].ts and st.tiers[2].n[list(st.tiers[2].ts).index(lh)] > 0, f'hour pts {h_before}->{len(st.tiers[2])}') +st = Store(d) +check('second reload changes nothing', lm in st.tiers[1].ts and lh in st.tiers[2].ts and len(set(st.tiers[1].ts)) == len(st.tiers[1]), f'minute={len(st.tiers[1])} hour={len(st.tiers[2])}') +# ---- 2. a cut-off record at the end of a file is removed before appending --------------------- +d = os.path.join(scratch, 'h2') +st = Store(d) +for t in range(now - 600, now - 300, 10): st.add(t, [7.0] * H_COUNT, True) +n0 = len(st.tiers[0]) +with open(os.path.join(d, 'raw.bin'), 'ab') as f: f.write(b'\x01' * 50) # crash in the middle of a write +st = Store(d) +for t in range(now - 300, now, 10): st.add(t, [7.0] * H_COUNT, True) +n1 = len(st.tiers[0]) +st = Store(d) +size = os.path.getsize(os.path.join(d, 'raw.bin')) - len(HEADER) +check('cut-off record does not misalign later appends', len(st.tiers[0]) == n1 and size % REC.size == 0 and all(abs(v - 7) < 1e-6 for v in st.tiers[0].avg[0]), f'before={n0} written={n1} reloaded={len(st.tiers[0])} tail={size % REC.size}') + +# ---- 3. link: no orphan after close, exec timeout returns at once ---------------------------- +if plat.NAME == 'Linux': + cfg = ServerConfig('t1', 't', transport=0, interval=30) + frames = [] + link = session.Link(cfg, frames.append, lambda why: frames.append(('lost', why))) + link.start() + pump(8, lambda: frames) + p = next(iter(link.procs)) + kids = subprocess.run(['pgrep', '-P', str(p.pid)], capture_output=True, text=True).stdout.split() + link.close() + time.sleep(0.5) + alive = [k for k in kids if os.path.exists(f'/proc/{k}') and 'sleep' in open(f'/proc/{k}/comm').read()] + check('closing a link leaves no orphaned sleep', frames and kids and not alive, f'frames={len(frames)} children={kids} alive={alive}') + for k in alive: os.kill(int(k), 15) + + link = session.Link(cfg, None, None) + got, t0 = [], time.time() + link.exec('sleep 6\n', 1, lambda code, out: got.append((code, out, time.time() - t0))) + pump(9, lambda: got) + check('command time-out reports at once (child still holds the pipe)', got and got[0][2] < 3 and got[0][0] == -1, f'{got}') + link.close() + + # a command that is running when the link closes: callback gets -1 and nothing is left behind + link = session.Link(cfg, None, None) + got = [] + link.exec('sleep 20\n', 60, lambda code, out: got.append((code, out))) + pump(0.5) + p = next(iter(link.procs)); kids = subprocess.run(['pgrep', '-P', str(p.pid)], capture_output=True, text=True).stdout.split() + link.close('connection lost: test') + pump(1) + alive = [k for k in kids if os.path.exists(f'/proc/{k}')] + check('pending command fails when the link closes, once', got == [(-1, 'connection lost: test')], f'{got}') + check('its child process is gone', kids and not alive, f'children={kids} alive={alive}') + for k in alive: os.kill(int(k), 15) + +# ---- 4. session logic with fed metrics (no processes) --------------------------------------- +session.Link.start = lambda self: None +mgr = session.Manager() +cfg = ServerConfig('s1', 'srv', transport=0) +cfg.autopilot.dryRun = True +s = mgr.attach(cfg) +events = [] +s.alert.append(events.append) +s.status = session.ONLINE +def feed(services, procs=()): + m = Metrics(time.time() * 1000); m.valid = True; m.uptime = 1000; m.cpu_count = 2; m.mem_total = 8e9 + m.services, m.procs = list(services), list(procs) + m.services_failed = sum(x.active == 'failed' for x in m.services) + s.m = m; s.track(m.timestamp); s.evaluate_rules() +svc = lambda name, active: Service(name, 'loaded', active, 'failed' if active == 'failed' else 'running', name) +feed([svc('a.service', 'failed'), svc('b.service', 'active')]) +feed([svc('a.service', 'failed'), svc('b.service', 'failed')]) +s.analyze() +f = {x.key: x for x in s.an.findings} +check('service failed before monitoring is never auto-restarted', 'svc:a.service' in f and not f['svc:a.service'].auto) +check('service that failed later is auto-eligible', 'svc:b.service' in f and f['svc:b.service'].auto) +dry = [e.message for e in events if e.severity == 'action'] +check('dry run only reports', len(dry) == 1 and 'dry run' in dry[0] and 'b.service' in dry[0], f'{dry}') +n = len(events); s.analyze() +check('restart cooldown (2 min) holds', len([e for e in events[n:] if e.severity == 'action']) == 0) +ran = []; s.run_finding = lambda f, automatic, done=None: ran.append(f.key) # never runs anything +s.cfg.autopilot.dryRun = False +s.analyze(); s.analyze() +check('real mode: one restart, then the 2 min cooldown', ran == ['svc:b.service'], str(ran)) +s.cooldown['svc:b.service'] -= 121000; s.analyze() +check('after the cooldown it acts again', ran == ['svc:b.service'] * 2, str(ran)) +s.cfg.autopilot.dryRun = True; n = len(events); s.analyze(); s.analyze() +check('dry run says it once per finding', len([e for e in events[n:] if e.severity == 'action']) == 1) +s.status = session.OFFLINE; s.analyze(); s.status = session.ONLINE +s.m.valid = False; n = len(ran) + len(events); s.cfg.autopilot.dryRun = False; s.analyze(); s.cfg.autopilot.dryRun = True; s.m.valid = True +check('no autopilot action without valid data', len(ran) + len([e for e in events if e.severity == 'action']) <= n, str(ran)) +feed([svc('b.service', 'active')]) # a.service is gone from the list (reset-failed / removed) +s.analyze() +check('a service that disappeared is no longer reported as failed', not any(x.key == 'svc:a.service' for x in s.an.findings), f'{[x.key for x in s.an.findings]}') +# action results are one line in alerts.log +s.exec = lambda cmd, priv, done=None, timeout=60: done(1, 'line one\nline two\n\nline three\n') +s.run('command', 'echo x', 'Test action') +log = open(mgr.path('alerts.log'), encoding='utf-8').read().splitlines() +check('alerts.log has one line per event', all(len(l.split('\t')) == 4 for l in log) and 'line three' in log[-1], f'last={log[-1]!r} lines={len(log)}') +# offline samples weigh like online ones +s.status = session.OFFLINE +n0 = len(s.store.tiers[0]) +t0 = time.time() +while time.time() - t0 < 2 * cfg.interval + 1.5: session.loop.pump(); time.sleep(0.05) +got = len(s.store.tiers[0]) - n0 +check('downtime is sampled once per interval', got >= 2, f'{got} offline samples in {time.time() - t0:.1f} s at interval {cfg.interval} s') +mgr.close() +# corrupt servers.json must not stop the app from starting +open(mgr.path('servers.json'), 'w').write('{"version":1,"servers":[{"id":') +try: + m2 = session.Manager(); m2.load(); ok = True; m2.close() +except Exception as e: ok = repr(e) +check('damaged servers.json does not crash the start', ok is True, str(ok)) +print(f'{sum(res)}/{len(res)} passed') diff --git a/dev/tests/python/t_spec.py b/dev/tests/python/t_spec.py new file mode 100644 index 0000000000000000000000000000000000000000..abea9ed6c1e005685d842362f6eb3d967f282db2 --- /dev/null +++ b/dev/tests/python/t_spec.py @@ -0,0 +1,32 @@ +"""Windows command tables against SPEC section 3 / 6 (character for character) + ASCII check.""" +import re, sys +sys.dont_write_bytecode = True +sys.path.insert(0, sys.argv[1]) +import plat, model +spec = open(sys.argv[2], encoding='utf-8').read() +ticks = spec.replace('\\|', '|') +ok = True +def has(name, s): + global ok + good = ('`' + s + '`') in ticks or s in ticks and len(s) > 40 + ok &= good + print(('ok ' if good else 'DIFF ') + name + ('' if good else f'\n {s}')) +for k, v in plat.CMD.items(): has('CMD ' + k, v) +has('cleanup', plat.CLEANUP) +for k, v in plat.POWER.items(): has('power ' + k, v) +for label, cmd, flags in plat.PROC_ACTIONS: has('proc ' + label, cmd) +for k, v in plat.PRIORITIES.items(): has('priority ' + k, plat.PRIORITY_CMD.replace('{v}', str(v)).replace('{v}', '') if False else plat.PRIORITY_CMD.replace('{v}', '')) +for k, v in plat.SERVICE_VERBS.items(): has('service ' + k, v) +has('service logs', plat.SERVICE_LOGS) +for label, cmd in plat.QUICK: has('quick ' + label, cmd) +for label, cmd in plat.ACTIONS: has('action ' + label, cmd) +has('PS_ARGS', ' '.join(plat.PS_ARGS).split(' -EncodedCommand ')[1]) +print('labels quick:', [l for l, _ in plat.QUICK]); print('labels actions:', [l for l, _ in plat.ACTIONS]) +print('rule actions:', [a[0] for a in model.RULE_ACTIONS]); print('rule metrics:', [m[0] for m in model.RULE_METRICS]) +w = plat.wrap('CMD', True, True) +print('wrap ok:', w.replace('CMD', '').strip() in spec) +texts = [plat.COLLECTOR, plat.CLEANUP, plat.SERVICE_LOGS, plat.PRIORITY_CMD, w, plat.collector(3)] + list(plat.CMD.values()) + list(plat.POWER.values()) + [c for _, c in plat.QUICK + plat.ACTIONS] + [c for _, c, _ in plat.PROC_ACTIONS] + list(plat.SERVICE_VERBS.values()) +print('all scripts ASCII:', all(t.isascii() for t in texts)) +print('collector stdin starts:', repr(plat.collector(3)[:34])) +print('filled:', model.command(plat.SERVICE_LOGS, "MSSQL$SQL'X", 300)[:120]); print('filled:', model.command(plat.CMD['restart_service'], "it's")); print('filled:', model.command(plat.CMD['kill_pid'], '1234; rm x')) +print('ALL MATCH' if ok else 'MISMATCHES') diff --git a/dev/tests/python/ui2.py b/dev/tests/python/ui2.py new file mode 100644 index 0000000000000000000000000000000000000000..baf21e2c2110e53a5c1a6cbb65c57b3697e72a8e --- /dev/null +++ b/dev/tests/python/ui2.py @@ -0,0 +1,142 @@ +"""Lifecycle + leak test of one edition: ui2.py [WxH]. Scratch config, dry run; kills only its own collector child.""" +import gc, os, signal, subprocess, sys, threading, time, traceback +sys.dont_write_bytecode = True +proj, shots, long_secs = sys.argv[1], sys.argv[2], float(sys.argv[3]) +size = sys.argv[4] if len(sys.argv) > 4 else '1500x940' +sys.path.insert(0, proj) +import tkinter as tk +import plat, session +from model import AutopilotConfig, ServerConfig, new_id +from session import Manager, OFFLINE, ONLINE, CONNECTING, loop +from ui import MainWindow +from widgets import Dialog, Paint +import tabs as tabsmod + +os.makedirs(shots, exist_ok=True) +errors, checks = [], [] +root, mgr = tk.Tk(), Manager() +def report(*exc): errors.append(''.join(traceback.format_exception(*exc))); traceback.print_exception(*exc) +root.report_callback_exception = report +win = MainWindow(root, mgr) +root.geometry(size + '+0+0') +mgr.load() +tabs = win.detail.tabs +tab = dict(zip((t for t, _ in tabsmod.TABS), tabs.pages)) +def wait(sec, until=lambda: False): + end = time.time() + sec + while time.time() < end and not until(): root.update(); time.sleep(0.01) +def shot(name): + wait(0.4) + xwd = subprocess.run(['xwd', '-root', '-silent'], capture_output=True).stdout + subprocess.run(['ffmpeg', '-loglevel', 'error', '-y', '-f', 'xwd_pipe', '-i', '-', '-pix_fmt', 'rgb24', os.path.join(shots, name + '.png')], input=xwd) +def check(name, ok, info=''): + checks.append(bool(ok)); print(('PASS ' if ok else 'FAIL ') + name + (f' [{info}]' if info else ''), flush=True) +def all_widgets(w=None): + w = w or root; yield w + for c in w.winfo_children(): yield from all_widgets(c) +def kids(): # live child processes of this test + out = subprocess.run(['ps', '-o', 'pid=,stat=,comm=', '--ppid', str(os.getpid())], capture_output=True, text=True).stdout.split('\n') + return [l.split() for l in out if l.strip() and 'Z' not in l.split()[1] and l.split()[2] not in ('ps', 'xwd', 'ffmpeg')] +def modal(action, pick, delay=1200): + def go(): + ds = [w for w in all_widgets() if isinstance(w, Dialog)] + if not ds: errors.append('dialog did not open'); return + [b for b in ds[-1].winfo_children()[-1].winfo_children() if pick in b['text']][0].invoke() + root.after(delay, go); return action() +def stats(): + gc.collect() + rss = int(next(l for l in open('/proc/self/status') if l.startswith('VmRSS')).split()[1]) / 1024 + items = sum(len(w.find_all()) for w in all_widgets() if isinstance(w, tk.Canvas)) + return dict(rss=round(rss, 1), threads=threading.active_count(), items=items, widgets=sum(1 for _ in all_widgets()), after=len(root.tk.call('after', 'info')), + timers=len(loop.timers), fds=len(os.listdir('/proc/self/fd')), kids=len(kids()), queue=loop.calls.qsize()) + +local = mgr.sessions[0] +print('edition', plat.NAME, 'config', mgr.config_dir(), 'size', size, flush=True) +wait(12, lambda: local.online()) +check('local online', local.online(), f'{local.m.hostname} cpu={local.m.cpu_usage:.0f}%') +tag = size.split('x')[0] +shot(f'{tag}-00-dashboard'); win.open(local.cfg.id); wait(1) +for i, title in enumerate(tab): + tabs.show(i); wait(1.0); shot(f'{tag}-{i + 1:02d}-{title.split()[0].lower()}') +win.show_events(); shot(f'{tag}-12-events'); win.show_dashboard() + +# ---- collector dies mid-run -> offline, back-off 3 s, online again; an action in flight fails once ------------------------ +win.open(local.cfg.id); tabs.show(list(tab).index('Console')); con = tab['Console'] +n_alerts = len(mgr.alerts); threads0 = threading.active_count() +got = [] +local.exec('sleep 25', False, lambda code, out: got.append((code, out))) +wait(0.5) +p = next(x for x in local.link.procs if x not in local.link.pending) +t0 = time.time(); os.kill(p.pid, signal.SIGKILL) # our own collector child +wait(4, lambda: local.status == OFFLINE) +t_off = time.time() - t0 +check('killed collector -> offline', local.status == OFFLINE and not local.online(), f'after {t_off:.1f} s: {local.err}') +check('pending command failed with the link', got and (got[0][0] == -1 and 'connection lost' in got[0][1] or plat.NAME != 'Linux'), str(got)[:120]) +wait(1); check('command child is gone after the link dropped', not [k for k in kids() if k[2] == 'sleep'], str(kids())) +shot(f'{tag}-30-offline') +wait(12, lambda: local.online()) +check('reconnected after the back-off', local.online() and local.retries == 0, f'online again {time.time() - t0:.1f} s after the kill') +msgs = [e.message for e in mgr.alerts[:len(mgr.alerts) - n_alerts]] +check('events: unreachable + back online', any('unreachable' in m for m in msgs) and any('back online' in m for m in msgs), ' | '.join(m[:50] for m in msgs)) +wait(1.5); check('reader threads ended', threading.active_count() <= threads0 + 1, f'{threads0} -> {threading.active_count()}') + +# several quick reconnects in a row: no pile-up of children or threads +for _ in range(5): local.reconnect(); wait(0.3) +wait(10, lambda: local.online()); wait(1.5) +k = kids() +check('5 quick reconnects: one collector left, threads back', local.online() and len(k) == 1 and threading.active_count() <= threads0 + 1, f'children={k} threads={threading.active_count()}') + +# ---- remove a server while its page is open, a command runs and its log dialog is open --------------------------- +extra = mgr.add(ServerConfig(new_id(), 'Temp local', 'Test', transport=0, autopilot=AutopilotConfig(dryRun=True))) +win.open(extra.cfg.id); wait(10, lambda: extra.online()) +check('second local server online', extra.online()) +tabs.show(list(tab).index('Services')); st = tab['Services']; wait(1.5) +if st.tbl.rows: + st.tbl.selected = st.tbl.ident(st.tbl.rows[0]); st.logs(); wait(2) +tabs.show(list(tab).index('Console')); con.cmd.put('sleep 25'); con.enter(); wait(0.8) +pt = tab['Processes']; pt.freeze.var.set(True) +before = len(kids()) +modal(lambda: win.remove(extra.cfg.id), 'keep history') +wait(1.5) +out = con.out.get('1.0', 'end') +check('server removed while its page was open', mgr.session(extra.cfg.id) is None and win.page is win.dash and win.detail.s is None) +check('its running command was ended', not [k for k in kids() if k[2] == 'sleep'] and len(kids()) == 1, f'{before} -> {kids()}') +dl = [w for w in all_widgets() if isinstance(w, Dialog)] +if dl: + [b for b in dl[0].winfo_children()[-1].winfo_children() if isinstance(b, tk.Button) and b['text'] == 'Reload'][0].invoke(); wait(0.8) + txt = [w for w in all_widgets(dl[0]) if isinstance(w, tk.Text)][0].get('1.0', 'end').strip() + check('log dialog of the removed server: reload is harmless', 'not connected' in txt, txt[:60]); dl[0].close() +wait(3) +check('removed session gets no more samples or timers', extra.link is None and not any(t in loop.timers for t in extra.timers)) +win.open(local.cfg.id) +check('freeze switched off for another server', not pt.freeze.var.get()) +check('no callback errors so far', not errors, f'{len(errors)}') + +# ---- long run: memory, threads, canvas items, timers --------------------------------------------------------------- +samples, t_start, i = [], time.time(), 0 +while time.time() - t_start < long_secs: + tabs.show(i % len(tabs.pages)); i += 1 + if i % 13 == 0: win.show_dashboard(); wait(2); win.show_events(); wait(1); win.open(local.cfg.id) + if i % 7 == 0: local.analyze() + if i % 9 == 0: con.cmd.put('echo tick'); con.enter() + wait(3) + if i % 5 == 0: samples.append(stats()); print(' ', round(time.time() - t_start), samples[-1], flush=True) +if len(samples) >= 4: + a, b = samples[1], samples[-1] + check(f'long run {long_secs:.0f} s: threads, timers, children, fds steady', + b['threads'] <= a['threads'] and b['timers'] == a['timers'] and b['kids'] == a['kids'] and b['fds'] <= a['fds'] + 2 and b['after'] <= a['after'] + 2, f'{a} -> {b}') + check('long run: canvas items and widgets do not pile up', b['items'] < a['items'] * 1.5 + 200 and b['widgets'] < a['widgets'] + 80, f"items {a['items']} -> {b['items']}, widgets {a['widgets']} -> {b['widgets']}") + check('long run: memory steady', b['rss'] - a['rss'] < 12, f"{a['rss']} -> {b['rss']} MB") +check('still online, history grows', local.online() and len(local.store.tiers[0]) > 5, f'{len(local.live.t)} live samples, raw {len(local.store.tiers[0])}') + +# ---- quit while a command is running and a test connection is open ------------------------------------------------------- +tabs.show(list(tab).index('Console')); con.cmd.put('sleep 25'); con.enter(); wait(0.8) +root.after(600, lambda: [w for w in all_widgets() if isinstance(w, Dialog)][-1].run_test()) +root.after(2200, win.quit) +t0 = time.time(); win.add() +root.mainloop() if root.children else None +check('quit with a command running and a dialog open returns at once', time.time() - t0 < 5, f'{time.time() - t0:.1f} s') +time.sleep(0.6) +check('no child process after quit', not kids(), str(kids())) +check('no callback errors', not errors, f'{len(errors)}: ' + ' / '.join(e.strip().splitlines()[-1] for e in errors)) +print(f'RESULT {sum(checks)}/{len(checks)} passed', flush=True) diff --git a/dev/tests/python/uitest.py b/dev/tests/python/uitest.py new file mode 100644 index 0000000000000000000000000000000000000000..5f80c5fc99b42b54f2a0e51b00829ad7d477ebb7 --- /dev/null +++ b/dev/tests/python/uitest.py @@ -0,0 +1,212 @@ +"""Headless UI drive of one edition: uitest.py [min seconds]. Run under xvfb with a scratch config dir.""" +import json, os, struct, subprocess, sys, time, traceback +sys.dont_write_bytecode = True +proj, shots, min_secs = sys.argv[1], sys.argv[2], float(sys.argv[3]) if len(sys.argv) > 3 else 70 +sys.path.insert(0, proj) +import tkinter as tk +from tkinter import filedialog +import plat +from session import Manager, OFFLINE, ONLINE +from ui import MainWindow, ServerDialog +from widgets import Dialog + +os.makedirs(shots, exist_ok=True) +errors, checks, t_start = [], [], time.time() +root, mgr = tk.Tk(), Manager() +def report(*exc): + errors.append(''.join(traceback.format_exception(*exc))); traceback.print_exception(*exc) +root.report_callback_exception = report +win = MainWindow(root, mgr) +mgr.load() +tabs = win.detail.tabs +tab = dict(zip((t for t, _ in __import__('tabs').TABS), tabs.pages)) + +def wait(sec): + end = time.time() + sec + while time.time() < end: + root.update(); time.sleep(0.01) +def shot(name): + wait(0.3) + xwd = subprocess.run(['xwd', '-root', '-silent'], capture_output=True).stdout + subprocess.run(['ffmpeg', '-loglevel', 'error', '-y', '-f', 'xwd_pipe', '-i', '-', '-pix_fmt', 'rgb24', os.path.join(shots, name + '.png')], input=xwd) +def check(name, ok, info=''): + checks.append((name, bool(ok))); print(('PASS ' if ok else 'FAIL ') + name + (f' [{info}]' if info else ''), flush=True) +def dialogs(): + return [w for w in root.winfo_children() + win.detail.winfo_children() + [c for p in tabs.pages for c in p.winfo_children()] if isinstance(w, Dialog) and w.winfo_exists()] +def modal(action, script, delay=1500): + """Runs a blocking dialog action; script(dialog) is called once it is open and must close it.""" + def go(): + ds = dialogs() + if not ds: errors.append('dialog did not open'); return + try: script(ds[-1]) + except Exception: report(*sys.exc_info()); ds[-1].winfo_exists() and ds[-1].close() + root.after(delay, go) + return action() + +local, dead = mgr.sessions[0], mgr.sessions[1] +print('edition', plat.NAME, 'config', mgr.config_dir(), flush=True) +wait(9) +check('local server online with valid data', local.online(), f'status={local.status} cpu={local.m.cpu_usage:.0f}% procs={len(local.m.procs)} host={local.m.hostname}') +check('first frames parsed: cores, memory, mounts, nets', local.m.cpu_count >= 1 and local.m.mem_total > 0 and local.m.mounts and local.m.nets) +check('unreachable ssh host detected', dead.status == OFFLINE and dead.err, dead.err) +shot('00-dashboard') +win.dash.search.put('unreach'); win.dash.filter(); wait(0.3) +check('dashboard search filters cards', len(win.dash.flow.cards) == 2, f'{len(win.dash.flow.cards) - 1} card(s) + add card') +win.dash.search.put(''); win.dash.filter() + +win.open(local.cfg.id); wait(1) +for i, (title, page) in enumerate(tab.items()): + tabs.show(i); wait(1.2); shot(f'{i + 1:02d}-{title.split()[0].lower()}') +check('every tab opened', tabs.current == len(tabs.pages) - 1) + +# console: a harmless command +con = tab['Console']; tabs.show(list(tab).index('Console')) +con.cmd.put('echo hello-from-test'); con.enter(); wait(3) +out = con.out.get('1.0', 'end') +check('console ran echo', 'hello-from-test' in out and '[exit 0' in out, out.strip().splitlines()[-1]) +con.recall(-1); check('console history recall', con.cmd.text() == 'echo hello-from-test') +con.cmd.put(''); shot('20-console-echo') + +# processes / services lists +pt = tab['Processes']; tabs.show(list(tab).index('Processes')); wait(1) +n_all = len(pt.tbl.rows); pt.filter.put('python' if plat.NAME == 'Linux' else 'sql'); pt.show(); wait(0.3) +check('process list + filter', 0 < len(pt.tbl.rows) < n_all, f'{len(pt.tbl.rows)} of {n_all} rows') +pt.filter.put(''); pt.show() +pt.tbl.selected = pt.tbl.ident(pt.tbl.rows[0]); check('process selection', pt.selected() is not None, str(pt.selected())) +st = tab['Services']; tabs.show(list(tab).index('Services')); wait(1.5) +n_all = len(st.tbl.rows); st.state.current(2); st.show(); wait(0.3) +check('service list + failed filter', n_all > 0 and len(st.tbl.rows) < n_all, f'{len(st.tbl.rows)} failed of {n_all}') +st.state.current(0); st.show() +st.tbl.selected = st.tbl.ident(st.tbl.rows[0]); st.logs(); wait(4) +logs = [d for d in dialogs()] +text = [w for w in logs[0].winfo_children()[0].winfo_children() if isinstance(w, tk.Text)][0].get('1.0', 'end') if logs else '' +check('service logs dialog loaded', logs and len(text.strip()) > 20 and 'Loading' not in text, text.strip().splitlines()[0][:80] if text.strip() else '') +shot('21-service-logs'); [d.close() for d in logs] + +# rule editor: open + cancel, then add a rule with OK, toggle, delete +rt = tab['Alert rules']; tabs.show(list(tab).index('Alert rules')); wait(0.5) +n_rules = len(local.cfg.rules) +modal(lambda: rt.edit(0), lambda d: (shot('22-rule-editor'), d.close())) +check('rule editor opened and cancelled', len(local.cfg.rules) == n_rules) +def ok(d): + [b for b in d.winfo_children()[-1].winfo_children() if b['text'] == 'OK'][0].invoke() +modal(lambda: rt.edit(-1), ok) +check('rule added through the editor', len(local.cfg.rules) == n_rules + 1, local.cfg.rules[-1].condition()) +rt.toggle(n_rules); check('rule toggled off', not local.cfg.rules[n_rules].enabled) +rt.rules.selected = n_rules; rt.store([x for i, x in enumerate(local.cfg.rules) if i != rt.index()]) +check('rule deleted', len(local.cfg.rules) == n_rules) + +# add-server dialog + test connection against the local machine +res = {} +def test_conn(d): + d.via.current(0); d.sync(); shot('23-add-server'); d.run_test() + def done(): + res['text'] = d.outcome['text']; shot('24-test-connection'); d.close() + root.after(9000, done) +modal(win.add, test_conn) +check('add-server dialog: test connection (local)', res.get('text', '').startswith('✓ Connected'), res.get('text', '')) +check('cancelled add-server dialog adds nothing', len(mgr.sessions) == 2) + +# history: ranges + CSV export +ht = tab['History']; tabs.show(list(tab).index('History')); wait(0.5) +ht.pick(3600); wait(0.5); check('history 1 h range', len(ht.pts) > 3, ht.res['text']) +csv = os.path.join(shots, 'export.csv'); filedialog.asksaveasfilename = lambda **kw: csv +ht.export(); lines = open(csv).read().split('\n') +check('history CSV export', lines[0].startswith('time,samples,online_pct,cpu_avg,cpu_max') and len(lines) == len(ht.pts) + 1 and len(lines[1].split(',')) == 33, lines[1][:60]) +os.remove(csv); shot('25-history-1h'); ht.pick(86400) + +# insights: analysis + autopilot form edit keeps dry run +it = tab['Insights & Autopilot']; tabs.show(list(tab).index('Insights & Autopilot')); local.analyze(); wait(0.8) +check('analysis ran', local.an.when > 0, f'health {local.an.health} {local.an.grade}, {len(local.an.findings)} finding(s)') +put = dict((n, p) for n, g, p in it.binds)['anomalyZ']; put(3.5); it.store(); wait(0.3) +saved = json.load(open(mgr.path('servers.json')))['servers'][0] +check('autopilot form saved (still dry run)', saved['autopilot']['anomalyZ'] == 3.5 and saved['autopilot']['dryRun'] is True and local.cfg.autopilot.dryRun) +shot('26-insights') + +# pause / resume, live window, reconnect, reorder, events page +win.detail.pause.invoke(); wait(0.3); check('pause', local.paused); win.detail.pause.invoke(); check('resume', not local.paused) +tabs.show(0); win.detail.span.current(0); win.detail.refresh(False); check('live window 5 min', tab['Overview'].span == 300000) +mgr.move(dead.cfg.id, -1); check('reorder servers', mgr.sessions[0] is dead); mgr.move(dead.cfg.id, 1) +win.show_events(); wait(0.5); n_ev = len(win.events.rows) +win.event_filter.current(1); win.list_events(); wait(0.3) +check('events page + filter', n_ev > 0 and 0 < len(win.events.rows) <= n_ev, f'{len(win.events.rows)} critical of {n_ev}') +shot('27-events'); win.event_filter.current(0); win.show_dashboard() + +# context menus (posting is replaced by a recorder), table sorting, mouse wheel +menus = [] +tk.Menu.tk_popup = lambda self, x, y, entry='': menus.append([self.entrycget(i, 'label') for i in range(self.index('end') + 1) if self.type(i) == 'command']) +wait(0.5); win.dash.cards[0].event_generate('', x=30, y=30); win.list.event_generate('', x=40, y=20); root.update() +win.open(local.cfg.id); tabs.show(list(tab).index('Processes')); wait(1) +pt.tbl.cv.event_generate('', x=60, y=80); root.update() +[w for w in win.detail.winfo_children()[0].winfo_children()[0].winfo_children() if isinstance(w, tk.Button) and 'Power' in w['text']][0].event_generate('', x=5, y=5); root.update() +check('context menus: card, sidebar, process, power', len(menus) == 4 and 'Move up' in menus[1] and 'Change priority…' in menus[2] and 'Reboot…' in menus[3], ' | '.join(str(len(m)) for m in menus)) +pt.tbl.cv.event_generate('', x=140, y=10); root.update(); names = [r[1].text.lower() for r in pt.tbl.rows] +check('table sorts by a clicked header', pt.tbl.sort == (1, False) and names == sorted(names)) +pt.tbl.sort = (4, True); before = pt.tbl.top; pt.tbl.cv.event_generate('', x=140, y=100); pt.tbl.cv.event_generate('', x=140, y=100, delta=-120); root.update() +check('mouse wheel scrolls the table', pt.tbl.top > before or len(pt.tbl.rows) <= pt.tbl.visible(), f'top {before} -> {pt.tbl.top}') + +# a rule with a harmless command action +import copy +from model import AutopilotConfig, Rule, ServerConfig, new_id, xor_b64 +from session import DISABLED +rules = copy.deepcopy(local.cfg.rules) + [Rule(new_id(), 'procs', '>', 'command', 'echo rule-fired-ok', 'info', True, 0.0, 0, 10)] +tabs.show(list(tab).index('Alert rules')); rt.store(rules); wait(7) +log = open(mgr.path('alerts.log')).read() +check('rule action ran a command', 'Process count > 0 (now' in log and 'Automation "Process count > 0": Run a command: echo rule-fired-ok -> OK' in log and 'rule-fired-ok' in log.split('-> OK')[1][:400]) +check('rule shows as active problem', 'Process count > 0' in local.active_alerts()) +rt.store(rules[:-1]) + +# autopilot in dry run: a simulated 11-minute CPU streak of an unprotected process must only be reported +busy = next(p for p in local.m.procs if not plat.protected(p)) +assert local.cfg.autopilot.dryRun and local.cfg.autopilot.enabled +local.procs[busy.pid].high_since = time.time() * 1000 - 11 * 60000 +tabs.show(list(tab).index('Insights & Autopilot')); local.analyze(); wait(0.8) +found = [f for f in local.an.findings if f.key == f'runaway:{busy.pid}']; log = open(mgr.path('alerts.log')).read() +check('autopilot dry run reports instead of acting', found and found[0].auto and found[0].action == 'renice' and + 'Autopilot (dry run) would: ' + plat.TEXT['renice'] + ' - Runaway process: ' + busy.name in log and 'Autopilot: ' not in log, found[0].title if found else '') +check('protected processes are excluded', plat.protected(next(p for p in local.m.procs if p.pid <= 4 or p.name in ('systemd', 'sshd')))) +shot('29-insights-dry-run') + +# add (edit dialog), disable, remove with its history +extra = mgr.add(ServerConfig(new_id(), 'Temp box', 'Test', '127.0.0.1', 'nobody', port=1, autopilot=AutopilotConfig(dryRun=True))); wait(13) +hdir = extra.store.dir +check('added server: offline, downtime recorded', extra.status == OFFLINE and os.path.getsize(os.path.join(hdir, 'raw.bin')) >= 144, extra.err) +def rename(d): d.name.put('Renamed box'); d.interval.put(5); d.save() +modal(lambda: win.edit(extra.cfg.id), rename) +check('edit dialog saved', extra.cfg.name == 'Renamed box' and extra.cfg.interval == 5 and 'Renamed box' in open(mgr.path('servers.json')).read()) +c = copy.deepcopy(extra.cfg); c.enabled = False; mgr.update(c); wait(0.3); check('server disabled', extra.status == DISABLED) +modal(lambda: win.remove(extra.cfg.id), lambda d: [b for b in d.winfo_children()[-1].winfo_children() if 'delete' in b['text']][0].invoke()) +check('server removed with its history', len(mgr.sessions) == 2 and not os.path.exists(hdir)) + +# formats +c = ServerConfig(new_id(), 'x', password='p@ss wörd', notes='n'); j = json.loads(json.dumps(c.to_json())) +check('servers.json round trip + password disguise', ServerConfig.from_json(j) == c and j['password'] != c.password and xor_b64('abc', True) == 'MgcR' and j['transport'] == 1) +import shutil; from history import Store, CPU, DISK, stats +for label, cpp, tier, want in (('C++ app', '~/.local/share/sm-dev/tmp/cfgc/ServerMonitor/ServerMonitor/history/local1', 0, None), + ('C++ analyzer test (4 tiers)', '~/.local/share/sm-dev/tmp/python/hist_cpp', 1, [4320, 72, 3])): + cpp, tmp = os.path.expanduser(cpp), os.path.join(shots, 'cpp-hist') + if os.path.isdir(cpp): + shutil.rmtree(tmp, ignore_errors=True); shutil.copytree(cpp, tmp); cs = Store(tmp); n = [len(t) for t in cs.tiers] + on_disk = (os.path.getsize(os.path.join(cpp, 'raw.bin')) - 8) // 136 + check(f'history written by the {label} loads', n[tier] > 0 and 0 <= stats(cs.tiers[tier], CPU).avg <= 100 and (want is None and n[0] == on_disk or n[1:] == want), + f'tiers {n}, cpu avg {stats(cs.tiers[tier], CPU).avg:.1f}%, disk avg {stats(cs.tiers[tier], DISK).avg:.1f}%') + shutil.rmtree(tmp) +win.show_dashboard() + +wait(max(0, min_secs - (time.time() - t_start))) +shot('28-dashboard-end') +check(f'ran {time.time() - t_start:.0f} s, still online', local.online() and len(local.live.t) > 10, f'{len(local.live.t)} live samples') +hist = os.path.join(mgr.config_dir(), 'history', local.cfg.id) +sizes = {n: os.path.getsize(os.path.join(hist, n)) for n in sorted(os.listdir(hist))} +head = open(os.path.join(hist, 'raw.bin'), 'rb').read(8) +check('history files: SMH1 header + 136-byte records', head == b'SMH1' + bytes([15, 0]) + struct.pack(' 8 + 136 * 10 and sizes.get('minute.bin', 0) >= 8 + 136, str(sizes)) +dh = os.path.join(mgr.config_dir(), 'history', dead.cfg.id) +check('downtime recorded for the offline host', os.path.getsize(os.path.join(dh, 'raw.bin')) >= 8 + 136 * 3 and len(dead.store.tiers[0]) and sum(dead.store.tiers[0].up) == 0) +log = open(mgr.path('alerts.log')).read() +check('alerts.log has the unreachable event', 'Server is unreachable' in log and len(log.split('\n')[0].split('\t')) == 4) +check('servers.json keeps schema and mode 600', set(saved) >= {'id', 'name', 'transport', 'password', 'rules', 'autopilot', 'keyFile', 'useSudo'} and oct(os.stat(mgr.path('servers.json')).st_mode)[-3:] == '600') +check('no real autopilot action (dry run)', 'Autopilot:' not in log and 'Manual fix' not in log) +win.quit() +check('no exceptions in callbacks', not errors, f'{len(errors)} error(s)') +print(f'RESULT {sum(ok for _, ok in checks)}/{len(checks)} passed, {len(errors)} callback errors') diff --git a/dev/tests/web/analysis_test.js b/dev/tests/web/analysis_test.js new file mode 100644 index 0000000000000000000000000000000000000000..d71eb381e9a985f5255e6bed1cc148fc5fc90f9b --- /dev/null +++ b/dev/tests/web/analysis_test.js @@ -0,0 +1,33 @@ +// JS port of ref/analysis_test.cpp: synthetic 3-day history -> store reload + analyzer. +const path = require('path'), fs = require('fs'); +const root = process.argv[2], dir = process.argv[3]; +const { HistoryStore, analyze, stats, TIERS, I, nowSec } = require(path.join(root, 'core/history.js')), { H } = require(path.join(root, 'public/shared.js')); +const { blank } = require(path.join(root, 'core/metrics.js')); +const model = require(path.join(root, 'core/model.js')); +fs.rmSync(dir, { recursive: true, force: true }); +const now = nowSec(), start = now - 3 * 86400; +let st = new HistoryStore(dir); +for (let t = start; t <= now; t += 30) { + const v = new Array(H.length).fill(0), days = (t - start) / 86400, hr = Math.floor(t / 3600) % 24; + v[I.cpu] = 20 + 10 * (hr > 8 && hr < 18); + v[I.disk] = 70 + 5 * days; + v[I.mem] = now - t < 6 * 3600 ? 50 + 2.0 * (6 - (now - t) / 3600.0) : 50; + v[I.load] = 1, v[I.rx] = 1e6, v[I.tx] = 5e5; + st.add(t, v, !(t > now - 86400 && t < now - 86400 + 1800)); +} +st = new HistoryStore(dir); +console.log(`reloaded raw=${st.t[0].length} minute=${st.t[1].length} hour=${st.t[2].length} day=${st.t[3].length} bytes=${st.diskBytes()}`); +const used = st.tierFor(now - 7 * 86400, now), r = st.range(now - 7 * 86400, now); +console.log(`range 7d -> ${TIERS[used]}, ${r.length} pts`); +const m = Object.assign(blank(0), { valid: true, cpuCount: 4, memPct: 62, maxDiskPct: 85, fullestMount: '/' }); +const ap = { ...model.make({}, '').autopilot, diskCleanup: true, diskForecastDays: 5 }; +const trend = o => ({ pid: 0, minutesTracked: 0, name: '', user: '', cpuNow: 0, highCpuMinutes: 0, rssNow: 0, rssGrowth: 0, rssGrowthPct: 0, rssMonotonic: 0, kernel: false, ...o }); +const p = trend({ pid: 4242, name: 'leaky', minutesTracked: 45, rssNow: 900e6, rssGrowth: 400e6, rssGrowthPct: 80, rssMonotonic: 0.95 }); +const q = trend({ pid: 777, name: 'spinner', cpuNow: 99, highCpuMinutes: 12 }); +const svc = (unit, failedNow, preexisting, failsLastHour, autoRestartsLastHour) => ({ unit, failedNow, preexisting, failsLastHour, autoRestartsLastHour }); +const a = analyze(st, m, ap, [p, q], [svc('web.service', true, false, 1, 0), svc('old.service', true, true, 0, 0)], true); +const f = (v, n = 2) => v.toFixed(n); +console.log(`health=${a.health} grade=${a.grade} diskFullDays=${f(a.diskFullDays)} slope/day=${f(a.diskSlopePerDay)} memSlope/h=${f(a.memSlopePerHour)} r2=${f(a.memTrendR2)} up24=${f(a.up[0])} up7=${f(a.up[1])}`); +for (const x of a.findings) console.log(` [${x.severity}] ${x.title} | auto=${+x.autoEligible} action=${x.action} ${x.actionArg}`); +const s = stats(r, I.disk); +console.log(`disk stats min=${f(s.min, 1)} avg=${f(s.avg, 1)} p95=${f(s.p95, 1)} max=${f(s.max, 1)} n=${s.count}; capacity: ${a.capacity.join(' | ')}`); diff --git a/dev/tests/web/apitest2.js b/dev/tests/web/apitest2.js new file mode 100644 index 0000000000000000000000000000000000000000..5bbf2b7ff03fce1d4bbfe113c9ef27a621db1b16 --- /dev/null +++ b/dev/tests/web/apitest2.js @@ -0,0 +1,194 @@ +// API test: node apitest.js . Never runs a real kill / restart / cleanup / reboot on Linux. +const http = require('http'), fs = require('fs'), path = require('path'); +const [port, cfgRoot, os] = process.argv.slice(2), dir = path.join(cfgRoot, 'ServerMonitorWeb'), t0 = Date.now(), win = os === 'Windows'; +let failed = 0; +const check = (name, ok, info = '') => { console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${info ? ' — ' + info : ''}`); if (!ok) ++failed; }; +const sleep = ms => new Promise(r => setTimeout(r, ms)); +function req(method, p, body, headers = {}) { // raw request so that any header (Host, Origin) can be forged + return new Promise((resolve, reject) => { + const data = body === undefined ? null : typeof body === 'string' ? body : JSON.stringify(body); + const r = http.request({ host: '127.0.0.1', port, method, path: p, headers: { ...(data != null && { 'Content-Type': 'application/json', 'X-SM': '1' }), ...headers } }, res => { + let s = ''; res.setEncoding('utf8').on('data', d => s += d).on('end', () => { let json; try { json = JSON.parse(s); } catch {} resolve({ status: res.statusCode, headers: res.headers, text: s, json }); }); + }); + r.on('error', reject); r.end(data); + }); +} +const post = async (p, body) => { const r = await req('POST', '/api/' + p, body); if (r.status !== 200) throw new Error(`${p}: ${r.status} ${r.text}`); return r.json; }; +const state = async () => (await req('GET', '/api/state')).json; +function sse(p, ms) { // collect events for a while + return new Promise(resolve => { + const events = [], r = http.get({ host: '127.0.0.1', port, path: p }, res => { + let buf = ''; res.setEncoding('utf8').on('data', d => { buf += d; for (let i; (i = buf.indexOf('\n\n')) >= 0; buf = buf.slice(i + 2)) { const [e, data] = buf.slice(0, i).split('\n'); events.push([e.slice(7), JSON.parse(data.slice(6))]); } }); + setTimeout(() => { r.destroy(); resolve({ events, type: res.headers['content-type'], headers: res.headers }); }, ms); + }); + }); +} +(async () => { + // --- state + security --- + let s = await state(); + check('GET /api/state', s.plat.name === os && s.servers.length === 2, `${s.plat.name}, ${s.servers.map(x => x.cfg.name + '=' + x.status).join(', ')}`); + const local = s.servers[0].cfg.id, dead = s.servers[1].cfg.id; + check('no password field is sent, only hasPassword', s.servers.every(x => !('password' in x.cfg) && 'hasPassword' in x.cfg)); + const page = await req('GET', '/'); + check('GET / serves the page with security headers', page.status === 200 && /app\.js/.test(page.text) && page.headers['content-security-policy'].includes("default-src 'self'") && page.headers['x-content-type-options'] === 'nosniff'); + for (const f of ['/app.js', '/shared.js', '/style.css', '/icon.svg']) { const r = await req('GET', f); check('GET ' + f, r.status === 200 && r.text.length > 300, r.headers['content-type']); } + check('GET /../server.js is not served', (await req('GET', '/../server.js')).status === 404 && (await req('GET', '/%2e%2e/server.js')).status === 404); + let r = await req('GET', '/api/state', undefined, { Host: 'evil.example:' + port }); + check('wrong Host header is rejected (DNS rebinding)', r.status === 403, `${r.status} ${r.text}`); + r = await req('GET', '/api/state', undefined, { Host: '127.0.0.1:1' }); + check('right host with wrong port is rejected', r.status === 403); + r = await req('GET', '/api/state', undefined, { Host: 'localhost:' + port }); + check('Host localhost: is accepted', r.status === 200); + r = await req('POST', '/api/alerts/clear', '{}', { 'X-SM': '' }); + check('POST without the X-SM header is rejected', r.status === 403, `${r.status} ${r.text}`); + r = await req('POST', '/api/alerts/clear', '{}', { 'Content-Type': 'text/plain' }); + check('POST with a non-JSON content type is rejected', r.status === 403); + r = await req('POST', '/api/exec', { id: local, cmd: 'echo should-not-run' }, { Origin: 'http://evil.example' }); + check('POST from a foreign Origin is rejected', r.status === 403, `${r.status} ${r.text}`); + r = await req('GET', '/api/alerts/clear'); + check('state-changing route does not answer GET', r.status === 404); + r = await req('OPTIONS', '/api/exec', undefined, { Origin: 'http://evil.example', 'Access-Control-Request-Method': 'POST', 'Access-Control-Request-Headers': 'x-sm,content-type' }); + check('CORS preflight gets no permission', r.status >= 400 && !Object.keys(r.headers).some(h => h.startsWith('access-control')), `status ${r.status}`); + check('no CORS headers on normal replies', !Object.keys(page.headers).some(h => h.startsWith('access-control'))); + r = await req('POST', '/api/exec', '{broken'); + check('invalid JSON body -> 400', r.status === 400, r.text); + r = await req('POST', '/api/exec', { id: 'nope', cmd: 'echo x' }); + check('unknown server -> 404', r.status === 404, r.text); + + // --- live streams --- + const [g, d] = await Promise.all([sse('/api/events', 7000), sse('/api/events?id=' + local, 7000)]); + const count = (x, name) => x.events.filter(e => e[0] === name).length; + check('SSE /api/events: hello + state updates', g.type === 'text/event-stream' && count(g, 'hello') === 1 && count(g, 'state') >= 2, g.events.map(e => e[0]).join(' ')); + check('SSE /api/events?id=: live + samples', count(d, 'live') === 1 && count(d, 'sample') >= 2, d.events.map(e => e[0]).join(' ')); + const m = d.events.findLast(e => e[0] === 'sample')[1].m; + check('sample carries full metrics', m.valid && m.cpuCount >= 1 && m.memTotal > 1e9 && m.procs.length > 3 && m.mounts.length >= 1 && m.nets.length >= 1, + `${m.hostname} | ${m.os} | ${m.cpuCount} cores | cpu ${m.cpuUsage.toFixed(1)}% | mem ${m.memPct.toFixed(1)}% | ${m.procs.length} procs | ${m.services.length} services | load ${m.load1.toFixed(2)} | net rx ${Math.round(m.netRxBps)} B/s`); + if (win) { + const eth = m.nets.find(n => n.name === 'Ethernet'); + check('Windows parser: Hyper-V NIC "Ethernet" is physical and counted in the totals', eth && !eth.virt && m.netRxBps > 0 && m.netRxBps === eth.rxBps, `rx ${Math.round(m.netRxBps)} B/s tx ${Math.round(m.netTxBps)} B/s; virtual: ${m.nets.filter(n => n.virt).map(n => n.name).join(', ')}`); + check('Windows parser: services / tcp / disks / load', m.servicesFailed === 1 && m.servicesRunning === 4 && m.tcp.ESTABLISHED === 42 && m.tcp.LISTEN === 27 && m.socketsUsed === 73 && m.disks.length === 2 && m.mounts[0].mount === 'C:\\' && m.load1 > 0 && m.temps.length === 1, + `failed ${m.servicesFailed}, running ${m.servicesRunning}, tcp ${JSON.stringify(m.tcp)}, fullest ${m.fullestMount} ${m.maxDiskPct.toFixed(1)}%, load ${m.load1.toFixed(2)}/${m.load5.toFixed(2)}/${m.load15.toFixed(2)}, temp ${m.maxTemp}`); + const sql = m.procs.find(p => p.name === 'sqlservr.exe'); + check('Windows parser: processes', m.procs.length === 7 && !m.procs.some(p => p.pid === 0) && sql.user === 'NT AUTHORITY\\SYSTEM' && sql.nice === 8 && sql.age > 86400, `top: ${m.procs[0].name} ${m.procs[0].cpu.toFixed(1)}% (${m.procs[0].user})`); + } + s = await state(); + check('offline host is detected', s.servers[1].status === 'Offline' && !s.servers[1].online && /Unreachable/.test(s.servers[1].alerts[0]), s.servers[1].alerts[0]); + check('an "unreachable" alert was raised', s.alerts.some(a => a.severity === 'critical' && a.serverName === s.servers[1].cfg.name && /unreachable/.test(a.message))); + + // --- console + platform commands --- + r = await post('exec', { id: local, cmd: 'echo hello-$((6*7))' }); + check('console echo', win ? r.code === 0 && /would run/.test(r.out) && /echo hello/.test(r.out) : r.code === 0 && r.out === 'hello-42\n', JSON.stringify(r)); + r = await post('exec', { id: dead, cmd: 'echo x' }); + check('console on an offline server', r.code === -1 && r.out === 'server is not connected', JSON.stringify(r)); + if (!win) { + r = await post('exec', { id: local, cmd: 'echo out; echo err >&2; exit 3' }); + check('console merges stderr and reports the exit code', r.code === 3 && /out/.test(r.out) && /err/.test(r.out), JSON.stringify(r)); + r = await post('run', { id: local, list: 'procActions', i: 0, arg: '4999999' }); // a pid above pid_max: nothing can be hit + check('process action builds the platform command (non-existent pid)', r.cmd === 'kill -TERM 4999999' && r.code !== 0, JSON.stringify(r)); + r = await post('logs', { id: local, unit: "no'such.service", lines: 60 }); + check('service logs (read-only, quoted unit name)', /journal/.test(r.out), JSON.stringify(r.out.slice(0, 120))); + } else { + r = await post('run', { id: local, list: 'procActions', i: 2, arg: '1200' }); + check('process action builds the platform command', r.cmd === 'taskkill /F /T /PID 1200' && r.code === 0 && r.out.includes(r.cmd), JSON.stringify(r)); + r = await post('run', { id: local, list: 'serviceActions', i: 2, arg: "Bro'ken" }); + check('service action quotes the name', r.cmd === "Restart-Service -Name 'Bro''ken' -Force", r.cmd); + r = await post('run', { id: local, list: 'priorities', i: 0, arg: '1200' }); + check('priority action', r.cmd === "(Get-Process -Id 1200).PriorityClass = 'Idle'", r.cmd); + r = await post('logs', { id: local, unit: 'Spooler', lines: 100 }); + check('service logs command', /Select-Object -First 100/.test(r.out), JSON.stringify(r.out.slice(-160))); + r = await post('power', { id: local, reboot: true }); + check('power command (stand-in powershell only echoes)', r.code === 0 && /shutdown \/r \/t 5/.test(r.out), JSON.stringify(r.out)); + await post('server/analyze', { id: local }); + const f = (await sse('/api/events?id=' + local, 1500)).events.find(e => e[0] === 'live')[1].an.findings.find(x => x.action === 'restart_service'); + r = f && await post('finding', { id: local, key: f.key }); + check('manual fix of a finding (echo only)', r && r.code === 0 && /Restart-Service -Name 'BrokenSvc' -Force/.test(r.out), f && f.title); + } + r = await req('POST', '/api/run', { id: local, list: 'ui', i: 0, arg: '1' }); + check('unknown command list -> 400', r.status === 400, r.text); + r = await req('POST', '/api/finding', { id: local, key: 'nope' }); + check('unknown finding -> 404', r.status === 404, r.text); + + // --- servers: test connection, add, edit, reorder, password handling, remove --- + r = await post('server/test', { name: 't', transport: 0 }); + check('test connection (local, two frames)', r.ok && /Connected in \d+ ms/.test(r.text), r.text); + r = await post('server/test', { name: 't', transport: 1, host: '127.0.0.1', port: 1, user: 'nobody' }); + check('test connection (unreachable)', !r.ok && r.text.startsWith('✗'), r.text); + r = await req('POST', '/api/server/add', { name: '', transport: 1, host: '' }); + check('add without name/address -> 400', r.status === 400, r.text); + r = await req('POST', '/api/server/add', { name: 'x', transport: 1, host: '-oProxyCommand=id' }); + check('add with an option-like host -> 400', r.status === 400, r.text); + const added = (await post('server/add', { name: ' second local ', group: 'Test', transport: 0, interval: 1, autopilot: { dryRun: true } })).id; + const ssh = (await post('server/add', { name: 'with password', group: 'Test', transport: 1, host: '127.0.0.1', port: 1, user: 'nobody', password: 'p@ss "w" ö', enabled: false, autopilot: { dryRun: true } })).id; + s = await state(); + const a = s.servers.find(x => x.cfg.id === added), b = s.servers.find(x => x.cfg.id === ssh); + check('add server', a && a.cfg.name === 'second local' && a.cfg.interval === 1 && a.cfg.rules.length === 7 && a.cfg.autopilot.dryRun && a.cfg.autopilot.maxRestartsPerHour === 3, `${s.servers.length} servers`); + check('added disabled SSH server: Disabled, hasPassword', b && b.status === 'Disabled' && b.cfg.hasPassword === true && !('password' in b.cfg)); + const stored = () => JSON.parse(fs.readFileSync(path.join(dir, 'servers.json'), 'utf8')); + const unxor = p => Buffer.from(p, 'base64').map((c, i) => c ^ Buffer.from('ServerMonitor/obfuscation/v1')[i % 28]).toString(); + check('servers.json: version 1, password XOR+base64, mode 600', stored().version === 1 && unxor(stored().servers.find(x => x.id === ssh).password) === 'p@ss "w" ö' && (fs.statSync(path.join(dir, 'servers.json')).mode & 0o777) === 0o600, + stored().servers.find(x => x.id === ssh).password); + await post('server/update', { id: ssh, name: 'renamed', password: '', notes: 'n' }); + check('edit with an empty password keeps the stored one', unxor(stored().servers.find(x => x.id === ssh).password) === 'p@ss "w" ö' && stored().servers.find(x => x.id === ssh).name === 'renamed'); + await post('server/update', { id: ssh, clearPassword: true }); + check('"remove stored" clears the password', stored().servers.find(x => x.id === ssh).password === '' && !(await state()).servers.find(x => x.cfg.id === ssh).cfg.hasPassword); + await post('server/move', { id: ssh, delta: -1 }); + s = await state(); + check('reorder', s.servers.map(x => x.cfg.id).join() === [local, dead, ssh, added].join() && stored().servers[2].id === ssh); + await sleep(3500); + s = await state(); + check('added local server comes online', s.servers.find(x => x.cfg.id === added).online); + + // --- rules + autopilot --- + const rules = s.servers[0].cfg.rules; + await post('server/update', { id: local, rules: [...rules, { metric: 'procs', op: '>', value: 1, duration: 0, severity: 'info', action: 'notify', cooldown: 30 }] }); + s = await state(); + const mine = s.servers[0].cfg.rules.at(-1); + check('add rule', s.servers[0].cfg.rules.length === rules.length + 1 && mine.id.length === 12 && mine.metric === 'procs' && mine.enabled === true && stored().servers[0].rules.length === rules.length + 1); + await sleep(2600); + s = await state(); + check('new rule fires (notify only)', s.servers[0].alerts.includes('Process count > 1') && s.alerts.some(x => x.severity === 'info' && x.message.startsWith('Process count > 1 (now')), s.alerts.find(x => x.severity === 'info')?.message); + await post('server/update', { id: local, rules: s.servers[0].cfg.rules.filter(x => x.id !== mine.id) }); + s = await state(); + check('delete rule', s.servers[0].cfg.rules.length === rules.length && !s.servers[0].cfg.rules.some(x => x.id === mine.id)); + await post('server/update', { id: local, autopilot: { ...s.servers[0].cfg.autopilot, runawayMinutes: 25, anomalyZ: 4.5, leakMode: 'none', dryRun: true } }); + s = await state(); + const ap = stored().servers[0].autopilot; + check('autopilot save', s.servers[0].cfg.autopilot.runawayMinutes === 25 && ap.anomalyZ === 4.5 && ap.leakMode === 'none' && ap.dryRun === true && ap.enabled === true, JSON.stringify(ap).slice(0, 150)); + + // --- pause / reconnect / analyze / history / events --- + await post('server/pause', { id: local, paused: true }); + check('pause', (await state()).servers[0].paused === true); + await post('server/pause', { id: local, paused: false }); + await post('server/analyze', { id: local }); + const an = (await sse('/api/events?id=' + local, 1200)).events.find(e => e[0] === 'live')[1].an; // review: the id stream now starts with hello, then live + check('analysis', an.when > 0 && an.health >= 0 && an.grade.length === 1 && an.heat.length === 2 && an.up.length === 3, `health ${an.health} ${an.grade}; findings: ${an.findings.map(f => `[${f.severity}] ${f.title}`).join('; ') || 'none'}`); + await post('server/reconnect', { id: local }); + check('reconnect -> Connecting', (await state()).servers[0].status === 'Connecting'); + await sleep(Math.max(6000, 72000 - (Date.now() - t0))); // let the server run for more than 70 s (a minute bucket closes) + s = await state(); + check('online again after reconnect', s.servers[0].online); + for (const range of [3600, 86400, 0]) { + const h = (await req('GET', `/api/history?id=${local}&range=${range}`)).json; + check(`history range ${range || 'all'}`, h.points >= 1 && h.t.length >= h.points && h.v.cpu.length === h.t.length && h.stats.length === 15 && h.stats[0].count >= 1, + `${h.tier}, ${h.points} points, availability ${h.availability?.toFixed(2)}%, cpu avg ${h.stats[0].avg?.toFixed(1)} p95 ${h.stats[0].p95?.toFixed(1)} max ${h.stats[0].max?.toFixed(1)}, stored ${h.bytes} B`); + } + r = await req('GET', `/api/history.csv?id=${local}&range=3600`); + const lines = r.text.split('\n'); + check('CSV export', r.status === 200 && lines[0].startsWith('time,samples,online_pct,cpu_avg,cpu_max,iowait_avg') && lines[0].split(',').length === 33 && lines.length > 10 && /^\d{4}-\d\d-\d\dT[\d:]{8},1,100,/.test(lines[1]) && /attachment/.test(r.headers['content-disposition']), `${lines.length - 1} rows; ${lines[1].slice(0, 60)}`); + r = await req('GET', '/api/alerts.log'); + check('alerts.log download = file on disk', r.status === 200 && r.text === fs.readFileSync(path.join(dir, 'alerts.log'), 'utf8') && /^\d{4}-\d\d-\d\dT[\d:]{8}\t(critical|warning|info|resolved|action)\t[^\t]+\t./.test(r.text), `${r.text.split('\n').length - 1} lines`); + const hd = path.join(dir, 'history', local), files = fs.readdirSync(hd); + check('history files: SMH1 header + 136-byte records', files.includes('raw.bin') && files.includes('minute.bin') && files.every(f => { const b = fs.readFileSync(path.join(hd, f)); return b.subarray(0, 8).equals(Buffer.from([0x53, 0x4d, 0x48, 0x31, 15, 0, 136, 0])) && (b.length - 8) % 136 === 0 && b.length > 8; }), + files.map(f => `${f} ${fs.statSync(path.join(hd, f)).size} B`).join(', ')); + check('offline host: downtime recorded for availability', fs.statSync(path.join(dir, 'history', dead, 'raw.bin')).size > 8 && (await req('GET', `/api/history?id=${dead}&range=3600`)).json.availability === 0); + await post('alerts/clear', {}); + check('clear events', (await state()).alerts.length === 0); + + // --- remove --- + await post('server/remove', { id: added, deleteHistory: true }); + await post('server/remove', { id: ssh, deleteHistory: false }); + s = await state(); + check('remove servers (delete history / keep history files)', s.servers.length === 2 && !fs.existsSync(path.join(dir, 'history', added)) && fs.existsSync(path.join(dir, 'history', ssh)) && stored().servers.length === 2); + console.log(`\n${failed ? failed + ' check(s) FAILED' : 'all checks passed'} — server ran ${(Math.round((Date.now() - t0) / 1000))} s during the test`); + process.exit(failed ? 1 : 0); +})().catch(e => { console.error('TEST ERROR', e); process.exit(2); }); diff --git a/dev/tests/web/cdp.js b/dev/tests/web/cdp.js new file mode 100644 index 0000000000000000000000000000000000000000..7e3f8af24cccb8cf49e94cee130148ff645186c0 --- /dev/null +++ b/dev/tests/web/cdp.js @@ -0,0 +1,32 @@ +// minimal DevTools-protocol driver for headless Chrome (Node's built-in WebSocket) +const { spawn } = require('child_process'), fs = require('fs'), os = require('os'), path = require('path'); +const sleep = ms => new Promise(r => setTimeout(r, ms)); +exports.sleep = sleep; +exports.launch = async (size = '1500,940') => { + const port = 9800 + (process.pid % 150), dir = fs.mkdtempSync(path.join(os.tmpdir(), 'sm-review-chrome-')); + const chrome = spawn('google-chrome', ['--headless=new', '--no-sandbox', '--password-store=basic', '--disable-gpu', `--remote-debugging-port=${port}`, `--user-data-dir=${dir}`, `--window-size=${size}`, 'about:blank'], { stdio: 'ignore' }); + const list = async () => (await (await fetch(`http://127.0.0.1:${port}/json`)).json()).filter(t => t.type === 'page'); + for (let i = 0; i < 60; ++i) { await sleep(200); try { if ((await list()).length) break; } catch {} } + const attach = async target => { + const ws = new WebSocket(target.webSocketDebuggerUrl), pending = new Map(), problems = []; + let id = 0; + const send = (method, params = {}) => new Promise(res => { pending.set(++id, res); ws.send(JSON.stringify({ id, method, params })); }); + ws.onmessage = e => { + const m = JSON.parse(e.data); + if (m.id) return pending.get(m.id)?.(m.result || m.error); + if (m.method === 'Runtime.exceptionThrown') problems.push('EXCEPTION ' + (m.params.exceptionDetails.exception?.description || m.params.exceptionDetails.text)); + if (m.method === 'Runtime.consoleAPICalled' && ['error', 'warning'].includes(m.params.type)) problems.push('CONSOLE ' + m.params.args.map(a => a.value ?? a.description).join(' ')); + if (m.method === 'Log.entryAdded' && ['error', 'warning'].includes(m.params.entry.level)) problems.push('LOG ' + m.params.entry.text + ' ' + (m.params.entry.url || '')); + }; + await new Promise(r => ws.onopen = r); + await send('Runtime.enable'), await send('Log.enable'), await send('Page.enable'); + const evaluate = async body => { // async function body run in the page + const r = await send('Runtime.evaluate', { expression: `(async () => { ${body} })()`, awaitPromise: true, returnByValue: true }); + if (r.exceptionDetails) throw new Error(r.exceptionDetails.exception?.description || r.exceptionDetails.text); + return r.result?.value; + }; + return { send, evaluate, problems, go: url => send('Page.navigate', { url }), shot: async file => fs.writeFileSync(file, Buffer.from((await send('Page.captureScreenshot', { format: 'png' })).data, 'base64')) }; + }; + const newTab = async url => attach(await (await fetch(`http://127.0.0.1:${port}/json/new?${encodeURIComponent(url)}`, { method: 'PUT' })).json()); + return { first: async () => attach((await list())[0]), newTab, close: () => { chrome.kill(); setTimeout(() => fs.rmSync(dir, { recursive: true, force: true }), 500); } }; +}; diff --git a/dev/tests/web/fake/powershell b/dev/tests/web/fake/powershell new file mode 100755 index 0000000000000000000000000000000000000000..9e8cce2721ec39307cef630f69f5b1b430d21d4b --- /dev/null +++ b/dev/tests/web/fake/powershell @@ -0,0 +1,44 @@ +#!/usr/bin/env python3 +"""Review stand-in for powershell.exe (based on sm-dev/fakewin). Behaviour is steered by the file $FAKE_CTL (one word): +ok | stall (alive, no frames) | die (exit with an error) | failsvc (Spooler fails) | nosvc (Spooler gone) | reboot (uptime restarts). +One-shot scripts are appended to $FAKE_LOG; a script containing HANG sleeps 60 s. Every text field carries HTML to test escaping.""" +import math, os, random, re, sys, time +src = sys.stdin.read() +ctl = lambda: (open(os.environ['FAKE_CTL']).read().strip() if os.path.exists(os.environ.get('FAKE_CTL', '')) else 'ok') +X = '' +if '@@SNAP_BEGIN' not in src: + cmd = src.strip().splitlines() + open(os.environ['FAKE_LOG'], 'a').write('\n'.join(cmd[2:-2]) + '\n') + if 'HANG' in src: time.sleep(60) + print('[fake powershell] would run:'); print('\n'.join(cmd[-6:])); print(X + ''); sys.exit(3 if 'EXIT3' in src else 0) +open(os.environ['FAKE_LOG'], 'a').write(f'COLLECTOR {time.time():.1f}\n') +iv = float((re.search(r'\$iv\s*=\s*([\d.]+)', src) or [0, 2])[1]) +GB = 1 << 30; n = 0; rx = tx = 5e9; cput = {4: 9e9, 620: 1e8, 1200: 5e9, 2040: 3e9} +names = {4: 'System', 620: 'svchost.exe', 1200: X, 2040: 'chrome.exe'} +boot = time.time() - 4 * 86400 +if ctl() == 'die': sys.stderr.write('boom: cannot collect\n'); sys.exit(7) +while True: + c = ctl() + if c == 'die': sys.stderr.write('boom: cannot collect\n'); sys.exit(7) + if c == 'stall': time.sleep(1); continue + if c == 'reboot': boot = time.time() - 30 + t = time.time(); L = ['@@SNAP_BEGIN'] + if n % 15 == 0: + L += ['@@S info', 'hostname=' + X, 'os=' + X, 'kernel=10.0.1' + X, 'arch=64-bit', 'cpumodel=' + X, 'mhz=2500', 'virt=' + X, 'admin=1', '@@S users'] + [f'{p}|{X}' for p in names] + L += ['@@S os', f'ts={int(t * 1000)}', f'uptime={int(t - boot)}', f'memtotal={16 * GB}', f'swaptotal={8 * GB}', f'swapfree={int(6.5 * GB)}', '@@S cpu'] + for k in ['_Total', '0', '1']: L.append(f'{k}|40|28|12|1|3000') + L += ['@@S sys', 'queue=0', 'ctxt=8000', 'threads=1832', '@@S mem', f'avail={6 * GB}', f'free={2 * GB}', f'standby={4 * GB}', f'syscache={GB // 2}', f'modified={GB // 8}', f'pool={GB}', '@@S net'] + rx += 5e5 * iv; tx += 1e5 * iv + L += [f'{X}|Up|10000|Ethernet|{int(rx)}|{int(tx)}|{int(rx / 900)}|{int(tx / 700)}|0|3|{X}', '@@S tcp', 'Established 42', 'Listen 27', '@@S disk', f'0 {X}|1000|2000|3|4|90', + '@@S df', f'{X}|{X}|NTFS|{127 * GB}|{int(21.5 * GB)}', '@@S procs'] + for p, nm in names.items(): + cput[p] += .05 * iv * 1e7 + L.append(f'{p}|4|{int(cput[p])}|8|12|{int(boot + p)}|{2 * GB}|{int(.3 * GB)}|{nm}') + L += ['@@S sessions', '1'] + if n % 2 == 0: + L += ['@@S services', f'W3SVC|Running|Auto|0|{X}', 'BrokenSvc|Stopped|Auto|1067|Broken Demo Service', 'gupdate|Stopped|Auto||Empty exit code', 'RemoteRegistry|Stopped|Disabled|1077|Remote Registry'] + if c != 'nosvc': L += ['Spooler|Stopped|Auto|1067|Print Spooler' if c == 'failsvc' else 'Spooler|Running|Auto|0|Print Spooler'] + L += ['@@S thermal', f'{X}|45.5', '@@SNAP_END'] + try: sys.stdout.write('\n'.join(L) + '\n'); sys.stdout.flush() + except OSError: sys.exit(0) + n += 1; time.sleep(iv) diff --git a/dev/tests/web/fake/taskkill b/dev/tests/web/fake/taskkill new file mode 100755 index 0000000000000000000000000000000000000000..eb653e453033f8f8c28f258dbce0b2461a1d1abf --- /dev/null +++ b/dev/tests/web/fake/taskkill @@ -0,0 +1,14 @@ +#!/usr/bin/env python3 +"""Review stand-in for taskkill.exe: "taskkill /PID /T /F" ends the process and everything below it (like /T on Windows).""" +import os, signal, sys +args = sys.argv[1:] +pid = int(args[args.index('/PID') + 1]) +kids = {} +for d in os.listdir('/proc'): + if d.isdigit(): + try: kids.setdefault(int(open(f'/proc/{d}/stat').read().rsplit(')', 1)[1].split()[1]), []).append(int(d)) + except OSError: pass +def tree(p): return [p] + [x for k in kids.get(p, []) for x in tree(k)] +for p in tree(pid) if '/T' in args else [pid]: + try: os.kill(p, signal.SIGKILL) + except OSError: pass diff --git a/dev/tests/web/fakessh/ssh b/dev/tests/web/fakessh/ssh new file mode 100755 index 0000000000000000000000000000000000000000..322fa1334d13aba51b967cf354ed3caa23f7f830 --- /dev/null +++ b/dev/tests/web/fakessh/ssh @@ -0,0 +1,12 @@ +#!/usr/bin/env python3 +"""Review stand-in for ssh: logs argv and the askpass environment as JSON lines to $FAKESSH_LOG, asks the askpass helper for the +password like ssh would, then runs the remote command line locally with stdin/stdout passed through (the "server" is this machine).""" +import json, os, subprocess, sys +env = {k: os.environ.get(k) for k in ('SSH_ASKPASS', 'SSH_ASKPASS_REQUIRE', 'SERVERMONITOR_ASKPASS', 'DISPLAY')} +answer = mode = None +if env['SSH_ASKPASS']: + mode = oct(os.stat(env['SSH_ASKPASS']).st_mode & 0o777) + ' in ' + oct(os.stat(os.path.dirname(env['SSH_ASKPASS'])).st_mode & 0o777) + if env['SSH_ASKPASS'].endswith('.sh'): answer = subprocess.run([env['SSH_ASKPASS'], "me@fakehost's password: "], capture_output=True, text=True).stdout +open(os.environ['FAKESSH_LOG'], 'a').write(json.dumps({'argv': sys.argv[1:], 'env': env, 'askpass_answer': answer, 'askpass_mode': mode, 'askpass_text': open(env['SSH_ASKPASS'], newline='').read() if env['SSH_ASKPASS'] else None}) + '\n') +if 'deadhost' in ' '.join(sys.argv): sys.stderr.write('ssh: connect to host deadhost port 22: Connection refused\n'); sys.exit(255) +os.execvp('/bin/sh', ['/bin/sh', '-c', sys.argv[-1]]) diff --git a/dev/tests/web/lib.js b/dev/tests/web/lib.js new file mode 100644 index 0000000000000000000000000000000000000000..819e956134cd9c2d8082c5cd7b93a56fe390b9ed --- /dev/null +++ b/dev/tests/web/lib.js @@ -0,0 +1,18 @@ +// shared helpers for the review tests +const http = require('http'); +exports.sleep = ms => new Promise(r => setTimeout(r, ms)); +exports.client = port => { + const req = (method, p, body, headers = {}) => new Promise((resolve, reject) => { + const data = body === undefined ? null : typeof body === 'string' ? body : JSON.stringify(body); + const r = http.request({ host: '127.0.0.1', port, method, path: p, agent: false, headers: { ...(data != null && { 'Content-Type': 'application/json', 'X-SM': '1' }), ...headers } }, res => { + let s = ''; res.setEncoding('utf8').on('data', d => s += d).on('end', () => { let json; try { json = JSON.parse(s); } catch {} resolve({ status: res.statusCode, headers: res.headers, text: s, json }); }); + }); + r.on('error', reject); r.end(data); + }); + const post = async (p, body) => { const r = await req('POST', '/api/' + p, body); if (r.status !== 200) throw new Error(`${p}: ${r.status} ${r.text}`); return r.json; }; + const state = async () => (await req('GET', '/api/state')).json; + return { req, post, state }; +}; +let failed = 0; +exports.check = (name, ok, info = '') => { console.log(`${ok ? 'PASS' : 'FAIL'} ${name}${info ? ' — ' + String(info).slice(0, 300) : ''}`); if (!ok) ++failed; }; +exports.done = () => console.log(failed ? `${failed} FAILED` : 'all passed'); diff --git a/dev/tests/web/mkcfg.sh b/dev/tests/web/mkcfg.sh new file mode 100755 index 0000000000000000000000000000000000000000..ecf02d4a4468961a2d26597a8f6d3522ff48fd94 --- /dev/null +++ b/dev/tests/web/mkcfg.sh @@ -0,0 +1,8 @@ +#!/bin/sh +# mkcfg.sh : fresh scratch config (local + unreachable ssh, both dry run) +rm -rf "$1"; mkdir -p "$1/ServerMonitorWeb" +cat > "$1/ServerMonitorWeb/servers.json" <<'J' +{"version":1,"servers":[ + {"id":"local1","name":"This computer","group":"Local","transport":0,"interval":2,"enabled":true,"autopilot":{"enabled":true,"dryRun":true}}, + {"id":"ssh1","name":"unreachable","group":"Test","transport":1,"host":"127.0.0.1","port":1,"user":"nobody","interval":2,"enabled":true,"autopilot":{"enabled":true,"dryRun":true}}]} +J diff --git a/dev/tests/web/parse_dump.cpp b/dev/tests/web/parse_dump.cpp new file mode 100644 index 0000000000000000000000000000000000000000..573b6172787ee099390e13998d56f276597efb8c --- /dev/null +++ b/dev/tests/web/parse_dump.cpp @@ -0,0 +1,29 @@ +// Feeds captured collector frames to the C++ reference parser and prints every value (for comparison with the JS parser). +#include "core/Model.h" +#include +#include +static void d(const char *k, double v) { printf("%s=%.4f\n", k, v); } +int main(int, char **argv) { + QFile f(argv[1]); f.open(QIODevice::ReadOnly); + QByteArray buf = f.readAll(); + MetricsEngine e; Metrics m; int n = 0; + for (int end; (end = buf.indexOf("@@SNAP_END")) >= 0;) { + const int begin = buf.lastIndexOf("@@SNAP_BEGIN", end); + if (begin >= 0) m = e.process(buf.mid(begin, end - begin), 1000 + n++); + buf.remove(0, end + 10); + } + printf("frames=%d valid=%d host=%s os=%s kernel=%s arch=%s cpu=%s virt=%s fullest=%s busiest=%s\n", n, m.valid, qPrintable(m.hostname), qPrintable(m.os), qPrintable(m.kernel), qPrintable(m.arch), qPrintable(m.cpuModel), qPrintable(m.virt), qPrintable(m.fullestMount), qPrintable(m.busiestDisk)); +#define D(x) d(#x, m.x); + D(cpuCount) D(loggedUsers) D(procsRunning) D(procsBlocked) D(threadsTotal) D(socketsUsed) D(servicesFailed) D(servicesRunning) D(uptime) D(load1) D(load5) D(load15) + D(cpuUsage) D(cpuUser) D(cpuSystem) D(cpuIowait) D(cpuSteal) D(cpuIrq) D(ctxtPerSec) D(intrPerSec) D(forksPerSec) D(avgMhz) D(memTotal) D(memFree) D(memAvailable) D(memUsed) D(buffers) D(cached) + D(shared) D(slab) D(dirty) D(swapTotal) D(swapUsed) D(memPct) D(swapPct) D(diskReadBps) D(diskWriteBps) D(maxDiskPct) D(maxDiskUtil) D(netRxBps) D(netTxBps) D(maxTemp) + for (const auto &c : m.cores) printf("core %.4f %.4f\n", c.usage, c.mhz); + for (const auto &x : m.mounts) printf("mount %s|%s|%s %.0f %.0f %.0f %.4f\n", qPrintable(x.device), qPrintable(x.type), qPrintable(x.mount), x.total, x.used, x.avail, x.pct); + for (const auto &x : m.disks) printf("disk %s %.4f %.4f %.4f %.4f %.4f %.0f %.0f\n", qPrintable(x.name), x.readBps, x.writeBps, x.readIops, x.writeIops, x.util, x.totalRead, x.totalWritten); + for (const auto &x : m.nets) printf("net %s %s %d %d %.4f %.4f %.4f %.4f %.0f %.0f %.0f %.0f\n", qPrintable(x.name), qPrintable(x.state), x.speed, x.virt, x.rxBps, x.txBps, x.rxPps, x.txPps, x.rxBytes, x.txBytes, x.errors, x.drops); + for (auto it = m.tcp.cbegin(); it != m.tcp.cend(); ++it) printf("tcp %s %d\n", qPrintable(it.key()), it.value()); + for (const auto &p : m.procs) printf("proc %d %d %d %d %s|%s|%c %.4f %.4f %.0f %.0f %.2f\n", p.pid, p.ppid, p.threads, p.nice, qPrintable(p.name), qPrintable(p.user), p.state.toLatin1(), p.cpu, p.memPct, p.rss, p.vsz, p.age); + for (const auto &s : m.services) printf("svc %s|%s|%s|%s|%s\n", qPrintable(s.unit), qPrintable(s.load), qPrintable(s.active), qPrintable(s.sub), qPrintable(s.description)); + for (const auto &t : m.temps) printf("temp %s %.4f\n", qPrintable(t.name), t.celsius); + for (const auto &g : m.gpus) printf("gpu %d %s %.2f %.2f %.2f %.2f %.2f %.2f\n", g.index, qPrintable(g.name), g.util, g.memUsed, g.memTotal, g.temp, g.power, g.fan); +} diff --git a/dev/tests/web/parse_dump.js b/dev/tests/web/parse_dump.js new file mode 100644 index 0000000000000000000000000000000000000000..358d305906e19699b0845f0570ca14e618e0d8b7 --- /dev/null +++ b/dev/tests/web/parse_dump.js @@ -0,0 +1,18 @@ +// same dump as parse_dump.cpp from the JS parser: node parse_dump.js +const fs = require('fs'), path = require('path'), plat = require(path.join(process.argv[2], 'core/platform.js')); +let buf = fs.readFileSync(process.argv[3], 'utf8'), m, n = 0; +const st = {}, out = [], f = (v, p = 4) => (+v).toFixed(p), line = s => out.push(s); +for (let end; (end = buf.indexOf('@@SNAP_END')) >= 0; buf = buf.slice(end + 10)) { const begin = buf.lastIndexOf('@@SNAP_BEGIN', end); if (begin >= 0) m = plat.parse(buf.slice(begin, end), st, 1000 + n++); } +line(`frames=${n} valid=${+m.valid} host=${m.hostname} os=${m.os} kernel=${m.kernel} arch=${m.arch} cpu=${m.cpuModel} virt=${m.virt} fullest=${m.fullestMount} busiest=${m.busiestDisk}`); +for (const k of ('cpuCount loggedUsers procsRunning procsBlocked threadsTotal socketsUsed servicesFailed servicesRunning uptime load1 load5 load15 cpuUsage cpuUser cpuSystem cpuIowait cpuSteal cpuIrq ctxtPerSec intrPerSec forksPerSec avgMhz memTotal memFree memAvailable memUsed buffers cached ' + + 'shared slab dirty swapTotal swapUsed memPct swapPct diskReadBps diskWriteBps maxDiskPct maxDiskUtil netRxBps netTxBps maxTemp').split(' ')) line(`${k}=${f(m[k])}`); +for (const c of m.cores) line(`core ${f(c.usage)} ${f(c.mhz)}`); +for (const x of m.mounts) line(`mount ${x.device}|${x.type}|${x.mount} ${f(x.total, 0)} ${f(x.used, 0)} ${f(x.avail, 0)} ${f(x.pct)}`); +for (const x of m.disks) line(`disk ${x.name} ${f(x.readBps)} ${f(x.writeBps)} ${f(x.readIops)} ${f(x.writeIops)} ${f(x.util)} ${f(x.totalRead, 0)} ${f(x.totalWritten, 0)}`); +for (const x of m.nets) line(`net ${x.name} ${x.state} ${x.speed} ${+x.virt} ${f(x.rxBps)} ${f(x.txBps)} ${f(x.rxPps)} ${f(x.txPps)} ${f(x.rxBytes, 0)} ${f(x.txBytes, 0)} ${f(x.errors, 0)} ${f(x.drops, 0)}`); +for (const k of Object.keys(m.tcp).sort()) line(`tcp ${k} ${m.tcp[k]}`); +for (const p of m.procs) line(`proc ${p.pid} ${p.ppid} ${p.threads} ${p.nice} ${p.name}|${p.user}|${p.state} ${f(p.cpu)} ${f(p.memPct)} ${f(p.rss, 0)} ${f(p.vsz, 0)} ${f(p.age, 2)}`); +for (const s of m.services) line(`svc ${s.unit}|${s.load}|${s.active}|${s.sub}|${s.description}`); +for (const t of m.temps) line(`temp ${t.name} ${f(t.celsius)}`); +for (const g of m.gpus) line(`gpu ${g.index} ${g.name} ${f(g.util, 2)} ${f(g.memUsed, 2)} ${f(g.memTotal, 2)} ${f(g.temp, 2)} ${f(g.power, 2)} ${f(g.fan, 2)}`); +console.log(out.join('\n')); diff --git a/dev/tests/web/spec_cmds.js b/dev/tests/web/spec_cmds.js new file mode 100644 index 0000000000000000000000000000000000000000..9a391ffe895857299f2d9cd059dcc183f782eb50 --- /dev/null +++ b/dev/tests/web/spec_cmds.js @@ -0,0 +1,24 @@ +// compares every command string of a platform.js with the backticked strings of SPEC.md §6 (and §3 wrap text) +const fs = require('fs'), path = require('path'); +const root = process.argv[2], plat = require(path.join(root, 'core/platform.js')); +const spec = fs.readFileSync(path.join(process.env.HOME, '.local/share/sm-dev/SPEC.md'), 'utf8'); +const sec6 = spec.slice(spec.indexOf('## 6.'), spec.indexOf('## 7.')); +const ticks = [...sec6.matchAll(/`([^`]+)`/g)].map(m => m[1].replace(/\\\|/g, '|')); +const have = new Set(); +for (const k of ['procActions', 'priorities', 'serviceActions', 'diagnostics', 'systemActions']) for (const c of plat.ui[k]) have.add(c.cmd), have.add(c.label); +for (const a of ['kill_pid', 'renice', 'restart_service', 'restart_failed', 'drop_caches']) { const c = plat.command(a, 'ARG'); if (c) have.add(c.replace(/'ARG'/g, '{q}').replace(/\b0\b/, '{n}')); } +have.add(plat.cleanup), have.add(plat.power(true)), have.add(plat.power(false)); +have.add(plat.serviceLogs('ARG', 123).replace(/'ARG'/g, '{q}').replace('123', '{n}')); +const all = [...have].join('\n'); +let miss = 0; +for (const t of ticks) { + if (t.length < 12 || /^(C\+\+|\{|Model|Session|Tabs)/.test(t)) continue; + const ok = all.includes(t) || all.includes(t.replace('', 'Idle')) || all.includes(t.replace('', 'start')); + if (!ok) ++miss, console.log('NOT FOUND:', t); +} +console.log(`${ticks.length} backticked strings in §6, ${miss} not found in ${plat.ui.name} platform.js`); +console.log('rule actions:', plat.ui.ruleActions.map(a => a[0]).join(' ')); +console.log('wrap:', JSON.stringify(plat.wrap('CMD', true))); +console.log('shell:', plat.shell(3).join(' ')); +console.log('collector head:', JSON.stringify(plat.collector(3).slice(0, 40))); +console.log('quote:', plat.quote("a'b")); diff --git a/dev/tests/web/start.sh b/dev/tests/web/start.sh new file mode 100755 index 0000000000000000000000000000000000000000..d9cd421a29a2473ef4edb4250a7885c2142d826d --- /dev/null +++ b/dev/tests/web/start.sh @@ -0,0 +1,6 @@ +#!/bin/sh +# start.sh : starts an edition in the background with a scratch config; pid in .pid +T=$HOME/.local/share/sm-dev/tmp/review-web +if [ "$1" = W ]; then P="$HOME/Desktop/Server Monitor(web-window)"; PATH="$HOME/.local/share/sm-dev/fakewin:$PATH"; else P="$HOME/Desktop/Server Monitor(web-linux)"; fi +XDG_CONFIG_HOME="$2" APPDATA="$2" PORT="$3" nohup node "$P/server.js" > "$2.out" 2> "$2.err" & +echo $! > "$2.pid" diff --git a/dev/tests/web/startW.sh b/dev/tests/web/startW.sh new file mode 100755 index 0000000000000000000000000000000000000000..becb8cb1731e21abf1c47f2d4ae9387004ef53d7 --- /dev/null +++ b/dev/tests/web/startW.sh @@ -0,0 +1,5 @@ +#!/bin/sh +# startW.sh : Windows edition with the review stand-in powershell +T=$HOME/.local/share/sm-dev/tmp/review-web; P="$HOME/Desktop/Server Monitor(web-window)" +PATH="$T/fake:$PATH" FAKE_CTL="$1.ctl" FAKE_LOG="$1.log" XDG_CONFIG_HOME="$1" APPDATA="$1" PORT="$2" nohup node "$P/server.js" > "$1.out" 2> "$1.err" & +echo $! > "$1.pid" diff --git a/dev/tests/web/t_bg.js b/dev/tests/web/t_bg.js new file mode 100644 index 0000000000000000000000000000000000000000..51bec5c10f88e6917141ff1abe85c96e3fda316c --- /dev/null +++ b/dev/tests/web/t_bg.js @@ -0,0 +1,13 @@ +// The delayed-background pattern of "Reboot" / "Shut down" ((sleep 2; systemctl reboot) >/dev/null 2>&1 &) must survive the end of its +// command and a reconnect, now that children are ended by process group. Uses a harmless marker file instead. node t_bg.js +const fs = require('fs'), { sleep, client, check, done } = require('./lib'), [port, mark] = process.argv.slice(2), { post } = client(port); +(async () => { + for (const f of [mark + '.1', mark + '.2']) fs.existsSync(f) && fs.unlinkSync(f); + let t = Date.now(), r = await post('exec', { id: 'local1', cmd: `(sleep 2; echo ran > '${mark}.1') >/dev/null 2>&1 & echo scheduled`, privileged: true }); + check('the command returns at once', r.code === 0 && r.out === 'scheduled\n' && Date.now() - t < 1000, `${JSON.stringify(r)} after ${Date.now() - t} ms`); + r = await post('exec', { id: 'local1', cmd: `(sleep 2; echo ran > '${mark}.2') >/dev/null 2>&1 & echo scheduled` }); + await post('server/reconnect', { id: 'local1' }); // drops the link right after the command ended + await sleep(3500); + check('the delayed part still runs (also after a reconnect)', fs.existsSync(mark + '.1') && fs.existsSync(mark + '.2'), `${fs.existsSync(mark + '.1')} ${fs.existsSync(mark + '.2')}`); + done(); +})(); diff --git a/dev/tests/web/t_children.js b/dev/tests/web/t_children.js new file mode 100644 index 0000000000000000000000000000000000000000..579e8ebd49b314facb744511525d64521d90e329 --- /dev/null +++ b/dev/tests/web/t_children.js @@ -0,0 +1,41 @@ +// No child process may outlive the monitor. node t_children.js +// Starts an edition with a scratch config (local server + a server over the stand-in ssh, dry run), opens several connection +// tests and a console "sleep 30" (HANG on the Windows stand-in), ends the server and looks for survivors. Every process started +// below the server carries SM_REVIEW_MARK in its environment, so survivors are found even after they were re-parented. +const fs = require('fs'), path = require('path'), { spawn } = require('child_process'), { sleep, client, check, done } = require('./lib'); +const [edition, port, how] = process.argv.slice(2), win = edition === 'W', T = __dirname, cfg = path.join(T, `cfgK${edition}`), mark = `mark-${process.pid}-${Date.now()}`; +const root = path.join(process.env.HOME, 'Desktop', win ? 'Server Monitor(web-window)' : 'Server Monitor(web-linux)'); +const marked = () => fs.readdirSync('/proc').filter(d => /^\d+$/.test(d)).filter(pid => { try { return fs.readFileSync(`/proc/${pid}/environ`, 'utf8').includes(mark); } catch { return false; } }) + .map(pid => { try { return `${pid}:${fs.readFileSync(`/proc/${pid}/cmdline`, 'utf8').replace(/\0/g, ' ').trim().replace(/^.*\/(python3|node) /, '$1 ').slice(0, 60)}`; } catch { return ''; } }).filter(Boolean); +(async () => { + const tmp0 = fs.readdirSync(require('os').tmpdir()); + fs.mkdirSync(path.join(cfg, 'ServerMonitorWeb'), { recursive: true }); + fs.writeFileSync(path.join(cfg, 'ServerMonitorWeb', 'servers.json'), JSON.stringify({ version: 1, servers: [ + { id: 'local1', name: 'local', transport: 0, interval: 1, enabled: true, autopilot: { enabled: true, dryRun: true } }, + { id: 'ssh1', name: 'over ssh', transport: 1, host: 'fakehost', user: 'me', interval: 1, enabled: true, autopilot: { enabled: true, dryRun: true } }] })); + fs.writeFileSync(cfg + '.ctl', 'ok'), fs.writeFileSync(cfg + '.log', ''), fs.writeFileSync(cfg + '.sshlog', ''); + const env = { ...process.env, PATH: `${T}/fakessh:${win ? T + '/fake:' : ''}${process.env.PATH}`, FAKESSH_LOG: cfg + '.sshlog', FAKE_CTL: cfg + '.ctl', FAKE_LOG: cfg + '.log', XDG_CONFIG_HOME: cfg, APPDATA: cfg, PORT: port, SM_REVIEW_MARK: mark }; + const srv = spawn('node', [path.join(root, 'server.js')], { env, stdio: ['ignore', 'ignore', fs.openSync(cfg + '.err', 'w')] }); + const { post, state } = client(port); + for (let i = 0; i < 40; ++i) { await sleep(250); try { if ((await state()).servers.every(s => s.online)) break; } catch {} } + const st = await state(); + check('both servers online (local and over the stand-in ssh)', st.servers.every(s => s.online), st.servers.map(s => s.cfg.name + '=' + s.status).join(', ')); + // work in flight: three connection tests and two commands that would run for a long time + const pending = [post('server/test', { name: 't1', transport: 0 }), post('server/test', { name: 't2', transport: 1, host: 'fakehost' }), post('server/test', { name: 't3', transport: 1, host: 'fakehost', password: 'pw' }), + post('exec', { id: 'local1', cmd: win ? 'HANG' : 'sleep 30; echo late' }), post('exec', { id: 'ssh1', cmd: win ? 'HANG' : 'sleep 31' })].map(p => p.catch(() => null)); + await sleep(700); + const before = marked(); + check('children are running', before.length >= 8, `${before.length}: ${before.map(x => x.replace(/^\d+:/, '')).join(' | ')}`); + srv.kill(how); + const t0 = Date.now(); + await new Promise(r => srv.on('exit', r)); + let left = marked(); + for (; left.length && Date.now() - t0 < 4000; left = marked()) await sleep(200); + check(`${how}: no child process is left`, !left.length, left.length ? `after 4 s still: ${left.join(' | ')}` : `all ${before.length} gone after ${((Date.now() - t0) / 1000).toFixed(1)} s`); + await Promise.all(pending); + for (const pid of marked().map(x => +x.split(':')[0])) try { process.kill(pid, 'SIGKILL'); } catch {} // never leave test processes behind + const tmp = fs.readdirSync(require('os').tmpdir()).filter(f => /^sm-[A-Za-z0-9]{6}$/.test(f) && !tmp0.includes(f)); + check('askpass helper folder is removed' + (how === 'SIGKILL' ? ' (not possible after a hard kill: reported only)' : ''), how === 'SIGKILL' || !tmp.length, tmp.join(' ')); + console.log('server stderr:', JSON.stringify(fs.readFileSync(cfg + '.err', 'utf8').slice(0, 300))); + done(); +})(); diff --git a/dev/tests/web/t_flood.js b/dev/tests/web/t_flood.js new file mode 100644 index 0000000000000000000000000000000000000000..12fca5696f9d28158186dc57e8345ca7c1b812c9 --- /dev/null +++ b/dev/tests/web/t_flood.js @@ -0,0 +1,11 @@ +// a console command with endless output must not take the monitor down. node t_flood.js +const { sleep, client, check, done } = require('./lib'), { req, post } = client(process.argv[2]); +(async () => { + const t = Date.now(); + const r = await req('POST', '/api/exec', { id: 'local1', cmd: 'yes 0123456789012345678901234567890123456789' }).catch(e => ({ status: 0, text: String(e) })); + check('endless output: the command is stopped and reported', r.status === 200 && r.json.code === -1 && r.json.out.length < 6e6, `status ${r.status} after ${Date.now() - t} ms, ${r.json ? r.json.out.length + ' chars, …' + JSON.stringify(r.json.out.slice(-40)) : r.text}`); + await sleep(1500); + const s = await req('GET', '/api/state').catch(e => ({ status: 0, text: String(e) })); + check('the monitor is still running', s.status === 200, s.status || s.text); + done(); +})(); diff --git a/dev/tests/web/t_fuzz.js b/dev/tests/web/t_fuzz.js new file mode 100644 index 0000000000000000000000000000000000000000..893b5fdb15d404e5634965c4604d0f1f744b52f5 --- /dev/null +++ b/dev/tests/web/t_fuzz.js @@ -0,0 +1,37 @@ +// A broken frame must never throw (an exception in the parser would stop the whole monitor). node t_fuzz.js +const fs = require('fs'), path = require('path'), { check, done } = require('./lib'); +const plat = require(path.join(process.argv[2], 'core/platform.js')), text = fs.readFileSync(process.argv[3], 'utf8'); +const frames = text.split('@@SNAP_END').filter(f => f.includes('@@SNAP_BEGIN')).map(f => f.slice(f.indexOf('@@SNAP_BEGIN'))); +let seed = 12345; const rnd = n => (seed = (seed * 1103515245 + 12345) & 0x7fffffff) % n; +const junk = ['', ' ', '|', '||||||||||||', ':', '=', '@@S ', '@@S procs', '-1', 'NaN', '1e999', '0x10', '\u0000', '\t\t', 'a'.repeat(5000), '9'.repeat(400), '__proto__=1', '__proto__|1|2|3|4|5|6|7|8|9', 'constructor 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16', 'cpu', 'cpu0', '1 (a b) S', '%s%n', '\r']; +function mutate(f) { + let lines = f.split('\n'); + for (let k = 0, n = 1 + rnd(12); k < n; ++k) { + const i = rnd(lines.length), how = rnd(8); + if (how === 0) lines.splice(i, 1 + rnd(20)); + else if (how === 1) lines[i] = junk[rnd(junk.length)]; + else if (how === 2) lines.splice(i, 0, junk[rnd(junk.length)]); + else if (how === 3) lines[i] = lines[i].slice(0, rnd(lines[i].length + 1)); + else if (how === 4) lines[i] = lines[i].replace(/\d+/g, () => junk[rnd(junk.length)]); + else if (how === 5) lines[i] = lines[i].split(/([ |:=])/).sort(() => rnd(3) - 1).join(''); + else if (how === 6) lines = lines.slice(0, rnd(lines.length)); + else lines.splice(i, 0, lines[rnd(lines.length)]); + } + return lines.join(rnd(2) ? '\n' : '\r\n'); +} +let thrown = 0, first = '', n = 0, bad = 0; +for (let round = 0; round < 3000; ++round) { + const st = {}; + for (let k = 0; k < 4; ++k) { + const f = rnd(4) ? mutate(frames[rnd(frames.length)]) : frames[rnd(frames.length)]; + try { + const m = plat.parse(f, st, Date.now()); ++n; + const flat = JSON.stringify(m); // what the page gets + if (!Array.isArray(m.procs) || !Array.isArray(m.cores) || typeof m.cpuCount !== 'number' || !(m.cpuCount >= 0) || /"(cpuUsage|memPct|maxDiskPct|load1|netRxBps)":null/.test(flat)) ++bad, first ||= 'non-finite value: ' + flat.match(/"\w+":null/)?.[0]; + } catch (e) { ++thrown, first ||= e.stack.split('\n').slice(0, 3).join(' | '); } + } +} +check(`${n + thrown} mutated ${plat.ui.name} frames: the parser never throws`, !thrown, thrown ? `${thrown} exceptions, first: ${first}` : ''); +check('main values stay finite numbers', !bad, bad ? `${bad} frames, first: ${first}` : ''); +check('nothing leaked onto Object.prototype', ({}).polluted === undefined && Object.keys({}).length === 0 && ({})[1] === undefined); +done(); diff --git a/dev/tests/web/t_history.js b/dev/tests/web/t_history.js new file mode 100644 index 0000000000000000000000000000000000000000..b4f157aae8fcba6ba28912c8e5eea43eae3e14c5 --- /dev/null +++ b/dev/tests/web/t_history.js @@ -0,0 +1,62 @@ +// history store: file layout, cut-off record, buckets left open by the last run, trimming. node t_history.js +const fs = require('fs'), path = require('path'), { check, done } = require('./lib'); +const [root, scratch] = process.argv.slice(2); +let fake = Math.floor(new Date(2026, 5, 10, 10, 20, 0).getTime() / 1000); // local 10:20 +const realNow = Date.now; Date.now = () => fake * 1000; +const { HistoryStore, I, stats } = require(path.join(root, 'core/history.js')); +const dir = n => { const d = path.join(scratch, n); fs.rmSync(d, { recursive: true, force: true }); return d; }; +const vals = x => Array.from({ length: 15 }, (_, i) => i === 4 ? NaN : x + i); +const read = f => { // independent reader of the documented format + const b = fs.readFileSync(f), out = []; + if (b.subarray(0, 4).toString() !== 'SMH1' || b[4] !== 15 || b[5] !== 0 || b.readUInt16LE(6) !== 136) return null; + for (let o = 8; o + 136 <= b.length; o += 136) out.push({ ts: Number(b.readBigInt64LE(o)), n: b.readUInt32LE(o + 8), nUp: b.readUInt32LE(o + 12), avg0: b.readFloatLE(o + 16), avg4: b.readFloatLE(o + 32), max0: b.readFloatLE(o + 76) }); + return Object.assign(out, { rest: (b.length - 8) % 136 }); +}; + +// 1. layout + accumulation +let d = dir('h1'), st = new HistoryStore(d), t0 = fake; +for (let i = 0; i < 120; ++i) fake = t0 + i * 10, st.add(fake, vals(i % 6 * 10), i !== 7); // 20 min, one sample down +st.add(fake, vals(999), true); // same second again: not a second raw point +let raw = read(path.join(d, 'raw.bin')), min = read(path.join(d, 'minute.bin')); +check('raw.bin: SMH1 header, 136-byte records, one per sample', raw && raw.length === 120 && raw.rest === 0 && raw[0].ts === t0 && raw[0].n === 1 && raw[0].nUp === 1 && isNaN(raw[0].avg4), raw && `${raw.length} records`); +check('a downtime sample is n=1 nUp=0 with NaN values', raw[7].n === 1 && raw[7].nUp === 0 && isNaN(raw[7].avg0)); +check('minute.bin: closed minutes only, avg and max per bucket', min.length === 19 && min[0].ts === t0 && min[0].n === 6 && min[0].avg0 === 25 && min[0].max0 === 50 && min[1].n === 6 && min[1].nUp === 5, JSON.stringify(min[0])); +const open = st.range(t0, fake, 1).at(-1); +check('range() includes the open bucket', st.range(t0, fake, 1).length === 20 && open.ts === t0 + 19 * 60 && open.n === 7, `n=${open.n}`); +check('no hour / day file content before a bucket closes', !fs.existsSync(path.join(d, 'hour.bin')) && st.range(t0 - 3600, fake, 2).length === 1 && st.range(t0 - 86400, fake, 3)[0].n === 121); + +// 2. restart later: the buckets the last run left open must not be lost (they are stored with the first new sample). +// The raw tier keeps one sample per second, so the rebuilt minute has 6 of the 7 samples. +fake = t0 + 2 * 3600 + 300, st = new HistoryStore(d); +check('restart 2 h later: the open buckets of the last run are still in range()', st.range(t0 - 3600, fake, 1).length === 20 && st.range(t0 - 3600, fake, 2)[0]?.n === 120 && st.range(t0 - 86400, fake, 3)[0]?.n === 120); +st.add(fake, vals(1), true); +check('restart 2 h later: last open minute is stored', st.t[1].length === 20 && st.t[1].at(-1).n === 6 && read(path.join(d, 'minute.bin')).length === 20, `${st.t[1].length} minutes`); +check('restart 2 h later: the open hour of the last run is stored', st.t[2].length === 1 && st.t[2][0].n === 120 && st.t[2][0].nUp === 119 && st.t[2][0].ts === t0 - 20 * 60 && read(path.join(d, 'hour.bin'))?.length === 1, `${st.t[2].length} hours`); +fake = Math.floor(new Date(2026, 5, 11, 9, 5, 0).getTime() / 1000), st = new HistoryStore(d), st.add(fake, vals(1), true); +check('restart next day: yesterday is stored in the day tier', st.t[3].length === 1 && st.t[3][0].n === 120 && st.t[3][0].ts === Math.floor(new Date(2026, 5, 10).getTime() / 1000), `${st.t[3].length} days, n=${st.t[3][0]?.n}`); +st = new HistoryStore(d); +check('another restart does not duplicate buckets', st.t[1].length === 20 && st.t[2].length === 1 && st.t[3].length === 1 && st.range(fake - 86400 * 2, fake, 3).length === 2 && read(path.join(d, 'day.bin')).length === 1, `${st.t[1].length} ${st.t[2].length} ${st.t[3].length}`); + +// 3. a record cut off by a crash must not misalign what is appended later +d = dir('h2'), fake = t0, st = new HistoryStore(d); +for (let i = 0; i < 10; ++i) st.add(fake = t0 + i, vals(i), true); +fs.truncateSync(path.join(d, 'raw.bin'), 8 + 136 * 9 + 50); +st = new HistoryStore(d); +for (let i = 10; i < 13; ++i) st.add(fake = t0 + i, vals(i), true); +st = new HistoryStore(d), raw = read(path.join(d, 'raw.bin')); +check('cut-off record: file realigned, later samples readable', raw.rest === 0 && st.t[0].length === 12 && st.t[0].at(-1).ts === t0 + 12 && st.t[0].at(-1).avg[0] === 12, `${st.t[0].length} points, last ts ${st.t[0].at(-1)?.ts - t0}, file remainder ${raw.rest}`); + +// 4. foreign file is set aside, expired points are trimmed +fs.writeFileSync(path.join(d, 'hour.bin'), 'not a history file'), fs.writeFileSync(path.join(d, 'hour.bin.old'), 'older'); +st = new HistoryStore(d); +check('file with a wrong header is renamed to .old (replacing an older one)', fs.readFileSync(path.join(d, 'hour.bin.old'), 'utf8') === 'not a history file' && !fs.existsSync(path.join(d, 'hour.bin'))); +d = dir('h3'), fake = t0, st = new HistoryStore(d); +for (let i = 0; i < 1100; ++i) st.add(fake = t0 + i * 60, vals(1), true); // 18 h of raw samples, 6 h are kept +raw = read(path.join(d, 'raw.bin')); +check('raw tier trimmed to 6 h every 500 appends (memory and file)', st.t[0].length < 500 && st.t[0][0].ts >= t0 + 999 * 60 - 6 * 3600 && raw.length === st.t[0].length && raw.rest === 0, `${st.t[0].length} in memory, ${raw.length} in file`); +check('tierFor: 1 h raw, 24 h minute, 30 d hour, 2 y day', [3600, 86400, 30 * 86400, 730 * 86400].map(r => st.tierFor(fake - r, fake)).join() === '0,1,2,3'); +st = new HistoryStore(d); +check('reload drops expired raw points', st.t[0].every(p => p.ts >= fake - 6 * 3600) && st.t[0].length === 361, st.t[0].length); +const s = stats([{ nUp: 1, avg: [1], max: [5] }, { nUp: 3, avg: [3], max: [4] }, { nUp: 0, avg: [9], max: [9] }, { nUp: 1, avg: [NaN], max: [NaN] }], 0); +check('stats: weighted average, min, p95, peak', s.avg === 2.5 && s.min === 1 && s.p95 === 3 && s.max === 5 && s.count === 2, JSON.stringify(s)); +Date.now = realNow, done(); diff --git a/dev/tests/web/t_parse_win.js b/dev/tests/web/t_parse_win.js new file mode 100644 index 0000000000000000000000000000000000000000..1d8b331a54c76a0a4b928c2f4a5fec09f7e74bbc --- /dev/null +++ b/dev/tests/web/t_parse_win.js @@ -0,0 +1,58 @@ +// Windows frame parser against SPEC §5 with hand-computed values. node t_parse_win.js +const path = require('path'), { check, done } = require('./lib'); +const plat = require(path.join(process.argv[2], 'core/platform.js')); +const near = (a, b, eps = 1e-6) => Math.abs(a - b) <= eps * Math.max(1, Math.abs(b)); +const GB = 2 ** 30; +const frame = (ts, o = {}) => ['@@SNAP_BEGIN', ...(o.info ? ['@@S info', 'hostname=H1', 'os=Win Server', 'kernel=10.0.1', 'arch=64-bit', 'cpumodel=Xeon = fast', 'mhz=2500', 'virt=VM', 'admin=1', '@@S users', '10|DOM\\alice', '20|'] : []), + '@@S os', `ts=${ts}`, `uptime=${o.uptime ?? 1000}`, `memtotal=${16 * GB}`, `swaptotal=${8 * GB}`, `swapfree=${6 * GB}`, + '@@S cpu', '1|30|20|10|2|100', `_Total|${o.cpu ?? 50}|35|15|5|4000`, '10|70|50|20|8|300', '0|50|35|15|5|200', '2|', // core "2" has empty fields + '@@S sys', `queue=${o.queue ?? 2}`, 'ctxt=9000', 'threads=777', + '@@S mem', `avail=${4 * GB}`, `free=${GB}`, `standby=${3 * GB}`, `syscache=${GB}`, `modified=${GB / 2}`, `pool=${GB / 4}`, 'commit=1', 'commitlimit=2', 'pages=3', + '@@S net', `Ethernet|Up|10000|Ethernet|${o.rx ?? 1000}|${o.tx ?? 500}|${o.rxp ?? 10}|20|1|2|Microsoft Hyper-V Network Adapter`, 'Loop|Up|1073|Loopback|5|5|5|5|0|0|Software Loopback', + 'vEthernet (WSL)|Down|0|Ethernet|9|9|9|9|0|0|Hyper-V Virtual Ethernet Adapter', 'Tun0|Dormant|0|Tunnel|0|0|0|0|0|0|Teredo', 'Aaa|NotPresent||Wireless80211|0|0|0|0|||', + '@@S tcp', 'Established 40', 'TimeWait 3', 'CloseWait 1', 'Listen 27', 'SynSent 2', + '@@S disk', '0 C:|100|200|3|4|80', '1 D:|10|20|1|2|', '2 E:|1|1|1|1|130', '3 F:|1|1|1|1|-5', + '@@S df', `C:\\|System|NTFS|${100 * GB}|${25 * GB}`, `D:\\|Data|NTFS|${200 * GB}|${180 * GB}`, 'E:\\|Empty|NTFS|0|0', + '@@S procs', '0|0|999999|0|4|0|1|1|System Idle Process', `4|0|${o.p4 ?? 0}|8|100|0|${GB}|${GB / 8}|System`, `10|4|${o.p10 ?? 0}|13|5|${o.born ?? 0}|${2 * GB}|${GB}|sql server.exe`, + ...(o.newProc ? ['30|4|50|8|1|0|1|1|new.exe'] : []), `20|4|${o.p20 ?? 0}|6|7|0|1|${GB / 2}|idle.exe`, + '@@S sessions', '3', + ...(o.services ? ['@@S services', 'A|Running|Auto|0|Service A', 'B|Stopped|Auto|1067|Service B', 'C|Stopped|Auto|1077|Never started', 'D|Stopped|Manual|5|Manual stopped', 'E|Stopped|Auto||No code', 'F|Start Pending|Auto|0|Starting', 'G|Stopped|Disabled|1|Disabled'] : []), + '@@S thermal', 'TZ00|45.5', 'TZ00|50', 'TZ01|0', 'TZ02|151', 'TZ|03|60', + ...(o.gpu ? ['@@S gpu', '0, NVIDIA RTX, 55, 1000, 8000, 60, 120.5, 30'] : []), '@@SNAP_END'].join('\r\n'); +const st = {}, T = 1700000000000; +let m = plat.parse(frame(T, { info: true, services: true, gpu: true, p10: 1e7, p20: 0 }), st, 1); +check('first frame: valid=false, load = instant (cpu/100 × cores + queue)', m.valid === false && near(m.load1, 0.5 * 4 + 2) && m.load5 === m.load1 && m.load15 === m.load1, `load ${m.load1}`); +check('info: hostname, os, kernel, arch, cpu model (with "="), virt', m.hostname === 'H1' && m.os === 'Win Server' && m.kernel === '10.0.1' && m.arch === '64-bit' && m.cpuModel === 'Xeon = fast' && m.virt === 'VM'); +m = plat.parse(frame(T + 2000, { cpu: 80, queue: 1, rx: 1000 + 4000, tx: 500 + 1000, rxp: 30, p4: 4e7, p10: 1e7 + 1.5e7, p20: 1e5, born: (T + 2000) / 1000 - 600, newProc: true }), st, 2); +const inst = 0.8 * 4 + 1, ema = T_ => 4 + (inst - 4) * (1 - Math.exp(-2 / T_)); +check('second frame is valid; cached info kept', m.valid && m.hostname === 'H1' && m.uptime === 1000); +check('cpu: usage, user, irq, system = privileged − irq, interrupts/s, iowait = steal = 0', m.cpuUsage === 80 && m.cpuUser === 35 && m.cpuIrq === 5 && m.cpuSystem === 10 && m.intrPerSec === 4000 && m.cpuIowait === 0 && m.cpuSteal === 0); +check('cores sorted by number, mhz from info, cpuCount', m.cpuCount === 4 && m.cores.map(c => c.usage).join() === '50,30,0,70' && m.cores.every(c => c.mhz === 2500) && m.avgMhz === 2500, m.cores.map(c => c.usage).join()); +check('load averages: exponential moving averages with T = 60, 300, 900 s', near(m.load1, ema(60)) && near(m.load5, ema(300)) && near(m.load15, ema(900)), `${m.load1} ${m.load5} ${m.load15}`); +check('procsRunning = round(cpu/100 × cores), procsBlocked = queue, ctxt', m.procsRunning === 3 && m.procsBlocked === 1 && m.ctxtPerSec === 9000); +check('memory: available, free, cached = standby + syscache, slab = pool, dirty = modified, used, percent', m.memTotal === 16 * GB && m.memAvailable === 4 * GB && m.memFree === GB && m.cached === 4 * GB && m.buffers === 0 && m.shared === 0 && m.slab === GB / 4 && m.dirty === GB / 2 && m.memUsed === 12 * GB && m.memPct === 75); +check('swap: used = total − free, percent', m.swapTotal === 8 * GB && m.swapUsed === 2 * GB && m.swapPct === 25); +const eth = m.nets.find(n => n.name === 'Ethernet'); +check('net: rates from counter deltas / dt', eth.rxBps === 2000 && eth.txBps === 500 && eth.rxPps === 10 && eth.txPps === 0 && eth.rxBytes === 5000 && eth.errors === 1 && eth.drops === 2 && eth.speed === 10000 && eth.state === 'up'); +check('net: virtual = Loopback / Tunnel type or name+description pattern; a Hyper-V VM NIC is physical', m.nets.map(n => `${n.name}:${+n.virt}`).join() === 'Aaa:0,Ethernet:0,Loop:1,Tun0:1,vEthernet (WSL):1', m.nets.map(n => `${n.name}:${+n.virt}:${n.state}`).join()); +check('net: totals over physical interfaces only; states lower-cased', m.netRxBps === 2000 && m.netTxBps === 500 && m.nets.find(n => n.name === 'Tun0').state === 'dormant' && m.nets.find(n => n.name === 'vEthernet (WSL)').state === 'down'); +check('tcp: names mapped, others upper-cased, socketsUsed = sum', m.tcp.ESTABLISHED === 40 && m.tcp.TIME_WAIT === 3 && m.tcp.CLOSE_WAIT === 1 && m.tcp.LISTEN === 27 && m.tcp.SYNSENT === 2 && m.socketsUsed === 73, JSON.stringify(m.tcp)); +check('disk: util = clamp(100 − idle), 0 without idle; sums; busiest', m.disks.map(d => d.util).join() === '20,0,0,100' && m.diskReadBps === 112 && m.diskWriteBps === 222 && m.maxDiskUtil === 100 && m.busiestDisk === '3 F:' && m.disks[0].readIops === 3 && m.disks[0].totalRead === 0, m.disks.map(d => d.util).join()); +check('df: device = label, used = total − free, percent, fullest; empty volume skipped', m.mounts.length === 2 && m.mounts[0].device === 'System' && m.mounts[0].used === 75 * GB && m.mounts[0].avail === 25 * GB && m.mounts[0].pct === 75 && m.maxDiskPct === 75 && m.fullestMount === 'C:\\' && m.mounts[0].type === 'NTFS'); +const P = Object.fromEntries(m.procs.map(p => [p.pid, p])); +check('procs: pid 0 skipped; cpu % of one core = Δ100ns / 1e7 / dt × 100; clamped to 100 × cores', !(0 in P) && near(P[10].cpu, 75) && near(P[20].cpu, 0.5) && P[4].cpu === 200 || near(P[4].cpu, 200), `${P[4].cpu} ${P[10].cpu} ${P[20].cpu}`); +check('procs: state R above 0.5 %, nice = priority, age = now − created (0 unknown), user, memory %', P[10].state === 'R' && P[20].state === 'S' && P[10].nice === 13 && near(P[10].age, 600) && P[4].age === 0 && P[10].user === 'DOM\\alice' && P[20].user === '—' && P[4].user === '—' && P[10].memPct === 6.25 && P[10].name === 'sql server.exe' && P[10].ppid === 4 && P[10].rss === GB && P[10].vsz === 2 * GB); +check('procs: sorted by cpu then rss; threads total; forks/s = new pids / dt', m.procs.map(p => p.pid).join() === '4,10,20,30' && m.threadsTotal === 113 && m.forksPerSec === 0.5, m.procs.map(p => p.pid).join() + ' forks ' + m.forksPerSec); +const S = Object.fromEntries(m.services.map(s => [s.unit, s])); +check('services (cached list): failed only for Auto + Stopped + exit code not 0 / 1077', 'ABCDEFG'.split('').map(k => S[k].active).join() === 'active,failed,inactive,inactive,inactive,inactive,inactive' && S.A.sub === 'running' && S.F.sub === 'start pending' && S.B.load === 'Auto' && S.B.description === 'Service B' && m.servicesFailed === 1 && m.servicesRunning === 1, 'ABCDEFG'.split('').map(k => S[k].active).join()); +check('thermal: 0 < t ≤ 150, unique names (name may contain "|")', m.temps.map(t => `${t.name}=${t.celsius}`).join() === 'TZ00=45.5,TZ|03=60' && m.maxTemp === 60, m.temps.map(t => `${t.name}=${t.celsius}`).join()); +check('gpu list cached from the earlier frame; sessions', m.gpus.length === 1 && m.gpus[0].name === 'NVIDIA RTX' && m.gpus[0].util === 55 && m.gpus[0].power === 120.5 && m.loggedUsers === 3); +const before = [...st.load]; +m = plat.parse(frame(T + 1000, { cpu: 80, queue: 1 }), st, 3); // the collector clock went back +check('clock set back: no rates, load unchanged, frame not valid', !m.valid && near(m.load1, before[0]) && m.procs.every(p => p.cpu === 0) && m.forksPerSec === 0, `valid ${m.valid} load ${m.load1}`); +m = plat.parse(frame(T + 3000, { uptime: 0 }), st, 4); +check('frame without uptime is ignored', m.uptime === 0 && !m.valid); +m = plat.parse('@@SNAP_BEGIN\n@@S os\nts=' + (T + 9000) + '\nuptime=5\n', st, 5); +check('frame with missing sections does not throw; every missing value is 0', m.valid && m.cpuCount === 1 && m.memPct === 0 && m.procs.length === 0 && m.services.length === 7); +check('protected processes', ['System', 'lsass.exe', 'svchost.exe', 'sshd.exe'].every(name => plat.isProtected({ pid: 500, rss: 1, name })) && plat.isProtected({ pid: 4, rss: 1, name: 'x' }) && plat.isProtected({ pid: 500, rss: 0, name: 'x' }) && !plat.isProtected({ pid: 500, rss: 1, name: 'w3wp.exe' })); +done(); diff --git a/dev/tests/web/t_security.js b/dev/tests/web/t_security.js new file mode 100644 index 0000000000000000000000000000000000000000..ae3d82cc50c18c2d26bb8342eb342deaa379f7c6 --- /dev/null +++ b/dev/tests/web/t_security.js @@ -0,0 +1,77 @@ +// Tries to get past the local-only API. node t_security.js +// Uses the scratch config (local1 online, ssh1 unreachable). Commands are built for the unreachable server (never executed) or are +// read-only (service logs) on the local one. +const fs = require('fs'), net = require('net'), path = require('path'), { sleep, client, check, done } = require('./lib'); +const [port, cfg, root, os] = process.argv.slice(2), win = os === 'Windows', { req, post, state } = client(port), dir = path.join(cfg, 'ServerMonitorWeb'); +const raw = text => new Promise(resolve => { // a request exactly as written + const s = net.connect(port, '127.0.0.1', () => s.write(text)); let d = ''; + s.setEncoding('utf8').on('data', x => d += x).on('close', () => resolve(d)).on('error', () => resolve(d)); setTimeout(() => s.destroy(), 1500); +}); +(async () => { + const src = fs.readFileSync(path.join(root, 'server.js'), 'utf8'), routes = [...src.slice(src.indexOf('const POST')).matchAll(/'(\/api\/[a-z/.]+)':/g)].map(m => m[1]); + const before = JSON.stringify((await state()).servers.map(s => [s.cfg, s.status === 'Disabled', s.paused])), file = fs.readFileSync(path.join(dir, 'servers.json'), 'utf8'); + // 1. Host / Origin + const hosts = ['evil.example', `evil.example:${port}`, `127.0.0.1:${port}.evil.example`, `127.0.0.1.evil.example:${port}`, `LOCALHOST:${port}`, `localhost.:${port}`, `[::1]:${port}`, `0.0.0.0:${port}`, `127.0.0.1`, `127.0.0.1:${+port + 1}`, `127.1:${port}`]; + let bad = []; + for (const h of hosts) for (const [m, p, b] of [['GET', '/'], ['GET', '/api/state'], ['GET', '/app.js'], ['POST', '/api/alerts/clear', {}]]) { const r = await req(m, p, b, { Host: h }); if (r.status !== 403) bad.push(`${h} ${p} -> ${r.status}`); } + check(`${hosts.length} foreign or malformed Host values are refused on pages, files and API`, !bad.length, bad.join('; ')); + const noHost = await raw(`GET /api/state HTTP/1.0\r\n\r\n`), twoHosts = await raw(`GET /api/state HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nHost: evil.example\r\n\r\n`); + check('no Host header is refused (a second Host header is ignored by Node: reported)', /^HTTP\/1\.1 40[03]/.test(noHost), noHost.split('\r\n')[0] + ' / ' + twoHosts.split('\r\n')[0]); + bad = []; + for (const o of ['http://evil.example', 'null', `https://127.0.0.1:${port}`, `http://127.0.0.1:${+port + 1}`, `http://127.0.0.1:${port}.evil.example`, `http://evil.example/http://127.0.0.1:${port}`, `http://localhost`, 'file://', `http://http://127.0.0.1:${port}`]) + for (const [m, p, b] of [['GET', '/api/state'], ['GET', '/api/events'], ['POST', '/api/alerts/clear', {}], ['POST', '/api/exec', { id: 'local1', cmd: 'echo x' }]]) { const r = await req(m, p, b, { Origin: o }); if (r.status !== 403) bad.push(`${o} ${p} -> ${r.status}`); } + check('9 foreign Origin values are refused (also for GET and the event stream)', !bad.length, bad.join('; ')); + const same = await req('POST', '/api/server/analyze', { id: 'local1' }, { Origin: `http://127.0.0.1:${port}` }), sameL = await req('GET', '/api/state', undefined, { Origin: `http://localhost:${port}`, Host: `localhost:${port}` }); + check('the page\'s own Origin is accepted', same.status === 200 && sameL.status === 200); + // 2. custom header rule on every state-changing route; other methods + bad = []; + for (const r of routes) { + for (const [what, h] of [['no X-SM', { 'X-SM': '' }], ['X-SM: 0', { 'X-SM': '0' }], ['text/plain', { 'Content-Type': 'text/plain' }], ['form', { 'Content-Type': 'application/x-www-form-urlencoded' }], ['application/jsonx', { 'Content-Type': 'application/jsonx' }]]) { + const x = await req('POST', r, { id: 'local1', cmd: 'echo x', paused: true, delta: 1, deleteHistory: true, name: 'n', transport: 0 }, h); + if (x.status !== 403) bad.push(`${r} ${what} -> ${x.status}`); + } + for (const m of ['GET', 'PUT', 'DELETE', 'PATCH', 'OPTIONS', 'HEAD']) { const x = await req(m, r, m === 'GET' || m === 'HEAD' ? undefined : { id: 'local1' }); if (x.status !== 404) bad.push(`${m} ${r} -> ${x.status}`); } + } + check(`all ${routes.length} POST routes: 403 without the custom header or JSON type; no other method reaches them`, routes.length >= 14 && !bad.length, bad.join('; ') || routes.join(' ')); + check('nothing changed by the refused requests', JSON.stringify((await state()).servers.map(s => [s.cfg, s.status === 'Disabled', s.paused])) === before && fs.readFileSync(path.join(dir, 'servers.json'), 'utf8') === file); + const all = [await req('GET', '/'), await req('GET', '/api/state'), await req('POST', '/api/alerts/clear', {}), await req('OPTIONS', '/api/exec', undefined, { Origin: 'http://evil.example', 'Access-Control-Request-Method': 'POST' }), await req('GET', '/nope')]; + check('no CORS header on any reply; security headers on all', all.every(r => !Object.keys(r.headers).some(h => h.startsWith('access-control')) && r.headers['x-content-type-options'] === 'nosniff' && /frame-ancestors 'none'/.test(r.headers['content-security-policy']) && r.headers['cross-origin-resource-policy'] === 'same-origin')); + // 3. static files + bad = []; + for (const p of ['/../server.js', '/..%2fserver.js', '/%2e%2e/server.js', '/%2e%2e%2fserver.js', '//server.js', '/public/../server.js', '/app.js/../../server.js', '/..\\server.js', '/%5c..%5cserver.js', '/core/platform.js', '/server.js', '/README.md', '/app.js%00', '/app.js/', '/./app.js/.', '/.', '/index.html/..', '/%00', '/__proto__', '/constructor', '/api/__proto__', '/api/../server.js']) { + const r = await raw(`GET ${p} HTTP/1.1\r\nHost: 127.0.0.1:${port}\r\nConnection: close\r\n\r\n`), status = +r.split(' ')[1]; + if (/require\(|createServer|Server Monitor \(web/.test(r) && !//i.test(r) || ![200, 400, 404].includes(status) || (status === 200 && !/|Server Monitor page/i.test(r))) bad.push(`${p} -> ${status}`); + } + check('22 traversal and odd paths serve nothing outside public/', !bad.length, bad.join('; ')); + // 4. bodies + bad = []; + for (const b of ['null', '[]', '"x"', '123', 'true', '{"id":{"$ne":1}}', '{"id":["local1"]}', '{"__proto__":{"polluted":1},"id":"x"}', '{"constructor":{"prototype":{"polluted":1}}}']) for (const r of routes) { + const x = await req('POST', r, b); + if (x.status >= 500 || ({}).polluted) bad.push(`${r} ${b} -> ${x.status} ${x.text.slice(0, 60)}`); + } + check('odd JSON bodies on every route: no server error', !bad.length, bad.slice(0, 6).join('; ')); + const s1 = await state(); + check('odd bodies changed nothing but the event list', s1.servers.length === 2 || s1.servers.every(s => s.cfg.id), s1.servers.map(s => s.cfg.name).join()); + for (const s of s1.servers.filter(s => !['local1', 'ssh1'].includes(s.cfg.id))) await post('server/remove', { id: s.cfg.id, deleteHistory: true }); // "add" accepted {name?}: none expected + const run = await req('POST', '/api/run', { id: 'ssh1', list: '__proto__', i: 0, arg: 1 }), run2 = await req('POST', '/api/run', { id: 'ssh1', list: 'procActions', i: '__proto__', arg: 1 }), run3 = await req('POST', '/api/run', { id: 'ssh1', list: 'diagnostics', i: 0, arg: 1 }); + check('command tables cannot be addressed through prototype keys or other lists', [run, run2, run3].every(r => r.status === 400), [run, run2, run3].map(r => r.status).join()); + const big = await req('POST', '/api/exec', JSON.stringify({ id: 'ssh1', cmd: 'x'.repeat(3 << 20) })).catch(e => ({ status: 0, text: e.code })); + check('a 3 MB body is cut off', big.status === 0 || big.status >= 400, `${big.status} ${big.text}`); + check('the server still answers', (await req('GET', '/api/state')).status === 200); + // 5. quoting of names (commands for the unreachable server are returned, not run) + const nasty = `a'b"c$(touch ${cfg}.pwned)\`touch ${cfg}.pwned\`;touch ${cfg}.pwned|&\n$HOME %PATH% -rf`; + const svc = (await post('run', { id: 'ssh1', list: 'serviceActions', i: 0, arg: nasty })).cmd; + const expect = win ? `Start-Service -Name '${nasty.replace(/'/g, "''")}'` : `systemctl start '${nasty.replace(/'/g, "'\\''")}'`; + check('service name is one quoted argument in the command', svc === expect, JSON.stringify(svc)); + const logs = await post('logs', { id: 'local1', unit: nasty, lines: '50; touch ' + cfg + '.pwned' }); + await sleep(500); + check('service logs with a hostile name and line count: nothing is injected', !fs.existsSync(cfg + '.pwned') && typeof logs.out === 'string', JSON.stringify(logs.out.slice(0, 120))); + if (win) { const l = fs.readFileSync(cfg + '.log', 'utf8'); check('PowerShell: the name arrives single-quoted with doubled quotes, lines as a number', l.includes(`Where-Object Name -eq '${nasty.replace(/'/g, "''").split('\n')[0]}`) && /Select-Object -First 50 \|/.test(l)); } + const pid = (await post('run', { id: 'ssh1', list: 'procActions', i: 1, arg: '4242' })).cmd, prio = (await post('run', { id: 'ssh1', list: 'priorities', i: 0, arg: 77 })).cmd; + check('pid commands take digits only', pid === (win ? 'taskkill /F /PID 4242' : 'kill -KILL 4242') && prio === (win ? "(Get-Process -Id 77).PriorityClass = 'Idle'" : 'renice -n -20 -p 77') && (await req('POST', '/api/run', { id: 'ssh1', list: 'procActions', i: 1, arg: '1 2' })).status === 400, `${pid} | ${prio}`); + // 6. file modes + const mode = f => (fs.statSync(f).mode & 0o777).toString(8); + await post('server/update', { id: 'ssh1', notes: 'saved' }); + check('servers.json is 600 after a save (whatever it was before)', mode(path.join(dir, 'servers.json')) === '600'); + done(); +})(); diff --git a/dev/tests/web/t_session.js b/dev/tests/web/t_session.js new file mode 100644 index 0000000000000000000000000000000000000000..58780603d6b4362b278da9a59539bb33a13a2f95 --- /dev/null +++ b/dev/tests/web/t_session.js @@ -0,0 +1,95 @@ +// session lifecycle on the Windows edition with the review stand-in powershell (nothing real runs; dry run is on). +// node t_session.js +const fs = require('fs'), http = require('http'), { execSync } = require('child_process'), { sleep, client, check, done } = require('./lib'); +const [port, cfg] = process.argv.slice(2), { req, post, state } = client(port), ctl = w => fs.writeFileSync(cfg + '.ctl', w), log = () => fs.readFileSync(cfg + '.log', 'utf8'); +const srv = async () => (await state()).servers.find(s => s.cfg.id === 'win1'), alerts = async () => (await state()).alerts; +const until = async (fn, ms) => { for (const t0 = Date.now(); Date.now() - t0 < ms; await sleep(250)) { const v = await fn(); if (v) return v; } return false; }; +const t0 = Date.now(), at = () => ((Date.now() - t0) / 1000).toFixed(1) + ' s'; +const trail = []; // status changes seen on the state stream +http.get({ host: '127.0.0.1', port, path: '/api/events' }, res => { let buf = '', last; res.setEncoding('utf8').on('data', d => { buf += d; for (let i; (i = buf.indexOf('\n\n')) >= 0; buf = buf.slice(i + 2)) { const [e, data] = buf.slice(0, i).split('\n'); if (e === 'event: state') { const s = JSON.parse(data.slice(6)).find(x => x.cfg.id === 'win1'); if (s && s.status !== last) trail.push([Date.now(), last = s.status]); } } }); }); +const fakes = () => execSync(`pgrep -c -f "^python3 .*/fake/powershell" || true`).toString().trim(); +(async () => { + let s = await srv(); + check('online with a valid sample', s.status === 'Online' && s.online && s.m.cpuCount === 2, `${s.status}, load ${s.m.load1}`); + // the "already failed when monitoring started" rule + dry run + await post('server/analyze', { id: 'win1' }); + const an = async () => { const r = await new Promise(res => http.get({ host: '127.0.0.1', port, path: '/api/events?id=win1' }, r => { let b = ''; r.setEncoding('utf8').on('data', d => { b += d; const ev = b.split('\n\n').slice(0, -1).find(e => e.startsWith('event: live\n')); if (ev) r.destroy(), res(JSON.parse(ev.split('\n')[1].slice(6))); }); })); return r; }; // the "live" event follows "hello" + let a = (await an()).an, f = a.findings.find(x => x.key === 'svc:BrokenSvc'); + check('service that was failed at the start: finding, never auto-eligible', f && !f.autoEligible && /already failed when monitoring started/.test(f.detail), f && f.detail); + check('service with an empty exit code is not "failed"', !a.findings.some(x => x.key === 'svc:gupdate')); + ctl('failsvc'), await sleep(3500), await post('server/analyze', { id: 'win1' }); + a = (await an()).an, f = a.findings.find(x => x.key === 'svc:Spooler'); + check('service that fails while monitored: auto-eligible', f?.autoEligible && /Failed 1× in the last hour/.test(f.detail), f && f.detail); + for (let i = 0; i < 3; ++i) await post('server/analyze', { id: 'win1' }); + let ev = (await alerts()).filter(e => e.severity === 'action'); + check('dry run: one "would: Restart" event for Spooler (cooldown), none for BrokenSvc, nothing executed', ev.length === 1 && /Autopilot \(dry run\) would: Restart - Service Spooler has failed/.test(ev[0].message) && !/Restart-Service/.test(log()), ev.map(e => e.message).join(' | ')); + ctl('nosvc'), await sleep(3500), await post('server/analyze', { id: 'win1' }); + a = (await an()).an; + check('a service that left the list is forgotten', !a.findings.some(x => x.key === 'svc:Spooler') && a.findings.some(x => x.key === 'svc:BrokenSvc'), a.findings.map(x => x.key).join()); + ctl('ok'); + + // pending commands when the link is dropped + let p = post('exec', { id: 'win1', cmd: 'HANG' }), t = Date.now(); + await sleep(700), await post('server/reconnect', { id: 'win1' }); + let r = await p; + check('Reconnect fails a pending command at once', r.code === -1 && Date.now() - t < 3000, `${JSON.stringify(r)} after ${Date.now() - t} ms`); + check('online again after Reconnect', await until(async () => (await srv()).online, 6000)); + r = await post('exec', { id: 'win1', cmd: 'EXIT3' }); + check('exit code and output of a command', r.code === 3 && /would run/.test(r.out), r.code); + + // watchdog: the collector stays alive but sends nothing (interval 1 s -> 15 s) + ctl('stall'), t = Date.now(); + p = (async () => { await sleep(3000); return post('exec', { id: 'win1', cmd: 'HANG' }); })(); + const lost = await until(async () => (await srv()).status !== 'Online' && Date.now(), 25000); + s = await srv(); + check('watchdog: no data for 15 s -> Offline', lost && lost - t > 13000 && lost - t < 19000 && /no data received/.test(s.err), `${((lost - t) / 1000).toFixed(1)} s: ${s.err}`); + r = await p; + check('a command pending when the link is lost fails with the reason', r.code === -1 && /connection lost: no data received/.test(r.out), JSON.stringify(r)); + r = await post('exec', { id: 'win1', cmd: 'echo x' }); + check('command while offline', r.code === -1 && r.out === 'server is not connected'); + // back-off: reconnect attempts after 3, 5, 10 s (each attempt runs into the 25 s start watchdog while stalled, so switch to "die") + ctl('die'); + const mark = Date.now() / 1000; + await sleep(45000); + const starts = log().split('\n').filter(l => l.startsWith('COLLECTOR')).map(l => +l.split(' ')[1]).filter(x => x > mark - 30), gaps = starts.slice(1).map((x, i) => Math.round(x - starts[i])); + const first = starts.find(x => x > lost / 1000) - lost / 1000; + check('reconnect back-off: attempts 3, 5, 10, 20 s after each failure', Math.round(first) === 3 && gaps.slice(-3).join() === '5,10,20', `first retry ${first.toFixed(1)} s after the loss, then ${gaps.slice(-3).join(', ')} s; error: ${(await srv()).err}`); + ev = await alerts(); + check('one "unreachable" alert for the whole outage', ev.filter(e => /Server is unreachable/.test(e.message)).length === 1, ev.filter(e => e.severity === 'critical').map(e => e.message).join(' | ')); + check('card shows the collector\'s error text', /boom: cannot collect/.test((await srv()).err), (await srv()).err); + const rawBefore = fs.statSync(`${cfg}/ServerMonitorWeb/history/win1/raw.bin`).size; + await sleep(5000); + const down = (fs.statSync(`${cfg}/ServerMonitorWeb/history/win1/raw.bin`).size - rawBefore) / 136; + check('downtime recorded once per interval while offline or reconnecting', down >= 4 && down <= 6, down + ' records in 5 s'); + ctl('ok'), await post('server/reconnect', { id: 'win1' }), t = Date.now(); + check('back online', await until(async () => (await srv()).online, 8000)); + await sleep(500); + ev = await alerts(), a = (await an()).an; + check('"back online" event', ev.some(e => e.severity === 'resolved' && /back online/.test(e.message))); + check('analysis ran with the first valid sample (no "server unreachable" left)', a.when * 1000 >= t - 1000 && !a.healthReasons.some(x => /unreachable/.test(x)), `analyzed ${((Date.now() - a.when * 1000) / 1000).toFixed(0)} s ago: ${a.healthReasons.join('; ')}`); + const f24 = a.findings.find(x => x.key === 'avail24'); + check('"could not be reached for about …" is the measured downtime, not a share of 24 h', f24 && /about (\d+m )?\d+s in the last day/.test(f24.detail), f24 ? `${f24.title} / ${f24.detail} / down ${a.down}` : 'no finding, up ' + a.up); + + // pause, config change, remove with a command in flight + await post('server/pause', { id: 'win1', paused: true }); + const n1 = fs.statSync(`${cfg}/ServerMonitorWeb/history/win1/raw.bin`).size; await sleep(2500); + check('paused: nothing recorded', fs.statSync(`${cfg}/ServerMonitorWeb/history/win1/raw.bin`).size === n1 && (await srv()).paused); + await post('server/pause', { id: 'win1', paused: false }); + p = post('exec', { id: 'win1', cmd: 'HANG' }), t = Date.now(); + await sleep(600), await post('server/update', { id: 'win1', interval: 2 }); + r = await p; + check('changing the interval restarts the link and fails the pending command', r.code === -1 && Date.now() - t < 3000, JSON.stringify(r)); + check('online again', await until(async () => (await srv()).online, 8000)); + p = post('exec', { id: 'win1', cmd: 'HANG' }), t = Date.now(); + const hist = post('server/analyze', { id: 'win1' }); + await sleep(600), await post('server/remove', { id: 'win1', deleteHistory: true }); + r = await p, await hist; + check('removing the server fails the pending command', r.code === -1 && Date.now() - t < 3000, `${JSON.stringify(r)} after ${Date.now() - t} ms`); + await sleep(800); + check('no helper process is left, history folder deleted, list saved', fakes() === '0' && !fs.existsSync(`${cfg}/ServerMonitorWeb/history/win1`) && JSON.parse(fs.readFileSync(`${cfg}/ServerMonitorWeb/servers.json`)).servers.length === 0, `${fakes()} stand-in processes`); + r = await req('POST', '/api/exec', { id: 'win1', cmd: 'x' }); + const gone = await new Promise(res => http.get({ host: '127.0.0.1', port, path: '/api/events?id=win1' }, x => { let b = ''; x.setEncoding('utf8').on('data', d => b += d); setTimeout(() => (x.destroy(), res(b)), 1500); })); + check('requests for the removed server -> 404; its stream is a plain one (hello, no live)', r.status === 404 && (await req('GET', '/api/history?id=win1&range=3600')).status === 404 && gone.startsWith('event: hello') && !gone.includes('event: live')); + console.log('server stderr:', JSON.stringify(fs.readFileSync(cfg + '.err', 'utf8').slice(0, 500))); + done(), process.exit(0); +})(); diff --git a/dev/tests/web/t_ssh.js b/dev/tests/web/t_ssh.js new file mode 100644 index 0000000000000000000000000000000000000000..34145d65a5fe186f7ca1990b7e4decabd233be98 --- /dev/null +++ b/dev/tests/web/t_ssh.js @@ -0,0 +1,57 @@ +// ssh transport with a stand-in ssh that logs its arguments and runs the command line on this machine (read-only collector; dry run on). +// node t_ssh.js +const fs = require('fs'), path = require('path'), { sleep, client, check, done } = require('./lib'); +const [port, cfg, os] = process.argv.slice(2), win = os === 'Windows', { req, post, state } = client(port), dir = path.join(cfg, 'ServerMonitorWeb'); +const calls = () => fs.readFileSync(cfg + '.sshlog', 'utf8').split('\n').filter(Boolean).map(JSON.parse); +const until = async (fn, ms) => { for (const t0 = Date.now(); Date.now() - t0 < ms; await sleep(250)) { const v = await fn(); if (v) return v; } return false; }; +const SECRET = "S3cr3t'pw \"$HOME\" & %PATH% !x! ^<>|", OPTS = ['-o', 'ConnectTimeout=10', '-o', 'ServerAliveInterval=10', '-o', 'ServerAliveCountMax=3', '-o', 'StrictHostKeyChecking=accept-new', '-o', 'LogLevel=ERROR']; +(async () => { + let s = await state(); + check('first start: "This computer" (local) is created', s.servers.length === 1 && s.servers[0].cfg.name === 'This computer' && s.servers[0].cfg.transport === 0 && s.servers[0].cfg.group === 'Local' && s.servers[0].cfg.interval === (win ? 3 : 2)); + const mode = f => (fs.statSync(f).mode & 0o777).toString(8); + check('config folder 700, servers.json 600', mode(dir) === '700' && mode(path.join(dir, 'servers.json')) === '600', `${mode(dir)} ${mode(path.join(dir, 'servers.json'))}`); + await post('server/update', { id: s.servers[0].cfg.id, autopilot: { ...s.servers[0].cfg.autopilot, dryRun: true } }); + for (const [what, b] of [['host starting with "-"', { host: '-oProxyCommand=touch /tmp/pwn' }], ['host " -o…" (spaces are trimmed first)', { host: ' -oProxyCommand=x' }], ['user starting with "-"', { host: 'h', user: '-oProxyCommand=x' }]]) { + const r = await req('POST', '/api/server/add', { name: 'x', transport: 1, ...b }), t = await req('POST', '/api/server/test', { name: 'x', transport: 1, ...b }); + check(`${what} is refused (add and test)`, r.status === 400 && t.status === 400, r.text); + } + check('nothing was started for the refused servers', !fs.existsSync(cfg + '.sshlog') && (await state()).servers.length === 1); + // key login: BatchMode, no askpass + const key = await post('server/add', { name: 'key box', transport: 1, host: 'fakehost', user: 'me', keyFile: '~/.ssh/-oProxyCommand=evil key', port: 22, interval: 1, autopilot: { dryRun: true } }); + await until(() => fs.existsSync(cfg + '.sshlog'), 5000); + let c = calls()[0], home = require('os').homedir(); + const shell = win ? 'powershell -NoLogo -NoProfile -NonInteractive -ExecutionPolicy Bypass -OutputFormat Text -EncodedCommand aQBlAHgAIAAoAEAAKAAkAGkAbgBwAHUAdAApACAALQBqAG8AaQBuACAAWwBjAGgAYQByAF0AMQAwACkA' : 'sh -s -- 1'; + check('ssh argv with a key: options, BatchMode, -i , -T user@host, command line', JSON.stringify(c.argv) === JSON.stringify([...OPTS, '-o', 'BatchMode=yes', '-i', home + '/.ssh/-oProxyCommand=evil key', '-T', 'me@fakehost', shell]), JSON.stringify(c.argv)); + check('no askpass environment without a password', !c.env.SSH_ASKPASS && !c.env.SERVERMONITOR_ASKPASS); + // password login + const pw = await post('server/add', { name: 'pw box', transport: 1, host: 'fake host;$(id)', user: '', port: 2222, password: SECRET, interval: 1, useSudo: true, autopilot: { dryRun: true } }); + c = await until(() => calls().find(x => x.argv.includes('2222')), 5000); + check('ssh argv with a password: NumberOfPasswordPrompts=1, -p, host kept as one argument', JSON.stringify(c.argv) === JSON.stringify([...OPTS, '-o', 'NumberOfPasswordPrompts=1', '-p', '2222', '-T', 'fake host;$(id)', shell]), JSON.stringify(c.argv)); + check('askpass environment: helper, force, password, DISPLAY', c.env.SSH_ASKPASS_REQUIRE === 'force' && c.env.SERVERMONITOR_ASKPASS === SECRET && !!c.env.DISPLAY && path.basename(c.env.SSH_ASKPASS) === (win ? 'askpass.cmd' : 'askpass.sh'), JSON.stringify({ ...c.env, SERVERMONITOR_ASKPASS: '…' })); + if (!win) check('askpass helper prints exactly the password; helper 700 in a 700 folder', c.askpass_answer === SECRET + '\n' && c.askpass_mode === '0o700 in 0o700', JSON.stringify(c.askpass_answer) + ' ' + c.askpass_mode); + else check('askpass.cmd: CRLF batch file that echoes the variable with delayed expansion', c.askpass_text === '@echo off\r\nsetlocal EnableDelayedExpansion\r\necho(!SERVERMONITOR_ASKPASS!\r\n', JSON.stringify(c.askpass_text)); + check('the password is in no argument', calls().every(x => !x.argv.join(' ').includes('S3cr3t'))); + // the stored password never reaches the browser + const b64 = JSON.parse(fs.readFileSync(path.join(dir, 'servers.json'))).servers.find(x => x.id === pw.id).password; + const texts = [(await req('GET', '/api/state')).text, (await req('GET', '/api/history?id=' + pw.id + '&range=3600')).text, (await req('GET', '/api/alerts.log')).text, fs.readFileSync(cfg + '.out', 'utf8') + fs.readFileSync(cfg + '.err', 'utf8')]; + const sse = p => new Promise(res => require('http').get({ host: '127.0.0.1', port, path: p }, r => { let b = ''; r.on('data', d => b += d); setTimeout(() => (r.destroy(), res(b)), 2500); })); + texts.push(await sse('/api/events'), await sse('/api/events?id=' + pw.id)); + check('stored password: obfuscated in servers.json, absent from every reply, stream and log', b64.length > 8 && !fs.readFileSync(path.join(dir, 'servers.json'), 'utf8').includes('S3cr3t') && texts.every(t => t.length > 0 || t === '') && texts.slice(0, 2).concat(texts.slice(4)).every(t => t.length > 50) && !texts.some(t => t.includes('S3cr3t') || t.includes(b64)), `${texts.map(t => t.length).join('/')} bytes searched`); + s = (await state()).servers.find(x => x.cfg.id === pw.id); + check('page gets hasPassword only', s.cfg.hasPassword === true && !('password' in s.cfg)); + if (!win) { + check('server over (stand-in) ssh comes online', await until(async () => (await state()).servers.find(x => x.cfg.id === pw.id).online, 8000)); + let r = await post('exec', { id: pw.id, cmd: 'echo "$0 over ssh"; echo err >&2; exit 4', privileged: false }); + check('one-shot command over ssh: stdin script, merged output, exit code', r.code === 4 && /over ssh\nerr\n/.test(r.out), JSON.stringify(r)); + const one = calls().at(-1); + check('one-shot ssh call runs "sh -s"', one.argv.at(-1) === 'sh -s', one.argv.at(-1)); + const t = await post('server/test', { id: pw.id, name: 'pw box', transport: 1, host: 'fake host;$(id)', port: 2222, password: '' }); + check('test connection of an edited server uses the stored password', t.ok && calls().at(-1).env.SERVERMONITOR_ASKPASS === SECRET && /Connected in \d+ ms — .+ · \d+ cores · .+ RAM · CPU \d+%/.test(t.text), t.text); + } + const dead = await post('server/test', { name: 'd', transport: 1, host: 'deadhost' }); + check('test connection: failure text is ssh\'s last error line', dead.ok === false && dead.text === '✗ ssh: connect to host deadhost port 22: Connection refused', dead.text); + await post('server/update', { id: pw.id, password: '', clearPassword: true, enabled: false }); + check('"remove stored" clears the password', JSON.parse(fs.readFileSync(path.join(dir, 'servers.json'))).servers.find(x => x.id === pw.id).password === '' && !(await state()).servers.find(x => x.cfg.id === pw.id).cfg.hasPassword); + await post('server/remove', { id: key.id, deleteHistory: true }), await post('server/remove', { id: pw.id, deleteHistory: true }); + done(); +})(); diff --git a/dev/tests/web/t_start.js b/dev/tests/web/t_start.js new file mode 100644 index 0000000000000000000000000000000000000000..1bf2971d6e746e81422d41758c2a416a9914e2f5 --- /dev/null +++ b/dev/tests/web/t_start.js @@ -0,0 +1,26 @@ +// start-up edge cases: port in use, damaged servers.json, entries that are not objects. node t_start.js +const fs = require('fs'), path = require('path'), { spawnSync, spawn } = require('child_process'), { sleep, client, check, done } = require('./lib'); +const [root, busy, free] = process.argv.slice(2), T = __dirname, name = `cfgT${Date.now()}`, cfg = path.join(T, name), dir = path.join(cfg, 'ServerMonitorWeb'); +const env = { ...process.env, XDG_CONFIG_HOME: cfg, APPDATA: cfg, PATH: `${T}/fake:${process.env.PATH}`, FAKE_CTL: cfg + '.ctl', FAKE_LOG: cfg + '.log' }; +(async () => { + fs.mkdirSync(dir, { recursive: true }), fs.writeFileSync(cfg + '.log', ''); + const before = fs.readdirSync(cfg).join(); + const r = spawnSync('node', [path.join(root, 'server.js')], { env: { ...env, PORT: busy }, encoding: 'utf8', timeout: 8000 }); + check('port in use: one clear line, exit code 1, nothing started or written', r.status === 1 && /^Cannot listen on 127\.0\.0\.1:\d+ .*EADDRINUSE/.test(r.stderr) && r.stderr.trim().split('\n').length === 1 && fs.readdirSync(dir).length === 0 && fs.readdirSync(cfg).join() === before, JSON.stringify(r.stderr.slice(0, 160))); + // damaged file: start empty, keep a copy; entries that are not objects are skipped + fs.writeFileSync(path.join(dir, 'servers.json'), '{"version":1,"servers":[{"id":"a","name":"kept?"'); + let p = spawn('node', [path.join(root, 'server.js')], { env: { ...env, PORT: free }, stdio: 'ignore' }); + const { state, post } = client(free); + await sleep(2500); + let s = await state().catch(() => null); + check('damaged servers.json: starts with an empty list and keeps a copy', s?.servers.length === 0 && fs.readFileSync(path.join(dir, 'servers.json.bad'), 'utf8').includes('kept?'), s ? s.servers.length + ' servers' : 'no answer'); + p.kill('SIGTERM'), await sleep(500); + fs.writeFileSync(path.join(dir, 'servers.json'), JSON.stringify({ version: 1, servers: [null, 5, 'x', [], { id: 'ok1', name: 'ok', transport: 1, host: 'h', enabled: false, autopilot: { dryRun: true } }, { name: 'no id', transport: 1, host: 'h', enabled: false, interval: 9999, rules: 'x', autopilot: 7 }] })); + p = spawn('node', [path.join(root, 'server.js')], { env: { ...env, PORT: free }, stdio: 'ignore' }); + await sleep(2500); + s = await state().catch(() => null); + check('odd entries are skipped or completed with defaults', s && s.servers.map(x => x.cfg.name).join() === ',ok,no id' && s.servers[2].cfg.interval === 300 && s.servers[2].cfg.rules.length === 7 && s.servers[2].cfg.id.length === 12 && s.servers[2].cfg.autopilot.maxRestartsPerHour === 3, s ? JSON.stringify(s.servers.map(x => [x.cfg.name, x.cfg.interval, x.cfg.rules.length])) : 'no answer'); + for (const x of s?.servers || []) if (!x.cfg.name) await post('server/remove', { id: x.cfg.id }); + p.kill('SIGTERM'); + done(); +})(); diff --git a/dev/tests/web/t_tabs.js b/dev/tests/web/t_tabs.js new file mode 100644 index 0000000000000000000000000000000000000000..18f290dc769aea72f9143bc4880dde6bd5d8efc7 --- /dev/null +++ b/dev/tests/web/t_tabs.js @@ -0,0 +1,13 @@ +// how many browser tabs can show a server page at once? (browsers allow 6 connections per site; live streams hold them) +const { launch, sleep } = require('./cdp'), base = process.argv[2]; +(async () => { + const b = await launch(), tabs = []; + for (let i = 0; i < 7; ++i) { + const t = i ? await b.newTab(base + '/#/server/0/overview') : await b.first(); + if (!i) await t.go(base + '/#/server/0/overview'); + tabs.push(t), await sleep(2500); + const r = await Promise.race([t.evaluate(`if (typeof S === 'undefined' || !S.plat) return 'page did not load'; const t0 = Date.now(); const r = await Promise.race([api('state').then(() => 'ok'), new Promise(r => setTimeout(() => r('request hangs'), 3000))]); return (S.m ? 'live data' : 'no live data') + ', API request: ' + r`), sleep(8000).then(() => 'page did not load')]); + console.log(`tab ${i + 1}: ${r}`); + } + b.close(), process.exit(0); +})(); diff --git a/dev/tests/web/t_ui.js b/dev/tests/web/t_ui.js new file mode 100644 index 0000000000000000000000000000000000000000..375a39570299a9dfd8fc324de4348ef06f185abf --- /dev/null +++ b/dev/tests/web/t_ui.js @@ -0,0 +1,64 @@ +// Page behaviour on the Windows edition with the review stand-in powershell: every text field of the "server" carries HTML. +// node t_ui.js +const fs = require('fs'), { launch, sleep } = require('./cdp'), { check, done } = require('./lib'); +const [base, cfg] = process.argv.slice(2), ctl = w => fs.writeFileSync(cfg + '.ctl', w), log = () => fs.readFileSync(cfg + '.log', 'utf8'); +const H = `const $ = (sel, root = document) => root.querySelector(sel), $$ = (sel, root = document) => [...root.querySelectorAll(sel)]; +const sleep = ms => new Promise(r => setTimeout(r, ms)), until = async (fn, ms = 6000) => { for (const t0 = Date.now(); Date.now() - t0 < ms; await sleep(100)) { const v = fn(); if (v) return v; } return fn(); }; +const page = () => $('main > section:not([hidden])'), tab = () => $('.tab', page()), dlg = () => $('dialog[open]'), byText = (sel, text, root = document) => $$(sel, root).find(e => e.textContent.trim() === text); +const down = el => el.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })), rows = (root = tab()) => $$('tbody tr', root).filter(r => !r.hidden), row = pid => rows().find(r => r.cells[0].textContent === String(pid)); +const type = (el, v) => { el.value = v; el.dispatchEvent(new Event('input', { bubbles: true })); el.dispatchEvent(new Event('change', { bubbles: true })); }; +const X = '', clean = () => window.__xss === undefined && $$('img').length === 1 && $$('script').length === 2 && !$$('*').some(e => e.hasAttribute('onerror') || e.hasAttribute('onclick')); +const open = async key => { go('server', S.id, key); await until(() => S.tab === key && tab() && S.m); await sleep(350); };`; +(async () => { + const b = await launch(), p = await b.first(), ev = body => p.evaluate(H + body).catch(e => (console.log(' step threw: ' + e.message.split('\n')[0]), false)); + await p.go(base + '/#/server/0/overview'), await sleep(3500); + check('deep link #/server/0/overview opens the first server with live data', await ev(`return !!(await until(() => S.page === 'server' && S.m && tab())) && $('.tabbar .on').textContent === 'Overview' && $('h1', page()).textContent`)); + // every tab with hostile data + const seen = await ev(`const out = []; for (const key of Object.keys(TABS)) { await open(key); out.push(key + ':' + +clean() + ':' + +tab().textContent.includes(X) + ':' + +(page().textContent.includes(X))); } return out.join(' ')`); + check('all 11 tabs: no element is created from server data (img / script / handlers), the text is shown literally', seen.split(' ').length === 11 && seen.split(' ').every(s => /:1:[01]:1$/.test(s)) && ['overview', 'cpu', 'memory', 'storage', 'network', 'processes', 'services'].every(k => seen.includes(k + ':1:1:1')), seen); + await p.shot(cfg + '-hostile-processes.png'); + check('console output and service logs are text', await ev(`await open('console'); const i = $('input.mono', tab()); i.value = 'echo hi'; byText('button', 'Run', tab()).click(); await until(() => $('.console .good'), 8000); const c = $('.console').textContent.includes(X + '