Export CSV on every table, edit recurring maintenance, runs-on nothing, and run package checks outside the agent sandbox
- Export CSV for the small tables that had none (reads the table as shown) - Servers page shows a skeleton while loading instead of "No servers registered yet" - Recurring maintenance schedules can be edited (PUT /schedules/:id) - A server can be set to run on nothing (servers.no_parent, migration 0028) - Linux agent v3: package-manager question runs in ExecStartPre=-+ outside the sandbox, with --prepare-updates and --check-updates modes - Docs: README, DATABASE, AGENT_UPDATE Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
c17e9aa140
commit
540ab704b7
32 files changed
+3003
-66
No files matched your search
+18
-5
@@ -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. |
|
| 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. |
|
| 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
|
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
|
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 |
|
| 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. |
|
| 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). |
|
| 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. |
|
| 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.
|
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.
|
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
|
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
|
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`), which suits `apt`'s
|
sandbox (read-only system, no hardware, minimal privileges, see `install.sh`), and `dnf` and `zypper` write to
|
||||||
simulation but may stop `dnf` or `zypper` from reading their caches. If you hit that, the sandbox is what
|
`/var` and `/run` even when only asked a question. So from agent version 3 the unit asks the package manager in
|
||||||
to look at; loosen it only as far as that one need, and only on the hosts that need it.
|
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.
|
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
|
A server that says nothing keeps what it last said — an agent that skips a report never turns an old figure
|
||||||
|
|||||||
+2
-1
@@ -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. |
|
| **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. |
|
| **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`. |
|
| **Tables** | 30 application tables, plus drizzle's own `__drizzle_migrations`. |
|
||||||
|
|
||||||
**Not in the database:**
|
**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. |
|
| `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. |
|
| `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. |
|
| `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. |
|
| `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. |
|
| `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. |
|
| `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. |
|
||||||
|
|||||||
@@ -164,6 +164,11 @@ All modules from the original plan are built:
|
|||||||
20 rows per page by default — adjustable under Settings → Display — and
|
20 rows per page by default — adjustable under Settings → Display — and
|
||||||
CSV export still covers every sorted/filtered row, not just the current
|
CSV export still covers every sorted/filtered row, not just the current
|
||||||
page.
|
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,
|
- **Settings** (admin-only) — notification channels (Gotify, ntfy, SMTP,
|
||||||
generic webhook) with per-channel test buttons, per-event toggles (DNS
|
generic webhook) with per-channel test buttons, per-event toggles (DNS
|
||||||
record added/updated/deleted, daily secret-expiry reminder and daily
|
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
|
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.
|
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
|
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
|
**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
|
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
|
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
|
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
|
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
|
**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
|
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
|
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.
|
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
|
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
|
hours, cached under `%ProgramData%\HomelabManager`). A server whose agent hasn't
|
||||||
said — an older agent, or another package manager — shows "not reported", never "up
|
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
|
to date"; run its install command again to update its agent (how, and how to
|
||||||
|
|||||||
@@ -88,6 +88,13 @@ Description=Report scheduled tasks to Homelab Manager
|
|||||||
Type=oneshot
|
Type=oneshot
|
||||||
EnvironmentFile=$CONFIG_DIR/homelab-manager-agent.env
|
EnvironmentFile=$CONFIG_DIR/homelab-manager-agent.env
|
||||||
ExecStart=$INSTALL_DIR/homelab-manager-agent.sh
|
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
|
# 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
|
# 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.
|
# how it names the program behind each listening port. Directives an older systemd doesn't know are ignored.
|
||||||
|
|||||||
@@ -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
|
# 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).
|
# 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
|
# 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}"
|
ENV_FILE="${ENV_FILE:-/etc/homelab-manager-agent.env}"
|
||||||
if [[ -f "$ENV_FILE" ]]; then
|
if [[ -f "$ENV_FILE" ]]; then
|
||||||
@@ -27,7 +28,22 @@ API_INSECURE="${API_INSECURE:-false}"
|
|||||||
DRY_RUN=0
|
DRY_RUN=0
|
||||||
[[ "${1:-}" == "--dry-run" ]] && DRY_RUN=1
|
[[ "${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
|
echo "API_URL and API_TOKEN must be set (env vars or $ENV_FILE)" >&2
|
||||||
exit 1
|
exit 1
|
||||||
fi
|
fi
|
||||||
@@ -196,7 +212,7 @@ collect_updates() {
|
|||||||
if command -v apt-get >/dev/null 2>&1; then
|
if command -v apt-get >/dev/null 2>&1; then
|
||||||
manager="apt"
|
manager="apt"
|
||||||
# -s simulates: "Inst" lines are what an upgrade would install. Security ones come from a "-security" or "Security" archive.
|
# -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)
|
count=$(grep -c '^Inst ' <<<"$out" || true)
|
||||||
security=$(grep '^Inst ' <<<"$out" | grep -ci 'security' || true)
|
security=$(grep '^Inst ' <<<"$out" | grep -ci 'security' || true)
|
||||||
fi
|
fi
|
||||||
@@ -204,17 +220,17 @@ collect_updates() {
|
|||||||
elif command -v dnf >/dev/null 2>&1; then
|
elif command -v dnf >/dev/null 2>&1; then
|
||||||
manager="dnf"
|
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.
|
# 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
|
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")
|
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
|
fi
|
||||||
if command -v needs-restarting >/dev/null 2>&1; then
|
if command -v needs-restarting >/dev/null 2>&1; then
|
||||||
needs-restarting -r >/dev/null 2>&1 || reboot="true"
|
needs-restarting -r >/dev/null 2>&1 || reboot="true"
|
||||||
fi
|
fi
|
||||||
elif command -v zypper >/dev/null 2>&1; then
|
elif command -v zypper >/dev/null 2>&1; then
|
||||||
manager="zypper"
|
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)
|
count=$(grep -c '^v |' <<<"$out" || true)
|
||||||
fi
|
fi
|
||||||
[[ -f /run/reboot-needed ]] && reboot="true"
|
[[ -f /run/reboot-needed ]] && reboot="true"
|
||||||
@@ -232,6 +248,18 @@ collect_updates() {
|
|||||||
fi
|
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() {
|
collect_system_info() {
|
||||||
local ip_json="[]"
|
local ip_json="[]"
|
||||||
if command -v ip >/dev/null 2>&1; then
|
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.
|
# Best-effort like the rest: a package manager that misbehaves must not cost the report.
|
||||||
UPDATES_JSON="null"
|
UPDATES_JSON="null"
|
||||||
collect_updates || UPDATES_JSON="null"
|
use_prepared_updates || collect_updates || UPDATES_JSON="null"
|
||||||
|
|
||||||
SYSTEM_JSON=$(jq -n \
|
SYSTEM_JSON=$(jq -n \
|
||||||
--argjson updates "$UPDATES_JSON" \
|
--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_cron
|
||||||
collect_systemd_timers
|
collect_systemd_timers
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1 @@
|
|||||||
|
ALTER TABLE `servers` ADD `no_parent` integer DEFAULT false NOT NULL;
|
||||||
File diff suppressed because it is too large.
Load diff
@@ -197,6 +197,13 @@
|
|||||||
"when": 1792260718106,
|
"when": 1792260718106,
|
||||||
"tag": "0027_bizarre_magus",
|
"tag": "0027_bizarre_magus",
|
||||||
"breakpoints": true
|
"breakpoints": true
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"idx": 28,
|
||||||
|
"version": "6",
|
||||||
|
"when": 1792267930026,
|
||||||
|
"tag": "0028_thankful_ultron",
|
||||||
|
"breakpoints": true
|
||||||
}
|
}
|
||||||
]
|
]
|
||||||
}
|
}
|
||||||
@@ -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 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.
|
// 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"),
|
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.
|
// What the agent says is waiting to be installed, as JSON: {manager, count, security, rebootRequired, reportedAt}. Null until it reports.
|
||||||
pendingUpdates: text("pending_updates"),
|
pendingUpdates: text("pending_updates"),
|
||||||
|
|||||||
@@ -309,23 +309,32 @@ maintenanceRouter.get("/schedules", asyncHandler(async (_req, res) => {
|
|||||||
res.json({ schedules: out });
|
res.json({ schedules: out });
|
||||||
}));
|
}));
|
||||||
|
|
||||||
maintenanceRouter.post("/schedules", requireRole("operator"), asyncHandler(async (req, res) => {
|
type ScheduleBody = z.infer<typeof scheduleSchema>;
|
||||||
const parsed = scheduleSchema.safeParse(req.body);
|
|
||||||
|
/** 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) {
|
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;
|
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." });
|
if (!isValidTimeZone(data.timezone)) return { status: 400, json: { error: "invalid_timezone", message: "That isn't a time zone this server knows." } };
|
||||||
// Only things that exist, once each.
|
|
||||||
const seen = new Set<string>();
|
const seen = new Set<string>();
|
||||||
const targets = [];
|
const targets: ScheduleBody["targets"] = [];
|
||||||
for (const t of data.targets) {
|
for (const t of data.targets) {
|
||||||
const key = `${t.type}:${t.id}`;
|
const key = `${t.type}:${t.id}`;
|
||||||
if (seen.has(key)) continue;
|
if (seen.has(key)) continue;
|
||||||
seen.add(key);
|
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);
|
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 actor = req.currentUser!;
|
||||||
const [created] = await db
|
const [created] = await db
|
||||||
.insert(maintenanceSchedules)
|
.insert(maintenanceSchedules)
|
||||||
@@ -345,6 +354,36 @@ maintenanceRouter.post("/schedules", requireRole("operator"), asyncHandler(async
|
|||||||
res.status(201).json({ id: created.id, windowsMade: made });
|
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) => {
|
maintenanceRouter.patch("/schedules/:id", requireRole("operator"), asyncHandler(async (req, res) => {
|
||||||
const id = Number(req.params.id);
|
const id = Number(req.params.id);
|
||||||
const parsed = z.object({ enabled: z.boolean() }).safeParse(req.body);
|
const parsed = z.object({ enabled: z.boolean() }).safeParse(req.body);
|
||||||
|
|||||||
@@ -120,6 +120,8 @@ const updateServerSchema = z
|
|||||||
hideProxmoxLink: z.boolean().optional(),
|
hideProxmoxLink: z.boolean().optional(),
|
||||||
// The server this one runs on. Null goes back to working it out from the Proxmox node.
|
// The server this one runs on. Null goes back to working it out from the Proxmox node.
|
||||||
parentServerId: z.number().int().nullable().optional(),
|
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(
|
.refine(
|
||||||
(data) => {
|
(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({
|
await recordAudit({
|
||||||
actor: req.currentUser!,
|
actor: req.currentUser!,
|
||||||
@@ -174,7 +179,7 @@ serversRouter.patch("/:id", requireRole("admin"), asyncHandler(async (req, res)
|
|||||||
action: "update",
|
action: "update",
|
||||||
targetType: "server",
|
targetType: "server",
|
||||||
targetId: id,
|
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);
|
const serverOut = publicServer(updated);
|
||||||
|
|||||||
@@ -6,6 +6,7 @@
|
|||||||
*
|
*
|
||||||
* 1 — before the number was reported (so an agent that says nothing is version 1)
|
* 1 — before the number was reported (so an agent that says nothing is version 1)
|
||||||
* 2 — reports pending updates, and its own version
|
* 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 { readFileSync } from "node:fs";
|
||||||
import { dirname, join } from "node:path";
|
import { dirname, join } from "node:path";
|
||||||
|
|||||||
@@ -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
|
* 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
|
* 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
|
* 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 { db } from "../db/client.js";
|
||||||
import { servers } from "../db/schema.js";
|
import { servers } from "../db/schema.js";
|
||||||
@@ -13,6 +13,8 @@ export interface ParentRow {
|
|||||||
hostname: string | null;
|
hostname: string | null;
|
||||||
parentServerId: number | null;
|
parentServerId: number | null;
|
||||||
proxmoxNode: string | 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 {
|
export interface ParentLink {
|
||||||
@@ -36,6 +38,7 @@ export function resolveParents(rows: ParentRow[]): Map<number, ParentLink> {
|
|||||||
const byId = new Map(rows.map((r) => [r.id, r]));
|
const byId = new Map(rows.map((r) => [r.id, r]));
|
||||||
const out = new Map<number, ParentLink>();
|
const out = new Map<number, ParentLink>();
|
||||||
for (const row of rows) {
|
for (const row of rows) {
|
||||||
|
if (row.noParent) continue;
|
||||||
if (row.parentServerId !== null && row.parentServerId !== row.id && byId.has(row.parentServerId)) {
|
if (row.parentServerId !== null && row.parentServerId !== row.id && byId.has(row.parentServerId)) {
|
||||||
out.set(row.id, { parentId: row.parentServerId, auto: false });
|
out.set(row.id, { parentId: row.parentServerId, auto: false });
|
||||||
continue;
|
continue;
|
||||||
@@ -86,6 +89,6 @@ export function wouldLoop(rows: ParentRow[], id: number, parentId: number): bool
|
|||||||
|
|
||||||
export async function loadParentRows(): Promise<ParentRow[]> {
|
export async function loadParentRows(): Promise<ParentRow[]> {
|
||||||
return db
|
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);
|
.from(servers);
|
||||||
}
|
}
|
||||||
@@ -358,6 +358,14 @@ describe("Linux agent", () => {
|
|||||||
// The two intended expansions, and nothing else turned into something unexpected.
|
// 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("EnvironmentFile"), "/etc/homelab-manager-agent.env");
|
||||||
assert.equal(settings.get("ExecStart"), "/usr/local/bin/homelab-manager-agent.sh");
|
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, /[`\\]/);
|
assert.doesNotMatch(rendered, /[`\\]/);
|
||||||
|
|
||||||
for (const [key, value] of Object.entries({
|
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)", () => {
|
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");
|
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"/);
|
assert.match(text, /chmod 644 "\$SYSTEMD_DIR\/homelab-manager-agent\.service" "\$SYSTEMD_DIR\/homelab-manager-agent\.timer"/);
|
||||||
|
|||||||
@@ -168,10 +168,42 @@ describe("the schedules and their windows", () => {
|
|||||||
assert.ok((await windowsOf(scheduleId)).length >= 12);
|
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 () => {
|
test("only operators change schedules; a bad one is refused", async () => {
|
||||||
who = "viewer";
|
who = "viewer";
|
||||||
assert.equal((await call("POST", "/schedules", { ...good, targets: [{ type: "server", id: a }] })).status, 403);
|
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("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("DELETE", `/schedules/${scheduleId}`)).status, 403);
|
||||||
assert.equal((await call("GET", "/schedules")).status, 200, "anyone signed in can see them");
|
assert.equal((await call("GET", "/schedules")).status, 200, "anyone signed in can see them");
|
||||||
who = "operator";
|
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 windowsOf(scheduleId)).filter((w) => w.startedAt > new Date().toISOString()).length, 0);
|
||||||
assert.equal((await call("DELETE", `/schedules/${scheduleId}`)).status, 404);
|
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);
|
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);
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
@@ -61,6 +61,14 @@ describe("resolveParents", () => {
|
|||||||
assert.equal(parents.get(6), undefined, "not its own parent");
|
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", () => {
|
test("a server is not its own node", () => {
|
||||||
assert.equal(resolveParents([row(1, "pve1", { proxmoxNode: "pve1" })]).size, 0);
|
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");
|
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 () => {
|
test("removing the host sets the servers on it free", async () => {
|
||||||
await call("PATCH", `/servers/${guestId}`, { parentServerId: hostId });
|
await call("PATCH", `/servers/${guestId}`, { parentServerId: hostId });
|
||||||
assert.equal((await call("DELETE", `/servers/${hostId}`)).status, 204);
|
assert.equal((await call("DELETE", `/servers/${hostId}`)).status, 204);
|
||||||
|
|||||||
@@ -518,6 +518,8 @@ export interface ServerRecord {
|
|||||||
proxmoxGuestType: "qemu" | "lxc" | null;
|
proxmoxGuestType: "qemu" | "lxc" | null;
|
||||||
proxmoxVmid: number | null;
|
proxmoxVmid: number | null;
|
||||||
hideProxmoxLink: boolean;
|
hideProxmoxLink: boolean;
|
||||||
|
/** An admin said it runs on nothing, so nothing is worked out for it. */
|
||||||
|
noParent: boolean;
|
||||||
tags: string[];
|
tags: string[];
|
||||||
/** The server this one runs on, when an admin said so; null means it is worked out from the Proxmox node. */
|
/** The server this one runs on, when an admin said so; null means it is worked out from the Proxmox node. */
|
||||||
parentServerId: number | null;
|
parentServerId: number | null;
|
||||||
@@ -851,6 +853,8 @@ export interface ServerUpdateInput {
|
|||||||
hideProxmoxLink?: boolean;
|
hideProxmoxLink?: boolean;
|
||||||
/** The server this one runs on; null goes back to working it out from the Proxmox node. */
|
/** The server this one runs on; null goes back to working it out from the Proxmox node. */
|
||||||
parentServerId?: number | null;
|
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". */
|
/** A maintenance that repeats: "every Sunday 02:00–04:00 on these servers". */
|
||||||
@@ -1489,6 +1493,7 @@ export const api = {
|
|||||||
schedules: {
|
schedules: {
|
||||||
list: () => request<{ schedules: MaintenanceSchedule[] }>("/api/maintenance/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) }),
|
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 }) }),
|
setEnabled: (id: number, enabled: boolean) => request<{ enabled: boolean }>(`/api/maintenance/schedules/${id}`, { method: "PATCH", body: JSON.stringify({ enabled }) }),
|
||||||
remove: (id: number) => request<void>(`/api/maintenance/schedules/${id}`, { method: "DELETE" }),
|
remove: (id: number) => request<void>(`/api/maintenance/schedules/${id}`, { method: "DELETE" }),
|
||||||
},
|
},
|
||||||
|
|||||||
@@ -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<HTMLButtonElement>(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 (
|
||||||
|
<button ref={ref} type="button" className={className} onClick={exportNow} hidden={!hasTable}>
|
||||||
|
Export CSV
|
||||||
|
</button>
|
||||||
|
);
|
||||||
|
}
|
||||||
@@ -5,6 +5,7 @@ import { readableError } from "../utils/errors";
|
|||||||
import { toast } from "../utils/toast";
|
import { toast } from "../utils/toast";
|
||||||
import TimeAgo from "./TimeAgo";
|
import TimeAgo from "./TimeAgo";
|
||||||
import { ErrorNotice } from "./Notice";
|
import { ErrorNotice } from "./Notice";
|
||||||
|
import ExportTableButton from "./ExportTableButton";
|
||||||
|
|
||||||
// Monday first, as a week reads; the numbers are what the server keeps (0 = Sunday).
|
// Monday first, as a week reads; the numbers are what the server keeps (0 = Sunday).
|
||||||
const DAYS: { value: number; short: string }[] = [
|
const DAYS: { value: number; short: string }[] = [
|
||||||
@@ -57,9 +58,14 @@ export default function RecurringMaintenance({ canEdit, targets, onChanged }: {
|
|||||||
const [schedules, setSchedules] = useState<MaintenanceSchedule[] | null>(null);
|
const [schedules, setSchedules] = useState<MaintenanceSchedule[] | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [adding, setAdding] = useState(false);
|
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<number | null>(null);
|
||||||
const [busy, setBusy] = useState(false);
|
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<string | null>(null);
|
||||||
|
const timezone = scheduleZone ?? browserTimezone;
|
||||||
const [name, setName] = useState("");
|
const [name, setName] = useState("");
|
||||||
const [reason, setReason] = useState("");
|
const [reason, setReason] = useState("");
|
||||||
const [days, setDays] = useState<number[]>([0]);
|
const [days, setDays] = useState<number[]>([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) {
|
async function create(e: React.FormEvent) {
|
||||||
e.preventDefault();
|
e.preventDefault();
|
||||||
setError(null);
|
setError(null);
|
||||||
@@ -100,12 +131,10 @@ export default function RecurringMaintenance({ canEdit, targets, onChanged }: {
|
|||||||
const [type, id] = k.split(":");
|
const [type, id] = k.split(":");
|
||||||
return { type: type as MaintenanceTargetType, id: Number(id) };
|
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.`);
|
toast.success(`Saved. ${res.windowsMade} maintenance window${res.windowsMade === 1 ? "" : "s"} made for the coming week.`);
|
||||||
setName("");
|
closeForm();
|
||||||
setReason("");
|
|
||||||
setPicked(new Set());
|
|
||||||
setAdding(false);
|
|
||||||
load();
|
load();
|
||||||
onChanged();
|
onChanged();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
@@ -143,13 +172,14 @@ export default function RecurringMaintenance({ canEdit, targets, onChanged }: {
|
|||||||
<div className="card mb-3">
|
<div className="card mb-3">
|
||||||
<div className="card-header">
|
<div className="card-header">
|
||||||
<h3 className="card-title">Recurring</h3>
|
<h3 className="card-title">Recurring</h3>
|
||||||
{canEdit && !adding && (
|
<div className="card-actions">
|
||||||
<div className="card-actions">
|
<ExportTableButton filename="maintenance-recurring" />
|
||||||
<button type="button" className="btn btn-sm btn-primary" onClick={() => setAdding(true)}>
|
{canEdit && !adding && (
|
||||||
|
<button type="button" className="btn btn-sm btn-primary" onClick={() => { setError(null); setAdding(true); }}>
|
||||||
Add recurring maintenance
|
Add recurring maintenance
|
||||||
</button>
|
</button>
|
||||||
</div>
|
)}
|
||||||
)}
|
</div>
|
||||||
</div>
|
</div>
|
||||||
|
|
||||||
{adding && (
|
{adding && (
|
||||||
@@ -194,6 +224,8 @@ export default function RecurringMaintenance({ canEdit, targets, onChanged }: {
|
|||||||
For
|
For
|
||||||
</label>
|
</label>
|
||||||
<select id="rec-length" className="form-select" value={minutes} onChange={(e) => setMinutes(Number(e.target.value))}>
|
<select id="rec-length" className="form-select" value={minutes} onChange={(e) => setMinutes(Number(e.target.value))}>
|
||||||
|
{/* A schedule made some other way (or before these choices) keeps whatever length it has. */}
|
||||||
|
{!LENGTHS.some((l) => l.minutes === minutes) && <option value={minutes}>{minutes} minutes</option>}
|
||||||
{LENGTHS.map((l) => (
|
{LENGTHS.map((l) => (
|
||||||
<option key={l.minutes} value={l.minutes}>
|
<option key={l.minutes} value={l.minutes}>
|
||||||
{l.label}
|
{l.label}
|
||||||
@@ -245,9 +277,9 @@ export default function RecurringMaintenance({ canEdit, targets, onChanged }: {
|
|||||||
</div>
|
</div>
|
||||||
<div className="card-footer d-flex gap-2">
|
<div className="card-footer d-flex gap-2">
|
||||||
<button type="submit" className="btn btn-primary" disabled={busy || picked.size === 0 || days.length === 0 || name.trim() === ""}>
|
<button type="submit" className="btn btn-primary" disabled={busy || picked.size === 0 || days.length === 0 || name.trim() === ""}>
|
||||||
{busy ? "Saving…" : "Save"}
|
{busy ? "Saving…" : editingId === null ? "Save" : "Save changes"}
|
||||||
</button>
|
</button>
|
||||||
<button type="button" className="btn" onClick={() => setAdding(false)}>
|
<button type="button" className="btn" onClick={closeForm}>
|
||||||
Cancel
|
Cancel
|
||||||
</button>
|
</button>
|
||||||
</div>
|
</div>
|
||||||
@@ -277,12 +309,15 @@ export default function RecurringMaintenance({ canEdit, targets, onChanged }: {
|
|||||||
<td>{namesWords(s.targets.map((t) => t.name))}</td>
|
<td>{namesWords(s.targets.map((t) => t.name))}</td>
|
||||||
<td>
|
<td>
|
||||||
{daysWords(s.days)} {timeWords(s.startTime, s.durationMinutes)}
|
{daysWords(s.days)} {timeWords(s.startTime, s.durationMinutes)}
|
||||||
{s.timezone !== timezone && <span className="text-secondary small"> ({s.timezone})</span>}
|
{s.timezone !== browserTimezone && <span className="text-secondary small"> ({s.timezone})</span>}
|
||||||
</td>
|
</td>
|
||||||
<td>{s.nextStart ? <TimeAgo value={s.nextStart} /> : "—"}</td>
|
<td>{s.nextStart ? <TimeAgo value={s.nextStart} /> : "—"}</td>
|
||||||
{canEdit && (
|
{canEdit && (
|
||||||
<td>
|
<td>
|
||||||
<div className="btn-list flex-nowrap">
|
<div className="btn-list flex-nowrap">
|
||||||
|
<button type="button" className="btn btn-sm btn-outline-secondary" onClick={() => startEditing(s)} disabled={editingId === s.id}>
|
||||||
|
Edit
|
||||||
|
</button>
|
||||||
<button type="button" className="btn btn-sm btn-outline-secondary" onClick={() => void toggle(s)}>
|
<button type="button" className="btn btn-sm btn-outline-secondary" onClick={() => void toggle(s)}>
|
||||||
{s.enabled ? "Turn off" : "Turn on"}
|
{s.enabled ? "Turn off" : "Turn on"}
|
||||||
</button>
|
</button>
|
||||||
|
|||||||
@@ -7,9 +7,12 @@ import { toast } from "../utils/toast";
|
|||||||
/**
|
/**
|
||||||
* Which server this one runs on (a virtual machine on its host). When the host stops reporting, this server's own "offline" alert is
|
* Which server this one runs on (a virtual machine on its host). When the host stops reporting, this server's own "offline" alert is
|
||||||
* folded under the host's instead of being a second one. Left alone it is worked out from the Proxmox node the server is linked to;
|
* folded under the host's instead of being a second one. Left alone it is worked out from the Proxmox node the server is linked to;
|
||||||
* an admin can say it by hand. Everyone sees it; only admins change it.
|
* an admin can say it by hand, or say it runs on nothing (a physical machine that happens to carry a Proxmox node name).
|
||||||
|
* Everyone sees it; only admins change it.
|
||||||
*/
|
*/
|
||||||
export default function RunsOn({ serverId, parent, canEdit, onChanged }: { serverId: number; parent: ServerRelation | null; canEdit: boolean; onChanged: () => void }) {
|
const NONE = "none";
|
||||||
|
|
||||||
|
export default function RunsOn({ serverId, parent, noParent, canEdit, onChanged }: { serverId: number; parent: ServerRelation | null; noParent: boolean; canEdit: boolean; onChanged: () => void }) {
|
||||||
const [servers, setServers] = useState<ServerRecord[] | null>(null);
|
const [servers, setServers] = useState<ServerRecord[] | null>(null);
|
||||||
const [busy, setBusy] = useState(false);
|
const [busy, setBusy] = useState(false);
|
||||||
|
|
||||||
@@ -24,8 +27,8 @@ export default function RunsOn({ serverId, parent, canEdit, onChanged }: { serve
|
|||||||
async function change(value: string) {
|
async function change(value: string) {
|
||||||
setBusy(true);
|
setBusy(true);
|
||||||
try {
|
try {
|
||||||
await api.servers.update(serverId, { parentServerId: value === "" ? null : Number(value) });
|
await api.servers.update(serverId, value === NONE ? { noParent: true } : { parentServerId: value === "" ? null : Number(value) });
|
||||||
toast.success(value === "" ? "Back to working it out from the Proxmox node." : "Saved.");
|
toast.success(value === "" ? "Back to working it out from the Proxmox node." : value === NONE ? "It runs on nothing, so its alerts always stand alone." : "Saved.");
|
||||||
onChanged();
|
onChanged();
|
||||||
} catch (err) {
|
} catch (err) {
|
||||||
toast.error(readableError(err));
|
toast.error(readableError(err));
|
||||||
@@ -39,8 +42,9 @@ export default function RunsOn({ serverId, parent, canEdit, onChanged }: { serve
|
|||||||
}
|
}
|
||||||
return (
|
return (
|
||||||
<div>
|
<div>
|
||||||
<select className="form-select form-select-sm" aria-label="The server this one runs on" value={parent && !parent.auto ? String(parent.id) : ""} disabled={busy || servers === null} onChange={(e) => void change(e.target.value)}>
|
<select className="form-select form-select-sm" aria-label="The server this one runs on" value={noParent ? NONE : parent && !parent.auto ? String(parent.id) : ""} disabled={busy || servers === null} onChange={(e) => void change(e.target.value)}>
|
||||||
<option value="">{parent?.auto ? `Automatic: ${parent.name}` : "None (automatic)"}</option>
|
<option value="">{parent?.auto ? `Automatic: ${parent.name}` : "Automatic (none found)"}</option>
|
||||||
|
<option value={NONE}>Nothing — it runs on its own</option>
|
||||||
{(servers ?? [])
|
{(servers ?? [])
|
||||||
.filter((s) => s.id !== serverId)
|
.filter((s) => s.id !== serverId)
|
||||||
.map((s) => (
|
.map((s) => (
|
||||||
@@ -49,7 +53,7 @@ export default function RunsOn({ serverId, parent, canEdit, onChanged }: { serve
|
|||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
<div className="form-hint text-secondary small mt-1">Automatic means worked out from its Proxmox node. If it stops reporting, this server's offline alert is folded under its host's.</div>
|
<div className="form-hint text-secondary small mt-1">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.</div>
|
||||||
</div>
|
</div>
|
||||||
);
|
);
|
||||||
}
|
}
|
||||||
@@ -19,6 +19,7 @@ import { toast } from "../utils/toast";
|
|||||||
import { confirmDialog } from "../utils/dialogs";
|
import { confirmDialog } from "../utils/dialogs";
|
||||||
import MaintenanceTimeline from "../components/MaintenanceTimeline";
|
import MaintenanceTimeline from "../components/MaintenanceTimeline";
|
||||||
import RecurringMaintenance from "../components/RecurringMaintenance";
|
import RecurringMaintenance from "../components/RecurringMaintenance";
|
||||||
|
import ExportTableButton from "../components/ExportTableButton";
|
||||||
|
|
||||||
const DURATIONS: { minutes: number; label: string }[] = [
|
const DURATIONS: { minutes: number; label: string }[] = [
|
||||||
{ minutes: 30, label: "30 minutes" },
|
{ minutes: 30, label: "30 minutes" },
|
||||||
@@ -479,6 +480,9 @@ export default function Maintenance({ user }: { user: CurrentUser }) {
|
|||||||
<div className="card mb-3">
|
<div className="card mb-3">
|
||||||
<div className="card-header">
|
<div className="card-header">
|
||||||
<h3 className="card-title">Address aliases</h3>
|
<h3 className="card-title">Address aliases</h3>
|
||||||
|
<div className="card-actions">
|
||||||
|
<ExportTableButton filename="maintenance-aliases" />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<form onSubmit={addAlias}>
|
<form onSubmit={addAlias}>
|
||||||
<div className="card-body row g-3">
|
<div className="card-body row g-3">
|
||||||
@@ -579,6 +583,9 @@ export default function Maintenance({ user }: { user: CurrentUser }) {
|
|||||||
<div className="card mb-3">
|
<div className="card mb-3">
|
||||||
<div className="card-header">
|
<div className="card-header">
|
||||||
<h3 className="card-title">Scheduled</h3>
|
<h3 className="card-title">Scheduled</h3>
|
||||||
|
<div className="card-actions">
|
||||||
|
<ExportTableButton filename="maintenance-scheduled" />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="table-responsive">
|
<div className="table-responsive">
|
||||||
<table className="table table-vcenter card-table">
|
<table className="table table-vcenter card-table">
|
||||||
@@ -598,11 +605,11 @@ export default function Maintenance({ user }: { user: CurrentUser }) {
|
|||||||
{w.targetName} <span className="text-secondary">· {w.targetKind}</span>
|
{w.targetName} <span className="text-secondary">· {w.targetKind}</span>
|
||||||
</td>
|
</td>
|
||||||
<td className="text-secondary">{w.reason ?? "—"}</td>
|
<td className="text-secondary">{w.reason ?? "—"}</td>
|
||||||
<td>
|
<td data-csv={w.startedAt}>
|
||||||
<span className="badge bg-blue-lt text-blue me-2">in {formatRemaining(w.startedAt, now)}</span>
|
<span className="badge bg-blue-lt text-blue me-2">in {formatRemaining(w.startedAt, now)}</span>
|
||||||
<span className="text-secondary small">{formatDateTime(new Date(w.startedAt))}</span>
|
<span className="text-secondary small">{formatDateTime(new Date(w.startedAt))}</span>
|
||||||
</td>
|
</td>
|
||||||
<td className="text-secondary small">{formatDateTime(new Date(w.endsAt))}</td>
|
<td className="text-secondary small" data-csv={w.endsAt}>{formatDateTime(new Date(w.endsAt))}</td>
|
||||||
{canEdit && (
|
{canEdit && (
|
||||||
<td>
|
<td>
|
||||||
<button className="btn btn-sm btn-outline-secondary" onClick={() => end(w)}>
|
<button className="btn btn-sm btn-outline-secondary" onClick={() => end(w)}>
|
||||||
@@ -625,13 +632,14 @@ export default function Maintenance({ user }: { user: CurrentUser }) {
|
|||||||
<div className="card mb-3">
|
<div className="card mb-3">
|
||||||
<div className="card-header">
|
<div className="card-header">
|
||||||
<h3 className="card-title">Active</h3>
|
<h3 className="card-title">Active</h3>
|
||||||
{canEdit && (windows?.length ?? 0) > 1 && (
|
<div className="card-actions">
|
||||||
<div className="card-actions">
|
<ExportTableButton filename="maintenance-active" />
|
||||||
|
{canEdit && (windows?.length ?? 0) > 1 && (
|
||||||
<button className="btn btn-sm btn-outline-secondary" onClick={() => void endAll()}>
|
<button className="btn btn-sm btn-outline-secondary" onClick={() => void endAll()}>
|
||||||
End all ({windows?.length})
|
End all ({windows?.length})
|
||||||
</button>
|
</button>
|
||||||
</div>
|
)}
|
||||||
)}
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="table-responsive">
|
<div className="table-responsive">
|
||||||
<table className="table table-vcenter card-table">
|
<table className="table table-vcenter card-table">
|
||||||
@@ -652,7 +660,7 @@ export default function Maintenance({ user }: { user: CurrentUser }) {
|
|||||||
{w.source?.startsWith("kuma:") && <span className="badge bg-cyan-lt ms-2">Uptime Kuma</span>}
|
{w.source?.startsWith("kuma:") && <span className="badge bg-cyan-lt ms-2">Uptime Kuma</span>}
|
||||||
</td>
|
</td>
|
||||||
<td className="text-secondary">{w.reason ?? "—"}</td>
|
<td className="text-secondary">{w.reason ?? "—"}</td>
|
||||||
<td>
|
<td data-csv={w.endsAt}>
|
||||||
<span className="badge bg-yellow-lt text-yellow me-2">{formatRemaining(w.endsAt, now)} left</span>
|
<span className="badge bg-yellow-lt text-yellow me-2">{formatRemaining(w.endsAt, now)} left</span>
|
||||||
<span className="text-secondary small">{formatDateTime(new Date(w.endsAt))}</span>
|
<span className="text-secondary small">{formatDateTime(new Date(w.endsAt))}</span>
|
||||||
</td>
|
</td>
|
||||||
|
|||||||
@@ -14,6 +14,7 @@ import { formatDateTime } from "../utils/date";
|
|||||||
import { downloadCsv } from "../utils/csv";
|
import { downloadCsv } from "../utils/csv";
|
||||||
import IntegrationPageTitle from "../components/IntegrationPageTitle";
|
import IntegrationPageTitle from "../components/IntegrationPageTitle";
|
||||||
import { ErrorNotice } from "../components/Notice";
|
import { ErrorNotice } from "../components/Notice";
|
||||||
|
import ExportTableButton from "../components/ExportTableButton";
|
||||||
|
|
||||||
function formatBytes(bytes: number | null): string {
|
function formatBytes(bytes: number | null): string {
|
||||||
if (bytes === null) return "—";
|
if (bytes === null) return "—";
|
||||||
@@ -297,6 +298,9 @@ export default function PbsBackup({ user: _user }: { user: CurrentUser }) {
|
|||||||
<div className="card">
|
<div className="card">
|
||||||
<div className="card-header">
|
<div className="card-header">
|
||||||
<h3 className="card-title">Recent verification failures</h3>
|
<h3 className="card-title">Recent verification failures</h3>
|
||||||
|
<div className="card-actions">
|
||||||
|
<ExportTableButton filename="pbs-verification-failures" />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="table-responsive">
|
<div className="table-responsive">
|
||||||
<table className="table table-vcenter card-table">
|
<table className="table table-vcenter card-table">
|
||||||
|
|||||||
@@ -25,6 +25,7 @@ import { useTableSearch } from "../hooks/useTableSearch";
|
|||||||
import DetailDrawer, { ObjectDetails } from "../components/DetailDrawer";
|
import DetailDrawer, { ObjectDetails } from "../components/DetailDrawer";
|
||||||
import { useRowDetail } from "../hooks/useRowDetail";
|
import { useRowDetail } from "../hooks/useRowDetail";
|
||||||
import { formatDateTime } from "../utils/date";
|
import { formatDateTime } from "../utils/date";
|
||||||
|
import ExportTableButton from "../components/ExportTableButton";
|
||||||
|
|
||||||
function proxmoxStatusBadge(status: string) {
|
function proxmoxStatusBadge(status: string) {
|
||||||
return status === "running" ? (
|
return status === "running" ? (
|
||||||
@@ -381,7 +382,10 @@ export default function Proxmox({ user }: { user: CurrentUser }) {
|
|||||||
</div>
|
</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="text-secondary small mb-1">Scheduled jobs</div>
|
<div className="text-secondary small mb-1 d-flex align-items-center justify-content-between">
|
||||||
|
Scheduled jobs
|
||||||
|
<ExportTableButton of="next" filename="proxmox-backup-jobs" className="btn btn-sm btn-ghost-secondary" />
|
||||||
|
</div>
|
||||||
{backupJobs && backupJobs.length > 0 ? (
|
{backupJobs && backupJobs.length > 0 ? (
|
||||||
<table className="table table-sm table-vcenter mb-4">
|
<table className="table table-sm table-vcenter mb-4">
|
||||||
<thead>
|
<thead>
|
||||||
@@ -413,7 +417,10 @@ export default function Proxmox({ user }: { user: CurrentUser }) {
|
|||||||
!backupsError && <div className="text-secondary small mb-4">No backup jobs configured in Proxmox.</div>
|
!backupsError && <div className="text-secondary small mb-4">No backup jobs configured in Proxmox.</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="text-secondary small mb-1">Guests without backup coverage</div>
|
<div className="text-secondary small mb-1 d-flex align-items-center justify-content-between">
|
||||||
|
Guests without backup coverage
|
||||||
|
<ExportTableButton of="next" filename="proxmox-uncovered-guests" className="btn btn-sm btn-ghost-secondary" />
|
||||||
|
</div>
|
||||||
{uncoveredGuests && uncoveredGuests.length > 0 ? (
|
{uncoveredGuests && uncoveredGuests.length > 0 ? (
|
||||||
<table className="table table-sm table-vcenter mb-4">
|
<table className="table table-sm table-vcenter mb-4">
|
||||||
<thead>
|
<thead>
|
||||||
@@ -444,7 +451,10 @@ export default function Proxmox({ user }: { user: CurrentUser }) {
|
|||||||
uncoveredGuests && <div className="text-secondary small mb-4">Every VM/LXC is covered by at least one enabled backup job.</div>
|
uncoveredGuests && <div className="text-secondary small mb-4">Every VM/LXC is covered by at least one enabled backup job.</div>
|
||||||
)}
|
)}
|
||||||
|
|
||||||
<div className="text-secondary small mb-1">Recent runs</div>
|
<div className="text-secondary small mb-1 d-flex align-items-center justify-content-between">
|
||||||
|
Recent runs
|
||||||
|
<ExportTableButton of="next" filename="proxmox-backup-runs" className="btn btn-sm btn-ghost-secondary" />
|
||||||
|
</div>
|
||||||
{backupTasks && backupTasks.length > 0 ? (
|
{backupTasks && backupTasks.length > 0 ? (
|
||||||
<table className="table table-sm table-vcenter mb-0">
|
<table className="table table-sm table-vcenter mb-0">
|
||||||
<thead>
|
<thead>
|
||||||
|
|||||||
@@ -3,6 +3,7 @@ import { Link, useSearchParams } from "react-router-dom";
|
|||||||
import { api, type ServerMetricSeries, type ServerRecord } from "../api/client";
|
import { api, type ServerMetricSeries, type ServerRecord } from "../api/client";
|
||||||
import MultiLineChart, { type ChartSeries } from "../components/MultiLineChart";
|
import MultiLineChart, { type ChartSeries } from "../components/MultiLineChart";
|
||||||
import { BlockSkeleton } from "../components/Skeleton";
|
import { BlockSkeleton } from "../components/Skeleton";
|
||||||
|
import ExportTableButton from "../components/ExportTableButton";
|
||||||
|
|
||||||
const MAX_SERVERS = 4;
|
const MAX_SERVERS = 4;
|
||||||
const RANGES = [
|
const RANGES = [
|
||||||
@@ -132,6 +133,7 @@ export default function ServerCompare() {
|
|||||||
</option>
|
</option>
|
||||||
))}
|
))}
|
||||||
</select>
|
</select>
|
||||||
|
<ExportTableButton filename={`compare-${metric}`} />
|
||||||
</div>
|
</div>
|
||||||
<div className="card-body">
|
<div className="card-body">
|
||||||
{failed ? (
|
{failed ? (
|
||||||
|
|||||||
@@ -762,7 +762,7 @@ export default function ServerDetail({ user }: { user: CurrentUser }) {
|
|||||||
</dd>
|
</dd>
|
||||||
<dt className="col-5">Runs on</dt>
|
<dt className="col-5">Runs on</dt>
|
||||||
<dd className="col-7">
|
<dd className="col-7">
|
||||||
<RunsOn serverId={server.id} parent={detail.relations.parent} canEdit={isAdmin} onChanged={() => void loadDetail()} />
|
<RunsOn serverId={server.id} parent={detail.relations.parent} noParent={server.noParent} canEdit={isAdmin} onChanged={() => void loadDetail()} />
|
||||||
</dd>
|
</dd>
|
||||||
{detail.relations.children.length > 0 && (
|
{detail.relations.children.length > 0 && (
|
||||||
<>
|
<>
|
||||||
|
|||||||
@@ -20,6 +20,7 @@ import { SearchBox } from "../components/TableToolbar";
|
|||||||
import { useTableSearch } from "../hooks/useTableSearch";
|
import { useTableSearch } from "../hooks/useTableSearch";
|
||||||
import SaveViewButton from "../components/SaveViewButton";
|
import SaveViewButton from "../components/SaveViewButton";
|
||||||
import { agentState } from "../utils/agent";
|
import { agentState } from "../utils/agent";
|
||||||
|
import { BlockSkeleton } from "../components/Skeleton";
|
||||||
|
|
||||||
function typeBadgeStyle(colors: Record<string, string>, type: string): CSSProperties {
|
function typeBadgeStyle(colors: Record<string, string>, type: string): CSSProperties {
|
||||||
const color = colors[type];
|
const color = colors[type];
|
||||||
@@ -32,6 +33,8 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
|||||||
const isAdmin = user.role === "admin";
|
const isAdmin = user.role === "admin";
|
||||||
|
|
||||||
const [servers, setServers] = useState<ServerRecord[]>([]);
|
const [servers, setServers] = useState<ServerRecord[]>([]);
|
||||||
|
// 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<AgentLatest | null>(null);
|
const [agentLatest, setAgentLatest] = useState<AgentLatest | null>(null);
|
||||||
const [error, setError] = useState<string | null>(null);
|
const [error, setError] = useState<string | null>(null);
|
||||||
const [managingServers, setManagingServers] = useState(false);
|
const [managingServers, setManagingServers] = useState(false);
|
||||||
@@ -74,7 +77,8 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
|||||||
setServers(res.servers);
|
setServers(res.servers);
|
||||||
setAgentLatest(res.agentLatest);
|
setAgentLatest(res.agentLatest);
|
||||||
})
|
})
|
||||||
.catch((err) => setError(String(err)));
|
.catch((err) => setError(String(err)))
|
||||||
|
.finally(() => setLoaded(true));
|
||||||
}, []);
|
}, []);
|
||||||
|
|
||||||
useEffect(() => {
|
useEffect(() => {
|
||||||
@@ -428,7 +432,7 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
|||||||
</td>
|
</td>
|
||||||
</tr>
|
</tr>
|
||||||
))}
|
))}
|
||||||
{sortedServers?.length === 0 && (
|
{loaded && sortedServers?.length === 0 && (
|
||||||
<tr>
|
<tr>
|
||||||
<td colSpan={7} className="text-secondary text-center">
|
<td colSpan={7} className="text-secondary text-center">
|
||||||
No servers registered yet.
|
No servers registered yet.
|
||||||
@@ -441,6 +445,12 @@ export default function Servers({ user }: { user: CurrentUser }) {
|
|||||||
<Pagination page={serverPage} pageCount={serverPageCount} totalCount={serverTotalCount} onPageChange={setServerPage} />
|
<Pagination page={serverPage} pageCount={serverPageCount} totalCount={serverTotalCount} onPageChange={setServerPage} />
|
||||||
</div>
|
</div>
|
||||||
</>
|
</>
|
||||||
|
) : !loaded ? (
|
||||||
|
<div className="card">
|
||||||
|
<div className="card-body">
|
||||||
|
<BlockSkeleton lines={4} />
|
||||||
|
</div>
|
||||||
|
</div>
|
||||||
) : servers.length === 0 ? (
|
) : servers.length === 0 ? (
|
||||||
<div className="card">
|
<div className="card">
|
||||||
<div className="card-body text-secondary">
|
<div className="card-body text-secondary">
|
||||||
|
|||||||
@@ -12,6 +12,7 @@ import { useSortable } from "../hooks/useSortable";
|
|||||||
import { useTableSearch } from "../hooks/useTableSearch";
|
import { useTableSearch } from "../hooks/useTableSearch";
|
||||||
import { downloadCsv } from "../utils/csv";
|
import { downloadCsv } from "../utils/csv";
|
||||||
import { readableError } from "../utils/errors";
|
import { readableError } from "../utils/errors";
|
||||||
|
import ExportTableButton from "../components/ExportTableButton";
|
||||||
|
|
||||||
interface Row {
|
interface Row {
|
||||||
id: number;
|
id: number;
|
||||||
@@ -220,6 +221,9 @@ export default function Updates() {
|
|||||||
<div className="card">
|
<div className="card">
|
||||||
<div className="card-header">
|
<div className="card-header">
|
||||||
<h3 className="card-title">Docker containers with a newer image</h3>
|
<h3 className="card-title">Docker containers with a newer image</h3>
|
||||||
|
<div className="card-actions">
|
||||||
|
<ExportTableButton filename="docker-newer-images" />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="table-responsive">
|
<div className="table-responsive">
|
||||||
<table className="table table-vcenter card-table">
|
<table className="table table-vcenter card-table">
|
||||||
|
|||||||
@@ -6,6 +6,7 @@ import { ErrorNotice } from "../../components/Notice";
|
|||||||
import { confirmDialog } from "../../utils/dialogs";
|
import { confirmDialog } from "../../utils/dialogs";
|
||||||
import { readableError } from "../../utils/errors";
|
import { readableError } from "../../utils/errors";
|
||||||
import { toast } from "../../utils/toast";
|
import { toast } from "../../utils/toast";
|
||||||
|
import ExportTableButton from "../../components/ExportTableButton";
|
||||||
|
|
||||||
const EVENT_WORDS: Record<WebhookEventName, string> = {
|
const EVENT_WORDS: Record<WebhookEventName, string> = {
|
||||||
"alert.opened": "A problem begins",
|
"alert.opened": "A problem begins",
|
||||||
@@ -139,6 +140,9 @@ export default function ApiSettings() {
|
|||||||
<div className="card mb-3">
|
<div className="card mb-3">
|
||||||
<div className="card-header">
|
<div className="card-header">
|
||||||
<h3 className="card-title">Metrics for Prometheus</h3>
|
<h3 className="card-title">Metrics for Prometheus</h3>
|
||||||
|
<div className="card-actions">
|
||||||
|
<ExportTableButton filename="metrics-tokens" />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="card-body">
|
<div className="card-body">
|
||||||
<p className="text-secondary">
|
<p className="text-secondary">
|
||||||
@@ -218,13 +222,14 @@ export default function ApiSettings() {
|
|||||||
<div className="card">
|
<div className="card">
|
||||||
<div className="card-header">
|
<div className="card-header">
|
||||||
<h3 className="card-title">Event webhooks</h3>
|
<h3 className="card-title">Event webhooks</h3>
|
||||||
{!adding && (
|
<div className="card-actions">
|
||||||
<div className="card-actions">
|
<ExportTableButton filename="event-webhooks" />
|
||||||
|
{!adding && (
|
||||||
<button className="btn btn-sm btn-primary" onClick={() => setAdding(true)}>
|
<button className="btn btn-sm btn-primary" onClick={() => setAdding(true)}>
|
||||||
Add a webhook
|
Add a webhook
|
||||||
</button>
|
</button>
|
||||||
</div>
|
)}
|
||||||
)}
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="card-body">
|
<div className="card-body">
|
||||||
<p className="text-secondary">
|
<p className="text-secondary">
|
||||||
|
|||||||
@@ -7,6 +7,7 @@ import { confirmDialog } from "../../utils/dialogs";
|
|||||||
import { formatDateTime } from "../../utils/date";
|
import { formatDateTime } from "../../utils/date";
|
||||||
import { readableError } from "../../utils/errors";
|
import { readableError } from "../../utils/errors";
|
||||||
import { toast } from "../../utils/toast";
|
import { toast } from "../../utils/toast";
|
||||||
|
import ExportTableButton from "../../components/ExportTableButton";
|
||||||
|
|
||||||
const LASTS: { days: number | null; label: string }[] = [
|
const LASTS: { days: number | null; label: string }[] = [
|
||||||
{ days: null, label: "Until I remove it" },
|
{ days: null, label: "Until I remove it" },
|
||||||
@@ -144,6 +145,9 @@ export default function ShareSettings() {
|
|||||||
<div className="card">
|
<div className="card">
|
||||||
<div className="card-header">
|
<div className="card-header">
|
||||||
<h3 className="card-title">Links</h3>
|
<h3 className="card-title">Links</h3>
|
||||||
|
<div className="card-actions">
|
||||||
|
<ExportTableButton filename="share-links" />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="table-responsive">
|
<div className="table-responsive">
|
||||||
<table className="table table-vcenter card-table">
|
<table className="table table-vcenter card-table">
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { ErrorNotice } from "../../components/Notice";
|
|||||||
import { PageSkeleton } from "../../components/Skeleton";
|
import { PageSkeleton } from "../../components/Skeleton";
|
||||||
import { readableError } from "../../utils/errors";
|
import { readableError } from "../../utils/errors";
|
||||||
import { toast } from "../../utils/toast";
|
import { toast } from "../../utils/toast";
|
||||||
|
import ExportTableButton from "../../components/ExportTableButton";
|
||||||
|
|
||||||
const DEFAULTS: SignInSettingsData = { roleFromGroups: false, groupsClaim: "groups", adminGroups: [], operatorGroups: [], otherwise: "viewer" };
|
const DEFAULTS: SignInSettingsData = { roleFromGroups: false, groupsClaim: "groups", adminGroups: [], operatorGroups: [], otherwise: "viewer" };
|
||||||
|
|
||||||
@@ -147,6 +148,9 @@ export default function SignInSettings() {
|
|||||||
<div className="card">
|
<div className="card">
|
||||||
<div className="card-header">
|
<div className="card-header">
|
||||||
<h3 className="card-title">What these rules would do</h3>
|
<h3 className="card-title">What these rules would do</h3>
|
||||||
|
<div className="card-actions">
|
||||||
|
<ExportTableButton filename="role-preview" />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
{preview.adminsAfter === 0 && (
|
{preview.adminsAfter === 0 && (
|
||||||
<div className="alert alert-danger m-3 mb-0" role="alert">
|
<div className="alert alert-danger m-3 mb-0" role="alert">
|
||||||
|
|||||||
@@ -4,6 +4,7 @@ import { readableError } from "../../utils/errors";
|
|||||||
import { normalizeTagInput, refreshTagColors, tagBadge } from "../../utils/tags";
|
import { normalizeTagInput, refreshTagColors, tagBadge } from "../../utils/tags";
|
||||||
import { confirmDialog, promptDialog } from "../../utils/dialogs";
|
import { confirmDialog, promptDialog } from "../../utils/dialogs";
|
||||||
import { ErrorNotice, SuccessNotice } from "../../components/Notice";
|
import { ErrorNotice, SuccessNotice } from "../../components/Notice";
|
||||||
|
import ExportTableButton from "../../components/ExportTableButton";
|
||||||
|
|
||||||
const DEFAULT_PICK = "#3b82f6";
|
const DEFAULT_PICK = "#3b82f6";
|
||||||
|
|
||||||
@@ -145,6 +146,9 @@ export default function TagSettings() {
|
|||||||
<div className="card">
|
<div className="card">
|
||||||
<div className="card-header">
|
<div className="card-header">
|
||||||
<h3 className="card-title">All tags</h3>
|
<h3 className="card-title">All tags</h3>
|
||||||
|
<div className="card-actions">
|
||||||
|
<ExportTableButton filename="tags" />
|
||||||
|
</div>
|
||||||
</div>
|
</div>
|
||||||
<div className="table-responsive">
|
<div className="table-responsive">
|
||||||
<table className="table table-vcenter card-table">
|
<table className="table table-vcenter card-table">
|
||||||
|
|||||||
@@ -13,3 +13,39 @@ export function downloadCsv(filename: string, headers: string[], rows: unknown[]
|
|||||||
a.click();
|
a.click();
|
||||||
URL.revokeObjectURL(url);
|
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 };
|
||||||
|
}
|
||||||
Reference in new issue
Block a user