diff --git a/AGENT_UPDATE.md b/AGENT_UPDATE.md index 49bea95..fbb55c7 100644 --- a/AGENT_UPDATE.md +++ b/AGENT_UPDATE.md @@ -22,6 +22,7 @@ number when it is worth installing the agent again for. |---|---| | 1 | Everything before the number was reported — so an agent that says no version is version 1. | | 2 | Reports pending updates, and its own version. | +| 3 (Linux only) | Asks the package manager outside the agent's systemd sandbox, so `dnf` and `zypper` hosts can answer (below). The Windows agent stays at 2. Install again to get it: the unit file changes too. | Reports are always read leniently — a field an older agent doesn't send is simply left alone, and a field an agent sends that the server doesn't know yet is ignored — so there is never a rush, and a mixed fleet of @@ -163,7 +164,7 @@ The agent only *asks*; it never installs, downloads or refreshes anything. | System | What it asks | Notes | |---|---|---| | Debian, Ubuntu, Raspberry Pi OS (`apt`) | a simulated upgrade (`apt-get -s upgrade`) | Uses the package lists already on the machine. If nothing refreshes them (`apt update`, or the distribution's own daily timer), the count is only as fresh as they are. Security updates are those from a `-security` archive. | -| Fedora, RHEL and relatives (`dnf`) | `dnf check-update --cacheonly` | Reads dnf's cache only; if the cache is empty or unreadable the server stays *not reported*. A restart is flagged by `needs-restarting -r` when that tool is installed. | +| Fedora, RHEL and relatives (`dnf`) | `dnf check-update --cacheonly` | Reads dnf's cache only; if the cache is empty the server stays *not reported* (`sudo dnf makecache` fills it, and dnf's own timer keeps it fresh). A restart is flagged by `needs-restarting -r` when that tool is installed. | | openSUSE, SLES (`zypper`) | `zypper list-updates` without refreshing | Security figure not available (shown as unknown). | | Windows | Windows Update, through its own API | Searching can take a minute or two, so it is done at most **every six hours** and kept in `%ProgramData%\HomelabManager\updates.json`. It runs in a separate process with a 150-second limit (the scheduled task itself is stopped after five minutes). If the search fails or times out it isn't tried again for an hour, and that report leaves updates out. | @@ -172,10 +173,22 @@ The agent only *asks*; it never installs, downloads or refreshes anything. 1. **It is an older agent.** Update it (above). This is by far the most common. 2. **Another package manager** — Alpine (`apk`), Arch (`pacman`) and others aren't read yet. 3. **The check couldn't run.** On Linux the agent writes a line to the journal when its package manager - couldn't be read — `journalctl -u homelab-manager-agent -n 30`. The agent runs inside a tight systemd - sandbox (read-only system, no hardware, minimal privileges, see `install.sh`), which suits `apt`'s - simulation but may stop `dnf` or `zypper` from reading their caches. If you hit that, the sandbox is what - to look at; loosen it only as far as that one need, and only on the hosts that need it. + couldn't be read — `journalctl -u homelab-manager-agent -n 30`. The agent itself runs inside a tight systemd + sandbox (read-only system, no hardware, minimal privileges, see `install.sh`), and `dnf` and `zypper` write to + `/var` and `/run` even when only asked a question. So from agent version 3 the unit asks the package manager in + one separate step *before* the report — `ExecStartPre=-+…homelab-manager-agent.sh --prepare-updates`, where + `+` means outside the sandbox and `-` means a failure doesn't stop the report — and hands the answer to the + report through a private directory (`/run/homelab-manager-agent/updates.json`, removed when the run ends). + That step only runs the package manager's read-only questions. The report itself keeps the full sandbox. + To see what it finds on a host, as root: + + ```bash + sudo /usr/local/bin/homelab-manager-agent.sh --check-updates + ``` + + It prints what the package manager said (errors included) and the figures that would be reported. To try the + whole path the way the timer does it: `sudo systemctl start homelab-manager-agent` and then + `journalctl -u homelab-manager-agent -n 30`. 4. **The package manager was busy** (another update running). It is tried again at the next report. A server that says nothing keeps what it last said — an agent that skips a report never turns an old figure diff --git a/DATABASE.md b/DATABASE.md index 45c377a..24061c1 100644 --- a/DATABASE.md +++ b/DATABASE.md @@ -23,7 +23,7 @@ what the app actually creates. |---|---| | **File** | `DATABASE_PATH`, default `../data/homelab-manager.sqlite` (relative to `server/`; `/app/data/...` in Docker). The folder is created if missing. | | **Foreign keys** | Switched on for every connection (`PRAGMA foreign_keys = ON`), so the `ON DELETE` rules below are enforced. | -| **Migrations** | SQL files in [`server/drizzle/`](server/drizzle) (`0000` … `0027`), applied automatically when the server starts. Which ones have run is recorded in the table `__drizzle_migrations`. | +| **Migrations** | SQL files in [`server/drizzle/`](server/drizzle) (`0000` … `0028`), applied automatically when the server starts. Which ones have run is recorded in the table `__drizzle_migrations`. | | **Tables** | 30 application tables, plus drizzle's own `__drizzle_migrations`. | **Not in the database:** @@ -216,6 +216,7 @@ what it last reported. | `proxmox_vmid` | integer | The four `proxmox_*` columns are set together or cleared together (enforced by the API), by an admin — never by the agent. | | `hide_proxmox_link` | bool NOT NULL, default 0 | Hides the "Proxmox link" card for servers that aren't Proxmox guests. Ignored while the server is actually linked. | | `parent_server_id` | integer | The server this one runs on, set by an admin. **Not a foreign key** (a removed host's servers are cleared by the app). Null = work it out: a server linked to a Proxmox guest runs on the one server named after that guest's node. When the parent is down, this server's offline alert is folded under it. | +| `no_parent` | bool NOT NULL, default 0 | An admin said this server runs on nothing: no link, and no guess from its Proxmox node. Choosing a server by hand, or going back to automatic, clears it. | | `pending_updates` | text | JSON `{"manager":"apt","count":5,"security":2,"rebootRequired":false,"reportedAt":"…"}` from the agent; null until it has said. `security` is null when the package manager can't tell. | | `updates_pending_since` | text | ISO; when updates were first seen waiting (and none were before). Null when none are waiting. | | `agent_version` | integer | Which version of the agent script runs on it, as the agent says in each report. Null until it says; an agent that predates the number counts as version 1. Compared with the scripts the app serves to say which agents are behind. | diff --git a/README.md b/README.md index 1539341..b8464b9 100644 --- a/README.md +++ b/README.md @@ -164,6 +164,11 @@ All modules from the original plan are built: 20 rows per page by default — adjustable under Settings → Display — and CSV export still covers every sorted/filtered row, not just the current page. + The few small tables that have no search or sorting of their own (the + maintenance lists, tags, share links, API tokens and webhooks, the + Backup page's job and run lists, the comparison table) have an Export CSV + too, which writes the table as it is on screen — times as exact timestamps, + action buttons left out. - **Settings** (admin-only) — notification channels (Gotify, ntfy, SMTP, generic webhook) with per-channel test buttons, per-event toggles (DNS record added/updated/deleted, daily secret-expiry reminder and daily @@ -411,7 +416,9 @@ alert, not counted, left out of notifications and osTicket tickets, and labelled uptime ribbons and "Since you last looked"), and if the host comes back while a guest is still down, that guest alerts then as new — an outage is never swallowed. Links that loop back on themselves cover nothing, and setting one that would is -refused. +refused. "Nothing — it runs on its own" stops the guess for a server that isn't a +guest (a physical machine that happens to share a Proxmox node's name), so its +alerts always stand alone. **Recurring maintenance** (Maintenance → Recurring) repeats a window on the days and clock time you choose — "Sundays 02:00–04:00 on these servers" — in the time @@ -419,7 +426,10 @@ zone of the browser it was made in, so 02:00 stays 02:00 across summer and winte time. Each time becomes an ordinary maintenance window a week ahead (shown on the timeline with vertical stripes, and in Scheduled), so any single one can be cancelled and stays cancelled. Turning a schedule off or removing it takes back -the windows that haven't begun. +the windows that haven't begun. Edit changes a schedule's name, days, time, length +or what it covers: the windows that haven't begun are made again from the new +settings (a single one cancelled by hand comes back too), and one already under +way keeps its times and ends on its own. **Running a playbook** from an alert or a server: a server's page has a "Run a playbook" card, and alerts about a server have a "Run…" button, which pick a @@ -433,7 +443,7 @@ and where. Operators and admins only. installed — how many, how many are security fixes, whether a restart is due, and how long updates have been waiting — plus the Docker containers with a newer image. The Linux agent asks apt, dnf or zypper (only what they already know; nothing is -installed or refreshed) and the Windows agent asks Windows Update (at most every six +installed or refreshed — that one question is asked outside the agent's sandbox, which `dnf` and `zypper` need) and the Windows agent asks Windows Update (at most every six hours, cached under `%ProgramData%\HomelabManager`). A server whose agent hasn't said — an older agent, or another package manager — shows "not reported", never "up to date"; run its install command again to update its agent (how, and how to diff --git a/agent/linux/install.sh b/agent/linux/install.sh index 2b1e096..7f9ce78 100644 --- a/agent/linux/install.sh +++ b/agent/linux/install.sh @@ -88,6 +88,13 @@ Description=Report scheduled tasks to Homelab Manager Type=oneshot EnvironmentFile=$CONFIG_DIR/homelab-manager-agent.env ExecStart=$INSTALL_DIR/homelab-manager-agent.sh +# Asking dnf or zypper what is waiting still writes to /var and /run, which the sandbox below makes read-only, so this one step runs +# first and outside it (the + does that; the - lets the report go ahead whatever happens). It only reads what the package manager +# knows and leaves the answer in the unit's private directory, which goes away when the run ends. +ExecStartPre=-+$INSTALL_DIR/homelab-manager-agent.sh --prepare-updates +RuntimeDirectory=homelab-manager-agent +RuntimeDirectoryMode=0700 +TimeoutStartSec=420 # The agent only reads (crontabs, timers, /proc, listening sockets) and makes one HTTPS request, but it runs as root. These # keep a bug in it, or in anything it parses, from being able to change the system. It still sees every process, which is # how it names the program behind each listening port. Directives an older systemd doesn't know are ignored. diff --git a/agent/linux/report-tasks.sh b/agent/linux/report-tasks.sh index 05cf82d..847941c 100644 --- a/agent/linux/report-tasks.sh +++ b/agent/linux/report-tasks.sh @@ -13,7 +13,8 @@ set -euo pipefail # Which version of this script this is, sent with every report so Homelab Manager can tell which agents are behind. Raise it whenever a # change here is worth installing the agent again for (and add it to the list at the top of server/src/services/agentVersions.ts). # 1 = before the number was reported 2 = reports pending updates, and its own version -AGENT_VERSION=2 +# 3 = the package manager is asked outside the sandbox (see --prepare-updates), so dnf and zypper can answer there too +AGENT_VERSION=3 ENV_FILE="${ENV_FILE:-/etc/homelab-manager-agent.env}" if [[ -f "$ENV_FILE" ]]; then @@ -27,7 +28,22 @@ API_INSECURE="${API_INSECURE:-false}" DRY_RUN=0 [[ "${1:-}" == "--dry-run" ]] && DRY_RUN=1 -if [[ -z "$API_URL" || -z "$API_TOKEN" ]]; then +# Two extra ways to run it, neither of which reports anything: +# --prepare-updates asks the package manager what is waiting and leaves the answer in $UPDATES_FILE for the report to pick up. The +# systemd unit runs this step outside its sandbox (ExecStartPre=+), because dnf and zypper write to /var and /run +# even when only asked a question, and the sandbox makes those read-only. A failure here only means no figure. +# --check-updates for a person at a terminal: runs the same check, shows what the package manager said and the result. +MODE=report +case "${1:-}" in + --prepare-updates) MODE=prepare ;; + --check-updates) MODE=check ;; +esac +UPDATES_FILE="${UPDATES_FILE:-/run/homelab-manager-agent/updates.json}" +# Where the package managers' own error output goes: nowhere, unless a person asked to see it. +PM_ERR=/dev/null +[[ "$MODE" == "check" ]] && PM_ERR=/dev/stderr + +if [[ "$MODE" == "report" && ( -z "$API_URL" || -z "$API_TOKEN" ) ]]; then echo "API_URL and API_TOKEN must be set (env vars or $ENV_FILE)" >&2 exit 1 fi @@ -196,7 +212,7 @@ collect_updates() { if command -v apt-get >/dev/null 2>&1; then manager="apt" # -s simulates: "Inst" lines are what an upgrade would install. Security ones come from a "-security" or "Security" archive. - if out=$(LC_ALL=C timeout 60 apt-get -s -o Debug::NoLocking=true upgrade 2>/dev/null); then + if out=$(LC_ALL=C timeout 60 apt-get -s -o Debug::NoLocking=true upgrade 2>"$PM_ERR"); then count=$(grep -c '^Inst ' <<<"$out" || true) security=$(grep '^Inst ' <<<"$out" | grep -ci 'security' || true) fi @@ -204,17 +220,17 @@ collect_updates() { elif command -v dnf >/dev/null 2>&1; then manager="dnf" # check-update exits 100 when there are updates, 0 when none, 1 on an error. --cacheonly: never goes to the network from here. - out=$(LC_ALL=C timeout 120 dnf -q check-update --cacheonly 2>/dev/null) || status=$? + out=$(LC_ALL=C timeout 120 dnf -q check-update --cacheonly 2>"$PM_ERR") || status=$? if [[ "$status" -eq 0 || "$status" -eq 100 ]]; then count=$(awk 'NF >= 3 && $1 ~ /^[A-Za-z0-9_.+-]+\.[A-Za-z0-9_]+$/ && /Obsoleting/ == 0 { n++ } /^Obsoleting/ { exit } END { print n + 0 }' <<<"$out") - security=$(LC_ALL=C timeout 120 dnf -q updateinfo list --security --cacheonly 2>/dev/null | grep -c '/Sec\.' || true) + security=$(LC_ALL=C timeout 120 dnf -q updateinfo list --security --cacheonly 2>"$PM_ERR" | grep -c '/Sec\.' || true) fi if command -v needs-restarting >/dev/null 2>&1; then needs-restarting -r >/dev/null 2>&1 || reboot="true" fi elif command -v zypper >/dev/null 2>&1; then manager="zypper" - if out=$(LC_ALL=C timeout 120 zypper -q --no-refresh list-updates 2>/dev/null); then + if out=$(LC_ALL=C timeout 120 zypper -q --no-refresh list-updates 2>"$PM_ERR"); then count=$(grep -c '^v |' <<<"$out" || true) fi [[ -f /run/reboot-needed ]] && reboot="true" @@ -232,6 +248,18 @@ collect_updates() { fi } +# The answer --prepare-updates left for this report, if it is there, recent and looks like what it should. Read back through jq rather than +# trusted: the report only ever carries these four fields, whatever the file holds. +use_prepared_updates() { + [[ -r "$UPDATES_FILE" ]] || return 1 + [[ -n "$(find "$UPDATES_FILE" -mmin -10 -print 2>/dev/null)" ]] || return 1 + local json + json=$(jq -ce 'select(type == "object" and (.manager | type) == "string" and (.count | type) == "number") + | {manager: .manager, count: .count, security: (if (.security | type) == "number" then .security else null end), reboot_required: (.reboot_required == true)}' "$UPDATES_FILE" 2>/dev/null) || return 1 + [[ -n "$json" ]] || return 1 + UPDATES_JSON=$json +} + collect_system_info() { local ip_json="[]" if command -v ip >/dev/null 2>&1; then @@ -295,7 +323,7 @@ collect_system_info() { # Best-effort like the rest: a package manager that misbehaves must not cost the report. UPDATES_JSON="null" - collect_updates || UPDATES_JSON="null" + use_prepared_updates || collect_updates || UPDATES_JSON="null" SYSTEM_JSON=$(jq -n \ --argjson updates "$UPDATES_JSON" \ @@ -317,6 +345,22 @@ collect_system_info() { }') } +if [[ "$MODE" != "report" ]]; then + collect_updates + if [[ "$MODE" == "check" ]]; then + echo "Pending updates as they would be reported:" + jq . <<<"$UPDATES_JSON" + exit 0 + fi + # prepare: leave the answer (or no file at all) for the report that follows. Written whole and moved into place, so a report never reads half of it. + rm -f "$UPDATES_FILE" + if [[ "$UPDATES_JSON" != "null" ]]; then + mkdir -p "$(dirname "$UPDATES_FILE")" 2>/dev/null || exit 0 + printf '%s\n' "$UPDATES_JSON" > "$UPDATES_FILE.tmp" 2>/dev/null && mv -f "$UPDATES_FILE.tmp" "$UPDATES_FILE" 2>/dev/null || true + fi + exit 0 +fi + collect_cron collect_systemd_timers diff --git a/server/drizzle/0028_thankful_ultron.sql b/server/drizzle/0028_thankful_ultron.sql new file mode 100644 index 0000000..ded7ba7 --- /dev/null +++ b/server/drizzle/0028_thankful_ultron.sql @@ -0,0 +1 @@ +ALTER TABLE `servers` ADD `no_parent` integer DEFAULT false NOT NULL; \ No newline at end of file diff --git a/server/drizzle/meta/0028_snapshot.json b/server/drizzle/meta/0028_snapshot.json new file mode 100644 index 0000000..a7700ee --- /dev/null +++ b/server/drizzle/meta/0028_snapshot.json @@ -0,0 +1,2543 @@ +{ + "version": "6", + "dialect": "sqlite", + "id": "e7eccd67-f116-4a77-8ac2-05ac5885abd6", + "prevId": "65cae39e-5f10-46b2-a807-fd01408276f0", + "tables": { + "alert_tickets": { + "name": "alert_tickets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "alert_key": { + "name": "alert_key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "status": { + "name": "status", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "seen_count": { + "name": "seen_count", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 1 + }, + "integration_id": { + "name": "integration_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ticket_number": { + "name": "ticket_number", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "grouped": { + "name": "grouped", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "severity": { + "name": "severity", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "first_seen_at": { + "name": "first_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ticketed_at": { + "name": "ticketed_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cleared_at": { + "name": "cleared_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "alert_tickets_key_idx": { + "name": "alert_tickets_key_idx", + "columns": [ + "alert_key" + ], + "isUnique": false + } + }, + "foreignKeys": { + "alert_tickets_integration_id_integrations_id_fk": { + "name": "alert_tickets_integration_id_integrations_id_fk", + "tableFrom": "alert_tickets", + "tableTo": "integrations", + "columnsFrom": [ + "integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "assets": { + "name": "assets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "kind": { + "name": "kind", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'other'" + }, + "manufacturer": { + "name": "manufacturer", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "model": { + "name": "model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "serial": { + "name": "serial", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "purchase_date": { + "name": "purchase_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "purchase_price": { + "name": "purchase_price", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "warranty_until": { + "name": "warranty_until", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "rack_unit": { + "name": "rack_unit", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "power_watts": { + "name": "power_watts", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "audit_log": { + "name": "audit_log", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "actor_user_id": { + "name": "actor_user_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "actor_label": { + "name": "actor_label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "action": { + "name": "action", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "audit_log_actor_user_id_users_id_fk": { + "name": "audit_log_actor_user_id_users_id_fk", + "tableFrom": "audit_log", + "tableTo": "users", + "columnsFrom": [ + "actor_user_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "consistency_ignores": { + "name": "consistency_ignores", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "key": { + "name": "key", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "consistency_ignores_key_unique": { + "name": "consistency_ignores_key_unique", + "columns": [ + "key" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "diag_log": { + "name": "diag_log", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "operation": { + "name": "operation", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ok": { + "name": "ok", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "latency_ms": { + "name": "latency_ms", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "error": { + "name": "error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "dns_providers": { + "name": "dns_providers", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider_type": { + "name": "provider_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "credential_id": { + "name": "credential_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "config": { + "name": "config", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "dns_providers_credential_id_integration_credentials_id_fk": { + "name": "dns_providers_credential_id_integration_credentials_id_fk", + "tableFrom": "dns_providers", + "tableTo": "integration_credentials", + "columnsFrom": [ + "credential_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "dns_records_cache": { + "name": "dns_records_cache", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider_id": { + "name": "provider_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "zone_id": { + "name": "zone_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "record_id": { + "name": "record_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "content": { + "name": "content", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ttl": { + "name": "ttl", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "priority": { + "name": "priority", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxied": { + "name": "proxied", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "dns_records_cache_provider_id_dns_providers_id_fk": { + "name": "dns_records_cache_provider_id_dns_providers_id_fk", + "tableFrom": "dns_records_cache", + "tableTo": "dns_providers", + "columnsFrom": [ + "provider_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "dns_zones_cache": { + "name": "dns_zones_cache", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "provider_id": { + "name": "provider_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "zone_id": { + "name": "zone_id", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "zone_name": { + "name": "zone_name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "synced_at": { + "name": "synced_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "dns_zones_cache_provider_zone_idx": { + "name": "dns_zones_cache_provider_zone_idx", + "columns": [ + "provider_id", + "zone_id" + ], + "isUnique": true + } + }, + "foreignKeys": { + "dns_zones_cache_provider_id_dns_providers_id_fk": { + "name": "dns_zones_cache_provider_id_dns_providers_id_fk", + "tableFrom": "dns_zones_cache", + "tableTo": "dns_providers", + "columnsFrom": [ + "provider_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "domains": { + "name": "domains", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'manual'" + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "registrar": { + "name": "registrar", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "lookup_source": { + "name": "lookup_source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_checked_at": { + "name": "last_checked_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_checked_ok_at": { + "name": "last_checked_ok_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_check_error": { + "name": "last_check_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "domains_name_unique": { + "name": "domains_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "event_webhooks": { + "name": "event_webhooks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "secret": { + "name": "secret", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "events": { + "name": "events", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_attempt_at": { + "name": "last_attempt_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_result": { + "name": "last_result", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "integration_credentials": { + "name": "integration_credentials", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "encrypted_secret": { + "name": "encrypted_secret", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "integrations": { + "name": "integrations", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "base_url": { + "name": "base_url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "credential_id": { + "name": "credential_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "config": { + "name": "config", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "integrations_credential_id_integration_credentials_id_fk": { + "name": "integrations_credential_id_integration_credentials_id_fk", + "tableFrom": "integrations", + "tableTo": "integration_credentials", + "columnsFrom": [ + "credential_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "ipam_entries": { + "name": "ipam_entries", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "ip_address": { + "name": "ip_address", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "vendor": { + "name": "vendor", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "location": { + "name": "location", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "ipam_entries_ip_address_unique": { + "name": "ipam_entries_ip_address_unique", + "columns": [ + "ip_address" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "maintenance_aliases": { + "name": "maintenance_aliases", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "address": { + "name": "address", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "maintenance_aliases_unique_idx": { + "name": "maintenance_aliases_unique_idx", + "columns": [ + "address", + "target_type", + "target_id" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "maintenance_schedules": { + "name": "maintenance_schedules", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "targets": { + "name": "targets", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "days": { + "name": "days", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "start_time": { + "name": "start_time", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "duration_minutes": { + "name": "duration_minutes", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "timezone": { + "name": "timezone", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "maintenance_windows": { + "name": "maintenance_windows", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "reason": { + "name": "reason", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "started_at": { + "name": "started_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "ends_at": { + "name": "ends_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "metrics_tokens": { + "name": "metrics_tokens", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_prefix": { + "name": "token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_used_at": { + "name": "last_used_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "metrics_tokens_token_hash_unique": { + "name": "metrics_tokens_token_hash_unique", + "columns": [ + "token_hash" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "notification_queue": { + "name": "notification_queue", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "message": { + "name": "message", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "port_forwards": { + "name": "port_forwards", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "external_port": { + "name": "external_port", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "protocol": { + "name": "protocol", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'tcp'" + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "destination": { + "name": "destination", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "internal_port": { + "name": "internal_port", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "comment": { + "name": "comment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "port_forwards_server_id_servers_id_fk": { + "name": "port_forwards_server_id_servers_id_fk", + "tableFrom": "port_forwards", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "runbooks": { + "name": "runbooks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "target_type": { + "name": "target_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "target_id": { + "name": "target_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "title": { + "name": "title", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "body": { + "name": "body", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "category": { + "name": "category", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_by": { + "name": "updated_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "runbooks_target_idx": { + "name": "runbooks_target_idx", + "columns": [ + "target_type", + "target_id" + ], + "isUnique": false + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "scheduled_tasks": { + "name": "scheduled_tasks", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "schedule_type": { + "name": "schedule_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "origin": { + "name": "origin", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'agent'" + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "command": { + "name": "command", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "schedule_expression": { + "name": "schedule_expression", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "source": { + "name": "source", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "enabled": { + "name": "enabled", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": true + }, + "next_run_at": { + "name": "next_run_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "raw_metadata": { + "name": "raw_metadata", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "is_stale": { + "name": "is_stale", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "first_seen_at": { + "name": "first_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "scheduled_tasks_server_id_servers_id_fk": { + "name": "scheduled_tasks_server_id_servers_id_fk", + "tableFrom": "scheduled_tasks", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "secrets": { + "name": "secrets", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "type": { + "name": "type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'generic'" + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "expiry_date": { + "name": "expiry_date", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "warn_days": { + "name": "warn_days", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": 30 + }, + "notes": { + "name": "notes", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check_host": { + "name": "check_host", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "check_port": { + "name": "check_port", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_checked_at": { + "name": "last_checked_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_check_error": { + "name": "last_check_error", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "server_links": { + "name": "server_links", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "url": { + "name": "url", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": { + "server_links_server_id_servers_id_fk": { + "name": "server_links_server_id_servers_id_fk", + "tableFrom": "server_links", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "server_metrics": { + "name": "server_metrics", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "metric": { + "name": "metric", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "real", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "recorded_at": { + "name": "recorded_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + } + }, + "indexes": { + "server_metrics_lookup_idx": { + "name": "server_metrics_lookup_idx", + "columns": [ + "server_id", + "metric", + "recorded_at" + ], + "isUnique": false + } + }, + "foreignKeys": { + "server_metrics_server_id_servers_id_fk": { + "name": "server_metrics_server_id_servers_id_fk", + "tableFrom": "server_metrics", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "server_ports": { + "name": "server_ports", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "server_id": { + "name": "server_id", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "port": { + "name": "port", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "protocol": { + "name": "protocol", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'tcp'" + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "comment": { + "name": "comment", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "open": { + "name": "open", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "last_seen_open_at": { + "name": "last_seen_open_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "server_ports_unique": { + "name": "server_ports_unique", + "columns": [ + "server_id", + "port", + "protocol" + ], + "isUnique": true + } + }, + "foreignKeys": { + "server_ports_server_id_servers_id_fk": { + "name": "server_ports_server_id_servers_id_fk", + "tableFrom": "server_ports", + "tableTo": "servers", + "columnsFrom": [ + "server_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "cascade", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "servers": { + "name": "servers", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "hostname": { + "name": "hostname", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "os_type": { + "name": "os_type", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'linux'" + }, + "description": { + "name": "description", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "api_token_hash": { + "name": "api_token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "api_token_prefix": { + "name": "api_token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_seen_at": { + "name": "last_seen_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "ip_addresses": { + "name": "ip_addresses", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cpu_model": { + "name": "cpu_model", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cpu_cores": { + "name": "cpu_cores", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "cpu_load_percent": { + "name": "cpu_load_percent", + "type": "real", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mem_total_bytes": { + "name": "mem_total_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "mem_used_bytes": { + "name": "mem_used_bytes", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "disks": { + "name": "disks", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "listening_ports": { + "name": "listening_ports", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_port_scan": { + "name": "last_port_scan", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "tags": { + "name": "tags", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxmox_integration_id": { + "name": "proxmox_integration_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxmox_node": { + "name": "proxmox_node", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxmox_guest_type": { + "name": "proxmox_guest_type", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "proxmox_vmid": { + "name": "proxmox_vmid", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "hide_proxmox_link": { + "name": "hide_proxmox_link", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "parent_server_id": { + "name": "parent_server_id", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "no_parent": { + "name": "no_parent", + "type": "integer", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": false + }, + "pending_updates": { + "name": "pending_updates", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "updates_pending_since": { + "name": "updates_pending_since", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "agent_version": { + "name": "agent_version", + "type": "integer", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": {}, + "foreignKeys": { + "servers_proxmox_integration_id_integrations_id_fk": { + "name": "servers_proxmox_integration_id_integrations_id_fk", + "tableFrom": "servers", + "tableTo": "integrations", + "columnsFrom": [ + "proxmox_integration_id" + ], + "columnsTo": [ + "id" + ], + "onDelete": "set null", + "onUpdate": "no action" + } + }, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "settings": { + "name": "settings", + "columns": { + "key": { + "name": "key", + "type": "text", + "primaryKey": true, + "notNull": true, + "autoincrement": false + }, + "value": { + "name": "value", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "updated_at": { + "name": "updated_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": {}, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "share_links": { + "name": "share_links", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "label": { + "name": "label", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_hash": { + "name": "token_hash", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "token_prefix": { + "name": "token_prefix", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "detail": { + "name": "detail", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'summary'" + }, + "created_by": { + "name": "created_by", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "expires_at": { + "name": "expires_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_used_at": { + "name": "last_used_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "share_links_token_hash_unique": { + "name": "share_links_token_hash_unique", + "columns": [ + "token_hash" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "tag_definitions": { + "name": "tag_definitions", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "color": { + "name": "color", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + } + }, + "indexes": { + "tag_definitions_name_unique": { + "name": "tag_definitions_name_unique", + "columns": [ + "name" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + }, + "users": { + "name": "users", + "columns": { + "id": { + "name": "id", + "type": "integer", + "primaryKey": true, + "notNull": true, + "autoincrement": true + }, + "oidc_sub": { + "name": "oidc_sub", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false + }, + "email": { + "name": "email", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "name": { + "name": "name", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "role": { + "name": "role", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "'viewer'" + }, + "created_at": { + "name": "created_at", + "type": "text", + "primaryKey": false, + "notNull": true, + "autoincrement": false, + "default": "(current_timestamp)" + }, + "last_login_at": { + "name": "last_login_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "favorites": { + "name": "favorites", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "last_looked_at": { + "name": "last_looked_at", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "groups": { + "name": "groups", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + }, + "dashboard_layout": { + "name": "dashboard_layout", + "type": "text", + "primaryKey": false, + "notNull": false, + "autoincrement": false + } + }, + "indexes": { + "users_oidc_sub_unique": { + "name": "users_oidc_sub_unique", + "columns": [ + "oidc_sub" + ], + "isUnique": true + } + }, + "foreignKeys": {}, + "compositePrimaryKeys": {}, + "uniqueConstraints": {}, + "checkConstraints": {} + } + }, + "views": {}, + "enums": {}, + "_meta": { + "schemas": {}, + "tables": {}, + "columns": {} + }, + "internal": { + "indexes": {} + } +} \ No newline at end of file diff --git a/server/drizzle/meta/_journal.json b/server/drizzle/meta/_journal.json index e57814e..b13493f 100644 --- a/server/drizzle/meta/_journal.json +++ b/server/drizzle/meta/_journal.json @@ -197,6 +197,13 @@ "when": 1792260718106, "tag": "0027_bizarre_magus", "breakpoints": true + }, + { + "idx": 28, + "version": "6", + "when": 1792267930026, + "tag": "0028_thankful_ultron", + "breakpoints": true } ] } \ No newline at end of file diff --git a/server/src/db/schema.ts b/server/src/db/schema.ts index 7f14b51..55ed964 100644 --- a/server/src/db/schema.ts +++ b/server/src/db/schema.ts @@ -289,6 +289,8 @@ export const servers = sqliteTable("servers", { // The server this one runs on (a VM on its host), set by an admin. Null means "work it out": a guest linked to a Proxmox node runs on // the server named after that node. When the parent stops reporting, this server's own offline alert is folded under the parent's. parentServerId: integer("parent_server_id"), + // An admin said this server runs on nothing, so the automatic guess from its Proxmox node is not used for it. + noParent: integer("no_parent", { mode: "boolean" }).notNull().default(false), // What the agent says is waiting to be installed, as JSON: {manager, count, security, rebootRequired, reportedAt}. Null until it reports. pendingUpdates: text("pending_updates"), diff --git a/server/src/routes/maintenance.ts b/server/src/routes/maintenance.ts index aa08ea9..1790622 100644 --- a/server/src/routes/maintenance.ts +++ b/server/src/routes/maintenance.ts @@ -309,23 +309,32 @@ maintenanceRouter.get("/schedules", asyncHandler(async (_req, res) => { res.json({ schedules: out }); })); -maintenanceRouter.post("/schedules", requireRole("operator"), asyncHandler(async (req, res) => { - const parsed = scheduleSchema.safeParse(req.body); +type ScheduleBody = z.infer; + +/** Checks a schedule's fields the same way for making one and for changing one: the shape, the time zone, and that what it covers exists (once each). */ +async function checkScheduleBody(body: unknown): Promise<{ data: ScheduleBody; targets: ScheduleBody["targets"] } | { status: number; json: object }> { + const parsed = scheduleSchema.safeParse(body); if (!parsed.success) { - return res.status(400).json({ error: "invalid_body", message: "Name it, choose what it covers, the days, a start time and how long.", details: parsed.error.flatten() }); + return { status: 400, json: { error: "invalid_body", message: "Name it, choose what it covers, the days, a start time and how long.", details: parsed.error.flatten() } }; } const data = parsed.data; - if (!isValidTimeZone(data.timezone)) return res.status(400).json({ error: "invalid_timezone", message: "That isn't a time zone this server knows." }); - // Only things that exist, once each. + if (!isValidTimeZone(data.timezone)) return { status: 400, json: { error: "invalid_timezone", message: "That isn't a time zone this server knows." } }; const seen = new Set(); - const targets = []; + const targets: ScheduleBody["targets"] = []; for (const t of data.targets) { const key = `${t.type}:${t.id}`; if (seen.has(key)) continue; seen.add(key); - if (!(await describeTarget(t.type, t.id))) return res.status(400).json({ error: "unknown_target", message: "One of the things chosen doesn't exist any more." }); + if (!(await describeTarget(t.type, t.id))) return { status: 400, json: { error: "unknown_target", message: "One of the things chosen doesn't exist any more." } }; targets.push(t); } + return { data, targets }; +} + +maintenanceRouter.post("/schedules", requireRole("operator"), asyncHandler(async (req, res) => { + const checked = await checkScheduleBody(req.body); + if ("status" in checked) return res.status(checked.status).json(checked.json); + const { data, targets } = checked; const actor = req.currentUser!; const [created] = await db .insert(maintenanceSchedules) @@ -345,6 +354,36 @@ maintenanceRouter.post("/schedules", requireRole("operator"), asyncHandler(async res.status(201).json({ id: created.id, windowsMade: made }); })); +/** + * Changes a schedule's name, days, time, length or what it covers. Windows it made that haven't begun are taken back and made again from the + * new settings; one already under way keeps the times it started with, and ends on its own. + */ +maintenanceRouter.put("/schedules/:id", requireRole("operator"), asyncHandler(async (req, res) => { + const id = Number(req.params.id); + if (!Number.isInteger(id)) return res.status(400).json({ error: "invalid_id" }); + const [row] = await db.select().from(maintenanceSchedules).where(eq(maintenanceSchedules.id, id)).limit(1); + if (!row) return res.status(404).json({ error: "not_found" }); + const checked = await checkScheduleBody(req.body); + if ("status" in checked) return res.status(checked.status).json(checked.json); + const { data, targets } = checked; + await db + .update(maintenanceSchedules) + .set({ + name: data.name, + reason: data.reason || null, + targets: JSON.stringify(targets), + days: JSON.stringify([...new Set(data.days)].sort()), + startTime: data.startTime, + durationMinutes: data.durationMinutes, + timezone: data.timezone, + }) + .where(eq(maintenanceSchedules.id, id)); + await removeFutureWindows(id); + const made = row.enabled ? await materializeSchedules(new Date(), undefined, id) : 0; + await recordAudit({ actor: req.currentUser!, category: "maintenance", action: "update_schedule", targetType: "maintenance_schedule", targetId: id, detail: { name: data.name, targets: targets.length, days: data.days, startTime: data.startTime, durationMinutes: data.durationMinutes } }); + res.json({ windowsMade: made }); +})); + maintenanceRouter.patch("/schedules/:id", requireRole("operator"), asyncHandler(async (req, res) => { const id = Number(req.params.id); const parsed = z.object({ enabled: z.boolean() }).safeParse(req.body); diff --git a/server/src/routes/servers.ts b/server/src/routes/servers.ts index aac31e1..60a42c0 100644 --- a/server/src/routes/servers.ts +++ b/server/src/routes/servers.ts @@ -120,6 +120,8 @@ const updateServerSchema = z hideProxmoxLink: z.boolean().optional(), // The server this one runs on. Null goes back to working it out from the Proxmox node. parentServerId: z.number().int().nullable().optional(), + // True says it runs on nothing, which also stops the Proxmox-node guess. Choosing a server, or null, turns it off again. + noParent: z.boolean().optional(), }) .refine( (data) => { @@ -166,7 +168,10 @@ serversRouter.patch("/:id", requireRole("admin"), asyncHandler(async (req, res) } } - const [updated] = await db.update(servers).set(parsed.data).where(eq(servers.id, id)).returning(); + const changes: typeof parsed.data = { ...parsed.data }; + if (changes.noParent === true) changes.parentServerId = null; + else if (changes.parentServerId !== undefined) changes.noParent = false; + const [updated] = await db.update(servers).set(changes).where(eq(servers.id, id)).returning(); await recordAudit({ actor: req.currentUser!, @@ -174,7 +179,7 @@ serversRouter.patch("/:id", requireRole("admin"), asyncHandler(async (req, res) action: "update", targetType: "server", targetId: id, - detail: { name: updated.name, ...(parsed.data.parentServerId !== undefined ? { parentServerId: parsed.data.parentServerId } : {}) }, + detail: { name: updated.name, ...(parsed.data.parentServerId !== undefined ? { parentServerId: parsed.data.parentServerId } : {}), ...(parsed.data.noParent !== undefined ? { noParent: parsed.data.noParent } : {}) }, }); const serverOut = publicServer(updated); diff --git a/server/src/services/agentVersions.ts b/server/src/services/agentVersions.ts index 168afb9..f216bcf 100644 --- a/server/src/services/agentVersions.ts +++ b/server/src/services/agentVersions.ts @@ -6,6 +6,7 @@ * * 1 — before the number was reported (so an agent that says nothing is version 1) * 2 — reports pending updates, and its own version + * 3 — Linux: the package manager is asked outside the systemd sandbox, so dnf and zypper can answer too (Windows stays at 2) */ import { readFileSync } from "node:fs"; import { dirname, join } from "node:path"; diff --git a/server/src/services/serverParents.ts b/server/src/services/serverParents.ts index 9b6de6f..1b5bd06 100644 --- a/server/src/services/serverParents.ts +++ b/server/src/services/serverParents.ts @@ -2,7 +2,7 @@ * Which server runs on which: a virtual machine on its Proxmox host, a container on a Docker box. When the host stops reporting, the * things on it stop too, and seven alerts about seven guests only hide the one that matters — so those alerts are folded under the * host's. The link is either set by hand ("runs on") or worked out: a server linked to a Proxmox guest runs on the server named after - * that guest's Proxmox node, when there is exactly one such server. + * that guest's Proxmox node, when there is exactly one such server. An admin can also say a server runs on nothing, which stops the guess. */ import { db } from "../db/client.js"; import { servers } from "../db/schema.js"; @@ -13,6 +13,8 @@ export interface ParentRow { hostname: string | null; parentServerId: number | null; proxmoxNode: string | null; + /** Said by hand to run on nothing: no link, and no guessing from the Proxmox node. */ + noParent?: boolean; } export interface ParentLink { @@ -36,6 +38,7 @@ export function resolveParents(rows: ParentRow[]): Map { const byId = new Map(rows.map((r) => [r.id, r])); const out = new Map(); for (const row of rows) { + if (row.noParent) continue; if (row.parentServerId !== null && row.parentServerId !== row.id && byId.has(row.parentServerId)) { out.set(row.id, { parentId: row.parentServerId, auto: false }); continue; @@ -86,6 +89,6 @@ export function wouldLoop(rows: ParentRow[], id: number, parentId: number): bool export async function loadParentRows(): Promise { return db - .select({ id: servers.id, name: servers.name, hostname: servers.hostname, parentServerId: servers.parentServerId, proxmoxNode: servers.proxmoxNode }) + .select({ id: servers.id, name: servers.name, hostname: servers.hostname, parentServerId: servers.parentServerId, proxmoxNode: servers.proxmoxNode, noParent: servers.noParent }) .from(servers); } diff --git a/server/test/hardening.test.ts b/server/test/hardening.test.ts index 3a835e1..f1f3c7a 100644 --- a/server/test/hardening.test.ts +++ b/server/test/hardening.test.ts @@ -358,6 +358,14 @@ describe("Linux agent", () => { // The two intended expansions, and nothing else turned into something unexpected. assert.equal(settings.get("EnvironmentFile"), "/etc/homelab-manager-agent.env"); assert.equal(settings.get("ExecStart"), "/usr/local/bin/homelab-manager-agent.sh"); + + // The one step that runs outside the sandbox (+) is the package-manager question, which may fail without stopping the report (-), + // and it hands its answer over through the unit's own private directory, which is where the script looks for it. + assert.equal(settings.get("ExecStartPre"), "-+/usr/local/bin/homelab-manager-agent.sh --prepare-updates"); + assert.equal(rendered.split("\n").filter((l) => /^ExecStartPre=/.test(l.trim())).length, 1, "only that one step is outside the sandbox"); + assert.equal(settings.get("RuntimeDirectory"), "homelab-manager-agent"); + assert.equal(settings.get("RuntimeDirectoryMode"), "0700"); + assert.ok(readFileSync(agentScript, "utf8").includes("/run/homelab-manager-agent/updates.json"), "the script looks where the unit leaves it"); assert.doesNotMatch(rendered, /[`\\]/); for (const [key, value] of Object.entries({ @@ -389,6 +397,18 @@ describe("Linux agent", () => { } }); + test("the update check can be run on its own, and what it leaves behind is read back through jq, not trusted", () => { + const text = readFileSync(agentScript, "utf8"); + assert.ok(text.includes("--prepare-updates) MODE=prepare")); + assert.ok(text.includes("--check-updates) MODE=check")); + assert.ok(text.includes("use_prepared_updates || collect_updates"), "the report uses the prepared answer first and asks itself otherwise"); + assert.ok(text.includes('find "$UPDATES_FILE" -mmin -10'), "an old answer isn't used"); + assert.ok(text.includes("jq -ce 'select(type == \"object\""), "the file is re-shaped by jq, so the report only carries the four known fields"); + assert.ok(text.includes('mv -f "$UPDATES_FILE.tmp" "$UPDATES_FILE"'), "written whole, then moved into place"); + // the two modes must not need a server address or a token + assert.ok(text.includes('[[ "$MODE" == "report" && ( -z "$API_URL" || -z "$API_TOKEN" ) ]]')); + }); + test("unit files are made readable by everyone (the umask above them is for the token file)", () => { const text = readFileSync(installScript, "utf8").replace(/\r\n/g, "\n"); assert.match(text, /chmod 644 "\$SYSTEMD_DIR\/homelab-manager-agent\.service" "\$SYSTEMD_DIR\/homelab-manager-agent\.timer"/); diff --git a/server/test/maintenanceSchedules.test.ts b/server/test/maintenanceSchedules.test.ts index e0ef87a..0e975fb 100644 --- a/server/test/maintenanceSchedules.test.ts +++ b/server/test/maintenanceSchedules.test.ts @@ -168,10 +168,42 @@ describe("the schedules and their windows", () => { assert.ok((await windowsOf(scheduleId)).length >= 12); }); + test("editing a schedule remakes the windows that haven't begun from the new settings, and keeps what is under way", async () => { + const now = Date.now(); + await db.insert(maintenanceWindows).values({ targetType: "server", targetId: a, reason: "x", startedAt: new Date(now - 60_000).toISOString(), endsAt: new Date(now + 600_000).toISOString(), source: `schedule:${scheduleId}:2000-01-02` }); + const edited = { ...good, name: "Patch weekend", reason: "", targets: [{ type: "server", id: a }], days: [6], startTime: "01:30", durationMinutes: 90 }; + const res = await call("PUT", `/schedules/${scheduleId}`, edited); + assert.equal(res.status, 200); + const future = (await windowsOf(scheduleId)).filter((w) => w.startedAt > new Date().toISOString()); + assert.ok(future.length >= 1 && future.length <= 2, `${future.length} Saturdays in the coming week`); + assert.ok(future.every((w) => w.targetId === a && w.reason === "Patch weekend" && new Date(w.startedAt).getUTCDay() === 6 && w.startedAt.includes("T01:30") && Date.parse(w.endsAt) - Date.parse(w.startedAt) === 90 * 60_000)); + assert.ok((await windowsOf(scheduleId)).some((w) => w.source.endsWith("2000-01-02")), "the one under way is left alone"); + await db.delete(maintenanceWindows).where(eq(maintenanceWindows.source, `schedule:${scheduleId}:2000-01-02`)); + const list = await (await call("GET", "/schedules")).json(); + assert.equal(list.schedules[0].name, "Patch weekend"); + assert.deepEqual(list.schedules[0].days, [6]); + assert.equal(list.schedules[0].reason, null); + assert.equal(list.schedules[0].targets.length, 1); + assert.equal(list.schedules[0].enabled, true); + + // a bad edit changes nothing; a schedule that is off stays off and makes nothing + assert.equal((await call("PUT", `/schedules/${scheduleId}`, { ...edited, timezone: "Mars/Olympus" })).status, 400); + assert.equal((await call("PUT", `/schedules/${scheduleId}`, { ...edited, targets: [{ type: "server", id: 99999 }] })).status, 400); + assert.equal((await call("PUT", "/schedules/99999", edited)).status, 404); + assert.equal((await (await call("GET", "/schedules")).json()).schedules[0].name, "Patch weekend"); + await call("PATCH", `/schedules/${scheduleId}`, { enabled: false }); + assert.equal((await (await call("PUT", `/schedules/${scheduleId}`, { ...edited, days: [0, 1] })).json()).windowsMade, 0); + assert.equal((await windowsOf(scheduleId)).filter((w) => w.startedAt > new Date().toISOString()).length, 0); + assert.equal((await (await call("GET", "/schedules")).json()).schedules[0].enabled, false); + await call("PUT", `/schedules/${scheduleId}`, { ...good, targets: [{ type: "server", id: a }, { type: "server", id: b }] }); + await call("PATCH", `/schedules/${scheduleId}`, { enabled: true }); + }); + test("only operators change schedules; a bad one is refused", async () => { who = "viewer"; assert.equal((await call("POST", "/schedules", { ...good, targets: [{ type: "server", id: a }] })).status, 403); assert.equal((await call("PATCH", `/schedules/${scheduleId}`, { enabled: false })).status, 403); + assert.equal((await call("PUT", `/schedules/${scheduleId}`, { ...good, targets: [{ type: "server", id: a }] })).status, 403); assert.equal((await call("DELETE", `/schedules/${scheduleId}`)).status, 403); assert.equal((await call("GET", "/schedules")).status, 200, "anyone signed in can see them"); who = "operator"; @@ -197,6 +229,6 @@ describe("the schedules and their windows", () => { assert.equal((await windowsOf(scheduleId)).filter((w) => w.startedAt > new Date().toISOString()).length, 0); assert.equal((await call("DELETE", `/schedules/${scheduleId}`)).status, 404); const actions = (await db.select().from(auditLog)).filter((e) => e.category === "maintenance").map((e) => e.action); - for (const wanted of ["create_schedule", "disable_schedule", "enable_schedule", "delete_schedule"]) assert.ok(actions.includes(wanted), wanted); + for (const wanted of ["create_schedule", "update_schedule", "disable_schedule", "enable_schedule", "delete_schedule"]) assert.ok(actions.includes(wanted), wanted); }); }); diff --git a/server/test/parentsAndUpdates.test.ts b/server/test/parentsAndUpdates.test.ts index 5909835..5ce0fd6 100644 --- a/server/test/parentsAndUpdates.test.ts +++ b/server/test/parentsAndUpdates.test.ts @@ -61,6 +61,14 @@ describe("resolveParents", () => { assert.equal(parents.get(6), undefined, "not its own parent"); }); + test("one said to run on nothing is not guessed at, and a link set by hand clears that", () => { + const rows = [row(1, "pve1"), { ...row(2, "web", { proxmoxNode: "pve1" }), noParent: true }, { ...row(3, "db", { proxmoxNode: "pve1", parentServerId: 1 }), noParent: true }]; + const parents = resolveParents(rows); + assert.equal(parents.get(2), undefined, "no guess"); + assert.equal(parents.get(3), undefined, "no link either while it is set"); + assert.deepEqual(resolveParents([row(1, "pve1"), row(2, "web", { proxmoxNode: "pve1" })]).get(2), { parentId: 1, auto: true }, "unset, it is found again"); + }); + test("a server is not its own node", () => { assert.equal(resolveParents([row(1, "pve1", { proxmoxNode: "pve1" })]).size, 0); }); @@ -297,6 +305,34 @@ describe("the routes", () => { assert.equal((await (await call("GET", `/servers/${guestId}/detail`)).json()).relations.parent, null, "back to working it out"); }); + test("an admin can say a server runs on nothing, even when its Proxmox node would be found, and take that back", async () => { + const detailOf = async () => (await call("GET", `/servers/${guestId}/detail`)).json(); + await db.update(servers).set({ proxmoxNode: "rack" }).where(eq(servers.id, guestId)); + assert.deepEqual((await detailOf()).relations.parent, { id: hostId, name: "rack", auto: true }, "found from the node"); + + assert.equal((await call("PATCH", `/servers/${guestId}`, { noParent: true })).status, 200); + let d = await detailOf(); + assert.equal(d.relations.parent, null); + assert.equal(d.server.noParent, true); + assert.deepEqual((await (await call("GET", `/servers/${hostId}/detail`)).json()).relations.children, [], "and the host no longer lists it"); + + // choosing a server by hand ends it; so does going back to automatic + assert.equal((await call("PATCH", `/servers/${guestId}`, { parentServerId: hostId })).status, 200); + d = await detailOf(); + assert.equal(d.server.noParent, false); + assert.deepEqual(d.relations.parent, { id: hostId, name: "rack", auto: false }); + await call("PATCH", `/servers/${guestId}`, { noParent: true }); + assert.equal((await call("PATCH", `/servers/${guestId}`, { parentServerId: null })).status, 200); + d = await detailOf(); + assert.equal(d.server.noParent, false); + assert.deepEqual(d.relations.parent, { id: hostId, name: "rack", auto: true }); + + who = "operator"; + assert.equal((await call("PATCH", `/servers/${guestId}`, { noParent: true })).status, 403); + who = "admin"; + await db.update(servers).set({ proxmoxNode: null }).where(eq(servers.id, guestId)); + }); + test("removing the host sets the servers on it free", async () => { await call("PATCH", `/servers/${guestId}`, { parentServerId: hostId }); assert.equal((await call("DELETE", `/servers/${hostId}`)).status, 204); diff --git a/web/src/api/client.ts b/web/src/api/client.ts index 94b20be..7948926 100644 --- a/web/src/api/client.ts +++ b/web/src/api/client.ts @@ -518,6 +518,8 @@ export interface ServerRecord { proxmoxGuestType: "qemu" | "lxc" | null; proxmoxVmid: number | null; hideProxmoxLink: boolean; + /** An admin said it runs on nothing, so nothing is worked out for it. */ + noParent: boolean; tags: string[]; /** The server this one runs on, when an admin said so; null means it is worked out from the Proxmox node. */ parentServerId: number | null; @@ -851,6 +853,8 @@ export interface ServerUpdateInput { hideProxmoxLink?: boolean; /** The server this one runs on; null goes back to working it out from the Proxmox node. */ parentServerId?: number | null; + /** True says it runs on nothing, which stops the guess from its Proxmox node. */ + noParent?: boolean; } /** A maintenance that repeats: "every Sunday 02:00–04:00 on these servers". */ @@ -1489,6 +1493,7 @@ export const api = { schedules: { list: () => request<{ schedules: MaintenanceSchedule[] }>("/api/maintenance/schedules"), create: (data: MaintenanceScheduleInput) => request<{ id: number; windowsMade: number }>("/api/maintenance/schedules", { method: "POST", body: JSON.stringify(data) }), + update: (id: number, data: MaintenanceScheduleInput) => request<{ windowsMade: number }>(`/api/maintenance/schedules/${id}`, { method: "PUT", body: JSON.stringify(data) }), setEnabled: (id: number, enabled: boolean) => request<{ enabled: boolean }>(`/api/maintenance/schedules/${id}`, { method: "PATCH", body: JSON.stringify({ enabled }) }), remove: (id: number) => request(`/api/maintenance/schedules/${id}`, { method: "DELETE" }), }, diff --git a/web/src/components/ExportTableButton.tsx b/web/src/components/ExportTableButton.tsx new file mode 100644 index 0000000..16c2c81 --- /dev/null +++ b/web/src/components/ExportTableButton.tsx @@ -0,0 +1,38 @@ +import { useEffect, useRef, useState } from "react"; +import { downloadCsv, tableToRows } from "../utils/csv"; + +/** + * "Export CSV" for a table that has no export of its own. It reads the table as it is on screen, so what you see is what you get. + * By default it takes the first table in the same card; `of="next"` takes the table that follows the element this button sits in + * (for a card with several tables, each under its own small heading). With no table to read it shows nothing. + */ +export default function ExportTableButton({ filename, of = "card", className = "btn btn-sm btn-outline-secondary" }: { filename: string; of?: "card" | "next"; className?: string }) { + const ref = useRef(null); + const [hasTable, setHasTable] = useState(true); + + function findTable(): HTMLTableElement | null { + const button = ref.current; + if (!button) return null; + const scope = of === "next" ? button.parentElement?.nextElementSibling : button.closest(".card"); + return scope instanceof HTMLTableElement ? scope : (scope?.querySelector("table") ?? null); + } + + // The table may arrive after the button (loading, an empty list filling up), so look again after every render. + useEffect(() => { + const found = findTable() !== null; + if (found !== hasTable) setHasTable(found); + }); + + function exportNow() { + const table = findTable(); + if (!table) return; + const { headers, rows } = tableToRows(table); + downloadCsv(filename.endsWith(".csv") ? filename : `${filename}.csv`, headers, rows); + } + + return ( + + ); +} diff --git a/web/src/components/RecurringMaintenance.tsx b/web/src/components/RecurringMaintenance.tsx index 4b2cced..e751a31 100644 --- a/web/src/components/RecurringMaintenance.tsx +++ b/web/src/components/RecurringMaintenance.tsx @@ -5,6 +5,7 @@ import { readableError } from "../utils/errors"; import { toast } from "../utils/toast"; import TimeAgo from "./TimeAgo"; import { ErrorNotice } from "./Notice"; +import ExportTableButton from "./ExportTableButton"; // Monday first, as a week reads; the numbers are what the server keeps (0 = Sunday). const DAYS: { value: number; short: string }[] = [ @@ -57,9 +58,14 @@ export default function RecurringMaintenance({ canEdit, targets, onChanged }: { const [schedules, setSchedules] = useState(null); const [error, setError] = useState(null); const [adding, setAdding] = useState(false); + // The schedule being changed, if the form is open to change one rather than to add one. + const [editingId, setEditingId] = useState(null); const [busy, setBusy] = useState(false); - const timezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; + const browserTimezone = Intl.DateTimeFormat().resolvedOptions().timeZone || "UTC"; + // A schedule keeps the zone it was made in when it is changed; a new one uses this browser's. + const [scheduleZone, setScheduleZone] = useState(null); + const timezone = scheduleZone ?? browserTimezone; const [name, setName] = useState(""); const [reason, setReason] = useState(""); const [days, setDays] = useState([0]); @@ -91,6 +97,31 @@ export default function RecurringMaintenance({ canEdit, targets, onChanged }: { }); } + function closeForm() { + setAdding(false); + setEditingId(null); + setScheduleZone(null); + setName(""); + setReason(""); + setDays([0]); + setStartTime("02:00"); + setMinutes(120); + setPicked(new Set()); + } + + function startEditing(s: MaintenanceSchedule) { + setError(null); + setEditingId(s.id); + setScheduleZone(s.timezone); + setName(s.name); + setReason(s.reason ?? ""); + setDays(s.days); + setStartTime(s.startTime); + setMinutes(s.durationMinutes); + setPicked(new Set(s.targets.map((t) => key(t.type, t.id)))); + setAdding(true); + } + async function create(e: React.FormEvent) { e.preventDefault(); setError(null); @@ -100,12 +131,10 @@ export default function RecurringMaintenance({ canEdit, targets, onChanged }: { const [type, id] = k.split(":"); return { type: type as MaintenanceTargetType, id: Number(id) }; }); - const res = await api.maintenance.schedules.create({ name: name.trim(), reason: reason.trim() || undefined, targets: chosen, days, startTime, durationMinutes: minutes, timezone }); + const input = { name: name.trim(), reason: reason.trim() || undefined, targets: chosen, days, startTime, durationMinutes: minutes, timezone }; + const res = editingId === null ? await api.maintenance.schedules.create(input) : await api.maintenance.schedules.update(editingId, input); toast.success(`Saved. ${res.windowsMade} maintenance window${res.windowsMade === 1 ? "" : "s"} made for the coming week.`); - setName(""); - setReason(""); - setPicked(new Set()); - setAdding(false); + closeForm(); load(); onChanged(); } catch (err) { @@ -143,13 +172,14 @@ export default function RecurringMaintenance({ canEdit, targets, onChanged }: {

