Report uptime from the agents, and stop the Integrations page overflowing a phone
Linux agent 8 and Windows agent 7 say how long the machine has been up; the server stores it (migration 0086) and shows it as Up for in the status strip (left out while offline) and Uptime on the server page. The Integrations header wraps and its button no longer squeezes, and .table-responsive is positioned so hidden text in scrolled-off columns cannot widen the page. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
d88a24b33a
commit
41fbbf3467
18 files changed
+9161
-10
No files matched your search
@@ -28,6 +28,7 @@ number when it is worth installing the agent again for.
|
|||||||
| 4 (Windows) | Also reports failed services, disk health and Storage Spaces pools (below), and what the machine is (maker, model, serial number). |
|
| 4 (Windows) | Also reports failed services, disk health and Storage Spaces pools (below), and what the machine is (maker, model, serial number). |
|
||||||
| 6 (Linux), 5 (Windows) | Also says **what it couldn't collect and why** (no `smartctl`, no systemd, a package manager that didn't answer, Windows Update that timed out …), shown on the server's page with what to do about it (below). |
|
| 6 (Linux), 5 (Windows) | Also says **what it couldn't collect and why** (no `smartctl`, no systemd, a package manager that didn't answer, Windows Update that timed out …), shown on the server's page with what to do about it (below). |
|
||||||
| 7 (Linux), 6 (Windows) | Also says **which operating system it runs** (distribution and release, or Windows product and build), so the server's page can say when that release stops being supported (below). |
|
| 7 (Linux), 6 (Windows) | Also says **which operating system it runs** (distribution and release, or Windows product and build), so the server's page can say when that release stops being supported (below). |
|
||||||
|
| 8 (Linux), 7 (Windows) | Also says **how long the machine has been up**, shown as *Up for* in the status strip and as *Uptime* on the server's page. Older agents keep working; the figure just stays empty until the agent is installed again (or updates itself). |
|
||||||
| 5 (Linux) | Also says what the machine is — maker, model and serial number, read from the firmware — so the inventory can fill itself in (below). |
|
| 5 (Linux) | Also says what the machine is — maker, model and serial number, read from the firmware — so the inventory can fill itself in (below). |
|
||||||
|
|
||||||
Reports are always read leniently — a field an older agent doesn't send is simply left alone, and a field
|
Reports are always read leniently — a field an older agent doesn't send is simply left alone, and a field
|
||||||
|
|||||||
@@ -948,7 +948,7 @@ hours (maintenance), is handed to you or is still going is counted in the badge
|
|||||||
**A server's page in sections.** Overview (links, hardware, identity, runbooks — fold a card by clicking its header, and *Arrange cards* puts them in the order you like, for every server), Health, Network (what it is connected through, ports), History (trends, activity), Tasks (scheduled tasks, run a playbook) and Settings (Proxmox link, its own alert limits),
|
**A server's page in sections.** Overview (links, hardware, identity, runbooks — fold a card by clicking its header, and *Arrange cards* puts them in the order you like, for every server), Health, Network (what it is connected through, ports), History (trends, activity), Tasks (scheduled tasks, run a playbook) and Settings (Proxmox link, its own alert limits),
|
||||||
switched by `?view=`, so a section can be linked to: an alert about a failing service opens the Health section, a new-port alert the Network section.
|
switched by `?view=`, so a section can be linked to: an alert about a failing service opens the Health section, a new-port alert the Network section.
|
||||||
|
|
||||||
**The status strip.** Under a server's name, on every section of its page, a row of figures says how it is at a glance: **Status** (online, with when it last reported — or *offline*, with when it did, and a note when Proxmox says the guest is still running, so a stopped agent is not read as a dead machine; for a server with no agent report, what Proxmox says, or that nothing has reported), **Maintenance** (only while a window on this server is on, with when it ends and why), **Alerts** (how many are open about this server and how bad — what a maintenance window, a snooze or a closing has put aside is not counted, but said — and a link to the Alerts page), **Updates** (what is waiting, how many of them security fixes, whether a reboot is needed), **Disk** (the fullest, against its own limit: green, yellow within ten points of it, red at it; a mount with its own limit is judged by that, and an ignored mount is left out), **CPU · memory** and, for a guest Proxmox reads, **how long it has run**. A figure nothing is known for is left out or says so — it is never filled in. It uses what the page already has plus the alerts and the maintenance windows, read again whenever the page is (the *Refresh* button). Everyone signed in sees it.
|
**The status strip.** Under a server's name, on every section of its page, a row of figures says how it is at a glance: **Status** (online, with when it last reported — or *offline*, with when it did, and a note when Proxmox says the guest is still running, so a stopped agent is not read as a dead machine; for a server with no agent report, what Proxmox says, or that nothing has reported), **Maintenance** (only while a window on this server is on, with when it ends and why), **Alerts** (how many are open about this server and how bad — what a maintenance window, a snooze or a closing has put aside is not counted, but said — and a link to the Alerts page), **Updates** (what is waiting, how many of them security fixes, whether a reboot is needed), **Disk** (the fullest, against its own limit: green, yellow within ten points of it, red at it; a mount with its own limit is judged by that, and an ignored mount is left out), **CPU · memory** and **how long it has run** (for a guest Proxmox reads, or from an agent of version 8 on Linux, 7 on Windows, which say it in every report; left out while the server is offline, since it is then no longer how long it has been up). A figure nothing is known for is left out or says so — it is never filled in. It uses what the page already has plus the alerts and the maintenance windows, read again whenever the page is (the *Refresh* button). Everyone signed in sees it.
|
||||||
|
|
||||||
**Away mode, and critical alerts through the night.** For a one-person homelab, "on call" is about *when you can be reached*. **Settings → Notifications → When → Away** is a one-off "I'm away until Sunday evening": notifications are held while it lasts
|
**Away mode, and critical alerts through the night.** For a one-person homelab, "on call" is about *when you can be reached*. **Settings → Notifications → When → Away** is a one-off "I'm away until Sunday evening": notifications are held while it lasts
|
||||||
(a banner on every page says so and counts them) and sent as **one digest** when it ends — at the time you gave, or when you press *I'm back* — so a week away is one message to read, not a buzzing phone. **Critical** alerts (a server down, a disk full, mains
|
(a banner on every page says so and counts them) and sent as **one digest** when it ends — at the time you gave, or when you press *I'm back* — so a week away is one message to read, not a buzzing phone. **Critical** alerts (a server down, a disk full, mains
|
||||||
|
|||||||
@@ -17,7 +17,7 @@ set -euo pipefail
|
|||||||
# 4 = also reports failed services, disk health (SMART) and ZFS pools, reads pacman, and can update itself when told to
|
# 4 = also reports failed services, disk health (SMART) and ZFS pools, reads pacman, and can update itself when told to
|
||||||
# 5 = also says what the machine is (maker, model, serial number), from the firmware, for the inventory
|
# 5 = also says what the machine is (maker, model, serial number), from the firmware, for the inventory
|
||||||
# 6 = also says what it could not collect and why (no smartctl, no systemd, a package manager that failed ...), so the server can say what to fix
|
# 6 = also says what it could not collect and why (no smartctl, no systemd, a package manager that failed ...), so the server can say what to fix
|
||||||
AGENT_VERSION=7
|
AGENT_VERSION=8
|
||||||
|
|
||||||
ENV_FILE="${ENV_FILE:-/etc/homelab-manager-agent.env}"
|
ENV_FILE="${ENV_FILE:-/etc/homelab-manager-agent.env}"
|
||||||
if [[ -f "$ENV_FILE" ]]; then
|
if [[ -f "$ENV_FILE" ]]; then
|
||||||
@@ -579,6 +579,13 @@ collect_system_info() {
|
|||||||
cpu_load_percent=$(awk -v l="$load1" -v c="$cpu_cores" 'BEGIN { printf "%.1f", (l/c)*100 }')
|
cpu_load_percent=$(awk -v l="$load1" -v c="$cpu_cores" 'BEGIN { printf "%.1f", (l/c)*100 }')
|
||||||
fi
|
fi
|
||||||
|
|
||||||
|
# How long the host has been up: the first figure in /proc/uptime, in seconds. null if it cannot be read.
|
||||||
|
local uptime_seconds="null"
|
||||||
|
if [[ -r /proc/uptime ]]; then
|
||||||
|
uptime_seconds=$(awk '{ printf "%d", $1 }' /proc/uptime 2>/dev/null || true)
|
||||||
|
[[ "$uptime_seconds" =~ ^[0-9]+$ ]] || uptime_seconds="null"
|
||||||
|
fi
|
||||||
|
|
||||||
local mem_total=0 mem_used=0
|
local mem_total=0 mem_used=0
|
||||||
if command -v free >/dev/null 2>&1; then
|
if command -v free >/dev/null 2>&1; then
|
||||||
read -r mem_total mem_used < <(free -b | awk '/^Mem:/ {print $2, $3}')
|
read -r mem_total mem_used < <(free -b | awk '/^Mem:/ {print $2, $3}')
|
||||||
@@ -648,11 +655,13 @@ collect_system_info() {
|
|||||||
--argjson cpu_load_percent "$cpu_load_percent" \
|
--argjson cpu_load_percent "$cpu_load_percent" \
|
||||||
--argjson mem_total_bytes "${mem_total:-0}" \
|
--argjson mem_total_bytes "${mem_total:-0}" \
|
||||||
--argjson mem_used_bytes "${mem_used:-0}" \
|
--argjson mem_used_bytes "${mem_used:-0}" \
|
||||||
|
--argjson uptime_seconds "$uptime_seconds" \
|
||||||
--argjson disks "$disks_json" \
|
--argjson disks "$disks_json" \
|
||||||
'{
|
'{
|
||||||
ip_addresses: $ip_addresses,
|
ip_addresses: $ip_addresses,
|
||||||
cpu: { model: $cpu_model, cores: $cpu_cores, load_percent: $cpu_load_percent },
|
cpu: { model: $cpu_model, cores: $cpu_cores, load_percent: $cpu_load_percent },
|
||||||
memory: { total_bytes: $mem_total_bytes, used_bytes: $mem_used_bytes },
|
memory: { total_bytes: $mem_total_bytes, used_bytes: $mem_used_bytes },
|
||||||
|
uptime_seconds: $uptime_seconds,
|
||||||
disks: $disks,
|
disks: $disks,
|
||||||
listening_ports: $listening_ports,
|
listening_ports: $listening_ports,
|
||||||
updates: $updates,
|
updates: $updates,
|
||||||
|
|||||||
@@ -36,7 +36,7 @@ $ErrorActionPreference = 'Stop'
|
|||||||
# 3 = can replace itself with the newer script when an administrator has switched that on in Homelab Manager
|
# 3 = can replace itself with the newer script when an administrator has switched that on in Homelab Manager
|
||||||
# 4 = also reports services that have failed, disk health, Storage Spaces pools and what the machine is (maker, model, serial)
|
# 4 = also reports services that have failed, disk health, Storage Spaces pools and what the machine is (maker, model, serial)
|
||||||
# 5 = also says what it could not collect and why, so Homelab Manager can say what to fix
|
# 5 = also says what it could not collect and why, so Homelab Manager can say what to fix
|
||||||
$script:AgentVersion = 6
|
$script:AgentVersion = 7
|
||||||
|
|
||||||
$script:DefaultConfigPath = Join-Path $env:ProgramData 'HomelabManager\agent.json'
|
$script:DefaultConfigPath = Join-Path $env:ProgramData 'HomelabManager\agent.json'
|
||||||
|
|
||||||
@@ -432,6 +432,10 @@ function Get-SystemInfo($Config = $null) {
|
|||||||
$load = ($cpus | Where-Object { $null -ne $_.LoadPercentage } | Measure-Object -Property LoadPercentage -Average).Average
|
$load = ($cpus | Where-Object { $null -ne $_.LoadPercentage } | Measure-Object -Property LoadPercentage -Average).Average
|
||||||
$cores = ($cpus | Measure-Object -Property NumberOfLogicalProcessors -Sum).Sum
|
$cores = ($cpus | Measure-Object -Property NumberOfLogicalProcessors -Sum).Sum
|
||||||
|
|
||||||
|
# How long it has been up, in seconds (null if Windows does not say when it started).
|
||||||
|
$uptime = $null
|
||||||
|
try { if ($os.LastBootUpTime) { $uptime = [int64][math]::Floor(((Get-Date) - $os.LastBootUpTime).TotalSeconds); if ($uptime -lt 1) { $uptime = $null } } } catch { }
|
||||||
|
|
||||||
$disks = @()
|
$disks = @()
|
||||||
foreach ($d in @(Get-CimInstance -ClassName Win32_LogicalDisk -Filter 'DriveType=3')) {
|
foreach ($d in @(Get-CimInstance -ClassName Win32_LogicalDisk -Filter 'DriveType=3')) {
|
||||||
if (-not $d.Size) { continue } # an unformatted or unavailable volume
|
if (-not $d.Size) { continue } # an unformatted or unavailable volume
|
||||||
@@ -468,6 +472,7 @@ function Get-SystemInfo($Config = $null) {
|
|||||||
ip_addresses = @($ips)
|
ip_addresses = @($ips)
|
||||||
cpu = [ordered]@{ model = [string]($cpus[0].Name).Trim(); cores = [int]$cores; load_percent = $(if ($null -ne $load) { [math]::Round([double]$load, 1) } else { $null }) }
|
cpu = [ordered]@{ model = [string]($cpus[0].Name).Trim(); cores = [int]$cores; load_percent = $(if ($null -ne $load) { [math]::Round([double]$load, 1) } else { $null }) }
|
||||||
memory = [ordered]@{ total_bytes = $totalBytes; used_bytes = ($totalBytes - $freeBytes) }
|
memory = [ordered]@{ total_bytes = $totalBytes; used_bytes = ($totalBytes - $freeBytes) }
|
||||||
|
uptime_seconds = $uptime
|
||||||
disks = @($disks)
|
disks = @($disks)
|
||||||
listening_ports = @(Get-ListeningPorts)
|
listening_ports = @(Get-ListeningPorts)
|
||||||
}
|
}
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE `servers` ADD `uptime_seconds` integer;
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -603,6 +603,13 @@
|
|||||||
"when": 1793832143749,
|
"when": 1793832143749,
|
||||||
"tag": "0085_broad_skrulls",
|
"tag": "0085_broad_skrulls",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 86,
|
||||||
|
"version": "6",
|
||||||
|
"when": 1794155585495,
|
||||||
|
"tag": "0086_talented_starfox",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -442,6 +442,7 @@ export const servers = sqliteTable("servers", {
|
|||||||
cpuLoadPercent: real("cpu_load_percent"),
|
cpuLoadPercent: real("cpu_load_percent"),
|
||||||
memTotalBytes: integer("mem_total_bytes"),
|
memTotalBytes: integer("mem_total_bytes"),
|
||||||
memUsedBytes: integer("mem_used_bytes"),
|
memUsedBytes: integer("mem_used_bytes"),
|
||||||
|
uptimeSeconds: integer("uptime_seconds"), // how long the host had been up when it last reported
|
||||||
disks: text("disks"), // JSON string: {mount, sizeBytes, usedBytes}[]
|
disks: text("disks"), // JSON string: {mount, sizeBytes, usedBytes}[]
|
||||||
listeningPorts: text("listening_ports"), // JSON string: {protocol, port, address, process}[] — what the agent sees bound on the host
|
listeningPorts: text("listening_ports"), // JSON string: {protocol, port, address, process}[] — what the agent sees bound on the host
|
||||||
lastPortScan: text("last_port_scan"), // JSON string: summary of the most recent network scan from this app
|
lastPortScan: text("last_port_scan"), // JSON string: summary of the most recent network scan from this app
|
||||||
|
|||||||
@@ -101,6 +101,11 @@ const systemSchema = z.object({
|
|||||||
ip_addresses: z.array(text(100)).transform(cap(200)).optional(),
|
ip_addresses: z.array(text(100)).transform(cap(200)).optional(),
|
||||||
cpu: z.object({ model: text(200).optional(), cores: z.number().optional(), load_percent: z.number().nullable().optional() }).optional(),
|
cpu: z.object({ model: text(200).optional(), cores: z.number().optional(), load_percent: z.number().nullable().optional() }).optional(),
|
||||||
memory: z.object({ total_bytes: z.number().optional(), used_bytes: z.number().optional() }).optional(),
|
memory: z.object({ total_bytes: z.number().optional(), used_bytes: z.number().optional() }).optional(),
|
||||||
|
// Lenient like the rest: a figure that makes no sense is dropped, never allowed to cost the agent its report.
|
||||||
|
uptime_seconds: z
|
||||||
|
.unknown()
|
||||||
|
.optional()
|
||||||
|
.transform((v) => (typeof v === "number" && Number.isFinite(v) && v > 0 && v < 3_000_000_000 ? Math.floor(v) : undefined)),
|
||||||
disks: z
|
disks: z
|
||||||
.array(z.object({ mount: text(500), size_bytes: z.number(), used_bytes: z.number() }))
|
.array(z.object({ mount: text(500), size_bytes: z.number(), used_bytes: z.number() }))
|
||||||
.transform(cap(500))
|
.transform(cap(500))
|
||||||
|
|||||||
@@ -382,6 +382,7 @@ serversRouter.get("/:id/detail", asyncHandler(async (req, res) => {
|
|||||||
cpuLoadPercent: server.cpuLoadPercent,
|
cpuLoadPercent: server.cpuLoadPercent,
|
||||||
memTotalBytes: server.memTotalBytes,
|
memTotalBytes: server.memTotalBytes,
|
||||||
memUsedBytes: server.memUsedBytes,
|
memUsedBytes: server.memUsedBytes,
|
||||||
|
uptime: server.uptimeSeconds,
|
||||||
disks: server.disks ? JSON.parse(server.disks) : [],
|
disks: server.disks ? JSON.parse(server.disks) : [],
|
||||||
};
|
};
|
||||||
} else {
|
} else {
|
||||||
@@ -424,6 +425,7 @@ serversRouter.get("/:id/detail", asyncHandler(async (req, res) => {
|
|||||||
cpuLoadPercent: _cpuLoadPercent,
|
cpuLoadPercent: _cpuLoadPercent,
|
||||||
memTotalBytes: _memTotalBytes,
|
memTotalBytes: _memTotalBytes,
|
||||||
memUsedBytes: _memUsedBytes,
|
memUsedBytes: _memUsedBytes,
|
||||||
|
uptimeSeconds: _uptimeSeconds,
|
||||||
listeningPorts: _listeningPorts,
|
listeningPorts: _listeningPorts,
|
||||||
lastPortScan: _lastPortScan,
|
lastPortScan: _lastPortScan,
|
||||||
pendingUpdates: rawUpdates,
|
pendingUpdates: rawUpdates,
|
||||||
|
|||||||
@@ -13,6 +13,7 @@
|
|||||||
* 5 — Linux: also says what the machine is (maker, model, serial), for the inventory
|
* 5 — Linux: also says what the machine is (maker, model, serial), for the inventory
|
||||||
* 6 — Linux (and Windows 5): also says what it could not collect and why, so the server can say what to fix
|
* 6 — Linux (and Windows 5): also says what it could not collect and why, so the server can say what to fix
|
||||||
* 7 — Linux (and Windows 6): also says which operating system and release it runs, so the server can say when that release stops being supported
|
* 7 — Linux (and Windows 6): also says which operating system and release it runs, so the server can say when that release stops being supported
|
||||||
|
* 8 — Linux (and Windows 7): also says how long the machine has been up
|
||||||
*/
|
*/
|
||||||
import { createHash } from "node:crypto";
|
import { createHash } from "node:crypto";
|
||||||
import { readFileSync } from "node:fs";
|
import { readFileSync } from "node:fs";
|
||||||
|
|||||||
@@ -24,6 +24,8 @@ export interface IncomingSystemInfo {
|
|||||||
ip_addresses?: string[];
|
ip_addresses?: string[];
|
||||||
cpu?: { model?: string; cores?: number; load_percent?: number | null };
|
cpu?: { model?: string; cores?: number; load_percent?: number | null };
|
||||||
memory?: { total_bytes?: number; used_bytes?: number };
|
memory?: { total_bytes?: number; used_bytes?: number };
|
||||||
|
/** Seconds the machine had been up. Absent from an agent that predates it. */
|
||||||
|
uptime_seconds?: number;
|
||||||
disks?: { mount: string; size_bytes: number; used_bytes: number }[];
|
disks?: { mount: string; size_bytes: number; used_bytes: number }[];
|
||||||
listening_ports?: { protocol: "tcp" | "udp"; port: number; address: string; process?: string }[];
|
listening_ports?: { protocol: "tcp" | "udp"; port: number; address: string; process?: string }[];
|
||||||
/** Updates waiting to be installed. Absent from an agent that doesn't report them (or couldn't find out this time). */
|
/** Updates waiting to be installed. Absent from an agent that doesn't report them (or couldn't find out this time). */
|
||||||
@@ -141,6 +143,8 @@ export async function syncServerTasks(serverId: number, report: AgentReport) {
|
|||||||
...(system?.cpu?.load_percent !== undefined ? { cpuLoadPercent: system.cpu.load_percent } : {}),
|
...(system?.cpu?.load_percent !== undefined ? { cpuLoadPercent: system.cpu.load_percent } : {}),
|
||||||
...(system?.memory?.total_bytes !== undefined ? { memTotalBytes: system.memory.total_bytes } : {}),
|
...(system?.memory?.total_bytes !== undefined ? { memTotalBytes: system.memory.total_bytes } : {}),
|
||||||
...(system?.memory?.used_bytes !== undefined ? { memUsedBytes: system.memory.used_bytes } : {}),
|
...(system?.memory?.used_bytes !== undefined ? { memUsedBytes: system.memory.used_bytes } : {}),
|
||||||
|
// Only stored when said, so an agent that predates this doesn't wipe it.
|
||||||
|
...(system?.uptime_seconds !== undefined ? { uptimeSeconds: system.uptime_seconds } : {}),
|
||||||
...(system?.disks
|
...(system?.disks
|
||||||
? {
|
? {
|
||||||
disks: JSON.stringify(
|
disks: JSON.stringify(
|
||||||
|
|||||||
@@ -129,7 +129,7 @@ describe("through a report, the page, the alerts and the figures", () => {
|
|||||||
|
|
||||||
before(async () => {
|
before(async () => {
|
||||||
await db.insert(users).values([{ oidcSub: "admin", name: "Ada", role: "admin" }]);
|
await db.insert(users).values([{ oidcSub: "admin", name: "Ada", role: "admin" }]);
|
||||||
const [s] = await db.insert(servers).values({ name: "elsa", apiTokenHash: hashToken("tok"), apiTokenPrefix: "t", lastSeenAt: new Date().toISOString(), agentVersion: 7 }).returning();
|
const [s] = await db.insert(servers).values({ name: "elsa", apiTokenHash: hashToken("tok"), apiTokenPrefix: "t", lastSeenAt: new Date().toISOString(), agentVersion: 8 }).returning();
|
||||||
id = s.id;
|
id = s.id;
|
||||||
const a = express();
|
const a = express();
|
||||||
a.use("/api/agent/report", agentReportRouter);
|
a.use("/api/agent/report", agentReportRouter);
|
||||||
@@ -155,7 +155,7 @@ describe("through a report, the page, the alerts and the figures", () => {
|
|||||||
});
|
});
|
||||||
|
|
||||||
const report = (system: unknown) =>
|
const report = (system: unknown) =>
|
||||||
fetch(`${base}/agent/report`, { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer tok" }, body: JSON.stringify({ hostname: "h", os_type: "linux", agent_version: 7, tasks: [], system }) });
|
fetch(`${base}/agent/report`, { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer tok" }, body: JSON.stringify({ hostname: "h", os_type: "linux", agent_version: 8, tasks: [], system }) });
|
||||||
const detail = async () => await (await fetch(`${base}/servers/${id}/detail`)).json();
|
const detail = async () => await (await fetch(`${base}/servers/${id}/detail`)).json();
|
||||||
const patch = (body: unknown) => fetch(`${base}/servers/${id}`, { method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
const patch = (body: unknown) => fetch(`${base}/servers/${id}`, { method: "PATCH", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
/**
|
||||||
|
* How long a server has been up, as its agent says it: taken from a report (and dropped if it makes no sense), kept when an older agent
|
||||||
|
* reports without it, given back on the server's page, and not claimed on the strip once the server has stopped reporting.
|
||||||
|
*
|
||||||
|
* Run with: npm test --workspace server
|
||||||
|
*/
|
||||||
|
import { test, describe, before, after } from "node:test";
|
||||||
|
import assert from "node:assert/strict";
|
||||||
|
import { mkdtempSync, readFileSync, rmSync } from "node:fs";
|
||||||
|
import { tmpdir } from "node:os";
|
||||||
|
import { join } from "node:path";
|
||||||
|
import type { AddressInfo } from "node:net";
|
||||||
|
import type { Server } from "node:http";
|
||||||
|
|
||||||
|
const dir = mkdtempSync(join(tmpdir(), "hm-uptime-"));
|
||||||
|
process.env.DATABASE_PATH = join(dir, "test.sqlite");
|
||||||
|
process.env.SESSION_DIR = join(dir, "sessions");
|
||||||
|
process.env.CREDENTIALS_ENCRYPTION_KEY = "ab".repeat(32);
|
||||||
|
|
||||||
|
const express = (await import("express")).default;
|
||||||
|
const { db } = await import("../src/db/client.js");
|
||||||
|
const { users, servers } = await import("../src/db/schema.js");
|
||||||
|
const { runMigrations } = await import("../src/db/migrate.js");
|
||||||
|
const { serversRouter } = await import("../src/routes/servers.js");
|
||||||
|
const { agentReportRouter } = await import("../src/routes/agentReport.js");
|
||||||
|
const { hashToken } = await import("../src/services/tokens.js");
|
||||||
|
const { parseAgentVersion, latestAgentVersions, AGENT_DIR } = await import("../src/services/agentVersions.js");
|
||||||
|
const { serverStrip } = await import("../../web/src/utils/serverStrip.js");
|
||||||
|
const { eq } = await import("drizzle-orm");
|
||||||
|
|
||||||
|
await runMigrations();
|
||||||
|
|
||||||
|
describe("a report's uptime", () => {
|
||||||
|
let app: Server;
|
||||||
|
let base = "";
|
||||||
|
let id = 0;
|
||||||
|
|
||||||
|
before(async () => {
|
||||||
|
await db.insert(users).values({ oidcSub: "tester", name: "Tester", role: "viewer" });
|
||||||
|
id = (await db.insert(servers).values({ name: "web-1", apiTokenHash: hashToken("tok"), apiTokenPrefix: "t" }).returning({ id: servers.id }))[0].id;
|
||||||
|
const a = express();
|
||||||
|
a.use("/api/agent/report", agentReportRouter);
|
||||||
|
a.use(express.json());
|
||||||
|
a.use((req, _res, next) => {
|
||||||
|
(req as unknown as { session: unknown }).session = { user: { sub: "tester" } };
|
||||||
|
next();
|
||||||
|
});
|
||||||
|
a.use("/api/servers", serversRouter);
|
||||||
|
app = await new Promise<Server>((resolve) => {
|
||||||
|
const x = a.listen(0, "127.0.0.1", () => resolve(x));
|
||||||
|
});
|
||||||
|
base = `http://127.0.0.1:${(app.address() as AddressInfo).port}/api`;
|
||||||
|
});
|
||||||
|
after(() => {
|
||||||
|
app.close();
|
||||||
|
try {
|
||||||
|
rmSync(dir, { recursive: true, force: true });
|
||||||
|
} catch {
|
||||||
|
// Windows keeps the database file locked until the process exits.
|
||||||
|
}
|
||||||
|
});
|
||||||
|
|
||||||
|
const system = (extra: Record<string, unknown>) => ({ cpu: { model: "x", cores: 4, load_percent: 5 }, memory: { total_bytes: 1000, used_bytes: 100 }, disks: [], ...extra });
|
||||||
|
const report = (sys: unknown) => fetch(`${base}/agent/report`, { method: "POST", headers: { "content-type": "application/json", authorization: "Bearer tok" }, body: JSON.stringify({ os_type: "linux", system: sys, tasks: [] }) });
|
||||||
|
const stored = async () => (await db.select().from(servers).where(eq(servers.id, id)))[0].uptimeSeconds;
|
||||||
|
const detail = async () => (await (await fetch(`${base}/servers/${id}/detail`)).json()) as { hardware: { uptime?: number | null }; server: Record<string, unknown> };
|
||||||
|
|
||||||
|
test("a report with uptime stores it, whole seconds, and the server's page gives it back", async () => {
|
||||||
|
assert.equal((await report(system({ uptime_seconds: 1_234_567.8 }))).status, 202);
|
||||||
|
assert.equal(await stored(), 1_234_567);
|
||||||
|
const d = await detail();
|
||||||
|
assert.equal(d.hardware.uptime, 1_234_567);
|
||||||
|
assert.ok(!("uptimeSeconds" in d.server), "it is not handed out twice");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a newer report replaces it, and an older agent's report (with none) leaves it as it was", async () => {
|
||||||
|
await report(system({ uptime_seconds: 2_000_000 }));
|
||||||
|
assert.equal(await stored(), 2_000_000);
|
||||||
|
assert.equal((await report(system({}))).status, 202);
|
||||||
|
assert.equal(await stored(), 2_000_000);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("a figure that makes no sense is dropped, never costing the report", async () => {
|
||||||
|
for (const bad of [-5, 0, "12", null, Number.MAX_SAFE_INTEGER, { a: 1 }]) {
|
||||||
|
assert.equal((await report(system({ uptime_seconds: bad }))).status, 202, JSON.stringify(bad));
|
||||||
|
assert.equal(await stored(), 2_000_000, `kept after ${JSON.stringify(bad)}`);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("the strip", () => {
|
||||||
|
const NOW = Date.parse("2026-06-10T12:00:00Z");
|
||||||
|
const base = { defaults: { serverOfflineMinutes: 15, diskUsagePercent: 90 }, alerts: [], windows: [], now: NOW } as never;
|
||||||
|
const make = (lastSeenAt: string) =>
|
||||||
|
serverStrip({ ...(base as object), server: { id: 1, name: "web-1", lastSeenAt, pendingUpdates: null, thresholds: null }, hardware: { source: "agent", uptime: 90_000 } } as never);
|
||||||
|
|
||||||
|
test("shows how long it has been up while it reports", () => {
|
||||||
|
const t = make(new Date(NOW - 60_000).toISOString()).find((x) => x.id === "uptime");
|
||||||
|
assert.equal(t?.value, "1d 1h");
|
||||||
|
});
|
||||||
|
|
||||||
|
test("says nothing of it once the server has stopped reporting — that is no longer how long it has been up", () => {
|
||||||
|
const tiles = make(new Date(NOW - 3 * 3600_000).toISOString());
|
||||||
|
assert.equal(tiles[0].value, "Offline");
|
||||||
|
assert.equal(tiles.find((x) => x.id === "uptime"), undefined);
|
||||||
|
});
|
||||||
|
});
|
||||||
|
|
||||||
|
describe("the agents", () => {
|
||||||
|
test("both say the new version, and the Linux one reads /proc/uptime and sends it as uptime_seconds", () => {
|
||||||
|
const latest = latestAgentVersions();
|
||||||
|
assert.equal(latest.linux, 8);
|
||||||
|
assert.equal(latest.windows, 7);
|
||||||
|
const sh = readFileSync(join(AGENT_DIR, "linux", "report-tasks.sh"), "utf8");
|
||||||
|
assert.equal(parseAgentVersion(sh, "linux"), 8);
|
||||||
|
assert.match(sh, /\/proc\/uptime/);
|
||||||
|
assert.match(sh, /uptime_seconds: \$uptime_seconds/);
|
||||||
|
});
|
||||||
|
|
||||||
|
test("the Windows one works it out from when Windows started, and the file stays plain ASCII", () => {
|
||||||
|
const ps = readFileSync(join(AGENT_DIR, "windows", "report-tasks.ps1"), "utf8");
|
||||||
|
assert.match(ps, /LastBootUpTime/);
|
||||||
|
assert.match(ps, /uptime_seconds\s*=\s*\$uptime/);
|
||||||
|
assert.ok(!/[^\x00-\x7f]/.test(ps), "downloaded as text, so no characters beyond ASCII");
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -32,9 +32,9 @@ function run(snippet: string): unknown {
|
|||||||
}
|
}
|
||||||
|
|
||||||
describe("the Windows agent's health parts", { skip: !havePwsh }, () => {
|
describe("the Windows agent's health parts", { skip: !havePwsh }, () => {
|
||||||
test("it says it is version 5, and stays plain ASCII", () => {
|
test("it says it is version 7, and stays plain ASCII", () => {
|
||||||
const text = readFileSync(script, "utf8");
|
const text = readFileSync(script, "utf8");
|
||||||
assert.match(text, /^\$script:AgentVersion = 6\s*$/m);
|
assert.match(text, /^\$script:AgentVersion = 7\s*$/m);
|
||||||
assert.ok(!/[^\x00-\x7f]/.test(text));
|
assert.ok(!/[^\x00-\x7f]/.test(text));
|
||||||
});
|
});
|
||||||
|
|
||||||
|
|||||||
@@ -241,7 +241,7 @@ function IntegrationsList({ user, tabs }: { user: CurrentUser; tabs: ReactNode }
|
|||||||
|
|
||||||
return (
|
return (
|
||||||
<>
|
<>
|
||||||
<div className="d-flex align-items-center mb-3">
|
<div className="d-flex flex-wrap align-items-center gap-2 mb-3">
|
||||||
<div>
|
<div>
|
||||||
<h2 className="page-title mb-0">Integrations</h2>
|
<h2 className="page-title mb-0">Integrations</h2>
|
||||||
<div className="text-secondary small mt-1">
|
<div className="text-secondary small mt-1">
|
||||||
@@ -249,7 +249,7 @@ function IntegrationsList({ user, tabs }: { user: CurrentUser; tabs: ReactNode }
|
|||||||
</div>
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{isAdmin && !adding && !editingIntegration && (
|
{isAdmin && !adding && !editingIntegration && (
|
||||||
<button className="btn btn-primary ms-auto" onClick={() => setAdding(true)}>
|
<button className="btn btn-primary ms-auto flex-shrink-0 text-nowrap" onClick={() => setAdding(true)}>
|
||||||
Add integration
|
Add integration
|
||||||
</button>
|
</button>
|
||||||
)}
|
)}
|
||||||
|
|||||||
@@ -220,6 +220,11 @@ html[data-env] .navbar-vertical {
|
|||||||
vertical-align: 0.1em;
|
vertical-align: 0.1em;
|
||||||
}
|
}
|
||||||
|
|
||||||
|
/* A table wider than its box scrolls inside it; its hidden-for-the-eye text (position: absolute) has to stay inside that box too, or it widens the whole page from a column that is scrolled out of sight. */
|
||||||
|
.table-responsive {
|
||||||
|
position: relative;
|
||||||
|
}
|
||||||
|
|
||||||
/* ── On a phone, wide tables become a stack of cards: each row a card, each cell labelled with its column (data-label is set by useStackedTables). ── */
|
/* ── On a phone, wide tables become a stack of cards: each row a card, each cell labelled with its column (data-label is set by useStackedTables). ── */
|
||||||
@media (max-width: 767.98px) {
|
@media (max-width: 767.98px) {
|
||||||
.card > .table-responsive {
|
.card > .table-responsive {
|
||||||
|
|||||||
@@ -134,6 +134,8 @@ export function serverStrip(i: StripInput): StripTile[] {
|
|||||||
tiles.push({ id: "load", label: "CPU · memory", value: [cpu !== null ? `${Math.round(cpu)}%` : "—", mem !== null ? `${mem}%` : "—"].join(" · "), sub: null, tone: busy ? "warn" : "muted" });
|
tiles.push({ id: "load", label: "CPU · memory", value: [cpu !== null ? `${Math.round(cpu)}%` : "—", mem !== null ? `${mem}%` : "—"].join(" · "), sub: null, tone: busy ? "warn" : "muted" });
|
||||||
}
|
}
|
||||||
|
|
||||||
if (typeof hardware.uptime === "number" && hardware.uptime > 0) tiles.push({ id: "uptime", label: "Up for", value: uptimeText(hardware.uptime), sub: null, tone: "muted" });
|
// How long it had been up when it last reported; once it has stopped reporting that is no longer how long it has been up, so it is left out.
|
||||||
|
const offline = tiles[0]?.id === "status" && tiles[0].value === "Offline";
|
||||||
|
if (!offline && typeof hardware.uptime === "number" && hardware.uptime > 0) tiles.push({ id: "uptime", label: "Up for", value: uptimeText(hardware.uptime), sub: null, tone: "muted" });
|
||||||
return tiles;
|
return tiles;
|
||||||
}
|
}
|
||||||
Reference in new issue
Block a user