ServerMonitor / dev /SPEC.md
mchuca's picture
Server Monitor: six editions (C++/Qt, Python, web for Linux and Windows), requirements and developer kit
bad179a
|
Raw History Blame Contribute Delete
20.5 kB

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/<serverId>/{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 -- <interval> / sh -s powershell + PS_ARGS (below)
remote spawn ssh <opts> [-i key] [-p port] -T user@host "<same command line>" same, command line = powershell + PS_ARGS joined by spaces
collector stdin collector.sh "$iv = <n>; $once = $false\n" + collector.ps1
one-shot stdin wrap(cmd, privileged, useSudo) cmd + "\n"; privileged+sudo → sudo -n sh -c <quote(cmd)> 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=<helper>, SSH_ASKPASS_REQUIRE=force, SERVERMONITOR_ASKPASS=<password>, 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
& {
<cmd>
} 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 <section> + 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 <v> -p {n} Idle, BelowNormal, Normal, AboveNormal, High → (Get-Process -Id {n}).PriorityClass = '<v>'
priority column header Nice, normal = 0 header Priority, normal = 8

Services tab

Linux Windows
verbs start, stop, restart, reload, enable, disable → systemctl <verb> {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 <kernel> / build <kernel>; 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=<scratch>) 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.