Recurring

- {canEdit && !adding && ( -
- -
- )} + )} +
{adding && ( @@ -194,6 +224,8 @@ export default function RecurringMaintenance({ canEdit, targets, onChanged }: { For void change(e.target.value)}> - + -
Automatic means worked out from its Proxmox node. If it stops reporting, this server's offline alert is folded under its host's.
+
Automatic means worked out from its Proxmox node. If it stops reporting, this server's offline alert is folded under its host's. "Nothing" stops that, so it always alerts for itself.
); } diff --git a/web/src/pages/Maintenance.tsx b/web/src/pages/Maintenance.tsx index 76dc727..1f6298f 100644 --- a/web/src/pages/Maintenance.tsx +++ b/web/src/pages/Maintenance.tsx @@ -19,6 +19,7 @@ import { toast } from "../utils/toast"; import { confirmDialog } from "../utils/dialogs"; import MaintenanceTimeline from "../components/MaintenanceTimeline"; import RecurringMaintenance from "../components/RecurringMaintenance"; +import ExportTableButton from "../components/ExportTableButton"; const DURATIONS: { minutes: number; label: string }[] = [ { minutes: 30, label: "30 minutes" }, @@ -479,6 +480,9 @@ export default function Maintenance({ user }: { user: CurrentUser }) {

Address aliases

+
+ +
@@ -579,6 +583,9 @@ export default function Maintenance({ user }: { user: CurrentUser }) {

Scheduled

+
+ +
@@ -598,11 +605,11 @@ export default function Maintenance({ user }: { user: CurrentUser }) { {w.targetName} · {w.targetKind} - - + {canEdit && (
{w.reason ?? "—"} + in {formatRemaining(w.startedAt, now)} {formatDateTime(new Date(w.startedAt))} {formatDateTime(new Date(w.endsAt))}{formatDateTime(new Date(w.endsAt))} - - )} + )} +
@@ -652,7 +660,7 @@ export default function Maintenance({ user }: { user: CurrentUser }) { {w.source?.startsWith("kuma:") && Uptime Kuma} - diff --git a/web/src/pages/PbsBackup.tsx b/web/src/pages/PbsBackup.tsx index 2f8f58f..4666d87 100644 --- a/web/src/pages/PbsBackup.tsx +++ b/web/src/pages/PbsBackup.tsx @@ -14,6 +14,7 @@ import { formatDateTime } from "../utils/date"; import { downloadCsv } from "../utils/csv"; import IntegrationPageTitle from "../components/IntegrationPageTitle"; import { ErrorNotice } from "../components/Notice"; +import ExportTableButton from "../components/ExportTableButton"; function formatBytes(bytes: number | null): string { if (bytes === null) return "—"; @@ -297,6 +298,9 @@ export default function PbsBackup({ user: _user }: { user: CurrentUser }) {

Recent verification failures

+
+ +
{w.reason ?? "—"} + {formatRemaining(w.endsAt, now)} left {formatDateTime(new Date(w.endsAt))}
diff --git a/web/src/pages/Proxmox.tsx b/web/src/pages/Proxmox.tsx index 675e9a9..0c0b033 100644 --- a/web/src/pages/Proxmox.tsx +++ b/web/src/pages/Proxmox.tsx @@ -25,6 +25,7 @@ import { useTableSearch } from "../hooks/useTableSearch"; import DetailDrawer, { ObjectDetails } from "../components/DetailDrawer"; import { useRowDetail } from "../hooks/useRowDetail"; import { formatDateTime } from "../utils/date"; +import ExportTableButton from "../components/ExportTableButton"; function proxmoxStatusBadge(status: string) { return status === "running" ? ( @@ -381,7 +382,10 @@ export default function Proxmox({ user }: { user: CurrentUser }) { )} -
Scheduled jobs
+
+ Scheduled jobs + +
{backupJobs && backupJobs.length > 0 ? (
@@ -413,7 +417,10 @@ export default function Proxmox({ user }: { user: CurrentUser }) { !backupsError &&
No backup jobs configured in Proxmox.
)} -
Guests without backup coverage
+
+ Guests without backup coverage + +
{uncoveredGuests && uncoveredGuests.length > 0 ? (
@@ -444,7 +451,10 @@ export default function Proxmox({ user }: { user: CurrentUser }) { uncoveredGuests &&
Every VM/LXC is covered by at least one enabled backup job.
)} -
Recent runs
+
+ Recent runs + +
{backupTasks && backupTasks.length > 0 ? (
diff --git a/web/src/pages/ServerCompare.tsx b/web/src/pages/ServerCompare.tsx index a8175bc..af32a1a 100644 --- a/web/src/pages/ServerCompare.tsx +++ b/web/src/pages/ServerCompare.tsx @@ -3,6 +3,7 @@ import { Link, useSearchParams } from "react-router-dom"; import { api, type ServerMetricSeries, type ServerRecord } from "../api/client"; import MultiLineChart, { type ChartSeries } from "../components/MultiLineChart"; import { BlockSkeleton } from "../components/Skeleton"; +import ExportTableButton from "../components/ExportTableButton"; const MAX_SERVERS = 4; const RANGES = [ @@ -132,6 +133,7 @@ export default function ServerCompare() { ))} +
{failed ? ( diff --git a/web/src/pages/ServerDetail.tsx b/web/src/pages/ServerDetail.tsx index ecf929c..463086f 100644 --- a/web/src/pages/ServerDetail.tsx +++ b/web/src/pages/ServerDetail.tsx @@ -762,7 +762,7 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
Runs on
- void loadDetail()} /> + void loadDetail()} />
{detail.relations.children.length > 0 && ( <> diff --git a/web/src/pages/Servers.tsx b/web/src/pages/Servers.tsx index 67db73a..e237e4c 100644 --- a/web/src/pages/Servers.tsx +++ b/web/src/pages/Servers.tsx @@ -20,6 +20,7 @@ import { SearchBox } from "../components/TableToolbar"; import { useTableSearch } from "../hooks/useTableSearch"; import SaveViewButton from "../components/SaveViewButton"; import { agentState } from "../utils/agent"; +import { BlockSkeleton } from "../components/Skeleton"; function typeBadgeStyle(colors: Record, type: string): CSSProperties { const color = colors[type]; @@ -32,6 +33,8 @@ export default function Servers({ user }: { user: CurrentUser }) { const isAdmin = user.role === "admin"; const [servers, setServers] = useState([]); + // Until the first answer arrives there is nothing to say about "no servers", so show the page's shape instead of the empty message. + const [loaded, setLoaded] = useState(false); const [agentLatest, setAgentLatest] = useState(null); const [error, setError] = useState(null); const [managingServers, setManagingServers] = useState(false); @@ -74,7 +77,8 @@ export default function Servers({ user }: { user: CurrentUser }) { setServers(res.servers); setAgentLatest(res.agentLatest); }) - .catch((err) => setError(String(err))); + .catch((err) => setError(String(err))) + .finally(() => setLoaded(true)); }, []); useEffect(() => { @@ -428,7 +432,7 @@ export default function Servers({ user }: { user: CurrentUser }) { ))} - {sortedServers?.length === 0 && ( + {loaded && sortedServers?.length === 0 && (
No servers registered yet. @@ -441,6 +445,12 @@ export default function Servers({ user }: { user: CurrentUser }) { + ) : !loaded ? ( +
+
+ +
+
) : servers.length === 0 ? (
diff --git a/web/src/pages/Updates.tsx b/web/src/pages/Updates.tsx index 216e7b9..c497c4b 100644 --- a/web/src/pages/Updates.tsx +++ b/web/src/pages/Updates.tsx @@ -12,6 +12,7 @@ import { useSortable } from "../hooks/useSortable"; import { useTableSearch } from "../hooks/useTableSearch"; import { downloadCsv } from "../utils/csv"; import { readableError } from "../utils/errors"; +import ExportTableButton from "../components/ExportTableButton"; interface Row { id: number; @@ -220,6 +221,9 @@ export default function Updates() {

Docker containers with a newer image

+
+ +
diff --git a/web/src/pages/settings/ApiSettings.tsx b/web/src/pages/settings/ApiSettings.tsx index 631d7fc..1988fba 100644 --- a/web/src/pages/settings/ApiSettings.tsx +++ b/web/src/pages/settings/ApiSettings.tsx @@ -6,6 +6,7 @@ import { ErrorNotice } from "../../components/Notice"; import { confirmDialog } from "../../utils/dialogs"; import { readableError } from "../../utils/errors"; import { toast } from "../../utils/toast"; +import ExportTableButton from "../../components/ExportTableButton"; const EVENT_WORDS: Record = { "alert.opened": "A problem begins", @@ -139,6 +140,9 @@ export default function ApiSettings() {

Metrics for Prometheus

+
+ +

@@ -218,13 +222,14 @@ export default function ApiSettings() {

Event webhooks

- {!adding && ( -
+
+ + {!adding && ( -
- )} + )} +

diff --git a/web/src/pages/settings/ShareSettings.tsx b/web/src/pages/settings/ShareSettings.tsx index ea59e24..982e6b4 100644 --- a/web/src/pages/settings/ShareSettings.tsx +++ b/web/src/pages/settings/ShareSettings.tsx @@ -7,6 +7,7 @@ import { confirmDialog } from "../../utils/dialogs"; import { formatDateTime } from "../../utils/date"; import { readableError } from "../../utils/errors"; import { toast } from "../../utils/toast"; +import ExportTableButton from "../../components/ExportTableButton"; const LASTS: { days: number | null; label: string }[] = [ { days: null, label: "Until I remove it" }, @@ -144,6 +145,9 @@ export default function ShareSettings() {

Links

+
+ +
diff --git a/web/src/pages/settings/SignInSettings.tsx b/web/src/pages/settings/SignInSettings.tsx index aab89a1..bdcfb3d 100644 --- a/web/src/pages/settings/SignInSettings.tsx +++ b/web/src/pages/settings/SignInSettings.tsx @@ -4,6 +4,7 @@ import { ErrorNotice } from "../../components/Notice"; import { PageSkeleton } from "../../components/Skeleton"; import { readableError } from "../../utils/errors"; import { toast } from "../../utils/toast"; +import ExportTableButton from "../../components/ExportTableButton"; const DEFAULTS: SignInSettingsData = { roleFromGroups: false, groupsClaim: "groups", adminGroups: [], operatorGroups: [], otherwise: "viewer" }; @@ -147,6 +148,9 @@ export default function SignInSettings() {

What these rules would do

+
+ +
{preview.adminsAfter === 0 && (
diff --git a/web/src/pages/settings/TagSettings.tsx b/web/src/pages/settings/TagSettings.tsx index 7c4ad3b..e3a34b5 100644 --- a/web/src/pages/settings/TagSettings.tsx +++ b/web/src/pages/settings/TagSettings.tsx @@ -4,6 +4,7 @@ import { readableError } from "../../utils/errors"; import { normalizeTagInput, refreshTagColors, tagBadge } from "../../utils/tags"; import { confirmDialog, promptDialog } from "../../utils/dialogs"; import { ErrorNotice, SuccessNotice } from "../../components/Notice"; +import ExportTableButton from "../../components/ExportTableButton"; const DEFAULT_PICK = "#3b82f6"; @@ -145,6 +146,9 @@ export default function TagSettings() {

All tags

+
+ +
diff --git a/web/src/utils/csv.ts b/web/src/utils/csv.ts index 466a784..745261d 100644 --- a/web/src/utils/csv.ts +++ b/web/src/utils/csv.ts @@ -13,3 +13,39 @@ export function downloadCsv(filename: string, headers: string[], rows: unknown[] a.click(); URL.revokeObjectURL(url); } + +/** + * What a cell says as a person reads it — except times, which give their exact ISO value rather than "5 min ago". A cell, or anything in it, + * can say what it should be in a CSV with `data-csv="…"` (for a cell that mixes a badge and a date, say). + */ +function cellText(cell: Element): string { + const own = cell.getAttribute("data-csv"); + if (own !== null) return own; + const clone = cell.cloneNode(true) as Element; + clone.querySelectorAll("button, svg, input, select, textarea, .dropdown-menu, .visually-hidden").forEach((n) => n.remove()); + clone.querySelectorAll("[data-csv]").forEach((n) => n.replaceWith(n.getAttribute("data-csv") ?? "")); + clone.querySelectorAll("time[datetime]").forEach((t) => t.replaceWith(t.getAttribute("datetime") ?? "")); + // Lines and paragraphs inside a cell are words apart, not run together. + clone.querySelectorAll("div, p, li, br").forEach((n) => n.prepend(" ")); + return (clone.textContent ?? "").replace(/\s+/g, " ").trim(); +} + +const ACTION_HEADERS = new Set(["", "action", "actions"]); + +/** + * Reads a table as it is on screen — the header row, then each body row — for the many small tables that have no export of their own. + * Columns with no heading or headed "Actions" are left out, and so are rows that span the table (an empty message, an open detail). + */ +export function tableToRows(table: HTMLTableElement): { headers: string[]; rows: string[][] } { + const headCells = Array.from(table.tHead?.rows[table.tHead.rows.length - 1]?.cells ?? []); + const keep = headCells.map((th, i) => (ACTION_HEADERS.has(cellText(th).toLowerCase()) ? -1 : i)).filter((i) => i >= 0); + const headers = keep.map((i) => cellText(headCells[i])); + const rows: string[][] = []; + for (const body of Array.from(table.tBodies)) { + for (const tr of Array.from(body.rows)) { + if (tr.cells.length !== headCells.length) continue; + rows.push(keep.map((i) => cellText(tr.cells[i]))); + } + } + return { headers, rows }; +}