Compare commits
111
Commits
5c7a4cf9a0
...
dev
@@ -228,18 +228,31 @@ jobs:
|
||||
fi
|
||||
|
||||
# A backup made by the image restores into an empty database, and
|
||||
# Steward starts on it (milestone 507). It carries configuration
|
||||
# (the marker setting) and leaves metrics' rows out.
|
||||
# Steward starts on it (milestone 507). It carries settings (the
|
||||
# marker setting) and leaves metrics and the audit log out.
|
||||
sql() { docker exec "$SMOKE-pg" psql -U steward -v ON_ERROR_STOP=1 -tA "$@"; }
|
||||
sql -d steward -c "INSERT INTO app_settings (key, value_json, updated_at) VALUES ('smoke.backup', '\"kept\"', now())"
|
||||
sql -d steward -c "INSERT INTO plugin_metrics (id, source_module, resource_name, metric_name, value, recorded_at) VALUES ('smoke-metric', 'smoke', 'smoke', 'smoke', 1, now())"
|
||||
sql -d steward -c "INSERT INTO audit_events (id, timestamp, username, action) VALUES ('smoke-audit', now(), 'smoke', 'smoke.backup')"
|
||||
docker exec -u app "$SMOKE-app" steward backup --to /tmp/backups
|
||||
# Checked against the database it was made from, it matches (#5823):
|
||||
# a real pg_restore read, and what a running Steward writes by itself
|
||||
# (last-seen times, backup history) left out of the comparison.
|
||||
docker exec -u app "$SMOKE-app" sh -c 'steward check-backup /tmp/backups/steward-*.tar' | tee /tmp/smoke-check.txt
|
||||
grep -q "Matches what is in place" /tmp/smoke-check.txt
|
||||
# Put back in place over a changed setting (#5815): the setting comes
|
||||
# back, and history the backup leaves out (the audit log) stays.
|
||||
sql -d steward -c "UPDATE app_settings SET value_json = '\"changed\"' WHERE key = 'smoke.backup'"
|
||||
docker exec -u app "$SMOKE-app" sh -c 'steward restore --in-place /tmp/backups/steward-*.tar'
|
||||
test "$(sql -d steward -c "SELECT value_json FROM app_settings WHERE key = 'smoke.backup'")" = '"kept"'
|
||||
test "$(sql -d steward -c "SELECT count(*) FROM audit_events WHERE id = 'smoke-audit'")" = "1"
|
||||
sql -d steward -c "CREATE DATABASE restored"
|
||||
docker exec -u app \
|
||||
-e "STEWARD_DATABASE_URL=postgresql+asyncpg://steward:steward@$SMOKE-pg:5432/restored" \
|
||||
"$SMOKE-app" sh -c 'steward restore /tmp/backups/steward-*.tar'
|
||||
test "$(sql -d restored -c "SELECT value_json FROM app_settings WHERE key = 'smoke.backup'")" = '"kept"'
|
||||
test "$(sql -d restored -c "SELECT count(*) FROM plugin_metrics")" = "0"
|
||||
test "$(sql -d restored -c "SELECT count(*) FROM audit_events")" = "0"
|
||||
test "$(sql -d restored -c "SELECT count(*) FROM alembic_version")" -ge 1
|
||||
docker run -d --name "$SMOKE-restored" --network "$SMOKE-net" \
|
||||
-e "STEWARD_DATABASE_URL=postgresql+asyncpg://steward:steward@$SMOKE-pg:5432/restored" \
|
||||
|
||||
+1
-1
@@ -52,7 +52,7 @@ RUN useradd -m -u 1000 app \
|
||||
&& mkdir -p /data/ansible/sources /data/ansible/runs /data/ansible/playbooks /data/plugins \
|
||||
&& chown -R app:app /data /app
|
||||
|
||||
EXPOSE 5000
|
||||
EXPOSE 5000 5514/udp 5514/tcp
|
||||
|
||||
ENTRYPOINT ["/usr/bin/tini", "--", "/entrypoint.sh"]
|
||||
CMD ["steward", "--host", "0.0.0.0", "--port", "5000"]
|
||||
|
||||
@@ -53,7 +53,7 @@ cp .env.example .env
|
||||
docker compose -f compose.deploy.yml up -d
|
||||
```
|
||||
|
||||
Open `http://<server>:5000` and create the admin account on first run.
|
||||
Open `http://<server>:5000` and create the admin account on first run. Devices send syslog to `<server>:5514` (UDP or TCP); see `docs/plugins/syslog.md`.
|
||||
|
||||
**Update to the latest dev build:**
|
||||
|
||||
@@ -120,9 +120,13 @@ See `docs/plugins/` for a full plugin development guide.
|
||||
| `docs/core/alerting.md` | Alert rules, state machine, notification channels, template variables |
|
||||
| `docs/core/ansible.md` | Playbook sources, run lifecycle, SSE streaming |
|
||||
| `docs/core/backups.md` | Steward's daily backup to an S3 bucket (Fabled Archives), what it holds, and `steward restore` |
|
||||
| `docs/core/timeline.md` | The timeline: what it records from each source, areas and kinds, Settings → Timeline |
|
||||
| `docs/core/tickets.md` | Tickets: known problems, linked to alerts and anomalies, shown as known issues, resolved onto the timeline |
|
||||
| `docs/plugins/overview.md` | Plugin system: how loading works, plugin.yaml schema, required exports |
|
||||
| `docs/plugins/writing-a-plugin.md` | Step-by-step plugin development guide |
|
||||
| `docs/plugins/traefik.md` | Traefik plugin: config, metrics, alert rule examples |
|
||||
| `docs/plugins/prometheus.md` | Prometheus plugin: scraping any /metrics endpoint, how series are stored, the Fabled Archives recipe |
|
||||
| `docs/plugins/homeassistant.md` | Home Assistant plugin: waiting updates, backup age, and installing updates after a confirmed backup |
|
||||
| `docs/plugins/syslog.md` | Syslog plugin: sources, patterns and alerts, publishing port 5514 (ingress or host mode under Swarm) |
|
||||
| `docs/plugins/prometheus-widgets.md` | Prometheus widget templates: writing, sharing and copying one in, every block, the format reference |
|
||||
| `docs/reference/code-map.md` | Where every key function, model, and route lives in the codebase |
|
||||
|
||||
@@ -16,6 +16,14 @@ services:
|
||||
pull_policy: always
|
||||
ports:
|
||||
- "5000:5000"
|
||||
# Syslog (plugins/syslog): devices send here. Steward runs unprivileged,
|
||||
# so it listens above 1024; publish 514 to it instead ("514:5514/udp")
|
||||
# if a device can't choose its port. Under Docker Swarm's ingress every
|
||||
# device arrives from one internal address and is told apart by the name
|
||||
# its lines carry; the long form with `mode: host` keeps each device's
|
||||
# own address but ties Steward to that node.
|
||||
- "5514:5514/udp"
|
||||
- "5514:5514/tcp"
|
||||
networks:
|
||||
- backend
|
||||
volumes:
|
||||
|
||||
@@ -8,6 +8,8 @@ services:
|
||||
command: ["steward", "--host", "0.0.0.0", "--port", "5000", "--debug"]
|
||||
ports:
|
||||
- "5000:5000"
|
||||
- "5514:5514/udp" # syslog (plugins/syslog)
|
||||
- "5514:5514/tcp"
|
||||
volumes:
|
||||
- app_data:/data
|
||||
# Live-edit core + first-party plugins without rebuilding. PYTHONPATH=/app
|
||||
|
||||
@@ -105,7 +105,7 @@ A two-minute spike raises the peak and leaves the p95 low; an hour spent at that
|
||||
|
||||
A metric a plugin registers with `learn_normal()` gets a normal per hour of the day, then per hour of the week once three weeks of history exist (`metric_norms`, relearned hourly by `metric_norms`; `steward/core/norms.py`).
|
||||
|
||||
Every minute, `metric_anomalies` averages each learned key's last 15 minutes and compares it with the normal for that hour. A level above the usual hold ×1.25, and above the metric's floor, opens an anomaly (`steward/core/anomalies.py`):
|
||||
Every minute, `metric_anomalies` averages each learned key's last 15 minutes and compares it with the normal for that hour. A level above the usual hold ×1.25, and above the metric's floor, has departed. It opens an anomaly once it is also higher than the metric usually goes, or held: the median of the last hour is over the same line. How high it usually goes is the greater of the usual peak for that hour and how high it has gone in most hours of the day, so bursts that land at any hour are told from a job with a time of its own. A burst of a few minutes within that lifts the 15-minute average and opens nothing. Height is judged with the window's highest reading left out, so one slow request can't carry a window past it, and a held level needs at least three readings behind its median, so a lone reading never opens an anomaly (`steward/core/anomalies.py`):
|
||||
- `metric_anomalies` holds one row per item to review. A repeat while the row still waits joins it as another occurrence (`metric_anomaly_spans`).
|
||||
- A row is `to_review` until someone marks it `normal` or `real` (Alerts → Anomalies, or MCP `review_anomaly`). An ended row nobody reviews within `anomalies.review_days` (14) becomes `lapsed`.
|
||||
- Learning skips every hour an occurrence covers unless its anomaly was marked `normal`, so a new level is never learned without review.
|
||||
@@ -118,14 +118,14 @@ What learns a normal, and the floor each departure must clear (Settings → Thre
|
||||
| Host CPU | `host_agent` / `cpu_pct` | 10 points |
|
||||
| Host memory | `host_agent` / `mem_used_pct` | 5 points |
|
||||
| Host load per core | `host_agent` / `load_pct` (load_1m ÷ cores × 100, recorded at ingest) | 10 points |
|
||||
| Container CPU | `docker` / `cpu_pct` (100% is one core) | 10 points of one core |
|
||||
| Container memory | `docker` / `mem_pct` (of its limit, or of host RAM when it has none) | 5 points |
|
||||
| Container CPU | `docker` / `cpu_pct` (100% is one core; a swarm service's under `swarm/<service>`, shared by its tasks) | 10 points of one core |
|
||||
| Container memory | `docker` / `mem_used_pct` (its processes' own memory, file cache left out, of its limit or of host RAM when it has none) | 5 points |
|
||||
| Monitor response time | `<type>` / `response_ms` | 100 ms |
|
||||
| Router 4xx share, p95 | `traefik` / `error_rate_4xx_pct`, `latency_p95_ms` | 2 points, 50 ms |
|
||||
|
||||
Host metrics learn with `parts=False`: the host learns, its cores (`<host>:core<N>`) don't. Disk space, a monitor that is down, an agent gone quiet and a router's 5xx share are failures and keep their fixed cutoffs.
|
||||
Host metrics learn with `parts=False`: the host learns, its cores (`<host>:core<N>`) don't. Disk space, a monitor that is down, an agent gone quiet and a router's 5xx share are failures and keep their fixed cutoffs (a router's shares are judged only over enough requests).
|
||||
|
||||
Pages grade by the normal through `anomalies.graded()` (hosts' `host_grades` and `worst_reading(normals=)`, `docker.service.usage(thresholds=, norms=)`, `monitors.service.latency_grade`): a reading past its cutoff but within its normal reads healthy and says what is usual at this hour. The host, monitor, container and Traefik pages list their anomalies with `_anomaly_card.html`.
|
||||
Pages grade by the normal through `anomalies.graded()` (hosts' `host_grades` and `worst_reading(normals=)`, `docker.service.usage(thresholds=, norms=)`, `monitors.service.latency_grade`): a reading past its cutoff but within its normal reads healthy and says what is usual at this hour. The host, monitor, container and Traefik pages each carry a one-line `_anomaly_card.html`. It says how many anomalies wait for review and names any that are out of their normal now. Its Review button opens Alerts → Anomalies narrowed to that resource (`?source=&resource=`), where they are reviewed.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -73,6 +73,7 @@ Alert rules are created in the UI at `/alerts/`. Each rule requires:
|
||||
- **Metric name** — the metric key (e.g. `response_time_ms`, `up`, `error_rate_5xx_pct`)
|
||||
- **Operator** — `>`, `<`, `>=`, `<=`, `==`, `!=`
|
||||
- **Threshold** — numeric value
|
||||
- **rose by** — instead of a line to cross, fires when a reading is at least the threshold above the one before it, for a count that only grows (a disk's bad sectors). A fall doesn't fire. A reading that hasn't risen counts as OK, so the checks to clear set how long the alert stays up, and rises inside that are one alert
|
||||
- **Consecutive failures required** — how many consecutive breaches before FIRING (default 1)
|
||||
|
||||
The form offers only what has reported, read from `plugin_metric_latest`.
|
||||
@@ -138,6 +139,7 @@ failed agent posts, a gap in watching, or open files near the limit.
|
||||
| `ingest_slowest_ms` | The slowest post in the last minute; agents give up at 10 s |
|
||||
| `db_roundtrip_ms` | A `SELECT 1`, connection checkout included |
|
||||
| `unwatched_secs` | The gap before this tick when it exceeds `watch.GAP_S` (a deploy or an outage); 0 when unbroken |
|
||||
| `restart_gap_secs` | Recorded once, on a new process's first tick: the time since the last process's last sample, however short |
|
||||
| `cleanup_secs` | How long the last hourly retention and rollup run took |
|
||||
| `open_fds` / `open_fds_pct` | Steward's open files, and as a share of its limit (absent without `/proc`) |
|
||||
|
||||
@@ -212,6 +214,7 @@ Configured at `/settings/` under Webhook. The body is a Jinja2 template rendered
|
||||
| `alert.threshold` | float | Configured threshold |
|
||||
| `alert.resource` | str | Resource name |
|
||||
| `alert.source_module` | str | `ping`, `dns`, `traefik`, etc. |
|
||||
| `alert.which` | str | For a figure that counts things, what it counts when it fires, joined by ", " (`web_app (0 of 2 running), …`); `raw.which` is the list. Empty for other figures. |
|
||||
| `alert.timestamp` | str | ISO 8601 UTC |
|
||||
|
||||
Default template (Discord-compatible):
|
||||
|
||||
+116
-13
@@ -1,8 +1,9 @@
|
||||
# Backups: Steward backing itself up, and coming back
|
||||
|
||||
Steward sends a backup of itself to an S3 bucket once a day. Fabled Archives
|
||||
is the intended target. A backup is one file, and `steward restore` brings
|
||||
Steward back from it into an empty database.
|
||||
is the intended target. A backup is one file. Settings → Backups restores it
|
||||
on a running Steward, first-run setup restores it on a new one, and
|
||||
`steward restore` brings Steward back from it when Steward can't start.
|
||||
|
||||
## What a backup holds
|
||||
|
||||
@@ -14,18 +15,28 @@ Steward back from it into an empty database.
|
||||
| `secret.key` | The key Steward's stored passwords and tokens are sealed with |
|
||||
| `manifest.json` | Format, Steward version, migration heads, time, and the tables whose rows were left out |
|
||||
|
||||
A backup is for **system recovery**: it holds what you would otherwise have
|
||||
to set up again, and no logs or history.
|
||||
|
||||
**Kept:**
|
||||
- configuration: settings, users, API tokens, hosts, monitors, alert rules, maintenance windows, Ansible inventory and schedules, dashboards, SNMP devices, Prometheus targets, UniFi client names;
|
||||
- the audit log;
|
||||
- alert history.
|
||||
- settings, with the passwords and keys they hold;
|
||||
- users and API tokens;
|
||||
- hosts and their agent enrolments, so agents don't need enrolling again;
|
||||
- monitors, alert rules, maintenance windows and maintenance cadences;
|
||||
- Ansible inventory and schedules;
|
||||
- dashboards and share links;
|
||||
- SNMP devices, Prometheus targets and widget templates, UniFi client names.
|
||||
|
||||
**Left out** (the tables come back empty and fill again as Steward runs):
|
||||
- metrics and their rollups;
|
||||
- the audit log;
|
||||
- alert history and alert state. Each rule starts inactive and is watched
|
||||
again within a minute;
|
||||
- metric anomalies and their reviews;
|
||||
- metrics, their rollups and learned normals;
|
||||
- monitor check results;
|
||||
- Docker, Traefik and UniFi history;
|
||||
- Ansible run records;
|
||||
- the email queue;
|
||||
- password-reset links.
|
||||
- Ansible run records and maintenance job history;
|
||||
- the email queue, pending invites and password-reset links.
|
||||
|
||||
The list is `steward/backup/contents.py`. A test fails when a new table
|
||||
appears in neither list, so whoever adds a table decides.
|
||||
@@ -69,6 +80,47 @@ While backups are on, Steward records two metrics under the source
|
||||
A rule such as `backup_age_secs > 93600` (26 hours) fires when a daily backup
|
||||
has been missed.
|
||||
|
||||
An agent on the MCP sees the same without a rule. `get_overview` names a
|
||||
scheduled backup that failed, is two hours past its slot with none made, or has
|
||||
no bucket set up. `list_backups`, `check_backup` and `make_backup` are this
|
||||
page's admin tools (see [MCP](mcp.md)); restoring isn't among them.
|
||||
|
||||
## Checking a backup
|
||||
|
||||
**Settings → Backups → Check** compares a backup with what is in place, without
|
||||
changing anything. It shows what a restore would bring back, change or remove.
|
||||
Each row under Recent backups has its own Check button, and **Check a file**
|
||||
takes a file downloaded from the bucket. From a shell:
|
||||
|
||||
```sh
|
||||
docker exec -u app <steward container> steward check-backup /tmp/steward-20261015T030000Z.tar
|
||||
```
|
||||
|
||||
The check reports:
|
||||
- for each area (Settings, Users and API tokens, Hosts and agents, Monitors,
|
||||
Alert rules, Ansible, Dashboards, Plugins), how many entries are the same,
|
||||
differ, are only in the backup or are only here;
|
||||
- each setting that differs, with both values. A password or key shows only
|
||||
"differs": sealed values are opened with their own key and compared, never
|
||||
shown;
|
||||
- whether the backup's secret key is the one in use, and whether it opens the
|
||||
backup's own sealed values. A backup whose key can't open them fails the
|
||||
check, because its secrets would not come back;
|
||||
- whether the backup was made by this Steward's schema, an older one or a
|
||||
newer one.
|
||||
|
||||
What Steward records as it runs is left out of the comparison: when an agent
|
||||
or monitor was last seen, a schedule's last run, the backup history. These
|
||||
change by the minute. The list is `ACTIVITY` and `STATE_SETTINGS` in
|
||||
`steward/backup/contents.py`.
|
||||
|
||||
Each backup Steward sends is checked once it is written, and its row under
|
||||
Recent backups says so. A backup is sent even when its check can't run.
|
||||
|
||||
Checking a backup on the bucket reads it back from there. An append-only key
|
||||
may not be allowed to; the page then says AccessDenied, and the file can be
|
||||
downloaded and checked with **Check a file** instead.
|
||||
|
||||
## Making a backup by hand
|
||||
|
||||
```sh
|
||||
@@ -80,8 +132,57 @@ as Steward itself.
|
||||
|
||||
## Restoring
|
||||
|
||||
### From the web UI
|
||||
|
||||
**On a running Steward: Settings → Backups.** Press **Restore** on one of
|
||||
the recent backups, or choose a file on the "Check or restore a file" card.
|
||||
Steward first shows what the backup would change: the same comparison as
|
||||
Check. Then it says what a restore does and asks you to type `restore`.
|
||||
|
||||
- **A backup of this Steward's schema goes back in place.** Settings,
|
||||
users, hosts, monitors, alert rules and dashboards become the backup's.
|
||||
The audit log and the history of everything still here stay. History of
|
||||
anything the backup doesn't have goes with it. It is one transaction: if
|
||||
anything fails part-way, nothing changes, and Backups says why.
|
||||
- **A backup from an older Steward replaces everything**, history included,
|
||||
and you tick "Replace everything" as well. Steward brings it up to date
|
||||
as it starts.
|
||||
- **A backup from a newer Steward isn't offered.** Update Steward first.
|
||||
|
||||
Before anything changes, Steward makes a **safety backup** of itself as it
|
||||
stands. It goes to `/data/backups` (the newest five are kept) and to the
|
||||
bucket, and it is listed under Recent backups as "before restore". A
|
||||
restore can be undone by restoring that.
|
||||
|
||||
While the restore runs:
|
||||
- every page says Steward is restoring;
|
||||
- agents get a 503 and keep their readings until Steward is back;
|
||||
- scheduled work holds.
|
||||
|
||||
Then Steward restarts (it exits with code 3 so Swarm, compose or systemd
|
||||
starts it again), and you sign in as a user from the backup. If an older
|
||||
backup's full replace fails after the database was emptied, Steward starts
|
||||
at first-run setup, where the safety backup can be uploaded.
|
||||
|
||||
**On a new Steward: first-run setup.** Next to "Create the initial admin
|
||||
account" is **Or restore from a backup**: upload a backup file instead,
|
||||
and Steward comes up with its users, settings and key. There is nothing to
|
||||
keep yet, so no safety backup is made.
|
||||
|
||||
The backup's secret key is put in place as `/data/secret.key`. If
|
||||
`STEWARD_SECRET_KEY` is set instead, it must equal the backup's key, or the
|
||||
restore stops before anything changes.
|
||||
|
||||
### From the command line
|
||||
|
||||
`steward restore` writes into an **empty** database. Pass `--wipe` to drop
|
||||
everything in the database's public schema first.
|
||||
everything in the database's public schema first. Use it when Steward
|
||||
can't start at all.
|
||||
|
||||
`steward restore --in-place` does what Settings → Backups does for a backup
|
||||
of the same schema, from the shell: it replaces what the backup carries and
|
||||
keeps the audit log and history, in one transaction. Restart Steward after
|
||||
it so the restored settings load.
|
||||
|
||||
1. Stop Steward (scale its service to 0) so nothing writes during the restore.
|
||||
2. Download the backup file from Archives.
|
||||
@@ -105,7 +206,7 @@ everything in the database's public schema first.
|
||||
then data, then constraints and indexes. Between the data and the
|
||||
constraints, a kept row that points at a left-out row is put right by its
|
||||
foreign key's ON DELETE:
|
||||
- an alert event's link to an Ansible run is cleared;
|
||||
- a SET NULL link is cleared and the row kept;
|
||||
- a row whose foreign key would cascade or block is removed.
|
||||
|
||||
pg_restore 17 writes each section as a script for psql. It runs against
|
||||
@@ -113,5 +214,7 @@ Postgres 16 with one setting line dropped (`transaction_timeout`, which 16
|
||||
doesn't know).
|
||||
|
||||
CI checks the whole path on every build. The built image backs up its own
|
||||
database, restores into a second one, checks a setting came back and the
|
||||
metrics table is empty, then starts Steward on it.
|
||||
database and checks the backup against it. It changes a setting and puts
|
||||
the backup back in place: the setting returns and the audit log stays.
|
||||
Then it restores into a second, empty database, checks a setting came back
|
||||
and the metrics table and audit log are empty, and starts Steward on it.
|
||||
|
||||
+47
-8
@@ -52,7 +52,7 @@ authentication. The AI access page shows the recipes for both.
|
||||
| Bearer tokens only, no OAuth | `steward/core/api_tokens.py`. Only a hash is stored, and the token is shown once. |
|
||||
| A token never acts above its user | Effective role = min(token role, user's **current** role). Lowering a user lowers every token they hold; disabling the user stops them all. |
|
||||
| Default deny | A tool is reachable only if it was registered with a role (`register_tool(fn, role=..., read_only=...)`). `tools/list` shows a caller only the tools their role allows. A call above the role is refused, and the refusal names the role it needs. |
|
||||
| Plugin tools follow the plugin | A disabled plugin's tools are hidden and refused. |
|
||||
| Plugin tools follow the plugin | A disabled plugin's tools are hidden and refused. The host agent is built in and always on (it can't be disabled), so its tools are always there. |
|
||||
| Dry run first | `run_playbook`, `create_schedule` and `set_alert_action` default to Ansible check mode (`--check --diff`). Changes are applied only when the caller passes `check=false`. A playbook its author flagged `# steward:confirm: true` also needs `confirmed=true`. `prune_docker` previews unless `check=false`. |
|
||||
| Secrets stay put | Playbook variables Steward detects as secret reach the run but are never stored, audited or returned. Schedules and alert actions refuse them, since they would have to store them. Inventory variables are listed by name only, and HTTP monitor header values are redacted. |
|
||||
| Every change is audited | Each write records an audit event as `<user> via MCP`, with the token id in its detail. `list_audit_events(user="<user>")` includes those events. |
|
||||
@@ -75,11 +75,19 @@ Each role includes the tools of the roles above it in this list.
|
||||
| Hosts and metrics | `list_hosts`, `get_host`, `get_host_metrics`, `query_metrics` |
|
||||
| Monitors | `list_monitors`, `get_monitor` |
|
||||
| Alerts | `list_alerts`, `get_alert_history`, `list_alert_rules`, `get_alert_rule_options`, `list_maintenance_windows` |
|
||||
| Metric anomalies | `list_anomalies` (metrics that left their normal for the hour, to review first) |
|
||||
| Metric anomalies | `list_anomalies` (metrics that left their normal for the hour, to review first), `get_anomaly` (one anomaly with each occurrence against what is usual at that hour, the metric around it, what else happened on its host — alerts, Ansible runs, container deaths and starts, maintenance, reboots, other anomalies — and how earlier ones on the same metric were judged), `get_metric_normal` (the learned normal slot by slot, and the level that would be flagged), `get_anomaly_settings` (the review window and each floor) |
|
||||
| Thresholds | `get_thresholds` (the warn and crit cutoffs CPU, memory, disk, load and temperature are graded by on the pages) |
|
||||
| Automation | `list_playbooks`, `get_playbook`, `list_inventory`, `list_ansible_runs`, `get_ansible_run`, `wait_for_run`, `list_schedules` |
|
||||
| Audit | `list_audit_events` |
|
||||
| Timeline | `get_timeline` (everything that happened, newest first, in one list: alerts firing and clearing, playbook runs and what they changed, maintenance, reboots, deploys and crash-loops, reviewed anomalies, changes recorded by hand, changes to Steward's settings; by host, area or kind, and kept after the records it came from age out) |
|
||||
| Tickets | `list_tickets` (known problems someone recorded, open first; by host, subject or area), `get_ticket` (one ticket: its description, the alert rules and anomalies it links, its resolution and its log). `list_alerts` and `list_anomalies` mark what an open ticket covers as `known_issue`; `get_overview`, `get_host`, `get_monitor` and `get_container` carry `open_tickets` |
|
||||
| Docker plugin | `list_containers`, `get_container`, `list_swarm_services`, `search_container_logs`, `get_docker_disk_usage` |
|
||||
| Host agent plugin | `list_agents` |
|
||||
| Host agent (built in, always on) | `list_agents`, `list_maintenance_plans` (each plan's group, weekly slot, next run and latest run: how far it got, who it skipped and why), `get_maintenance_job` (a host's update jobs or one job: state, packages updated, whether it rebooted, why it failed), `get_host_senders` (who sent or received a host's network traffic over a window: its containers and NFS mounts ranked at the host's peak, and what none of them accounts for) |
|
||||
| Traefik plugin | `list_routers` (each router graded as the Traefik page grades it, with the status codes behind a problem, what they mean and the swarm service behind it), `get_router` (one router's history, codes, normal and anomalies), `list_certificates` (served certificates, days left, the routers they cover), `get_traffic` (the access log's clients, countries and routers, and Traefik's own figures) |
|
||||
| UniFi plugin | `get_network` (the WAN, clients, Wi-Fi networks, speed tests and devices by status), `list_devices`, `list_clients` (everyone seen, or the newest poll's top talkers), `list_network_events`, `list_alarms`, `get_network_config` (networks and VLANs, port forwards, firewall rules) |
|
||||
| SNMP plugin | `list_snmp_devices` (each device's state, newest readings in their units and the readings it didn't return), `get_snmp_device` (one device's readings over a range). Never the community or v3 keys |
|
||||
| Syslog plugin | `list_syslog_sources` (the devices sending syslog: added, offered or ignored, each with its rate, last heard and newest line), `search_syslog` (an added source's kept lines, or a host's, filtered by text, severity and worse, app and time, newest first), `list_syslog_patterns` (the phrases and severities counted, the metric each writes and the ready-made ones not added), `add_syslog_preset` (admin: add a ready-made one) |
|
||||
| Prometheus plugin | `list_prometheus_targets` (each target's state and its newest scrape: series kept, dropped and over the cap), `get_prometheus_target` (a target's stored series by metric, with labels and newest values). Never the token, and a password in a URL is masked |
|
||||
|
||||
### Operator: run playbooks, change monitoring
|
||||
|
||||
@@ -88,12 +96,38 @@ Each role includes the tools of the roles above it in this list.
|
||||
| Automation | `run_playbook`, `cancel_ansible_run`, `create_schedule`, `update_schedule`, `delete_schedule`, `update_group_members` (put hosts into an inventory group or take them out; a group alert rule follows within a minute) |
|
||||
| Monitors | `create_monitor`, `update_monitor`, `set_monitor_enabled` |
|
||||
| Alerts | `create_alert_rule`, `update_alert_rule`, `acknowledge_alert`, `send_test_alert`, `create_maintenance_window`, `end_maintenance_window` |
|
||||
| Metric anomalies | `review_anomaly` (mark one normal, so its hours are learned, or real) |
|
||||
| Metric anomalies | `review_anomaly` (mark one or several normal, so their hours are learned, or real, with a note saying why) |
|
||||
| Timeline | `log_change` (record a change Steward can't see happen — a config edited by hand, a disk swapped — on the hosts it was done on, under an area; shown as by "<you> via MCP"), `update_change` and `delete_change` (correct or take back a recorded change: its author or an admin) |
|
||||
| Tickets | `open_ticket` (a known problem, on its hosts and what it is about, linked to alert rules and anomalies; goes on the timeline), `update_ticket` (its fields and links), `comment_ticket`, `resolve_ticket` (with what fixed it, which goes on the timeline), `reopen_ticket` |
|
||||
|
||||
### Admin: destructive and remediation
|
||||
|
||||
`set_alert_action` (the playbook a rule runs when it fires), `delete_monitor`,
|
||||
`delete_alert_rule`, `prune_docker`.
|
||||
`set_anomaly_settings` (the anomaly review window and each normal's floor, as
|
||||
Settings → Thresholds sets them), `set_thresholds` (the warn and crit cutoffs host
|
||||
readings are graded by, as the same page sets them), `set_alert_action` (the playbook a rule runs when it fires), `delete_monitor`,
|
||||
`delete_alert_rule`, `prune_docker`, `run_maintenance` (update a host now, rebooting
|
||||
only if the update needs it, as the host page's Update now does).
|
||||
|
||||
`save_playbook` and `delete_playbook` write this instance's own playbooks into
|
||||
`steward-local`, the same as Steward's editor (#5748). That is automation for
|
||||
these hosts that isn't part of Steward itself; Steward's built-in playbooks are
|
||||
changed in its repository, and a git source by its repo, so both are refused.
|
||||
A save must parse as a list of plays or nothing is written; it won't overwrite
|
||||
an existing playbook without `replace=true`; and it then runs
|
||||
`ansible-playbook --syntax-check` (no host contacted) and says what that found.
|
||||
The loop for building one is save → `run_playbook` in check mode on one target
|
||||
→ `get_ansible_run` → fix and save again → apply with `check=false`. The audit
|
||||
row records the size, never the content.
|
||||
|
||||
`list_backups`, `check_backup` and `make_backup` are Settings → Backups for an
|
||||
agent (#5836), admin only like the page, since a backup holds every secret
|
||||
Steward keeps. `list_backups` gives the schedule, the next run and the last 30
|
||||
runs with the check each one got after it was sent (`bucket=true` also lists the
|
||||
bucket, which an append-only key may refuse). `check_backup` fetches one and
|
||||
compares it with what is in place, changing nothing. `make_backup` starts one in
|
||||
the background and is audited. Restoring stays in the browser, behind its typed
|
||||
confirmation. `get_overview` reports, for every role, a scheduled backup that
|
||||
failed, is overdue, or has no bucket set up.
|
||||
|
||||
The client sees each tool's full contract: arguments, what an empty value
|
||||
means, and what comes back. That contract is the tool's docstring, so read the
|
||||
@@ -128,7 +162,12 @@ Every tool follows these conventions (`steward/mcp/tools/_shape.py`):
|
||||
|
||||
Core tools: add an `async def` to a module in `steward/mcp/tools/` and list it
|
||||
in that module's `register()` with its minimum role and `read_only`. A plugin
|
||||
exposes `register_mcp_tools(register)`, and optionally `mcp_overview(db)` to
|
||||
contribute findings to `get_overview`. See
|
||||
exposes `register_mcp_tools(register)`, optionally `mcp_overview(db)` to
|
||||
contribute findings to `get_overview`, and optionally
|
||||
`mcp_events(db, host_id, host_name, since, until)`: what it knows happened on a
|
||||
host in a window, as a list of `steward.mcp.tools._events.event(...)`, which
|
||||
`get_anomaly` shows beside an anomaly; for a resource with no host, optionally
|
||||
`mcp_resource_events(db, source, resource, since, until)`. Core adds the
|
||||
stretches Steward itself wasn't recording to every anomaly. See
|
||||
[Writing a plugin](../plugins/writing-a-plugin.md). A tool that changes
|
||||
anything calls `audit_mcp(...)` from `steward/mcp/tools/_audit.py`.
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
# Tickets
|
||||
|
||||
A ticket records a known problem that takes more than a moment to fix: a disk failing slowly, a service that keeps restarting, a backup that times out at night. It says what is wrong, what has been tried and, once resolved, what fixed it. Acknowledging an alert only quiets it. A ticket keeps the story, and while it is open the alerts and anomalies it covers read as a **known issue**.
|
||||
|
||||
Open the list from **Tickets** in the sidebar. A host's page, a monitor's page and a container's page each show a **Known issues** card with their open tickets. MCP clients use `list_tickets`, `get_ticket`, `open_ticket`, `update_ticket`, `comment_ticket`, `resolve_ticket` and `reopen_ticket`.
|
||||
|
||||
**Source:** `steward/tickets/` (`service.py` for every write, `routes.py` for the pages), `steward/mcp/tools/tickets.py`
|
||||
**Tables:** `tickets`, `ticket_links`, `ticket_notes` (`steward/models/tickets.py`)
|
||||
|
||||
---
|
||||
|
||||
## What a ticket holds
|
||||
|
||||
| Field | |
|
||||
|---|---|
|
||||
| Number | `#12`, in order of opening |
|
||||
| Title | What is wrong, one line (up to 200 characters) |
|
||||
| Area | One of the timeline's areas (Settings → Timeline) |
|
||||
| Hosts | The hosts it is on, by name; none for a problem not on any one host |
|
||||
| Subject | What it is about when that is not a host as a whole: an alert rule's resource (`web-1:/`), a container (`web-1/nginx`), a monitor's name |
|
||||
| Description | What is seen, since when, what has been tried |
|
||||
| Links | Alert rules and metric anomalies it covers |
|
||||
| Log | Opened, comments, edits (which fields changed, what was linked or unlinked), resolved, reopened, each with who and when |
|
||||
|
||||
A ticket is **open** or **resolved**. Resolving one needs a resolution: what fixed it, or why it no longer matters. Reopening clears it, with an optional reason.
|
||||
|
||||
## Opening one
|
||||
|
||||
- **From an alert:** **Open a ticket** on an active alert (Alerts page) fills in the title, area, hosts and subject from the rule, and links the rule.
|
||||
- **From an anomaly:** **Open a ticket** on an anomaly to review, or one reviewed as real, does the same and links the anomaly.
|
||||
- **From a page:** the **Known issues** card on a host, monitor or container opens one about it.
|
||||
- **From scratch:** **Open a ticket** on the Tickets page.
|
||||
- **Through MCP:** `open_ticket(title, area, description, hosts, subject, alert_rules, anomalies)`.
|
||||
|
||||
Opening, editing, commenting, resolving and reopening need an operator or admin. Viewers read everything.
|
||||
|
||||
## Known issues
|
||||
|
||||
An alert or anomaly is a known issue while an open ticket:
|
||||
|
||||
- links its alert rule (or the covering group rule it came from), or the anomaly;
|
||||
- names its resource as its subject; or
|
||||
- is about its host as a whole (no subject), when the resource is the host itself.
|
||||
|
||||
The Alerts page and the anomaly lists show a **Known issue** badge with the ticket. `list_alerts` and `list_anomalies` return the same as `known_issue`. `get_overview` lists up to ten open tickets in `open_tickets` and counts them all in `counts.tickets_open`. `get_host`, `get_monitor` and `get_container` carry their own `open_tickets`.
|
||||
|
||||
## On the timeline
|
||||
|
||||
Opening, resolving and reopening a ticket each write a timeline entry under the ticket's area, on its hosts and subject (`ticket.opened`, `ticket.resolved`, `ticket.reopened`, kind Ticket). The resolution is the resolved entry's note, so the timeline keeps what fixed it. Comments and edits stay in the ticket's own log.
|
||||
|
||||
Every step is audited (`ticket.opened`, `ticket.edited`, `ticket.commented`, `ticket.resolved`, `ticket.reopened`). Those audit rows stay off the timeline, which holds the ticket's own entries.
|
||||
|
||||
## Backups
|
||||
|
||||
Tickets are not in Steward's backups yet, the same as the timeline itself (`steward/backup/contents.py`, `EXCLUDED`).
|
||||
@@ -0,0 +1,66 @@
|
||||
# Timeline
|
||||
|
||||
The timeline is one list of everything that happened to the infrastructure, newest first: alerts firing and clearing, playbook runs and what they changed, maintenance runs and reboots, deploys and crash-loops, anomalies once reviewed, changes recorded by hand, and changes to Steward's own settings. Open it from **Timeline** in the sidebar, from a host's **History** card, or through the `get_timeline` MCP tool.
|
||||
|
||||
Each entry stands on its own. An alert event, an Ansible run, a maintenance job or an audit row is pruned after its own retention, but the entry for it stays. Its link then reads "Details no longer kept".
|
||||
|
||||
**Source:** `steward/timeline/`
|
||||
**Table:** `timeline_entries` (`steward/models/timeline.py`)
|
||||
|
||||
---
|
||||
|
||||
## What is recorded
|
||||
|
||||
Every source writes its entry in the same transaction as its own record, through `steward/timeline/record.py`:
|
||||
|
||||
| Source | Written by | Entry types |
|
||||
|---|---|---|
|
||||
| Alert events | `core/alerts._add_event` | `alert.fired`, `alert.resolved`, `alert.acknowledged`, `alert.silent`, `alert.resumed` |
|
||||
| Ansible runs, when they finish | `ansible/executor.start_run`, and the startup sweep of interrupted runs | `ansible.changed`, `ansible.unchanged`, `ansible.failed`, `ansible.check` |
|
||||
| Audit rows | `core/audit.log_audit` | `steward.config`, `steward.access`, `steward.signin`, `steward.backup` |
|
||||
| Metric anomalies: one entry each, whose type follows its review | `core/anomalies` (opened, ended, marked, lapsed) | `anomaly.to_review`, `anomaly.real`, `anomaly.normal`, `anomaly.lapsed` |
|
||||
| Maintenance jobs, when they end (and again if the host comes back late) | host agent: `maintenance`, `cadence` | `maintenance.done`, `maintenance.failed` |
|
||||
| A host away: a reboot, a crash, lost contact, the agent restarting; kept up to date until it ends | host agent: `downtime.record_events` | `host.rebooted`, `host.lost_contact`, `host.agent_restarted` |
|
||||
| Container snapshots: a new image, a recreated container, a restart or death | Docker: `ingest.persist_host_docker` → `timeline.from_snapshot` | `docker.deployed`, `docker.crash_loop`, `docker.restarted` |
|
||||
| A change recorded by hand, from the Timeline page, a host's History card or MCP `log_change` | `timeline/changes.py` | `change.recorded` |
|
||||
| Tickets: opened, resolved (the resolution is the entry's note) and reopened | `tickets/service.py` | `ticket.opened`, `ticket.resolved`, `ticket.reopened` |
|
||||
|
||||
A source whose record changes after it is written keeps one entry for it (`record.record_or_update`): a downtime gets its length when it ends, an anomaly changes type when it is reviewed.
|
||||
|
||||
Docker's units are swarm services where a container has one, so a service's tasks, replaced on every deploy and crash, read as one subject. A swarm task moving to another host is not a deploy. A crash loop uses the same rule as the Docker pages: Settings → Thresholds' deaths within an hour. The death that reaches it opens one `docker.crash_loop` entry, and each later one extends it until the container has been quiet for an hour. The deaths before it stay as hidden `docker.restarted` entries.
|
||||
|
||||
Some audit actions are left to another writer, because the event itself is recorded there: starting a run, acknowledging an alert, starting maintenance, and recording a change by hand. A person's own preferences (time zone, email settings) are not recorded. `catalog.audit_type` holds that mapping.
|
||||
|
||||
On its first start, Steward fills the timeline from the last 90 days of records that predate it (`service.backfill`): core's alert events, finished runs and audit rows, and each loaded plugin's own through its `timeline_backfill(session, since)` (the host agent's maintenance jobs and downtime). It fills from each source once and records which in `timeline.filled`, so a plugin loaded later fills on the next daily turn. An entry for a record that is already covered is skipped. Docker has no fill: its events can't tell a deploy from a restart after the fact.
|
||||
|
||||
`get_anomaly`'s "what else was going on" reads the timeline for the host or resource, hidden types included, beside each occurrence.
|
||||
|
||||
## Recording a change by hand
|
||||
|
||||
Steward can't see every change happen: a config edited on a host, a disk swapped, a service moved. Whoever made it records it, with **Record a change** on the Timeline page or a host's History card, or the `log_change` MCP tool. It says what was done, the area it is about, when, the hosts it was done on (none for a change not on any one host), optionally what it was done to (a container, a file) and a longer detail.
|
||||
|
||||
An operator or admin can record one. Its author can edit or delete it from its **Edit** link, or with the `update_change` and `delete_change` MCP tools, and so can an admin. One recorded through MCP is shown as by "<user> via MCP" and is editable by that token's user. Recording, editing and deleting are audited (`timeline.change_recorded`, `…_edited`, `…_deleted`), and those audit rows stay off the timeline, which holds the change itself.
|
||||
|
||||
## Areas and kinds
|
||||
|
||||
An entry has a **kind**, which says how it came about: Change, Automation, Alert, Anomaly, Ticket, Observed (Steward saw it happen with no rule or person behind it: a reboot, a crash-loop) or Steward. Kinds are fixed in `catalog.KINDS`.
|
||||
|
||||
An entry also has an **area**, which says what part of the infrastructure it is about. The areas start as Service, Host OS, Hardware, Storage, Network, Security and Monitoring.
|
||||
|
||||
Each entry is written with an area of its own. An alert's area comes from what its rule watches (`catalog.area_of_metric`): drive health is Hardware, a mount is Storage, an HTTP monitor is Service. A change recorded by hand has the area its author picked. Other entries use their type's area.
|
||||
|
||||
## Settings → Timeline
|
||||
|
||||
| Setting | Key | Default |
|
||||
|---|---|---|
|
||||
| Areas, in order: rename, add, or remove one and move its entries to another | `timeline.areas`, `timeline.area_moved` | the seven above |
|
||||
| Each type's area ("As recorded" keeps each entry's own) and whether it is shown | `timeline.types` | from the catalog |
|
||||
| Keep for, in days (0 keeps everything) | `timeline.retention_days` | 0 |
|
||||
|
||||
These are applied when the timeline is read, never written onto an entry. A change re-sorts the whole history. A hidden type is still recorded, so showing it again brings its entries back.
|
||||
|
||||
Hidden by default: dry runs, playbook runs that changed nothing, sign-ins, single container restarts, the agent restarting, and anomalies not yet reviewed, accepted as normal or lapsed.
|
||||
|
||||
## Adding a type
|
||||
|
||||
A plugin registers its types in `setup()` with `catalog.register_type(key, label, kind, area, shown, about)`, and the records its entries point to with `catalog.register_ref(ref_type, model)`, so an entry whose record has aged out reads "Details no longer kept". It writes entries with `record.record(session, type=…, at=…, summary=…, hosts=…, ref=(ref_type, id))`, or `record.record_or_update` for a record that changes. It may add `timeline_backfill(session, since)` to its `__init__.py` for records that predate the timeline. Settings → Timeline lists the new type at once. `plugins/host_agent/timeline.py` and `plugins/docker/timeline.py` are worked examples.
|
||||
@@ -0,0 +1,54 @@
|
||||
# Home Assistant plugin
|
||||
|
||||
Keeps a Home Assistant instance running: shows whether backups are happening and whether the system has a problem, and installs Core, OS and add-on updates, on a click or a weekly schedule, each only after a fresh backup is confirmed. It looks after Home Assistant itself and doesn't read your devices. Each update goes on the timeline. Nothing is added to Home Assistant: you sign in, and Steward uses its standard API.
|
||||
|
||||
## Setting it up
|
||||
|
||||
1. In Home Assistant, turn on automatic backups (Settings → System → Backups).
|
||||
2. Make a user for Steward (Settings → People → Add person), as an administrator if Steward should install updates.
|
||||
3. On Steward's Home Assistant page, choose Connect, enter Home Assistant's address, and continue to its sign-in page. Sign in as that user.
|
||||
|
||||
Your browser and Steward both need to reach Home Assistant at that address. Home Assistant sends your browser back to Steward's Public base URL (Settings → General), so open Steward at that address.
|
||||
|
||||
## What Steward holds
|
||||
|
||||
**Steward stores a credential with the same access as the user who signed in.** Home Assistant has no narrower permission, so an administrator's credential can do anything that administrator can, including controlling every device. Steward only uses it to read status, take backups and install updates. It is stored encrypted.
|
||||
|
||||
We recommend a service account, a user made just for Steward, rather than your own. What Steward does then appears under its own name in Home Assistant's logs, so it's easy to tell apart from what people do.
|
||||
|
||||
Installing needs an administrator, because Home Assistant only lets administrators take backups. With any other user, Steward shows status only. Steward learns which it has by asking once after sign-in, and a user who isn't an administrator is refused that one request, which Home Assistant may show as a failed login notification.
|
||||
|
||||
Removing the connection ends the sign-in on Home Assistant. You can also end it yourself under Security on that user's profile, and Steward then stops asking until you sign in again. Home Assistant bans an address after a few refused requests, so Steward stops after one refusal until you sign in again or choose Try again.
|
||||
|
||||
## Installing an update
|
||||
|
||||
Install asks once, then Steward:
|
||||
|
||||
1. Asks for a backup and waits until Home Assistant's last successful backup time moves. If it doesn't, nothing is installed.
|
||||
2. Asks for the update and follows it until the new version is installed, or until a deadline: 20 minutes for an add-on, 30 for Core, 45 for the OS.
|
||||
|
||||
One runs at a time, and it carries on if Steward restarts. Firmware and custom integrations are left to Home Assistant, and Supervisor updates itself.
|
||||
|
||||
An OS update takes effect only after the machine reboots, and Install leaves that to you. Steward records the update as done once Home Assistant reports the new version, which it does before the reboot. Home Assistant then raises a repair asking for the reboot, which appears under System problems until you do it.
|
||||
|
||||
## System problems
|
||||
|
||||
Each read also asks Home Assistant whether the system itself has a problem, and the page and the overview show what it says:
|
||||
|
||||
- open repairs, from Settings → System → Repairs
|
||||
- the Supervisor calling the system unhealthy or unsupported
|
||||
- less than 10% of the disk free
|
||||
- starting in recovery mode, when its configuration didn't load
|
||||
- an add-on set to start on its own that isn't running
|
||||
|
||||
Repairs need an administrator's sign-in. Disk space and add-ons come from the Supervisor, so an install without one doesn't report them, and the page says so.
|
||||
|
||||
## Scheduled updates
|
||||
|
||||
Set a day and time under Scheduled updates on the page. It's off until you do. At that time Steward installs what's waiting, add-ons first, then Core, then the OS, one at a time and each after its own confirmed backup. It starts nothing new more than 4 hours after the slot. The first failure ends the run and the rest wait, and the page, the overview and `update_failed` say so. A Core update restarts Home Assistant with nobody there to watch, and an update can change how automations behave.
|
||||
|
||||
An OS update installed by the schedule also reboots the machine, with nobody there to watch. It counts as done once the new version is running. If that hasn't happened 20 minutes after the reboot, for example because the machine didn't come back or fell back to the old version, the update is marked failed.
|
||||
|
||||
## Metrics
|
||||
|
||||
Under source `homeassistant`, resource `homeassistant`, read every 5 minutes: `is_up`, `updates_waiting`, `backup_age_hours`, `problems_open`, `disk_free_pct` and `update_failed`. Useful alert rules: `backup_age_hours` above 26 for a missed daily backup, `problems_open` above 0, and `update_failed` above 0. A rule's no-data warning covers Home Assistant going quiet.
|
||||
@@ -124,13 +124,27 @@ Python 3.8+ stdlib only. `urllib.request` for the POST, plus `json`, `os`, `shut
|
||||
|
||||
Each mount is read in a daemon thread under one 5 s deadline. A hard-mounted NFS share whose server stops blocks `statvfs` in the kernel with no timeout; read inline, that froze the whole agent. A mount that misses the deadline is sent as `{"mount", "stalled": true}`, and isn't probed again while its last probe is still blocked. Steward counts them as `mounts_stalled`.
|
||||
|
||||
### NFS delay per mount (1.22.0, #5996)
|
||||
|
||||
`mounts_stalled` says a mount is stuck; it can't say a share was slow before it stuck, or how slow it was when it came back. Each sample also reads `/proc/self/mountstats`, the kernel's own cumulative count of every NFS request each mount has finished. Reading it never touches the share, so it answers while one is stuck. The agent sends each NFS mount's requests since the last sample as `nfs: [{mount, ops_per_sec, retrans, timeouts, rtt_ms, exe_ms, read_ms, write_ms}]`: `rtt_ms` is the network and server's round trip, `exe_ms` that plus the time queued on the host, which is what a program waits. The delays are averages over the requests that finished, and are left out when none did. A mount new since the last sample, or whose counters went back (remounted), waits for the next one.
|
||||
|
||||
**Bytes per mount (1.25.0, #6115).** Each op's line also counts the bytes sent and received on the wire, so each mount's row carries `tx_bps` and `rx_bps` too: the share's part of the host's network traffic, which belongs to no container. A large copy to the NAS shows here rather than as traffic nobody sent.
|
||||
|
||||
Steward stores them per mount (`nfs_*` on `<host>:<mount>`), and the slowest mount's `exe_ms` on the host as `nfs_exe_max_ms`, for a rule ("NFS slow": over 1000 ms for 3 checks) and for the host page's NFS chart beside `mounts_stalled`. Each mount's bar on the host page says what a request took and how many were sent again or timed out. A request is counted when it finishes, so a stuck share shows nothing until it comes back, then its long requests all at once.
|
||||
|
||||
### A container's memory is its processes' own (1.23.0, #6030)
|
||||
|
||||
Each running container sends `mem_used_bytes` and `mem_used_pct` (of its limit, or of the host's RAM when it has none) and, beside them, `mem_cache_bytes`. Used is anon plus shmem from the container's cgroup memory stats (v1: rss plus shmem). It is what the processes hold and can't give back without swap, and it counts Postgres's shared buffers, which live in shmem. Cache is the file cache charged to the container (v2's `file`, v1's `cache`, shmem taken out). The kernel keeps what the container read or wrote for as long as nothing else needs the memory, and gives it back when something does.
|
||||
|
||||
Before this, the agent sent Docker's working set (usage less `inactive_file`) as `mem_usage_bytes`. That figure still counts recently used file cache. On 2026-10-17 a file-heavy container with no memory limit read 191 GB that way, while its processes held 2.2 GB. The host's own figure (`MemTotal − MemAvailable`) already left cache out, so the two disagreed. The new names keep the two meanings apart in history and in learned normals.
|
||||
|
||||
### Every Docker read is bounded (1.15.0, #5764)
|
||||
|
||||
One Docker answer must arrive within 15 s and fit in 32 MiB, and one log answer within 5 s and 4 MiB. Past either limit the read is cut off, not waited on. A per-read timeout alone never ends a body that keeps trickling in. Container logs are read since each container's cursor, but only its newest 2,000 lines, all containers within 10 s. A container that writes more than that gets a `_steward` note saying older lines were skipped. A container whose answer is too big skips ahead to now. Before this, a 1.13.0 agent re-read a growing backlog every interval and went silent for a day at 2.1 GB. Each sample also carries the agent's own `agent` footprint (`rss_bytes`, `cpu_pct`), which Steward records as `agent_rss_bytes` and `agent_cpu_pct`.
|
||||
|
||||
### What the host has waiting (1.16.0, #5765)
|
||||
|
||||
Once an hour, and when the agent starts, a background thread asks the package manager what it would upgrade, so a slow apt never holds up a sample. On apt hosts it uses `/usr/lib/update-notifier/apt-check` (pending;security), or `apt list --upgradable` when that's missing. On dnf hosts it uses `dnf -C check-update`, `dnf -C updateinfo list --security`, and `needs-restarting -r` for whether to reboot. None of this needs root or the network: the commands read lists the system's own timers already fetched. Each command has 120 s. The last answer rides every sample as `updates`. Every sample also reads Debian's `/var/run/reboot-required` (and `.pkgs`) as `reboot`. Steward records `updates_pending`, `updates_security` and `reboot_required` (1/0) for rules, and keeps the newest on the registration. The host page's Agent card leads with "Reboot required since …", then "N updates waiting (M security)" or "Up to date", with when the check ran. `state["updates_due"] = True` asks for a check on the next sample; a maintenance job uses it once it has updated the host.
|
||||
Once an hour, and when the agent starts, a background thread asks the package manager what it would upgrade, so a slow apt never holds up a sample. On apt hosts it uses `/usr/lib/update-notifier/apt-check` (pending;security), or `apt list --upgradable` when that's missing. On dnf hosts it uses `dnf -C check-update`, `dnf -C updateinfo list --security`, and `needs-restarting -r` for whether to reboot; yum hosts the same through `yum -C` (1.21.0, #5803). On zypper hosts it uses `zypper --no-refresh list-updates` (`--dup` on Tumbleweed, which upgrades by distribution), `list-patches --category security` for the needed security patches (Tumbleweed has none to list), and `zypper needs-rebooting`. On pacman hosts it uses `checkupdates` from pacman-contrib, which install-deps.sh installs; pacman says nothing of security, and a reboot is required once the running kernel's `/usr/lib/modules/<release>` is gone, i.e. the kernel was upgraded under it. None of this needs root, and apart from `checkupdates` none of it needs the network: the commands read lists the system's own timers already fetched. `checkupdates` syncs a copy of the package lists into its own temporary directory, so it reaches the host's mirrors once an hour but never touches pacman's real database. Each command has 120 s. The last answer rides every sample as `updates`. Every sample also reads Debian's `/var/run/reboot-required` (and `.pkgs`) as `reboot`. Steward records `updates_pending`, `updates_security` and `reboot_required` (1/0) for rules, and keeps the newest on the registration. The host page's Agent card leads with "Reboot required since …", then "N updates waiting (M security)" or "Up to date", with when the check ran. `state["updates_due"] = True` asks for a check on the next sample; a maintenance job uses it once it has updated the host.
|
||||
|
||||
|
||||
### A root helper for updates and reboots (1.17.0, #5766)
|
||||
@@ -148,16 +162,29 @@ systemd when the agent leaves it a request:
|
||||
- `steward-maint.path` (`PathExistsGlob=…/requests/*.json`) starts
|
||||
`steward-maint.service`, a oneshot running `maint.py` as root.
|
||||
- The helper opens each request with `O_NOFOLLOW`, wants a regular file under
|
||||
4 KiB, and accepts only `update`, `reboot`, `drain` or `undrain`, an id of
|
||||
4 KiB, and accepts only `check`, `update`, `reboot`, `drain` or `undrain`, an id of
|
||||
letters, digits and dashes, and a node id in the swarm's own 25-character
|
||||
form. It deletes every request, valid or not, and writes the outcome to
|
||||
`/var/lib/steward-maint/results/<id>.json` (root's; kept a week). A request
|
||||
whose id already has a result is not run again.
|
||||
- **check** (1.24.0, #6098): what the update would upgrade, changing nothing
|
||||
but the package lists: `apt-get update` then `apt-get -s dist-upgrade`;
|
||||
`dnf`/`yum check-update`; `zypper list-updates` (`dup --dry-run` on
|
||||
Tumbleweed); `pacman -Sy` then `-Qu`. It says whether Docker is among it
|
||||
(`docker`, `docker-ce`, `docker.io`, `docker-engine`, `moby-engine`,
|
||||
`containerd`, `containerd.io`: the packages whose install scripts restart
|
||||
the daemon), and lists the running containers that aren't swarm tasks,
|
||||
each with its restart policy (at most 40).
|
||||
- **update**: `apt-get update` then `dist-upgrade` keeping existing config
|
||||
files, with `NEEDRESTART_MODE=l` so needrestart only lists services rather
|
||||
than restarting the Docker daemon under its containers; or
|
||||
`dnf -y upgrade --refresh`. The result says how many packages changed and
|
||||
whether a reboot is now required.
|
||||
than restarting them. A package's own install script still restarts its
|
||||
service: Docker's does, stopping every container on the host, which is
|
||||
what the check is for;
|
||||
`dnf -y upgrade --refresh` (or yum's); `zypper refresh` then
|
||||
`zypper update` (`zypper dup` on Tumbleweed), counting zypper's 102/103
|
||||
"reboot / restart needed" exits as success; or `pacman -Syu`
|
||||
(#5804). The result says how many packages changed and whether a reboot is
|
||||
now required.
|
||||
- **reboot**: writes `rebooting`, syncs, `systemctl reboot`. Any request after
|
||||
it waits for the next boot.
|
||||
- **drain / undrain**: `docker node update --availability drain|active`, on
|
||||
@@ -184,11 +211,40 @@ runs on, loses nothing. `plugins/host_agent/maintenance.py` has the states and
|
||||
transitions (model-free, unit-tested) and the database side.
|
||||
|
||||
```
|
||||
queued → updating → [draining →] rebooting → [undraining →] done
|
||||
↘ done (no reboot needed, or the job may never reboot)
|
||||
queued → [checking →] [draining → settling →] updating
|
||||
→ [draining → settling →] [rebooting →] [undraining →] [recovering →] done
|
||||
any state → failed (a step's result said so) | timed_out (its deadline passed)
|
||||
draining / settling / updating / rebooting, once drained → undraining → failed | timed_out
|
||||
```
|
||||
|
||||
**A job never ends leaving its drain behind (#6387).** On 2026-10-25 a job
|
||||
drained VDNT-Docker02, which ran Traefik and Steward. Its agent's result
|
||||
reaches Steward through Traefik, and Traefik took 11.5 minutes to start on
|
||||
Docker03 (its image had to be pulled). The job gave up at the 10-minute drain
|
||||
deadline and finished `timed_out` where it stood, leaving the node drained
|
||||
for hours. Now a job that fails or times out while its node may be drained
|
||||
(the drain was handed out, or went through and wasn't undone) goes to
|
||||
**undraining** first, with the outcome kept in `ends_as`, and finishes as that
|
||||
once the node is active again. If the undrain goes wrong too, `detail` says
|
||||
both. The drain deadline is 30 minutes, so a result held up by the proxy
|
||||
moving still lands.
|
||||
|
||||
**Docker upgraded, drained first (1.24.0, #6098).** On 2026-10-18 an update
|
||||
on VDNT-Docker02 restarted the Docker daemon six seconds in, before the drain
|
||||
that came only with the reboot: every container on the node stopped, and
|
||||
portal_app was down until it was redeployed by hand. A job for an agent of
|
||||
1.24.0 or later now starts with a **check**. When the update upgrades Docker,
|
||||
a swarm node is drained before it; otherwise it is drained only before a
|
||||
reboot, and a node is drained at most once a job. After a drain, **settling**
|
||||
gives the node's tasks 5 minutes (`DRAIN_SETTLE`) to move before the update
|
||||
or reboot goes ahead. The containers the check found running outside the
|
||||
swarm are kept on the job (`checked`); once the work is over, **recovering**
|
||||
waits up to 10 minutes (`RECOVER_LIMIT`) for each to be seen running again
|
||||
in the Docker plugin's stored containers, and fails the job naming any that
|
||||
aren't, marking those with no restart policy. settling and recovering are
|
||||
Steward's own waits, moved on by the minute tick. An older agent gets no
|
||||
check, and its job runs as before.
|
||||
|
||||
- **Hand-off.** Steward's answer to an ingest post carries
|
||||
`"maintenance": [{"id", "action", ["node"]}]`, the step that host's agent
|
||||
should carry out now. It is repeated on every post until a result for that
|
||||
@@ -203,13 +259,15 @@ any state → failed (a step's result said so) | timed_out (its deadline passed)
|
||||
restart on a host that stayed up has an old `boot_at` and changes nothing.
|
||||
- **Reboot only when required**: the update's result says whether a reboot is
|
||||
needed; a job made with "never reboot" stops after the update.
|
||||
- **Swarm nodes** are drained first and made active after. The node is found
|
||||
- **Swarm nodes** are drained first and made active after (see above for
|
||||
when). The node is found
|
||||
by hostname in the Docker plugin's swarm nodes; a manager drains itself, a
|
||||
worker is drained by a manager whose agent has the helper. With no such
|
||||
manager the job is refused rather than rebooting an undrained node.
|
||||
- **Deadlines** (`DEADLINES`): queued 1 h, updating 90 min, draining 10 min,
|
||||
rebooting 30 min, undraining 10 min. A minute tick (`host_agent_maintenance`)
|
||||
times out a job past its deadline.
|
||||
- **Deadlines** (`DEADLINES`): queued 1 h, checking 30 min, draining 30 min,
|
||||
settling 15 min, updating 90 min, rebooting 30 min, undraining 10 min,
|
||||
recovering 15 min. A minute tick (`host_agent_maintenance`) times out a job
|
||||
past its deadline.
|
||||
- **A maintenance window** scoped to the host's agent metrics
|
||||
(`host_agent/<host>`) opens when the job starts, lasts as long as the rest of
|
||||
the job could take, and ends when it does.
|
||||
@@ -252,6 +310,40 @@ Maintenance** (`/plugins/host_agent/maintenance`).
|
||||
last week, then each plan with its schedule, next slot and last five runs.
|
||||
Each host's Agent panel shows its last maintenance job.
|
||||
|
||||
#### Spreading swarm services back out (1.26.0, `rebalance.py`)
|
||||
|
||||
A run drains each swarm node in turn, and the swarm never moves a task back
|
||||
by itself, so every run used to end with the services on the node drained
|
||||
first. A plan with **Spread swarm services back out** (on by default) ends a
|
||||
run that drained a node with a run-level step, once its last host is back in
|
||||
service:
|
||||
|
||||
- **What moves.** While the fullest active node has two or more tasks than
|
||||
the emptiest, a replicated service whose running tasks are all on the
|
||||
fullest moves; one with several replicas there goes first. A service is
|
||||
left where it is, and the run says why, when the plan keeps it in place
|
||||
(**Keep in place**, service names), when it is below its replicas, when its
|
||||
image isn't pinned to a digest, or when the emptier node doesn't hold that
|
||||
digest. Only what kept the nodes from evening out is reported.
|
||||
- **The image check.** Agent 1.26.0 reports each service's pinned digest and
|
||||
every `repo@sha256:…` its host holds (from `/system/df`, every 10 min; a
|
||||
list older than 30 min isn't trusted). A service moves only to a node that
|
||||
already holds its exact image, so a pruned image or a digest the registry
|
||||
has since deleted can't strand it.
|
||||
- **Who moves them.** A swarm manager's helper, through a fifth step action,
|
||||
`rebalance`, carrying the service names (each checked against Docker's name
|
||||
alphabet, at most 48). It force-updates each in turn (`docker service update
|
||||
--force --detach=false`, spec unchanged, no registry lookup), skipping one a
|
||||
constraint or preference places, gives each 5 min to settle and starts no
|
||||
move after 40 min. The swarm starts each on its emptiest node. A stolen
|
||||
manager's agent token can therefore also restart named services in place.
|
||||
- **How it ends.** The run stays `running` until the result arrives, then
|
||||
ends `done` with what moved, or `failed` if a move didn't settle or the
|
||||
manager didn't answer within 60 min. A window over the `docker` figures
|
||||
covers the restarts, and the step goes on the timeline
|
||||
(`maintenance.rebalanced`). With no manager on 1.26.0, or nothing to move,
|
||||
the run ends `done` and says so.
|
||||
|
||||
### The swarm's health, alertable (1.19.0, #5788)
|
||||
|
||||
Every manager's agent reports the whole swarm. From each report the docker plugin (`plugins/docker/swarm_health.py`) records three swarm-wide figures on resource `swarm`, source `docker`:
|
||||
@@ -324,7 +416,7 @@ The agent's self-reported hostname in the payload is advisory. The real identity
|
||||
### Failure behavior
|
||||
|
||||
- POST fails → push sample to ring buffer (max 20), exponential backoff `30s → 60s → 120s → 300s cap`, resets on first success.
|
||||
- On next success → flush all buffered samples in a single batched POST.
|
||||
- On next success → flush the buffer oldest first, five samples a POST (`MAX_SAMPLES_PER_POST`). The new sample queues behind the backlog, so Steward always receives a host's samples in the order they were taken (1.22.0, #5995): a rule counting checks in a row then sees a stall's run of breaching checks unbroken. Before, each post carried the newest sample too, and after the 2026-10-17 NFS stall its healthy reading ended every post's run, so "Mount not answering" (10 in a row) never fired.
|
||||
- Ring buffer full → drop oldest, keep newest. Logged at DEBUG (expected during extended outages).
|
||||
- Malformed payload rejection (400) → drop the sample (don't re-buffer, it'll just be rejected again). Indicates agent/server version skew.
|
||||
- Token rejection (401) → log ERROR with remediation hint, continue retry loop at backoff cadence. Admin fixes via UI + conf file edit; no restart needed.
|
||||
@@ -458,7 +550,7 @@ Content-Type: application/json
|
||||
|
||||
### Design points
|
||||
|
||||
- **`samples` is always a list**, even for a single sample. This is how the ring buffer drains after a failure — agent POSTs `[current, ...buffered]` in a single request. One-path server code.
|
||||
- **`samples` is always a list**, even for a single sample. This is how the ring buffer drains after a failure — agent POSTs the oldest buffered samples, with the current one only once the backlog is through. One-path server code.
|
||||
- **`ts` is agent-reported, ISO-8601 UTC.** Server trusts it for `PluginMetric.recorded_at`. Host clocks drift but NTP is reliable enough for our purposes.
|
||||
- **If `|ts - now| > 5 minutes`**, server logs a WARN but still accepts. Don't reject, don't lose data over clock skew.
|
||||
- **`metadata` is sent on every POST**, not just on change. Server-side diff detects actual changes and only writes on change. Cost per POST is one dict — negligible. Benefit: server can cleanly detect agent restarts.
|
||||
|
||||
@@ -46,6 +46,8 @@ Each target also records four metrics about itself, under its own name:
|
||||
|
||||
A value's unit is read from Prometheus naming: `_bytes` as bytes, `_seconds` as a span, `_timestamp_seconds` as a moment ("3h ago"), `_per_sec` as a rate.
|
||||
|
||||
**A refused token stops the scraping.** When an endpoint answers 401 or 403, Steward stops asking and says so on the target's page and in the overview, because asking again won't change the answer and some services, Home Assistant among them, ban an address after a few refusals. Saving the target, usually with a new token, or pausing and resuming it, starts it again. Any other failure is retried at the next scrape.
|
||||
|
||||
A **state set** is one series per possible state, the current one 1 and the rest 0, such as `fabledarchives_backup_target_state{target, state}`. The target page shows it as one row per target (or job), naming the current state; the other states are listed on hover. A metric is read as a state set when its name ends in `_state` and every series has a `state` label reading 0 or 1. The OpenMetrics form, where the label is named after the metric (`foo{foo="a"} 1`), counts too. Each state is still stored as its own series, so an alert rule can watch one state.
|
||||
|
||||
**Only what the endpoint reports now is current.** When a scrape succeeds, any series it no longer has loses its newest value. That happens when the endpoint stopped reporting it, for example an old `build_info` after an upgrade, or when a filter or the cap now leaves it out. Its history stays on the chart until retention removes it. A failed scrape leaves the newest values as they were.
|
||||
|
||||
@@ -0,0 +1,88 @@
|
||||
# Syslog plugin
|
||||
|
||||
Receives syslog from NASes, routers and other devices over UDP and TCP
|
||||
(RFC 3164 and RFC 5424). The plugin keeps the lines of the sources you add and
|
||||
puts them beside Steward's other readings.
|
||||
|
||||
## What it does
|
||||
|
||||
- **Sources.** A device that starts sending is *offered* on the Syslog page.
|
||||
Its lines are counted there but not stored until an admin adds it. Ignored
|
||||
senders are still counted. Each added source keeps its lines in a ring:
|
||||
the age limit (`retention_days`, 14 by default) and the size cap
|
||||
(`max_bytes_per_source`) are set in Settings → Plugins → Syslog.
|
||||
- **Reading.** Each source has its own page, with lines filtered by severity,
|
||||
app, text and time. A host's page and an SNMP device's page show the newest
|
||||
lines of the sources mapped to them. A source maps to a host by its binding,
|
||||
or, when it has none, by sharing the host's or device's address.
|
||||
- **Patterns.** Syslog → Patterns counts each source's lines matching some
|
||||
phrases (case-insensitive) or a severity over a window. The count is written
|
||||
every minute as the metric `lines_matching_<key>` under source module
|
||||
`syslog`, zeros included, so an ordinary alert rule fires on the first match
|
||||
and clears once the window has passed. Ready-made patterns cover disk I/O
|
||||
errors, disk resets, NFS server trouble, filesystem errors, degraded arrays
|
||||
and "errors and worse". "Alert on it" opens the rule form aimed at the count.
|
||||
- **Beside the readings.** `get_anomaly` includes the warnings and worse logged
|
||||
by the anomaly's host or SNMP device. Each anomaly row has "Syslog around
|
||||
it". Host metrics charts and SNMP device charts mark each error with a
|
||||
dashed red line.
|
||||
- **MCP.** `list_syslog_sources`, `search_syslog`, `list_syslog_patterns` and `add_syslog_preset`.
|
||||
|
||||
## Deploying
|
||||
|
||||
Steward runs as an unprivileged user, so it listens on **5514** (UDP and TCP),
|
||||
not 514. Publish that port from the container:
|
||||
|
||||
```yaml
|
||||
# docker compose
|
||||
ports:
|
||||
- "5514:5514/udp"
|
||||
- "5514:5514/tcp"
|
||||
```
|
||||
|
||||
Under **Docker Swarm**, either publishing mode works.
|
||||
|
||||
**Ingress** (Swarm's default) lets Steward move between nodes. Devices send to
|
||||
any node's address, or to an address shared over the nodes (a keepalived VIP):
|
||||
|
||||
```yaml
|
||||
ports:
|
||||
- { target: 5514, published: 5514, protocol: udp }
|
||||
- { target: 5514, published: 5514, protocol: tcp }
|
||||
```
|
||||
|
||||
Through ingress every line arrives from Docker's own address on the ingress
|
||||
network, so the address no longer tells the devices apart. For such an address
|
||||
Steward keys the source by the hostname each line carries instead (#6096): each
|
||||
device is its own source. A device must put its hostname in its lines (NASes
|
||||
and routers do); lines with none at Docker's address all fold into one source,
|
||||
and the page says so. Docker's address changes when Steward's task moves to
|
||||
another node; a named source stays the same source, added or not, and takes the
|
||||
new address.
|
||||
|
||||
Such a source's own address, which places its lines on its SNMP device's and
|
||||
host's pages (chart marks, the lines around an anomaly), is found by name: the
|
||||
SNMP device whose reported name (sysName, asked with every poll) or given name
|
||||
matches, else the host of that name. Where nothing matches, set **Device
|
||||
address** on the source's edit page; a value set there always wins.
|
||||
|
||||
**Host mode** keeps each device's own address, but only the node running the
|
||||
task answers, so devices must be pointed at that node:
|
||||
|
||||
```yaml
|
||||
ports:
|
||||
- { target: 5514, published: 5514, protocol: udp, mode: host }
|
||||
- { target: 5514, published: 5514, protocol: tcp, mode: host }
|
||||
```
|
||||
|
||||
To let devices use 514 instead, publish `514:5514` instead of `5514:5514`.
|
||||
|
||||
## Pointing a device at it
|
||||
|
||||
The Syslog page's "Point a device here" section gives the address and port,
|
||||
and where the setting is on common devices (Synology, ASUSTOR, QNAP, TrueNAS,
|
||||
OpenWrt, UniFi, rsyslog). The address is the plugin's `send_to` setting
|
||||
(Settings → Plugins → Syslog): Steward's web address is often a name only its
|
||||
proxy answers, so it isn't guessed. Both formats are read, BSD (RFC 3164) and
|
||||
IETF (RFC 5424); choose IETF where it is offered, as its lines carry their time
|
||||
zone. ASUSTOR's ADM offers no choice and sends BSD.
|
||||
+16
-3
@@ -14,13 +14,26 @@ On each scrape:
|
||||
|
||||
Request rates and error rates are computed as deltas between the current and previous scrape, divided by elapsed time. Latency percentiles (p50, p95, p99) are approximated via linear interpolation over histogram buckets — these are estimates, not exact percentiles. They cover the responses since the previous scrape (each bucket's rise, summed over every status code and method), not every response since Traefik started. A scrape in which a router answered nothing records no latency, shown as "—"; one past the last bucket (5 s by default) reads as that bucket's edge.
|
||||
|
||||
When the metrics URL can reach more than one Traefik (a swarm service's replicas behind the routing mesh or its VIP, a Kubernetes Service's pods, a keepalived pair after a failover, or the same Traefik after a restart), each process keeps its own counters. Steward tells them apart by `process_start_time_seconds` and compares each scrape only with the same process's previous one. The first scrape from a process it hasn't seen in the last hour sets that process's baseline and counts nothing. When `metrics_url`'s host name resolves to several addresses, Steward scrapes each one and adds the replicas' requests, bytes and latency buckets together, so the figures are the whole proxy's. Each replica still counts only against its own last scrape; one that doesn't answer is left out with a warning in the log. Certificates are listed once however many replicas serve them; Traefik's own figures add open connections and memory and show the newest reload.
|
||||
|
||||
Through a name with one address (a swarm service's VIP, a Kubernetes ClusterIP, a load balancer) you get whichever replica answered, which can be one that serves no traffic at all. Point `metrics_url` at a name that lists every replica instead:
|
||||
|
||||
| Where Traefik runs | `metrics_url` |
|
||||
|---|---|
|
||||
| One container | its address, e.g. `http://traefik:8080/metrics` |
|
||||
| Docker Swarm service (Steward on a network it shares with Traefik) | `http://tasks.<service>:8080/metrics`, e.g. `http://tasks.traefik_router:8080/metrics` |
|
||||
| Kubernetes | a headless Service's name |
|
||||
| A pair behind a keepalived VIP | a name that resolves to both nodes |
|
||||
|
||||
`api_url` can stay on one address: every replica serves the same configuration.
|
||||
|
||||
---
|
||||
|
||||
## Configuration
|
||||
|
||||
| Key | Default | Description |
|
||||
|---|---|---|
|
||||
| `metrics_url` | `http://localhost:8080/metrics` | Traefik Prometheus endpoint |
|
||||
| `metrics_url` | `http://localhost:8080/metrics` | Traefik Prometheus endpoint. A host name with several addresses is scraped address by address and added up (see above) |
|
||||
| `scrape_interval_seconds` | `60` | How often to scrape |
|
||||
|
||||
Enable the plugin by setting `enabled: true` in the app settings (Settings UI or directly in `app_settings` DB table under key `plugin.traefik`).
|
||||
@@ -90,11 +103,11 @@ The full Traefik page at `/plugins/traefik/` reads top to bottom, for the time r
|
||||
- **Slow responses** compare p95 with p50. When p95 is 4× p50 or more, a few requests are slow (one endpoint or a heavy page). When p50 is close behind, the whole app is slow.
|
||||
- **Next:** a fault links to the swarm service behind the router (its tasks and logs) when Steward can match the name ("codex@swarm" → `codex_app`, "radarr@swarm" → `arr_radarr`), otherwise to Docker → Swarm. Traffic links to Settings → Thresholds.
|
||||
4. **Traefik's own figures:** when its config last reloaded, open connections, memory.
|
||||
5. **The healthy routers,** folded into one table, then the routers Traefik no longer reports, then TLS certificates by soonest expiry, then Traffic Origin when the access log is on.
|
||||
5. **The healthy routers,** folded into one table, then the routers Traefik no longer reports, then TLS certificates by soonest expiry, then Traffic Origin when the access log is on. A certificate Traefik has renewed is listed as old, not by its expiry, though a Traefik that hasn't restarted since keeps reporting it: one whose every name a later-expiring certificate covers.
|
||||
|
||||
A router is graded on its last 15 minutes against Settings → Thresholds. When a problem started is read from the router's history over the range.
|
||||
|
||||
Once a router has 5 days of history, its 4xx share and p95 latency are judged against its own normal for that hour (see [Normals and anomalies](../architecture.md)) instead of the fixed cutoffs. One over the cutoff but within its normal is healthy, and the healthy table says it is usual for that router (an error-pages service that answers 4xx all day, a login wall's steady 401s). One out of its normal is a warning that says what is usual, and a metric anomaly to review; the Traefik page lists the routers' anomalies of the last 30 days. How far out counts is set on Settings → Thresholds → Normals (2 points of 4xx share, 50 ms of p95 by default). A 4xx share over fewer requests in the 15 minutes than Settings → Thresholds allows (30 by default) isn't judged at all. The 5xx share is a failure and always keeps its fixed cutoff. Latency is learned only from #5755's per-scrape figures, so its normal arrives 5 days after that release.
|
||||
Once a router has 5 days of history, its 4xx share and p95 latency are judged against its own normal for that hour (see [Normals and anomalies](../architecture.md)) instead of the fixed cutoffs. One over the cutoff but within its normal is healthy, and the healthy table says it is usual for that router (an error-pages service that answers 4xx all day, a login wall's steady 401s). One out of its normal is a warning that says what is usual, and a metric anomaly to review; the Traefik page lists the routers' anomalies of the last 30 days. How far out counts is set on Settings → Thresholds → Normals (2 points of 4xx share, 50 ms of p95 by default). A 4xx or 5xx share over fewer requests in the 15 minutes than Settings → Thresholds allows (30 by default) isn't judged at all: two 500s of sixteen requests would otherwise read 12% and critical. A 5xx share past its cutoff is failing only once the router answered at least 3 server errors in those 15 minutes (Settings → Thresholds, "Fewest server errors to fail"): one 502 among 70 requests is 1.4%, but it is one error. The 5xx share is a failure and keeps its fixed cutoff whatever the router's history. Latency is learned only from #5755's per-scrape figures, so its normal arrives 5 days after that release.
|
||||
|
||||
---
|
||||
|
||||
|
||||
@@ -391,6 +391,25 @@ async def mcp_overview(db) -> list[dict]:
|
||||
- `severity` is `"critical"` (something is down or about to be) or `"warning"` (degraded, or heading that way). Report problems only; a healthy plugin returns `[]`.
|
||||
- It is called only while the plugin is enabled, with its own session. If it raises, the overview still returns, and names the plugin under `unavailable`.
|
||||
|
||||
### What happened on a host
|
||||
|
||||
`get_anomaly` shows, beside a metric anomaly, what else happened on its host around each occurrence. A plugin that records events on a host adds them by exporting an optional `mcp_events(db, host_id, host_name, since, until)` that returns events built with `steward.mcp.tools._events.event`:
|
||||
|
||||
```python
|
||||
# plugins/myplugin/__init__.py
|
||||
async def mcp_events(db, host_id, host_name, since, until) -> list[dict]:
|
||||
from steward.mcp.tools._events import event
|
||||
return [event(r.at, "backup_job", f"Backup {r.name}: {r.state}", until=r.finished_at)
|
||||
for r in await _jobs_on(db, host_id, since, until)]
|
||||
```
|
||||
|
||||
- Return what happened between `since` and `until`, oldest first: something that lasted gives `until`. Bound your query (a few hundred rows); Steward keeps the 40 nearest the occurrence's start and tells the caller how many it left out (`around_left_out`).
|
||||
- It is called only while the plugin is enabled, with its own session. If it raises, the anomaly is still returned without the plugin's events. The host agent (maintenance jobs, reboots) and Docker (container starts, deaths, OOM kills) are the examples to read.
|
||||
|
||||
A resource with no host (a Traefik router, say) has no host to read events by. A plugin that knows what happened to one of its own resources exports `mcp_resource_events(db, source, resource, since, until)` instead, same return shape, and returns `[]` for a source that isn't its own. Traefik's is the example: it gives a router's swarm service's container events, on whichever hosts they ran.
|
||||
|
||||
Core adds, beside every anomaly, the stretches Steward itself wasn't recording (kind `"steward"`: a restart, a deploy, a stall), read from its own once-a-minute health sample; a restart is shown however quick, from the `restart_gap_secs` its new process records. A plugin doesn't need to report those.
|
||||
|
||||
---
|
||||
|
||||
## Shipping a Plugin
|
||||
|
||||
+41
-11
@@ -44,19 +44,32 @@ def setup(app: "Quart") -> None:
|
||||
required_role=UserRole.viewer,
|
||||
)
|
||||
# Each container's CPU (100% is one core) and memory share learn their
|
||||
# normal (#5742), each with its floor from Settings → Thresholds.
|
||||
# normal (#5742), each with its floor from Settings → Thresholds. Memory
|
||||
# is its processes' own, file cache left out (#6030).
|
||||
from steward.core.norms import floor_setting, learn_normal
|
||||
learn_normal("docker", "cpu_pct", floor_setting(app, "container_cpu_pct"))
|
||||
learn_normal("docker", "mem_pct", floor_setting(app, "container_mem_pct"))
|
||||
# A host's agent carries its containers' figures: they go silent with it (#5721).
|
||||
learn_normal("docker", "mem_used_pct", floor_setting(app, "container_mem_pct"))
|
||||
# A host's agent carries its containers' figures: they go silent with it
|
||||
# (#5721). A swarm service's aren't tied to one host.
|
||||
from steward.core.alerts import agent_fed
|
||||
agent_fed("docker", lambda resource: resource.split("/", 1)[0])
|
||||
from .service import SERVICE_RESOURCE
|
||||
agent_fed("docker", lambda resource: None if resource.startswith(SERVICE_RESOURCE)
|
||||
else resource.split("/", 1)[0])
|
||||
# An alert on a swarm figure names the services or nodes it counts (#6400).
|
||||
from steward.core.alerts import names_behind
|
||||
from .swarm_health import NAMERS
|
||||
for metric, names in NAMERS.items():
|
||||
names_behind("docker", metric, names)
|
||||
# Deploys and crash-loops go on the timeline.
|
||||
from .timeline import register as register_timeline
|
||||
register_timeline()
|
||||
|
||||
|
||||
def get_scheduled_tasks() -> list:
|
||||
# Collection is now agent-driven (pushed to the host_agent ingest); the
|
||||
# central socket scrape was removed. No periodic task to register.
|
||||
return []
|
||||
# Collection is agent-driven (pushed to the host_agent ingest). The one
|
||||
# task here moves task-named history to its service.
|
||||
from .rekey import make_rekey_task
|
||||
return [make_rekey_task(_app)]
|
||||
|
||||
|
||||
def get_blueprint():
|
||||
@@ -74,19 +87,36 @@ async def mcp_overview(db) -> list[dict]:
|
||||
return await findings(db)
|
||||
|
||||
|
||||
async def mcp_events(db, host_id: str, host_name: str, since, until) -> list[dict]:
|
||||
from .mcp_tools import mcp_events as events
|
||||
return await events(db, host_id, host_name, since, until)
|
||||
|
||||
|
||||
async def mcp_resource_events(db, source: str, resource: str, since, until) -> list[dict]:
|
||||
from .service import SERVICE_RESOURCE
|
||||
if source != "docker" or not resource.startswith(SERVICE_RESOURCE):
|
||||
return []
|
||||
from .mcp_tools import service_events
|
||||
return await service_events(db, resource[len(SERVICE_RESOURCE):], since, until)
|
||||
|
||||
|
||||
def get_nav() -> list[dict]:
|
||||
# Surfaces in the sidebar's Infrastructure group (fleet-wide container view).
|
||||
return [{"label": "Docker", "href": "/plugins/docker/"}]
|
||||
|
||||
|
||||
def get_alert_metrics() -> dict[str, list[str]]:
|
||||
"""What ingest.py records per container (resource "<host>/<container>"):
|
||||
restart_count is cumulative (alert on crash-looping); is_healthy is 1.0 /
|
||||
0.0 from the container's HEALTHCHECK, only for containers that define one.
|
||||
"""What ingest.py records per container (resource "swarm/<service>" for a
|
||||
swarm task, else "<host>/<container>"): restart_count is cumulative (alert
|
||||
on crash-looping); is_healthy is 1.0 / 0.0 from the container's HEALTHCHECK,
|
||||
only for containers that define one. net_rx_bps / net_tx_bps are the bytes
|
||||
a second it receives and sends, under "<host>/<service or container>"
|
||||
(#6115): "a container flooding the uplink" is net_tx_bps over a level.
|
||||
Per host (resource "<host>"), what Docker keeps on its disk (#5304).
|
||||
Swarm-wide (resource "swarm"), from any manager's report: services short
|
||||
of their replicas, nodes down and managers unreachable, drained nodes
|
||||
aside (#5788, swarm_health.py)."""
|
||||
from .disk_view import DISK_METRICS
|
||||
from .swarm_health import SWARM_METRICS
|
||||
return {"docker": ["cpu_pct", "mem_pct", "restart_count", "is_healthy", *DISK_METRICS, *SWARM_METRICS]}
|
||||
return {"docker": ["cpu_pct", "mem_used_pct", "restart_count", "is_healthy", "net_rx_bps", "net_tx_bps",
|
||||
*DISK_METRICS, *SWARM_METRICS]}
|
||||
|
||||
+79
-17
@@ -30,6 +30,41 @@ def _parse_started_at(value) -> datetime | None:
|
||||
return None
|
||||
|
||||
|
||||
def net_rates(before: dict, snapshots: list) -> list:
|
||||
"""(recorded_at, name, rx_bps, tx_bps) for each running container in each
|
||||
snapshot, from its cumulative network counters against the last ones seen
|
||||
for it: `before` is {name: (at, container_id, rx, tx)} from the stored rows,
|
||||
and each snapshot moves it on. A container new since then, recreated under
|
||||
the same name, or whose counters went back (restarted) has no rate until
|
||||
its next snapshot (#6115)."""
|
||||
last = dict(before)
|
||||
out = []
|
||||
for at, containers in snapshots:
|
||||
for c in containers:
|
||||
name, rx, tx = c.get("name"), c.get("net_rx_bytes"), c.get("net_tx_bytes")
|
||||
if not name or c.get("status") != "running" or rx is None or tx is None:
|
||||
continue
|
||||
cid = c.get("container_id") or ""
|
||||
prev = last.get(name)
|
||||
last[name] = (at, cid, rx, tx)
|
||||
if prev is None or prev[1] != cid or prev[2] is None or prev[3] is None:
|
||||
continue
|
||||
dt = (at - prev[0]).total_seconds()
|
||||
if dt <= 0 or rx < prev[2] or tx < prev[3]:
|
||||
continue
|
||||
out.append((at, name, (rx - prev[2]) / dt, (tx - prev[3]) / dt))
|
||||
return out
|
||||
|
||||
|
||||
def _crash_loop_deaths() -> int:
|
||||
from quart import current_app
|
||||
from .service import CRASH_LOOP_DEATHS, crash_loop_deaths
|
||||
try:
|
||||
return crash_loop_deaths(current_app.config)
|
||||
except RuntimeError: # outside the app (a unit test)
|
||||
return CRASH_LOOP_DEATHS
|
||||
|
||||
|
||||
def _derive_events(old_state: dict, new_containers: list) -> list:
|
||||
"""Diff a fresh snapshot against stored per-container state → lifecycle events.
|
||||
|
||||
@@ -204,6 +239,8 @@ async def _persist_swarm(session, host, swarm: dict) -> None:
|
||||
row.desired = int(s.get("desired") or 0)
|
||||
row.running = int(s.get("running") or 0)
|
||||
row.image = s.get("image")
|
||||
digest = s.get("image_digest")
|
||||
row.image_digest = digest[:80] if isinstance(digest, str) else None
|
||||
row.placement_json = json.dumps(s.get("placement") or [])
|
||||
row.tasks_json = json.dumps(s.get("tasks") or [])
|
||||
row.updated_at = now
|
||||
@@ -263,6 +300,9 @@ async def _persist_disk(session, host, disk: dict) -> None:
|
||||
summary.images_active = int(disk.get("images_active") or 0)
|
||||
summary.containers_count = int(disk.get("containers_count") or 0)
|
||||
summary.volumes_count = int(disk.get("volumes_count") or 0)
|
||||
digests = disk.get("digests")
|
||||
summary.digests_json = json.dumps(
|
||||
[d[:512] for d in digests if isinstance(d, str)][:400] if isinstance(digests, list) else [])
|
||||
summary.updated_at = now
|
||||
# The totals as metrics too (#5304): a history of each host's growth, and
|
||||
# something an alert rule can watch. Resource: the host's name.
|
||||
@@ -345,8 +385,9 @@ async def persist_host_docker(session, host, snapshots, swarm=None, disk=None,
|
||||
`snapshots` is a list of (recorded_at: datetime, containers: list[dict]) —
|
||||
one entry per ingested sample carrying docker data (usually one; more when
|
||||
the agent flushes a backlog). Every snapshot's running containers record
|
||||
cpu_pct, mem_pct and mem_usage_bytes into the one metric store, at the
|
||||
snapshot's time; the newest snapshot drives current container state and
|
||||
cpu_pct, mem_used_pct, mem_used_bytes and mem_cache_bytes into the one
|
||||
metric store, at the snapshot's time, and net_rx_bps / net_tx_bps from
|
||||
their counters (net_rates); the newest snapshot drives current container state and
|
||||
lifecycle-event derivation. `swarm` is the newest
|
||||
sample's swarm object (or None off managers) — persisted when present.
|
||||
`disk` is the newest sample's /system/df summary (or None on Docker-less
|
||||
@@ -363,6 +404,7 @@ async def persist_host_docker(session, host, snapshots, swarm=None, disk=None,
|
||||
"""
|
||||
from steward.core.alerts import MetricBatch
|
||||
from .models import DockerContainer, DockerEvent
|
||||
from .service import container_resource, traffic_resource
|
||||
|
||||
async def mark(name: str) -> None:
|
||||
if phases is not None:
|
||||
@@ -391,27 +433,39 @@ async def persist_host_docker(session, host, snapshots, swarm=None, disk=None,
|
||||
latest_at, latest_containers = ordered[-1]
|
||||
|
||||
# Time series for every snapshot (running containers with a CPU read), in
|
||||
# the one metric store (#5752): resource "<host>/<container>", so
|
||||
# containers of the same name on different hosts don't collide. Recorded
|
||||
# with the alert batch below, at each snapshot's own time.
|
||||
# the one metric store: resource "swarm/<service>" for a swarm task, so its
|
||||
# history survives the task being replaced or moved, else
|
||||
# "<host>/<container>", so containers of the same name on different hosts
|
||||
# don't collide. Recorded with the alert batch below, at each snapshot's
|
||||
# own time.
|
||||
# Snapshot of stored per-container state BEFORE the upsert overwrites it —
|
||||
# the network counters each rate counts from, and the lifecycle-event diff.
|
||||
# Skip event derivation on the host's first snapshot (empty state) so we
|
||||
# don't emit a start per pre-existing container.
|
||||
old_rows = (await session.execute(
|
||||
select(DockerContainer).where(DockerContainer.host_id == host.id)
|
||||
)).scalars().all()
|
||||
|
||||
batch = MetricBatch()
|
||||
for recorded_at, containers in ordered:
|
||||
for c in containers:
|
||||
if c.get("status") != "running" or c.get("cpu_pct") is None or not c.get("name"):
|
||||
continue
|
||||
resource = f"{host.name}/{c['name']}"
|
||||
for metric in ("cpu_pct", "mem_pct", "mem_usage_bytes"):
|
||||
resource = container_resource(host.name, c["name"])
|
||||
for metric in ("cpu_pct", "mem_used_pct", "mem_used_bytes", "mem_cache_bytes"):
|
||||
if c.get(metric) is not None:
|
||||
batch.add(source_module="docker", resource_name=resource,
|
||||
metric_name=metric, value=c[metric], recorded_at=recorded_at)
|
||||
# Bytes a second each container receives and sends, so a host's traffic
|
||||
# can be put down to the container behind it (#6115).
|
||||
before = {r.name: (r.scraped_at, r.container_id, r.net_rx_bytes, r.net_tx_bytes) for r in old_rows}
|
||||
for recorded_at, name, rx_bps, tx_bps in net_rates(before, ordered):
|
||||
resource = traffic_resource(host.name, name)
|
||||
batch.add(source_module="docker", resource_name=resource,
|
||||
metric_name="net_rx_bps", value=round(rx_bps, 1), recorded_at=recorded_at)
|
||||
batch.add(source_module="docker", resource_name=resource,
|
||||
metric_name="net_tx_bps", value=round(tx_bps, 1), recorded_at=recorded_at)
|
||||
await mark("metrics")
|
||||
|
||||
# Snapshot of stored per-container state BEFORE the upsert overwrites it —
|
||||
# used to diff lifecycle events. Skip event derivation on the host's first
|
||||
# snapshot (empty state) so we don't emit a start per pre-existing container.
|
||||
old_rows = (await session.execute(
|
||||
select(DockerContainer).where(DockerContainer.host_id == host.id)
|
||||
)).scalars().all()
|
||||
old_state = {
|
||||
r.name: {"status": r.status, "health": r.health,
|
||||
"oom_killed": r.oom_killed, "exit_code": r.exit_code,
|
||||
@@ -423,12 +477,19 @@ async def persist_host_docker(session, host, snapshots, swarm=None, disk=None,
|
||||
# the sample that noticed it was taken.
|
||||
finished = {c.get("name"): _parse_started_at(c.get("finished_at"))
|
||||
for c in latest_containers}
|
||||
derived = []
|
||||
for name, event, detail in _derive_events(old_state, latest_containers):
|
||||
at = finished.get(name) if event in ("die", "stop") else None
|
||||
session.add(DockerEvent(
|
||||
host_id=host.id, container_name=name,
|
||||
event=event, detail=detail, at=at or latest_at,
|
||||
))
|
||||
derived.append((name, event, detail, at or latest_at))
|
||||
# Deploys and crash-loops go on the timeline, judged against the
|
||||
# containers as they were before this snapshot.
|
||||
from . import timeline
|
||||
await timeline.from_snapshot(session, host, old_rows, latest_containers, derived, latest_at,
|
||||
_crash_loop_deaths())
|
||||
await mark("events")
|
||||
|
||||
# Current state, and the restart and health alerts, from the newest snapshot only.
|
||||
@@ -444,9 +505,10 @@ async def persist_host_docker(session, host, snapshots, swarm=None, disk=None,
|
||||
existing.image = c.get("image", "") or ""
|
||||
existing.status = c.get("status", "unknown") or "unknown"
|
||||
existing.cpu_pct = c.get("cpu_pct")
|
||||
existing.mem_usage_bytes = c.get("mem_usage_bytes")
|
||||
existing.mem_used_bytes = c.get("mem_used_bytes")
|
||||
existing.mem_limit_bytes = c.get("mem_limit_bytes")
|
||||
existing.mem_pct = c.get("mem_pct")
|
||||
existing.mem_used_pct = c.get("mem_used_pct")
|
||||
existing.mem_cache_bytes = c.get("mem_cache_bytes")
|
||||
existing.ports_json = json.dumps(c.get("ports") or [])
|
||||
existing.started_at = _parse_started_at(c.get("started_at"))
|
||||
existing.scraped_at = latest_at
|
||||
@@ -465,7 +527,7 @@ async def persist_host_docker(session, host, snapshots, swarm=None, disk=None,
|
||||
existing.blk_read_bytes = c.get("blk_read_bytes")
|
||||
existing.blk_write_bytes = c.get("blk_write_bytes")
|
||||
|
||||
resource = f"{host.name}/{name}"
|
||||
resource = container_resource(host.name, name)
|
||||
# Restart count is alertable regardless of state (crash-looping matters
|
||||
# most while the container is down/restarting).
|
||||
batch.add(
|
||||
|
||||
+125
-34
@@ -12,12 +12,13 @@ from datetime import datetime, timedelta
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from steward.mcp.tools.tickets import open_tickets_for
|
||||
from steward.ansible.runner import trigger_run
|
||||
from steward.ansible.sources import BUILTIN_SOURCE_NAME
|
||||
from steward.mcp._context import current_caller, mcp_app
|
||||
from steward.mcp.tools._audit import audit_mcp
|
||||
from steward.mcp.tools._shape import (
|
||||
age_s, bounded, clamp_limit, db_session, iso, lookback, now_utc, pick, rnd, summarize,
|
||||
age_s, bounded, clamp_limit, cut_middle, db_session, iso, lookback, now_utc, pick, rnd, summarize,
|
||||
)
|
||||
from steward.mcp.tools.overview import finding
|
||||
from steward.models.ansible_inventory import AnsibleTarget
|
||||
@@ -27,23 +28,14 @@ from steward.models.users import UserRole
|
||||
from . import service as docker_svc
|
||||
from .service import PROBLEM_SAYS, PROBLEM_SEVERITY, PROBLEMS, container_problems, problem_since
|
||||
from .dedup import dedup_by_container_id
|
||||
from .models import DockerContainer, DockerDiskUsage, DockerSwarmNode, DockerSwarmService
|
||||
from .models import DockerContainer, DockerDiskUsage, DockerEvent, DockerSwarmNode, DockerSwarmService
|
||||
from .swarm_view import build_swarm_services, replaced_tasks, task_time
|
||||
|
||||
CRASH_LOOP_DEATHS = docker_svc.CRASH_LOOP_DEATHS
|
||||
LOG_LINE_CHARS = 2000
|
||||
|
||||
|
||||
# ── pure helpers ─────────────────────────────────────────────────────────────
|
||||
|
||||
def cut_middle(text: str, limit: int = LOG_LINE_CHARS) -> str:
|
||||
"""Keep both ends of an over-long line and say how much of the middle went."""
|
||||
if text is None or len(text) <= limit:
|
||||
return text
|
||||
keep = limit // 2
|
||||
return f"{text[:keep]} [… {len(text) - 2 * keep} characters omitted …] {text[-keep:]}"
|
||||
|
||||
|
||||
def container_row(c, host_names: dict, problems: list[str], now: datetime,
|
||||
replaced: bool = False, since: datetime | None = None) -> dict:
|
||||
running = (c.status or "").lower() == "running"
|
||||
@@ -62,8 +54,8 @@ def container_row(c, host_names: dict, problems: list[str], now: datetime,
|
||||
"oom_killed": bool(c.oom_killed),
|
||||
"restart_count": c.restart_count,
|
||||
"cpu_pct": rnd(c.cpu_pct),
|
||||
"mem_pct": rnd(c.mem_pct),
|
||||
"mem_usage_bytes": c.mem_usage_bytes,
|
||||
"mem_used_pct": rnd(c.mem_used_pct),
|
||||
"mem_used_bytes": c.mem_used_bytes,
|
||||
"mem_limit_bytes": c.mem_limit_bytes,
|
||||
"started_at": iso(c.started_at),
|
||||
"uptime_s": age_s(c.started_at, now) if running and c.started_at else None,
|
||||
@@ -200,12 +192,63 @@ async def _swarm(db, now: datetime):
|
||||
return built["services"], nodes, host_names
|
||||
|
||||
|
||||
def unique_nodes(nodes: list) -> list:
|
||||
"""Each swarm node once: every manager reports them all, so keep the
|
||||
newest report of each."""
|
||||
seen, out = set(), []
|
||||
for n in sorted(nodes, key=lambda n: n.updated_at, reverse=True):
|
||||
if n.node_id not in seen:
|
||||
seen.add(n.node_id)
|
||||
out.append(n)
|
||||
return out
|
||||
|
||||
|
||||
async def _maintaining(db) -> dict[str, str]:
|
||||
"""{host name, lower case: job state} for hosts with a maintenance job
|
||||
running (#5835): a node drained or rebooting for one is expected. The
|
||||
host agent is always loaded; None-safe all the same."""
|
||||
from steward.core.plugin_manager import loaded_plugin_submodule
|
||||
models = loaded_plugin_submodule("host_agent", "models")
|
||||
maint = loaded_plugin_submodule("host_agent", "maintenance")
|
||||
if models is None or maint is None:
|
||||
return {}
|
||||
job = models.HostMaintenanceJob
|
||||
rows = await db.execute(select(Host.name, job.state).join(Host, Host.id == job.host_id)
|
||||
.where(job.state.in_(maint.ACTIVE)))
|
||||
return {name.lower(): state for name, state in rows}
|
||||
|
||||
|
||||
NODE_AVAILABILITY_SAYS = {"drain": "drained", "pause": "paused"}
|
||||
|
||||
|
||||
def node_findings(nodes: list, maintaining: dict[str, str]) -> list[dict]:
|
||||
"""Swarm nodes down now (#5835): status not ready. A node whose host has
|
||||
a maintenance job running is rebooting on purpose and isn't named.
|
||||
|
||||
Drained alone is not a finding: the operator keeps a manager drained on
|
||||
purpose (#5777), and a drain a failed maintenance job left behind is that
|
||||
job's finding."""
|
||||
out = []
|
||||
for n in unique_nodes(nodes):
|
||||
name = n.hostname or n.node_id
|
||||
if n.status == "ready" or name.lower() in maintaining:
|
||||
continue
|
||||
drained = NODE_AVAILABILITY_SAYS.get(n.availability)
|
||||
out.append(finding(
|
||||
"critical", "swarm_node_down", name,
|
||||
f"swarm {n.role} {name} is {n.status}" + (f" and {drained}" if drained else ""),
|
||||
ids={"node_id": n.node_id}, next="list_swarm_services()"))
|
||||
return out
|
||||
|
||||
|
||||
async def mcp_overview(db) -> list[dict]:
|
||||
"""get_overview findings: failing containers and under-replicated swarm services."""
|
||||
"""get_overview findings: failing containers, under-replicated swarm
|
||||
services, and swarm nodes that are down."""
|
||||
now = now_utc()
|
||||
rows = await _rows(db, now)
|
||||
services, _, _ = await _swarm(db, now)
|
||||
return container_findings(rows) + service_findings(services)
|
||||
services, nodes, _ = await _swarm(db, now)
|
||||
return (container_findings(rows) + service_findings(services)
|
||||
+ node_findings(nodes, await _maintaining(db)))
|
||||
|
||||
|
||||
# ── tools ────────────────────────────────────────────────────────────────────
|
||||
@@ -337,9 +380,10 @@ async def get_container(container: str, host: str = "", range: str = "24h", even
|
||||
a name also works (swarm task names are long).
|
||||
host: the host's name or id. Needed only when several hosts run a
|
||||
container with this name.
|
||||
range: the window for `cpu_pct_history` and `mem_pct_history` (min, avg,
|
||||
max, p95, last and a ≤60-point series) — "1h", "6h", "24h" (default),
|
||||
"7d" or "30d". `cpu_pct` and `mem_pct` are the latest reported values.
|
||||
range: the window for `cpu_pct_history` and `mem_used_pct_history` (min,
|
||||
avg, max, p95, last and a ≤60-point series) — "1h", "6h", "24h"
|
||||
(default), "7d" or "30d". `cpu_pct` and `mem_used_pct` are the latest
|
||||
reported values.
|
||||
events: how many lifecycle events (start, restart, stop, die, oom, health_change)
|
||||
to return, newest first (default 20, max 100).
|
||||
|
||||
@@ -347,7 +391,14 @@ async def get_container(container: str, host: str = "", range: str = "24h", even
|
||||
still resolves by its exact name, or by a part of it that matches one
|
||||
removed container, while Steward retains its logs or events: the reply
|
||||
has `removed: true`, `last_seen_at`, its history and its events, and no
|
||||
live state. A live container has `removed: false`.
|
||||
live state. A live container has `removed: false`. `open_tickets` are the
|
||||
open tickets about it (list_tickets).
|
||||
|
||||
Memory (`mem_used_bytes`, `mem_used_pct`, of its limit or of the host's
|
||||
RAM when it has none) is what its processes hold: anon + shmem.
|
||||
`mem_cache_bytes` is the file cache charged to it, which the kernel
|
||||
gives back when the host needs the memory, so a large figure there is
|
||||
not memory the container needs.
|
||||
"""
|
||||
since, key = lookback(range)
|
||||
events = clamp_limit(events, 20, 100)
|
||||
@@ -361,9 +412,11 @@ async def get_container(container: str, host: str = "", range: str = "24h", even
|
||||
db, now - timedelta(hours=24))).get((c.host_id, c.name), [])
|
||||
host_names = await _host_names(db)
|
||||
cpu = await docker_svc.container_points(db, c.host_id, c.name, "cpu_pct", since)
|
||||
mem = await docker_svc.container_points(db, c.host_id, c.name, "mem_pct", since)
|
||||
mem = await docker_svc.container_points(db, c.host_id, c.name, "mem_used_pct", since)
|
||||
evs = await docker_svc.container_events(db, c.host_id, c.name, events)
|
||||
sick = await docker_svc.unhealthy_since(db, [(c.host_id, c.name)])
|
||||
tickets = await open_tickets_for(
|
||||
db, subject=docker_svc.container_resource(host_names.get(c.host_id, c.host_id), c.name))
|
||||
hour_ago = now - timedelta(hours=1)
|
||||
recent = sum(1 for e in failures if e.at >= hour_ago)
|
||||
try:
|
||||
@@ -379,10 +432,12 @@ async def get_container(container: str, host: str = "", range: str = "24h", even
|
||||
"ports": ports,
|
||||
"net_rx_bytes": c.net_rx_bytes, "net_tx_bytes": c.net_tx_bytes,
|
||||
"blk_read_bytes": c.blk_read_bytes, "blk_write_bytes": c.blk_write_bytes,
|
||||
"mem_cache_bytes": c.mem_cache_bytes,
|
||||
"range": key,
|
||||
"cpu_pct_history": summarize(cpu),
|
||||
"mem_pct_history": summarize(mem),
|
||||
"mem_used_pct_history": summarize(mem),
|
||||
"events": _event_rows(evs, now),
|
||||
"open_tickets": tickets,
|
||||
"next": f'search_container_logs(container="{c.name}", host="{c.host_id}")',
|
||||
}
|
||||
|
||||
@@ -397,7 +452,7 @@ async def _removed_container(db, c: RemovedContainer, since, key: str, events: i
|
||||
"""get_container for a container Docker has removed: what Steward kept."""
|
||||
host_names = await _host_names(db)
|
||||
cpu = await docker_svc.container_points(db, c.host_id, c.name, "cpu_pct", since)
|
||||
mem = await docker_svc.container_points(db, c.host_id, c.name, "mem_pct", since)
|
||||
mem = await docker_svc.container_points(db, c.host_id, c.name, "mem_used_pct", since)
|
||||
evs = await docker_svc.container_events(db, c.host_id, c.name, events)
|
||||
return {
|
||||
"container_name": c.name, "host_id": c.host_id, "host_name": host_names.get(c.host_id),
|
||||
@@ -405,7 +460,7 @@ async def _removed_container(db, c: RemovedContainer, since, key: str, events: i
|
||||
"last_seen_at": iso(c.last_seen), "last_seen_age_s": age_s(c.last_seen, now),
|
||||
"range": key,
|
||||
"cpu_pct_history": summarize(cpu),
|
||||
"mem_pct_history": summarize(mem),
|
||||
"mem_used_pct_history": summarize(mem),
|
||||
"events": _event_rows(evs, now),
|
||||
"next": f'search_container_logs(container="{c.name}", host="{c.host_id}", range="24h")',
|
||||
}
|
||||
@@ -438,21 +493,25 @@ async def list_swarm_services(limit: int = 100) -> dict:
|
||||
Swarm keeps few old tasks, so a long outage reads as a lower bound.
|
||||
|
||||
Services with a problem come first. `nodes` lists every swarm node once,
|
||||
with its role (manager/worker), availability and status.
|
||||
with its role (manager/worker, `leader`), availability (active, drain,
|
||||
pause) and status (ready, down, unknown); `host_id` is the Steward host
|
||||
of that name (get_host, get_maintenance_job), and `maintenance` the state
|
||||
of a maintenance job running on it, which drains and reboots it on
|
||||
purpose (null when none).
|
||||
limit: default 100, max 500.
|
||||
"""
|
||||
limit = clamp_limit(limit, 100, 500)
|
||||
now = now_utc()
|
||||
async with db_session() as db:
|
||||
services, nodes, host_names = await _swarm(db, now)
|
||||
seen, node_rows = set(), []
|
||||
for n in sorted(nodes, key=lambda n: n.updated_at, reverse=True):
|
||||
if n.node_id in seen:
|
||||
continue
|
||||
seen.add(n.node_id)
|
||||
node_rows.append({"node_id": n.node_id, "hostname": n.hostname, "role": n.role,
|
||||
"leader": n.leader, "availability": n.availability, "status": n.status,
|
||||
"reported_by": host_names.get(n.host_id)})
|
||||
maintaining = await _maintaining(db)
|
||||
host_ids = {name.lower(): hid for hid, name in host_names.items()}
|
||||
node_rows = [{"node_id": n.node_id, "hostname": n.hostname, "role": n.role,
|
||||
"leader": n.leader, "availability": n.availability, "status": n.status,
|
||||
"host_id": host_ids.get((n.hostname or "").lower()),
|
||||
"maintenance": maintaining.get((n.hostname or "").lower()),
|
||||
"reported_by": host_names.get(n.host_id)}
|
||||
for n in unique_nodes(nodes)]
|
||||
node_rows.sort(key=lambda n: n["hostname"].lower())
|
||||
order = {"down": 0, "degraded": 1, "healthy": 2}
|
||||
|
||||
@@ -481,7 +540,7 @@ async def list_swarm_services(limit: int = 100) -> dict:
|
||||
{"ghost": True, "host": r["host"], "count": r["count"]} if r["ghost"] else
|
||||
{"ghost": False, "host": r["host"], "host_id": r["host_id"], "container_name": r["name"],
|
||||
"status": r["status"], "health": r["health"], "restart_count": r["restart_count"],
|
||||
"cpu_pct": rnd(r["cpu_pct"]), "mem_pct": rnd(r["mem_pct"])}
|
||||
"cpu_pct": rnd(r["cpu_pct"]), "mem_used_pct": rnd(r["mem_pct"])}
|
||||
for r in s["replicas"]
|
||||
],
|
||||
}
|
||||
@@ -696,6 +755,38 @@ async def prune_docker(host: str, what: str, check: bool = True) -> dict:
|
||||
"next": f'wait_for_run(run_id="{run.id}")'}
|
||||
|
||||
|
||||
# Deploys, restarts, deaths and OOM kills are on the timeline (timeline.py),
|
||||
# which get_anomaly reads; these are the container events it doesn't hold.
|
||||
_UNTIMELINED = ("start", "stop", "health_change")
|
||||
|
||||
|
||||
async def mcp_events(db, host_id: str, host_name: str, since, until) -> list[dict]:
|
||||
"""Container events on a host in a window (get_anomaly) that aren't on
|
||||
the timeline: starts, stops and health changes."""
|
||||
from steward.mcp.tools._events import event
|
||||
rows = (await db.execute(select(DockerEvent).where(
|
||||
DockerEvent.host_id == host_id, DockerEvent.event.in_(_UNTIMELINED),
|
||||
DockerEvent.at >= since, DockerEvent.at <= until)
|
||||
.order_by(DockerEvent.at).limit(500))).scalars()
|
||||
return [event(e.at, "container", f"{e.container_name} {e.event}" + (f" ({e.detail})" if e.detail else ""),
|
||||
subject=f"{host_name}/{e.container_name}") for e in rows]
|
||||
|
||||
|
||||
async def service_events(db, service: str, since, until) -> list[dict]:
|
||||
"""What happened to a swarm service's containers on every host in a window
|
||||
(get_anomaly): starts with their image, deaths, OOM kills, health changes.
|
||||
A service has no one host to read events by."""
|
||||
from steward.mcp.tools._events import event
|
||||
from steward.models.hosts import Host
|
||||
rows = (await db.execute(
|
||||
select(DockerEvent, Host.name).join(Host, Host.id == DockerEvent.host_id)
|
||||
.where(DockerEvent.container_name.startswith(f"{service}.", autoescape=True),
|
||||
DockerEvent.at >= since, DockerEvent.at <= until)
|
||||
.order_by(DockerEvent.at).limit(500))).all()
|
||||
return [event(e.at, "container", f"{e.container_name} {e.event}" + (f" ({e.detail})" if e.detail else ""),
|
||||
subject=f"{host}/{e.container_name}") for e, host in rows]
|
||||
|
||||
|
||||
def register_tools(register) -> None:
|
||||
for fn in (list_containers, get_container, list_swarm_services,
|
||||
search_container_logs, get_docker_disk_usage):
|
||||
|
||||
@@ -0,0 +1,36 @@
|
||||
"""A container's memory is its processes' own, with file cache beside it
|
||||
|
||||
Renames docker_containers.mem_usage_bytes / mem_pct to mem_used_bytes /
|
||||
mem_used_pct and adds mem_cache_bytes (#6030). The old figure was Docker's
|
||||
working set (usage less idle file cache), which still counted recently used
|
||||
file cache: a container that reads a lot of files showed hundreds of GB it
|
||||
didn't need. The new figure is anon + shmem, what the processes hold and
|
||||
can't hand back without swap, read by agent 1.23.0. The old values are
|
||||
cleared rather than carried under the new names; each container's next
|
||||
report from an updated agent fills them.
|
||||
|
||||
Revision ID: docker_013_mem_used
|
||||
Revises: docker_012_drop_metrics
|
||||
Create Date: 2026-10-18
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision: str = "docker_013_mem_used"
|
||||
down_revision: Union[str, None] = "docker_012_drop_metrics"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.alter_column("docker_containers", "mem_usage_bytes", new_column_name="mem_used_bytes")
|
||||
op.alter_column("docker_containers", "mem_pct", new_column_name="mem_used_pct")
|
||||
op.add_column("docker_containers", sa.Column("mem_cache_bytes", sa.BigInteger, nullable=True))
|
||||
op.execute("UPDATE docker_containers SET mem_used_bytes = NULL, mem_used_pct = NULL")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("docker_containers", "mem_cache_bytes")
|
||||
op.alter_column("docker_containers", "mem_used_pct", new_column_name="mem_pct")
|
||||
op.alter_column("docker_containers", "mem_used_bytes", new_column_name="mem_usage_bytes")
|
||||
@@ -0,0 +1,30 @@
|
||||
"""Which image a swarm service is pinned to, and which images each host holds
|
||||
|
||||
Adds docker_swarm_services.image_digest (the sha256 digest a stack deploy
|
||||
pinned) and docker_disk_usage.digests_json (every "repo@sha256:…" the host
|
||||
holds), both from agent 1.26.0. A maintenance run spreads services back out
|
||||
only onto a node holding the service's image. Older agents leave them empty.
|
||||
|
||||
Revision ID: docker_014_image_digests
|
||||
Revises: docker_013_mem_used
|
||||
Create Date: 2026-10-25
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision: str = "docker_014_image_digests"
|
||||
down_revision: Union[str, None] = "docker_013_mem_used"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("docker_swarm_services", sa.Column("image_digest", sa.String(80), nullable=True))
|
||||
op.add_column("docker_disk_usage", sa.Column("digests_json", sa.Text, nullable=False,
|
||||
server_default="[]"))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("docker_disk_usage", "digests_json")
|
||||
op.drop_column("docker_swarm_services", "image_digest")
|
||||
@@ -29,10 +29,14 @@ class DockerContainer(Base):
|
||||
# running | stopped | paused | exited | dead
|
||||
cpu_pct: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
# BigInteger: a container's memory usage/limit routinely exceeds 2^31 bytes
|
||||
# (~2.1 GB), which overflows int4 and fails the insert.
|
||||
mem_usage_bytes: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
|
||||
# (~2.1 GB), which overflows int4 and fails the insert. Used is what its
|
||||
# processes hold (anon + shmem); file cache is kept apart, since the kernel
|
||||
# gives it back when the host needs it (#6030). used_pct is of the limit,
|
||||
# which is the host's RAM when none is set.
|
||||
mem_used_bytes: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
|
||||
mem_limit_bytes: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
|
||||
mem_pct: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
mem_used_pct: Mapped[float | None] = mapped_column(Float, nullable=True)
|
||||
mem_cache_bytes: Mapped[int | None] = mapped_column(BigInteger, nullable=True)
|
||||
restart_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
ports_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
|
||||
# JSON: [{"host_port": 8080, "container_port": 80, "protocol": "tcp"}]
|
||||
@@ -155,6 +159,9 @@ class DockerSwarmService(Base):
|
||||
desired: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
running: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
image: Mapped[str | None] = mapped_column(String(512), nullable=True)
|
||||
# The digest a stack deploy pinned ("sha256:…"), agent ≥ 1.26.0; None when
|
||||
# the spec names a tag only.
|
||||
image_digest: Mapped[str | None] = mapped_column(String(80), nullable=True)
|
||||
# task→node placement of running replicas: [{"node_id", "running"}], JSON.
|
||||
# A manager sees every task, so this captures cross-node placement that the
|
||||
# local docker_containers rows (this host only) can't.
|
||||
@@ -192,6 +199,10 @@ class DockerDiskUsage(Base):
|
||||
images_active: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
containers_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
volumes_count: Mapped[int] = mapped_column(Integer, nullable=False, default=0)
|
||||
# Every image the host holds by repository digest, ["repo@sha256:…"], JSON
|
||||
# (agent ≥ 1.26.0): what a swarm service's pinned image is checked against
|
||||
# before a maintenance run moves the service here.
|
||||
digests_json: Mapped[str] = mapped_column(Text, nullable=False, default="[]")
|
||||
updated_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False,
|
||||
default=lambda: datetime.now(timezone.utc),
|
||||
|
||||
@@ -0,0 +1,198 @@
|
||||
# plugins/docker/rekey.py
|
||||
"""Moves history kept under a swarm task's own name, "<host>/<service>.<slot>.
|
||||
<task>", onto its service's key, "swarm/<service>": samples, hourly rollups,
|
||||
anomalies and the alert rules and maintenance windows that name it.
|
||||
|
||||
The raw table holds millions of rows, too many to move in a migration that the
|
||||
app has to wait for. A small task moves what it can in a short pass in the
|
||||
background instead, newest history first, and does nothing once none are left. Network
|
||||
rates stay where they are: they are kept per host, and age out with retention.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
import time
|
||||
from collections import Counter
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import delete, select, text, update
|
||||
|
||||
from steward.core.scheduler import ScheduledTask
|
||||
from steward.models.alerts import AlertRule, MaintenanceWindow
|
||||
from steward.models.metrics import PluginMetric, PluginMetricHourly, PluginMetricLatest
|
||||
from steward.models.norms import MetricAnomaly, MetricAnomalySpan
|
||||
from steward.models.tickets import TicketLink
|
||||
from steward.models.timeline import TimelineEntry
|
||||
from steward.timeline.record import anomaly_changed
|
||||
|
||||
from .service import container_resource, task_service
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from quart import Quart
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
BATCH = 1000 # raw samples moved in one go: each rewrites its row and every index on it
|
||||
EVERY_S = 15
|
||||
PASS_S = 2 # a key with only a few rows takes milliseconds, and there can be many
|
||||
REST = 4 # after a pass, wait this many times as long as it took, so ingest keeps the disk
|
||||
TRAFFIC = ("net_rx_bps", "net_tx_bps")
|
||||
_TASK_KEY = r"^[^/]+/.+\.([0-9]+|[a-z0-9]{25})\.[a-z0-9]{25}$"
|
||||
_NOT_TRAFFIC = "metric_name NOT IN ('net_rx_bps', 'net_tx_bps')"
|
||||
|
||||
# Hours the service has no row for change name; hours it has are combined, as
|
||||
# two tasks of a service can share an hour.
|
||||
_RENAME_HOURS = text(f"""
|
||||
UPDATE plugin_metrics_hourly o SET resource_name = :new
|
||||
WHERE o.source_module = 'docker' AND o.resource_name = :old AND o.{_NOT_TRAFFIC}
|
||||
AND NOT EXISTS (SELECT 1 FROM plugin_metrics_hourly n
|
||||
WHERE n.source_module = 'docker' AND n.resource_name = :new
|
||||
AND n.metric_name = o.metric_name AND n.bucket = o.bucket)
|
||||
""")
|
||||
_COMBINE_HOURS = text("""
|
||||
UPDATE plugin_metrics_hourly n SET
|
||||
value_avg = COALESCE((n.value_avg * n.sample_count + o.value_avg * o.sample_count)
|
||||
/ NULLIF(n.sample_count + o.sample_count, 0), n.value_avg),
|
||||
value_max = GREATEST(n.value_max, o.value_max),
|
||||
value_p95 = GREATEST(n.value_p95, o.value_p95),
|
||||
sample_count = n.sample_count + o.sample_count
|
||||
FROM plugin_metrics_hourly o
|
||||
WHERE o.source_module = 'docker' AND o.resource_name = :old
|
||||
AND n.source_module = 'docker' AND n.resource_name = :new
|
||||
AND n.metric_name = o.metric_name AND n.bucket = o.bucket
|
||||
""")
|
||||
_DROP_HOURS = text(f"""
|
||||
DELETE FROM plugin_metrics_hourly
|
||||
WHERE source_module = 'docker' AND resource_name = :old AND {_NOT_TRAFFIC}
|
||||
""")
|
||||
|
||||
|
||||
def service_key(old: str) -> str:
|
||||
"""The key a task-named resource belongs under now."""
|
||||
return container_resource("", old.split("/", 1)[1])
|
||||
|
||||
|
||||
async def old_keys(session) -> list[str]:
|
||||
"""Every task-named docker resource still holding something to move, to be
|
||||
taken from the end: those with raw samples last, as they are what a chart
|
||||
and a normal read first. The latest-value table stands for the raw samples,
|
||||
as a key stays in it until its samples have aged out."""
|
||||
async def names(column, *where) -> set[str]:
|
||||
found = (await session.execute(select(column).distinct().where(*where, column.op("~")(_TASK_KEY)))).scalars()
|
||||
return {k for k in found if task_service(k.split("/", 1)[1])}
|
||||
|
||||
recent = await names(PluginMetricLatest.resource_name, PluginMetricLatest.source_module == "docker",
|
||||
PluginMetricLatest.metric_name.notin_(TRAFFIC))
|
||||
hourly = await names(PluginMetricHourly.resource_name, PluginMetricHourly.source_module == "docker",
|
||||
PluginMetricHourly.metric_name.notin_(TRAFFIC))
|
||||
named = (await names(MetricAnomaly.resource_name, MetricAnomaly.source_module == "docker")
|
||||
| await names(AlertRule.resource_name, AlertRule.source_module == "docker")
|
||||
| await names(MaintenanceWindow.scope_resource, MaintenanceWindow.scope_source == "docker"))
|
||||
logger.info("Swarm history under task names: %d keys with raw samples, %d with hourly rows, "
|
||||
"%d named by anomalies, rules or windows", len(recent), len(hourly), len(named))
|
||||
by_service = Counter(task_service(k.split("/", 1)[1]) for k in hourly - recent)
|
||||
logger.info("Swarm history under task names, hourly only, most keys first: %s; for example %s",
|
||||
by_service.most_common(10), sorted(hourly - recent)[:3])
|
||||
return sorted(hourly - recent) + sorted((named - hourly) - recent) + sorted(recent)
|
||||
|
||||
|
||||
async def _merge_anomalies(session, new: str) -> None:
|
||||
"""One row per metric still to review, as for any key: the rows waiting on
|
||||
the service become the newest of them, with all their occurrences."""
|
||||
rows = (await session.execute(
|
||||
select(MetricAnomaly).where(
|
||||
MetricAnomaly.source_module == "docker", MetricAnomaly.resource_name == new,
|
||||
MetricAnomaly.review == "to_review")
|
||||
.order_by(MetricAnomaly.last_started_at.desc()))).scalars().all()
|
||||
keep: dict[str, MetricAnomaly] = {}
|
||||
for row in rows:
|
||||
into = keep.setdefault(row.metric_name, row)
|
||||
if into is row:
|
||||
continue
|
||||
await session.execute(update(MetricAnomalySpan).where(
|
||||
MetricAnomalySpan.anomaly_id == row.id).values(anomaly_id=into.id))
|
||||
into.occurrences += row.occurrences
|
||||
into.started_at = min(into.started_at, row.started_at)
|
||||
if row.ended_at is None:
|
||||
into.ended_at = None
|
||||
if row.peak_level > into.peak_level:
|
||||
into.peak_level, into.peak_at = row.peak_level, row.peak_at
|
||||
into.usual_hold, into.usual_peak = row.usual_hold, row.usual_peak
|
||||
linked = (await session.execute(select(TicketLink.ticket_id).where(
|
||||
TicketLink.ref_type == "metric_anomaly", TicketLink.ref_id == into.id))).scalars().all()
|
||||
await session.execute(update(TicketLink).where(
|
||||
TicketLink.ref_type == "metric_anomaly", TicketLink.ref_id == row.id,
|
||||
TicketLink.ticket_id.notin_(linked)).values(ref_id=into.id))
|
||||
await session.execute(delete(TicketLink).where(
|
||||
TicketLink.ref_type == "metric_anomaly", TicketLink.ref_id == row.id))
|
||||
await session.execute(delete(TimelineEntry).where(
|
||||
TimelineEntry.ref_type == "metric_anomaly", TimelineEntry.ref_id == row.id))
|
||||
await session.delete(row)
|
||||
|
||||
|
||||
async def move_key(session, old: str) -> bool:
|
||||
"""Move the next batch of `old`, and the rest of what it holds once its raw
|
||||
samples are done. Returns whether it is finished. Runs inside the caller's
|
||||
transaction."""
|
||||
new = service_key(old)
|
||||
batch = select(PluginMetric.id).where(
|
||||
PluginMetric.source_module == "docker", PluginMetric.resource_name == old,
|
||||
PluginMetric.metric_name.notin_(TRAFFIC)).limit(BATCH)
|
||||
moved = await session.execute(
|
||||
update(PluginMetric).where(PluginMetric.id.in_(batch)).values(resource_name=new)
|
||||
.execution_options(synchronize_session=False))
|
||||
if moved.rowcount >= BATCH:
|
||||
return False
|
||||
keys = {"old": old, "new": new}
|
||||
for statement in (_RENAME_HOURS, _COMBINE_HOURS, _DROP_HOURS):
|
||||
await session.execute(statement, keys)
|
||||
await session.execute(delete(PluginMetricLatest).where(
|
||||
PluginMetricLatest.source_module == "docker", PluginMetricLatest.resource_name == old,
|
||||
PluginMetricLatest.metric_name.notin_(TRAFFIC)))
|
||||
await session.execute(update(AlertRule).where(
|
||||
AlertRule.source_module == "docker", AlertRule.resource_name == old).values(resource_name=new))
|
||||
await session.execute(update(MaintenanceWindow).where(
|
||||
MaintenanceWindow.scope_source == "docker", MaintenanceWindow.scope_resource == old)
|
||||
.values(scope_resource=new))
|
||||
renamed = await session.execute(update(MetricAnomaly).where(
|
||||
MetricAnomaly.source_module == "docker", MetricAnomaly.resource_name == old)
|
||||
.values(resource_name=new).execution_options(synchronize_session=False))
|
||||
if not renamed.rowcount:
|
||||
return True
|
||||
session.expire_all()
|
||||
await _merge_anomalies(session, new)
|
||||
await session.flush()
|
||||
for row in (await session.execute(select(MetricAnomaly).where(
|
||||
MetricAnomaly.source_module == "docker", MetricAnomaly.resource_name == new))).scalars().all():
|
||||
await anomaly_changed(session, row)
|
||||
return True
|
||||
|
||||
|
||||
def make_rekey_task(app: "Quart") -> ScheduledTask:
|
||||
remaining: list[str] | None = None
|
||||
busy = asyncio.Lock()
|
||||
resume_at = 0.0
|
||||
|
||||
async def rekey() -> None:
|
||||
nonlocal remaining, resume_at
|
||||
started = time.monotonic()
|
||||
if remaining == [] or busy.locked() or started < resume_at:
|
||||
return
|
||||
async with busy, app.db_sessionmaker() as session:
|
||||
if remaining is None:
|
||||
async with session.begin():
|
||||
remaining = await old_keys(session)
|
||||
deadline = time.monotonic() + PASS_S
|
||||
while remaining and time.monotonic() < deadline:
|
||||
async with session.begin():
|
||||
finished = await move_key(session, remaining[-1])
|
||||
if not finished: # a full batch of samples is enough for one pass
|
||||
break
|
||||
remaining.pop()
|
||||
if not remaining:
|
||||
logger.info("Swarm history under task names: all moved")
|
||||
now = time.monotonic()
|
||||
resume_at = now + REST * (now - started)
|
||||
|
||||
return ScheduledTask(name="docker_rekey", coro_factory=rekey, interval_seconds=EVERY_S)
|
||||
@@ -482,7 +482,7 @@ async def container_detail(host_id: str, name: str):
|
||||
resource = docker_svc.container_resource(host.name, name) if host is not None else None
|
||||
anomalies = await anom.views(db, await anom.list_anomalies(
|
||||
db, source="docker", resource=resource,
|
||||
since=datetime.now(timezone.utc) - timedelta(days=30), limit=20),
|
||||
since=datetime.now(timezone.utc) - timedelta(days=30), limit=100),
|
||||
links=False) if resource else []
|
||||
|
||||
if c is None:
|
||||
|
||||
+51
-27
@@ -12,6 +12,7 @@ from datetime import datetime, timedelta, timezone
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from steward.core import metric_series
|
||||
from steward.core.like import escape_like
|
||||
from steward.models.hosts import Host
|
||||
from steward.models.metrics import PluginMetric
|
||||
|
||||
@@ -161,9 +162,10 @@ def usage(c, cpus: int | None, mem_total: int | None, cpu_pct: float | None = No
|
||||
|
||||
Docker's CPU% is per core (100% = one core busy), so it is shown as cores
|
||||
and graded as a share of the host's CPUs when the host's core count is
|
||||
known. Docker's memory limit is the host's RAM when none is set, so memory
|
||||
is shown in bytes, against a limit only when one is actually set; mem_pct
|
||||
is then a share of that limit, otherwise of the host's memory. `cpu_pct`
|
||||
known. Memory is what the container's processes hold, file cache left out
|
||||
(#6030). Docker's memory limit is the host's RAM when none is set, so
|
||||
memory is shown in bytes, against a limit only when one is actually set;
|
||||
mem_pct is then a share of that limit, otherwise of the host's memory. `cpu_pct`
|
||||
replaces the container's last sample (an average, say) when given.
|
||||
|
||||
With `thresholds`, cpu_grade and mem_grade are the grades to show: past
|
||||
@@ -178,9 +180,9 @@ def usage(c, cpus: int | None, mem_total: int | None, cpu_pct: float | None = No
|
||||
"cores": None if cpu is None else cpu / 100.0,
|
||||
"cpu_share": None if cpu is None or not cpus else cpu / cpus,
|
||||
"cpus": cpus,
|
||||
"mem_bytes": getattr(c, "mem_usage_bytes", None),
|
||||
"mem_bytes": getattr(c, "mem_used_bytes", None),
|
||||
"mem_limit": limit if limited else None,
|
||||
"mem_pct": getattr(c, "mem_pct", None),
|
||||
"mem_pct": getattr(c, "mem_used_pct", None),
|
||||
"mem_of": "its limit" if limited else ("the host's memory" if mem_total else None),
|
||||
"cpu_grade": None, "cpu_usual": None, "mem_grade": None, "mem_usual": None,
|
||||
}
|
||||
@@ -191,7 +193,7 @@ def usage(c, cpus: int | None, mem_total: int | None, cpu_pct: float | None = No
|
||||
|
||||
# Container figures graded against their own normal (#5742): the metric that
|
||||
# learns it and its floor's setting (norms.floor.*).
|
||||
NORMED = {"cpu": ("cpu_pct", "container_cpu_pct"), "mem": ("mem_pct", "container_mem_pct")}
|
||||
NORMED = {"cpu": ("cpu_pct", "container_cpu_pct"), "mem": ("mem_used_pct", "container_mem_pct")}
|
||||
|
||||
|
||||
def _grade(u: dict, cpu: float | None, thresholds: dict, norms: dict) -> None:
|
||||
@@ -209,7 +211,7 @@ def _grade(u: dict, cpu: float | None, thresholds: dict, norms: dict) -> None:
|
||||
u["cpu_grade"] = grade
|
||||
if u["mem_of"]:
|
||||
u["mem_grade"], u["mem_usual"] = graded(
|
||||
u["mem_pct"], "mem", thresholds, norms.get("mem_pct"),
|
||||
u["mem_pct"], "mem", thresholds, norms.get("mem_used_pct"),
|
||||
floor_of(thresholds, "container_mem_pct"), "%")
|
||||
else:
|
||||
u["mem_grade"] = "dim"
|
||||
@@ -225,7 +227,8 @@ async def container_norms(db, keys, now: datetime | None = None) -> dict:
|
||||
now or datetime.now(timezone.utc))
|
||||
out: dict = {}
|
||||
for (_s, resource, metric), norm in got.items():
|
||||
out.setdefault(resources[resource], {})[metric] = norm
|
||||
for key in resources[resource]:
|
||||
out.setdefault(key, {})[metric] = norm
|
||||
return out
|
||||
|
||||
|
||||
@@ -273,11 +276,6 @@ async def host_map(db, host_ids: set[str]) -> dict[str, Host]:
|
||||
}
|
||||
|
||||
|
||||
def escape_like(text: str) -> str:
|
||||
"""Make `text` match literally inside a LIKE/ILIKE pattern (escape char \\)."""
|
||||
return text.replace("\\", "\\\\").replace("%", "\\%").replace("_", "\\_")
|
||||
|
||||
|
||||
async def list_containers(db, host_id: str | None = None) -> list[DockerContainer]:
|
||||
"""Containers, running first then by name; one host's when host_id is given."""
|
||||
stmt = select(DockerContainer)
|
||||
@@ -318,21 +316,46 @@ async def query_logs(db, host_id: str, name: str, stream: str, query: str,
|
||||
return (await db.execute(stmt)).all()
|
||||
|
||||
|
||||
CONTAINER_SERIES = ("cpu_pct", "mem_pct", "mem_usage_bytes")
|
||||
CONTAINER_SERIES = ("cpu_pct", "mem_used_pct", "mem_used_bytes", "mem_cache_bytes")
|
||||
|
||||
|
||||
# A container's series live in the one metric store (#5752): source "docker",
|
||||
# resource "<host name>/<container name>", recorded at ingest.
|
||||
# A swarm task's container: "<service>.<slot or node id>.<task id>".
|
||||
_TASK = re.compile(r"^(?P<service>.+?)\.(?:\d+|[a-z0-9]{25})\.[a-z0-9]{25}$")
|
||||
SERVICE_RESOURCE = "swarm/"
|
||||
|
||||
|
||||
def task_service(name: str) -> str | None:
|
||||
"""The swarm service a container is a task of, from its name, or None."""
|
||||
m = _TASK.match(name or "")
|
||||
return m["service"] if m else None
|
||||
|
||||
|
||||
# A container's series live in the one metric store: source "docker", recorded
|
||||
# at ingest. A swarm service's are under "swarm/<service>", which stays the same
|
||||
# when a task is replaced or moves host, and which all its tasks share. Any
|
||||
# other container's are under "<host name>/<container name>".
|
||||
def container_resource(host_name: str, name: str) -> str:
|
||||
return f"{host_name}/{name}"
|
||||
service = task_service(name)
|
||||
return f"{SERVICE_RESOURCE}{service}" if service else f"{host_name}/{name}"
|
||||
|
||||
|
||||
async def container_resources(db, keys) -> dict[str, tuple[str, str]]:
|
||||
"""{resource: (host_id, container_name)} for (host_id, container_name)
|
||||
keys whose host still exists."""
|
||||
def traffic_resource(host_name: str, name: str) -> str:
|
||||
"""Where a container's network rates are kept: "<host name>/<service or
|
||||
container>", as they say who on that host is carrying its traffic."""
|
||||
return f"{host_name}/{task_service(name) or name}"
|
||||
|
||||
|
||||
async def container_resources(db, keys) -> dict[str, list[tuple[str, str]]]:
|
||||
"""{resource: [(host_id, container_name), ...]} for (host_id,
|
||||
container_name) keys whose host still exists. A swarm service's tasks share
|
||||
one resource."""
|
||||
keys = set(keys)
|
||||
hosts = await host_map(db, {h for h, _ in keys})
|
||||
return {container_resource(hosts[h].name, n): (h, n) for h, n in keys if h in hosts}
|
||||
out: dict[str, list[tuple[str, str]]] = {}
|
||||
for h, n in keys:
|
||||
if h in hosts:
|
||||
out.setdefault(container_resource(hosts[h].name, n), []).append((h, n))
|
||||
return out
|
||||
|
||||
|
||||
async def container_points(db, host_id: str, name: str, metric: str, since,
|
||||
@@ -379,7 +402,7 @@ async def average_cpu(db, keys, since: datetime) -> dict[tuple[str, str], float]
|
||||
PluginMetric.metric_name == "cpu_pct",
|
||||
PluginMetric.recorded_at >= since)
|
||||
.group_by(PluginMetric.resource_name))).all()
|
||||
return {resources[r]: float(v) for r, v in rows if v is not None}
|
||||
return {key: float(v) for r, v in rows if v is not None for key in resources[r]}
|
||||
|
||||
|
||||
# Busiest Containers bars (#5214): the recent past in BARS equal slices.
|
||||
@@ -397,17 +420,18 @@ def bar_slots(now: datetime, hours: int, bars: int = BARS) -> tuple[list[datetim
|
||||
|
||||
|
||||
async def recent_usage(db, keys, since: datetime, width: int) -> dict:
|
||||
"""{(host_id, container_name): {bucket start: (cpu_pct, mem_usage_bytes)}}
|
||||
"""{(host_id, container_name): {bucket start: (cpu_pct, mem_used_bytes)}}
|
||||
averaged per bucket since `since`, for the given containers, in one query."""
|
||||
resources = await container_resources(db, keys)
|
||||
if not resources:
|
||||
return {}
|
||||
out: dict = {}
|
||||
for resource, at, metric, value in await _samples(
|
||||
db, resources, ("cpu_pct", "mem_usage_bytes"), since, width):
|
||||
cpu, mem = out.setdefault(resources[resource], {}).get(at, (None, None))
|
||||
db, resources, ("cpu_pct", "mem_used_bytes"), since, width):
|
||||
v = None if value is None else float(value)
|
||||
out[resources[resource]][at] = (v, mem) if metric == "cpu_pct" else (cpu, v)
|
||||
for key in resources[resource]:
|
||||
cpu, mem = out.setdefault(key, {}).get(at, (None, None))
|
||||
out[key][at] = (v, mem) if metric == "cpu_pct" else (cpu, v)
|
||||
return out
|
||||
|
||||
|
||||
@@ -595,7 +619,7 @@ async def service_history(db, containers, since: datetime) -> list:
|
||||
return []
|
||||
joined: dict[tuple[str, datetime], list] = {}
|
||||
for resource, at, metric, value in await _samples(
|
||||
db, resources, ("cpu_pct", "mem_usage_bytes"), since):
|
||||
db, resources, ("cpu_pct", "mem_used_bytes"), since):
|
||||
pair = joined.setdefault((resource, at), [None, None])
|
||||
pair[0 if metric == "cpu_pct" else 1] = value
|
||||
rows = [(resource, at, cpu, mem) for (resource, at), (cpu, mem) in
|
||||
|
||||
@@ -31,20 +31,74 @@ RECORD_EVERY = timedelta(seconds=30)
|
||||
_last_recorded: datetime | None = None
|
||||
|
||||
|
||||
def short_services(services: list[dict]) -> list[str]:
|
||||
"""The services swarm_services_short counts, each with how many of its
|
||||
tasks run: "web_app (0 of 2 running)"."""
|
||||
return [f"{s.get('service_name')} ({int(s.get('running') or 0)} of {int(s.get('desired') or 0)} running)"
|
||||
for s in sorted(services, key=lambda s: s.get("service_name") or "")
|
||||
if int(s.get("desired") or 0) > 0 and int(s.get("running") or 0) < int(s.get("desired") or 0)]
|
||||
|
||||
|
||||
def _in_service(nodes: list[dict]) -> list[dict]:
|
||||
return sorted((n for n in nodes if (n.get("availability") or "active") != "drain"),
|
||||
key=lambda n: n.get("hostname") or "")
|
||||
|
||||
|
||||
def down_nodes(nodes: list[dict]) -> list[str]:
|
||||
"""The nodes swarm_nodes_down counts, by hostname, with their status."""
|
||||
return [f"{n.get('hostname') or n.get('node_id')} ({n.get('status') or 'unknown'})"
|
||||
for n in _in_service(nodes) if (n.get("status") or "unknown") != "ready"]
|
||||
|
||||
|
||||
def unreachable_managers(nodes: list[dict]) -> list[str]:
|
||||
"""The managers swarm_managers_unreachable counts, by hostname."""
|
||||
return [n.get("hostname") or n.get("node_id") for n in _in_service(nodes)
|
||||
if n.get("role") == "manager"
|
||||
and (n["reachability"] != "reachable" if n.get("reachability")
|
||||
else (n.get("status") or "unknown") != "ready")]
|
||||
|
||||
|
||||
def figures(swarm: dict) -> dict[str, float]:
|
||||
"""The three figures from one manager's swarm report."""
|
||||
services = swarm.get("services") or []
|
||||
nodes = swarm.get("nodes") or []
|
||||
short = sum(1 for s in services
|
||||
if int(s.get("desired") or 0) > 0 and int(s.get("running") or 0) < int(s.get("desired") or 0))
|
||||
in_service = [n for n in nodes if (n.get("availability") or "active") != "drain"]
|
||||
down = sum(1 for n in in_service if (n.get("status") or "unknown") != "ready")
|
||||
managers = [n for n in in_service if n.get("role") == "manager"]
|
||||
unreachable = sum(1 for n in managers
|
||||
if (n["reachability"] != "reachable" if n.get("reachability")
|
||||
else (n.get("status") or "unknown") != "ready"))
|
||||
return {"swarm_services_short": float(short), "swarm_nodes_down": float(down),
|
||||
"swarm_managers_unreachable": float(unreachable)}
|
||||
return {"swarm_services_short": float(len(short_services(services))),
|
||||
"swarm_nodes_down": float(len(down_nodes(nodes))),
|
||||
"swarm_managers_unreachable": float(len(unreachable_managers(nodes)))}
|
||||
|
||||
|
||||
async def _stored(session) -> tuple[list[dict], list[dict]]:
|
||||
"""The swarm's services and nodes as stored, the newest report of each
|
||||
when more than one manager reported it, in the shape figures() reads.
|
||||
A stored node has no reachability, so its status stands in for it."""
|
||||
from sqlalchemy import select
|
||||
from .mcp_tools import unique_nodes
|
||||
from .models import DockerSwarmNode, DockerSwarmService
|
||||
services: dict[str, DockerSwarmService] = {}
|
||||
for s in (await session.execute(select(DockerSwarmService))).scalars():
|
||||
if s.service_name not in services or s.updated_at > services[s.service_name].updated_at:
|
||||
services[s.service_name] = s
|
||||
nodes = unique_nodes(list((await session.execute(select(DockerSwarmNode))).scalars()))
|
||||
return ([{"service_name": s.service_name, "desired": s.desired, "running": s.running}
|
||||
for s in services.values()],
|
||||
[{"node_id": n.node_id, "hostname": n.hostname, "role": n.role,
|
||||
"availability": n.availability, "status": n.status} for n in nodes])
|
||||
|
||||
|
||||
async def name_short_services(session, resource: str) -> list[str]:
|
||||
return short_services((await _stored(session))[0])
|
||||
|
||||
|
||||
async def name_down_nodes(session, resource: str) -> list[str]:
|
||||
return down_nodes((await _stored(session))[1])
|
||||
|
||||
|
||||
async def name_unreachable_managers(session, resource: str) -> list[str]:
|
||||
return unreachable_managers((await _stored(session))[1])
|
||||
|
||||
|
||||
NAMERS = {"swarm_services_short": name_short_services, "swarm_nodes_down": name_down_nodes,
|
||||
"swarm_managers_unreachable": name_unreachable_managers}
|
||||
|
||||
|
||||
def due(now: datetime) -> bool:
|
||||
|
||||
@@ -36,7 +36,7 @@ def node_cards(nodes, services, containers, *, node_host: dict, host_names: dict
|
||||
"measured": True})
|
||||
row["tasks"] += 1
|
||||
row["cpu_pct"] += c.cpu_pct or 0.0
|
||||
row["mem_bytes"] += c.mem_usage_bytes or 0
|
||||
row["mem_bytes"] += c.mem_used_bytes or 0
|
||||
placed: dict[str, dict[str, int]] = {}
|
||||
for s in services:
|
||||
for p in _placement(s):
|
||||
|
||||
@@ -289,8 +289,8 @@ def build_swarm_services(containers, services, node_hostname: dict, host_name: d
|
||||
"name": c.name,
|
||||
"status": getattr(c, "status", "unknown"),
|
||||
"cpu_pct": getattr(c, "cpu_pct", None),
|
||||
"mem_pct": getattr(c, "mem_pct", None),
|
||||
"mem_bytes": getattr(c, "mem_usage_bytes", None),
|
||||
"mem_pct": getattr(c, "mem_used_pct", None),
|
||||
"mem_bytes": getattr(c, "mem_used_bytes", None),
|
||||
"started_at": getattr(c, "started_at", None),
|
||||
"image": getattr(c, "image", None) or None,
|
||||
"health": getattr(c, "health", None),
|
||||
|
||||
@@ -2,7 +2,8 @@
|
||||
|
||||
Docker counts CPU per core (100% = one core busy), so CPU reads as cores,
|
||||
toned by its share of the host's CPUs when the host's core count is known.
|
||||
Memory reads in bytes, against a limit only when one is actually set;
|
||||
Memory is what its processes hold, file cache left out (#6030), and
|
||||
reads in bytes, against a limit only when one is actually set;
|
||||
mem_pct is then a share of that limit, otherwise of the host's memory.
|
||||
Each is toned by usage()'s grade when it has one: within the container's
|
||||
own normal for the hour reads healthy, and says what is usual (#5742). -#}
|
||||
|
||||
@@ -66,6 +66,8 @@
|
||||
|
||||
{# ── Its CPU or memory out of its normal for the hour, and past anomalies (#5742) #}
|
||||
{% with back=anomaly_back, base_resource=anomaly_resource %}{% include "_anomaly_card.html" %}{% endwith %}
|
||||
{# ── Its open tickets ──────────────────────────────────────────────────────── #}
|
||||
<div hx-get="/tickets/card?subject={{ anomaly_resource|urlencode }}&back={{ anomaly_back|urlencode }}" hx-trigger="load" hx-swap="outerHTML"></div>
|
||||
|
||||
{# ── What it is set up with, and what it moved since it started ─────────── #}
|
||||
<div class="card">
|
||||
@@ -78,6 +80,10 @@
|
||||
{%- if c.exit_code is not none and c.status == 'running' and c.restart_count %} <span class="tone-dim">· last exit {{ c.exit_code }}</span>{% endif %}</dd>
|
||||
{% endif %}
|
||||
<dt>Memory limit</dt><dd>{% if usage.mem_limit %}{{ usage.mem_limit|bytes }}{% else %}<span class="tone-dim">none set</span>{% endif %}</dd>
|
||||
{#- Its memory figure is what its processes hold; the file cache charged to
|
||||
it is shown here only, since the kernel gives it back when the host
|
||||
needs it (#6030). #}
|
||||
<dt>File cache</dt><dd>{% if c.mem_cache_bytes is not none %}{{ c.mem_cache_bytes|bytes }} <span class="tone-dim">files it read or wrote, kept in memory until the host needs it back; not counted in its memory</span>{% else %}<span class="tone-dim">—</span>{% endif %}</dd>
|
||||
{% if ports %}
|
||||
<dt>Ports</dt><dd class="mono">{% for p in ports %}{{ p.host_port }}:{{ p.container_port }}/{{ p.protocol }}{% if not loop.last %}, {% endif %}{% endfor %}</dd>
|
||||
{% endif %}
|
||||
|
||||
@@ -0,0 +1,160 @@
|
||||
# plugins/docker/timeline.py
|
||||
"""What Docker puts on the timeline, judged from each snapshot as it is
|
||||
ingested: a deploy (a container or swarm service running a new image, or a
|
||||
container recreated), and a crash-loop as one entry for the whole episode.
|
||||
A single restart or death is recorded but hidden. As on the Docker pages, a
|
||||
crash loop is Settings → Thresholds' number of deaths within CRASH_WINDOW:
|
||||
the one that reaches it opens a crash-loop entry, which each later one
|
||||
extends until the container has been quiet for CRASH_WINDOW.
|
||||
|
||||
A container belongs to its swarm service when it has one, so a service's
|
||||
tasks, replaced on every deploy and every crash, read as one subject.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import timedelta
|
||||
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from steward.models.timeline import TimelineEntry
|
||||
from steward.timeline import catalog
|
||||
from steward.timeline.record import record
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TYPES = (
|
||||
("docker.deployed", "Deployed", "change", "service", True,
|
||||
"A container or swarm service started on a new image, or a container was recreated."),
|
||||
("docker.crash_loop", "Crash-looping", "observed", "service", True,
|
||||
"A container kept restarting or dying: one entry for the whole episode."),
|
||||
("docker.restarted", "Container restarted or died", "observed", "service", False,
|
||||
"A single restart, death or out-of-memory kill."),
|
||||
)
|
||||
|
||||
CRASH_WINDOW = timedelta(hours=1)
|
||||
_TROUBLE = ("restart", "die", "oom")
|
||||
|
||||
|
||||
def register() -> None:
|
||||
for t in TYPES:
|
||||
catalog.register_type(*t)
|
||||
|
||||
|
||||
def unit(c: dict) -> str:
|
||||
"""What a container is part of: its swarm service, else itself."""
|
||||
return c.get("service_name") or c.get("name")
|
||||
|
||||
|
||||
def short_image(image: str | None) -> str:
|
||||
"""An image as a person reads it: the name and tag, and a few characters
|
||||
of the digest when there is one."""
|
||||
if not image:
|
||||
return "an unknown image"
|
||||
name, _, digest = image.partition("@")
|
||||
name = name.rsplit("/", 1)[-1]
|
||||
if digest:
|
||||
return f"{name} ({digest.split(':', 1)[-1][:12]})"
|
||||
return name
|
||||
|
||||
|
||||
def deploys(old_rows: list, latest: list[dict]) -> list[dict]:
|
||||
"""Each unit whose containers now run an image they didn't, or a
|
||||
container recreated under the same name: {unit, name, image, was,
|
||||
recreated, swarm}. A swarm task landing on a host that ran none of its
|
||||
service before is the scheduler moving it, not a deploy."""
|
||||
images: dict[str, set] = {}
|
||||
ids = {}
|
||||
for r in old_rows:
|
||||
images.setdefault(r.service_name or r.name, set()).add(r.image)
|
||||
ids[r.name] = (r.container_id, r.image)
|
||||
out, seen = [], set()
|
||||
for c in latest:
|
||||
if (c.get("status") or "").lower() != "running" or not c.get("name"):
|
||||
continue
|
||||
key, image = unit(c), c.get("image") or ""
|
||||
if key in seen:
|
||||
continue
|
||||
before = images.get(key)
|
||||
old_id, old_image = ids.get(c["name"], (None, None))
|
||||
if before and image not in before:
|
||||
was = old_image if old_image and old_image != image else sorted(before)[0]
|
||||
out.append({"unit": key, "name": c["name"], "image": image, "was": was,
|
||||
"recreated": False, "swarm": bool(c.get("service_name"))})
|
||||
elif old_id and c.get("container_id") and old_id != c["container_id"] and not c.get("service_name"):
|
||||
out.append({"unit": key, "name": c["name"], "image": image, "was": old_image,
|
||||
"recreated": True, "swarm": False})
|
||||
elif before is None and not c.get("service_name"):
|
||||
out.append({"unit": key, "name": c["name"], "image": image, "was": None,
|
||||
"recreated": False, "swarm": False})
|
||||
else:
|
||||
continue
|
||||
seen.add(key)
|
||||
return out
|
||||
|
||||
|
||||
def _deploy_summary(d: dict, host_name: str) -> str:
|
||||
what = f"{d['unit']} on {host_name}"
|
||||
if d["recreated"]:
|
||||
return f"{what}: recreated on {short_image(d['image'])}"
|
||||
if d["was"] is None:
|
||||
return f"{what}: started on {short_image(d['image'])}"
|
||||
new, old = short_image(d["image"]), short_image(d["was"])
|
||||
if d["image"].split("@")[0] == (d["was"] or "").split("@")[0]:
|
||||
return f"{what}: new build of {new}"
|
||||
return f"{what}: {old} → {new}"
|
||||
|
||||
|
||||
async def _trouble(session, host, key: str, name: str, at, said: str, deaths: int) -> None:
|
||||
"""One restart, death or OOM kill of `key`: extends its crash-loop, opens
|
||||
one when it is the `deaths`-th within CRASH_WINDOW, else a hidden entry."""
|
||||
subject = f"{host.name}/{key}"
|
||||
loop = (await session.execute(select(TimelineEntry).where(
|
||||
TimelineEntry.type == "docker.crash_loop", TimelineEntry.subject == subject,
|
||||
TimelineEntry.until >= at - CRASH_WINDOW).order_by(TimelineEntry.at.desc()).limit(1))
|
||||
).scalar_one_or_none()
|
||||
if loop is not None:
|
||||
count = (loop.detail or {}).get("count", 0) + 1
|
||||
loop.until = max(loop.until, at)
|
||||
loop.detail = {**(loop.detail or {}), "count": count, "last": said}
|
||||
loop.summary = f"{key} on {host.name} crash-looping: {count} restarts or deaths"
|
||||
return
|
||||
recent = (await session.execute(select(func.count(), func.min(TimelineEntry.at)).where(
|
||||
TimelineEntry.type == "docker.restarted", TimelineEntry.subject == subject,
|
||||
TimelineEntry.at >= at - CRASH_WINDOW))).one()
|
||||
url = f"/plugins/docker/container/{host.id}/{name}"
|
||||
if recent[0] + 1 >= deaths:
|
||||
count = recent[0] + 1
|
||||
record(session, type="docker.crash_loop", at=recent[1] or at, until=at,
|
||||
summary=f"{key} on {host.name} crash-looping: {count} restarts or deaths",
|
||||
hosts=[host.name], subject=subject, actor="Docker",
|
||||
detail={"count": count, "last": said, "url": url})
|
||||
return
|
||||
record(session, type="docker.restarted", at=at, summary=f"{key} on {host.name}: {said}",
|
||||
hosts=[host.name], subject=subject, actor="Docker", detail={"url": url})
|
||||
|
||||
|
||||
_SAID = {"restart": "restarted", "die": "died", "oom": "killed, out of memory"}
|
||||
|
||||
|
||||
async def from_snapshot(session, host, old_rows: list, latest: list[dict], events: list, at,
|
||||
deaths: int) -> None:
|
||||
"""The entries one snapshot makes: its deploys, and its restarts and
|
||||
deaths (`events`: (name, event, detail, when)), in a savepoint so a
|
||||
failure here never loses the snapshot. `deaths` makes a crash loop."""
|
||||
try:
|
||||
async with session.begin_nested():
|
||||
for d in deploys(old_rows, latest):
|
||||
url = "/plugins/docker/swarm" if d["swarm"] else f"/plugins/docker/container/{host.id}/{d['name']}"
|
||||
record(session, type="docker.deployed", at=at, summary=_deploy_summary(d, host.name),
|
||||
hosts=[host.name], subject=f"{host.name}/{d['unit']}", actor="Docker",
|
||||
detail={"image": d["image"], "was": d["was"], "url": url})
|
||||
units = {c.get("name"): unit(c) for c in latest if c.get("name")}
|
||||
units.update({r.name: r.service_name or r.name for r in old_rows if r.name not in units})
|
||||
for name, event, detail, when in events:
|
||||
if event in _TROUBLE:
|
||||
said = _SAID[event] + (f" ({detail})" if detail else "")
|
||||
await _trouble(session, host, units.get(name, name), name, when or at, said, deaths)
|
||||
await session.flush()
|
||||
except Exception:
|
||||
logger.exception("Docker on %s: timeline entries could not be written", host.name)
|
||||
@@ -0,0 +1,46 @@
|
||||
# plugins/homeassistant/__init__.py
|
||||
from __future__ import annotations
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from quart import Quart
|
||||
|
||||
_app: "Quart | None" = None
|
||||
|
||||
|
||||
def setup(app: "Quart") -> None:
|
||||
global _app
|
||||
_app = app
|
||||
from .models import HomeAssistantConnection, HomeAssistantSchedule, HomeAssistantUpdate # noqa: F401 — registers the tables
|
||||
from .timeline import register
|
||||
register()
|
||||
|
||||
|
||||
def get_scheduled_tasks() -> list:
|
||||
from .scheduler import make_tick_task
|
||||
return [make_tick_task(_app)]
|
||||
|
||||
|
||||
def get_blueprint():
|
||||
from .routes import homeassistant_bp
|
||||
return homeassistant_bp
|
||||
|
||||
|
||||
def get_nav() -> list[dict]:
|
||||
return [{"label": "Home Assistant", "href": "/plugins/homeassistant/"}]
|
||||
|
||||
|
||||
def get_alert_metrics() -> dict[str, list[str]]:
|
||||
"""What the poll records, all under the resource "homeassistant"."""
|
||||
return {"homeassistant": ["is_up", "backup_age_hours", "updates_waiting", "problems_open", "disk_free_pct",
|
||||
"update_failed"]}
|
||||
|
||||
|
||||
def register_mcp_tools(register) -> None:
|
||||
from .mcp_tools import register_tools
|
||||
register_tools(register)
|
||||
|
||||
|
||||
async def mcp_overview(db) -> list[dict]:
|
||||
from .mcp_tools import mcp_overview as findings
|
||||
return await findings(db)
|
||||
@@ -0,0 +1,292 @@
|
||||
# plugins/homeassistant/client.py
|
||||
"""Talking to Home Assistant, with what its own sign-in gave Steward: a refresh
|
||||
token kept in the connection, and access tokens made from it that last half an
|
||||
hour. Repairs and the Supervisor's reports are only offered on its websocket. Home Assistant bans an address after a few refused requests, so nothing is
|
||||
sent without a token and a refusal stops the asking. Every failure comes back as
|
||||
one sentence a page can show."""
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import json
|
||||
import ssl
|
||||
import time
|
||||
from contextlib import asynccontextmanager
|
||||
from urllib.parse import urlencode
|
||||
|
||||
import httpx
|
||||
from websockets.asyncio.client import connect as ws_connect
|
||||
from websockets.exceptions import WebSocketException
|
||||
|
||||
from steward.core.crypto import decrypt_secret
|
||||
|
||||
TIMEOUT_SECONDS = 15.0
|
||||
# Home Assistant answers an action when it has finished, minutes later for a
|
||||
# backup or an update, and carries on if the request ends. So its answer is only
|
||||
# waited for this long, and the outcome is read from its entities.
|
||||
ACTION_READ_SECONDS = 10.0
|
||||
MAX_BYTES = 16 * 1024 * 1024
|
||||
# An access token this close to running out isn't used for another request.
|
||||
EXPIRY_MARGIN_SECONDS = 60
|
||||
# One read of the system over the websocket, however its answers dribble in.
|
||||
SYSTEM_READ_SECONDS = 30
|
||||
|
||||
_access: dict[str, tuple[str, float]] = {} # refresh token -> access token, when to stop using it
|
||||
|
||||
|
||||
class Unreachable(Exception):
|
||||
"""Home Assistant didn't answer usefully; it may be restarting."""
|
||||
|
||||
|
||||
class Refused(Exception):
|
||||
"""Home Assistant refused Steward's sign-in, or has banned this address."""
|
||||
|
||||
|
||||
class Rejected(Exception):
|
||||
"""Home Assistant understood an action and wouldn't do it."""
|
||||
|
||||
|
||||
def _refusal(status: int) -> Refused | None:
|
||||
if status == 401:
|
||||
_access.clear()
|
||||
return Refused("Home Assistant refused Steward's sign-in. Sign in again, as a user who may do this.")
|
||||
if status == 403:
|
||||
return Refused("Home Assistant answered 403: it may have banned Steward's address "
|
||||
"after refused requests. Look in its ip_bans.yaml.")
|
||||
return None
|
||||
|
||||
|
||||
async def _request(method: str, url: str, path: str, verify_tls: bool, transport, *, token: str | None = None,
|
||||
read_timeout: float = TIMEOUT_SECONDS, **kwargs) -> tuple[int, bytes]:
|
||||
headers = {"Authorization": f"Bearer {token}"} if token else {}
|
||||
timeout = httpx.Timeout(TIMEOUT_SECONDS, read=read_timeout)
|
||||
try:
|
||||
# A slow drip of bytes can keep each read inside its own timeout for ever.
|
||||
async with asyncio.timeout(TIMEOUT_SECONDS + read_timeout):
|
||||
async with httpx.AsyncClient(timeout=timeout, verify=verify_tls, transport=transport,
|
||||
follow_redirects=False) as client:
|
||||
async with client.stream(method, url.rstrip("/") + path, headers=headers, **kwargs) as response:
|
||||
body = bytearray()
|
||||
async for chunk in response.aiter_bytes():
|
||||
body.extend(chunk)
|
||||
if len(body) > MAX_BYTES:
|
||||
raise Unreachable("Home Assistant's answer was too large to read.")
|
||||
return response.status_code, bytes(body)
|
||||
except TimeoutError:
|
||||
raise httpx.ReadTimeout("no complete answer in time") from None
|
||||
|
||||
|
||||
def _unreachable(exc: httpx.HTTPError) -> Unreachable:
|
||||
if isinstance(exc, httpx.TimeoutException):
|
||||
return Unreachable(f"Home Assistant didn't answer within {TIMEOUT_SECONDS:.0f} s.")
|
||||
return Unreachable(f"Couldn't reach Home Assistant: {exc}")
|
||||
|
||||
|
||||
# ── Signing in ───────────────────────────────────────────────────────────────
|
||||
|
||||
def sign_in_url(url: str, client_id: str, redirect_uri: str, state: str) -> str:
|
||||
"""Home Assistant's own sign-in page, which sends the browser back to
|
||||
`redirect_uri`. It accepts `client_id` as it is because the two share an
|
||||
address, so it needn't be able to reach Steward."""
|
||||
return f"{url.rstrip('/')}/auth/authorize?" + urlencode(
|
||||
{"response_type": "code", "client_id": client_id, "redirect_uri": redirect_uri, "state": state})
|
||||
|
||||
|
||||
async def _tokens(url: str, form: dict, verify_tls: bool, transport) -> dict:
|
||||
try:
|
||||
status, body = await _request("POST", url, "/auth/token", verify_tls, transport, data=form)
|
||||
except httpx.HTTPError as exc:
|
||||
raise _unreachable(exc) from None
|
||||
if status in (400, 401, 403):
|
||||
raise Refused("Home Assistant no longer accepts Steward's sign-in. Sign in again.")
|
||||
if status != 200:
|
||||
raise Unreachable(f"Home Assistant answered {status}.")
|
||||
try:
|
||||
found = json.loads(body)
|
||||
found["access_token"], int(found["expires_in"])
|
||||
except (ValueError, KeyError, TypeError):
|
||||
raise Unreachable("Home Assistant's answer wasn't a sign-in.") from None
|
||||
return found
|
||||
|
||||
|
||||
def _remember(refresh_token: str, found: dict) -> str:
|
||||
until = time.monotonic() + int(found["expires_in"]) - EXPIRY_MARGIN_SECONDS
|
||||
_access[refresh_token] = (found["access_token"], until)
|
||||
return found["access_token"]
|
||||
|
||||
|
||||
async def redeem_code(url: str, client_id: str, code: str, verify_tls: bool, transport=None) -> tuple[str, str]:
|
||||
"""(refresh token, access token) for the code the sign-in page sent back."""
|
||||
found = await _tokens(url, {"grant_type": "authorization_code", "client_id": client_id, "code": code},
|
||||
verify_tls, transport)
|
||||
refresh_token = found.get("refresh_token")
|
||||
if not refresh_token:
|
||||
raise Unreachable("Home Assistant's answer wasn't a sign-in.")
|
||||
return refresh_token, _remember(refresh_token, found)
|
||||
|
||||
|
||||
async def access_token(connection, transport=None) -> str:
|
||||
refresh_token = decrypt_secret(connection.refresh_token, context="Home Assistant sign-in")
|
||||
token, until = _access.get(refresh_token, (None, 0.0))
|
||||
if token and time.monotonic() < until:
|
||||
return token
|
||||
found = await _tokens(connection.url, {"grant_type": "refresh_token", "client_id": connection.client_id,
|
||||
"refresh_token": refresh_token}, connection.verify_tls, transport)
|
||||
return _remember(refresh_token, found)
|
||||
|
||||
|
||||
async def is_admin(url: str, token: str, verify_tls: bool, transport=None) -> bool:
|
||||
"""Whether the signed-in user is an administrator, which its API only says by
|
||||
refusing someone who isn't. So this is asked once, right after signing in, and
|
||||
a refusal here counts once toward a ban."""
|
||||
try:
|
||||
status, _ = await _request("POST", url, "/api/template", verify_tls, transport, token=token,
|
||||
json={"template": "1"})
|
||||
except httpx.HTTPError as exc:
|
||||
raise _unreachable(exc) from None
|
||||
if status == 401:
|
||||
return False
|
||||
if status != 200:
|
||||
raise (_refusal(status) or Unreachable(f"Home Assistant answered {status}."))
|
||||
return True
|
||||
|
||||
|
||||
async def revoke(connection, transport=None) -> None:
|
||||
"""End this sign-in on Home Assistant. It answers 200 whether or not it knew it."""
|
||||
refresh_token = decrypt_secret(connection.refresh_token, context="Home Assistant sign-in")
|
||||
_access.pop(refresh_token, None)
|
||||
try:
|
||||
status, _ = await _request("POST", connection.url, "/auth/revoke", connection.verify_tls, transport,
|
||||
data={"token": refresh_token})
|
||||
except httpx.HTTPError as exc:
|
||||
raise _unreachable(exc) from None
|
||||
if status != 200:
|
||||
raise Unreachable(f"Home Assistant answered {status}.")
|
||||
|
||||
|
||||
# ── Reading and acting ───────────────────────────────────────────────────────
|
||||
|
||||
async def _get(url: str, path: str, token: str, verify_tls: bool, transport) -> list | dict | None:
|
||||
"""The parsed JSON of a GET, or None for a 404."""
|
||||
try:
|
||||
status, body = await _request("GET", url, path, verify_tls, transport, token=token)
|
||||
except httpx.HTTPError as exc:
|
||||
raise _unreachable(exc) from None
|
||||
if refusal := _refusal(status):
|
||||
raise refusal
|
||||
if status == 404:
|
||||
return None
|
||||
if status != 200:
|
||||
raise Unreachable(f"Home Assistant answered {status}.")
|
||||
try:
|
||||
return json.loads(body)
|
||||
except ValueError:
|
||||
raise Unreachable("Home Assistant's answer wasn't JSON.") from None
|
||||
|
||||
|
||||
async def read_states(url: str, token: str, verify_tls: bool, transport=None) -> list[dict]:
|
||||
states = await _get(url, "/api/states", token, verify_tls, transport)
|
||||
if not isinstance(states, list):
|
||||
raise Unreachable("Home Assistant's answer wasn't a list of entities.")
|
||||
return states
|
||||
|
||||
|
||||
async def read_state(url: str, entity_id: str, token: str, verify_tls: bool, transport=None) -> dict | None:
|
||||
return await _get(url, f"/api/states/{entity_id}", token, verify_tls, transport)
|
||||
|
||||
|
||||
async def call_action(url: str, domain: str, action: str, data: dict, token: str, verify_tls: bool,
|
||||
transport=None) -> None:
|
||||
"""Ask Home Assistant to do something. Returning means it got the request,
|
||||
not that it has finished: a request cut off once sent has been taken up, and
|
||||
an update that restarts Home Assistant cuts its own request off."""
|
||||
try:
|
||||
status, body = await _request("POST", url, f"/api/services/{domain}/{action}", verify_tls, transport,
|
||||
token=token, read_timeout=ACTION_READ_SECONDS, json=data)
|
||||
except (httpx.ReadTimeout, httpx.ReadError, httpx.RemoteProtocolError):
|
||||
return
|
||||
except httpx.HTTPError as exc:
|
||||
raise _unreachable(exc) from None
|
||||
if refusal := _refusal(status):
|
||||
raise refusal
|
||||
if status != 200:
|
||||
try:
|
||||
said = json.loads(body).get("message")
|
||||
except (ValueError, AttributeError):
|
||||
said = None
|
||||
raise Rejected(said or f"Home Assistant answered {status}.")
|
||||
|
||||
|
||||
# ── The system, over the websocket ───────────────────────────────────────────
|
||||
|
||||
class _Socket:
|
||||
"""Home Assistant's websocket after sign-in: one question at a time, each with
|
||||
an id, and None for one it won't answer (no Supervisor, or not an administrator)."""
|
||||
|
||||
def __init__(self, ws):
|
||||
self.ws, self.asked = ws, 0
|
||||
|
||||
async def sign_in(self, token: str) -> None:
|
||||
await self.ws.recv()
|
||||
await self.ws.send(json.dumps({"type": "auth", "access_token": token}))
|
||||
if json.loads(await self.ws.recv()).get("type") != "auth_ok":
|
||||
raise Refused("Home Assistant refused Steward's sign-in. Sign in again, as a user who may do this.")
|
||||
|
||||
async def ask(self, **question):
|
||||
self.asked += 1
|
||||
await self.ws.send(json.dumps({"id": self.asked, **question}))
|
||||
while True:
|
||||
answer = json.loads(await self.ws.recv())
|
||||
if answer.get("id") == self.asked:
|
||||
return answer.get("result") if answer.get("success") else None
|
||||
|
||||
async def supervisor(self, endpoint: str):
|
||||
return await self.ask(type="supervisor/api", endpoint=endpoint, method="get")
|
||||
|
||||
|
||||
@asynccontextmanager
|
||||
async def _signed_in(url: str, token: str, verify_tls: bool, connect):
|
||||
"""A signed-in socket. `connect` stands in for the websocket in tests."""
|
||||
target = "ws" + url.rstrip("/").removeprefix("http") + "/api/websocket"
|
||||
options: dict = {"max_size": MAX_BYTES}
|
||||
if target.startswith("wss:") and not verify_tls:
|
||||
options["ssl"] = ssl.create_default_context()
|
||||
options["ssl"].check_hostname, options["ssl"].verify_mode = False, ssl.CERT_NONE
|
||||
try:
|
||||
async with asyncio.timeout(SYSTEM_READ_SECONDS):
|
||||
async with (connect or ws_connect)(target, **options) as ws:
|
||||
socket = _Socket(ws)
|
||||
await socket.sign_in(token)
|
||||
yield socket
|
||||
except TimeoutError:
|
||||
raise Unreachable(f"Home Assistant's system report didn't arrive within {SYSTEM_READ_SECONDS} s.") from None
|
||||
except (OSError, ValueError, KeyError, WebSocketException) as exc:
|
||||
raise Unreachable(f"Couldn't read Home Assistant's system report: {exc}") from None
|
||||
|
||||
|
||||
async def read_system(url: str, token: str, verify_tls: bool, connect=None) -> dict:
|
||||
"""What service.read_health needs, as Home Assistant answered it."""
|
||||
async with _signed_in(url, token, verify_tls, connect) as socket:
|
||||
found = {"config": await socket.ask(type="get_config"),
|
||||
"issues": (await socket.ask(type="repairs/list_issues") or {}).get("issues"),
|
||||
"resolution": await socket.supervisor("/resolution/info"),
|
||||
"host": await socket.supervisor("/host/info"), "titles": {}, "boots": {}}
|
||||
domains = sorted({i["domain"] for i in found["issues"] or []})
|
||||
if domains:
|
||||
titles = await socket.ask(type="frontend/get_translations", language="en",
|
||||
category="issues", integration=domains)
|
||||
found["titles"] = (titles or {}).get("resources") or {}
|
||||
found["addons"] = (await socket.supervisor("/addons") or {}).get("addons")
|
||||
# Whether one should be running is only on its own page, so a running one isn't asked.
|
||||
for addon in found["addons"] or []:
|
||||
if addon.get("state") != "started":
|
||||
info = await socket.supervisor(f"/addons/{addon['slug']}/info") or {}
|
||||
found["boots"][addon["slug"]] = info.get("boot")
|
||||
return found
|
||||
|
||||
|
||||
async def read_os(url: str, token: str, verify_tls: bool, connect=None) -> dict | None:
|
||||
"""The Supervisor's report on the OS: `version`, and `version_pending` while a
|
||||
written update waits for its reboot. None if it isn't answering yet, as just
|
||||
after a boot."""
|
||||
async with _signed_in(url, token, verify_tls, connect) as socket:
|
||||
return await socket.supervisor("/os/info")
|
||||
@@ -0,0 +1,168 @@
|
||||
"""The Home Assistant plugin's MCP tools and its get_overview findings.
|
||||
|
||||
get_home_assistant reads what the poll stored. update_home_assistant starts an
|
||||
update as the page's Install does. The sign-in Steward holds is never returned.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import timezone
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from steward.core import weekly
|
||||
from steward.core.formatting import zone
|
||||
from steward.mcp._context import current_caller, mcp_app
|
||||
from steward.mcp.tools._audit import audit_mcp, mcp_username
|
||||
from steward.mcp.tools._shape import age_s, db_session, iso, now_utc, redact_url
|
||||
from steward.mcp.tools.overview import finding
|
||||
from steward.models.users import UserRole
|
||||
|
||||
from . import schedule
|
||||
from .models import HomeAssistantConnection, HomeAssistantSchedule, HomeAssistantUpdate
|
||||
from .routes import connection_says
|
||||
from .service import STALE_BACKUP_HOURS, backup_age_hours, backup_verdict, installable, parse_moment, problems_open
|
||||
from .updates import CannotStart, start_update
|
||||
|
||||
RECENT_UPDATES = 10
|
||||
|
||||
|
||||
def _schedule_view(plan, now) -> dict | None:
|
||||
if plan is None:
|
||||
return None
|
||||
return {"enabled": plan.enabled, "when": weekly.describe(plan),
|
||||
"next_slot_at": iso(weekly.next_slot(plan, now)) if plan.enabled else None,
|
||||
"last_slot_at": iso(weekly.fired_slot(plan)), "stopped": plan.stopped}
|
||||
|
||||
|
||||
def _run_view(r: HomeAssistantUpdate) -> dict:
|
||||
return {"update_id": r.id, "entity_id": r.entity_id, "title": r.title, "kind": r.kind,
|
||||
"from_version": r.from_version, "to_version": r.to_version, "state": r.state, "message": r.message,
|
||||
"started_by": r.started_by, "started_at": iso(r.started_at), "backup_at": iso(r.backup_at),
|
||||
"finished_at": iso(r.finished_at)}
|
||||
|
||||
|
||||
async def get_home_assistant() -> dict:
|
||||
"""Home Assistant as of the last poll: whether it answers, which updates are
|
||||
waiting, how old its last backup is, and the updates Steward was asked to install.
|
||||
|
||||
`installable` is what update_home_assistant takes (Core, OS, add-ons);
|
||||
`others_waiting` is firmware and custom integrations, which Steward leaves
|
||||
to Home Assistant. `can_install` is whether the Home Assistant user who signed
|
||||
Steward in is an administrator, which installing needs. `system.problems` is
|
||||
what's wrong with the system itself: open repairs, Supervisor health, low disk,
|
||||
recovery mode, add-ons that should be running. `schedule` is the weekly slot
|
||||
for installing what's waiting, null until one is set.
|
||||
"""
|
||||
now = now_utc()
|
||||
async with db_session() as db:
|
||||
c = (await db.execute(select(HomeAssistantConnection))).scalars().first()
|
||||
runs = list((await db.execute(select(HomeAssistantUpdate).order_by(
|
||||
HomeAssistantUpdate.started_at.desc()).limit(RECENT_UPDATES))).scalars())
|
||||
plan = (await db.execute(select(HomeAssistantSchedule))).scalars().first()
|
||||
if c is None:
|
||||
return {"connected": False, "says": "No connection yet: an admin signs in on the Home Assistant page."}
|
||||
reach, says = connection_says(c, now)
|
||||
backup = c.backup or {}
|
||||
age = backup_age_hours(backup, now)
|
||||
return {"connected": True, "url": redact_url(c.url), "reach": reach, "says": says,
|
||||
"polled_at": iso(c.last_polled_at), "ok_age_s": age_s(c.last_ok_at, now), "can_install": c.can_install,
|
||||
"installable": [{k: u[k] for k in ("entity_id", "title", "kind", "installed", "latest", "in_progress")}
|
||||
for u in installable(c)],
|
||||
"others_waiting": [u["title"] for u in c.updates or [] if u["waiting"] and not u["kind"]],
|
||||
"backup": {"verdict": backup_verdict(backup, now)[1], "last_ok": iso(parse_moment(backup.get("last_ok"))),
|
||||
"age_hours": round(age, 1) if age is not None else None, "stale_after_hours": STALE_BACKUP_HOURS,
|
||||
"next": iso(parse_moment(backup.get("next"))), "last_result": backup.get("last_result")},
|
||||
"system": c.health or {}, "schedule": _schedule_view(plan, now),
|
||||
"updates": [_run_view(r) for r in runs]}
|
||||
|
||||
|
||||
async def update_home_assistant(entity_id: str) -> dict:
|
||||
"""Install one Core, OS or add-on update, as the page's Install does: Steward
|
||||
takes a backup, confirms it landed, installs, and follows it to its end.
|
||||
|
||||
entity_id: from get_home_assistant's `installable`.
|
||||
|
||||
An update restarts Home Assistant or the add-on. An OS update reads as done
|
||||
once it's written, and takes effect after a reboot, which Steward leaves to a
|
||||
person. Refused while another is under way, or if nothing is waiting there.
|
||||
Admin only, as on the page. Recorded in the audit log.
|
||||
"""
|
||||
caller = current_caller()
|
||||
try:
|
||||
run = await start_update(mcp_app(), entity_id, mcp_username(caller.username))
|
||||
except CannotStart as exc:
|
||||
raise ValueError(f"Nothing was started: {exc}.") from None
|
||||
await audit_mcp("homeassistant.update_started", "homeassistant_update", run.id,
|
||||
{"entity_id": entity_id, "title": run.title, "to": run.to_version})
|
||||
return {**_run_view(run), "next": "get_home_assistant follows it: `updates` shows its state."}
|
||||
|
||||
|
||||
async def set_home_assistant_schedule(enabled: bool, weekday: int = 5, at_time: str = "05:00",
|
||||
time_zone: str = "UTC") -> dict:
|
||||
"""Set the weekly slot for installing what's waiting, or turn it off, as the page does.
|
||||
|
||||
weekday: 0 for Monday to 6 for Sunday. at_time: "HH:MM" in time_zone.
|
||||
|
||||
At each slot Steward installs add-ons, then Core, then the OS, one at a time,
|
||||
each after a confirmed backup, stopping at the first failure. A Core update
|
||||
restarts Home Assistant and an OS update reboots the machine, which Steward
|
||||
does itself here, with nobody watching. The first slot is the next one from
|
||||
now. Admin only, and audited.
|
||||
"""
|
||||
try:
|
||||
weekly.parse_at(at_time)
|
||||
except ValueError:
|
||||
raise ValueError(f"at_time is HH:MM, not {at_time!r}.") from None
|
||||
if not 0 <= weekday <= 6:
|
||||
raise ValueError("weekday is 0 for Monday to 6 for Sunday.")
|
||||
if zone(time_zone) is timezone.utc and time_zone.upper() != "UTC":
|
||||
raise ValueError(f"Unknown time zone {time_zone!r}.")
|
||||
row = await schedule.save(mcp_app(), enabled=enabled, weekday=weekday, at_time=at_time, time_zone=time_zone)
|
||||
await audit_mcp("homeassistant.schedule_saved", "homeassistant_schedule", row.id,
|
||||
{"enabled": row.enabled, "when": weekly.describe(row)})
|
||||
return _schedule_view(row, now_utc())
|
||||
|
||||
|
||||
def overview_findings(c, latest_run, now, plan=None) -> list[dict]:
|
||||
"""A connection that isn't answering, a problem with the system, stale backups,
|
||||
a newest update that failed, and a scheduled run that stopped. Updates waiting
|
||||
aren't a problem to raise."""
|
||||
if c is None:
|
||||
return []
|
||||
found = []
|
||||
reach, says = connection_says(c, now)
|
||||
if reach == "down":
|
||||
found.append(finding("warning", "home_assistant_down", "Home Assistant",
|
||||
f"Home Assistant isn't answering: {says}", since=c.last_ok_at, next="get_home_assistant()"))
|
||||
problems = problems_open(c.health)
|
||||
if problems:
|
||||
more = f" (and {len(problems) - 1} more)" if len(problems) > 1 else ""
|
||||
found.append(finding("warning", "home_assistant_problem", "Home Assistant", f"{problems[0]['title']}{more}",
|
||||
next="get_home_assistant()"))
|
||||
tone, backup_says = backup_verdict(c.backup, now)
|
||||
if c.last_ok_at is not None and tone == "warn":
|
||||
found.append(finding("warning", "home_assistant_backup", "Home Assistant", backup_says,
|
||||
since=parse_moment((c.backup or {}).get("last_ok")), next="get_home_assistant()"))
|
||||
if latest_run is not None and latest_run.state == "failed":
|
||||
found.append(finding("warning", "home_assistant_update_failed", latest_run.title,
|
||||
f"The update of {latest_run.title} failed: {latest_run.message}",
|
||||
since=latest_run.finished_at, next="get_home_assistant()"))
|
||||
if plan is not None and plan.stopped:
|
||||
found.append(finding("warning", "home_assistant_schedule_stopped", "Home Assistant",
|
||||
f"The scheduled update run stopped: {plan.stopped}", since=weekly.fired_slot(plan),
|
||||
next="get_home_assistant()"))
|
||||
return found
|
||||
|
||||
|
||||
async def mcp_overview(db) -> list[dict]:
|
||||
c = (await db.execute(select(HomeAssistantConnection))).scalars().first()
|
||||
latest = (await db.execute(select(HomeAssistantUpdate).order_by(
|
||||
HomeAssistantUpdate.started_at.desc()).limit(1))).scalars().first()
|
||||
plan = (await db.execute(select(HomeAssistantSchedule))).scalars().first()
|
||||
return overview_findings(c, latest, now_utc(), plan)
|
||||
|
||||
|
||||
def register_tools(register) -> None:
|
||||
register(get_home_assistant, role=UserRole.viewer, read_only=True)
|
||||
register(update_home_assistant, role=UserRole.admin, read_only=False)
|
||||
register(set_home_assistant_schedule, role=UserRole.admin, read_only=False)
|
||||
@@ -0,0 +1,59 @@
|
||||
"""Home Assistant: the connection and the updates Steward was asked to install
|
||||
|
||||
Revision ID: homeassistant_001_connection
|
||||
Revises: (none — a branch off core via depends_on)
|
||||
Create Date: 2026-10-31
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "homeassistant_001_connection"
|
||||
down_revision: Union[str, None] = None
|
||||
branch_labels: Union[str, Sequence[str], None] = "homeassistant"
|
||||
depends_on: Union[str, Sequence[str], None] = ("0004_app_settings",)
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"homeassistant_connection",
|
||||
sa.Column("id", sa.String(36), primary_key=True),
|
||||
sa.Column("url", sa.String(500), nullable=False),
|
||||
sa.Column("token", sa.Text, nullable=False),
|
||||
sa.Column("webhook_id", sa.Text, nullable=False),
|
||||
sa.Column("verify_tls", sa.Boolean, nullable=False, server_default=sa.true()),
|
||||
sa.Column("refused", sa.Boolean, nullable=False, server_default=sa.false()),
|
||||
sa.Column("last_polled_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("last_ok_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("last_error", sa.Text, nullable=True),
|
||||
sa.Column("updates", sa.JSON, nullable=False, server_default="[]"),
|
||||
sa.Column("backup", sa.JSON, nullable=False, server_default="{}"),
|
||||
sa.Column("automation", sa.String(20), nullable=True),
|
||||
)
|
||||
op.create_table(
|
||||
"homeassistant_updates",
|
||||
sa.Column("id", sa.String(36), primary_key=True),
|
||||
sa.Column("entity_id", sa.String(255), nullable=False),
|
||||
sa.Column("title", sa.String(255), nullable=False),
|
||||
sa.Column("kind", sa.String(10), nullable=False),
|
||||
sa.Column("from_version", sa.String(100), nullable=True),
|
||||
sa.Column("to_version", sa.String(100), nullable=True),
|
||||
sa.Column("state", sa.String(20), nullable=False, server_default="backing_up"),
|
||||
sa.Column("message", sa.Text, nullable=True),
|
||||
sa.Column("started_by", sa.String(100), nullable=False, server_default=""),
|
||||
sa.Column("started_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("backup_before", sa.String(64), nullable=True),
|
||||
sa.Column("backup_event_before", sa.String(64), nullable=True),
|
||||
sa.Column("triggered_before", sa.String(64), nullable=True),
|
||||
sa.Column("backup_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("install_sent_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("finished_at", sa.DateTime(timezone=True), nullable=True),
|
||||
)
|
||||
op.execute("CREATE UNIQUE INDEX uq_homeassistant_update_under_way ON homeassistant_updates ((true)) "
|
||||
"WHERE state IN ('backing_up', 'installing')")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("homeassistant_updates")
|
||||
op.drop_table("homeassistant_connection")
|
||||
@@ -0,0 +1,42 @@
|
||||
"""Home Assistant: Steward holds a sign-in, in place of a token and a webhook
|
||||
|
||||
Revision ID: homeassistant_002_sign_in
|
||||
Revises: homeassistant_001_connection
|
||||
Create Date: 2026-10-31
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "homeassistant_002_sign_in"
|
||||
down_revision: Union[str, None] = "homeassistant_001_connection"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# A saved token can't be refreshed like a sign-in, so that connection signs in again.
|
||||
op.execute("DELETE FROM homeassistant_connection")
|
||||
op.drop_column("homeassistant_connection", "webhook_id")
|
||||
op.drop_column("homeassistant_connection", "automation")
|
||||
op.drop_column("homeassistant_updates", "triggered_before")
|
||||
op.alter_column("homeassistant_connection", "token", new_column_name="refresh_token")
|
||||
op.add_column("homeassistant_connection", sa.Column("client_id", sa.String(500), nullable=False))
|
||||
op.add_column("homeassistant_connection",
|
||||
sa.Column("can_install", sa.Boolean, nullable=False, server_default=sa.false()))
|
||||
op.add_column("homeassistant_connection",
|
||||
sa.Column("signed_in_by", sa.String(100), nullable=False, server_default=""))
|
||||
op.add_column("homeassistant_connection", sa.Column("signed_in_at", sa.DateTime(timezone=True), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.execute("DELETE FROM homeassistant_connection")
|
||||
op.drop_column("homeassistant_connection", "signed_in_at")
|
||||
op.drop_column("homeassistant_connection", "signed_in_by")
|
||||
op.drop_column("homeassistant_connection", "can_install")
|
||||
op.drop_column("homeassistant_connection", "client_id")
|
||||
op.alter_column("homeassistant_connection", "refresh_token", new_column_name="token")
|
||||
op.add_column("homeassistant_updates", sa.Column("triggered_before", sa.String(64), nullable=True))
|
||||
op.add_column("homeassistant_connection", sa.Column("automation", sa.String(20), nullable=True))
|
||||
op.add_column("homeassistant_connection", sa.Column("webhook_id", sa.Text, nullable=False))
|
||||
@@ -0,0 +1,37 @@
|
||||
"""Home Assistant: what the poll reads of the system, and a weekly slot for updates
|
||||
|
||||
Revision ID: homeassistant_003_health
|
||||
Revises: homeassistant_002_sign_in
|
||||
Create Date: 2026-11-01
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "homeassistant_003_health"
|
||||
down_revision: Union[str, None] = "homeassistant_002_sign_in"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("homeassistant_connection",
|
||||
sa.Column("health", sa.JSON, nullable=False, server_default="{}"))
|
||||
op.create_table(
|
||||
"homeassistant_schedule",
|
||||
sa.Column("id", sa.String(36), primary_key=True),
|
||||
sa.Column("enabled", sa.Boolean, nullable=False),
|
||||
sa.Column("weekday", sa.Integer, nullable=False),
|
||||
sa.Column("at_time", sa.String(5), nullable=False),
|
||||
sa.Column("time_zone", sa.String(64), nullable=False),
|
||||
sa.Column("window_minutes", sa.Integer, nullable=False),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), nullable=False),
|
||||
sa.Column("last_slot_at", sa.DateTime(timezone=True), nullable=True),
|
||||
sa.Column("stopped", sa.Text, nullable=True),
|
||||
)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_table("homeassistant_schedule")
|
||||
op.drop_column("homeassistant_connection", "health")
|
||||
@@ -0,0 +1,34 @@
|
||||
"""Home Assistant: an update the schedule installs can reboot the machine and follow it
|
||||
|
||||
Revision ID: homeassistant_004_reboot
|
||||
Revises: homeassistant_003_health
|
||||
Create Date: 2026-11-02
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "homeassistant_004_reboot"
|
||||
down_revision: Union[str, None] = "homeassistant_003_health"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def _under_way(states: str) -> None:
|
||||
op.execute("DROP INDEX uq_homeassistant_update_under_way")
|
||||
op.execute("CREATE UNIQUE INDEX uq_homeassistant_update_under_way ON homeassistant_updates ((true)) "
|
||||
f"WHERE state IN ({states})")
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("homeassistant_updates",
|
||||
sa.Column("reboot_after", sa.Boolean, nullable=False, server_default=sa.false()))
|
||||
op.add_column("homeassistant_updates", sa.Column("reboot_sent_at", sa.DateTime(timezone=True), nullable=True))
|
||||
_under_way("'backing_up', 'installing', 'rebooting'")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
_under_way("'backing_up', 'installing'")
|
||||
op.drop_column("homeassistant_updates", "reboot_sent_at")
|
||||
op.drop_column("homeassistant_updates", "reboot_after")
|
||||
@@ -0,0 +1,92 @@
|
||||
# plugins/homeassistant/models.py
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import JSON, Boolean, DateTime, Index, Integer, String, Text, text
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from steward.core.ids import time_ordered_id
|
||||
from steward.models.base import Base
|
||||
|
||||
|
||||
class HomeAssistantConnection(Base):
|
||||
"""The Home Assistant instance Steward looks after; at most one row.
|
||||
|
||||
`refresh_token` is what Home Assistant's sign-in gave Steward, encrypted. It
|
||||
has the same access as the user who signed in, whatever that is: Home
|
||||
Assistant has no narrower permission. `can_install` is whether that user was
|
||||
an administrator, which backups need. The last_* columns and `updates` and
|
||||
`backup` and `health` are the newest poll's outcome, which the pages read. `refused` stops
|
||||
all polling until someone signs in again or tries again: Home Assistant bans
|
||||
an address after a few refused requests.
|
||||
"""
|
||||
__tablename__ = "homeassistant_connection"
|
||||
|
||||
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=time_ordered_id)
|
||||
url: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
client_id: Mapped[str] = mapped_column(String(500), nullable=False)
|
||||
refresh_token: Mapped[str] = mapped_column(Text, nullable=False)
|
||||
can_install: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
signed_in_by: Mapped[str] = mapped_column(String(100), nullable=False, default="")
|
||||
signed_in_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
verify_tls: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
||||
refused: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
last_polled_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
last_ok_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
last_error: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
updates: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
|
||||
backup: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||
health: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||
|
||||
|
||||
class HomeAssistantSchedule(Base):
|
||||
"""The weekly slot for installing what's waiting; at most one row, none until an
|
||||
admin sets it. `last_slot_at` is the slot that last fired, and `stopped` says why
|
||||
that slot ended early. Times are read through steward.core.weekly."""
|
||||
__tablename__ = "homeassistant_schedule"
|
||||
|
||||
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=time_ordered_id)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
||||
weekday: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
at_time: Mapped[str] = mapped_column(String(5), nullable=False)
|
||||
time_zone: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
window_minutes: Mapped[int] = mapped_column(Integer, nullable=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, default=lambda: datetime.now(timezone.utc))
|
||||
last_slot_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
stopped: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
|
||||
|
||||
class HomeAssistantUpdate(Base):
|
||||
"""One update Steward was asked to install, from the click to its end. It
|
||||
moves through backing_up and installing to done or failed, and its row
|
||||
carries everything needed to carry on after Steward restarts. The *_before
|
||||
columns are Home Assistant's own readings at the start, so "a newer backup"
|
||||
is judged on its clock alone. One can be under way at a time. `reboot_after`
|
||||
sends it through rebooting too, for an OS update the schedule installs.
|
||||
"""
|
||||
__tablename__ = "homeassistant_updates"
|
||||
__table_args__ = (
|
||||
Index("uq_homeassistant_update_under_way", text("(true)"), unique=True,
|
||||
postgresql_where=text("state IN ('backing_up', 'installing', 'rebooting')")),
|
||||
)
|
||||
|
||||
id: Mapped[str] = mapped_column(String(36), primary_key=True, default=time_ordered_id)
|
||||
entity_id: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
title: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
kind: Mapped[str] = mapped_column(String(10), nullable=False)
|
||||
from_version: Mapped[str | None] = mapped_column(String(100), nullable=True)
|
||||
to_version: Mapped[str | None] = mapped_column(String(100), nullable=True)
|
||||
state: Mapped[str] = mapped_column(String(20), nullable=False, default="backing_up")
|
||||
message: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
started_by: Mapped[str] = mapped_column(String(100), nullable=False, default="")
|
||||
started_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, default=lambda: datetime.now(timezone.utc))
|
||||
backup_before: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
backup_event_before: Mapped[str | None] = mapped_column(String(64), nullable=True)
|
||||
backup_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
install_sent_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
reboot_after: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
reboot_sent_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
finished_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
@@ -0,0 +1,17 @@
|
||||
# plugins/homeassistant/plugin.yaml
|
||||
name: homeassistant
|
||||
version: "1.0.0"
|
||||
description: "Keeps Home Assistant running: shows whether backups are happening and whether the system has a problem, and installs Core, OS and add-on updates after a confirmed backup, on a click or a weekly schedule."
|
||||
author: "Steward"
|
||||
license: "MIT"
|
||||
min_app_version: "0.1.0"
|
||||
repository_url: "https://git.fabledsword.com/bvandeusen/FabledSteward"
|
||||
homepage: "https://git.fabledsword.com/bvandeusen/FabledSteward/src/branch/dev/plugins/homeassistant"
|
||||
tags:
|
||||
- home-assistant
|
||||
- updates
|
||||
- backups
|
||||
|
||||
# The connection is added and edited on the Home Assistant page
|
||||
# (/plugins/homeassistant/).
|
||||
config: {}
|
||||
@@ -0,0 +1,249 @@
|
||||
"""The Home Assistant page. Every GET reads Steward's own records, which the poll
|
||||
fills. Only signing in, removing the connection and Install, an admin's explicit
|
||||
actions, ask Home Assistant anything (System 178's ruling)."""
|
||||
from __future__ import annotations
|
||||
|
||||
import hmac
|
||||
import logging
|
||||
import secrets
|
||||
from datetime import datetime, timezone
|
||||
from types import SimpleNamespace
|
||||
|
||||
from quart import Blueprint, current_app, redirect, render_template, request, session
|
||||
from sqlalchemy import select
|
||||
|
||||
from steward.auth.middleware import require_role
|
||||
from steward.core import weekly
|
||||
from steward.core.audit import log_audit
|
||||
from steward.core.crypto import encrypt_secret
|
||||
from steward.core.formatting import zone
|
||||
from steward.core.settings import public_base_url
|
||||
from steward.models.users import User, UserRole
|
||||
|
||||
from . import client, schedule
|
||||
from .models import HomeAssistantConnection, HomeAssistantSchedule, HomeAssistantUpdate
|
||||
from .service import STALE_BACKUP_HOURS, backup_age_hours, backup_verdict, installable, parse_moment, problems_open
|
||||
from .updates import UNDER_WAY, CannotStart, start_update
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
homeassistant_bp = Blueprint("homeassistant", __name__, template_folder="templates")
|
||||
|
||||
RECENT_UPDATES = 10
|
||||
_SIGN_IN = "homeassistant_sign_in" # in the session between leaving for Home Assistant and coming back
|
||||
|
||||
|
||||
def _actor() -> tuple[str | None, str]:
|
||||
return session.get("user_id"), session.get("username", "")
|
||||
|
||||
|
||||
async def _connection(db) -> HomeAssistantConnection | None:
|
||||
return (await db.execute(select(HomeAssistantConnection))).scalars().first()
|
||||
|
||||
|
||||
def connection_says(connection, now: datetime) -> tuple[str, str]:
|
||||
"""(badge state, sentence) for whether Home Assistant is answering."""
|
||||
if connection.refused:
|
||||
return "down", f"{connection.last_error} Steward has stopped asking until you sign in again or try again."
|
||||
if connection.last_polled_at is None:
|
||||
return "pending", "Not read yet: the first read runs within seconds."
|
||||
if connection.last_error:
|
||||
return "down", connection.last_error
|
||||
return "up", "Answering."
|
||||
|
||||
|
||||
async def _render_index(error: str | None = None, status: int = 200):
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
connection = await _connection(db)
|
||||
runs = list((await db.execute(select(HomeAssistantUpdate).order_by(
|
||||
HomeAssistantUpdate.started_at.desc()).limit(RECENT_UPDATES))).scalars())
|
||||
plan = (await db.execute(select(HomeAssistantSchedule))).scalars().first()
|
||||
me = await db.get(User, session.get("user_id")) if session.get("user_id") else None
|
||||
if connection is None:
|
||||
return await render_template("homeassistant/index.html", connection=None, error=error), status
|
||||
default_zone = (me.time_zone if me and me.time_zone else "UTC")
|
||||
now = datetime.now(timezone.utc)
|
||||
reach, says = connection_says(connection, now)
|
||||
updates = connection.updates or []
|
||||
backup = connection.backup or {}
|
||||
tone, backup_says = backup_verdict(backup, now)
|
||||
return await render_template(
|
||||
"homeassistant/index.html", connection=connection, error=error, reach=reach, says=says,
|
||||
installable=installable(connection),
|
||||
others=[u for u in updates if u["waiting"] and not u["kind"]],
|
||||
current=[u for u in updates if not u["waiting"] and u["kind"]],
|
||||
runs=runs, under_way=next((r for r in runs if r.state in UNDER_WAY), None),
|
||||
backup=backup, backup_tone=tone, backup_says=backup_says,
|
||||
backup_at=parse_moment(backup.get("last_ok")), backup_next=parse_moment(backup.get("next")),
|
||||
backup_age=backup_age_hours(backup, now), stale_hours=STALE_BACKUP_HOURS,
|
||||
health=connection.health or {}, problems=problems_open(connection.health),
|
||||
plan=plan, plan_when=weekly.describe(plan) if plan else None,
|
||||
plan_next=weekly.next_slot(plan, now) if plan and plan.enabled else None,
|
||||
weekdays=weekly.WEEKDAYS, default_zone=default_zone), status
|
||||
|
||||
|
||||
@homeassistant_bp.get("/")
|
||||
@require_role(UserRole.viewer)
|
||||
async def index():
|
||||
return await _render_index()
|
||||
|
||||
|
||||
@homeassistant_bp.post("/install")
|
||||
@require_role(UserRole.admin)
|
||||
async def install():
|
||||
form = await request.form
|
||||
entity_id = (form.get("entity_id") or "").strip()
|
||||
user_id, username = _actor()
|
||||
try:
|
||||
run = await start_update(current_app, entity_id, username)
|
||||
except CannotStart as exc:
|
||||
return await _render_index(f"Nothing was started: {exc}.", 409)
|
||||
await log_audit(current_app, user_id, username, "homeassistant.update_started",
|
||||
entity_type="homeassistant_update", entity_id=run.id,
|
||||
detail={"entity_id": entity_id, "title": run.title, "to": run.to_version})
|
||||
return redirect("/plugins/homeassistant/")
|
||||
|
||||
|
||||
@homeassistant_bp.post("/schedule")
|
||||
@require_role(UserRole.admin)
|
||||
async def save_schedule():
|
||||
"""Set the weekly slot for installing what's waiting, or turn it off."""
|
||||
form = await request.form
|
||||
time_zone = (form.get("time_zone") or "UTC").strip()
|
||||
try:
|
||||
weekday, at_time = int(form.get("weekday", "")), (form.get("at_time") or "").strip()
|
||||
weekly.parse_at(at_time)
|
||||
except ValueError:
|
||||
return await _render_index("Choose a day and a time.", 422)
|
||||
if not 0 <= weekday <= 6 or (zone(time_zone) is timezone.utc and time_zone.upper() != "UTC"):
|
||||
return await _render_index(f"Choose a day, and a known time zone rather than “{time_zone}”.", 422)
|
||||
row = await schedule.save(current_app, enabled=bool(form.get("enabled")), weekday=weekday,
|
||||
at_time=at_time, time_zone=time_zone)
|
||||
await log_audit(current_app, *_actor(), "homeassistant.schedule_saved", entity_type="homeassistant_schedule",
|
||||
entity_id=row.id, detail={"enabled": row.enabled, "when": weekly.describe(row)})
|
||||
return redirect("/plugins/homeassistant/")
|
||||
|
||||
|
||||
# ── The connection ───────────────────────────────────────────────────────────
|
||||
|
||||
async def _render_form(connection, url: str | None = None, verify_tls: bool | None = None,
|
||||
error: str | None = None, status: int = 200):
|
||||
return await render_template(
|
||||
"homeassistant/form.html", connection=connection, error=error,
|
||||
url=url if url is not None else (connection.url if connection else ""),
|
||||
verify_tls=verify_tls if verify_tls is not None else (connection.verify_tls if connection else True)), status
|
||||
|
||||
|
||||
@homeassistant_bp.get("/connection")
|
||||
@require_role(UserRole.admin)
|
||||
async def connection_form():
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
connection = await _connection(db)
|
||||
return await _render_form(connection)
|
||||
|
||||
|
||||
@homeassistant_bp.post("/connection/sign-in")
|
||||
@require_role(UserRole.admin)
|
||||
async def sign_in():
|
||||
"""Send the browser to Home Assistant's own sign-in page."""
|
||||
form = await request.form
|
||||
url = (form.get("url") or "").strip().rstrip("/")
|
||||
verify_tls = bool(form.get("verify_tls"))
|
||||
if not url.startswith(("http://", "https://")):
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
connection = await _connection(db)
|
||||
return await _render_form(connection, url, verify_tls, "Enter Home Assistant's address: http://… or https://…", 422)
|
||||
base, state = public_base_url(request), secrets.token_urlsafe(32)
|
||||
client_id = f"{base}/"
|
||||
session[_SIGN_IN] = {"state": state, "url": url, "verify_tls": verify_tls, "client_id": client_id}
|
||||
return redirect(client.sign_in_url(url, client_id, f"{base}/plugins/homeassistant/connection/callback", state))
|
||||
|
||||
|
||||
@homeassistant_bp.get("/connection/callback")
|
||||
@require_role(UserRole.admin)
|
||||
async def sign_in_callback():
|
||||
"""Where Home Assistant sends the browser back. A GET that asks Home Assistant
|
||||
something, because the admin's sign-in has only just happened and its code
|
||||
lasts minutes. The state shows the sign-in began here, for this admin."""
|
||||
pending = session.pop(_SIGN_IN, None)
|
||||
state, code = request.args.get("state", ""), request.args.get("code", "")
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
connection = await _connection(db)
|
||||
if not pending or not hmac.compare_digest(pending["state"].encode(), state.encode()):
|
||||
return await _render_form(connection, error="That sign-in didn't start from this page, so it wasn't used. "
|
||||
"If it keeps happening, check Public base URL in Settings → General: "
|
||||
"Steward must be opened at that address.", status=400)
|
||||
url, verify_tls, client_id = pending["url"], pending["verify_tls"], pending["client_id"]
|
||||
if not code:
|
||||
return await _render_form(connection, url, verify_tls, "Home Assistant didn't finish the sign-in. Nothing changed.", 400)
|
||||
try:
|
||||
refresh_token, token = await client.redeem_code(url, client_id, code, verify_tls)
|
||||
can_install = await client.is_admin(url, token, verify_tls)
|
||||
except (client.Refused, client.Unreachable) as exc:
|
||||
return await _render_form(connection, url, verify_tls, f"The sign-in couldn't be finished: {exc}", 502)
|
||||
user_id, username = _actor()
|
||||
previous = None
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
async with db.begin():
|
||||
connection = await _connection(db)
|
||||
if connection is None:
|
||||
connection = HomeAssistantConnection(url=url, client_id=client_id, refresh_token="")
|
||||
db.add(connection)
|
||||
else:
|
||||
previous = (connection.url, connection.client_id, connection.refresh_token, connection.verify_tls)
|
||||
connection.url, connection.client_id, connection.verify_tls = url, client_id, verify_tls
|
||||
connection.refresh_token = encrypt_secret(refresh_token)
|
||||
connection.can_install, connection.signed_in_by = can_install, username
|
||||
connection.signed_in_at = datetime.now(timezone.utc)
|
||||
connection.refused, connection.last_error, connection.last_polled_at = False, None, None
|
||||
await db.flush()
|
||||
connection_id = connection.id
|
||||
if previous is not None:
|
||||
await _end_sign_in(SimpleNamespace(url=previous[0], client_id=previous[1], refresh_token=previous[2],
|
||||
verify_tls=previous[3]))
|
||||
await log_audit(current_app, user_id, username, "homeassistant.connection_saved",
|
||||
entity_type="homeassistant_connection", entity_id=connection_id,
|
||||
detail={"name": url, "can_install": can_install})
|
||||
return redirect("/plugins/homeassistant/")
|
||||
|
||||
|
||||
async def _end_sign_in(connection) -> bool:
|
||||
"""End a sign-in Steward no longer needs, so it doesn't stay valid on Home
|
||||
Assistant. It can be ended there by hand too, so failing here stops nothing."""
|
||||
try:
|
||||
await client.revoke(connection)
|
||||
except (client.Refused, client.Unreachable) as exc:
|
||||
logger.warning("Home Assistant: couldn't end Steward's old sign-in: %s", exc)
|
||||
return False
|
||||
return True
|
||||
|
||||
|
||||
@homeassistant_bp.post("/connection/retry")
|
||||
@require_role(UserRole.admin)
|
||||
async def retry_connection():
|
||||
"""Ask again after a refusal, once a ban has been dealt with."""
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
async with db.begin():
|
||||
connection = await _connection(db)
|
||||
if connection is not None:
|
||||
connection.refused, connection.last_polled_at = False, None
|
||||
return redirect("/plugins/homeassistant/")
|
||||
|
||||
|
||||
@homeassistant_bp.post("/connection/delete")
|
||||
@require_role(UserRole.admin)
|
||||
async def delete_connection():
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
async with db.begin():
|
||||
connection = await _connection(db)
|
||||
if connection is None:
|
||||
return redirect("/plugins/homeassistant/")
|
||||
connection_id, url = connection.id, connection.url
|
||||
await db.delete(connection)
|
||||
ended = await _end_sign_in(connection)
|
||||
await log_audit(current_app, *_actor(), "homeassistant.connection_removed",
|
||||
entity_type="homeassistant_connection", entity_id=connection_id, detail={"name": url, "sign_in_ended": ended})
|
||||
if not ended:
|
||||
return await _render_index("Removed from Steward, but Home Assistant couldn't be reached to end the sign-in. "
|
||||
"End it yourself under Security on that user's profile in Home Assistant.")
|
||||
return redirect("/plugins/homeassistant/")
|
||||
@@ -0,0 +1,95 @@
|
||||
# plugins/homeassistant/schedule.py
|
||||
"""Installing what's waiting at a weekly slot: one at a time through the same path
|
||||
as the page's Install, each after its own confirmed backup. Add-ons go first and
|
||||
the OS last, as it reboots the machine. The first failure ends the slot, leaving the
|
||||
rest for someone to look at. Everything is on the rows, so a restart of Steward or
|
||||
of Home Assistant only delays the next step."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from steward.core import weekly
|
||||
|
||||
from .models import HomeAssistantConnection, HomeAssistantSchedule, HomeAssistantUpdate
|
||||
from .service import installable
|
||||
from .updates import CannotStart, start_update, under_way
|
||||
|
||||
ACTOR = "schedule"
|
||||
WINDOW_MINUTES = 240
|
||||
_ORDER = {"addon": 0, "core": 1, "os": 2}
|
||||
|
||||
|
||||
def next_to_install(waiting: list[dict], tried: set[str]) -> dict | None:
|
||||
left = [u for u in waiting if u["entity_id"] not in tried and not u["in_progress"]]
|
||||
return min(left, key=lambda u: _ORDER[u["kind"]], default=None)
|
||||
|
||||
|
||||
async def _stop(app, schedule_id: str, why: str) -> None:
|
||||
async with app.db_sessionmaker() as session:
|
||||
async with session.begin():
|
||||
row = await session.get(HomeAssistantSchedule, schedule_id)
|
||||
if row is not None:
|
||||
row.stopped = why
|
||||
|
||||
|
||||
async def _fire(app, schedule_id: str, slot: datetime) -> None:
|
||||
"""Open the slot, and have the next poll say what's waiting at this moment."""
|
||||
async with app.db_sessionmaker() as session:
|
||||
async with session.begin():
|
||||
row = await session.get(HomeAssistantSchedule, schedule_id)
|
||||
row.last_slot_at, row.stopped = slot, None
|
||||
connection = (await session.execute(select(HomeAssistantConnection))).scalars().first()
|
||||
if connection is not None:
|
||||
connection.last_polled_at = None
|
||||
|
||||
|
||||
async def step(app, transport=None) -> None:
|
||||
"""Fire a slot that has come, or start the next update of one that's open."""
|
||||
now = datetime.now(timezone.utc)
|
||||
async with app.db_sessionmaker() as session:
|
||||
schedule = (await session.execute(select(HomeAssistantSchedule))).scalars().first()
|
||||
connection = (await session.execute(select(HomeAssistantConnection))).scalars().first()
|
||||
if schedule is None or connection is None:
|
||||
return
|
||||
slot = weekly.is_due(schedule, now)
|
||||
if slot is not None:
|
||||
await _fire(app, schedule.id, slot)
|
||||
return
|
||||
slot = weekly.fired_slot(schedule)
|
||||
if not schedule.enabled or schedule.stopped or slot is None \
|
||||
or now - slot >= timedelta(minutes=schedule.window_minutes):
|
||||
return
|
||||
# Only on a fresh, good read: Home Assistant may be restarting from the last update.
|
||||
if connection.refused or connection.last_polled_at is None or connection.last_error:
|
||||
return
|
||||
if await under_way(session) is not None:
|
||||
return
|
||||
runs = (await session.execute(select(HomeAssistantUpdate).where(
|
||||
HomeAssistantUpdate.started_at >= slot))).scalars().all()
|
||||
failed = next((r for r in runs if r.state == "failed"), None)
|
||||
if failed is not None:
|
||||
await _stop(app, schedule.id, f"{failed.title}: {failed.message} Nothing more was installed in this slot.")
|
||||
return
|
||||
update = next_to_install(installable(connection), {r.entity_id for r in runs})
|
||||
if update is None:
|
||||
return
|
||||
try:
|
||||
await start_update(app, update["entity_id"], ACTOR, transport, reboot_after=update["kind"] == "os")
|
||||
except CannotStart as exc:
|
||||
await _stop(app, schedule.id, f"{update['title']} wasn't started: {exc}. Nothing more was installed in this slot.")
|
||||
|
||||
|
||||
async def save(app, *, enabled: bool, weekday: int, at_time: str, time_zone: str) -> HomeAssistantSchedule:
|
||||
"""Set the slot. Its first is the next one from now, not one already past."""
|
||||
async with app.db_sessionmaker() as session:
|
||||
async with session.begin():
|
||||
row = (await session.execute(select(HomeAssistantSchedule))).scalars().first()
|
||||
if row is None:
|
||||
row = HomeAssistantSchedule(window_minutes=WINDOW_MINUTES)
|
||||
session.add(row)
|
||||
row.enabled, row.weekday, row.time_zone = enabled, weekday, time_zone
|
||||
row.at_time = f"{weekly.parse_at(at_time):%H:%M}"
|
||||
row.last_slot_at, row.stopped = datetime.now(timezone.utc), None
|
||||
return row
|
||||
@@ -0,0 +1,116 @@
|
||||
# plugins/homeassistant/scheduler.py
|
||||
from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from steward.core.scheduler import ScheduledTask
|
||||
|
||||
from . import client, schedule
|
||||
from .models import HomeAssistantConnection, HomeAssistantSchedule, HomeAssistantUpdate
|
||||
from .service import RESOURCE, SOURCE, backup_age_hours, installable, read_health, read_snapshot
|
||||
from .updates import advance
|
||||
|
||||
if TYPE_CHECKING:
|
||||
from quart import Quart
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
# An update under way is followed each tick, with one small read of its entity.
|
||||
TICK_SECONDS = 15
|
||||
# The whole entity list is a few hundred KB, and updates and backups change rarely.
|
||||
POLL_SECONDS = 300
|
||||
# A step past this is given up until the next tick, whatever the client's own
|
||||
# timeouts did: a slow drip of bytes can keep each read inside its timeout for ever.
|
||||
STEP_DEADLINE_SECONDS = 60
|
||||
|
||||
|
||||
def make_tick_task(app: "Quart") -> ScheduledTask:
|
||||
busy = asyncio.Lock()
|
||||
|
||||
async def tick() -> None:
|
||||
if busy.locked():
|
||||
return
|
||||
async with busy:
|
||||
for step in (poll, advance, schedule.step):
|
||||
try:
|
||||
await asyncio.wait_for(step(app), STEP_DEADLINE_SECONDS)
|
||||
except TimeoutError:
|
||||
logger.warning("Home Assistant %s gave up after %d s", step.__name__, STEP_DEADLINE_SECONDS)
|
||||
|
||||
return ScheduledTask(name="homeassistant_tick", coro_factory=tick,
|
||||
interval_seconds=TICK_SECONDS, run_on_startup=True)
|
||||
|
||||
|
||||
def is_due(connection, now: datetime) -> bool:
|
||||
"""Whether to poll. Never after a refusal: another refused request counts
|
||||
toward Home Assistant banning this address."""
|
||||
if connection.refused:
|
||||
return False
|
||||
if connection.last_polled_at is None:
|
||||
return True
|
||||
return (now - connection.last_polled_at).total_seconds() >= POLL_SECONDS - TICK_SECONDS / 2
|
||||
|
||||
|
||||
async def update_failed(session) -> bool:
|
||||
"""Whether the newest update failed, or the schedule couldn't start one."""
|
||||
stopped = (await session.execute(select(HomeAssistantSchedule.stopped))).scalars().first()
|
||||
newest = (await session.execute(select(HomeAssistantUpdate.state).order_by(
|
||||
HomeAssistantUpdate.started_at.desc()).limit(1))).scalars().first()
|
||||
return bool(stopped) or newest == "failed"
|
||||
|
||||
|
||||
async def poll(app: "Quart", transport=None, connect=None) -> None:
|
||||
from steward.core.alerts import MetricBatch
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
async with app.db_sessionmaker() as session:
|
||||
connection = (await session.execute(select(HomeAssistantConnection))).scalars().first()
|
||||
if connection is None or not is_due(connection, now):
|
||||
return
|
||||
snapshot, health, error, refused = None, None, None, False
|
||||
try:
|
||||
token = await client.access_token(connection, transport)
|
||||
snapshot = read_snapshot(await client.read_states(connection.url, token, connection.verify_tls, transport))
|
||||
try:
|
||||
health = read_health(await client.read_system(connection.url, token, connection.verify_tls, connect))
|
||||
except client.Unreachable as exc:
|
||||
# Updates and backups were read, so it's answering. The last report stands, and says it's old.
|
||||
health = {**(connection.health or {}), "error": str(exc)}
|
||||
except client.Refused as exc:
|
||||
snapshot, error, refused = None, str(exc), True
|
||||
except client.Unreachable as exc:
|
||||
error = str(exc)
|
||||
async with app.db_sessionmaker() as session:
|
||||
async with session.begin():
|
||||
row = await session.get(HomeAssistantConnection, connection.id)
|
||||
if row is None: # removed while it was being polled
|
||||
return
|
||||
batch = MetricBatch()
|
||||
row.last_polled_at, row.last_error, row.refused = now, error, refused
|
||||
if snapshot is None:
|
||||
batch.add(source_module=SOURCE, resource_name=RESOURCE, metric_name="is_up", value=0.0, recorded_at=now)
|
||||
else:
|
||||
row.last_ok_at = now
|
||||
row.updates, row.backup, row.health = snapshot["updates"], snapshot["backup"], health
|
||||
batch.add(source_module=SOURCE, resource_name=RESOURCE, metric_name="is_up", value=1.0, recorded_at=now)
|
||||
batch.add(source_module=SOURCE, resource_name=RESOURCE, metric_name="updates_waiting",
|
||||
value=len(installable(row)), recorded_at=now)
|
||||
age = backup_age_hours(snapshot["backup"], now)
|
||||
if age is not None:
|
||||
batch.add(source_module=SOURCE, resource_name=RESOURCE, metric_name="backup_age_hours",
|
||||
value=age, recorded_at=now)
|
||||
if not health.get("error"):
|
||||
if health["repairs_read"]:
|
||||
batch.add(source_module=SOURCE, resource_name=RESOURCE, metric_name="problems_open",
|
||||
value=len(health["problems"]), recorded_at=now)
|
||||
if health["disk_free_pct"] is not None:
|
||||
batch.add(source_module=SOURCE, resource_name=RESOURCE, metric_name="disk_free_pct",
|
||||
value=health["disk_free_pct"], recorded_at=now)
|
||||
batch.add(source_module=SOURCE, resource_name=RESOURCE, metric_name="update_failed",
|
||||
value=1.0 if await update_failed(session) else 0.0, recorded_at=now)
|
||||
await batch.record(session)
|
||||
@@ -0,0 +1,161 @@
|
||||
# plugins/homeassistant/service.py
|
||||
"""Reading what Home Assistant reports: which updates it knows of, which of them
|
||||
Steward may install, how its backups stand, and whether the system has a problem."""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timezone
|
||||
|
||||
SOURCE = "homeassistant"
|
||||
RESOURCE = "homeassistant"
|
||||
# Backups run daily, so past a day and a bit one has been missed.
|
||||
STALE_BACKUP_HOURS = 26
|
||||
LOW_DISK_PCT = 10
|
||||
|
||||
CORE = "update.home_assistant_core_update"
|
||||
OS = "update.home_assistant_operating_system_update"
|
||||
SUPERVISOR = "update.home_assistant_supervisor_update"
|
||||
LAST_BACKUP = "sensor.backup_last_successful_automatic_backup"
|
||||
NEXT_BACKUP = "sensor.backup_next_scheduled_automatic_backup"
|
||||
BACKUP_MANAGER = "sensor.backup_backup_manager_state"
|
||||
BACKUP_EVENT = "event.backup_automatic_backup"
|
||||
|
||||
_KIND_WORDS = {"core": "Core", "os": "Operating system", "addon": "Add-on"}
|
||||
_KIND_ORDER = {"core": 0, "os": 1, "addon": 2, None: 3}
|
||||
|
||||
def classify(entity: dict) -> str | None:
|
||||
""""core", "os" or "addon" for an update Steward may install; None for the
|
||||
rest: Supervisor updates itself, and firmware and custom integrations are
|
||||
Home Assistant's own to offer."""
|
||||
entity_id = entity.get("entity_id")
|
||||
if entity_id == CORE:
|
||||
return "core"
|
||||
if entity_id == OS:
|
||||
return "os"
|
||||
if entity_id == SUPERVISOR:
|
||||
return None
|
||||
picture = (entity.get("attributes") or {}).get("entity_picture") or ""
|
||||
return "addon" if picture.startswith("/api/hassio/addons/") else None
|
||||
|
||||
|
||||
def _update(entity: dict) -> dict:
|
||||
a = entity.get("attributes") or {}
|
||||
kind = classify(entity)
|
||||
url = a.get("release_url") or ""
|
||||
return {"entity_id": entity["entity_id"], "kind": kind, "kind_word": _KIND_WORDS.get(kind, "Other"),
|
||||
"title": a.get("title") or a.get("friendly_name") or entity["entity_id"],
|
||||
"installed": a.get("installed_version"), "latest": a.get("latest_version"),
|
||||
"waiting": entity.get("state") == "on", "in_progress": bool(a.get("in_progress")),
|
||||
"auto_update": bool(a.get("auto_update")),
|
||||
"release_url": url if url.startswith(("http://", "https://")) else None}
|
||||
|
||||
|
||||
def _state(entity: dict | None) -> str | None:
|
||||
value = (entity or {}).get("state")
|
||||
return None if value in (None, "unknown", "unavailable") else value
|
||||
|
||||
|
||||
def parse_moment(value: str | None) -> datetime | None:
|
||||
try:
|
||||
moment = datetime.fromisoformat(value) if value else None
|
||||
except ValueError:
|
||||
return None
|
||||
if moment is not None and moment.tzinfo is None:
|
||||
moment = moment.replace(tzinfo=timezone.utc)
|
||||
return moment
|
||||
|
||||
|
||||
def is_newer(value: str | None, than: str | None) -> bool:
|
||||
"""Whether reading `value` is a later moment than `than`, where `than` may be never."""
|
||||
moment, before = parse_moment(value), parse_moment(than)
|
||||
return moment is not None and (before is None or moment > before)
|
||||
|
||||
|
||||
def read_snapshot(states: list[dict]) -> dict:
|
||||
"""What a poll keeps of Home Assistant's entities."""
|
||||
by_id = {e.get("entity_id"): e for e in states}
|
||||
updates = [_update(e) for i, e in by_id.items() if (i or "").startswith("update.") and e.get("state") != "unavailable"]
|
||||
updates.sort(key=lambda u: (not u["waiting"], _KIND_ORDER[u["kind"]], u["title"].lower()))
|
||||
event = by_id.get(BACKUP_EVENT) or {}
|
||||
event_attrs = event.get("attributes") or {}
|
||||
return {
|
||||
"updates": updates,
|
||||
"backup": {"last_ok": _state(by_id.get(LAST_BACKUP)), "next": _state(by_id.get(NEXT_BACKUP)),
|
||||
"manager": _state(by_id.get(BACKUP_MANAGER)), "last_result": event_attrs.get("event_type"),
|
||||
"failed_reason": event_attrs.get("failed_reason"), "known": LAST_BACKUP in by_id},
|
||||
}
|
||||
|
||||
|
||||
def backup_age_hours(backup: dict | None, now: datetime) -> float | None:
|
||||
last = parse_moment((backup or {}).get("last_ok"))
|
||||
return None if last is None else max(0.0, (now - last).total_seconds() / 3600)
|
||||
|
||||
|
||||
def installable(connection) -> list[dict]:
|
||||
"""The waiting updates Steward may install."""
|
||||
return [u for u in (connection.updates or []) if u["waiting"] and u["kind"]]
|
||||
|
||||
|
||||
def backup_verdict(backup: dict | None, now: datetime) -> tuple[str, str]:
|
||||
"""(tone, sentence) for how the backups stand."""
|
||||
backup = backup or {}
|
||||
if not backup.get("known"):
|
||||
return "warn", "Home Assistant reports no automatic backups. Turn them on under Settings → System → Backups."
|
||||
age = backup_age_hours(backup, now)
|
||||
if age is None:
|
||||
return "warn", "Home Assistant has no successful automatic backup yet."
|
||||
if backup.get("last_result") == "failed":
|
||||
reason = backup.get("failed_reason")
|
||||
return "warn", f"The newest backup attempt failed{f' ({reason})' if reason else ''}."
|
||||
if age > STALE_BACKUP_HOURS:
|
||||
return "warn", f"The last good backup is {age:.0f} hours old, past the {STALE_BACKUP_HOURS} hours expected."
|
||||
return "ok", "Backups are up to date."
|
||||
|
||||
|
||||
def _issue_title(issue: dict, titles: dict) -> str:
|
||||
key = issue.get("translation_key") or issue.get("issue_id") or ""
|
||||
title = titles.get(f"component.{issue.get('domain')}.issues.{key}.title")
|
||||
if not title:
|
||||
return key.removeprefix("issue_").replace("_", " ").capitalize() or "A repair is open"
|
||||
for name, value in (issue.get("translation_placeholders") or {}).items():
|
||||
title = title.replace("{" + name + "}", str(value))
|
||||
return title
|
||||
|
||||
|
||||
def read_health(found: dict) -> dict:
|
||||
"""What a poll keeps of client.read_system: the problems to show, and the disk.
|
||||
A part Home Assistant wouldn't answer is left out rather than read as fine:
|
||||
`repairs_read` says whether the repairs were seen, and `supervised` whether a
|
||||
Supervisor answered, as it doesn't on every install or for every user."""
|
||||
problems = []
|
||||
if (found.get("config") or {}).get("recovery_mode"):
|
||||
problems.append({"kind": "recovery", "severity": "critical",
|
||||
"title": "Home Assistant started in recovery mode: its configuration didn't load."})
|
||||
issues = found.get("issues")
|
||||
for issue in issues or []:
|
||||
if not issue.get("ignored") and not issue.get("dismissed_version"):
|
||||
problems.append({"kind": "repair", "severity": issue.get("severity") or "warning",
|
||||
"title": _issue_title(issue, found.get("titles") or {})})
|
||||
resolution = found.get("resolution") or {}
|
||||
for word in ("unhealthy", "unsupported"):
|
||||
for reason in resolution.get(word) or []:
|
||||
problems.append({"kind": "supervisor", "severity": "error" if word == "unhealthy" else "warning",
|
||||
"title": f"The Supervisor calls this system {word}: {str(reason).replace('_', ' ')}."})
|
||||
host = found.get("host") or {}
|
||||
free, used, total = host.get("disk_free"), host.get("disk_used"), host.get("disk_total")
|
||||
free_pct = round(100 * free / total, 1) if free is not None and total else None
|
||||
# Used and free don't add up to the total: the system reserves some of the disk.
|
||||
used_pct = round(100 * used / total, 1) if used is not None and total else None
|
||||
if free_pct is not None and free_pct < LOW_DISK_PCT:
|
||||
problems.append({"kind": "disk", "severity": "error", "title": f"Only {free:g} GB of {total:g} GB free."})
|
||||
boots = found.get("boots") or {}
|
||||
for addon in found.get("addons") or []:
|
||||
if boots.get(addon.get("slug")) == "auto":
|
||||
problems.append({"kind": "addon", "severity": "error",
|
||||
"title": f"{addon.get('name') or addon.get('slug')} should start on its own and isn't running."})
|
||||
return {"repairs_read": issues is not None, "supervised": found.get("resolution") is not None, "problems": problems,
|
||||
"disk_free_gb": free, "disk_used_gb": used, "disk_total_gb": total,
|
||||
"disk_free_pct": free_pct, "disk_used_pct": used_pct}
|
||||
|
||||
|
||||
def problems_open(health: dict | None) -> list[dict]:
|
||||
return (health or {}).get("problems") or []
|
||||
@@ -0,0 +1,50 @@
|
||||
{# plugins/homeassistant/templates/homeassistant/form.html — where Home Assistant
|
||||
is, what signing in gives Steward, and leaving for its sign-in page. #}
|
||||
{% extends "base.html" %}
|
||||
{% from "_macros.html" import crumbs, page_header %}
|
||||
{% block title %}Home Assistant connection — Steward{% endblock %}
|
||||
{% block breadcrumb %}{{ crumbs([("Home Assistant", "/plugins/homeassistant/"), ("Connection", "")]) }}{% endblock %}
|
||||
{% block content %}
|
||||
{{ page_header("Home Assistant connection") }}
|
||||
|
||||
<div class="form-page">
|
||||
{% if error %}<p class="field-error" role="alert">{{ error }}</p>{% endif %}
|
||||
{% if connection %}
|
||||
<p class="field-hint">Signed in{% if connection.signed_in_at %} {{ connection.signed_in_at|ago }}{% endif %}{% if connection.signed_in_by %} by {{ connection.signed_in_by }}{% endif %}, as {{ "an administrator: Steward can install updates" if connection.can_install else "a user who isn't an administrator: Steward shows status only" }}.</p>
|
||||
{% endif %}
|
||||
<form method="post" action="/plugins/homeassistant/connection/sign-in">{{ csrf_field() }}
|
||||
<section class="card form-section" aria-labelledby="ha-sign-in">
|
||||
<h2 id="ha-sign-in" class="section-title">Sign in with Home Assistant</h2>
|
||||
<div class="field">
|
||||
<label class="field-label" for="ha-url">Address</label>
|
||||
<input class="input mono" id="ha-url" name="url" required maxlength="500" value="{{ url or '' }}" placeholder="http://homeassistant.local:8123" autocomplete="off">
|
||||
<span class="field-hint">Both your browser and Steward need to reach it at this address.</span>
|
||||
</div>
|
||||
<label style="display:flex;gap:0.5rem;align-items:center;cursor:pointer;margin-bottom:0.9rem;">
|
||||
<input type="checkbox" name="verify_tls" value="on"{% if verify_tls %} checked{% endif %}> Check its HTTPS certificate
|
||||
</label>
|
||||
<p class="tone-warn"><strong>Steward stores a credential with the same access as the user who signs in.</strong> Home Assistant has no narrower permission, so an administrator's credential can do anything that administrator can, including controlling every device. Steward only uses it to read status, take backups and install updates.</p>
|
||||
<p class="field-hint"><strong>We recommend a service account:</strong> a Home Assistant user made just for Steward (Settings → People → Add person). What Steward does then appears under its own name in Home Assistant's logs, so it's easy to tell apart from what people do.</p>
|
||||
<p class="field-hint" style="margin-bottom:0;">Installing updates needs an administrator. With any other user, Steward shows status only.</p>
|
||||
</section>
|
||||
|
||||
<div class="form-actions">
|
||||
<button type="submit" class="btn">{{ "Sign in again" if connection else "Continue to Home Assistant" }}</button>
|
||||
<a href="/plugins/homeassistant/" class="btn btn-ghost">Cancel</a>
|
||||
</div>
|
||||
</form>
|
||||
|
||||
{% if connection %}
|
||||
<section class="card danger-zone" aria-labelledby="ha-remove">
|
||||
<div>
|
||||
<h2 id="ha-remove" class="section-title">Remove this connection</h2>
|
||||
<p class="field-hint">Steward stops reading Home Assistant, forgets its credential and ends the sign-in there.</p>
|
||||
</div>
|
||||
<form method="post" action="/plugins/homeassistant/connection/delete"
|
||||
data-confirm="Remove the Home Assistant connection? Steward stops reading it and forgets its credential.">{{ csrf_field() }}
|
||||
<button class="btn btn-danger" type="submit">Remove connection</button>
|
||||
</form>
|
||||
</section>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,150 @@
|
||||
{# plugins/homeassistant/templates/homeassistant/index.html — whether Home
|
||||
Assistant answers, which updates are waiting with Install beside each, how its
|
||||
backups stand, and the updates Steward has run. Refreshes itself while one is
|
||||
under way. #}
|
||||
{% extends "base.html" %}
|
||||
{% from "_macros.html" import page_header, status_badge, stat_tile, empty_state %}
|
||||
{% block title %}Home Assistant — Steward{% endblock %}
|
||||
{% block content %}
|
||||
{% set admin = session.user_role == 'admin' %}
|
||||
{% call page_header("Home Assistant", connection.url if connection else none) %}
|
||||
{% if admin and connection %}<a class="btn btn-sm btn-ghost" href="/plugins/homeassistant/connection">Connection</a>{% endif %}
|
||||
{% endcall %}
|
||||
|
||||
{% if not connection %}
|
||||
{% if error %}<p class="field-error" role="alert">{{ error }}</p>{% endif %}
|
||||
<div class="card">{{ empty_state("Not connected. Sign in to a Home Assistant instance to see its waiting updates and backups, and to install updates after a confirmed backup.",
|
||||
"Connect" if admin else none, "/plugins/homeassistant/connection") }}</div>
|
||||
{% else %}
|
||||
{% if error %}<p class="field-error" role="alert">{{ error }}</p>{% endif %}
|
||||
<div id="ha-body"{% if under_way %} hx-get="/plugins/homeassistant/" hx-select="#ha-body" hx-trigger="every 15s" hx-swap="outerHTML"{% endif %}>
|
||||
<p class="page-verdict">
|
||||
{% if under_way %}{{ status_badge('pending', 'Updating') }}
|
||||
{{ under_way.title }}: {{ {'backing_up': "taking a backup first", 'rebooting': "rebooting into " ~ under_way.to_version}.get(under_way.state, "installing " ~ under_way.to_version) }}. Home Assistant may stop answering for a while.
|
||||
{% elif reach == 'up' %}{{ status_badge('up', 'Answering') }}
|
||||
{% if installable %}{{ installable|length }} update{{ "s" if installable|length != 1 }} waiting.{% else %}Everything Steward can update is up to date.{% endif %}
|
||||
Read {{ connection.last_polled_at|ago }}.
|
||||
{% elif reach == 'down' %}{{ status_badge('down', 'Not answering') }} <span class="tone-crit">{{ says }}</span>
|
||||
{% if connection.last_ok_at %}Last answered {{ connection.last_ok_at|ago }}; what's below is from then.{% endif %}
|
||||
{% if admin and connection.refused %}<form method="post" action="/plugins/homeassistant/connection/retry" style="display:inline;">{{ csrf_field() }}<button class="btn btn-sm btn-ghost" type="submit">Try again</button></form>{% endif %}
|
||||
{% else %}{{ status_badge('pending', 'Not read yet') }} {{ says }}{% endif %}
|
||||
</p>
|
||||
|
||||
{% if not connection.can_install %}
|
||||
<p class="tone-warn">The Home Assistant user who signed in isn't an administrator, so updates can't be installed from here.
|
||||
{% if admin %}<a href="/plugins/homeassistant/connection">Sign in again</a> as an administrator to install them.{% endif %}</p>
|
||||
{% endif %}
|
||||
|
||||
<div class="stat-strip">
|
||||
{{ stat_tile("System problems", problems|length if health.repairs_read else "—", state="degraded" if problems else none) }}
|
||||
{{ stat_tile("Storage", ("%s of %s GB (%.0f%%)"|format(health.disk_used_gb, health.disk_total_gb, health.disk_used_pct)) if health.disk_used_pct is number else "—") }}
|
||||
{{ stat_tile("Updates waiting", installable|length if connection.last_ok_at else "—") }}
|
||||
{{ stat_tile("Last good backup", (backup_at|ago) if backup_at else "—", state="degraded" if backup_tone == 'warn' else none) }}
|
||||
{{ stat_tile("Next backup", (backup_next|ago) if backup_next else "—") }}
|
||||
</div>
|
||||
<p class="{{ 'tone-warn' if backup_tone == 'warn' else 'field-hint' }}">{{ backup_says }}</p>
|
||||
|
||||
<section class="card" aria-labelledby="ha-system">
|
||||
<h2 id="ha-system" class="section-title">System</h2>
|
||||
{% if problems %}
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">Problem</th><th scope="col">Severity</th></tr></thead>
|
||||
<tbody>
|
||||
{% for p in problems %}<tr><td>{{ p.title }}</td><td>{{ status_badge('down' if p.severity in ('critical', 'error') else 'degraded', p.severity|capitalize) }}</td></tr>{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
<p class="field-hint">Fix these in Home Assistant: Settings → System → Repairs.</p>
|
||||
{% elif health.repairs_read %}
|
||||
<p class="field-hint">No repairs open, and nothing wrong reported.</p>
|
||||
{% elif connection.last_ok_at %}
|
||||
<p class="tone-warn">Home Assistant wouldn't share its repairs with this user. {% if admin %}<a href="/plugins/homeassistant/connection">Sign in again</a> as an administrator to see them.{% endif %}</p>
|
||||
{% endif %}
|
||||
{% if health.repairs_read and not health.supervised %}<p class="field-hint">No Supervisor answered, so disk space and add-ons aren't checked here.</p>{% endif %}
|
||||
{% if health.error %}<p class="tone-warn" style="margin-bottom:0;">This is from an earlier read. {{ health.error }}</p>{% endif %}
|
||||
</section>
|
||||
|
||||
<section class="card" aria-labelledby="ha-updates">
|
||||
<h2 id="ha-updates" class="section-title">Updates</h2>
|
||||
{% if installable %}
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">What</th><th scope="col">Now</th><th scope="col">New</th>{% if admin %}<th scope="col"></th>{% endif %}</tr></thead>
|
||||
<tbody>
|
||||
{% for u in installable %}
|
||||
<tr>
|
||||
<td>{{ u.title }}<div class="cell-sub">{{ u.kind_word }}{% if u.auto_update %}, updates itself{% endif %}</div></td>
|
||||
<td class="mono">{{ u.installed or "—" }}</td>
|
||||
<td class="mono">{% if u.release_url %}<a href="{{ u.release_url }}" rel="noopener noreferrer" target="_blank">{{ u.latest or "—" }}</a>{% else %}{{ u.latest or "—" }}{% endif %}</td>
|
||||
{% if admin %}<td style="text-align:right;">
|
||||
{% if connection.can_install and not under_way and not connection.refused and not u.in_progress %}
|
||||
<form method="post" action="/plugins/homeassistant/install"
|
||||
data-confirm="Install {{ u.title }} {{ u.latest }}? Steward takes a backup first and won't install without it. {{ 'Home Assistant restarts.' if u.kind == 'core' else ('It takes effect once you reboot the machine, which Steward leaves to you.' if u.kind == 'os' else 'The add-on restarts.') }}">{{ csrf_field() }}
|
||||
<input type="hidden" name="entity_id" value="{{ u.entity_id }}">
|
||||
<button class="btn btn-sm" type="submit">Install</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</td>{% endif %}
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
{% else %}
|
||||
<p class="field-hint" style="margin:0;">Nothing waiting.</p>
|
||||
{% endif %}
|
||||
{% if current %}<p class="field-hint">Up to date: {% for u in current %}{{ u.title }} {{ u.installed }}{{ ", " if not loop.last }}{% endfor %}.</p>{% endif %}
|
||||
{% if others %}<p class="field-hint" style="margin-bottom:0;">Waiting, for Home Assistant to install: {% for u in others %}{{ u.title }}{{ ", " if not loop.last }}{% endfor %}. Steward installs Core, OS and add-on updates only.</p>{% endif %}
|
||||
</section>
|
||||
|
||||
<section class="card" aria-labelledby="ha-schedule">
|
||||
<h2 id="ha-schedule" class="section-title">Scheduled updates</h2>
|
||||
{% if plan and plan.enabled %}
|
||||
<p class="field-hint">{{ plan_when }}. Next: {{ plan_next|ago }}. Add-ons first, then Core, then the OS and its reboot, each after a confirmed backup. A failure ends the run and the rest wait.</p>
|
||||
{% else %}
|
||||
<p class="field-hint">Off. Updates are only installed when someone chooses Install.</p>
|
||||
{% endif %}
|
||||
{% if plan and plan.stopped %}<p class="tone-warn">The last run stopped early. {{ plan.stopped }}</p>{% endif %}
|
||||
{% if admin %}
|
||||
<p class="tone-warn">A Core update restarts Home Assistant and an OS update reboots the machine, with nobody there to watch. An update can also change how automations behave.</p>
|
||||
<form method="post" action="/plugins/homeassistant/schedule" style="display:flex;flex-wrap:wrap;gap:0.75rem;align-items:flex-end;">{{ csrf_field() }}
|
||||
<label style="display:flex;gap:0.5rem;align-items:center;cursor:pointer;margin-bottom:0.4rem;">
|
||||
<input type="checkbox" name="enabled" value="on"{% if plan and plan.enabled %} checked{% endif %}> Install on a schedule
|
||||
</label>
|
||||
<div class="field" style="margin-bottom:0;">
|
||||
<label class="field-label" for="ha-day">Day</label>
|
||||
<select class="input" id="ha-day" name="weekday">{% for d in weekdays %}<option value="{{ loop.index0 }}"{% if loop.index0 == (plan.weekday if plan else 5) %} selected{% endif %}>{{ d }}</option>{% endfor %}</select>
|
||||
</div>
|
||||
<div class="field" style="margin-bottom:0;">
|
||||
<label class="field-label" for="ha-time">Time</label>
|
||||
<input class="input" id="ha-time" type="time" name="at_time" required value="{{ plan.at_time if plan else '05:00' }}">
|
||||
</div>
|
||||
<div class="field" style="margin-bottom:0;">
|
||||
<label class="field-label" for="ha-zone">Time zone</label>
|
||||
<input class="input" id="ha-zone" name="time_zone" required value="{{ plan.time_zone if plan else default_zone }}">
|
||||
</div>
|
||||
<button class="btn btn-sm" type="submit">Save</button>
|
||||
</form>
|
||||
{% endif %}
|
||||
</section>
|
||||
|
||||
{% if runs %}
|
||||
<section class="card" aria-labelledby="ha-runs">
|
||||
<h2 id="ha-runs" class="section-title">Updates run from Steward</h2>
|
||||
<table class="table">
|
||||
<thead><tr><th scope="col">What</th><th scope="col">Versions</th><th scope="col">Outcome</th><th scope="col">Started</th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in runs %}
|
||||
<tr>
|
||||
<td>{{ r.title }}<div class="cell-sub">by {{ r.started_by or "Steward" }}</div></td>
|
||||
<td class="mono">{{ r.from_version or "—" }} → {{ r.to_version or "—" }}</td>
|
||||
<td>{% if r.state == 'done' %}{{ status_badge('up', 'Done') }}
|
||||
{% elif r.state == 'failed' %}{{ status_badge('down', 'Failed') }}<div class="cell-sub">{{ r.message }}</div>
|
||||
{% else %}{{ status_badge('pending', {'backing_up': 'Taking a backup', 'rebooting': 'Rebooting'}.get(r.state, 'Installing')) }}{% endif %}</td>
|
||||
<td>{{ r.started_at|ago }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
</tbody>
|
||||
</table>
|
||||
</section>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
{% endblock %}
|
||||
@@ -0,0 +1,34 @@
|
||||
# plugins/homeassistant/timeline.py
|
||||
"""What Home Assistant maintenance puts on the timeline: each update once it ends."""
|
||||
from __future__ import annotations
|
||||
|
||||
from steward.timeline import catalog
|
||||
from steward.timeline.record import record_or_update
|
||||
|
||||
TYPES = (
|
||||
("homeassistant.updated", "Home Assistant updated", "automation", "service", True,
|
||||
"Steward installed a Home Assistant update after a confirmed backup."),
|
||||
("homeassistant.update_failed", "Home Assistant update failed", "automation", "service", True,
|
||||
"A Home Assistant update Steward was asked to install didn't finish."),
|
||||
)
|
||||
|
||||
|
||||
def register() -> None:
|
||||
for t in TYPES:
|
||||
catalog.register_type(*t)
|
||||
from .models import HomeAssistantUpdate
|
||||
catalog.register_ref("homeassistant_update", HomeAssistantUpdate)
|
||||
|
||||
|
||||
async def update_entry(session, run) -> None:
|
||||
done = run.state == "done"
|
||||
versions = f"{run.from_version} to {run.to_version}" if run.to_version else "a new version"
|
||||
summary = (f"{run.title} updated from {versions}" if done
|
||||
else f"{run.title} update failed: {run.message}")
|
||||
await record_or_update(
|
||||
session, ("homeassistant_update", run.id),
|
||||
type="homeassistant.updated" if done else "homeassistant.update_failed",
|
||||
at=run.started_at, until=run.finished_at, summary=summary, subject=run.title,
|
||||
detail={"entity_id": run.entity_id, "from": run.from_version, "to": run.to_version,
|
||||
"url": "/plugins/homeassistant/"},
|
||||
actor=run.started_by or "Steward")
|
||||
@@ -0,0 +1,259 @@
|
||||
# plugins/homeassistant/updates.py
|
||||
"""Installing one update: take a backup, confirm it landed, install, and follow
|
||||
it to its end. Its row holds where it has got to, so Steward restarting, or Home
|
||||
Assistant restarting as an update does, only delays the next step."""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from sqlalchemy import select
|
||||
from sqlalchemy.exc import IntegrityError
|
||||
|
||||
from . import client
|
||||
from .models import HomeAssistantConnection, HomeAssistantUpdate
|
||||
from .service import BACKUP_EVENT, LAST_BACKUP, is_newer, parse_moment
|
||||
from .timeline import update_entry
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
UNDER_WAY = ("backing_up", "installing", "rebooting")
|
||||
BACKUP_DEADLINE_S = 30 * 60
|
||||
REBOOT_DEADLINE_S = 20 * 60
|
||||
# An OS update downloads and writes a whole system image, which is slow on a Pi. Home
|
||||
# Assistant reports the new version as soon as that's written, before the reboot that
|
||||
# makes it run, and raises a repair asking for that reboot. The schedule's own OS
|
||||
# updates make that reboot; one started by a person leaves it to them.
|
||||
INSTALL_DEADLINE_S = {"addon": 20 * 60, "core": 30 * 60, "os": 45 * 60}
|
||||
|
||||
|
||||
class CannotStart(Exception):
|
||||
"""Why an update wasn't started, said to the person."""
|
||||
|
||||
|
||||
async def _mark_refused(app, connection_id: str, said: str) -> None:
|
||||
async with app.db_sessionmaker() as session:
|
||||
async with session.begin():
|
||||
row = await session.get(HomeAssistantConnection, connection_id)
|
||||
if row is not None:
|
||||
row.refused, row.last_error = True, said
|
||||
|
||||
|
||||
async def under_way(session) -> HomeAssistantUpdate | None:
|
||||
return (await session.execute(select(HomeAssistantUpdate).where(
|
||||
HomeAssistantUpdate.state.in_(UNDER_WAY)))).scalars().first()
|
||||
|
||||
|
||||
async def start_update(app, entity_id: str, username: str, transport=None, *, reboot_after: bool = False) -> HomeAssistantUpdate:
|
||||
"""Start installing `entity_id`, an explicit action that may contact Home
|
||||
Assistant. Raises CannotStart, with nothing started, unless the update is
|
||||
still waiting and the signed-in user may install it. `reboot_after` reboots
|
||||
the machine once it's written, and it's done when the new version is running."""
|
||||
async with app.db_sessionmaker() as session:
|
||||
connection = (await session.execute(select(HomeAssistantConnection))).scalars().first()
|
||||
if connection is None:
|
||||
raise CannotStart("Home Assistant isn't connected")
|
||||
if connection.refused:
|
||||
raise CannotStart("Home Assistant refused Steward's sign-in")
|
||||
if await under_way(session) is not None:
|
||||
raise CannotStart("another update is under way")
|
||||
if not connection.can_install:
|
||||
raise CannotStart("the Home Assistant user who signed in isn't an administrator")
|
||||
url, verify = connection.url, connection.verify_tls
|
||||
known = next((u for u in connection.updates or [] if u["entity_id"] == entity_id), None)
|
||||
if known is None or not known["kind"]:
|
||||
raise CannotStart("that isn't a Core, OS or add-on update")
|
||||
try:
|
||||
token = await client.access_token(connection, transport)
|
||||
current = await client.read_state(url, entity_id, token, verify, transport)
|
||||
backup = await client.read_state(url, LAST_BACKUP, token, verify, transport)
|
||||
event = await client.read_state(url, BACKUP_EVENT, token, verify, transport)
|
||||
except client.Refused as exc:
|
||||
await _mark_refused(app, connection.id, str(exc))
|
||||
raise CannotStart(str(exc).rstrip(".")) from None
|
||||
except client.Unreachable as exc:
|
||||
raise CannotStart(str(exc).rstrip(".")) from None
|
||||
if backup is None:
|
||||
raise CannotStart("Home Assistant has no automatic backups to confirm one with")
|
||||
if current is None or current.get("state") != "on":
|
||||
raise CannotStart("that update is no longer waiting")
|
||||
attrs = current.get("attributes") or {}
|
||||
run = HomeAssistantUpdate(
|
||||
entity_id=entity_id, title=known["title"], kind=known["kind"],
|
||||
from_version=attrs.get("installed_version"), to_version=attrs.get("latest_version"),
|
||||
started_by=username, backup_before=backup.get("state"),
|
||||
backup_event_before=(event or {}).get("state"), reboot_after=reboot_after)
|
||||
async with app.db_sessionmaker() as session:
|
||||
try:
|
||||
async with session.begin():
|
||||
session.add(run)
|
||||
await session.flush()
|
||||
run_id = run.id
|
||||
except IntegrityError:
|
||||
raise CannotStart("another update is under way") from None
|
||||
try:
|
||||
await client.call_action(url, "backup", "create_automatic", {}, token, verify, transport)
|
||||
except client.Refused as exc:
|
||||
await _mark_refused(app, connection.id, str(exc))
|
||||
await _finish(app, run_id, "failed", f"The backup couldn't be started: {exc} Nothing was installed.")
|
||||
raise CannotStart(str(exc).rstrip(".")) from None
|
||||
except (client.Unreachable, client.Rejected) as exc:
|
||||
await _finish(app, run_id, "failed", f"The backup couldn't be started: {exc} Nothing was installed.")
|
||||
raise CannotStart(str(exc).rstrip(".")) from None
|
||||
async with app.db_sessionmaker() as session:
|
||||
return await session.get(HomeAssistantUpdate, run_id)
|
||||
|
||||
|
||||
async def _finish(app, run_id: str, state: str, message: str | None) -> None:
|
||||
async with app.db_sessionmaker() as session:
|
||||
async with session.begin():
|
||||
run = await session.get(HomeAssistantUpdate, run_id)
|
||||
run.state, run.message, run.finished_at = state, message, datetime.now(timezone.utc)
|
||||
# The page should show the new versions now, not at the next poll.
|
||||
connection = (await session.execute(select(HomeAssistantConnection))).scalars().first()
|
||||
if connection is not None:
|
||||
connection.last_polled_at = None
|
||||
try:
|
||||
async with session.begin_nested():
|
||||
await update_entry(session, run)
|
||||
except Exception:
|
||||
logger.exception("Home Assistant update %s: its timeline entry could not be written", run_id)
|
||||
|
||||
|
||||
async def advance(app, transport=None, connect=None) -> None:
|
||||
"""Move the update under way one step on, if there is one."""
|
||||
async with app.db_sessionmaker() as session:
|
||||
run = await under_way(session)
|
||||
connection = (await session.execute(select(HomeAssistantConnection))).scalars().first()
|
||||
if run is None:
|
||||
return
|
||||
if connection is None:
|
||||
await _finish(app, run.id, "failed", "The Home Assistant connection was removed.")
|
||||
return
|
||||
try:
|
||||
if run.state == "backing_up":
|
||||
await _advance_backup(app, run, connection, transport)
|
||||
elif run.state == "installing":
|
||||
await _advance_install(app, run, connection, transport)
|
||||
else:
|
||||
await _advance_reboot(app, run, connection, transport, connect)
|
||||
except client.Refused as exc:
|
||||
await _mark_refused(app, connection.id, str(exc))
|
||||
await _finish(app, run.id, "failed", str(exc))
|
||||
except client.Rejected as exc:
|
||||
await _finish(app, run.id, "failed", f"Home Assistant wouldn't install it: {exc}")
|
||||
except client.Unreachable as exc:
|
||||
# Expected while Home Assistant restarts: the next tick asks again.
|
||||
logger.info("Home Assistant update %s: %s", run.id, exc)
|
||||
await _past_deadline(app, run)
|
||||
|
||||
|
||||
def _elapsed(since: datetime) -> float:
|
||||
return (datetime.now(timezone.utc) - since).total_seconds()
|
||||
|
||||
|
||||
async def _past_deadline(app, run) -> bool:
|
||||
if run.state == "backing_up" and _elapsed(run.started_at) > BACKUP_DEADLINE_S:
|
||||
await _finish(app, run.id, "failed",
|
||||
f"No new backup within {BACKUP_DEADLINE_S // 60} minutes. Nothing was installed.")
|
||||
return True
|
||||
if run.state == "installing":
|
||||
limit = INSTALL_DEADLINE_S.get(run.kind, INSTALL_DEADLINE_S["os"])
|
||||
if _elapsed(run.install_sent_at or run.backup_at or run.started_at) > limit:
|
||||
await _finish(app, run.id, "failed",
|
||||
f"Still not on {run.to_version} after {limit // 60} minutes. Look in Home Assistant.")
|
||||
return True
|
||||
if run.state == "rebooting" and _elapsed(run.reboot_sent_at or run.install_sent_at or run.started_at) > REBOOT_DEADLINE_S:
|
||||
await _finish(app, run.id, "failed", f"{run.to_version} was installed, but isn't running "
|
||||
f"{REBOOT_DEADLINE_S // 60} minutes after the reboot. Look in Home Assistant.")
|
||||
return True
|
||||
return False
|
||||
|
||||
|
||||
async def _advance_backup(app, run, connection, transport) -> None:
|
||||
token = await client.access_token(connection, transport)
|
||||
url, verify = connection.url, connection.verify_tls
|
||||
backup = await client.read_state(url, LAST_BACKUP, token, verify, transport)
|
||||
value = (backup or {}).get("state")
|
||||
if is_newer(value, run.backup_before):
|
||||
async with app.db_sessionmaker() as session:
|
||||
async with session.begin():
|
||||
row = await session.get(HomeAssistantUpdate, run.id)
|
||||
row.state, row.backup_at = "installing", parse_moment(value)
|
||||
return
|
||||
event = await client.read_state(url, BACKUP_EVENT, token, verify, transport)
|
||||
if event and event.get("state") != run.backup_event_before \
|
||||
and (event.get("attributes") or {}).get("event_type") == "failed":
|
||||
reason = (event.get("attributes") or {}).get("failed_reason")
|
||||
await _finish(app, run.id, "failed",
|
||||
f"The backup failed{f' ({reason})' if reason else ''}. Nothing was installed.")
|
||||
return
|
||||
await _past_deadline(app, run)
|
||||
|
||||
|
||||
async def _mark_sent(app, run_id: str, at: datetime | None) -> None:
|
||||
async with app.db_sessionmaker() as session:
|
||||
async with session.begin():
|
||||
row = await session.get(HomeAssistantUpdate, run_id)
|
||||
row.install_sent_at = at
|
||||
|
||||
|
||||
async def _advance_install(app, run, connection, transport) -> None:
|
||||
token = await client.access_token(connection, transport)
|
||||
url, verify = connection.url, connection.verify_tls
|
||||
if run.install_sent_at is None:
|
||||
# Marked first: Steward stopping here leaves an install that runs out its
|
||||
# deadline, where asking twice would fail one that is going fine.
|
||||
await _mark_sent(app, run.id, datetime.now(timezone.utc))
|
||||
try:
|
||||
await client.call_action(url, "update", "install", {"entity_id": run.entity_id}, token, verify, transport)
|
||||
except client.Unreachable:
|
||||
await _mark_sent(app, run.id, None)
|
||||
raise
|
||||
return
|
||||
current = await client.read_state(url, run.entity_id, token, verify, transport)
|
||||
attrs = (current or {}).get("attributes") or {}
|
||||
installed = attrs.get("installed_version")
|
||||
if installed and (installed == run.to_version
|
||||
or (current.get("state") == "off" and installed != run.from_version)):
|
||||
if run.reboot_after:
|
||||
async with app.db_sessionmaker() as session:
|
||||
async with session.begin():
|
||||
row = await session.get(HomeAssistantUpdate, run.id)
|
||||
row.state = "rebooting"
|
||||
return
|
||||
await _finish(app, run.id, "done", None)
|
||||
return
|
||||
await _past_deadline(app, run)
|
||||
|
||||
|
||||
async def _mark_reboot_sent(app, run_id: str, at: datetime | None) -> None:
|
||||
async with app.db_sessionmaker() as session:
|
||||
async with session.begin():
|
||||
row = await session.get(HomeAssistantUpdate, run_id)
|
||||
row.reboot_sent_at = at
|
||||
|
||||
|
||||
async def _advance_reboot(app, run, connection, transport, connect) -> None:
|
||||
"""Reboot once, and wait for the new version to be what's running. The version
|
||||
is judged against the old one, so a machine that fell back to it fails at the
|
||||
deadline, as does one that never comes back."""
|
||||
token = await client.access_token(connection, transport)
|
||||
url, verify = connection.url, connection.verify_tls
|
||||
if run.reboot_sent_at is None:
|
||||
await _mark_reboot_sent(app, run.id, datetime.now(timezone.utc))
|
||||
try:
|
||||
await client.call_action(url, "hassio", "host_reboot", {}, token, verify, transport)
|
||||
except client.Unreachable:
|
||||
await _mark_reboot_sent(app, run.id, None)
|
||||
await _past_deadline(app, run)
|
||||
return
|
||||
except client.Rejected as exc:
|
||||
await _finish(app, run.id, "failed", f"{run.to_version} was installed, but Home Assistant "
|
||||
f"wouldn't reboot: {exc} It needs a reboot to take effect.")
|
||||
return
|
||||
found = await client.read_os(url, token, verify, connect)
|
||||
if found and found.get("version") not in (None, run.from_version) and not found.get("version_pending"):
|
||||
await _finish(app, run.id, "done", None)
|
||||
return
|
||||
await _past_deadline(app, run)
|
||||
@@ -25,6 +25,14 @@ def setup(app: "Quart") -> None:
|
||||
from steward.hosts.service import agent_stale_after_seconds
|
||||
agent_heartbeat("host_agent", "seconds_since_seen", lambda: agent_stale_after_seconds(app.config))
|
||||
agent_fed("host_agent", lambda resource: resource.split(":", 1)[0])
|
||||
# temp_c_max stands for one of many sensors: its alert says which.
|
||||
from steward.core.alerts import names_behind
|
||||
from .routes import name_hottest_sensor
|
||||
names_behind("host_agent", "temp_c_max", name_hottest_sensor)
|
||||
# get_host over MCP marks the sensors the host's temperature leaves out.
|
||||
from steward.mcp.tools.hosts import judge_sensors
|
||||
from .routes import split_temps
|
||||
judge_sensors(lambda host, temps: {k: why for k, (_c, why) in split_temps(host, temps)[1].items()})
|
||||
# A reboot the agent announced is silence with a reason, for a while (#5756).
|
||||
from datetime import datetime, timezone
|
||||
from steward.core.alerts import agents_away
|
||||
@@ -34,6 +42,9 @@ def setup(app: "Quart") -> None:
|
||||
from steward.core.cleanup import prune_by_age
|
||||
from .models import HostDowntime
|
||||
prune_by_age(HostDowntime.started_at)
|
||||
# Maintenance runs and the stretches a host was away go on the timeline.
|
||||
from .timeline import register as register_timeline
|
||||
register_timeline()
|
||||
|
||||
|
||||
def get_audit_entities() -> dict:
|
||||
@@ -62,6 +73,11 @@ async def mcp_overview(db) -> list[dict]:
|
||||
return await findings(db)
|
||||
|
||||
|
||||
async def timeline_backfill(session, since) -> list:
|
||||
from .timeline import backfill
|
||||
return await backfill(session, since)
|
||||
|
||||
|
||||
def get_alert_metrics() -> dict[str, list[str]]:
|
||||
"""Host metrics ingest records for alert rules (resource = the host name;
|
||||
disk_used_pct per mount, resource "<host>:<mount>"). seconds_since_seen
|
||||
@@ -86,6 +102,17 @@ def get_alert_metrics() -> dict[str, list[str]]:
|
||||
the whole host ("<host>") or one interface ("<host>:net:<iface>") or disk
|
||||
("<host>:diskio:<device>").
|
||||
|
||||
NFS delay (agent ≥ 1.22.0, #5996), per NFS mount on "<host>:<mount>",
|
||||
over the requests it finished since the last sample: nfs_exe_ms is the
|
||||
average time a program waited on one (queueing included), nfs_rtt_ms the
|
||||
server's round trip, nfs_read_ms / nfs_write_ms the same for reads and
|
||||
writes alone, nfs_ops_per_sec how many, and nfs_retrans / nfs_timeouts the
|
||||
retransmissions and major timeouts among them; nfs_tx_bps / nfs_rx_bps
|
||||
(agent ≥ 1.25.0, #6115) are the bytes a second it sent and received, its
|
||||
share of the host's network traffic. nfs_exe_max_ms is the
|
||||
host's slowest mount, for a covering rule: "NFS slow" is > 1000 for 3
|
||||
checks. A healthy share answers in a few ms.
|
||||
|
||||
Drive health (agent ≥ 1.20.0, #5789), read hourly with smartctl by the
|
||||
root helper and judged in drives.py, per drive on "<host>:drive:<device>":
|
||||
drive_failing is 1 when the drive fails its own self-assessment, raises
|
||||
@@ -110,6 +137,8 @@ def get_alert_metrics() -> dict[str, list[str]]:
|
||||
"agent_rss_bytes", "agent_cpu_pct",
|
||||
"updates_pending", "updates_security", "reboot_required", "maintenance_failed",
|
||||
"temp_c_max", "temp_c", "net_rx_bps", "net_tx_bps", "disk_read_bps", "disk_write_bps",
|
||||
"nfs_exe_max_ms", "nfs_exe_ms", "nfs_rtt_ms", "nfs_read_ms", "nfs_write_ms",
|
||||
"nfs_ops_per_sec", "nfs_retrans", "nfs_timeouts", "nfs_tx_bps", "nfs_rx_bps",
|
||||
*DRIVE_METRICS,
|
||||
]}
|
||||
|
||||
|
||||
+317
-68
@@ -22,7 +22,7 @@ from collections import deque
|
||||
from concurrent.futures import ThreadPoolExecutor, wait as wait_futures
|
||||
from datetime import datetime, timezone
|
||||
|
||||
AGENT_VERSION = "1.20.1"
|
||||
AGENT_VERSION = "1.27.0"
|
||||
|
||||
# Default path to the local Docker Engine socket. Overridable via the
|
||||
# `docker_socket` config key; collection is silently skipped if it's absent or
|
||||
@@ -92,6 +92,7 @@ UPTIME_PATH = "/proc/uptime"
|
||||
OS_RELEASE_PATH = "/etc/os-release"
|
||||
NETDEV_PATH = "/proc/net/dev"
|
||||
DISKSTATS_PATH = "/proc/diskstats"
|
||||
MOUNTSTATS_PATH = "/proc/self/mountstats"
|
||||
HWMON_DIR = "/sys/class/hwmon"
|
||||
# Where the kernel lists virtual network devices (bridges, veth, docker0,
|
||||
# vxlan, tun, VLANs, bonds) and the block devices (a disk has a `device`).
|
||||
@@ -394,8 +395,94 @@ def collect_diskio_raw() -> dict:
|
||||
return _physical_only(out, _virtual_disk)
|
||||
|
||||
|
||||
# ─── NFS delay per mount (#5996) ─────────────────────────────────────────────
|
||||
#
|
||||
# The kernel's own count of every NFS request each mount has finished, read
|
||||
# from /proc/self/mountstats. Reading it never touches the share, so it answers
|
||||
# while one is stuck. Each op's line is cumulative: ops, transmissions, major
|
||||
# timeouts, bytes sent, bytes received, then queue, round-trip and execute
|
||||
# time in ms. A request is counted when it finishes, so a share that is stuck
|
||||
# shows nothing until it comes back, and then its long requests at once
|
||||
# (mounts_stalled says it is stuck meanwhile).
|
||||
|
||||
|
||||
def read_mountstats(text: str) -> dict:
|
||||
"""{mount point: {op: (ops, transmissions, timeouts, queue_ms, rtt_ms,
|
||||
execute_ms, bytes_sent, bytes_received)}} for each NFS mount in a
|
||||
mountstats text."""
|
||||
out: dict = {}
|
||||
mount = None
|
||||
in_ops = False
|
||||
for line in text.splitlines():
|
||||
if line.startswith("device "):
|
||||
mount, in_ops = None, False
|
||||
parts = line.split()
|
||||
try:
|
||||
at = parts.index("on")
|
||||
fstype = parts[parts.index("fstype") + 1]
|
||||
except (ValueError, IndexError):
|
||||
continue
|
||||
if fstype.startswith("nfs") and at + 1 < len(parts):
|
||||
mount = parts[at + 1].replace("\\040", " ")
|
||||
out[mount] = {}
|
||||
elif mount is None:
|
||||
continue
|
||||
elif line.strip() == "per-op statistics":
|
||||
in_ops = True
|
||||
elif in_ops:
|
||||
name, sep, rest = line.strip().partition(":")
|
||||
nums = rest.split()
|
||||
if sep and len(nums) >= 8 and all(n.isdigit() for n in nums[:8]):
|
||||
ops, trans, timeouts, sent, recv, queue, rtt, exe = (int(n) for n in nums[:8])
|
||||
out[mount][name] = (ops, trans, timeouts, queue, rtt, exe, sent, recv)
|
||||
return out
|
||||
|
||||
|
||||
def collect_nfs_raw() -> dict:
|
||||
try:
|
||||
return read_mountstats(_read_file(MOUNTSTATS_PATH))
|
||||
except OSError:
|
||||
return {}
|
||||
|
||||
|
||||
def nfs_delays(cur: dict, prev: dict, dt: float) -> list:
|
||||
"""Each NFS mount's requests since the last sample: how many a second,
|
||||
their average round trip and execute time (queueing included, what a
|
||||
program waits), READ and WRITE on their own, and the retransmissions and
|
||||
major timeouts among them, and the bytes a second it sent and received
|
||||
on the wire (#6115). A mount new since the last sample, or whose counters
|
||||
went back (remounted), is left for the next one."""
|
||||
out: list = []
|
||||
if dt <= 0:
|
||||
return out
|
||||
for mount, ops in cur.items():
|
||||
before = prev.get(mount)
|
||||
if before is None:
|
||||
continue
|
||||
d = {op: tuple(a - b for a, b in zip(v, before.get(op, (0,) * len(v)))) for op, v in ops.items()}
|
||||
if any(x < 0 for v in d.values() for x in v):
|
||||
continue
|
||||
n = sum(v[0] for v in d.values())
|
||||
row = {"mount": mount, "ops_per_sec": round(n / dt, 2),
|
||||
"retrans": max(0, sum(v[1] - v[0] for v in d.values())),
|
||||
"timeouts": sum(v[2] for v in d.values()),
|
||||
"tx_bps": round(sum(v[6] for v in d.values()) / dt, 1),
|
||||
"rx_bps": round(sum(v[7] for v in d.values()) / dt, 1)}
|
||||
if n:
|
||||
row["rtt_ms"] = round(sum(v[4] for v in d.values()) / n, 2)
|
||||
row["exe_ms"] = round(sum(v[5] for v in d.values()) / n, 2)
|
||||
for op, key in (("READ", "read_ms"), ("WRITE", "write_ms")):
|
||||
v = d.get(op)
|
||||
if v and v[0]:
|
||||
row[key] = round(v[5] / v[0], 2)
|
||||
out.append(row)
|
||||
return out
|
||||
|
||||
|
||||
def collect_temps() -> list:
|
||||
"""Return [{label, celsius}] from /sys/class/hwmon (best-effort, may be empty)."""
|
||||
"""Return [{label, celsius, chip}] from /sys/class/hwmon (best-effort, may
|
||||
be empty). `chip` is the hwmon driver's name (coretemp, nvme, nct6798…),
|
||||
which says what a bare label like "Sensor 2" is measuring."""
|
||||
out: list = []
|
||||
try:
|
||||
chips = os.listdir(HWMON_DIR)
|
||||
@@ -426,7 +513,7 @@ def collect_temps() -> list:
|
||||
except OSError:
|
||||
pass
|
||||
name = label or (f"{chip}_{idx}" if chip else idx)
|
||||
out.append({"label": name, "celsius": round(milli / 1000.0, 1)})
|
||||
out.append({"label": name, "celsius": round(milli / 1000.0, 1), "chip": chip})
|
||||
return out
|
||||
|
||||
|
||||
@@ -500,6 +587,9 @@ DOCKER_DEADLINE_SECONDS = 20.0
|
||||
# /system/df walks every image, container and volume: asked this often, not
|
||||
# every sample. Steward keeps the last answer between reports.
|
||||
DOCKER_DF_INTERVAL_SECONDS = 600.0
|
||||
# How many of a host's image digests a report carries: what Steward checks a
|
||||
# swarm service's pinned image against before moving it to this node.
|
||||
DOCKER_DIGESTS_MAX = 400
|
||||
|
||||
# Container-log collection (m79). Logs ride in the same push as metrics, so one
|
||||
# interval's batch is capped to keep a chatty container from bloating a POST (and
|
||||
@@ -640,19 +730,30 @@ def _docker_cpu_pct(stats: dict) -> float:
|
||||
|
||||
|
||||
def _docker_mem(stats: dict):
|
||||
"""Return (usage_bytes, limit_bytes, mem_pct); working set excludes cache."""
|
||||
"""Return (used_bytes, limit_bytes, used_pct, cache_bytes) (#6030).
|
||||
|
||||
Used is what the processes hold and can't hand back without swap: anon
|
||||
plus shmem (Postgres keeps its shared buffers in shmem). File cache is
|
||||
reported apart: the kernel keeps what a container read or wrote while
|
||||
nothing else wants the memory, so a file-heavy container's cache can
|
||||
run to hundreds of GB it doesn't need. Docker's own working set (usage
|
||||
less inactive_file) still counts the recently used part of it."""
|
||||
try:
|
||||
mem = stats.get("memory_stats", {})
|
||||
usage = mem.get("usage", 0)
|
||||
limit = mem.get("limit", 0)
|
||||
# Subtract page cache for working set (cgroup v1 "cache", v2 "inactive_file").
|
||||
cache = mem.get("stats", {}).get("cache", 0) or \
|
||||
mem.get("stats", {}).get("inactive_file", 0)
|
||||
actual = max(0, usage - cache)
|
||||
pct = round(actual / limit * 100.0, 2) if limit > 0 else 0.0
|
||||
return actual, limit, pct
|
||||
st = mem.get("stats", {})
|
||||
if "anon" in st: # cgroup v2
|
||||
shmem = st.get("shmem", 0)
|
||||
used = st["anon"] + shmem
|
||||
cache = max(0, st.get("file", 0) - shmem)
|
||||
else: # cgroup v1: rss leaves shmem out, cache has it in
|
||||
shmem = st.get("total_shmem", st.get("shmem", 0))
|
||||
used = st.get("total_rss", st.get("rss", 0)) + shmem
|
||||
cache = max(0, st.get("total_cache", st.get("cache", 0)) - shmem)
|
||||
pct = round(used / limit * 100.0, 2) if limit > 0 else 0.0
|
||||
return used, limit, pct, cache
|
||||
except (KeyError, TypeError):
|
||||
return 0, 0, 0.0
|
||||
return 0, 0, 0.0, 0
|
||||
|
||||
|
||||
def _docker_ports(ports: list) -> list:
|
||||
@@ -751,13 +852,13 @@ def _collect_one_container(socket_path: str, c: dict) -> dict:
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
|
||||
cpu_pct = mem_usage = mem_limit = mem_pct = None
|
||||
cpu_pct = mem_used = mem_limit = mem_pct = mem_cache = None
|
||||
net_rx = net_tx = blk_read = blk_write = None
|
||||
if state == "running":
|
||||
try:
|
||||
stats = _docker_request(socket_path, f"/containers/{cid}/stats?stream=false")
|
||||
cpu_pct = _docker_cpu_pct(stats)
|
||||
mem_usage, mem_limit, mem_pct = _docker_mem(stats)
|
||||
mem_used, mem_limit, mem_pct, mem_cache = _docker_mem(stats)
|
||||
net_rx, net_tx, blk_read, blk_write = _docker_net_io(stats)
|
||||
except (OSError, ValueError):
|
||||
pass
|
||||
@@ -772,9 +873,10 @@ def _collect_one_container(socket_path: str, c: dict) -> dict:
|
||||
"image": c.get("Image", ""),
|
||||
"status": state,
|
||||
"cpu_pct": cpu_pct,
|
||||
"mem_usage_bytes": mem_usage,
|
||||
"mem_used_bytes": mem_used,
|
||||
"mem_limit_bytes": mem_limit,
|
||||
"mem_pct": mem_pct,
|
||||
"mem_used_pct": mem_pct,
|
||||
"mem_cache_bytes": mem_cache,
|
||||
"ports": _docker_ports(c.get("Ports", [])),
|
||||
"started_at": started_at,
|
||||
"finished_at": finished_at,
|
||||
@@ -1154,11 +1256,14 @@ def _swarm_services(services: list, tasks: list) -> list:
|
||||
desired = (mode_obj.get("Replicated") or {}).get("Replicas", 0) or 0
|
||||
image = (((spec.get("TaskTemplate") or {}).get("ContainerSpec") or {})
|
||||
.get("Image") or "")
|
||||
image = image.split("@", 1)[0] # drop the @sha256:… digest suffix
|
||||
image, _, digest = image.partition("@") # the @sha256:… digest apart
|
||||
out.append({
|
||||
"service_name": name, "mode": mode,
|
||||
"desired": desired, "running": running_by_svc.get(sid, 0),
|
||||
"image": image,
|
||||
# The digest a stack deploy pinned, which a node must hold to start
|
||||
# the service without the registry.
|
||||
"image_digest": digest if digest.startswith("sha256:") else None,
|
||||
# task→node placement of the running replicas (cross-node — a manager
|
||||
# sees every task, even ones whose containers live on other hosts).
|
||||
"placement": [{"node_id": n, "running": cnt}
|
||||
@@ -1286,6 +1391,10 @@ def collect_disk_usage(socket_path: str):
|
||||
"volumes_size": sum(_vol_size(v) for v in volumes if _vol_size(v) > 0),
|
||||
"build_cache_size": sum(int(b.get("Size") or 0) for b in build_cache),
|
||||
"images": _disk_images(images),
|
||||
# Every image this host holds, by repository digest ("repo@sha256:…"),
|
||||
# so Steward can tell whether a swarm service could start here.
|
||||
"digests": sorted({d for im in images for d in (im.get("RepoDigests") or [])
|
||||
if isinstance(d, str) and "@sha256:" in d})[:DOCKER_DIGESTS_MAX],
|
||||
}
|
||||
|
||||
|
||||
@@ -1308,18 +1417,21 @@ class RingBuffer:
|
||||
return len(self._dq)
|
||||
|
||||
|
||||
# ─── pending updates and reboots (#5765) ─────────────────────────────────────
|
||||
# ─── pending updates and reboots (#5765, #5803) ──────────────────────────────
|
||||
#
|
||||
# What the package manager has waiting, read once an hour in a background
|
||||
# thread so a slow apt never holds up a sample, and whether the host needs a
|
||||
# reboot, read every sample (a file test). Nothing here needs root or the
|
||||
# network: apt-check and `apt list` read the lists apt-daily already fetched,
|
||||
# and dnf runs from its cache (-C).
|
||||
# reboot, read every sample (a file test). Nothing here needs root. apt-check
|
||||
# and `apt list` read the lists apt-daily already fetched; dnf, yum and zypper
|
||||
# run from their caches (-C, --no-refresh). pacman has no cache to ask without
|
||||
# root, so checkupdates (pacman-contrib) syncs its own copy of the package
|
||||
# lists, in the agent's private /tmp, and does reach the mirrors.
|
||||
|
||||
UPDATES_INTERVAL_SECONDS = 3600.0
|
||||
UPDATES_DEADLINE_SECONDS = 120.0
|
||||
REBOOT_REQUIRED = "/var/run/reboot-required"
|
||||
REBOOT_PACKAGES_MAX = 20
|
||||
KERNEL_MODULES = "/usr/lib/modules"
|
||||
|
||||
|
||||
def _run(cmd: list, deadline: float = UPDATES_DEADLINE_SECONDS):
|
||||
@@ -1332,6 +1444,11 @@ def _run(cmd: list, deadline: float = UPDATES_DEADLINE_SECONDS):
|
||||
return done.returncode, done.stdout, done.stderr
|
||||
|
||||
|
||||
def _failed(manager: str, got, what: str, at: str) -> dict:
|
||||
return {"manager": manager, "error": ((got[2] or got[1]) or what + " failed").strip()[:200],
|
||||
"checked_at": at}
|
||||
|
||||
|
||||
def parse_apt_check(stderr: str):
|
||||
"""apt-check writes "<pending>;<security>" to stderr; (pending, security) or None."""
|
||||
m = re.search(r"(\d+);(\d+)", stderr or "")
|
||||
@@ -1354,47 +1471,153 @@ def parse_apt_list(stdout: str) -> tuple:
|
||||
|
||||
|
||||
def parse_dnf_check_update(stdout: str) -> int:
|
||||
"""Packages `dnf check-update` lists, up to its "Obsoleting Packages" part."""
|
||||
"""Packages `dnf check-update` (or yum's) lists, up to its "Obsoleting
|
||||
Packages" part. yum also prints "Loaded plugins:" lines first."""
|
||||
count = 0
|
||||
for line in (stdout or "").splitlines():
|
||||
if line.startswith("Obsoleting"):
|
||||
break
|
||||
if line.strip() and not line.startswith((" ", "Last metadata")):
|
||||
if line.strip() and not line.startswith((" ", "Last metadata", "Loaded plugins",
|
||||
"Security:")):
|
||||
count += 1
|
||||
return count
|
||||
|
||||
|
||||
def parse_checkupdates(stdout: str) -> int:
|
||||
"""Packages pacman-contrib's checkupdates lists: "name old -> new"."""
|
||||
return sum(1 for line in (stdout or "").splitlines() if " -> " in line)
|
||||
|
||||
|
||||
def _zypper_rows(stdout: str) -> list:
|
||||
"""The data rows of a zypper table: lines with "|" after the "---+---" rule."""
|
||||
rows, seen_rule = [], False
|
||||
for line in (stdout or "").splitlines():
|
||||
if re.match(r"^-+\+[-+]+$", line.strip()):
|
||||
seen_rule = True
|
||||
elif seen_rule and "|" in line:
|
||||
rows.append([c.strip() for c in line.split("|")])
|
||||
return rows
|
||||
|
||||
|
||||
def parse_zypper_updates(stdout: str) -> int:
|
||||
"""Packages `zypper list-updates` lists (one table row each)."""
|
||||
return len(_zypper_rows(stdout))
|
||||
|
||||
|
||||
def parse_zypper_patches(stdout: str) -> int:
|
||||
"""Security patches `zypper list-patches --category security` says are
|
||||
still needed (its Status column), not those already applied."""
|
||||
return sum(1 for row in _zypper_rows(stdout) if "needed" in row)
|
||||
|
||||
|
||||
def _os_release_id(path: str = "/etc/os-release") -> str:
|
||||
try:
|
||||
with open(path) as fh:
|
||||
for line in fh:
|
||||
if line.startswith("ID="):
|
||||
return line.split("=", 1)[1].strip().strip('"')
|
||||
except OSError:
|
||||
pass
|
||||
return ""
|
||||
|
||||
|
||||
def _check_apt(at: str):
|
||||
got = _run(["/usr/lib/update-notifier/apt-check"])
|
||||
if got is not None:
|
||||
counts = parse_apt_check(got[2])
|
||||
if counts:
|
||||
return {"manager": "apt", "pending": counts[0], "security": counts[1], "checked_at": at}
|
||||
got = _run(["apt", "list", "--upgradable"])
|
||||
if got is not None and got[0] == 0:
|
||||
pending, security = parse_apt_list(got[1])
|
||||
return {"manager": "apt", "pending": pending, "security": security, "checked_at": at}
|
||||
return None
|
||||
|
||||
|
||||
def _needs_restarting(out: dict) -> dict:
|
||||
"""dnf and yum hosts: needs-restarting -r exits 1 when a reboot is needed."""
|
||||
restart = _run(["needs-restarting", "-r"])
|
||||
if restart is not None and restart[0] in (0, 1):
|
||||
out["reboot_required"] = restart[0] == 1
|
||||
return out
|
||||
|
||||
|
||||
def _check_dnf_like(manager: str, at: str):
|
||||
"""dnf, and yum where there is no dnf: the same output and exit codes."""
|
||||
got = _run([manager, "-q", "-C", "check-update"])
|
||||
if got is None:
|
||||
return None
|
||||
if got[0] not in (0, 100): # 100: updates are waiting
|
||||
return _failed(manager, got, manager + " check-update", at)
|
||||
out = {"manager": manager, "pending": parse_dnf_check_update(got[1]),
|
||||
"security": None, "checked_at": at}
|
||||
sec = _run([manager, "-q", "-C", "updateinfo", "list", "--security"] if manager == "dnf"
|
||||
else [manager, "-q", "-C", "updateinfo", "list", "security"])
|
||||
if sec is not None and sec[0] == 0:
|
||||
out["security"] = len({ln.split()[-1] for ln in sec[1].splitlines()
|
||||
if ln.strip() and not ln.startswith("Loaded plugins")})
|
||||
return _needs_restarting(out)
|
||||
|
||||
|
||||
def _check_zypper(at: str):
|
||||
"""openSUSE / SLES. Tumbleweed upgrades with dup, so its pending list is
|
||||
dup's, and it has no patches to call security."""
|
||||
tumbleweed = _os_release_id() == "opensuse-tumbleweed"
|
||||
got = _run(["zypper", "--no-refresh", "-q", "list-updates"] + (["--dup"] if tumbleweed else []))
|
||||
if got is None:
|
||||
return None
|
||||
if got[0] != 0:
|
||||
return _failed("zypper", got, "zypper list-updates", at)
|
||||
out = {"manager": "zypper", "pending": parse_zypper_updates(got[1]), "security": None,
|
||||
"checked_at": at}
|
||||
if not tumbleweed:
|
||||
sec = _run(["zypper", "--no-refresh", "-q", "list-patches", "--category", "security"])
|
||||
if sec is not None and sec[0] in (0, 100, 101):
|
||||
out["security"] = parse_zypper_patches(sec[1])
|
||||
restart = _run(["zypper", "needs-rebooting"])
|
||||
if restart is not None and restart[0] in (0, 102): # 102: a reboot is needed
|
||||
out["reboot_required"] = restart[0] == 102
|
||||
return out
|
||||
|
||||
|
||||
def _check_pacman(at: str):
|
||||
"""Arch and its family (CachyOS, Manjaro, EndeavourOS). pacman keeps no
|
||||
security list, so security is None. Without pacman-contrib there is no
|
||||
safe check: `pacman -Sy` needs root and leaves a partial upgrade."""
|
||||
if shutil.which("pacman") is None:
|
||||
return None
|
||||
got = _run(["checkupdates"])
|
||||
if got is None:
|
||||
return {"manager": "pacman", "error": "checkupdates isn't installed (pacman-contrib)",
|
||||
"checked_at": at}
|
||||
if got[0] not in (0, 2): # 2: nothing to update
|
||||
return _failed("pacman", got, "checkupdates", at)
|
||||
return {"manager": "pacman", "pending": parse_checkupdates(got[1]), "security": None,
|
||||
"checked_at": at}
|
||||
|
||||
|
||||
# Asked in this order; the first that answers is the host's. dnf comes before
|
||||
# yum because dnf hosts often keep a yum alias that is dnf underneath.
|
||||
UPDATE_CHECKS = (
|
||||
("apt", _check_apt),
|
||||
("dnf", lambda at: _check_dnf_like("dnf", at)),
|
||||
("yum", lambda at: _check_dnf_like("yum", at)),
|
||||
("zypper", _check_zypper),
|
||||
("pacman", _check_pacman),
|
||||
)
|
||||
|
||||
|
||||
def collect_updates() -> dict:
|
||||
"""{"manager", "pending", "security", "checked_at"} (security None when the
|
||||
manager can't say), {"error"} when the check failed, or {} on a host with
|
||||
no package manager we know. dnf hosts also say whether a reboot is
|
||||
required, from needs-restarting."""
|
||||
no package manager we know. dnf, yum and zypper hosts also say whether a
|
||||
reboot is required."""
|
||||
at = _now_iso()
|
||||
try:
|
||||
got = _run(["/usr/lib/update-notifier/apt-check"])
|
||||
if got is not None:
|
||||
counts = parse_apt_check(got[2])
|
||||
if counts:
|
||||
return {"manager": "apt", "pending": counts[0], "security": counts[1],
|
||||
"checked_at": at}
|
||||
got = _run(["apt", "list", "--upgradable"])
|
||||
if got is not None and got[0] == 0:
|
||||
pending, security = parse_apt_list(got[1])
|
||||
return {"manager": "apt", "pending": pending, "security": security, "checked_at": at}
|
||||
got = _run(["dnf", "-q", "-C", "check-update"])
|
||||
if got is not None:
|
||||
if got[0] not in (0, 100): # 100: updates are waiting
|
||||
return {"manager": "dnf", "error": (got[2] or "dnf check-update failed").strip()[:200],
|
||||
"checked_at": at}
|
||||
out = {"manager": "dnf", "pending": parse_dnf_check_update(got[1]),
|
||||
"security": None, "checked_at": at}
|
||||
sec = _run(["dnf", "-q", "-C", "updateinfo", "list", "--security"])
|
||||
if sec is not None and sec[0] == 0:
|
||||
out["security"] = len({ln.split()[-1] for ln in sec[1].splitlines() if ln.strip()})
|
||||
restart = _run(["needs-restarting", "-r"])
|
||||
if restart is not None and restart[0] in (0, 1):
|
||||
out["reboot_required"] = restart[0] == 1
|
||||
return out
|
||||
for _name, check in UPDATE_CHECKS:
|
||||
got = check(at)
|
||||
if got is not None:
|
||||
return got
|
||||
except subprocess.TimeoutExpired:
|
||||
return {"error": "the package manager didn't answer in %.0f s" % UPDATES_DEADLINE_SECONDS,
|
||||
"checked_at": at}
|
||||
@@ -1428,13 +1651,19 @@ def refresh_updates(state: dict, now_mono: float | None = None) -> None:
|
||||
threading.Thread(target=work, name="updates", daemon=True).start()
|
||||
|
||||
|
||||
def collect_reboot(path: str = REBOOT_REQUIRED):
|
||||
"""{"required", "since", "packages"} from Debian's reboot-required marker,
|
||||
or None where there is no such marker system (no apt) to ask."""
|
||||
def collect_reboot(path: str = REBOOT_REQUIRED, modules: str = KERNEL_MODULES):
|
||||
"""{"required", "since", "packages"} from Debian's reboot-required marker;
|
||||
on pacman hosts, whether the running kernel's modules are gone (an upgrade
|
||||
replaced the kernel); None where neither can be asked (dnf, yum and zypper
|
||||
say it with the hourly update check)."""
|
||||
try:
|
||||
st = os.stat(path)
|
||||
except FileNotFoundError:
|
||||
return {"required": False} if shutil.which("apt-get") else None
|
||||
if shutil.which("apt-get"):
|
||||
return {"required": False}
|
||||
if shutil.which("pacman"):
|
||||
return {"required": not os.path.isdir(os.path.join(modules, os.uname().release))}
|
||||
return None
|
||||
packages: list = []
|
||||
try:
|
||||
with open(path + ".pkgs") as fh:
|
||||
@@ -1450,13 +1679,13 @@ def collect_reboot(path: str = REBOOT_REQUIRED):
|
||||
# The agent can't update or reboot its host: it runs unprivileged under
|
||||
# NoNewPrivileges. It leaves a request in MAINT_REQUESTS, the one directory its
|
||||
# unit lets it write; steward-maint.path starts the root helper (maint.py),
|
||||
# which does only update / reboot / drain / undrain and writes each outcome to
|
||||
# MAINT_RESULTS. The agent reads those back and reports each new state once.
|
||||
# which does only check / update / reboot / drain / undrain / rebalance and writes each
|
||||
# outcome to MAINT_RESULTS. The agent reads those back and reports each new state once.
|
||||
|
||||
MAINT_REQUESTS = "/var/lib/steward-agent/requests"
|
||||
MAINT_RESULTS = "/var/lib/steward-maint/results"
|
||||
MAINT_PATH_UNIT = "/etc/systemd/system/steward-maint.path"
|
||||
MAINT_ACTIONS = ("update", "reboot", "drain", "undrain", "drives")
|
||||
MAINT_ACTIONS = ("check", "update", "reboot", "drain", "undrain", "drives", "rebalance")
|
||||
MAINT_RESULT_MAX_BYTES = 8192
|
||||
# The helper keeps results a week; only this recent a one is reported, so a
|
||||
# job a reboot interrupted still reaches Steward from the agent's next start
|
||||
@@ -1464,7 +1693,11 @@ MAINT_RESULT_MAX_BYTES = 8192
|
||||
MAINT_REPORT_WINDOW_SECONDS = 86400
|
||||
_MAINT_ID = re.compile(r"^[A-Za-z0-9-]{1,64}$")
|
||||
_MAINT_FIELDS = ("action", "state", "ok", "packages", "reboot_required", "node",
|
||||
"detail", "started_at", "finished_at")
|
||||
"detail", "started_at", "finished_at",
|
||||
# a check's answer (#6098)
|
||||
"pending", "docker_update", "docker_packages", "containers",
|
||||
# a rebalance's answer
|
||||
"moved", "left")
|
||||
|
||||
|
||||
def maint_helper_installed(unit: str = MAINT_PATH_UNIT,
|
||||
@@ -1474,14 +1707,17 @@ def maint_helper_installed(unit: str = MAINT_PATH_UNIT,
|
||||
|
||||
|
||||
def request_maintenance(job_id: str, action: str, node: str | None = None,
|
||||
requests_dir: str = MAINT_REQUESTS) -> None:
|
||||
requests_dir: str = MAINT_REQUESTS, services=None) -> None:
|
||||
"""Leave the helper a request, whole: written to a dot-file the path unit
|
||||
doesn't match, then renamed to `<id>.json`."""
|
||||
doesn't match, then renamed to `<id>.json`. A rebalance names the swarm
|
||||
services to move; the helper checks each name itself."""
|
||||
if action not in MAINT_ACTIONS or not _MAINT_ID.match(job_id or ""):
|
||||
raise ValueError(f"not a maintenance request: {action!r} {job_id!r}")
|
||||
req = {"id": job_id, "action": action}
|
||||
if node:
|
||||
req["node"] = node
|
||||
if action == "rebalance":
|
||||
req["services"] = [s for s in services if isinstance(s, str)] if isinstance(services, list) else []
|
||||
tmp = os.path.join(requests_dir, f".{job_id}.tmp")
|
||||
with open(tmp, "w") as fh:
|
||||
json.dump(req, fh)
|
||||
@@ -1499,7 +1735,8 @@ def take_maintenance(steps, requested: set, requests_dir: str = MAINT_REQUESTS)
|
||||
continue
|
||||
try:
|
||||
request_maintenance(str(step.get("id") or ""), str(step.get("action") or ""),
|
||||
step.get("node"), requests_dir=requests_dir)
|
||||
step.get("node"), requests_dir=requests_dir,
|
||||
services=step.get("services"))
|
||||
except (ValueError, OSError) as exc:
|
||||
_log("WARN", f"maintenance step {step.get('id')!r} not taken: {exc}")
|
||||
continue
|
||||
@@ -1669,7 +1906,13 @@ def build_sample(mounts: list[str], state: dict,
|
||||
{"device": n, "read_bps": round(rd, 1), "write_bps": round(wr, 1)}
|
||||
for n, (rd, wr) in _rates(disk_raw, state.get("disk", {}), dt).items()
|
||||
]
|
||||
state["net"], state["disk"], state["mono"] = net_raw, disk_raw, now_mono
|
||||
try:
|
||||
nfs_raw = collect_nfs_raw()
|
||||
except Exception:
|
||||
nfs_raw = {}
|
||||
if nfs_raw:
|
||||
sample["nfs"] = nfs_delays(nfs_raw, state.get("nfs", {}), dt)
|
||||
state["net"], state["disk"], state["nfs"], state["mono"] = net_raw, disk_raw, nfs_raw, now_mono
|
||||
|
||||
# Docker's status rides every sample, so Steward can tell "no containers"
|
||||
# (status ok, docker: []) from "couldn't ask" (unavailable / error).
|
||||
@@ -1836,10 +2079,16 @@ def _drop_logs(sample: dict) -> dict:
|
||||
return sample
|
||||
|
||||
|
||||
def split_backlog(buffered: list, limit: int = MAX_SAMPLES_PER_POST) -> tuple:
|
||||
"""(the buffered samples to send with this one, the ones held for later):
|
||||
the oldest limit-1, leaving room for the new sample."""
|
||||
return buffered[:limit - 1], buffered[limit - 1:]
|
||||
def split_backlog(queued: list, limit: int = MAX_SAMPLES_PER_POST) -> tuple:
|
||||
"""(the samples to send in this post, the ones held for later): the oldest
|
||||
`limit` of the backlog with the new sample queued behind it.
|
||||
|
||||
The new sample waits its turn. Sent ahead of the backlog it reached Steward
|
||||
before older samples did, and a rule counting checks in a row saw each
|
||||
post's run of stalled checks ended by the newest, healthy one: after the
|
||||
2026-10-17 NFS stall "Mount not answering" (10 in a row) never fired
|
||||
(#5995)."""
|
||||
return queued[:limit], queued[limit:]
|
||||
|
||||
|
||||
def next_backoff(current: int) -> int:
|
||||
@@ -1954,10 +2203,10 @@ def main_loop(conf_path: str) -> int:
|
||||
docker_logs_enabled=docker_logs_enabled,
|
||||
docker_log_exclude=docker_log_exclude)
|
||||
buffered = buffer.drain()
|
||||
send, held = split_backlog(buffered)
|
||||
send, held = split_backlog(buffered + [sample])
|
||||
maint_events, maint_keys = maintenance_results(maint_seen)
|
||||
payload = build_payload(
|
||||
samples=send + [sample],
|
||||
samples=send,
|
||||
hostname=hostname,
|
||||
metadata=metadata,
|
||||
events=events + ([lost_contact_event(lost_since)] if lost_since else [])
|
||||
@@ -1978,7 +2227,7 @@ def main_loop(conf_path: str) -> int:
|
||||
rate_state["updates_due"] = True
|
||||
for s in held:
|
||||
buffer.push(s)
|
||||
if send:
|
||||
if buffered:
|
||||
_log("INFO", f"flushed {len(send)} buffered samples"
|
||||
+ (f", {len(held)} still held" if held else ""))
|
||||
backoff = 0
|
||||
|
||||
@@ -10,7 +10,8 @@ active, every replicated service at its replicas. A job that fails, or a host
|
||||
that doesn't come back into service, stops the run, and the host's
|
||||
maintenance_failed figure goes to 1 for an alert rule to catch. No host is
|
||||
started after the window; the run then stops and says which hosts it didn't
|
||||
reach.
|
||||
reach. A run that drained swarm nodes ends by spreading the swarm's services
|
||||
back out (rebalance.py), unless its plan says not to.
|
||||
|
||||
The decisions are model-free here (plans and runs are anything with the
|
||||
attributes); the database side is below them, and the plugin's minute tick
|
||||
@@ -20,11 +21,12 @@ the host it runs on, picks up where it was.
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime, time, timedelta, timezone
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from . import maintenance
|
||||
from steward.core.weekly import WEEKDAYS, describe, fired_slot, is_due, last_slot, next_slot, parse_at # noqa: F401
|
||||
|
||||
from . import maintenance, rebalance, timeline
|
||||
|
||||
WEEKDAYS = ("Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday", "Sunday")
|
||||
# How long a host may take to be back in service after its job finished.
|
||||
SETTLE_LIMIT = timedelta(minutes=30)
|
||||
# An agent heard from this recently is posting.
|
||||
@@ -32,48 +34,6 @@ POSTING_WITHIN = timedelta(minutes=3)
|
||||
RUN_STATES = ("running", "done", "failed", "stopped")
|
||||
|
||||
|
||||
def _zone(name: str):
|
||||
from steward.core.formatting import zone
|
||||
return zone(name)
|
||||
|
||||
|
||||
def parse_at(at_time: str) -> time:
|
||||
h, m = (int(x) for x in at_time.split(":", 1))
|
||||
if not (0 <= h < 24 and 0 <= m < 60):
|
||||
raise ValueError(at_time)
|
||||
return time(h, m)
|
||||
|
||||
|
||||
def last_slot(plan, now: datetime) -> datetime:
|
||||
"""The most recent scheduled time at or before `now`, in UTC."""
|
||||
tz = _zone(plan.time_zone)
|
||||
local = now.astimezone(tz)
|
||||
day = local.date() - timedelta(days=(local.weekday() - plan.weekday) % 7)
|
||||
slot = datetime.combine(day, parse_at(plan.at_time), tzinfo=tz)
|
||||
if slot > local:
|
||||
slot -= timedelta(days=7)
|
||||
return slot.astimezone(timezone.utc)
|
||||
|
||||
|
||||
def next_slot(plan, now: datetime) -> datetime:
|
||||
return last_slot(plan, now) + timedelta(days=7)
|
||||
|
||||
|
||||
def is_due(plan, now: datetime) -> datetime | None:
|
||||
"""The slot to fire now, or None. A slot fires once (last_slot_at), and
|
||||
only while its window is still open: a Steward that was down over the slot
|
||||
starts late, not a day late."""
|
||||
if not plan.enabled:
|
||||
return None
|
||||
slot = last_slot(plan, now)
|
||||
since = plan.last_slot_at or plan.created_at
|
||||
if since is not None and slot <= since:
|
||||
return None
|
||||
if now - slot >= timedelta(minutes=plan.window_minutes):
|
||||
return None
|
||||
return slot
|
||||
|
||||
|
||||
def back_in_service(*, last_seen_at, node, services, job_finished_at, now: datetime,
|
||||
expect_active: bool = True) -> str | None:
|
||||
"""None when the host is back in service, else why not yet. `node` is the
|
||||
@@ -119,17 +79,10 @@ def next_move(run, plan, job, back: str | None, now: datetime) -> tuple[str, str
|
||||
if back is None:
|
||||
return "next", None
|
||||
if run.settle_since is not None and now - run.settle_since > SETTLE_LIMIT:
|
||||
return "fail", f"not back in service within {int(SETTLE_LIMIT.total_seconds() // 60)} min: {back}"
|
||||
return "fail", f"{maintenance.NOT_BACK} {int(SETTLE_LIMIT.total_seconds() // 60)} min: {back}"
|
||||
return "settling", back
|
||||
|
||||
|
||||
def describe(plan) -> str:
|
||||
""""Sundays at 03:00 (Europe/London), up to 4 h" for the page."""
|
||||
hours = plan.window_minutes / 60
|
||||
span = f"{hours:g} h" if plan.window_minutes % 60 == 0 else f"{plan.window_minutes} min"
|
||||
return f"{WEEKDAYS[plan.weekday]}s at {plan.at_time} ({plan.time_zone}), up to {span}"
|
||||
|
||||
|
||||
# ── applied to the database: the minute tick, Run now, the page ──────────────
|
||||
|
||||
async def group_hosts(session, group_id: str) -> list:
|
||||
@@ -231,12 +184,17 @@ async def advance(session, run, plan, now: datetime) -> str:
|
||||
if move == "fail":
|
||||
if job is not None and job.state == "done":
|
||||
maintenance._finish(job, "failed", now, why) # the host never came back into service
|
||||
await timeline.write(session, f"maintenance job {job.id}",
|
||||
timeline.job_entry(session, job, host.name if host else None))
|
||||
name = host.name if host else host_id
|
||||
_end(run, "failed", now, f"{name}: {why}")
|
||||
_end(run, "failed", f"{name}: {why}", now=now)
|
||||
elif move == "stop":
|
||||
_end(run, "stopped", now, why)
|
||||
_end(run, "stopped", why, now=now)
|
||||
elif move == "done":
|
||||
_end(run, "done", now, None)
|
||||
if await rebalance.begin(session, run, plan, now) or \
|
||||
(run.rebalance or {}).get("state") == "handed":
|
||||
return run.state # a manager is spreading services back out
|
||||
_end(run, *rebalance.outcome(run), now=now)
|
||||
return run.state
|
||||
return run.state
|
||||
|
||||
@@ -250,7 +208,7 @@ def _skip(run, host_id: str, reason: str) -> None:
|
||||
run.host_ids = json.dumps(hosts)
|
||||
|
||||
|
||||
def _end(run, state: str, now: datetime, detail: str | None) -> None:
|
||||
def _end(run, state: str, detail: str | None = None, *, now: datetime) -> None:
|
||||
run.state, run.finished_at, run.settle_since = state, now, None
|
||||
if detail:
|
||||
run.detail = detail[:maintenance.DETAIL_MAX]
|
||||
@@ -277,6 +235,8 @@ async def tick(session, now: datetime) -> list[str]:
|
||||
plan = await session.get(HostMaintenancePlan, run.plan_id)
|
||||
if plan is None:
|
||||
continue
|
||||
if rebalance.check_deadline(run, now):
|
||||
await rebalance.finish(session, run, now)
|
||||
before = run.state
|
||||
after = await advance(session, run, plan, now)
|
||||
if after != before:
|
||||
@@ -289,7 +249,10 @@ async def failed_hosts(session, now: datetime) -> dict[str, float]:
|
||||
finished maintenance job failed or timed out, for the maintenance_failed
|
||||
figure an alert rule watches. A host with no job yet reads 0, so a rule
|
||||
on it reports rather than sitting at "no data". A later job that
|
||||
succeeds puts it back to 0."""
|
||||
succeeds puts it back to 0, and so does a host that failed only for not
|
||||
coming back into service in time, once it is back (#6105). That return
|
||||
is kept on the job (came_back_at), so a later wobble in the host's
|
||||
services doesn't flag it again (#6175)."""
|
||||
from sqlalchemy import select
|
||||
from steward.models.hosts import Host
|
||||
from .models import HostAgentRegistration, HostMaintenanceJob
|
||||
@@ -297,13 +260,22 @@ async def failed_hosts(session, now: datetime) -> dict[str, float]:
|
||||
select(Host.name).join(HostAgentRegistration, HostAgentRegistration.host_id == Host.id))).scalars()
|
||||
out = {name: 0.0 for name in agents}
|
||||
rows = (await session.execute(
|
||||
select(Host.name, HostMaintenanceJob.state, HostMaintenanceJob.finished_at)
|
||||
select(Host, HostMaintenanceJob)
|
||||
.join(Host, Host.id == HostMaintenanceJob.host_id)
|
||||
.where(HostMaintenanceJob.state.in_(maintenance.FINISHED),
|
||||
HostMaintenanceJob.finished_at >= now - timedelta(days=30)))).all()
|
||||
latest: dict = {}
|
||||
for name, state, finished in rows:
|
||||
if name not in latest or finished > latest[name][1]:
|
||||
latest[name] = (state, finished)
|
||||
out.update({name: 0.0 if state == "done" else 1.0 for name, (state, _) in latest.items()})
|
||||
for host, job in rows:
|
||||
if host.name not in latest or job.finished_at > latest[host.name][1].finished_at:
|
||||
latest[host.name] = (host, job)
|
||||
for name, (host, job) in latest.items():
|
||||
if (job.state == "failed" and job.came_back_at is None
|
||||
and (job.detail or "").startswith(maintenance.NOT_BACK)):
|
||||
reg = (await session.execute(select(HostAgentRegistration).where(
|
||||
HostAgentRegistration.host_id == host.id))).scalar_one_or_none()
|
||||
if await _back(session, host, job, reg, now) is None:
|
||||
job.came_back_at = now
|
||||
await timeline.write(session, f"maintenance job {job.id}",
|
||||
timeline.job_entry(session, job, host.name))
|
||||
out[name] = 1.0 if maintenance.still_failed(job) else 0.0
|
||||
return out
|
||||
|
||||
@@ -51,36 +51,45 @@ async def record_events(session, host_id: str, events, last_seen_at: datetime |
|
||||
"""Apply one post's events to the host's downtime, oldest first; returns
|
||||
how many rows were added or changed. `last_seen_at` is when the agent was
|
||||
last heard before this post: a boot after it that nobody announced is a
|
||||
restart without a shutdown."""
|
||||
restart without a shutdown. Each row added or changed goes on the
|
||||
timeline, kept up to date as it ends."""
|
||||
if not isinstance(events, list):
|
||||
return 0
|
||||
timed = sorted(((t, e) for e in events if isinstance(e, dict)
|
||||
for t in [_when(e)] if t is not None), key=lambda te: te[0])
|
||||
changed = 0
|
||||
changed = []
|
||||
for at, event in timed:
|
||||
kind = event.get("kind")
|
||||
row = None
|
||||
if kind == "stopping":
|
||||
changed += await _stopping(session, host_id, at, event.get("host_shutdown"))
|
||||
row = await _stopping(session, host_id, at, event.get("host_shutdown"))
|
||||
elif kind == "started":
|
||||
changed += await _started(session, host_id, at, _at(event.get("boot_at")), last_seen_at)
|
||||
row = await _started(session, host_id, at, _at(event.get("boot_at")), last_seen_at)
|
||||
elif kind == "lost_contact":
|
||||
changed += await _lost_contact(session, host_id, at, _at(event.get("to")))
|
||||
return changed
|
||||
row = await _lost_contact(session, host_id, at, _at(event.get("to")))
|
||||
if row is not None and row not in changed:
|
||||
changed.append(row)
|
||||
if changed:
|
||||
from . import timeline
|
||||
await session.flush()
|
||||
for row in changed:
|
||||
await timeline.write(session, f"host downtime {row.id}", timeline.downtime_entry(session, row))
|
||||
return len(changed)
|
||||
|
||||
|
||||
async def _stopping(session, host_id: str, at: datetime, host_shutdown) -> int:
|
||||
async def _stopping(session, host_id: str, at: datetime, host_shutdown) -> HostDowntime | None:
|
||||
seen = (await session.execute(select(HostDowntime.id).where(
|
||||
HostDowntime.host_id == host_id, HostDowntime.kind.in_(ANNOUNCED),
|
||||
HostDowntime.started_at == at))).first()
|
||||
if seen:
|
||||
return 0
|
||||
session.add(HostDowntime(host_id=host_id, kind="reboot" if host_shutdown else "agent_stop",
|
||||
started_at=at))
|
||||
return 1
|
||||
return None
|
||||
row = HostDowntime(host_id=host_id, kind="reboot" if host_shutdown else "agent_stop", started_at=at)
|
||||
session.add(row)
|
||||
return row
|
||||
|
||||
|
||||
async def _started(session, host_id: str, at: datetime, boot_at: datetime | None,
|
||||
last_seen_at: datetime | None) -> int:
|
||||
last_seen_at: datetime | None) -> HostDowntime | None:
|
||||
stop = (await session.execute(select(HostDowntime).where(
|
||||
HostDowntime.host_id == host_id, HostDowntime.kind.in_(ANNOUNCED),
|
||||
HostDowntime.ended_at.is_(None), HostDowntime.started_at <= at)
|
||||
@@ -91,31 +100,34 @@ async def _started(session, host_id: str, at: datetime, boot_at: datetime | None
|
||||
# boot after it, or it stayed up while only the agent restarted.
|
||||
if boot_at is not None:
|
||||
stop.kind = "reboot" if boot_at > stop.started_at else "agent_stop"
|
||||
return 1
|
||||
return stop
|
||||
if boot_at is None or last_seen_at is None or boot_at <= last_seen_at:
|
||||
return 0
|
||||
return None
|
||||
seen = (await session.execute(select(HostDowntime.id).where(
|
||||
HostDowntime.host_id == host_id, HostDowntime.kind == "unclean",
|
||||
HostDowntime.ended_at == at))).first()
|
||||
if seen:
|
||||
return 0
|
||||
session.add(HostDowntime(host_id=host_id, kind="unclean", started_at=last_seen_at, ended_at=at))
|
||||
return 1
|
||||
return None
|
||||
row = HostDowntime(host_id=host_id, kind="unclean", started_at=last_seen_at, ended_at=at)
|
||||
session.add(row)
|
||||
return row
|
||||
|
||||
|
||||
async def _lost_contact(session, host_id: str, since: datetime, until: datetime | None) -> int:
|
||||
async def _lost_contact(session, host_id: str, since: datetime,
|
||||
until: datetime | None) -> HostDowntime | None:
|
||||
if until is None or until <= since:
|
||||
return 0
|
||||
return None
|
||||
row = (await session.execute(select(HostDowntime).where(
|
||||
HostDowntime.host_id == host_id, HostDowntime.kind == "lost_contact",
|
||||
HostDowntime.started_at == since))).scalar_one_or_none()
|
||||
if row is None:
|
||||
session.add(HostDowntime(host_id=host_id, kind="lost_contact", started_at=since, ended_at=until))
|
||||
return 1
|
||||
row = HostDowntime(host_id=host_id, kind="lost_contact", started_at=since, ended_at=until)
|
||||
session.add(row)
|
||||
return row
|
||||
if row.ended_at is None or until > row.ended_at:
|
||||
row.ended_at = until
|
||||
return 1
|
||||
return 0
|
||||
return row
|
||||
return None
|
||||
|
||||
|
||||
async def announced_stops(session, now: datetime, grace_seconds: int) -> dict[str, datetime]:
|
||||
|
||||
@@ -5,13 +5,14 @@
|
||||
# and the host_agent playbooks: one copy of the list.
|
||||
#
|
||||
# smartmontools gives the helper smartctl, which reads each drive's health.
|
||||
# On pacman hosts, pacman-contrib gives the agent checkupdates, the one safe
|
||||
# way to see pending updates without root (#5803).
|
||||
# A package that can't be installed is reported, never fatal: the agent runs
|
||||
# without it and the host page says what is missing.
|
||||
#
|
||||
# Recommended / weak dependencies are skipped: on Debian, smartmontools
|
||||
# recommends a mail server.
|
||||
|
||||
PACKAGES="smartmontools"
|
||||
|
||||
have() { command -v "$1" >/dev/null 2>&1; }
|
||||
|
||||
@@ -39,12 +40,15 @@ install_with() {
|
||||
|
||||
missing=""
|
||||
have smartctl || missing="$missing smartmontools"
|
||||
[ -n "$missing" ] || { echo "dependencies present: $PACKAGES"; exit 0; }
|
||||
if have pacman && ! have checkupdates; then
|
||||
missing="$missing pacman-contrib"
|
||||
fi
|
||||
[ -n "$missing" ] || { echo "dependencies present"; exit 0; }
|
||||
|
||||
# shellcheck disable=SC2086 # one word per package
|
||||
if install_with $missing; then
|
||||
echo "installed:$missing"
|
||||
else
|
||||
echo "WARNING: could not install$missing; drive health will read \"smartctl not installed\" until it is"
|
||||
echo "WARNING: could not install$missing; until it is, drive health reads \"smartctl not installed\" (smartmontools) and the update check reads \"checkupdates isn't installed\" (pacman-contrib)"
|
||||
fi
|
||||
exit 0
|
||||
|
||||
@@ -8,11 +8,20 @@ REQUESTS, the one directory it may write. This helper reads each request
|
||||
without following links, refuses anything outside the list, deletes it, does
|
||||
the action, and writes the outcome to RESULTS (root's own directory, which the
|
||||
agent reads back and reports to Steward). A stolen agent token can therefore
|
||||
make its host update, reboot or drain, and nothing else.
|
||||
make its host update, reboot or drain, or on a swarm manager restart named
|
||||
services where the swarm puts them, and nothing else.
|
||||
|
||||
One action only reads: `drives` (#5789) asks smartctl for each disk's health,
|
||||
which needs root, and writes a summary to DRIVES, never a result: it is not a
|
||||
maintenance job.
|
||||
maintenance job. `check` (#6098) changes nothing but the package lists: it
|
||||
says what an update would upgrade, whether Docker is among it, and which
|
||||
containers run outside the swarm.
|
||||
|
||||
`rebalance` spreads swarm services back out after a maintenance run left them
|
||||
on one node. Steward names the services, having checked that the emptier node
|
||||
holds each one's image; the helper force-updates them one at a time, spec
|
||||
unchanged and no image pulled, so the swarm places each on its emptiest node.
|
||||
A service a constraint or a preference places is left alone.
|
||||
|
||||
Stdlib only; served by Steward at /plugins/host_agent/files/maint.py.
|
||||
"""
|
||||
@@ -30,14 +39,22 @@ from datetime import datetime, timezone
|
||||
REQUESTS = "/var/lib/steward-agent/requests"
|
||||
RESULTS = "/var/lib/steward-maint/results"
|
||||
DRIVES = "/var/lib/steward-maint/drives.json"
|
||||
ACTIONS = ("update", "reboot", "drain", "undrain", "drives")
|
||||
ACTIONS = ("check", "update", "reboot", "drain", "undrain", "drives", "rebalance")
|
||||
REQUEST_MAX_BYTES = 4096
|
||||
RESULTS_KEPT_SECONDS = 7 * 86400
|
||||
UPDATE_DEADLINE_SECONDS = 3000
|
||||
COMMAND_DEADLINE_SECONDS = 600
|
||||
OUTPUT_KEPT_CHARS = 2000
|
||||
# A listing of what an update would change is read whole, not just its tail.
|
||||
LISTING_KEPT_CHARS = 1_000_000
|
||||
_ID = re.compile(r"^[A-Za-z0-9-]{1,64}$")
|
||||
_NODE = re.compile(r"^[a-z0-9]{25}$")
|
||||
# A swarm service's name as Docker allows it, never a flag.
|
||||
_SERVICE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9_.-]{0,62}$")
|
||||
SERVICES_MAX = 48
|
||||
MOVE_DEADLINE_SECONDS = 300
|
||||
# A rebalance starts no move after this long.
|
||||
REBALANCE_SECONDS = 2400
|
||||
|
||||
|
||||
def now_iso() -> str:
|
||||
@@ -66,18 +83,28 @@ def read_request(path: str):
|
||||
|
||||
|
||||
def valid(req) -> bool:
|
||||
"""A request names a known action, has a plain id, and a node id only in
|
||||
the swarm's own form."""
|
||||
"""A request names a known action, has a plain id, a node id only in the
|
||||
swarm's own form, and, for a rebalance alone, a list of service names."""
|
||||
if not isinstance(req, dict) or req.get("action") not in ACTIONS:
|
||||
return False
|
||||
if not isinstance(req.get("id"), str) or not _ID.match(req["id"]):
|
||||
return False
|
||||
services = req.get("services")
|
||||
if req["action"] == "rebalance":
|
||||
if not (isinstance(services, list) and 0 < len(services) <= SERVICES_MAX
|
||||
and all(isinstance(s, str) and _SERVICE.match(s) for s in services)):
|
||||
return False
|
||||
elif services is not None:
|
||||
return False
|
||||
node = req.get("node")
|
||||
return node is None or (isinstance(node, str) and bool(_NODE.match(node)))
|
||||
|
||||
|
||||
def run(cmd: list, deadline: int = COMMAND_DEADLINE_SECONDS, env: dict | None = None):
|
||||
"""(ok, output tail) of a command, bounded by `deadline`."""
|
||||
def run(cmd: list, deadline: int = COMMAND_DEADLINE_SECONDS, env: dict | None = None,
|
||||
ok_codes: tuple = (0,), keep: int | None = OUTPUT_KEPT_CHARS):
|
||||
"""(ok, output tail) of a command, bounded by `deadline`. `ok_codes` are
|
||||
the exit codes that mean it worked (zypper says more than 0); `keep` is
|
||||
how much of the output's end is kept, None for all of it."""
|
||||
try:
|
||||
done = subprocess.run(cmd, capture_output=True, text=True, timeout=deadline,
|
||||
env=dict(os.environ, LANG="C", LC_ALL="C", **(env or {})))
|
||||
@@ -86,59 +113,241 @@ def run(cmd: list, deadline: int = COMMAND_DEADLINE_SECONDS, env: dict | None =
|
||||
except OSError as exc:
|
||||
return False, str(exc)
|
||||
out = (done.stdout or "") + (done.stderr or "")
|
||||
return done.returncode == 0, out[-OUTPUT_KEPT_CHARS:]
|
||||
return done.returncode in ok_codes, out if keep is None else out[-keep:]
|
||||
|
||||
|
||||
REBOOT_MARKER = "/var/run/reboot-required" # Debian and Ubuntu
|
||||
KERNEL_MODULES = "/usr/lib/modules"
|
||||
# zypper's own exit codes for "done, and": 102 a reboot is needed, 103 zypper
|
||||
# updated itself and would run again (its next run picks up the rest).
|
||||
ZYPPER_OK = (0, 102, 103)
|
||||
|
||||
|
||||
def reboot_required() -> bool | None:
|
||||
if os.path.exists("/var/run/reboot-required"):
|
||||
"""Whether the host needs a reboot after an update, asked the way its
|
||||
package manager says it; None when it can't say."""
|
||||
if os.path.exists(REBOOT_MARKER):
|
||||
return True
|
||||
if shutil.which("apt-get"):
|
||||
return False
|
||||
if shutil.which("needs-restarting"):
|
||||
try:
|
||||
try:
|
||||
if shutil.which("needs-restarting"): # dnf, yum
|
||||
return subprocess.run(["needs-restarting", "-r"], capture_output=True,
|
||||
timeout=60).returncode == 1
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return None
|
||||
if shutil.which("zypper"):
|
||||
code = subprocess.run(["zypper", "needs-rebooting"], capture_output=True,
|
||||
timeout=60).returncode
|
||||
return {0: False, 102: True}.get(code)
|
||||
except (OSError, subprocess.TimeoutExpired):
|
||||
return None
|
||||
if shutil.which("pacman"):
|
||||
# An upgraded kernel removes the running one's modules.
|
||||
return not os.path.isdir(os.path.join(KERNEL_MODULES, os.uname().release))
|
||||
return None
|
||||
|
||||
|
||||
def upgraded_count(output: str) -> int | None:
|
||||
"""Packages an apt or dnf run changed, from its summary line."""
|
||||
"""Packages an update changed, from the manager's summary line."""
|
||||
m = re.search(r"(\d+) upgraded, (\d+) newly installed", output) # apt
|
||||
if m:
|
||||
return int(m.group(1)) + int(m.group(2))
|
||||
counts = re.findall(r"^\s*(?:Upgrade|Install)\s+(\d+) Packages?", output, re.MULTILINE) # dnf
|
||||
m = re.search(r"(\d+) packages? to upgrade(?:, (\d+) new)?", output) # zypper
|
||||
if m:
|
||||
return int(m.group(1)) + int(m.group(2) or 0)
|
||||
m = re.search(r"^Packages \((\d+)\)", output, re.MULTILINE) # pacman
|
||||
if m:
|
||||
return int(m.group(1))
|
||||
counts = re.findall(r"^\s*(?:Upgrade|Install)\s+(\d+) Packages?", output, re.MULTILINE) # dnf, yum
|
||||
return sum(int(c) for c in counts) if counts else None
|
||||
|
||||
|
||||
def do_update() -> dict:
|
||||
"""Upgrade every package, keeping existing config files and leaving
|
||||
service restarts to a reboot: needrestart only lists, so the Docker daemon
|
||||
isn't restarted under its containers mid-upgrade."""
|
||||
if shutil.which("apt-get"):
|
||||
# The same as the agent's: this helper runs as root on its own and imports
|
||||
# nothing of the agent's, so it keeps its own copy.
|
||||
def _os_release_id(path: str = "/etc/os-release") -> str:
|
||||
try:
|
||||
with open(path) as fh:
|
||||
for line in fh:
|
||||
if line.startswith("ID="):
|
||||
return line.split("=", 1)[1].strip().strip('"')
|
||||
except OSError:
|
||||
pass
|
||||
return ""
|
||||
|
||||
|
||||
def update_steps(manager: str) -> list:
|
||||
"""The commands an update runs on a host with `manager`, in order: each
|
||||
(what it is, command, deadline, env, ok exit codes). The last one is the upgrade
|
||||
whose output is counted. Existing config files are kept, and needrestart
|
||||
only lists, leaving service restarts to a reboot. A package's own install
|
||||
script can still restart its service: Docker's does, which is why the job
|
||||
checks first and drains a swarm node before such an update (#6098)."""
|
||||
long = UPDATE_DEADLINE_SECONDS
|
||||
if manager == "apt":
|
||||
env = {"DEBIAN_FRONTEND": "noninteractive", "NEEDRESTART_MODE": "l"}
|
||||
ok, out = run(["apt-get", "update"], env=env)
|
||||
return [("apt-get update", ["apt-get", "update"], COMMAND_DEADLINE_SECONDS, env, (0,)),
|
||||
("apt-get dist-upgrade", ["apt-get", "-y", "-o", "Dpkg::Options::=--force-confdef",
|
||||
"-o", "Dpkg::Options::=--force-confold", "dist-upgrade"],
|
||||
long, env, (0,))]
|
||||
if manager == "dnf":
|
||||
return [("dnf upgrade", ["dnf", "-y", "upgrade", "--refresh"], long, None, (0,))]
|
||||
if manager == "yum":
|
||||
return [("yum update", ["yum", "-y", "update"], long, None, (0,))]
|
||||
if manager == "zypper":
|
||||
# Tumbleweed is a rolling release: it upgrades with dup, not update.
|
||||
upgrade = "dup" if _os_release_id() == "opensuse-tumbleweed" else "update"
|
||||
return [("zypper refresh", ["zypper", "--non-interactive", "refresh"],
|
||||
COMMAND_DEADLINE_SECONDS, None, ZYPPER_OK),
|
||||
("zypper " + upgrade, ["zypper", "--non-interactive", upgrade, "--auto-agree-with-licenses"],
|
||||
long, None, ZYPPER_OK)]
|
||||
if manager == "pacman":
|
||||
# Packages from the AUR aren't updated: no AUR helper runs as root.
|
||||
return [("pacman -Syu", ["pacman", "-Syu", "--noconfirm"], long, None, (0,))]
|
||||
return []
|
||||
|
||||
|
||||
# Which manager a host has; dnf before yum, since dnf hosts often keep a yum
|
||||
# that is dnf underneath.
|
||||
UPDATE_MANAGERS = (("apt", "apt-get"), ("dnf", "dnf"), ("yum", "yum"), ("zypper", "zypper"),
|
||||
("pacman", "pacman"))
|
||||
|
||||
|
||||
def host_manager() -> str | None:
|
||||
for manager, binary in UPDATE_MANAGERS:
|
||||
if shutil.which(binary):
|
||||
return manager
|
||||
return None
|
||||
|
||||
|
||||
def do_update() -> dict:
|
||||
"""Upgrade every package with whichever package manager the host has."""
|
||||
manager = host_manager()
|
||||
if manager is None:
|
||||
return {"ok": False, "detail": "no package manager this helper knows "
|
||||
"(apt, dnf, yum, zypper, pacman) on this host"}
|
||||
out = ""
|
||||
for label, cmd, deadline, env, ok_codes in update_steps(manager):
|
||||
# The whole output: every manager prints its count before the long
|
||||
# log of what it then does, so a tail loses it on a large update.
|
||||
ok, out = run(cmd, deadline=deadline, env=env, ok_codes=ok_codes, keep=None)
|
||||
if not ok:
|
||||
return {"ok": False, "detail": "apt-get update failed: " + out}
|
||||
ok, out = run(["apt-get", "-y", "-o", "Dpkg::Options::=--force-confdef",
|
||||
"-o", "Dpkg::Options::=--force-confold", "dist-upgrade"],
|
||||
deadline=UPDATE_DEADLINE_SECONDS, env=env)
|
||||
if not ok:
|
||||
return {"ok": False, "detail": "apt-get dist-upgrade failed: " + out}
|
||||
changed = upgraded_count(out)
|
||||
run(["apt-get", "-y", "autoremove"], env=env)
|
||||
elif shutil.which("dnf"):
|
||||
ok, out = run(["dnf", "-y", "upgrade", "--refresh"], deadline=UPDATE_DEADLINE_SECONDS)
|
||||
if not ok:
|
||||
return {"ok": False, "detail": "dnf upgrade failed: " + out}
|
||||
changed = upgraded_count(out)
|
||||
else:
|
||||
return {"ok": False, "detail": "no apt-get or dnf on this host"}
|
||||
return {"ok": False, "detail": f"{label} failed: " + out[-OUTPUT_KEPT_CHARS:]}
|
||||
changed = upgraded_count(out)
|
||||
if manager == "apt":
|
||||
run(["apt-get", "-y", "autoremove"], env={"DEBIAN_FRONTEND": "noninteractive"})
|
||||
return {"ok": True, "packages": changed, "reboot_required": reboot_required(),
|
||||
"detail": out[-500:]}
|
||||
|
||||
|
||||
# ── what an update would change, and what runs outside the swarm (#6098) ─────
|
||||
# Docker's own packages restart the daemon from their install scripts, whatever
|
||||
# needrestart is told, and every container on the host stops with it. So the
|
||||
# job asks first: a swarm node is drained before an update that upgrades
|
||||
# Docker, not after it, and the containers running outside the swarm are
|
||||
# noted, to see each of them running again once the job is over.
|
||||
|
||||
DOCKER_PACKAGES = re.compile(
|
||||
r"^(docker|docker-ce|docker\.io|docker-engine|moby-engine|containerd|containerd\.io)$")
|
||||
CONTAINERS_MAX = 40
|
||||
CONTAINER_NAME_MAX = 64
|
||||
|
||||
|
||||
def pending_steps(manager: str) -> list:
|
||||
"""The commands that list what an update would upgrade, changing nothing
|
||||
but the package lists: each (what it is, command, ok exit codes). The
|
||||
last one's output names the packages."""
|
||||
if manager == "apt":
|
||||
return [("apt-get update", ["apt-get", "update"], (0,)),
|
||||
("apt-get -s dist-upgrade", ["apt-get", "-s", "dist-upgrade"], (0,))]
|
||||
if manager == "dnf":
|
||||
# check-update exits 100 when there is something to update.
|
||||
return [("dnf check-update", ["dnf", "-q", "check-update", "--refresh"], (0, 100))]
|
||||
if manager == "yum":
|
||||
return [("yum check-update", ["yum", "-q", "check-update"], (0, 100))]
|
||||
if manager == "zypper":
|
||||
if _os_release_id() == "opensuse-tumbleweed":
|
||||
listing = ("zypper dup --dry-run", ["zypper", "--non-interactive", "dup", "--dry-run",
|
||||
"--auto-agree-with-licenses"])
|
||||
else:
|
||||
listing = ("zypper list-updates", ["zypper", "--non-interactive", "list-updates"])
|
||||
return [("zypper refresh", ["zypper", "--non-interactive", "refresh"], ZYPPER_OK),
|
||||
(*listing, ZYPPER_OK)]
|
||||
if manager == "pacman":
|
||||
# -Sy refreshes the lists only; the update's -Syu follows it. -Qu exits
|
||||
# 1 when there is nothing to upgrade.
|
||||
return [("pacman -Sy", ["pacman", "-Sy"], (0,)), ("pacman -Qu", ["pacman", "-Qu"], (0, 1))]
|
||||
return []
|
||||
|
||||
|
||||
def pending_names(manager: str, output: str) -> list:
|
||||
"""The packages a listing from pending_steps says would be upgraded."""
|
||||
if manager == "apt":
|
||||
return re.findall(r"^Inst (\S+)", output, re.MULTILINE)
|
||||
if manager in ("dnf", "yum"):
|
||||
# "docker-ce.x86_64 3:27.1.1-1.el9 docker-ce-stable"
|
||||
return [parts[0].rsplit(".", 1)[0] for parts in (line.split() for line in output.splitlines())
|
||||
if len(parts) == 3 and "." in parts[0]]
|
||||
if manager == "zypper":
|
||||
names, column, listing = [], None, False
|
||||
for line in output.splitlines():
|
||||
cells = [c.strip() for c in line.split("|")]
|
||||
if len(cells) > 2 and column is None and "Name" in cells:
|
||||
column = cells.index("Name") # list-updates' table
|
||||
elif column is not None and len(cells) > column and cells[0] == "v":
|
||||
names.append(cells[column])
|
||||
elif re.search(r"going to be (upgraded|installed)", line):
|
||||
listing = True # dup --dry-run's lists
|
||||
elif listing and line.startswith(" ") and line.strip():
|
||||
names.extend(line.split())
|
||||
else:
|
||||
listing = False
|
||||
return names
|
||||
if manager == "pacman":
|
||||
return [line.split()[0] for line in output.splitlines() if line.strip()]
|
||||
return []
|
||||
|
||||
|
||||
def standalone_containers() -> list:
|
||||
"""The running containers that aren't swarm tasks, each with its restart
|
||||
policy, by name; at most CONTAINERS_MAX, so the result stays small."""
|
||||
if not shutil.which("docker"):
|
||||
return []
|
||||
ok, out = run(["docker", "ps", "-q", "--no-trunc"], deadline=30, keep=LISTING_KEPT_CHARS)
|
||||
ids = out.split() if ok else []
|
||||
if not ids:
|
||||
return []
|
||||
fmt = '{{.Name}}|{{.HostConfig.RestartPolicy.Name}}|{{index .Config.Labels "com.docker.swarm.task.id"}}'
|
||||
ok, out = run(["docker", "inspect", "--format", fmt, *ids], deadline=60, keep=LISTING_KEPT_CHARS)
|
||||
if not ok:
|
||||
return []
|
||||
found = []
|
||||
for line in out.splitlines():
|
||||
parts = line.split("|")
|
||||
if len(parts) != 3 or parts[2].strip():
|
||||
continue # a swarm task: the drain moves it
|
||||
found.append({"name": parts[0].lstrip("/")[:CONTAINER_NAME_MAX],
|
||||
"restart": parts[1].strip() or "no"})
|
||||
return sorted(found, key=lambda c: c["name"])[:CONTAINERS_MAX]
|
||||
|
||||
|
||||
def do_check() -> dict:
|
||||
"""What an update would upgrade, whether Docker is among it, and the
|
||||
containers running outside the swarm. Only the package lists change."""
|
||||
manager = host_manager()
|
||||
if manager is None:
|
||||
return {"ok": False, "detail": "no package manager this helper knows "
|
||||
"(apt, dnf, yum, zypper, pacman) on this host"}
|
||||
env = {"DEBIAN_FRONTEND": "noninteractive"} if manager == "apt" else None
|
||||
out = ""
|
||||
for label, cmd, ok_codes in pending_steps(manager):
|
||||
ok, out = run(cmd, env=env, ok_codes=ok_codes, keep=LISTING_KEPT_CHARS)
|
||||
if not ok:
|
||||
return {"ok": False, "detail": f"{label} failed: " + out[-500:]}
|
||||
names = pending_names(manager, out)
|
||||
docker = sorted({n for n in names if DOCKER_PACKAGES.match(n)})
|
||||
return {"ok": True, "pending": len(names), "docker_update": bool(docker),
|
||||
"docker_packages": docker[:10], "containers": standalone_containers()}
|
||||
|
||||
|
||||
def own_node() -> str | None:
|
||||
ok, out = run(["docker", "info", "--format", "{{.Swarm.NodeID}}"], deadline=30)
|
||||
node = out.strip() if ok else ""
|
||||
@@ -157,6 +366,52 @@ def do_node(availability: str, node: str | None) -> dict:
|
||||
return {"ok": ok, "node": node, "detail": out.strip()[-500:]}
|
||||
|
||||
|
||||
def placed_by_rule(name: str) -> bool | None:
|
||||
"""Whether a constraint or a preference decides where the service runs
|
||||
(a force-update would leave it where it is); None when it can't be read."""
|
||||
ok, out = run(["docker", "service", "inspect", "--format",
|
||||
"{{json .Spec.TaskTemplate.Placement}}", name], deadline=30)
|
||||
if not ok:
|
||||
return None
|
||||
try:
|
||||
placement = json.loads(out.strip() or "null") or {}
|
||||
except ValueError:
|
||||
return None
|
||||
return bool(placement.get("Constraints") or placement.get("Preferences"))
|
||||
|
||||
|
||||
def do_rebalance(services: list, clock=time.monotonic) -> dict:
|
||||
"""Force-update each named service in turn, waiting for it to settle, so
|
||||
the swarm starts it again on its emptiest node. Fails when a move didn't
|
||||
settle; what was left and why is in `left`."""
|
||||
if not shutil.which("docker"):
|
||||
return {"ok": False, "detail": "no docker on this host"}
|
||||
began = clock()
|
||||
moved, left, failed = [], [], []
|
||||
for name in services:
|
||||
if clock() - began > REBALANCE_SECONDS:
|
||||
left.append({"service": name, "reason": "out of time"})
|
||||
continue
|
||||
rule = placed_by_rule(name)
|
||||
if rule is None:
|
||||
left.append({"service": name, "reason": "not found on this manager"})
|
||||
continue
|
||||
if rule:
|
||||
left.append({"service": name, "reason": "placed by a constraint"})
|
||||
continue
|
||||
ok, out = run(["docker", "service", "update", "--force", "--detach=false", "--quiet", name],
|
||||
deadline=MOVE_DEADLINE_SECONDS)
|
||||
if ok:
|
||||
moved.append(name)
|
||||
else:
|
||||
failed.append(name)
|
||||
left.append({"service": name, "reason": f"didn't settle: {out.strip()[-120:]}"})
|
||||
detail = f"moved {len(moved)} of {len(services)}"
|
||||
if failed:
|
||||
detail += "; didn't settle: " + ", ".join(failed)
|
||||
return {"ok": not failed, "moved": moved, "left": left, "detail": detail}
|
||||
|
||||
|
||||
# ── drive health (#5789) ─────────────────────────────────────────────────────
|
||||
# smartctl ≥ 7.0 answers in JSON, the same for SATA, SAS and NVMe drives on any
|
||||
# distribution; an older one is reported, never parsed as text. The helper
|
||||
@@ -316,10 +571,14 @@ def handle(req: dict) -> dict:
|
||||
return {**base, "state": "done"}
|
||||
write_result({**base, "state": "running"})
|
||||
action = req["action"]
|
||||
if action == "update":
|
||||
if action == "check":
|
||||
outcome = do_check()
|
||||
elif action == "update":
|
||||
outcome = do_update()
|
||||
elif action in ("drain", "undrain"):
|
||||
outcome = do_node("drain" if action == "drain" else "active", req.get("node"))
|
||||
elif action == "rebalance":
|
||||
outcome = do_rebalance(req["services"])
|
||||
else: # reboot
|
||||
result = {**base, "state": "rebooting", "ok": True, "finished_at": now_iso()}
|
||||
write_result(result)
|
||||
|
||||
@@ -4,8 +4,18 @@
|
||||
Steward plans and the host's agent acts: a job is one host's update and, only
|
||||
when the update says one is needed, its reboot, with the host's swarm node
|
||||
drained first and made active again after. Each action is one step the agent
|
||||
hands to its root helper (maint.py, #5766). Everything lives on the job's row,
|
||||
so Steward restarting, or the host Steward runs on rebooting, loses nothing:
|
||||
hands to its root helper (maint.py, #5766).
|
||||
|
||||
A job first asks the helper what the update would change (#6098). Docker's
|
||||
own packages restart the daemon from their install scripts, stopping every
|
||||
container on the host, so a swarm node is drained before an update that
|
||||
upgrades Docker; otherwise only before a reboot. After a drain the node's
|
||||
tasks get DRAIN_SETTLE to move before the update or reboot goes ahead. The
|
||||
containers running outside the swarm when the job began must be running again
|
||||
when it ends, within RECOVER_LIMIT, or the job fails naming them.
|
||||
|
||||
Everything lives on the job's row, so Steward restarting, or the host Steward
|
||||
runs on rebooting, loses nothing:
|
||||
the next post from the agent carries the step's result, and the `started`
|
||||
event a host sends after booting is what completes a reboot.
|
||||
|
||||
@@ -13,27 +23,59 @@ The transitions here are model-free (a job is anything with the attributes),
|
||||
so they're unit-tested without a database; routes.ingest and the scheduler's
|
||||
tick apply them.
|
||||
|
||||
States: queued → updating → [draining →] rebooting → [undraining →] done,
|
||||
or failed / timed_out. A job with no reboot needed goes updating → done.
|
||||
States: queued → [checking →] [draining → settling →] updating →
|
||||
[draining → settling →] [rebooting →] [undraining →] [recovering →] done, or
|
||||
failed / timed_out. A node is drained at most once a job: before the update
|
||||
when Docker is upgraded, else before the reboot. settling and recovering are
|
||||
Steward's own waits, moved on by the minute tick. An agent older than
|
||||
CHECK_AGENT gets no check: its job starts at updating.
|
||||
|
||||
A job that fails or is given up while its node may be drained makes the node
|
||||
active again first: it goes to undraining with the outcome kept in
|
||||
`ends_as`, and finishes as that once the undrain is through. A job never ends
|
||||
leaving behind a drain it made.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
ACTIVE = ("queued", "updating", "draining", "rebooting", "undraining")
|
||||
ACTIVE = ("queued", "checking", "draining", "settling", "updating", "rebooting",
|
||||
"undraining", "recovering")
|
||||
FINISHED = ("done", "failed", "timed_out")
|
||||
# How a job failed for not coming back into service begins (cadence.py): its
|
||||
# update (and reboot) went through, so once the host is back nothing is left
|
||||
# failed.
|
||||
NOT_BACK = "not back in service within"
|
||||
# The helper action each handed state asks for.
|
||||
STEP_ACTION = {"updating": "update", "draining": "drain", "rebooting": "reboot",
|
||||
"undraining": "undrain"}
|
||||
STEP_ACTION = {"checking": "check", "updating": "update", "draining": "drain",
|
||||
"rebooting": "reboot", "undraining": "undrain"}
|
||||
# How long a state may last before the job is given up. Queued counts from the
|
||||
# job's creation (the host may be silent); the rest from their hand-off.
|
||||
DEADLINES = {
|
||||
"queued": timedelta(hours=1),
|
||||
"checking": timedelta(minutes=30), # two listings, the helper stops each at 10
|
||||
# The drain's result comes back the way the drain can take down: draining
|
||||
# the node that runs the proxy (or Steward) moves them, and the result
|
||||
# waits until they run elsewhere, image pull included.
|
||||
"draining": timedelta(minutes=30),
|
||||
"settling": timedelta(minutes=15), # the tick moves it on at DRAIN_SETTLE
|
||||
"updating": timedelta(minutes=90), # the helper itself stops at 60
|
||||
"draining": timedelta(minutes=10),
|
||||
"rebooting": timedelta(minutes=30),
|
||||
"undraining": timedelta(minutes=10),
|
||||
"recovering": timedelta(minutes=15), # the tick fails it at RECOVER_LIMIT
|
||||
}
|
||||
# After a drain, how long the node's swarm tasks get to move before the
|
||||
# update or the reboot goes ahead (the operator, #6098: "drain wait 5 minutes
|
||||
# and then reboot").
|
||||
DRAIN_SETTLE = timedelta(minutes=5)
|
||||
# How long the containers that ran outside the swarm before the job get to
|
||||
# run again after it.
|
||||
RECOVER_LIMIT = timedelta(minutes=10)
|
||||
# The first agent whose helper answers a check (#6098).
|
||||
CHECK_AGENT = (1, 24, 0)
|
||||
# A restart policy under which Docker starts a container again after a reboot.
|
||||
RESTARTS = ("always", "unless-stopped")
|
||||
CONTAINERS_KEPT = 40
|
||||
# A host's clock and Steward's differ by seconds; a boot this far before the
|
||||
# reboot was handed out is still taken as that reboot.
|
||||
BOOT_SLACK = timedelta(seconds=60)
|
||||
@@ -60,10 +102,49 @@ def _finish(job, state: str, now: datetime, detail: str | None = None) -> None:
|
||||
_enter(job, state, now)
|
||||
|
||||
|
||||
def start(job, now: datetime) -> None:
|
||||
"""The host's agent is about to be handed the job: update first."""
|
||||
def may_be_drained(job) -> bool:
|
||||
"""Whether the job may have left its node drained: its drain was handed
|
||||
out (a result may just not have come back), or went through and the node
|
||||
hasn't been made active again."""
|
||||
return drains(job) and (job.state == "draining" or
|
||||
(job.drained_at is not None and job.state in ("settling", "updating", "rebooting")))
|
||||
|
||||
|
||||
def _give_up(job, state: str, now: datetime, detail: str) -> None:
|
||||
"""End the job as `state` (failed or timed_out), making its node active
|
||||
again first when the job may have drained it."""
|
||||
if may_be_drained(job):
|
||||
job.detail = detail[:DETAIL_MAX]
|
||||
job.ends_as = state
|
||||
_enter(job, "undraining", now)
|
||||
else:
|
||||
_finish(job, state, now, detail)
|
||||
|
||||
|
||||
def can_check(agent_version) -> bool:
|
||||
"""Whether an agent this version hands the helper a check."""
|
||||
try:
|
||||
return tuple(int(x) for x in str(agent_version).split(".")[:3]) >= CHECK_AGENT
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def start(job, now: datetime, check: bool = False) -> None:
|
||||
"""The host's agent is about to be handed the job: what the update would
|
||||
change first, when its helper can say, else the update."""
|
||||
if job.state == "queued":
|
||||
_enter(job, "updating", now)
|
||||
_enter(job, "checking" if check else "updating", now)
|
||||
|
||||
|
||||
def drains(job) -> bool:
|
||||
"""Whether the job drains the host's swarm node: not when the host isn't
|
||||
in a swarm, nor when the operator keeps its node drained."""
|
||||
return bool(job.node_id and job.drain_host_id)
|
||||
|
||||
|
||||
def outside_swarm(job) -> list:
|
||||
"""The containers the check found running outside the swarm."""
|
||||
return (job.checked or {}).get("containers") or []
|
||||
|
||||
|
||||
def executor(job) -> str:
|
||||
@@ -97,15 +178,46 @@ def wants_reboot(job) -> bool:
|
||||
return bool(job.reboot_needed) and job.reboot_policy == "if_required"
|
||||
|
||||
|
||||
def _checked(event: dict) -> dict:
|
||||
"""What a check said, kept on the job: bounded, and only the fields used."""
|
||||
containers = []
|
||||
for c in event.get("containers") or []:
|
||||
if isinstance(c, dict) and isinstance(c.get("name"), str) and c["name"]:
|
||||
containers.append({"name": c["name"][:64], "restart": str(c.get("restart") or "no")[:16]})
|
||||
packages = [str(p)[:64] for p in event.get("docker_packages") or [] if isinstance(p, str)]
|
||||
pending = event.get("pending")
|
||||
return {"pending": pending if isinstance(pending, int) else None,
|
||||
"docker_packages": packages[:10], "containers": containers[:CONTAINERS_KEPT]}
|
||||
|
||||
|
||||
def _after_check(job, event: dict, now: datetime) -> None:
|
||||
job.docker_update = event.get("docker_update") is True
|
||||
job.checked = _checked(event)
|
||||
_enter(job, "draining" if job.docker_update and drains(job) else "updating", now)
|
||||
|
||||
|
||||
def _after_update(job, now: datetime) -> None:
|
||||
if not wants_reboot(job):
|
||||
_enter(job, "done", now)
|
||||
elif job.node_id and job.drain_host_id:
|
||||
_after_work(job, now)
|
||||
elif drains(job) and job.drained_at is None:
|
||||
_enter(job, "draining", now)
|
||||
else:
|
||||
_enter(job, "rebooting", now)
|
||||
|
||||
|
||||
def _after_work(job, now: datetime) -> None:
|
||||
"""The update (and any reboot) is over: make the node active again if the
|
||||
job drained it, then see the containers back."""
|
||||
if job.drained_at is not None and drains(job):
|
||||
_enter(job, "undraining", now)
|
||||
else:
|
||||
_recover(job, now)
|
||||
|
||||
|
||||
def _recover(job, now: datetime) -> None:
|
||||
_enter(job, "recovering" if outside_swarm(job) else "done", now)
|
||||
|
||||
|
||||
def apply_result(job, event: dict, now: datetime) -> bool:
|
||||
"""Apply a `maintenance` event for this job's current step; True when the
|
||||
job changed. A result for a step the job has moved past is ignored, so a
|
||||
@@ -124,18 +236,25 @@ def apply_result(job, event: dict, now: datetime) -> bool:
|
||||
what = STEP_ACTION[job.state]
|
||||
detail = f"{what} failed: {event.get('detail') or 'no detail'}"
|
||||
if job.state == "undraining":
|
||||
detail += " (the node is still drained)"
|
||||
_finish(job, "failed", now, detail)
|
||||
_finish(job, "failed", now, _after_given_up(job, detail + " (the node is still drained)"))
|
||||
else:
|
||||
_give_up(job, "failed", now, detail)
|
||||
return True
|
||||
if job.state == "updating":
|
||||
if job.state == "checking":
|
||||
_after_check(job, event, now)
|
||||
elif job.state == "updating":
|
||||
if isinstance(event.get("packages"), int):
|
||||
job.packages = event["packages"]
|
||||
job.reboot_needed = event.get("reboot_required") is True
|
||||
_after_update(job, now)
|
||||
elif job.state == "draining":
|
||||
_enter(job, "rebooting", now)
|
||||
job.drained_at = now
|
||||
_enter(job, "settling", now)
|
||||
elif job.state == "undraining":
|
||||
_enter(job, "done", now)
|
||||
if job.ends_as: # given up: the node is active again, the job ends as it was
|
||||
_enter(job, job.ends_as, now)
|
||||
else:
|
||||
_recover(job, now)
|
||||
else: # rebooting: the boot completes it, not this
|
||||
return False
|
||||
return True
|
||||
@@ -149,10 +268,36 @@ def apply_boot(job, boot_at: datetime | None, now: datetime) -> bool:
|
||||
if boot_at < job.state_at - BOOT_SLACK:
|
||||
return False # the agent restarted; the host didn't
|
||||
job.back_at = now
|
||||
if job.node_id and job.drain_host_id:
|
||||
_enter(job, "undraining", now)
|
||||
else:
|
||||
_after_work(job, now)
|
||||
return True
|
||||
|
||||
|
||||
def settle(job, now: datetime) -> bool:
|
||||
"""A drained node has had DRAIN_SETTLE for its tasks to move: on to the
|
||||
update, or to the reboot when the update is done (reboot_needed is set)."""
|
||||
if job.state != "settling" or job.state_at is None or now - job.state_at < DRAIN_SETTLE:
|
||||
return False
|
||||
_enter(job, "updating" if job.reboot_needed is None else "rebooting", now)
|
||||
return True
|
||||
|
||||
|
||||
def recovered(job, running: set, now: datetime) -> bool:
|
||||
"""Done once every container that ran outside the swarm before the job
|
||||
runs again (`running`: the host's containers seen running since the job
|
||||
came to this state); failed, naming the rest, past RECOVER_LIMIT."""
|
||||
if job.state != "recovering" or job.state_at is None:
|
||||
return False
|
||||
missing = [c for c in outside_swarm(job) if c["name"] not in running]
|
||||
if not missing:
|
||||
_enter(job, "done", now)
|
||||
return True
|
||||
if now - job.state_at < RECOVER_LIMIT:
|
||||
return False
|
||||
names = [c["name"] + ("" if c["restart"] in RESTARTS else " (no restart policy)")
|
||||
for c in missing[:6]]
|
||||
more = f" and {len(missing) - 6} more" if len(missing) > 6 else ""
|
||||
_finish(job, "failed", now, f"not running again {int(RECOVER_LIMIT.total_seconds() // 60)} min "
|
||||
f"after the job: {', '.join(names)}{more}")
|
||||
return True
|
||||
|
||||
|
||||
@@ -163,14 +308,26 @@ def check_deadline(job, now: datetime) -> bool:
|
||||
if limit is None or since is None or now - since <= limit:
|
||||
return False
|
||||
waiting = {"queued": "the host's agent didn't check in",
|
||||
"updating": "the update didn't finish",
|
||||
"checking": "the check of what the update would change didn't finish",
|
||||
"draining": "the node wasn't drained",
|
||||
"settling": "the wait after the drain didn't end",
|
||||
"updating": "the update didn't finish",
|
||||
"rebooting": "the host didn't come back",
|
||||
"undraining": "the node wasn't made active again"}[job.state]
|
||||
_finish(job, "timed_out", now, f"{waiting} within {int(limit.total_seconds() // 60)} min")
|
||||
"undraining": "the node wasn't made active again",
|
||||
"recovering": "its containers weren't seen again"}[job.state]
|
||||
detail = f"{waiting} within {int(limit.total_seconds() // 60)} min"
|
||||
if job.state == "undraining":
|
||||
_finish(job, job.ends_as or "timed_out", now, _after_given_up(job, detail))
|
||||
else:
|
||||
_give_up(job, "timed_out", now, detail)
|
||||
return True
|
||||
|
||||
|
||||
def _after_given_up(job, detail: str) -> str:
|
||||
"""What an undrain going wrong adds to why a given-up job ended."""
|
||||
return f"{job.detail}; then {detail}" if job.ends_as and job.detail else detail
|
||||
|
||||
|
||||
def window_end(job, now: datetime) -> datetime:
|
||||
"""When the job's maintenance window should end: the longest the rest of
|
||||
the job could take, or now once it has finished."""
|
||||
@@ -237,12 +394,24 @@ async def _host_name(session, host_id: str) -> str:
|
||||
return host.name if host is not None else host_id
|
||||
|
||||
|
||||
async def _moved(session, job, now: datetime) -> None:
|
||||
"""After a job moved: its window follows it, and once it ends it goes on
|
||||
the timeline."""
|
||||
host_name = await _host_name(session, job.host_id)
|
||||
await _window(session, job, host_name, now)
|
||||
if job.state in FINISHED:
|
||||
from . import timeline
|
||||
await timeline.write(session, f"maintenance job {job.id}",
|
||||
timeline.job_entry(session, job, host_name))
|
||||
|
||||
|
||||
async def apply_events(session, host_id: str, events, now: datetime) -> int:
|
||||
"""Apply one post's `maintenance` results and `started` boots to the jobs
|
||||
they belong to; returns how many jobs changed. A result is matched by its
|
||||
step id, so a drain reported by a manager reaches the job of the node it
|
||||
drained."""
|
||||
drained. A result no job owns may be a run's rebalance (rebalance.py)."""
|
||||
from sqlalchemy import select
|
||||
from . import rebalance
|
||||
from .downtime import _at
|
||||
from .models import HostMaintenanceJob
|
||||
if not isinstance(events, list):
|
||||
@@ -257,6 +426,8 @@ async def apply_events(session, host_id: str, events, now: datetime) -> int:
|
||||
HostMaintenanceJob.state.in_(ACTIVE)))).scalar_one_or_none()
|
||||
if job is not None and apply_result(job, event, now):
|
||||
changed.add(job)
|
||||
elif job is None:
|
||||
await rebalance.apply_event(session, event, now)
|
||||
elif event.get("kind") == "started":
|
||||
boot_at = _at(event.get("boot_at"))
|
||||
for job in (await session.execute(select(HostMaintenanceJob).where(
|
||||
@@ -265,14 +436,18 @@ async def apply_events(session, host_id: str, events, now: datetime) -> int:
|
||||
if apply_boot(job, boot_at, now):
|
||||
changed.add(job)
|
||||
for job in changed:
|
||||
await _window(session, job, await _host_name(session, job.host_id), now)
|
||||
await _moved(session, job, now)
|
||||
return len(changed)
|
||||
|
||||
|
||||
async def handoffs(session, host_id: str, host_name: str, now: datetime) -> list[dict]:
|
||||
async def handoffs(session, host_id: str, host_name: str, now: datetime,
|
||||
agent_version: str | None = None) -> list[dict]:
|
||||
"""The steps this host's agent should carry out now. A queued job for the
|
||||
host starts here, when its agent is known to be listening."""
|
||||
host starts here, when its agent is known to be listening, with a check
|
||||
when the agent is new enough to hand one over. A manager also carries out
|
||||
a run's rebalance."""
|
||||
from sqlalchemy import or_, select
|
||||
from . import rebalance
|
||||
from .models import HostMaintenanceJob
|
||||
jobs = (await session.execute(select(HostMaintenanceJob).where(
|
||||
HostMaintenanceJob.state.in_(ACTIVE),
|
||||
@@ -282,25 +457,46 @@ async def handoffs(session, host_id: str, host_name: str, now: datetime) -> list
|
||||
out = []
|
||||
for job in jobs:
|
||||
if job.state == "queued" and job.host_id == host_id:
|
||||
start(job, now)
|
||||
start(job, now, check=can_check(agent_version))
|
||||
await _window(session, job, host_name, now)
|
||||
if executor(job) == host_id:
|
||||
step = handoff(job)
|
||||
if step is not None:
|
||||
out.append(step)
|
||||
return out
|
||||
return out + await rebalance.handoffs(session, host_id)
|
||||
|
||||
|
||||
async def _running(session, job) -> set:
|
||||
"""The job's host's containers seen running since the job came to its
|
||||
state; without the Docker plugin, the ones it waits for, as nothing can
|
||||
say otherwise."""
|
||||
from sqlalchemy import select
|
||||
models = docker_models()
|
||||
if models is None:
|
||||
return {c["name"] for c in outside_swarm(job)}
|
||||
DockerContainer = models.DockerContainer
|
||||
return set((await session.execute(select(DockerContainer.name).where(
|
||||
DockerContainer.host_id == job.host_id, DockerContainer.status == "running",
|
||||
DockerContainer.scraped_at >= job.state_at))).scalars())
|
||||
|
||||
|
||||
async def tick(session, now: datetime) -> int:
|
||||
"""Give up on jobs past their deadline; returns how many."""
|
||||
"""Move on the jobs waiting on Steward (the wait after a drain, the
|
||||
containers seen again) and give up on jobs past their deadline; returns
|
||||
how many were given up."""
|
||||
from sqlalchemy import select
|
||||
from .models import HostMaintenanceJob
|
||||
gave_up = 0
|
||||
for job in (await session.execute(select(HostMaintenanceJob).where(
|
||||
HostMaintenanceJob.state.in_(ACTIVE)))).scalars():
|
||||
moved = settle(job, now)
|
||||
if job.state == "recovering":
|
||||
moved = recovered(job, await _running(session, job), now) or moved
|
||||
if check_deadline(job, now):
|
||||
gave_up += 1
|
||||
await _window(session, job, await _host_name(session, job.host_id), now)
|
||||
moved = True
|
||||
if moved:
|
||||
await _moved(session, job, now)
|
||||
return gave_up
|
||||
|
||||
|
||||
@@ -344,14 +540,19 @@ async def plan_job(session, host, reg, reboot_policy: str = "if_required") -> tu
|
||||
HostMaintenanceJob.state.in_(ACTIVE)))).first()
|
||||
if busy is not None:
|
||||
raise CannotStart("a maintenance job is already running on it")
|
||||
if reboot_policy == "never":
|
||||
return None, None
|
||||
nodes, managers, availability = await _swarm(session)
|
||||
helpers = set((await session.execute(select(HostAgentRegistration.host_id).where(
|
||||
HostAgentRegistration.maint_helper.is_(True)))).scalars())
|
||||
node_id = nodes.get(host.name.lower())
|
||||
return pick_drainer(nodes, managers, host.name, host.id, helpers,
|
||||
availability.get(node_id, "active"))
|
||||
try:
|
||||
return pick_drainer(nodes, managers, host.name, host.id, helpers,
|
||||
availability.get(node_id, "active"))
|
||||
except CannotStart:
|
||||
# A job that never reboots needs a drain only if Docker is upgraded;
|
||||
# with no manager to drain, it runs undrained rather than not at all.
|
||||
if reboot_policy == "never":
|
||||
return None, None
|
||||
raise
|
||||
|
||||
|
||||
async def create_job(session, host, reg, user_id: str | None,
|
||||
@@ -383,21 +584,42 @@ async def latest_job(session, host_id: str, now: datetime, days: int = 366):
|
||||
|
||||
LABELS = {
|
||||
"queued": "Waiting for the agent",
|
||||
"updating": "Updating",
|
||||
"checking": "Checking what the update will change",
|
||||
"draining": "Draining its swarm node",
|
||||
"settling": "Giving its swarm tasks 5 min to move",
|
||||
"updating": "Updating",
|
||||
"rebooting": "Rebooting",
|
||||
"undraining": "Making its swarm node active again",
|
||||
"recovering": "Waiting for its containers to run again",
|
||||
"done": "Done",
|
||||
"failed": "Failed",
|
||||
"timed_out": "Timed out",
|
||||
}
|
||||
|
||||
|
||||
def came_back_late(job) -> bool:
|
||||
"""A job failed only for not coming back into service in time, whose
|
||||
host has since been found back (#6175)."""
|
||||
return (job.state == "failed" and job.came_back_at is not None
|
||||
and (job.detail or "").startswith(NOT_BACK))
|
||||
|
||||
|
||||
def still_failed(job) -> bool:
|
||||
"""Whether a finished job still flags its host: it failed or timed out,
|
||||
and isn't a late return whose host has since come back (#6175). The
|
||||
maintenance_failed figure, the overview and the pages all ask this."""
|
||||
return job.state in ("failed", "timed_out") and not came_back_late(job)
|
||||
|
||||
|
||||
def summary(job) -> str:
|
||||
"""One line on what the job did, for the panel."""
|
||||
if job.state not in FINISHED:
|
||||
return LABELS[job.state]
|
||||
if came_back_late(job):
|
||||
return f"Back in service late, {job.came_back_at:%Y-%m-%d %H:%M}Z"
|
||||
parts = []
|
||||
if job.docker_update:
|
||||
parts.append("Docker upgraded")
|
||||
if job.packages is not None:
|
||||
parts.append(f"{job.packages} package{'s' if job.packages != 1 else ''} updated")
|
||||
if job.back_at is not None:
|
||||
|
||||
@@ -5,14 +5,18 @@ from datetime import timedelta
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
import json
|
||||
|
||||
from steward.hosts import service as host_svc
|
||||
from steward.mcp._context import mcp_app
|
||||
from steward.mcp.tools._shape import age_s, db_session, iso, now_utc
|
||||
from steward.mcp._context import current_caller, mcp_app
|
||||
from steward.mcp.tools._audit import audit_mcp
|
||||
from steward.mcp.tools._shape import age_s, clamp_limit, db_session, iso, lookback, now_utc, pick, rnd
|
||||
from steward.mcp.tools.overview import finding
|
||||
from steward.models.hosts import Host
|
||||
from steward.models.users import UserRole
|
||||
|
||||
from .models import HostAgentRegistration
|
||||
from . import cadence, maintenance, rebalance, senders
|
||||
from .models import HostAgentRegistration, HostMaintenanceJob, HostMaintenancePlan, HostMaintenanceRun
|
||||
|
||||
# A registration this old that has never checked in is a failed install, not one in progress.
|
||||
PENDING_GRACE = timedelta(minutes=30)
|
||||
@@ -80,21 +84,300 @@ async def list_agents() -> dict:
|
||||
return {"stale_after_s": stale_after, "counts": counts, "agents": agents, "total": len(agents)}
|
||||
|
||||
|
||||
# ── maintenance (#5834): plans, runs, jobs, and starting one ─────────────────
|
||||
|
||||
JOBS_MAX = 50
|
||||
# A failed job stays on the overview this long, unless a later one succeeded.
|
||||
FAILED_JOB_DAYS = 7
|
||||
|
||||
|
||||
async def _names(db, ids) -> dict[str, str]:
|
||||
from steward.models.users import User
|
||||
ids = {i for i in ids if i}
|
||||
if not ids:
|
||||
return {}
|
||||
hosts = dict((await db.execute(select(Host.id, Host.name).where(Host.id.in_(ids)))).all())
|
||||
users = dict((await db.execute(select(User.id, User.username).where(User.id.in_(ids)))).all())
|
||||
return {**users, **hosts}
|
||||
|
||||
|
||||
def _job_row(job, names: dict, now) -> dict:
|
||||
deadline = maintenance.DEADLINES.get(job.state)
|
||||
started = job.created_at if job.state == "queued" else job.state_at
|
||||
return {
|
||||
"job_id": job.id,
|
||||
"host": names.get(job.host_id, job.host_id),
|
||||
"state": job.state,
|
||||
"label": maintenance.LABELS.get(job.state, job.state),
|
||||
"summary": maintenance.summary(job),
|
||||
"active": job.state in maintenance.ACTIVE,
|
||||
"reboot_policy": job.reboot_policy,
|
||||
"packages_updated": job.packages,
|
||||
"reboot_needed": job.reboot_needed,
|
||||
"rebooted_at": iso(job.back_at),
|
||||
"swarm_node": job.node_id,
|
||||
"drained_by": names.get(job.drain_host_id, job.drain_host_id),
|
||||
"drained_at": iso(job.drained_at),
|
||||
"came_back_at": iso(job.came_back_at),
|
||||
"ends_as": job.ends_as,
|
||||
"docker_update": job.docker_update,
|
||||
"checked": job.checked,
|
||||
"detail": job.detail,
|
||||
"state_since": iso(job.state_at), "state_age_s": age_s(job.state_at, now),
|
||||
"gives_up_at": iso(started + deadline) if deadline and started else None,
|
||||
"started_by": names.get(job.created_by) if job.created_by else
|
||||
("maintenance plan" if job.run_id else None),
|
||||
"run_id": job.run_id,
|
||||
"created_at": iso(job.created_at),
|
||||
"finished_at": iso(job.finished_at),
|
||||
}
|
||||
|
||||
|
||||
async def list_maintenance_plans() -> dict:
|
||||
"""Each maintenance plan: which inventory group it updates, when (weekly
|
||||
slot, time zone, how long a run may keep starting hosts), its reboot
|
||||
policy, whether it is enabled, its next slot, and its latest run.
|
||||
|
||||
A run updates the group's hosts one at a time; `latest_run` says how far
|
||||
it got (`hosts_done` of `hosts`), which hosts it passed over and why
|
||||
(`skipped`), and how it ended. `last_slot_at` is the last scheduled slot
|
||||
that fired, null until one has. get_maintenance_job shows one host's job.
|
||||
Plans are created and edited on the Maintenance page.
|
||||
|
||||
With `spread_after_run`, a run that drained swarm nodes ends by spreading
|
||||
the swarm's services back out, leaving `keep_in_place` where they are;
|
||||
`latest_run.spread` says what it moved and what it left and why (state:
|
||||
handed, done, failed, timed_out, or nothing to move), null when the run
|
||||
had none.
|
||||
"""
|
||||
from steward.models.ansible_inventory import AnsibleGroup
|
||||
now = now_utc()
|
||||
async with db_session() as db:
|
||||
plans = list((await db.execute(select(HostMaintenancePlan)
|
||||
.order_by(HostMaintenancePlan.name))).scalars())
|
||||
groups = dict((await db.execute(select(AnsibleGroup.id, AnsibleGroup.name))).all())
|
||||
latest = {}
|
||||
for plan in plans:
|
||||
latest[plan.id] = (await db.execute(
|
||||
select(HostMaintenanceRun).where(HostMaintenanceRun.plan_id == plan.id)
|
||||
.order_by(HostMaintenanceRun.started_at.desc()).limit(1))).scalar_one_or_none()
|
||||
names = await _names(db, [h for r in latest.values() if r
|
||||
for h in json.loads(r.host_ids or "[]")
|
||||
+ [x["host_id"] for x in json.loads(r.skipped or "[]")]])
|
||||
out = []
|
||||
for plan in plans:
|
||||
run = latest[plan.id]
|
||||
nxt = cadence.next_slot(plan, now) if plan.enabled else None
|
||||
row = {
|
||||
"plan_id": plan.id, "name": plan.name,
|
||||
"group": groups.get(plan.group_id, plan.group_id),
|
||||
"schedule": cadence.describe(plan),
|
||||
"weekday": cadence.WEEKDAYS[plan.weekday], "at_time": plan.at_time,
|
||||
"time_zone": plan.time_zone, "window_minutes": plan.window_minutes,
|
||||
"reboot_policy": plan.reboot_policy, "enabled": plan.enabled,
|
||||
"spread_after_run": plan.spread,
|
||||
"keep_in_place": rebalance.keep_list(plan.keep_in_place),
|
||||
"next_slot_at": iso(nxt), "last_slot_at": iso(cadence.fired_slot(plan)),
|
||||
"latest_run": None,
|
||||
}
|
||||
if run:
|
||||
hosts = json.loads(run.host_ids or "[]")
|
||||
row["latest_run"] = {
|
||||
"run_id": run.id, "state": run.state, "manual": run.manual,
|
||||
"hosts": [names.get(h, h) for h in hosts],
|
||||
"hosts_done": min(run.position, len(hosts)),
|
||||
"skipped": [{"host": names.get(x["host_id"], x["host_id"]), "reason": x["reason"]}
|
||||
for x in json.loads(run.skipped or "[]")],
|
||||
"detail": run.detail,
|
||||
"spread": _spread_row(run.rebalance),
|
||||
"started_at": iso(run.started_at), "finished_at": iso(run.finished_at),
|
||||
}
|
||||
out.append(row)
|
||||
return {"plans": out, "total": len(out)}
|
||||
|
||||
|
||||
def _spread_row(rb: dict | None) -> dict | None:
|
||||
"""A run's rebalance as the tool shows it: no step ids or window ids."""
|
||||
if not rb:
|
||||
return None
|
||||
return {"state": rb.get("state"), "planned": rb.get("planned") or [],
|
||||
"moved": rb.get("moved") or [], "left": rb.get("left") or [],
|
||||
"detail": rb.get("detail"), "started_at": rb.get("at"),
|
||||
"finished_at": rb.get("finished_at")}
|
||||
|
||||
|
||||
async def get_maintenance_job(host: str = "", job: str = "", limit: int = 10) -> dict:
|
||||
"""A host's maintenance jobs, newest first (its running one first), or one
|
||||
job by id.
|
||||
|
||||
host: a host's name or id (list_hosts); job: a job id (from here, or a
|
||||
plan's run). One of the two.
|
||||
limit: how many of the host's jobs (default 10, max 50).
|
||||
|
||||
A job is one host's update and, only when the update needs it, a reboot,
|
||||
with its swarm node drained first and made active again after. It first
|
||||
checks what the update would change: `docker_update` is whether it
|
||||
upgrades Docker (whose packages restart the daemon), and `checked` holds
|
||||
{pending, docker_packages, containers}, the containers then running
|
||||
outside the swarm. A swarm node is drained before an update that upgrades
|
||||
Docker, else before a reboot; `drained_at` is when, and its tasks get 5
|
||||
min to move (settling). `state` moves queued → [checking →] [draining →
|
||||
settling →] updating → [draining → settling →] [rebooting →]
|
||||
[undraining →] [recovering →] done, or failed / timed_out; a job given
|
||||
up while its node may be drained goes through undraining first, and
|
||||
`ends_as` is what it then finishes as. recovering
|
||||
waits up to 10 min for those containers to run again; `detail` says why
|
||||
a job failed, naming any that didn't. A job failed only for not coming
|
||||
back into service in time has `came_back_at`, when its host was first
|
||||
found back; from then it no longer flags the host. `summary` is the host page's line
|
||||
("Done: 12 packages updated, rebooted"). `gives_up_at` is when an active
|
||||
job's current state times out.
|
||||
"""
|
||||
if bool(host.strip()) == bool(job.strip()):
|
||||
raise ValueError("pass either `host` (a name or id) or `job` (a job id).")
|
||||
now = now_utc()
|
||||
limit = clamp_limit(limit, 10, JOBS_MAX)
|
||||
async with db_session() as db:
|
||||
if job.strip():
|
||||
row = await db.get(HostMaintenanceJob, job.strip())
|
||||
if row is None:
|
||||
raise ValueError(f"no maintenance job {job.strip()!r}; "
|
||||
"get_maintenance_job(host=...) lists a host's jobs.")
|
||||
jobs = [row]
|
||||
else:
|
||||
h = pick(host, (await db.execute(select(Host))).scalars(),
|
||||
kind="host", list_tool="list_hosts")
|
||||
jobs = list((await db.execute(
|
||||
select(HostMaintenanceJob).where(HostMaintenanceJob.host_id == h.id)
|
||||
.order_by(HostMaintenanceJob.state.in_(maintenance.ACTIVE).desc(),
|
||||
HostMaintenanceJob.created_at.desc())
|
||||
.limit(limit + 1))).scalars())
|
||||
names = await _names(db, [j.host_id for j in jobs] + [j.drain_host_id for j in jobs]
|
||||
+ [j.created_by for j in jobs])
|
||||
rows = [_job_row(j, names, now) for j in jobs[:limit]]
|
||||
return {"jobs": rows, "total": len(rows), "truncated": len(jobs) > limit}
|
||||
|
||||
|
||||
async def get_host_senders(host: str, range: str = "1h", direction: str = "tx", limit: int = 10) -> dict:
|
||||
"""Who sent (or received) a host's network traffic: its containers and NFS
|
||||
mounts, ranked against the host's own total.
|
||||
|
||||
host: name or id (list_hosts). range: "1h" (default), "6h", "24h" or "7d"
|
||||
(at most the raw window; the rollup keeps no per-sender detail).
|
||||
direction: "tx" (default, what the host sent) or "rx" (what it received).
|
||||
limit: senders listed (default 10, max 50).
|
||||
|
||||
The window is cut into about 120 buckets (`bucket_s` wide). `host` is the
|
||||
host's physical interfaces: average, peak and the bucket it peaked in.
|
||||
Each sender is a container (a swarm service's tasks added up, by service
|
||||
name) or an NFS mount, with its average over the window, its own peak
|
||||
and when, and `at_host_peak_bps`, what it sent in the host's peak bucket;
|
||||
biggest there first. `unaccounted_*` is what the host carried beyond them
|
||||
all: the host itself (a download, a backup run on the host, swarm ingress
|
||||
passing traffic to another node). A container's traffic to another on
|
||||
the same host counts for it without crossing an interface, so senders
|
||||
can add up to more than the host. Per-container rates need Steward after
|
||||
#6115; NFS bytes need agent 1.25.0. Bytes a second throughout.
|
||||
"""
|
||||
since, key = lookback(range)
|
||||
limit = clamp_limit(limit, 10, 50)
|
||||
async with db_session() as db:
|
||||
h = pick(host, (await db.execute(select(Host))).scalars(), kind="host", list_tool="list_hosts")
|
||||
got = await senders.senders(db, h.name, since, direction=direction, limit=limit)
|
||||
if got["host"] is None:
|
||||
raise ValueError(f"no net_{direction}_bps recorded for host {h.name!r} in the last {key}; "
|
||||
"is its agent reporting? list_agents says.")
|
||||
return {
|
||||
"host_id": h.id, "host_name": h.name, "range": key, "direction": direction,
|
||||
"since": iso(got["since"]), "bucket_s": got["bucket_s"],
|
||||
"host": {"avg_bps": rnd(got["host"]["avg_bps"], 1), "peak_bps": rnd(got["host"]["peak_bps"], 1),
|
||||
"peak_at": iso(got["host"]["peak_at"])},
|
||||
"senders": [{"kind": r["kind"], "name": r["name"], "at_host_peak_bps": rnd(r["at_host_peak_bps"], 1),
|
||||
"avg_bps": rnd(r["avg_bps"], 1), "peak_bps": rnd(r["peak_bps"], 1),
|
||||
"peak_at": iso(r["peak_at"])} for r in got["senders"]],
|
||||
"more": got["more"],
|
||||
"unaccounted_avg_bps": rnd(got["unaccounted_avg_bps"], 1),
|
||||
"unaccounted_at_peak_bps": rnd(got["unaccounted_at_peak_bps"], 1),
|
||||
}
|
||||
|
||||
|
||||
async def run_maintenance(host: str, reboot: str = "if_required") -> dict:
|
||||
"""Update a host now, as the host page's Update now does: the job starts
|
||||
with the agent's next post and get_maintenance_job follows it.
|
||||
|
||||
host: the host's name or id.
|
||||
reboot: "if_required" (default) reboots only when the update says the
|
||||
host needs it, draining its swarm node first and making it active after;
|
||||
"never" updates and leaves any reboot for later.
|
||||
|
||||
Refused while the host already has a job running, or when its agent has
|
||||
no maintenance helper yet (Update agent installs it). Admin only, as on
|
||||
the page. Recorded in the audit log.
|
||||
"""
|
||||
if reboot not in ("if_required", "never"):
|
||||
raise ValueError('reboot must be "if_required" or "never". Nothing was started.')
|
||||
caller = current_caller()
|
||||
async with db_session() as db, db.begin():
|
||||
h = pick(host, (await db.execute(select(Host))).scalars(),
|
||||
kind="host", list_tool="list_hosts")
|
||||
reg = (await db.execute(select(HostAgentRegistration).where(
|
||||
HostAgentRegistration.host_id == h.id))).scalar_one_or_none()
|
||||
try:
|
||||
created = await maintenance.create_job(db, h, reg, caller.user_id, reboot)
|
||||
except maintenance.CannotStart as exc:
|
||||
raise ValueError(f"{h.name} can't be updated now: {exc}. Nothing was started.") from None
|
||||
job_id, host_id, name = created.id, h.id, h.name
|
||||
await audit_mcp("host_agent.maintenance", "host", host_id,
|
||||
{"job_id": job_id, "reboot_policy": reboot})
|
||||
return {"job_id": job_id, "host": name, "state": "queued", "reboot_policy": reboot,
|
||||
"next": f'get_maintenance_job(job="{job_id}") follows it; it starts with the '
|
||||
"agent's next post."}
|
||||
|
||||
|
||||
async def _failed_jobs(db, now) -> list:
|
||||
"""Each host's latest finished job, when it failed or timed out within
|
||||
FAILED_JOB_DAYS and still flags the host (a later success clears it, and
|
||||
so does a late return once the host is back, #6175)."""
|
||||
rows = (await db.execute(
|
||||
select(HostMaintenanceJob, Host.name).join(Host, Host.id == HostMaintenanceJob.host_id)
|
||||
.where(HostMaintenanceJob.state.in_(maintenance.FINISHED),
|
||||
HostMaintenanceJob.finished_at >= now - timedelta(days=FAILED_JOB_DAYS))
|
||||
.order_by(HostMaintenanceJob.finished_at.desc()))).all()
|
||||
latest = {}
|
||||
for j, name in rows:
|
||||
latest.setdefault(j.host_id, (j, name))
|
||||
return [(j, name) for j, name in latest.values() if maintenance.still_failed(j)]
|
||||
|
||||
|
||||
async def mcp_overview(db) -> list[dict]:
|
||||
"""Agents registered more than PENDING_GRACE ago that have never checked in.
|
||||
"""Agents registered more than PENDING_GRACE ago that have never checked
|
||||
in, and hosts whose latest maintenance job failed or timed out.
|
||||
|
||||
Agents that stopped reporting are already flagged by the core overview
|
||||
from their metrics, so they are not repeated here.
|
||||
"""
|
||||
now = now_utc()
|
||||
return [
|
||||
out = [
|
||||
finding("warning", "agent_never_reported", h.name,
|
||||
"host agent was registered but has never checked in; the install may have failed",
|
||||
since=reg.created_at, ids={"host_id": h.id}, next="list_agents()")
|
||||
for reg, h in await _agents(db)
|
||||
if reg.last_seen_at is None and now - reg.created_at > PENDING_GRACE
|
||||
]
|
||||
out += [
|
||||
finding("warning", "maintenance_failed", name,
|
||||
f"maintenance {maintenance.LABELS[j.state].lower()}"
|
||||
+ (f": {j.detail}" if j.detail else ""),
|
||||
since=j.finished_at, ids={"host_id": j.host_id, "job_id": j.id},
|
||||
next=f'get_maintenance_job(job="{j.id}")')
|
||||
for j, name in await _failed_jobs(db, now)
|
||||
]
|
||||
return out
|
||||
|
||||
|
||||
def register_tools(register) -> None:
|
||||
register(list_agents, role=UserRole.viewer, read_only=True)
|
||||
register(list_maintenance_plans, role=UserRole.viewer, read_only=True)
|
||||
register(get_maintenance_job, role=UserRole.viewer, read_only=True)
|
||||
register(get_host_senders, role=UserRole.viewer, read_only=True)
|
||||
register(run_maintenance, role=UserRole.admin, read_only=False)
|
||||
|
||||
@@ -21,10 +21,20 @@ SOURCE_MODULE = "host_agent"
|
||||
HISTORY_METRICS = (
|
||||
"cpu_pct", "mem_used_pct", "disk_used_pct_worst", "load_1m",
|
||||
"net_rx_bps", "net_tx_bps", "disk_read_bps", "disk_write_bps",
|
||||
"temp_c_max", "psi_mem_some_avg10",
|
||||
"temp_c_max", "psi_mem_some_avg10", "nfs_exe_max_ms", "mounts_stalled",
|
||||
)
|
||||
|
||||
|
||||
async def has_nfs(session, host_name: str) -> bool:
|
||||
"""Whether the host's agent has reported an NFS mount's delay (#5996)."""
|
||||
from steward.models.metrics import PluginMetricLatest
|
||||
return (await session.execute(
|
||||
select(PluginMetricLatest.metric_name).where(
|
||||
PluginMetricLatest.source_module == SOURCE_MODULE,
|
||||
PluginMetricLatest.resource_name.startswith(host_name + ":"),
|
||||
PluginMetricLatest.metric_name == "nfs_ops_per_sec").limit(1))).first() is not None
|
||||
|
||||
|
||||
async def _latest_metrics_for_host(session, host_name: str) -> dict[str, dict[str, float]]:
|
||||
"""{resource_name: {metric: value}} — latest sample per (resource, metric) for
|
||||
a host + its sub-resources, from plugin_metric_latest (#5208). A host whose
|
||||
|
||||
@@ -0,0 +1,32 @@
|
||||
# plugins/host_agent/migrations/versions/host_agent_010_maint_check.py
|
||||
"""host_agent: a maintenance job's check of what its update would change, and
|
||||
when it drained its node (#6098)
|
||||
|
||||
Revision ID: host_agent_010_maint_check
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision: str = "host_agent_010_maint_check"
|
||||
down_revision: Union[str, None] = "host_agent_009_drive_health"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("host_maintenance_jobs", sa.Column("docker_update", sa.Boolean(), nullable=True))
|
||||
op.add_column("host_maintenance_jobs", sa.Column("checked", sa.JSON(), nullable=True))
|
||||
op.add_column("host_maintenance_jobs",
|
||||
sa.Column("drained_at", sa.DateTime(timezone=True), nullable=True))
|
||||
# A job already past its drain when this lands still makes its node
|
||||
# active again: before this, every job that drained went on to undrain.
|
||||
op.execute("UPDATE host_maintenance_jobs SET drained_at = state_at "
|
||||
"WHERE state IN ('rebooting', 'undraining') "
|
||||
"AND node_id IS NOT NULL AND drain_host_id IS NOT NULL")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("host_maintenance_jobs", "drained_at")
|
||||
op.drop_column("host_maintenance_jobs", "checked")
|
||||
op.drop_column("host_maintenance_jobs", "docker_update")
|
||||
@@ -0,0 +1,23 @@
|
||||
# plugins/host_agent/migrations/versions/host_agent_011_came_back.py
|
||||
"""host_agent: when a job failed for not coming back into service in time
|
||||
first found its host back (#6175)
|
||||
|
||||
Revision ID: host_agent_011_came_back
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision: str = "host_agent_011_came_back"
|
||||
down_revision: Union[str, None] = "host_agent_010_maint_check"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("host_maintenance_jobs",
|
||||
sa.Column("came_back_at", sa.DateTime(timezone=True), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("host_maintenance_jobs", "came_back_at")
|
||||
@@ -0,0 +1,22 @@
|
||||
# plugins/host_agent/migrations/versions/host_agent_012_ends_as.py
|
||||
"""host_agent: what a job given up while its node may be drained finishes as,
|
||||
once the node is active again
|
||||
|
||||
Revision ID: host_agent_012_ends_as
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision: str = "host_agent_012_ends_as"
|
||||
down_revision: Union[str, None] = "host_agent_011_came_back"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("host_maintenance_jobs", sa.Column("ends_as", sa.String(16), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("host_maintenance_jobs", "ends_as")
|
||||
@@ -0,0 +1,28 @@
|
||||
# plugins/host_agent/migrations/versions/host_agent_013_spread.py
|
||||
"""host_agent: a maintenance run spreads swarm services back out after its
|
||||
last host, and a plan can keep named services where they are
|
||||
|
||||
Revision ID: host_agent_013_spread
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
from alembic import op
|
||||
import sqlalchemy as sa
|
||||
|
||||
revision: str = "host_agent_013_spread"
|
||||
down_revision: Union[str, None] = "host_agent_012_ends_as"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("host_maintenance_plans", sa.Column("spread", sa.Boolean, nullable=False,
|
||||
server_default=sa.true()))
|
||||
op.add_column("host_maintenance_plans", sa.Column("keep_in_place", sa.Text, nullable=False,
|
||||
server_default=""))
|
||||
op.add_column("host_maintenance_runs", sa.Column("rebalance", sa.JSON, nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("host_maintenance_runs", "rebalance")
|
||||
op.drop_column("host_maintenance_plans", "keep_in_place")
|
||||
op.drop_column("host_maintenance_plans", "spread")
|
||||
@@ -114,6 +114,19 @@ class HostMaintenanceJob(Base):
|
||||
# The cadence run this job belongs to (#5768); None for Update now.
|
||||
run_id = Column(String(36), ForeignKey("host_maintenance_runs.id", ondelete="SET NULL"),
|
||||
nullable=True, index=True)
|
||||
# What the check said the update would change (#6098): whether it
|
||||
# upgrades Docker, and {pending, docker_packages, containers} with the
|
||||
# containers then running outside the swarm. drained_at is when the job's
|
||||
# drain finished, before the update or before the reboot.
|
||||
docker_update = Column(Boolean, nullable=True)
|
||||
checked = Column(JSON, nullable=True)
|
||||
drained_at = Column(DateTime(timezone=True), nullable=True)
|
||||
# A job failed for not coming back into service in time: when its host
|
||||
# was first found back (#6175). From then on the job no longer flags it.
|
||||
came_back_at = Column(DateTime(timezone=True), nullable=True)
|
||||
# A job given up (failed or timed_out) while its node may be drained makes
|
||||
# the node active again first; ends_as is what it finishes as after that.
|
||||
ends_as = Column(String(16), nullable=True)
|
||||
|
||||
|
||||
class HostMaintenancePlan(Base):
|
||||
@@ -121,7 +134,9 @@ class HostMaintenancePlan(Base):
|
||||
`at_time` in `time_zone`, its hosts are updated one at a time, each
|
||||
rebooting per `reboot_policy`. No host is started after `window_minutes`
|
||||
from the run's start. last_slot_at is the last scheduled slot that fired;
|
||||
Run now leaves it alone, so the schedule keeps its time."""
|
||||
Run now leaves it alone, so the schedule keeps its time. With `spread`, a
|
||||
run that drained swarm nodes ends by spreading services back out, leaving
|
||||
the services named in `keep_in_place` (comma-separated) where they are."""
|
||||
__tablename__ = "host_maintenance_plans"
|
||||
|
||||
id = Column(String(36), primary_key=True, default=_uuid)
|
||||
@@ -134,6 +149,8 @@ class HostMaintenancePlan(Base):
|
||||
window_minutes = Column(Integer, nullable=False, default=240)
|
||||
reboot_policy = Column(String(16), nullable=False, default="if_required")
|
||||
enabled = Column(Boolean, nullable=False, default=True)
|
||||
spread = Column(Boolean, nullable=False, default=True)
|
||||
keep_in_place = Column(Text, nullable=False, default="")
|
||||
last_slot_at = Column(DateTime(timezone=True), nullable=True)
|
||||
created_by = Column(String(36), ForeignKey("users.id", ondelete="SET NULL"), nullable=True)
|
||||
created_at = Column(DateTime(timezone=True), nullable=False, default=_utcnow)
|
||||
@@ -145,7 +162,10 @@ class HostMaintenanceRun(Base):
|
||||
host_ids is the order fixed at the start (JSON list); position is the host
|
||||
being worked on; skipped is [{"host_id", "reason"}] for hosts the run
|
||||
passed over. settle_since is when the current host's job finished and the
|
||||
run began waiting for the host to be back in service."""
|
||||
run began waiting for the host to be back in service. rebalance is the
|
||||
spreading of swarm services back out once the last host is back
|
||||
(rebalance.py): its state, the manager carrying it out, what it moved and
|
||||
what it left and why; None while not reached or not wanted."""
|
||||
__tablename__ = "host_maintenance_runs"
|
||||
|
||||
id = Column(String(36), primary_key=True, default=_uuid)
|
||||
@@ -158,5 +178,6 @@ class HostMaintenanceRun(Base):
|
||||
settle_since = Column(DateTime(timezone=True), nullable=True)
|
||||
detail = Column(Text, nullable=True)
|
||||
manual = Column(Boolean, nullable=False, default=False)
|
||||
rebalance = Column(JSON, nullable=True)
|
||||
started_at = Column(DateTime(timezone=True), nullable=False, default=_utcnow)
|
||||
finished_at = Column(DateTime(timezone=True), nullable=True)
|
||||
|
||||
@@ -0,0 +1,374 @@
|
||||
# plugins/host_agent/rebalance.py
|
||||
"""A maintenance run spreads swarm services back out after its last host.
|
||||
|
||||
A run drains each swarm node in turn, and the swarm never moves a task back
|
||||
on its own, so every run used to end with the services on whichever node was
|
||||
drained first. Once the run's last host is back in service, Steward picks
|
||||
services to move from the fullest node to the emptiest and hands the list to
|
||||
a swarm manager's helper (maint.py `rebalance`), which force-updates each in
|
||||
turn: spec unchanged, no image pulled, and the swarm starts it again on its
|
||||
emptiest node.
|
||||
|
||||
A service moves only when the emptier node already holds the exact image the
|
||||
service is pinned to (its agent reports every image digest it holds), so a
|
||||
pruned image or a digest the registry has since deleted never strands one.
|
||||
A service the plan keeps in place, one below its replicas, and one a
|
||||
constraint places are left where they are, and the run says why.
|
||||
|
||||
The choice is model-free (`choose`); the database side is below it, driven by
|
||||
cadence.advance, the agent's posts (handoffs, results) and the minute tick.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
from datetime import datetime, timedelta
|
||||
|
||||
from . import maintenance
|
||||
|
||||
# The first agent whose helper can rebalance, and that reports image digests.
|
||||
REBALANCE_AGENT = (1, 26, 0)
|
||||
# How many services one rebalance moves at most; the helper refuses more.
|
||||
SERVICES_MAX = 48
|
||||
# A node's list of images older than this isn't trusted (agents report it
|
||||
# every 10 minutes).
|
||||
DIGESTS_FRESH = timedelta(minutes=30)
|
||||
# The helper starts no move after 40 min and gives each 5 to settle.
|
||||
DEADLINE = timedelta(minutes=60)
|
||||
STATES = ("handed", "done", "failed", "timed_out", "nothing")
|
||||
WINDOW_NAME = "Maintenance: spreading swarm services back out"
|
||||
|
||||
|
||||
def keep_list(text: str | None) -> list[str]:
|
||||
"""A plan's keep_in_place as names, in the order written."""
|
||||
out = []
|
||||
for name in (text or "").replace("\n", ",").split(","):
|
||||
name = name.strip()
|
||||
if name and name not in out:
|
||||
out.append(name)
|
||||
return out
|
||||
|
||||
|
||||
def _repo(image: str) -> str:
|
||||
"""An image reference's repository, without tag or digest, in the short
|
||||
form Docker reports (no docker.io/ or library/)."""
|
||||
ref = image.split("@", 1)[0]
|
||||
slash = ref.rfind("/")
|
||||
colon = ref.rfind(":")
|
||||
if colon > slash:
|
||||
ref = ref[:colon]
|
||||
for prefix in ("docker.io/", "index.docker.io/"):
|
||||
if ref.startswith(prefix):
|
||||
ref = ref[len(prefix):]
|
||||
if ref.startswith("library/"):
|
||||
ref = ref[len("library/"):]
|
||||
return ref
|
||||
|
||||
|
||||
def pinned(image: str | None, digest: str | None) -> str | None:
|
||||
""""repo@sha256:…" for a service's image, or None when it isn't pinned."""
|
||||
if not image or not digest or not digest.startswith("sha256:"):
|
||||
return None
|
||||
return f"{_repo(image)}@{digest}"
|
||||
|
||||
|
||||
def held(digests) -> set:
|
||||
"""A node's reported digests, in the same form as pinned()."""
|
||||
return {f"{_repo(d)}@{d.split('@', 1)[1]}" for d in digests or []
|
||||
if isinstance(d, str) and "@sha256:" in d}
|
||||
|
||||
|
||||
def choose(services: list, nodes: dict, images: dict, keep=(),
|
||||
limit: int = SERVICES_MAX) -> tuple[list, list]:
|
||||
"""(services to move, [{"service", "reason"}] left where they are).
|
||||
|
||||
services: {"name", "mode", "desired", "running", "image" ("repo@sha256:…"
|
||||
or None), "placement": [{"node_id", "running"}]}; nodes: {node id: name}
|
||||
for the nodes to balance across (ready and active); images: {node id: set
|
||||
of "repo@sha256:…"}, a node missing when its list is unknown.
|
||||
|
||||
While the fullest node has two or more tasks than the emptiest, a service
|
||||
whose tasks all run on the fullest moves; one with several replicas there
|
||||
first, as one node holding them all defeats the replicas. A move counts
|
||||
as its share of the replicas going to the emptiest. What is reported left
|
||||
is what kept the nodes from evening out: the services that would have
|
||||
moved next but can't."""
|
||||
if len(nodes) < 2:
|
||||
return [], []
|
||||
counts = {n: 0 for n in nodes}
|
||||
for s in services:
|
||||
for p in s.get("placement") or []:
|
||||
if p.get("node_id") in counts:
|
||||
counts[p["node_id"]] += int(p.get("running") or 0)
|
||||
keep = set(keep)
|
||||
order = sorted(services, key=lambda s: (-int(s.get("running") or 0), s["name"]))
|
||||
moves: list = []
|
||||
left: dict = {}
|
||||
while len(moves) < limit:
|
||||
src = max(counts, key=lambda n: (counts[n], n))
|
||||
dst = min(counts, key=lambda n: (counts[n], n))
|
||||
gap = counts[src] - counts[dst]
|
||||
if gap < 2:
|
||||
break
|
||||
pick, blocked = None, {}
|
||||
for s in order:
|
||||
name, running = s["name"], int(s.get("running") or 0)
|
||||
on = {p.get("node_id"): int(p.get("running") or 0) for p in s.get("placement") or []
|
||||
if int(p.get("running") or 0) > 0}
|
||||
if name in moves or s.get("mode") != "replicated" or set(on) != {src}:
|
||||
continue
|
||||
share = max(1, running // len(nodes))
|
||||
if 2 * share > gap:
|
||||
continue # it would only tip the balance the other way
|
||||
if name in keep:
|
||||
blocked[name] = "kept in place by the plan"
|
||||
elif running < int(s.get("desired") or 0):
|
||||
blocked[name] = "below its replicas"
|
||||
elif not s.get("image"):
|
||||
blocked[name] = "its image isn't pinned to a digest"
|
||||
elif dst not in images:
|
||||
blocked[name] = f"no image list from {nodes[dst]} (its agent needs 1.26.0)"
|
||||
elif s["image"] not in images[dst]:
|
||||
blocked[name] = f"its image isn't on {nodes[dst]}"
|
||||
else:
|
||||
pick = s
|
||||
break
|
||||
if pick is None:
|
||||
left = blocked # what kept the nodes from evening out
|
||||
break
|
||||
share = max(1, int(pick.get("running") or 0) // len(nodes))
|
||||
moves.append(pick["name"])
|
||||
counts[src] -= share
|
||||
counts[dst] += share
|
||||
return moves, [{"service": n, "reason": r} for n, r in sorted(left.items())]
|
||||
|
||||
|
||||
def can_rebalance(agent_version) -> bool:
|
||||
try:
|
||||
return tuple(int(x) for x in str(agent_version).split(".")[:3]) >= REBALANCE_AGENT
|
||||
except ValueError:
|
||||
return False
|
||||
|
||||
|
||||
def step_id(run) -> str:
|
||||
return f"{run.id}-rebalance"
|
||||
|
||||
|
||||
def _set(run, **changes) -> None:
|
||||
"""Change the run's rebalance record (a new dict, so the JSON column
|
||||
sees the change)."""
|
||||
run.rebalance = {**(run.rebalance or {}), **changes}
|
||||
|
||||
|
||||
def handoff(run) -> dict | None:
|
||||
"""The step to hand the manager's agent, until its result arrives."""
|
||||
rb = run.rebalance or {}
|
||||
if rb.get("state") != "handed" or rb.get("seen"):
|
||||
return None
|
||||
return {"id": rb["step_id"], "action": "rebalance", "services": rb.get("planned") or []}
|
||||
|
||||
|
||||
def apply_result(run, event: dict, now: datetime) -> bool:
|
||||
"""A `maintenance` event for the run's rebalance; True when it changed."""
|
||||
rb = run.rebalance or {}
|
||||
if rb.get("state") != "handed" or event.get("id") != rb.get("step_id"):
|
||||
return False
|
||||
state = event.get("state")
|
||||
if state == "running":
|
||||
if rb.get("seen"):
|
||||
return False
|
||||
_set(run, seen=True)
|
||||
return True
|
||||
if state not in ("done", "failed"):
|
||||
return False
|
||||
moved = [str(m)[:64] for m in event.get("moved") or [] if isinstance(m, str)][:SERVICES_MAX]
|
||||
gone = [{"service": str(x.get("service"))[:64], "reason": str(x.get("reason"))[:160]}
|
||||
for x in event.get("left") or [] if isinstance(x, dict)][:SERVICES_MAX]
|
||||
ok = state == "done" and event.get("ok") is not False
|
||||
_set(run, state="done" if ok else "failed", moved=moved, left=(rb.get("left") or []) + gone,
|
||||
detail=str(event.get("detail") or "")[:maintenance.DETAIL_MAX] or None,
|
||||
finished_at=now.isoformat())
|
||||
return True
|
||||
|
||||
|
||||
def check_deadline(run, now: datetime) -> bool:
|
||||
rb = run.rebalance or {}
|
||||
if rb.get("state") != "handed" or now - datetime.fromisoformat(rb["at"]) <= DEADLINE:
|
||||
return False
|
||||
_set(run, state="timed_out", finished_at=now.isoformat(),
|
||||
detail=f"the manager didn't finish within {int(DEADLINE.total_seconds() // 60)} min")
|
||||
return True
|
||||
|
||||
|
||||
def outcome(run) -> tuple[str, str | None]:
|
||||
"""How a run whose hosts are all done ends: ("done" | "failed", detail)."""
|
||||
rb = run.rebalance or {}
|
||||
state = rb.get("state")
|
||||
left = rb.get("left") or []
|
||||
tail = f"; {len(left)} left where they are" if left else ""
|
||||
if state == "done":
|
||||
n = len(rb.get("moved") or [])
|
||||
return "done", f"spread {n} swarm service{'s' if n != 1 else ''} back out{tail}"
|
||||
if state in ("failed", "timed_out"):
|
||||
return "failed", f"spreading swarm services back out: {rb.get('detail') or state}"
|
||||
if state == "nothing" and rb.get("detail"):
|
||||
return "done", f"swarm services not spread back out: {rb['detail']}"
|
||||
if state == "nothing" and left:
|
||||
return "done", f"no swarm service could be spread back out{tail}"
|
||||
return "done", None
|
||||
|
||||
|
||||
def label(run) -> tuple[str, bool, bool] | None:
|
||||
"""(text, bad, busy) for the run's swarm row on the page, or None when
|
||||
the run has no rebalance."""
|
||||
rb = run.rebalance or {}
|
||||
state = rb.get("state")
|
||||
if state is None:
|
||||
return None
|
||||
if state == "handed":
|
||||
n = len(rb.get("planned") or [])
|
||||
return f"Spreading {n} service{'s' if n != 1 else ''} back out", False, True
|
||||
text = outcome(run)[1] or "Nothing to spread back out"
|
||||
return text[:1].upper() + text[1:], state in ("failed", "timed_out"), False
|
||||
|
||||
|
||||
# ── applied to the database ──────────────────────────────────────────────────
|
||||
|
||||
async def _freshest(session, model, key: str) -> list:
|
||||
"""The newest row per `key` (several managers may report the swarm)."""
|
||||
from sqlalchemy import select
|
||||
rows: dict = {}
|
||||
for r in (await session.execute(select(model))).scalars():
|
||||
k = getattr(r, key)
|
||||
if k not in rows or r.updated_at > rows[k].updated_at:
|
||||
rows[k] = r
|
||||
return list(rows.values())
|
||||
|
||||
|
||||
async def _swarm_view(session, now: datetime) -> tuple[list, dict, dict] | None:
|
||||
"""(services, nodes, images) as choose() takes them, from what the Docker
|
||||
plugin last stored; None without it."""
|
||||
from sqlalchemy import select
|
||||
from steward.models.hosts import Host
|
||||
models = maintenance.docker_models()
|
||||
if models is None:
|
||||
return None
|
||||
services = [{"name": s.service_name, "mode": s.mode, "desired": s.desired,
|
||||
"running": s.running, "image": pinned(s.image, s.image_digest),
|
||||
"placement": json.loads(s.placement_json or "[]")}
|
||||
for s in await _freshest(session, models.DockerSwarmService, "service_name")]
|
||||
nodes = {n.node_id: n.hostname or n.node_id
|
||||
for n in await _freshest(session, models.DockerSwarmNode, "node_id")
|
||||
if n.status == "ready" and n.availability == "active"}
|
||||
hosts = dict((await session.execute(select(Host.name, Host.id))).all())
|
||||
by_name = {name.lower(): hid for name, hid in hosts.items()}
|
||||
images = {}
|
||||
for node_id, name in nodes.items():
|
||||
host_id = by_name.get(name.lower())
|
||||
disk = await session.get(models.DockerDiskUsage, host_id) if host_id else None
|
||||
if disk is not None and now - disk.updated_at <= DIGESTS_FRESH:
|
||||
got = held(json.loads(disk.digests_json or "[]"))
|
||||
if got:
|
||||
images[node_id] = got
|
||||
return services, nodes, images
|
||||
|
||||
|
||||
async def _manager(session, jobs: list) -> tuple[str | None, str | None]:
|
||||
"""(host id, None) of a swarm manager whose helper can rebalance, the one
|
||||
that drained the run's nodes first; (None, why) when there is none."""
|
||||
from sqlalchemy import select
|
||||
from .models import HostAgentRegistration
|
||||
_, managers, _ = await maintenance._swarm(session)
|
||||
regs = {r.host_id: r for r in (await session.execute(select(HostAgentRegistration).where(
|
||||
HostAgentRegistration.host_id.in_(list(managers)),
|
||||
HostAgentRegistration.maint_helper.is_(True)))).scalars()} if managers else {}
|
||||
drained_by = [j.drain_host_id for j in jobs if j.drain_host_id]
|
||||
for host_id in drained_by + sorted(regs):
|
||||
reg = regs.get(host_id)
|
||||
if reg is not None and can_rebalance(reg.agent_version):
|
||||
return host_id, None
|
||||
if regs:
|
||||
return None, "no swarm manager's agent can do it yet: run Update agent on a manager"
|
||||
return None, "no swarm manager has the maintenance helper"
|
||||
|
||||
|
||||
async def begin(session, run, plan, now: datetime) -> bool:
|
||||
"""The run's last host is back in service: hand a manager the services to
|
||||
move, or record why there are none. True while a rebalance is handed out."""
|
||||
from sqlalchemy import select
|
||||
from .models import HostMaintenanceJob
|
||||
if not plan.spread or run.rebalance is not None:
|
||||
return False
|
||||
jobs = (await session.execute(select(HostMaintenanceJob).where(
|
||||
HostMaintenanceJob.run_id == run.id))).scalars().all()
|
||||
if not any(maintenance.drains(j) for j in jobs):
|
||||
return False # nothing was drained: nothing to put back
|
||||
view = await _swarm_view(session, now)
|
||||
if view is None:
|
||||
return False
|
||||
services, nodes, images = view
|
||||
moves, left = choose(services, nodes, images, keep_list(plan.keep_in_place))
|
||||
if not moves:
|
||||
run.rebalance = {"state": "nothing", "left": left, "at": now.isoformat()}
|
||||
return False
|
||||
host_id, why = await _manager(session, jobs)
|
||||
if host_id is None:
|
||||
run.rebalance = {"state": "nothing", "left": left, "detail": why, "at": now.isoformat()}
|
||||
return False
|
||||
run.rebalance = {"state": "handed", "step_id": step_id(run), "host_id": host_id,
|
||||
"at": now.isoformat(), "planned": moves, "left": left, "seen": False,
|
||||
"window_id": await _window(session, plan, now)}
|
||||
return True
|
||||
|
||||
|
||||
async def _window(session, plan, now: datetime) -> str | None:
|
||||
"""A window over the Docker figures while services restart, so their
|
||||
restarts raise no alert; ended when the rebalance does."""
|
||||
from steward.models.alerts import MaintenanceWindow
|
||||
if plan.created_by is None:
|
||||
return None
|
||||
w = MaintenanceWindow(name=WINDOW_NAME, start_at=now, end_at=now + DEADLINE,
|
||||
scope_source="docker", scope_resource=None, created_by=plan.created_by)
|
||||
session.add(w)
|
||||
await session.flush()
|
||||
return w.id
|
||||
|
||||
|
||||
async def finish(session, run, now: datetime) -> None:
|
||||
"""The rebalance ended: its window ends, and it goes on the timeline."""
|
||||
from steward.models.alerts import MaintenanceWindow
|
||||
from . import timeline
|
||||
rb = run.rebalance or {}
|
||||
if rb.get("window_id"):
|
||||
w = await session.get(MaintenanceWindow, rb["window_id"])
|
||||
if w is not None:
|
||||
w.end_at = max(w.start_at, now)
|
||||
if rb.get("state") in ("done", "failed", "timed_out"):
|
||||
await timeline.write(session, f"maintenance run {run.id}", timeline.run_entry(session, run))
|
||||
|
||||
|
||||
async def running_runs(session) -> list:
|
||||
from sqlalchemy import select
|
||||
from .models import HostMaintenanceRun
|
||||
return (await session.execute(select(HostMaintenanceRun).where(
|
||||
HostMaintenanceRun.state == "running"))).scalars().all()
|
||||
|
||||
|
||||
async def handoffs(session, host_id: str) -> list[dict]:
|
||||
"""The rebalance steps this host's agent should carry out now."""
|
||||
out = []
|
||||
for run in await running_runs(session):
|
||||
if (run.rebalance or {}).get("host_id") == host_id:
|
||||
step = handoff(run)
|
||||
if step is not None:
|
||||
out.append(step)
|
||||
return out
|
||||
|
||||
|
||||
async def apply_event(session, event: dict, now: datetime) -> bool:
|
||||
"""Apply a `maintenance` event to the running run whose rebalance it is."""
|
||||
for run in await running_runs(session):
|
||||
if apply_result(run, event, now):
|
||||
if (run.rebalance or {}).get("state") != "handed":
|
||||
await finish(session, run, now)
|
||||
return True
|
||||
return False
|
||||
@@ -36,6 +36,7 @@ from .metrics_query import (
|
||||
SOURCE_MODULE,
|
||||
_history_for_host,
|
||||
_latest_metrics_for_host,
|
||||
has_nfs,
|
||||
)
|
||||
|
||||
host_agent_bp = Blueprint("host_agent", __name__, template_folder="templates")
|
||||
@@ -121,6 +122,29 @@ def is_thermometer(host_name: str, label: str, celsius: float) -> bool:
|
||||
return label not in sensors.unwired(host_name) and counts_as_hottest(label, celsius)
|
||||
|
||||
|
||||
def hottest_sensor(host_name: str, temps: dict[str, float]) -> list[str]:
|
||||
"""Which sensor sets a host's temperature, as an alert on it says:
|
||||
["CPU · Package id 0 at 86°C"], or [] with no thermometer among `temps`.
|
||||
The chip leads the label when the host's agent has said which it is."""
|
||||
from steward.core.formatting import metric_value
|
||||
real = {label: c for label, c in temps.items() if is_thermometer(host_name, label, c)}
|
||||
if not real:
|
||||
return []
|
||||
from .sensors import sensor_name
|
||||
label = max(real, key=real.get)
|
||||
return [f"{sensor_name(host_name, label)} at {metric_value('temp_c', real[label])}"]
|
||||
|
||||
|
||||
async def name_hottest_sensor(session, resource: str) -> list[str]:
|
||||
"""The sensor behind temp_c_max on host `resource` right now."""
|
||||
from steward.models.metrics import PluginMetricLatest
|
||||
prefix = f"{resource}:temp:"
|
||||
rows = (await session.execute(select(PluginMetricLatest.resource_name, PluginMetricLatest.value).where(
|
||||
PluginMetricLatest.source_module == "host_agent", PluginMetricLatest.metric_name == "temp_c",
|
||||
PluginMetricLatest.resource_name.startswith(prefix, autoescape=True)))).all()
|
||||
return hottest_sensor(resource, {name[len(prefix):]: value for name, value in rows})
|
||||
|
||||
|
||||
def split_temps(host_name: str, temps: dict) -> tuple[dict, dict]:
|
||||
"""(real, unwired): a host's sensors, hottest first, apart from the ones
|
||||
is_thermometer leaves out. Unwired ones map to (reading, why); they read
|
||||
@@ -290,6 +314,27 @@ def _expand_sample_to_metrics(
|
||||
row("disk_used_pct_worst", host_name, worst_pct)
|
||||
row("mounts_stalled", host_name, stalled)
|
||||
|
||||
# NFS delay per mount (agent ≥ 1.22.0, #5996): what its requests took
|
||||
# since the last sample, and (agent ≥ 1.25.0, #6115) the bytes a second
|
||||
# it sent and received. The host's slowest mount is its own metric, for
|
||||
# a rule; recorded only when some mount finished a request, since a mount
|
||||
# with none, idle or stuck, has no delay to give (mounts_stalled covers
|
||||
# stuck).
|
||||
slowest = None
|
||||
for nfs in sample.get("nfs") or []:
|
||||
mount_res = f"{host_name}:{nfs['mount']}"
|
||||
for key, metric in (("ops_per_sec", "nfs_ops_per_sec"), ("rtt_ms", "nfs_rtt_ms"),
|
||||
("exe_ms", "nfs_exe_ms"), ("read_ms", "nfs_read_ms"),
|
||||
("write_ms", "nfs_write_ms"), ("retrans", "nfs_retrans"),
|
||||
("timeouts", "nfs_timeouts"), ("tx_bps", "nfs_tx_bps"),
|
||||
("rx_bps", "nfs_rx_bps")):
|
||||
if isinstance(nfs.get(key), (int, float)):
|
||||
row(metric, mount_res, nfs[key])
|
||||
if isinstance(nfs.get("exe_ms"), (int, float)):
|
||||
slowest = max(slowest or 0.0, nfs["exe_ms"])
|
||||
if slowest is not None:
|
||||
row("nfs_exe_max_ms", host_name, slowest)
|
||||
|
||||
# Per-core CPU. Sub-resources carry a ':' so the fleet widget filters them out.
|
||||
for i, core_pct in enumerate(sample.get("cpu_cores") or []):
|
||||
if core_pct is not None:
|
||||
@@ -331,6 +376,8 @@ def _expand_sample_to_metrics(
|
||||
# counts only readings that can be real (#5759), from sensors that behave
|
||||
# like thermometers (#5783).
|
||||
max_temp: float | None = None
|
||||
from .sensors import note_chips
|
||||
note_chips(host_name, sample.get("temps"))
|
||||
for t in sample.get("temps") or []:
|
||||
c = t.get("celsius")
|
||||
if c is None:
|
||||
@@ -512,7 +559,8 @@ async def ingest():
|
||||
await maintenance.apply_events(session, host.id, events, received_at)
|
||||
if reg.maint_helper:
|
||||
maint_steps = await maintenance.handoffs(
|
||||
session, host.id, host.name, received_at)
|
||||
session, host.id, host.name, received_at,
|
||||
payload.get("agent_version") or reg.agent_version)
|
||||
except Exception:
|
||||
maint_steps = []
|
||||
current_app.logger.exception(
|
||||
@@ -864,6 +912,10 @@ def _split_host_metrics(host_name: str, latest: dict) -> tuple:
|
||||
else:
|
||||
mounts[suffix] = metrics
|
||||
cores.sort(key=lambda c: c[0])
|
||||
# Fullest first, by the worse of space and inodes (#5810): a full
|
||||
# /var/lib/docker must not sort after /boot.
|
||||
mounts = dict(sorted(mounts.items(), key=lambda kv: (
|
||||
-max(kv[1].get("disk_used_pct") or 0, kv[1].get("inodes_used_pct") or 0), kv[0])))
|
||||
return hostlvl, cores, nets, disks_io, temps, mounts
|
||||
|
||||
|
||||
@@ -879,9 +931,10 @@ async def host_detail(host_id: str):
|
||||
select(Host).where(Host.id == host_id))).scalar_one_or_none()
|
||||
if host is None:
|
||||
return _error(404, "not_found")
|
||||
nfs = await has_nfs(session, host.name)
|
||||
return await render_template(
|
||||
"host_detail.html",
|
||||
host=host, current_range=range_key, range_options=RANGE_OPTIONS,
|
||||
host=host, current_range=range_key, range_options=RANGE_OPTIONS, has_nfs=nfs,
|
||||
poll_seconds=_DETAIL_POLL_SECONDS, chart_poll_seconds=_CHART_POLL_SECONDS,
|
||||
)
|
||||
|
||||
@@ -929,6 +982,23 @@ async def host_detail_charts(host_id: str):
|
||||
return await render_template("_host_charts.html", series=series, range_key=range_key)
|
||||
|
||||
|
||||
@host_agent_bp.get("/<host_id>/senders")
|
||||
@require_role(UserRole.viewer)
|
||||
async def host_detail_senders(host_id: str):
|
||||
"""Who sent the host's traffic over the range (#6115), lazy-loaded below
|
||||
the charts and refreshed with them."""
|
||||
from .senders import senders
|
||||
since, range_key = parse_range(request.args.get("range"))
|
||||
async with current_app.db_sessionmaker() as session:
|
||||
host = (await session.execute(
|
||||
select(Host).where(Host.id == host_id))).scalar_one_or_none()
|
||||
if host is None:
|
||||
return "", 404
|
||||
raw_days = int(await get_setting(session, "metrics.retention.raw_days") or 7)
|
||||
got = await senders(session, host.name, since, raw_days=raw_days)
|
||||
return await render_template("_host_senders.html", got=got, range_key=range_key)
|
||||
|
||||
|
||||
def _new_token_pair() -> tuple[str, str]:
|
||||
raw = secrets.token_urlsafe(32)
|
||||
return raw, _hash_token(raw)
|
||||
@@ -937,7 +1007,7 @@ def _new_token_pair() -> tuple[str, str]:
|
||||
@host_agent_bp.get("/vitals/<host_id>")
|
||||
@require_role(UserRole.viewer)
|
||||
async def host_vitals(host_id: str):
|
||||
"""Compact live vitals strip (CPU/MEM/DISK/LOAD + pressure) for the Hosts hub.
|
||||
"""Compact live vitals strip (CPU/MEM/DISK/LOAD/temperature + pressure) for the Hosts hub.
|
||||
|
||||
Self-contained fragment, polled by hosts/detail.html. Renders nothing until
|
||||
the agent reports — the Agent panel below then carries provisioning.
|
||||
@@ -952,15 +1022,16 @@ async def host_vitals(host_id: str):
|
||||
latest = await _latest_metrics_for_host(db, host.name) if reg else {}
|
||||
norms = await host_svc.host_norms(db, host.name) if reg else {}
|
||||
|
||||
# The last 6 h for the at-a-glance sparklines (cpu/mem/load host-level,
|
||||
# The last 6 h for the at-a-glance sparklines (cpu/mem/load/temp host-level,
|
||||
# disk from the root mount), averaged into ~120 points in SQL, so the
|
||||
# line spans the whole window and only what is drawn is fetched.
|
||||
series_raw: dict[str, list[float]] = {"cpu": [], "mem": [], "disk": [], "load": []}
|
||||
series_raw: dict[str, list[float]] = {"cpu": [], "mem": [], "disk": [], "load": [], "temp": []}
|
||||
if reg:
|
||||
since = datetime.now(timezone.utc) - timedelta(hours=6)
|
||||
for key, resource, metric in (("cpu", host.name, "cpu_pct"),
|
||||
("mem", host.name, "mem_used_pct"),
|
||||
("load", host.name, "load_1m"),
|
||||
("temp", host.name, "temp_c_max"),
|
||||
("disk", host.name + ":/", "disk_used_pct")):
|
||||
series_raw[key] = [v for _t, v in await metric_points(
|
||||
db, SOURCE_MODULE, resource, metric, since, target=120)]
|
||||
@@ -987,9 +1058,16 @@ async def host_vitals(host_id: str):
|
||||
reporting = bool(reg) and ls is not None
|
||||
stale = reporting and (datetime.now(timezone.utc) - ls).total_seconds() > _stale_after_seconds()
|
||||
cpu, mem = hostlvl.get("cpu_pct"), hostlvl.get("mem_used_pct")
|
||||
# The hottest sensor that counts (temp_c_max leaves out unwired inputs),
|
||||
# named so the tile says what it is reading.
|
||||
temp = hostlvl.get("temp_c_max")
|
||||
prefix = host.name + ":temp:"
|
||||
hottest = hottest_sensor(host.name, {r[len(prefix):]: m["temp_c"] for r, m in latest.items()
|
||||
if r.startswith(prefix) and m.get("temp_c") is not None})
|
||||
thresholds = current_app.config.get("THRESHOLDS", {})
|
||||
worst = worst_reading((("CPU", cpu, "cpu"), ("Memory", mem, "mem"), ("Disk /", disk_root, "disk"),
|
||||
("Inodes on /", inodes_root, "disk"), ("Load per core", load_per_core, "load")),
|
||||
("Inodes on /", inodes_root, "disk"), ("Load per core", load_per_core, "load"),
|
||||
("Temperature", temp, "temp")),
|
||||
thresholds, host_svc.host_normals(norms, thresholds))
|
||||
# Each tile's grade; CPU, memory and load within the host's own normal
|
||||
# for the hour read healthy, and say what is usual (#5742).
|
||||
@@ -1002,7 +1080,7 @@ async def host_vitals(host_id: str):
|
||||
return await render_template(
|
||||
"_host_vitals.html",
|
||||
reg=reg, cpu=cpu, mem=mem, disk_root=disk_root, load_per_core=load_per_core,
|
||||
inodes_root=inodes_root,
|
||||
inodes_root=inodes_root, temp=temp, hottest=hottest[0].rsplit(" at ", 1)[0] if hottest else None,
|
||||
sparks=sparks, psi=psi, reporting=reporting, stale=stale, worst=worst,
|
||||
grades=grades, usual=usual,
|
||||
clock=clock_words(reg.clock_offset_s if reg else None, current_app.config.get("THRESHOLDS", {})),
|
||||
@@ -1054,6 +1132,7 @@ async def host_panel(host_id: str):
|
||||
host=host, reg=reg, reporting=reporting, stale=stale, target=target, downtime=downtime,
|
||||
maint_job=maint_job, maint_blocker=maint_blocker,
|
||||
maint_summary=maintenance.summary(maint_job) if maint_job else None,
|
||||
maint_failed=maint_job is not None and maintenance.still_failed(maint_job),
|
||||
ansible_available=has_capability("ansible.run_playbook"),
|
||||
managed_key_set=bool((ansible_cfg.get("ssh_public_key") or "").strip()),
|
||||
)
|
||||
@@ -1396,14 +1475,16 @@ async def update_via_ansible():
|
||||
# ── Maintenance cadence (#5768) ───────────────────────────────────────────────
|
||||
|
||||
def _run_rows(run, jobs: dict, names: dict) -> list[dict]:
|
||||
"""A run's hosts in order, each with where it stands, then those passed over."""
|
||||
"""A run's hosts in order, each with where it stands, then those passed
|
||||
over, then the spreading of its swarm services back out."""
|
||||
import json as _json
|
||||
from . import rebalance
|
||||
rows = []
|
||||
for i, host_id in enumerate(_json.loads(run.host_ids)):
|
||||
job = jobs.get((run.id, host_id))
|
||||
if job is not None:
|
||||
text = maintenance.summary(job)
|
||||
bad = job.state in ("failed", "timed_out")
|
||||
bad = maintenance.still_failed(job)
|
||||
busy = job.state in maintenance.ACTIVE
|
||||
elif run.state == "running" and i == run.position:
|
||||
text, bad, busy = "Starting", False, True
|
||||
@@ -1416,6 +1497,13 @@ def _run_rows(run, jobs: dict, names: dict) -> list[dict]:
|
||||
for s in _json.loads(run.skipped):
|
||||
rows.append({"host_id": s["host_id"], "name": names.get(s["host_id"], s["host_id"]),
|
||||
"text": f"Skipped: {s['reason']}", "bad": False, "busy": False, "detail": None})
|
||||
swarm = rebalance.label(run)
|
||||
if swarm is not None:
|
||||
rb = run.rebalance or {}
|
||||
said = [f"moved: {', '.join(rb['moved'])}"] if rb.get("moved") else []
|
||||
said += [f"{x['service']}: {x['reason']}" for x in rb.get("left") or []]
|
||||
rows.append({"host_id": None, "name": "Swarm services", "text": swarm[0], "bad": swarm[1],
|
||||
"busy": swarm[2], "detail": "; ".join(said) or None})
|
||||
return rows
|
||||
|
||||
|
||||
@@ -1486,6 +1574,7 @@ async def maintenance_plan_create():
|
||||
return _error(400, "invalid", "weekday, time (HH:MM) and window must be numbers")
|
||||
policy = form.get("reboot_policy") or "if_required"
|
||||
tz = (form.get("time_zone") or "UTC").strip()
|
||||
spread, keep = _spread_form(form)
|
||||
if not name or not 0 <= weekday <= 6 or not 30 <= window <= 24 * 60 \
|
||||
or policy not in maintenance.REBOOT_POLICIES:
|
||||
return _error(400, "invalid", "name, a weekday, a window of 30 min to 24 h and a reboot policy are needed")
|
||||
@@ -1497,6 +1586,7 @@ async def maintenance_plan_create():
|
||||
plan = HostMaintenancePlan(name=name, group_id=form["group_id"], weekday=weekday,
|
||||
at_time=f"{cadence.parse_at(at_time):%H:%M}", time_zone=tz,
|
||||
window_minutes=window, reboot_policy=policy, enabled=True,
|
||||
spread=spread, keep_in_place=keep,
|
||||
created_by=session.get("user_id"),
|
||||
# the first slot is the next one, not one already past
|
||||
last_slot_at=datetime.now(timezone.utc))
|
||||
@@ -1507,6 +1597,13 @@ async def maintenance_plan_create():
|
||||
return redirect(url_for("host_agent.maintenance_page"))
|
||||
|
||||
|
||||
def _spread_form(form) -> tuple[bool, str]:
|
||||
"""(spread, keep_in_place) from a plan form: the box, and the services
|
||||
named to stay where they are, tidied to one comma-separated list."""
|
||||
from .rebalance import keep_list
|
||||
return form.get("spread") == "on", ", ".join(keep_list(form.get("keep_in_place")))[:2000]
|
||||
|
||||
|
||||
async def _plan_action(plan_id: str, act):
|
||||
from .models import HostMaintenancePlan
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
@@ -1532,6 +1629,22 @@ async def maintenance_plan_toggle(plan_id: str):
|
||||
return resp
|
||||
|
||||
|
||||
@host_agent_bp.post("/maintenance/plans/<plan_id>/spread")
|
||||
@require_role(UserRole.admin)
|
||||
async def maintenance_plan_spread(plan_id: str):
|
||||
"""Whether the plan's runs end by spreading swarm services back out, and
|
||||
which services stay where they are."""
|
||||
form = await request.form
|
||||
spread, keep = _spread_form(form)
|
||||
|
||||
async def act(db, plan):
|
||||
plan.spread, plan.keep_in_place = spread, keep
|
||||
resp = await _plan_action(plan_id, act)
|
||||
await audit_request("host_agent.maintenance_plan_spread", "maintenance_plan", plan_id,
|
||||
{"spread": spread, "keep_in_place": keep})
|
||||
return resp
|
||||
|
||||
|
||||
@host_agent_bp.post("/maintenance/plans/<plan_id>/delete")
|
||||
@require_role(UserRole.admin)
|
||||
async def maintenance_plan_delete(plan_id: str):
|
||||
|
||||
@@ -147,8 +147,9 @@ def make_sensor_task(app) -> ScheduledTask:
|
||||
def make_maintenance_task(app) -> ScheduledTask:
|
||||
"""Gives up on maintenance jobs past their deadline (#5767), starts due
|
||||
maintenance plans and moves their runs on one host at a time (#5768), and
|
||||
records each host's maintenance_failed for an alert rule. Every move a job
|
||||
itself makes comes from its agent's posts."""
|
||||
records each host's maintenance_failed for an alert rule. A job's steps
|
||||
move on from its agent's posts; the tick moves on only Steward's own waits
|
||||
(the 5 minutes after a drain, the containers seen running again, #6098)."""
|
||||
async def _tick():
|
||||
from . import cadence, maintenance
|
||||
now = datetime.now(timezone.utc)
|
||||
|
||||
@@ -0,0 +1,113 @@
|
||||
"""Who sends a host's network traffic (#6115): its containers and NFS mounts,
|
||||
ranked against the host's own total over a window.
|
||||
|
||||
A host's net_tx_bps (net_rx_bps) is what its physical interfaces carried; each
|
||||
container's comes from Docker ingest (resource "<host>/<service or container>") and each
|
||||
NFS mount's from the agent (resource "<host>:<mount>"). All three are read in
|
||||
the same time buckets, so the busiest bucket of the host's total can be put
|
||||
down to who was sending in it. What no container or mount accounts for is the
|
||||
host itself (an apt download, a backup run from the host, a swarm ingress
|
||||
hand-off) or a container's traffic that never left the host.
|
||||
|
||||
Imports only the core metric model, like metrics_query, so the docker plugin
|
||||
being off leaves just the NFS mounts and the host.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from datetime import datetime, timedelta, timezone
|
||||
|
||||
from sqlalchemy import func, select
|
||||
|
||||
from steward.models.metrics import PluginMetric, PluginMetricLatest
|
||||
|
||||
SOURCE_MODULE = "host_agent"
|
||||
DIRECTIONS = ("tx", "rx")
|
||||
# Buckets a window is cut into: a 1 h window reads per 60 s sample, 24 h per
|
||||
# 12 minutes. Narrow the window to see a spike sharper.
|
||||
BUCKETS = 120
|
||||
# A swarm task's container, "<service>.<slot or node id>.<task id>", is shown
|
||||
# by its service, so its tasks over the window add up to one sender.
|
||||
_TASK = re.compile(r"^(?P<svc>.+?)\.(?:\d+|[a-z0-9]{25})\.[a-z0-9]{25}$")
|
||||
|
||||
|
||||
def sender_name(container: str) -> str:
|
||||
m = _TASK.match(container)
|
||||
return m["svc"] if m else container
|
||||
|
||||
|
||||
def rank(host: dict, senders: dict, limit: int = 10) -> dict:
|
||||
"""`host` is {bucket: bytes a second}; `senders` is {(kind, name):
|
||||
{bucket: bytes a second}}. The host's average, its peak and when, and each
|
||||
sender's average over the host's buckets (a bucket it is missing from
|
||||
counts as 0), its own peak and what it sent in the host's peak bucket,
|
||||
biggest at the host's peak first. `unaccounted_*` is what the host carried
|
||||
beyond them all, never below 0."""
|
||||
if not host:
|
||||
return {"host": None, "senders": [], "more": 0, "unaccounted_avg_bps": None,
|
||||
"unaccounted_at_peak_bps": None}
|
||||
n = len(host)
|
||||
peak_at = max(host, key=lambda b: host[b])
|
||||
rows = []
|
||||
for (kind, name), series in senders.items():
|
||||
top = max(series, key=lambda b: series[b])
|
||||
rows.append({"kind": kind, "name": name,
|
||||
"avg_bps": sum(v for b, v in series.items() if b in host) / n,
|
||||
"peak_bps": series[top], "peak_at": top,
|
||||
"at_host_peak_bps": series.get(peak_at, 0.0)})
|
||||
rows.sort(key=lambda r: (r["at_host_peak_bps"], r["avg_bps"]), reverse=True)
|
||||
host_avg = sum(host.values()) / n
|
||||
return {
|
||||
"host": {"avg_bps": host_avg, "peak_bps": host[peak_at], "peak_at": peak_at},
|
||||
"senders": rows[:limit],
|
||||
"more": max(0, len(rows) - limit),
|
||||
"unaccounted_avg_bps": max(0.0, host_avg - sum(r["avg_bps"] for r in rows)),
|
||||
"unaccounted_at_peak_bps": max(0.0, host[peak_at] - sum(r["at_host_peak_bps"] for r in rows)),
|
||||
}
|
||||
|
||||
|
||||
async def senders(session, host_name: str, since: datetime, direction: str = "tx",
|
||||
limit: int = 10, raw_days: int = 7) -> dict:
|
||||
"""rank() over the raw samples since `since` (no earlier than the raw
|
||||
window: the hourly rollup keeps no per-bucket sender to rank). Adds the
|
||||
window actually read and its bucket width."""
|
||||
if direction not in DIRECTIONS:
|
||||
raise ValueError(f"direction is one of {', '.join(DIRECTIONS)}")
|
||||
now = datetime.now(timezone.utc)
|
||||
since = max(since, now - timedelta(days=raw_days))
|
||||
width = max(60, int((now - since).total_seconds() / BUCKETS))
|
||||
bucket = func.date_bin(func.make_interval(0, 0, 0, 0, 0, 0, width), PluginMetric.recorded_at,
|
||||
func.to_timestamp(0)).label("bucket")
|
||||
metric = f"net_{direction}_bps"
|
||||
|
||||
async def named(source, metric_name, prefix):
|
||||
# The resources under the host, from the small latest-value table: a
|
||||
# prefix LIKE on plugin_metrics itself can't use its index (the
|
||||
# column's collation isn't C) and reads the whole table.
|
||||
return list((await session.execute(
|
||||
select(PluginMetricLatest.resource_name).where(
|
||||
PluginMetricLatest.source_module == source, PluginMetricLatest.metric_name == metric_name,
|
||||
PluginMetricLatest.resource_name.startswith(prefix, autoescape=True),
|
||||
PluginMetricLatest.recorded_at >= since))).scalars())
|
||||
|
||||
async def series(source, metric_name, resources):
|
||||
if not resources:
|
||||
return []
|
||||
return (await session.execute(
|
||||
select(PluginMetric.resource_name, bucket, func.avg(PluginMetric.value))
|
||||
.where(PluginMetric.source_module == source, PluginMetric.resource_name.in_(resources),
|
||||
PluginMetric.metric_name == metric_name, PluginMetric.recorded_at >= since)
|
||||
.group_by(PluginMetric.resource_name, bucket))).all()
|
||||
|
||||
host: dict = {}
|
||||
for _, b, v in await series(SOURCE_MODULE, metric, [host_name]):
|
||||
host[b] = float(v)
|
||||
out: dict = {}
|
||||
for res, b, v in await series("docker", metric, await named("docker", metric, host_name + "/")):
|
||||
key = ("container", sender_name(res[len(host_name) + 1:]))
|
||||
out.setdefault(key, {})
|
||||
out[key][b] = out[key].get(b, 0.0) + float(v) # a service's tasks add up
|
||||
nfs = f"nfs_{direction}_bps"
|
||||
for res, b, v in await series(SOURCE_MODULE, nfs, await named(SOURCE_MODULE, nfs, host_name + ":/")):
|
||||
out.setdefault(("nfs", res[len(host_name) + 1:]), {})[b] = float(v)
|
||||
return {"since": since, "bucket_s": width, "direction": direction, **rank(host, out, limit)}
|
||||
@@ -53,6 +53,51 @@ def unwired(host_name: str) -> dict[str, str]:
|
||||
return _unwired.get(host_name, {})
|
||||
|
||||
|
||||
# {host name: {sensor label: hwmon chip}}, as the host's latest sample said.
|
||||
# A sensor's metric is keyed by its label alone; the chip only names it.
|
||||
_chips: dict[str, dict[str, str]] = {}
|
||||
|
||||
# What each hwmon driver measures, in the words a page uses. A driver not
|
||||
# listed is shown by its own name.
|
||||
_CHIP_WORDS = (
|
||||
(re.compile(r"^(coretemp|k10temp|zenpower|cpu_thermal)$"), "CPU"),
|
||||
(re.compile(r"^nvme$"), "NVMe"),
|
||||
(re.compile(r"^drivetemp$"), "Drive"),
|
||||
(re.compile(r"^(nct\d+|it\d+|w83\w+|f71\w+)$"), "Board"),
|
||||
(re.compile(r"^pch_\w+$"), "Chipset"),
|
||||
(re.compile(r"^(amdgpu|radeon|nouveau|i915|xe)$"), "GPU"),
|
||||
(re.compile(r"^(spd5118|jc42)$"), "Memory"),
|
||||
(re.compile(r"^iwlwifi"), "Wi-Fi"),
|
||||
(re.compile(r"^acpitz$"), "ACPI"),
|
||||
)
|
||||
|
||||
|
||||
def note_chips(host_name: str, temps) -> None:
|
||||
"""Remember which chip each of a host's sensors is on, from a sample's
|
||||
temps. An agent that doesn't say leaves what is known as it is."""
|
||||
seen = {str(t["label"]): str(t["chip"]) for t in temps or [] if t.get("chip")}
|
||||
if seen:
|
||||
_chips[host_name] = seen
|
||||
|
||||
|
||||
def chip_word(chip: str) -> str:
|
||||
"""What a hwmon chip measures ("nvme" → "NVMe"), or its own name."""
|
||||
for pattern, word in _CHIP_WORDS:
|
||||
if pattern.match(chip):
|
||||
return word
|
||||
return chip
|
||||
|
||||
|
||||
def sensor_name(host_name: str, label: str) -> str:
|
||||
"""A sensor as a page names it: its chip, then its label, as in
|
||||
"NVMe · Sensor 2". The label alone when the chip isn't known or the
|
||||
label already carries it ("nvme_temp1")."""
|
||||
chip = _chips.get(host_name, {}).get(label)
|
||||
if not chip or label.lower().startswith(chip.lower()):
|
||||
return label
|
||||
return f"{chip_word(chip)} · {label}"
|
||||
|
||||
|
||||
def reference_label(labels) -> str | None:
|
||||
"""The sensor that reads the host's CPU, or None when it has none."""
|
||||
labels = sorted(labels)
|
||||
|
||||
@@ -114,6 +114,17 @@
|
||||
<span style="color:var(--text-muted);">{{ m.get('disk_used_bytes')|bytes }} / {{ m.get('disk_total_bytes')|bytes }}{% if m.get('disk_used_pct') is not none %} · {{ "%.0f"|format(m.get('disk_used_pct')) }}%{% endif %}</span>
|
||||
</div>
|
||||
{{ bar(m.get('disk_used_pct'), 'disk') }}
|
||||
{% if m.get('nfs_ops_per_sec') is not none %}
|
||||
{# NFS delay (#5996): what a request took since the agent's last sample. #}
|
||||
{% set exe = m.get('nfs_exe_ms') %}
|
||||
<div style="font-size:0.72rem;color:var(--text-dim);margin-top:0.2rem;">
|
||||
NFS {% if m.get('nfs_ops_per_sec') > 0 and exe is not none -%}
|
||||
<span class="{{ 'tone-crit' if exe >= 1000 else ('tone-warn' if exe >= 100 else '') }}">{{ "%.1f"|format(exe) }} ms a request</span> · {{ "%.3g"|format(m.get('nfs_ops_per_sec')) }}/s
|
||||
{%- else %}idle{% endif %}
|
||||
{%- if m.get('nfs_retrans') %} · <span class="tone-warn">{{ m.get('nfs_retrans')|int }} sent again</span>{% endif %}
|
||||
{%- if m.get('nfs_timeouts') %} · <span class="tone-crit">{{ m.get('nfs_timeouts')|int }} timed out</span>{% endif %}
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
{% endfor %}
|
||||
</div>
|
||||
|
||||
@@ -0,0 +1,38 @@
|
||||
{# Who sent the host's traffic over the range (#6115): its containers and NFS
|
||||
mounts at the host's busiest moment, biggest first. Lazy-loaded below the
|
||||
charts and refreshed with them. #}
|
||||
<div class="section-title" style="margin-bottom:0.5rem;">Who's sending — last {{ range_key }}</div>
|
||||
{% if not got.host %}
|
||||
<p class="field-hint" style="margin:0;">No outbound traffic recorded for this host in the last {{ range_key }}.</p>
|
||||
{% else %}
|
||||
{% set top = got.senders[0] if got.senders else None %}
|
||||
<p style="margin:0 0 0.6rem;">
|
||||
Busiest at {{ got.host.peak_at|when }}: <strong>{{ got.host.peak_bps|rate }}</strong> out (average {{ got.host.avg_bps|rate }}).
|
||||
{% if top and top.at_host_peak_bps >= got.unaccounted_at_peak_bps %}Most of it from <strong>{{ top.name }}</strong> ({{ top.at_host_peak_bps|rate }}).
|
||||
{% else %}Most of it from <strong>no container or NFS mount</strong>: the host itself.{% endif %}
|
||||
</p>
|
||||
<table class="table">
|
||||
<thead><tr><th>Sender</th><th>At the peak</th><th>Average</th><th>Its own peak</th></tr></thead>
|
||||
<tbody>
|
||||
{% for r in got.senders %}
|
||||
<tr>
|
||||
<td><span title="{{ r.name }}">{{ "NFS " if r.kind == "nfs" }}{{ r.name }}</span></td>
|
||||
<td style="font-variant-numeric:tabular-nums;">{{ r.at_host_peak_bps|rate }}</td>
|
||||
<td style="font-variant-numeric:tabular-nums;">{{ r.avg_bps|rate }}</td>
|
||||
<td style="font-variant-numeric:tabular-nums;">{{ r.peak_bps|rate }} · {{ r.peak_at|when }}</td>
|
||||
</tr>
|
||||
{% endfor %}
|
||||
<tr>
|
||||
<td style="color:var(--text-muted);">The host itself, or none of the above</td>
|
||||
<td style="font-variant-numeric:tabular-nums;">{{ got.unaccounted_at_peak_bps|rate }}</td>
|
||||
<td style="font-variant-numeric:tabular-nums;">{{ got.unaccounted_avg_bps|rate }}</td>
|
||||
<td>—</td>
|
||||
</tr>
|
||||
</tbody>
|
||||
</table>
|
||||
<p class="field-hint" style="margin:0.5rem 0 0;">
|
||||
Read in {{ (got.bucket_s / 60)|round|int }}-minute steps; a shorter range shows a spike sharper.
|
||||
{% if got.more %}{{ got.more }} more sent less. {% endif %}
|
||||
A container's traffic to another on this host counts for it without leaving the host.
|
||||
</p>
|
||||
{% endif %}
|
||||
@@ -1,10 +1,11 @@
|
||||
{# Host health header — live polled into the host hub: live or stale, the worst
|
||||
reading against Settings → Thresholds, last seen, then CPU / memory / disk /
|
||||
load tiles graded by the same cutoffs (`grades`; CPU, memory and load within
|
||||
load tiles, and the hottest sensor that counts with its name, graded by the same cutoffs (`grades`; CPU, memory and load within
|
||||
the host's own normal for the hour read healthy, and `usual` says so). Renders nothing until the agent
|
||||
reports (the Agent panel below then shows provisioning). #}
|
||||
{% from "_macros.html" import status_badge, stat_tile %}
|
||||
{% macro pct(v) %}{{ '%.0f%%'|format(v) if v is not none else '—' }}{% endmacro %}
|
||||
{% macro deg(v) %}{{ '%.0f°C'|format(v) if v is not none else '—' }}{% endmacro %}
|
||||
{% set grades = grades or {} %}
|
||||
{% if reporting %}
|
||||
<section class="card host-health" aria-label="Host health">
|
||||
@@ -12,7 +13,7 @@
|
||||
{{ status_badge('stale' if stale else 'up', 'Stale' if stale else 'Live') }}
|
||||
<span class="host-health-summary">
|
||||
{%- if stale %}No report since {{ reg.last_seen_at|ago }}; the readings below are from then.
|
||||
{%- elif worst %}<span class="tone-{{ worst[2] }}">{{ worst[0] }} {{ pct(worst[1]) }}</span> is past its {{ "critical" if worst[2] == "crit" else "warning" }} threshold.
|
||||
{%- elif worst %}<span class="tone-{{ worst[2] }}">{{ worst[0] }} {{ deg(worst[1]) if worst[0] == "Temperature" else pct(worst[1]) }}</span> is past its {{ "critical" if worst[2] == "crit" else "warning" }} threshold.
|
||||
{%- elif usual %}Every reading is within its thresholds or its usual level for this hour.
|
||||
{%- else %}Every reading is within its thresholds.{% endif -%}
|
||||
</span>
|
||||
@@ -21,14 +22,20 @@
|
||||
{%- if reg.agent_version %}{{ " · " if not stale }}agent v{{ reg.agent_version }}{% endif -%}
|
||||
{%- if clock and clock[0] %} · <span{% if clock[1] in ('warn', 'crit') %} class="tone-{{ clock[1] }}" title="Further from Steward's clock than Settings → Thresholds allows: check what keeps this host's time in sync"{% endif %}>{{ clock[0] }}</span>{% endif -%}
|
||||
</span>
|
||||
{# Charts, every mount, interface, disk and temperature sensor. #}
|
||||
<a href="/plugins/host_agent/{{ reg.host_id }}/" class="btn btn-sm btn-ghost" style="margin-left:auto;">Full metrics →</a>
|
||||
</div>
|
||||
<div class="stat-strip host-health-tiles" style="margin-bottom:0;">
|
||||
<div class="stat-strip host-health-tiles" style="margin-bottom:0;--tiles:{{ 5 if temp is not none else 4 }};">
|
||||
{{ stat_tile("CPU", pct(cpu), state=(grades.cpu or [status_class(cpu, 'cpu')])[0], hint=sparks.cpu|safe) }}
|
||||
{{ stat_tile("Memory", pct(mem), state=(grades.mem or [status_class(mem, 'mem')])[0], hint=sparks.mem|safe) }}
|
||||
{%- set inodes_worse = inodes_root is defined and inodes_root is not none and (disk_root is none or inodes_root > disk_root) %}
|
||||
{{ stat_tile("Disk /", pct(disk_root) ~ (" · inodes " ~ pct(inodes_root) if inodes_worse else ""),
|
||||
state=(grades.disk or [status_class(disk_root, 'disk')])[0], hint=sparks.disk|safe) }}
|
||||
{{ stat_tile("Load per core", pct(load_per_core), state=(grades.load or [status_class(load_per_core, 'load')])[0], hint=sparks.load|safe) }}
|
||||
{% if temp is not none %}
|
||||
{%- set temp_hint %}{{ sparks.temp|safe }}{% if hottest %}<span class="stat-tile-sensor" title="{{ hottest }}">{{ hottest }}</span>{% endif %}{% endset %}
|
||||
{{ stat_tile("Temperature", deg(temp), state=status_class(temp, 'temp'), hint=temp_hint) }}
|
||||
{% endif %}
|
||||
</div>
|
||||
{% if usual and not stale %}
|
||||
<p class="field-hint" style="margin-top:0.6rem;">{{ usual | join("; ") | capitalize }}.</p>
|
||||
|
||||
@@ -35,7 +35,22 @@
|
||||
<div class="section-title" style="margin-bottom:0.5rem;">Load & pressure — last <span class="hm-chart-range">{{ current_range }}</span></div>
|
||||
<div style="height:220px;"><canvas id="chart-pressure"></canvas></div>
|
||||
</div>
|
||||
{% if has_nfs %}
|
||||
<div class="card" style="margin-bottom:0;">
|
||||
<div class="section-title" style="margin-bottom:0.5rem;">NFS delay (ms) — last <span class="hm-chart-range">{{ current_range }}</span></div>
|
||||
<div style="height:220px;"><canvas id="chart-nfs"></canvas></div>
|
||||
</div>
|
||||
{% endif %}
|
||||
</div>
|
||||
<div id="hm-senders" class="card" style="margin-top:1rem;margin-bottom:0;"
|
||||
hx-get="/plugins/host_agent/{{ host.id }}/senders"
|
||||
hx-trigger="load, every {{ chart_poll_seconds }}s, rangeChange from:body"
|
||||
hx-include="#time-range"
|
||||
hx-swap="innerHTML">
|
||||
<div class="section-title" style="margin-bottom:0.5rem;">Who's sending</div>
|
||||
<p class="field-hint" style="margin:0;">Loading…</p>
|
||||
</div>
|
||||
{% if "syslog" in enabled_plugins %}<p id="hm-marks-note" class="field-hint" hidden style="margin:0.5rem 0 0;"></p>{% endif %}
|
||||
{# Hidden poller: fetches the history series and applies it to the charts above
|
||||
(no visible swap). Lazy on load → never blocks paint; refreshed slowly + on
|
||||
range change. #}
|
||||
@@ -79,6 +94,10 @@
|
||||
{ key: "psi_mem_some_avg10", label: "Mem PSI %", color: stewardColor("--red") },
|
||||
{ key: "temp_c_max", label: "Temp °C", color: stewardColor("--yellow") },
|
||||
] },
|
||||
"chart-nfs": { ymax: undefined, ds: [
|
||||
{ key: "nfs_exe_max_ms", label: "Slowest mount, ms a request", color: stewardColor("--blue") },
|
||||
{ key: "mounts_stalled", label: "Mounts not answering", color: stewardColor("--red") },
|
||||
] },
|
||||
};
|
||||
const charts = {};
|
||||
for (const id of Object.keys(defs)) {
|
||||
@@ -102,6 +121,11 @@
|
||||
ch.update("none");
|
||||
}
|
||||
if (rangeKey) document.querySelectorAll(".hm-chart-range").forEach((s) => { s.textContent = rangeKey; });
|
||||
{% if "syslog" in enabled_plugins %}
|
||||
// The host's own syslog errors over the same span (#6002).
|
||||
stewardMarkCharts("/plugins/syslog/marks?host_id={{ host.id }}&range=" + encodeURIComponent(rangeKey || ""),
|
||||
Object.values(charts), document.getElementById("hm-marks-note"));
|
||||
{% endif %}
|
||||
};
|
||||
})();
|
||||
</script>
|
||||
|
||||
@@ -10,7 +10,7 @@
|
||||
<div style="display:flex;flex-direction:column;gap:0.15rem;font-size:0.82rem;">
|
||||
{% for r in rows %}
|
||||
<div style="display:flex;gap:0.6rem;align-items:baseline;" {% if r.detail %}title="{{ r.detail }}"{% endif %}>
|
||||
<a href="/hosts/{{ r.host_id }}" style="min-width:10rem;">{{ r.name }}</a>
|
||||
{% if r.host_id %}<a href="/hosts/{{ r.host_id }}" style="min-width:10rem;">{{ r.name }}</a>{% else %}<span style="min-width:10rem;">{{ r.name }}</span>{% endif %}
|
||||
<span class="{{ 'tone-warn' if r.bad else '' }}" style="{{ '' if r.bad or r.busy else 'color:var(--text-muted);' }}">{{ r.text }}</span>
|
||||
</div>
|
||||
{% endfor %}
|
||||
@@ -20,9 +20,13 @@
|
||||
{{ page_header("Maintenance") }}
|
||||
<p style="color:var(--text-muted);font-size:0.84rem;margin:-0.4rem 0 1.25rem;">
|
||||
Each plan updates an inventory group's hosts once a week, one host at a time. A host reboots
|
||||
only when its update needs it, unless the plan says otherwise; a swarm node is drained first
|
||||
and made active again after. The next host starts once the last is back in service. A failure
|
||||
stops the run, and the host's <em>Maintenance failed</em> figure can drive an alert rule.
|
||||
only when its update needs it, unless the plan says otherwise. A swarm node is drained before
|
||||
a reboot, or before the update when it upgrades Docker, given 5 minutes for its tasks to move,
|
||||
and made active again after. Containers running outside the swarm must be running again
|
||||
within 10 minutes. The next host starts once the last is back in service. A failure stops the
|
||||
run, and the host's <em>Maintenance failed</em> figure can drive an alert rule. Once every host
|
||||
is back, a run that drained swarm nodes spreads the services back out: only those whose image
|
||||
the emptier node already holds, never one the plan keeps in place.
|
||||
</p>
|
||||
|
||||
{% if live %}
|
||||
@@ -66,8 +70,26 @@
|
||||
Group <a href="/hosts/?group={{ p.group|urlencode }}">{{ p.group }}</a> ({{ p.hosts }} host{{ 's' if p.hosts != 1 }})
|
||||
· {{ p.when }}
|
||||
· reboot {{ {'if_required': 'only when required', 'always': 'always', 'never': 'never'}[p.plan.reboot_policy] }}
|
||||
· {% if p.plan.spread %}spreads swarm services back out{% if p.plan.keep_in_place %}, keeping {{ p.plan.keep_in_place }} in place{% endif %}{% else %}leaves swarm services where the run put them{% endif %}
|
||||
{% if p.next %}· next {{ p.next|when }}{% endif %}
|
||||
</div>
|
||||
{% if session.user_role == 'admin' %}
|
||||
<details style="margin-bottom:0.5rem;">
|
||||
<summary style="cursor:pointer;font-size:0.82rem;color:var(--text-muted);">After the run</summary>
|
||||
<form method="post" action="/plugins/host_agent/maintenance/plans/{{ p.plan.id }}/spread"
|
||||
style="display:flex;gap:0.75rem;align-items:flex-end;flex-wrap:wrap;margin:0.4rem 0 0 1rem;">{{ csrf_field() }}
|
||||
<label style="display:flex;gap:0.4rem;align-items:center;font-size:0.84rem;">
|
||||
<input type="checkbox" name="spread" {% if p.plan.spread %}checked{% endif %}> Spread swarm services back out
|
||||
</label>
|
||||
<div class="form-group" style="margin-bottom:0;">
|
||||
<label>Keep in place</label>
|
||||
<input type="text" name="keep_in_place" value="{{ p.plan.keep_in_place }}" maxlength="2000"
|
||||
placeholder="web_proxy, metrics_app" style="width:22rem;" title="Swarm service names, comma-separated">
|
||||
</div>
|
||||
<button type="submit" class="btn btn-sm">Save</button>
|
||||
</form>
|
||||
</details>
|
||||
{% endif %}
|
||||
{% for r in p.runs %}
|
||||
<details {% if loop.first %}open{% endif %} style="margin-top:0.3rem;">
|
||||
<summary style="cursor:pointer;font-size:0.82rem;">
|
||||
@@ -127,6 +149,14 @@
|
||||
<option value="never">Never</option>
|
||||
</select>
|
||||
</div>
|
||||
<label style="display:flex;gap:0.4rem;align-items:center;font-size:0.84rem;margin-bottom:0.45rem;">
|
||||
<input type="checkbox" name="spread" checked> Spread swarm services back out after
|
||||
</label>
|
||||
<div class="form-group" style="margin-bottom:0;">
|
||||
<label>Keep in place</label>
|
||||
<input type="text" name="keep_in_place" maxlength="2000" placeholder="web_proxy, metrics_app"
|
||||
style="width:14rem;" title="Swarm service names, comma-separated">
|
||||
</div>
|
||||
<button type="submit" class="btn">Add plan</button>
|
||||
</form>
|
||||
<p style="font-size:0.78rem;color:var(--text-dim);margin:0.6rem 0 0;">
|
||||
|
||||
@@ -14,10 +14,9 @@
|
||||
</div>
|
||||
|
||||
{% if reporting %}
|
||||
{# Reporting: live vitals are shown by the vitals strip above; this panel is
|
||||
the way to the full metrics, with the lifecycle actions folded under
|
||||
"Manage agent" (#5278). #}
|
||||
<a href="/plugins/host_agent/{{ host.id }}/" class="btn btn-sm btn-ghost">Full metrics →</a>
|
||||
{# Reporting: live vitals, and the way to the full metrics, are in the
|
||||
vitals strip at the top of the page; this panel holds what the host has
|
||||
waiting, with the lifecycle actions folded under "Manage agent" (#5278). #}
|
||||
|
||||
{# What the host has waiting, from the agent's hourly check (#5765): a
|
||||
needed reboot first, then the updates. #}
|
||||
@@ -26,9 +25,9 @@
|
||||
{# Steward's own maintenance job on this host (#5767): a running one first. #}
|
||||
{% if maint_job %}
|
||||
{% set running = maint_job.state not in ('done', 'failed', 'timed_out') %}
|
||||
<div class="{{ 'tone-warn' if running or maint_job.state != 'done' else '' }}" title="{{ maint_job.detail or '' }}">
|
||||
<div class="{{ 'tone-warn' if running or maint_failed else '' }}" title="{{ maint_job.detail or '' }}">
|
||||
<a href="/plugins/host_agent/maintenance" style="color:inherit;">Maintenance</a>: {{ maint_summary }}
|
||||
<span style="color:var(--text-muted);">· {% if running %}since {{ maint_job.state_at|ago }}{% else %}{{ maint_job.finished_at|ago }}{% endif %}{% if maint_job.state in ('failed', 'timed_out') and maint_job.detail %} · {{ maint_job.detail|truncate(90) }}{% endif %}</span>
|
||||
<span style="color:var(--text-muted);">· {% if running %}since {{ maint_job.state_at|ago }}{% else %}{{ maint_job.finished_at|ago }}{% endif %}{% if maint_failed and maint_job.detail %} · {{ maint_job.detail|truncate(90) }}{% endif %}</span>
|
||||
</div>
|
||||
{% endif %}
|
||||
{% if reg.reboot_required %}
|
||||
@@ -93,7 +92,7 @@
|
||||
{% else %}
|
||||
<form method="post" action="/plugins/host_agent/fleet/{{ host.id }}/maintain"
|
||||
style="display:flex;gap:0.6rem;align-items:center;flex-wrap:wrap;margin:0.6rem 0 0;"
|
||||
data-confirm="Update {{ host.name }} now? It reboots only if the update needs it, after its swarm node is drained.">{{ csrf_field() }}
|
||||
data-confirm="Update {{ host.name }} now? It reboots only if the update needs it. A swarm node is drained first when it reboots or Docker is upgraded.">{{ csrf_field() }}
|
||||
<button type="submit" class="btn btn-sm">Update now</button>
|
||||
<label style="font-size:0.8rem;color:var(--text-muted);display:flex;gap:0.3rem;align-items:center;">
|
||||
<input type="checkbox" name="reboot_policy" value="never"> never reboot
|
||||
|
||||
@@ -0,0 +1,130 @@
|
||||
# plugins/host_agent/timeline.py
|
||||
"""What the host agent puts on the timeline: each maintenance job once it
|
||||
ends, the swarm services a maintenance run spread back out after its last
|
||||
host, and each stretch a host was away (a reboot, a crash, lost contact, the
|
||||
agent restarting). One entry per job and per downtime row, kept up to date
|
||||
as the row changes: a downtime that ends gets its length, a failed job
|
||||
whose host came back late reads as back.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import logging
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from steward.timeline import catalog
|
||||
from steward.timeline.record import record_or_update, username
|
||||
|
||||
from . import downtime, maintenance
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
TYPES = (
|
||||
("maintenance.done", "Maintenance run", "automation", "host_os", True,
|
||||
"A host's agent updated it, and rebooted it when the update needed one."),
|
||||
("maintenance.failed", "Maintenance failed", "automation", "host_os", True,
|
||||
"A maintenance job failed or timed out."),
|
||||
("maintenance.rebalanced", "Swarm services spread back out", "automation", "service", True,
|
||||
"After a maintenance run, its swarm services were moved back onto the nodes it had drained."),
|
||||
("host.rebooted", "Host rebooted", "observed", "host_os", True,
|
||||
"A host went down and came back, announced or not (a crash, a power cut)."),
|
||||
("host.lost_contact", "Agent lost contact", "observed", "network", True,
|
||||
"A host's agent ran but couldn't reach Steward."),
|
||||
("host.agent_restarted", "Agent stopped or restarted", "observed", "host_os", False,
|
||||
"The agent stopped or restarted while its host stayed up."),
|
||||
)
|
||||
|
||||
|
||||
def register() -> None:
|
||||
for t in TYPES:
|
||||
catalog.register_type(*t)
|
||||
from .models import HostDowntime, HostMaintenanceJob, HostMaintenanceRun
|
||||
catalog.register_ref("maintenance_job", HostMaintenanceJob)
|
||||
catalog.register_ref("maintenance_run", HostMaintenanceRun)
|
||||
catalog.register_ref("host_downtime", HostDowntime)
|
||||
|
||||
|
||||
async def _host_name(session, host_id: str) -> str | None:
|
||||
from steward.models.hosts import Host
|
||||
host = await session.get(Host, host_id)
|
||||
return host.name if host is not None else None
|
||||
|
||||
|
||||
async def job_entry(session, job, host_name: str | None = None):
|
||||
"""The entry for a finished maintenance job, written or brought up to date."""
|
||||
if job.state not in maintenance.FINISHED:
|
||||
return None
|
||||
host_name = host_name or await _host_name(session, job.host_id) or job.host_id
|
||||
return await record_or_update(
|
||||
session, ("maintenance_job", job.id),
|
||||
type="maintenance.failed" if maintenance.still_failed(job) else "maintenance.done",
|
||||
at=job.created_at, until=job.finished_at,
|
||||
summary=f"Maintenance on {host_name}: {maintenance.summary(job)}",
|
||||
hosts=[host_name], subject=host_name,
|
||||
detail={"state": job.state, "packages": job.packages, "rebooted": job.back_at is not None,
|
||||
"note": job.detail, "url": f"/hosts/{job.host_id}"},
|
||||
actor=await username(session, job.created_by) or "Steward")
|
||||
|
||||
|
||||
async def run_entry(session, run):
|
||||
"""The entry for a run's spreading of swarm services back out, once it ended."""
|
||||
from . import rebalance
|
||||
from .models import HostMaintenancePlan
|
||||
rb = run.rebalance or {}
|
||||
if rb.get("state") not in ("done", "failed", "timed_out"):
|
||||
return None
|
||||
plan = await session.get(HostMaintenancePlan, run.plan_id)
|
||||
summary = rebalance.outcome(run)[1] or "swarm services spread back out"
|
||||
return await record_or_update(
|
||||
session, ("maintenance_run", run.id), type="maintenance.rebalanced",
|
||||
at=datetime.fromisoformat(rb["at"]),
|
||||
until=datetime.fromisoformat(rb["finished_at"]) if rb.get("finished_at") else None,
|
||||
summary=f"{plan.name if plan else 'Maintenance'}: {summary}",
|
||||
hosts=[], subject=None,
|
||||
detail={"state": rb["state"], "moved": rb.get("moved") or [], "left": rb.get("left") or [],
|
||||
"note": rb.get("detail"), "url": "/plugins/host_agent/maintenance"},
|
||||
actor=await username(session, plan.created_by if plan else None) or "Steward")
|
||||
|
||||
|
||||
_DOWNTIME_TYPES = {"reboot": "host.rebooted", "unclean": "host.rebooted",
|
||||
"lost_contact": "host.lost_contact", "agent_stop": "host.agent_restarted"}
|
||||
|
||||
|
||||
async def downtime_entry(session, row, host_name: str | None = None):
|
||||
"""The entry for one stretch a host was away, written or brought up to date."""
|
||||
from steward.core.formatting import human_duration
|
||||
host_name = host_name or await _host_name(session, row.host_id) or row.host_id
|
||||
seen = downtime.describe(row, row.ended_at or row.started_at)
|
||||
said = seen["label"][:1].lower() + seen["label"][1:]
|
||||
said += f" for {human_duration(seen['seconds'])}" if row.ended_at is not None else ", not back yet"
|
||||
return await record_or_update(
|
||||
session, ("host_downtime", row.id),
|
||||
type=_DOWNTIME_TYPES.get(row.kind, "host.rebooted"),
|
||||
at=row.started_at, until=row.ended_at, summary=f"{host_name}: {said}",
|
||||
hosts=[host_name], subject=host_name,
|
||||
detail={"kind": row.kind, "url": f"/hosts/{row.host_id}"}, actor="Steward")
|
||||
|
||||
|
||||
async def write(session, what: str, coro) -> None:
|
||||
"""Run one entry writer in a savepoint: the source's own row matters more
|
||||
than its entry, so a failure is logged and nothing else is undone."""
|
||||
try:
|
||||
async with session.begin_nested():
|
||||
await coro
|
||||
except Exception:
|
||||
logger.exception("Timeline: the entry for %s could not be written", what)
|
||||
|
||||
|
||||
async def backfill(session, since) -> list:
|
||||
"""Entries for the jobs and downtime that predate the timeline."""
|
||||
from .models import HostDowntime, HostMaintenanceJob
|
||||
out = []
|
||||
for job in (await session.execute(select(HostMaintenanceJob).where(
|
||||
HostMaintenanceJob.created_at >= since,
|
||||
HostMaintenanceJob.state.in_(maintenance.FINISHED)))).scalars().all():
|
||||
out.append(await job_entry(session, job))
|
||||
for row in (await session.execute(select(HostDowntime).where(
|
||||
HostDowntime.started_at >= since))).scalars().all():
|
||||
out.append(await downtime_entry(session, row))
|
||||
return out
|
||||
@@ -68,3 +68,13 @@ def get_audit_entities() -> dict:
|
||||
from .models import PrometheusTarget, PrometheusWidgetTemplate
|
||||
return {"prometheus_target": (PrometheusTarget, "/plugins/prometheus/targets/{}"),
|
||||
"prometheus_template": (PrometheusWidgetTemplate, "/plugins/prometheus/templates/custom:{}")}
|
||||
|
||||
|
||||
def register_mcp_tools(register) -> None:
|
||||
from .mcp_tools import register_tools
|
||||
register_tools(register)
|
||||
|
||||
|
||||
async def mcp_overview(db) -> list[dict]:
|
||||
from .mcp_tools import mcp_overview as findings
|
||||
return await findings(db)
|
||||
|
||||
@@ -0,0 +1,114 @@
|
||||
"""The prometheus plugin's MCP tools and its get_overview findings (#5840).
|
||||
|
||||
Registered through register_mcp_tools() in __init__.py, so they exist only
|
||||
while the plugin is enabled. They read what the scraper stored; nothing
|
||||
reaches a target, and a target's bearer token (or a password in its URL)
|
||||
is never returned.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from steward.core.metric_series import latest_values
|
||||
from steward.mcp.tools._shape import age_s, bounded, clamp_limit, db_session, iso, now_utc, pick, redact_url
|
||||
from steward.mcp.tools.overview import finding
|
||||
from steward.models.metrics import PluginMetricLatest
|
||||
from steward.models.users import UserRole
|
||||
|
||||
from .models import PrometheusTarget
|
||||
from .routes import group_series
|
||||
from .service import OWN_METRICS, SOURCE, target_state
|
||||
|
||||
REACHES = ("down", "stale", "pending", "up", "paused")
|
||||
_ORDER = {r: i for i, r in enumerate(REACHES)}
|
||||
|
||||
|
||||
def _target_view(t: PrometheusTarget, own: dict, now) -> dict:
|
||||
state = target_state(t, now)
|
||||
return {"target_id": t.id, "name": t.name, "url": redact_url(t.url), "enabled": t.enabled,
|
||||
"reach": state.reach, "says": state.says, "interval_s": t.interval_seconds,
|
||||
"scraped_at": iso(t.last_scraped_at), "ok_at": iso(t.last_ok_at), "ok_age_s": age_s(t.last_ok_at, now),
|
||||
"series_kept": t.last_kept, "series_dropped": t.last_dropped, "series_capped": t.last_capped,
|
||||
"series_cap": t.series_cap, "keep": list(t.keep or []), "drop": list(t.drop or []),
|
||||
"scrape_ms": own.get("scrape_ms")}
|
||||
|
||||
|
||||
async def list_prometheus_targets() -> dict:
|
||||
"""The /metrics endpoints Steward scrapes, not answering first.
|
||||
|
||||
`reach`: "down" (the last scrape failed; `says` is why), "stale" (not
|
||||
scraped recently), "pending", "up" or "paused". `series_kept` /
|
||||
`series_dropped` count the newest scrape's series the keep/drop patterns
|
||||
let through or left out; `series_capped` those past `series_cap`, which
|
||||
were not stored. get_prometheus_target lists a target's series;
|
||||
query_metrics(source_module="prometheus", resource=…, metric=…) reads
|
||||
one's history.
|
||||
"""
|
||||
now = now_utc()
|
||||
async with db_session() as db:
|
||||
targets = list((await db.execute(select(PrometheusTarget).order_by(PrometheusTarget.name))).scalars())
|
||||
rows = (await db.execute(select(PluginMetricLatest).where(
|
||||
PluginMetricLatest.source_module == SOURCE,
|
||||
PluginMetricLatest.resource_name.in_([t.name for t in targets] or [""]),
|
||||
PluginMetricLatest.metric_name == "scrape_ms"))).scalars()
|
||||
own = {r.resource_name: {"scrape_ms": r.value} for r in rows}
|
||||
views = [_target_view(t, own.get(t.name, {}), now) for t in targets]
|
||||
views.sort(key=lambda v: (_ORDER[v["reach"]], v["name"].lower()))
|
||||
return {"targets": views}
|
||||
|
||||
|
||||
async def get_prometheus_target(target: str, search: str = "", limit: int = 100) -> dict:
|
||||
"""One target's stored series, grouped by metric name, each with the
|
||||
labels that tell its series apart and the newest value in its unit.
|
||||
|
||||
target: its name or id (list_prometheus_targets).
|
||||
search: part of a metric name; empty for all.
|
||||
limit: metric groups to return, default 100, max 500.
|
||||
|
||||
A state set (a series per state, one of them 1) is folded to the
|
||||
current state. `resource` is what query_metrics takes for a series'
|
||||
history (source_module "prometheus").
|
||||
"""
|
||||
now = now_utc()
|
||||
async with db_session() as db:
|
||||
t = pick(target, list((await db.execute(select(PrometheusTarget))).scalars()),
|
||||
kind="Prometheus target", list_tool="list_prometheus_targets")
|
||||
latest = await latest_values(db, SOURCE, t.name, include_children=True)
|
||||
own = {r.metric_name: r.value for r in latest if r.resource_name == t.name and r.metric_name in OWN_METRICS}
|
||||
groups = group_series(t.name, latest)
|
||||
if search:
|
||||
groups = [g for g in groups if search.lower() in g["metric"].lower()]
|
||||
|
||||
def row(r: dict, states: bool) -> dict:
|
||||
if states:
|
||||
return {"labels": r["labels"], "resource": r["resource"], "state": r["text"], "states": r["states"]}
|
||||
return {"labels": r["labels"], "resource": r["resource"], "value": r["value"],
|
||||
"shown": r["text"] or iso(r["moment"]), "at": iso(r["at"])}
|
||||
|
||||
shaped = [{"metric": g["metric"], "series": [row(r, g["states"]) for r in g["rows"][:50]],
|
||||
**({"more_series": len(g["rows"]) - 50} if len(g["rows"]) > 50 else {})} for g in groups]
|
||||
out = {"target": _target_view(t, own, now)}
|
||||
out.update(bounded(shaped, clamp_limit(limit, 100, 500), key="metrics",
|
||||
more="Pass a `search`, or a larger `limit`."))
|
||||
return out
|
||||
|
||||
|
||||
def target_findings(views: list[dict]) -> list[dict]:
|
||||
"""A target whose last scrape failed. Stale and paused are the plugin or
|
||||
the admin's choice, not the endpoint, so they are left out."""
|
||||
return [finding("warning", "prometheus_target_down", v["name"],
|
||||
f"Prometheus target {v['name']} isn't answering: {v['says']}",
|
||||
since=v["_ok_at"], ids={"target_id": v["target_id"]},
|
||||
next=f'get_prometheus_target(target="{v["name"]}")')
|
||||
for v in views if v["reach"] == "down"]
|
||||
|
||||
|
||||
async def mcp_overview(db) -> list[dict]:
|
||||
now = now_utc()
|
||||
targets = list((await db.execute(select(PrometheusTarget))).scalars())
|
||||
return target_findings([_target_view(t, {}, now) | {"_ok_at": t.last_ok_at} for t in targets])
|
||||
|
||||
|
||||
def register_tools(register) -> None:
|
||||
for fn in (list_prometheus_targets, get_prometheus_target):
|
||||
register(fn, role=UserRole.viewer, read_only=True)
|
||||
@@ -0,0 +1,23 @@
|
||||
"""A target whose token was refused stops being scraped until it is saved
|
||||
|
||||
Revision ID: prometheus_003_refused
|
||||
Revises: prometheus_002_templates
|
||||
Create Date: 2026-11-01
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "prometheus_003_refused"
|
||||
down_revision: Union[str, None] = "prometheus_002_templates"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("prometheus_targets", sa.Column("refused", sa.Boolean, nullable=False, server_default=sa.false()))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("prometheus_targets", "refused")
|
||||
@@ -0,0 +1,23 @@
|
||||
"""A target can take its token from another plugin's sign-in
|
||||
|
||||
Revision ID: prometheus_004_token_from
|
||||
Revises: prometheus_003_refused
|
||||
Create Date: 2026-11-01
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "prometheus_004_token_from"
|
||||
down_revision: Union[str, None] = "prometheus_003_refused"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("prometheus_targets", sa.Column("token_from", sa.String(50), nullable=True))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("prometheus_targets", "token_from")
|
||||
@@ -0,0 +1,32 @@
|
||||
"""Every target holds its own token: one that took it from a sign-in goes
|
||||
|
||||
Revision ID: prometheus_005_own_tokens
|
||||
Revises: prometheus_004_token_from
|
||||
Create Date: 2026-11-01
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "prometheus_005_own_tokens"
|
||||
down_revision: Union[str, None] = "prometheus_004_token_from"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
# Left in place, such a target would ask with no token, and some services ban
|
||||
# an address for that. Its newest values go with it; history ages out. On a new
|
||||
# database the metric tables may not exist yet, and there is nothing to remove.
|
||||
if sa.inspect(op.get_bind()).has_table("plugin_metric_latest"):
|
||||
op.execute("""
|
||||
DELETE FROM plugin_metric_latest l USING prometheus_targets t
|
||||
WHERE t.token_from IS NOT NULL AND l.source_module = 'prometheus'
|
||||
AND (l.resource_name = t.name OR left(l.resource_name, length(t.name) + 1) = t.name || ':')""")
|
||||
op.execute("DELETE FROM prometheus_targets WHERE token_from IS NOT NULL")
|
||||
op.drop_column("prometheus_targets", "token_from")
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.add_column("prometheus_targets", sa.Column("token_from", sa.String(50), nullable=True))
|
||||
@@ -17,7 +17,8 @@ class PrometheusTarget(Base):
|
||||
patterns ("fabledarchives_*") an admin chooses: Steward does the
|
||||
filtering, the endpoint serves everything. The last_* columns are the
|
||||
newest scrape's outcome, written by the scraper, so a page can say why a
|
||||
target isn't answering without asking it.
|
||||
target isn't answering without asking it. `refused` says its token was
|
||||
refused, which stops the scraping until the target is saved or resumed.
|
||||
"""
|
||||
__tablename__ = "prometheus_targets"
|
||||
|
||||
@@ -31,6 +32,7 @@ class PrometheusTarget(Base):
|
||||
drop: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
|
||||
series_cap: Mapped[int] = mapped_column(Integer, nullable=False, default=1000)
|
||||
enabled: Mapped[bool] = mapped_column(Boolean, nullable=False, default=True)
|
||||
refused: Mapped[bool] = mapped_column(Boolean, nullable=False, default=False)
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), nullable=False, default=lambda: datetime.now(timezone.utc))
|
||||
last_scraped_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
|
||||
@@ -20,12 +20,12 @@ from steward.models.users import UserRole
|
||||
from . import library
|
||||
from .models import PrometheusTarget, PrometheusWidgetTemplate
|
||||
from .scraper import ScrapeError, scrape
|
||||
from .service import (OWN_METRICS, SOURCE, FormError, fold_states, form_values, map_families,
|
||||
from .service import (OWN_METRICS, SOURCE, FormError, fold_states, form_values, is_moment, map_families,
|
||||
parse_form, patterns, shown_value, target_state)
|
||||
|
||||
prometheus_bp = Blueprint("prometheus", __name__, template_folder="templates")
|
||||
|
||||
_REACH_ORDER = {"down": 0, "stale": 1, "pending": 2, "up": 3, "off": 4}
|
||||
_REACH_ORDER = {"down": 0, "stale": 1, "pending": 2, "up": 3, "paused": 4}
|
||||
|
||||
|
||||
def _actor() -> tuple[str | None, str]:
|
||||
@@ -40,7 +40,8 @@ def view(target: PrometheusTarget, own: dict, now: datetime) -> dict:
|
||||
"""What a page says about a target: its state in words and the numbers
|
||||
from its newest scrape."""
|
||||
state = target_state(target, now)
|
||||
return {"id": target.id, "name": target.name, "url": target.url, "reach": state.reach,
|
||||
return {"id": target.id, "name": target.name, "url": target.url, "enabled": target.enabled,
|
||||
"reach": state.reach,
|
||||
"says": state.says, "scraped_at": target.last_scraped_at, "ok_at": target.last_ok_at,
|
||||
"interval": target.interval_seconds, "kept": target.last_kept,
|
||||
"dropped": target.last_dropped, "capped": target.last_capped, "cap": target.series_cap,
|
||||
@@ -79,8 +80,7 @@ def _typed(form, target: PrometheusTarget | None = None) -> dict:
|
||||
return {"name": form.get("name", ""), "url": form.get("url", ""),
|
||||
"interval_seconds": form.get("interval_seconds", ""), "series_cap": form.get("series_cap", ""),
|
||||
"keep": form.get("keep", ""), "drop": form.get("drop", ""),
|
||||
"verify_tls": bool(form.get("verify_tls")), "enabled": bool(form.get("enabled")),
|
||||
"has_token": bool(target and target.token)}
|
||||
"verify_tls": bool(form.get("verify_tls")), "has_token": bool(target and target.token)}
|
||||
|
||||
|
||||
async def _name_taken(db, name: str, other_than: str | None = None) -> bool:
|
||||
@@ -153,6 +153,7 @@ async def save_target(target_id: str):
|
||||
# Where it is or what is kept may have changed: the last outcome no
|
||||
# longer describes it, so the page says "not scraped yet" until the next scrape.
|
||||
target.last_scraped_at = target.last_ok_at = target.last_error = None
|
||||
target.refused = False
|
||||
target.last_kept = target.last_dropped = target.last_capped = 0
|
||||
if old_name != target.name:
|
||||
# Its history is stored under its name, and its labelled series
|
||||
@@ -176,6 +177,28 @@ async def save_target(target_id: str):
|
||||
return redirect(f"/plugins/prometheus/targets/{target_id}")
|
||||
|
||||
|
||||
@prometheus_bp.post("/targets/<target_id>/toggle")
|
||||
@require_role(UserRole.admin)
|
||||
async def toggle_target(target_id: str):
|
||||
"""Pause a target, or resume a paused one, from its page or the list."""
|
||||
async with current_app.db_sessionmaker() as db:
|
||||
async with db.begin():
|
||||
target = await _target_or_404(db, target_id)
|
||||
target.enabled = not target.enabled
|
||||
if target.enabled:
|
||||
# Resumed: it reads "not scraped yet" until the next scrape,
|
||||
# rather than stale from before the pause.
|
||||
target.last_scraped_at = target.last_error = None
|
||||
target.refused = False
|
||||
enabled, name = target.enabled, target.name
|
||||
# A rate needs two readings in a row; one from before the pause isn't one.
|
||||
from . import scheduler
|
||||
scheduler.RATES.forget(target_id)
|
||||
await log_audit(current_app, *_actor(), "prometheus.target_resumed" if enabled else "prometheus.target_paused",
|
||||
entity_type="prometheus_target", entity_id=target_id, detail={"name": name})
|
||||
return redirect(request.referrer or f"/plugins/prometheus/targets/{target_id}")
|
||||
|
||||
|
||||
@prometheus_bp.post("/targets/<target_id>/delete")
|
||||
@require_role(UserRole.admin)
|
||||
async def delete_target(target_id: str):
|
||||
@@ -304,7 +327,7 @@ async def series_detail(target_id: str):
|
||||
series = await points(db, SOURCE, resource, metric,
|
||||
datetime.now(timezone.utc) - timedelta(hours=hours))
|
||||
labels = resource[len(target.name) + 1:] if resource != target.name else ""
|
||||
stamp_axis = metric.endswith("_timestamp_seconds")
|
||||
stamp_axis = is_moment(metric)
|
||||
return await render_template(
|
||||
"prometheus/series.html", target=target, resource=resource, metric=metric, labels=labels,
|
||||
now=shown_value(metric, now_row.value if now_row else None), hours=hours, ranges=RANGES,
|
||||
|
||||
@@ -40,7 +40,7 @@ def make_scrape_task(app: "Quart") -> ScheduledTask:
|
||||
def is_due(target, now: datetime) -> bool:
|
||||
"""Whether a target's interval has elapsed since its last scrape, with
|
||||
half a tick of slack so tick jitter doesn't push it back a whole tick."""
|
||||
if not target.enabled:
|
||||
if not target.enabled or target.refused:
|
||||
return False
|
||||
if target.last_scraped_at is None:
|
||||
return True
|
||||
@@ -115,7 +115,7 @@ async def record(app: "Quart", targets, results, now: datetime) -> None:
|
||||
from steward.core.alerts import MetricBatch
|
||||
|
||||
from .models import PrometheusTarget
|
||||
from .scraper import ScrapeError
|
||||
from .scraper import ScrapeError, TokenRefused
|
||||
from .service import (IS_UP, OWN_METRICS, SCRAPE_MS, SERIES_CAPPED, SERIES_KEPT, SOURCE,
|
||||
map_families)
|
||||
|
||||
@@ -132,6 +132,7 @@ async def record(app: "Quart", targets, results, now: datetime) -> None:
|
||||
if not isinstance(result, ScrapeError):
|
||||
logger.warning("Prometheus scrape of %s failed: %r", target.name, result)
|
||||
row.last_error = str(result) or "The scrape failed."
|
||||
row.refused = isinstance(result, TokenRefused)
|
||||
batch.add(source_module=SOURCE, resource_name=row.name, metric_name=IS_UP,
|
||||
value=0.0, recorded_at=now)
|
||||
continue
|
||||
|
||||
@@ -18,6 +18,11 @@ class ScrapeError(Exception):
|
||||
"""Why a scrape got nothing, said to the person."""
|
||||
|
||||
|
||||
class TokenRefused(ScrapeError):
|
||||
"""The endpoint refused the token. Asking again won't change that, and
|
||||
Home Assistant, for one, bans an address after a few refusals."""
|
||||
|
||||
|
||||
async def scrape(url: str, token: str = "", verify_tls: bool = True,
|
||||
transport: httpx.AsyncBaseTransport | None = None) -> dict[str, prometheus.Family]:
|
||||
"""The endpoint's families. `transport` stands in for the network in tests."""
|
||||
@@ -29,8 +34,8 @@ async def scrape(url: str, token: str = "", verify_tls: bool = True,
|
||||
transport=transport, follow_redirects=False) as client:
|
||||
async with client.stream("GET", url, headers=headers) as response:
|
||||
if response.status_code in (401, 403):
|
||||
raise ScrapeError(f"Answered {response.status_code}: the token was refused. "
|
||||
"Check the token, or make a new one on the service.")
|
||||
raise TokenRefused(f"Answered {response.status_code}: the token was refused. "
|
||||
"Check the token, or make a new one on the service.")
|
||||
if response.status_code != 200:
|
||||
raise ScrapeError(f"Answered {response.status_code} {response.reason_phrase}, not metrics.")
|
||||
body = bytearray()
|
||||
|
||||
@@ -122,13 +122,23 @@ def fold_states(metric: str, rows: list[dict]) -> list[dict] | None:
|
||||
return folded
|
||||
|
||||
|
||||
# A series named for a moment holds Unix seconds, not a span of time: the
|
||||
# convention's *_timestamp_seconds, and the *_time_seconds some exporters use
|
||||
# (Home Assistant's homeassistant_last_updated_time_seconds).
|
||||
MOMENT_SUFFIXES = ("_timestamp_seconds", "_time_seconds")
|
||||
|
||||
|
||||
def is_moment(metric: str) -> bool:
|
||||
return metric.endswith(MOMENT_SUFFIXES)
|
||||
|
||||
|
||||
def shown_value(metric: str, value: float | None) -> dict:
|
||||
"""A series' value in its unit, from the Prometheus naming conventions.
|
||||
A *_timestamp_seconds is a moment: it comes back as `moment` for the page
|
||||
to show as "3m ago" in the reader's zone; 0 there means "never"."""
|
||||
A moment (is_moment) comes back as `moment` for the page to show as
|
||||
"3m ago" in the reader's zone; 0 there means "never"."""
|
||||
if value is None:
|
||||
return {"text": "—", "moment": None}
|
||||
if metric.endswith("_timestamp_seconds"):
|
||||
if is_moment(metric):
|
||||
if value <= 0:
|
||||
return {"text": "never", "moment": None}
|
||||
return {"text": "", "moment": datetime.fromtimestamp(value, timezone.utc)}
|
||||
@@ -184,11 +194,12 @@ def map_families(target: str, families: dict[str, prometheus.Family], keep: list
|
||||
# ── The form ─────────────────────────────────────────────────────────────────
|
||||
|
||||
def patterns(text: str) -> list[str]:
|
||||
"""Name patterns from a textarea: one per line or comma-separated."""
|
||||
"""Name patterns from a textarea: one per line, or separated by commas or
|
||||
spaces. A metric name never holds whitespace, so a paste that turned line
|
||||
breaks into spaces still reads as the patterns it was."""
|
||||
out: list[str] = []
|
||||
for line in (text or "").replace(",", "\n").splitlines():
|
||||
p = line.strip()
|
||||
if p and p not in out:
|
||||
for p in (text or "").replace(",", " ").split():
|
||||
if p not in out:
|
||||
out.append(p)
|
||||
return out
|
||||
|
||||
@@ -197,11 +208,10 @@ def form_values(target: PrometheusTarget | None) -> dict:
|
||||
"""The form's fields for an existing target. The token is never sent back
|
||||
to the browser; a blank token field on save keeps the stored one."""
|
||||
if target is None:
|
||||
return {"interval_seconds": 60, "series_cap": 1000, "verify_tls": True, "enabled": True,
|
||||
"keep": "", "drop": ""}
|
||||
return {"interval_seconds": 60, "series_cap": 1000, "verify_tls": True, "keep": "", "drop": ""}
|
||||
return {"name": target.name, "url": target.url, "interval_seconds": target.interval_seconds,
|
||||
"series_cap": target.series_cap, "verify_tls": target.verify_tls,
|
||||
"enabled": target.enabled, "keep": "\n".join(target.keep or []),
|
||||
"keep": "\n".join(target.keep or []),
|
||||
"drop": "\n".join(target.drop or []), "has_token": bool(target.token)}
|
||||
|
||||
|
||||
@@ -217,7 +227,8 @@ def _bounded(form, key: str, default: int, low: int, high: int, says: str) -> in
|
||||
|
||||
def parse_form(form, existing: PrometheusTarget | None = None) -> dict:
|
||||
"""The submitted form as the columns to store, the token encrypted.
|
||||
Raises FormError saying what to fix."""
|
||||
Whether it is paused isn't among them: Pause/Resume sets that, and a new
|
||||
target starts scraping. Raises FormError saying what to fix."""
|
||||
name = (form.get("name") or "").strip()
|
||||
url = (form.get("url") or "").strip()
|
||||
if not name:
|
||||
@@ -241,7 +252,7 @@ def parse_form(form, existing: PrometheusTarget | None = None) -> dict:
|
||||
return {"name": name, "url": url, "token": token,
|
||||
"verify_tls": bool(form.get("verify_tls")), "interval_seconds": interval,
|
||||
"keep": patterns(form.get("keep") or ""), "drop": patterns(form.get("drop") or ""),
|
||||
"series_cap": cap, "enabled": bool(form.get("enabled"))}
|
||||
"series_cap": cap}
|
||||
|
||||
|
||||
# ── What the newest scrape says ──────────────────────────────────────────────
|
||||
@@ -253,13 +264,16 @@ STALE_SCRAPES = 3
|
||||
|
||||
@dataclass
|
||||
class TargetState:
|
||||
reach: str # up | down | stale | pending | off
|
||||
reach: str # up | down | stale | pending | paused
|
||||
says: str # one line, in words
|
||||
|
||||
|
||||
def target_state(target: PrometheusTarget, now: datetime) -> TargetState:
|
||||
if not target.enabled:
|
||||
return TargetState("off", "Not scraped: turned off.")
|
||||
return TargetState("paused", "Paused: not scraped until it's resumed.")
|
||||
if target.refused:
|
||||
return TargetState("down", f"{target.last_error} Steward stopped asking, as some services ban an "
|
||||
"address after a few refusals. Save a new token to start again.")
|
||||
if target.last_scraped_at is None:
|
||||
return TargetState("pending", "Not scraped yet.")
|
||||
if (now - target.last_scraped_at).total_seconds() > STALE_SCRAPES * max(target.interval_seconds, 1):
|
||||
|
||||
@@ -51,9 +51,6 @@
|
||||
</div>
|
||||
</div>
|
||||
<div style="display:flex;gap:1.5rem;flex-wrap:wrap;margin-bottom:0.9rem;">
|
||||
<label style="display:flex;gap:0.5rem;align-items:center;cursor:pointer;">
|
||||
<input type="checkbox" name="enabled" value="on"{% if v.enabled %} checked{% endif %}> Scrape this target
|
||||
</label>
|
||||
<label style="display:flex;gap:0.5rem;align-items:center;cursor:pointer;">
|
||||
<input type="checkbox" name="verify_tls" value="on"{% if v.verify_tls %} checked{% endif %}> Check its HTTPS certificate
|
||||
</label>
|
||||
|
||||
@@ -23,13 +23,16 @@
|
||||
{% if t.reach == 'up' %}{{ status_badge('up', 'Answering') }}
|
||||
{% elif t.reach == 'down' %}{{ status_badge('down', 'Not answering') }}
|
||||
{% elif t.reach == 'stale' %}{{ status_badge('stale', 'Not scraped') }}
|
||||
{% elif t.reach == 'off' %}{{ status_badge('stale', 'Turned off') }}
|
||||
{% elif t.reach == 'paused' %}{{ status_badge('paused') }}
|
||||
{% else %}{{ status_badge('pending', 'Not scraped yet') }}{% endif %}
|
||||
<h2 id="prom-{{ t.id }}" class="section-title" style="margin:0;"><a href="/plugins/prometheus/targets/{{ t.id }}">{{ t.name }}</a></h2>
|
||||
<span class="field-hint mono" style="min-width:0;max-width:28rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;" title="{{ t.url }}">{{ t.url }}</span>
|
||||
<span class="page-actions" style="margin-left:auto;">
|
||||
<a href="/plugins/prometheus/targets/{{ t.id }}" class="btn btn-sm btn-ghost">Series</a>
|
||||
{% if admin %}<a href="/plugins/prometheus/targets/{{ t.id }}/edit" class="btn btn-sm btn-ghost">Edit</a>{% endif %}
|
||||
{% if admin %}<a href="/plugins/prometheus/targets/{{ t.id }}/edit" class="btn btn-sm btn-ghost">Edit</a>
|
||||
<form method="post" action="/plugins/prometheus/targets/{{ t.id }}/toggle">{{ csrf_field() }}
|
||||
<button type="submit" class="btn btn-sm btn-ghost">{{ "Pause" if t.enabled else "Resume" }}</button>
|
||||
</form>{% endif %}
|
||||
</span>
|
||||
</div>
|
||||
|
||||
@@ -38,7 +41,7 @@
|
||||
<p class="field-hint" style="margin:0 0 0.6rem;">
|
||||
{%- if t.ok_at %}Last answered {{ t.ok_at|ago }}.{% else %}It has never answered.{% endif %}
|
||||
Tried {{ t.scraped_at|ago }}.</p>
|
||||
{% elif t.reach in ('stale', 'off') %}
|
||||
{% elif t.reach in ('stale', 'paused') %}
|
||||
<p class="field-hint" style="margin:0 0 0.6rem;">{{ t.says }}{% if t.scraped_at %} Last scraped {{ t.scraped_at|ago }}.{% endif %}</p>
|
||||
{% elif t.reach == 'pending' %}
|
||||
<p class="field-hint" style="margin:0 0 0.6rem;">Not scraped yet: the first scrape runs within seconds of saving.</p>
|
||||
|
||||
@@ -1,6 +1,7 @@
|
||||
{# plugins/prometheus/templates/prometheus/series.html — one stored series
|
||||
of a target (milestone 506): its newest value and a chart over a chosen
|
||||
range. A *_timestamp_seconds series charts as moments, not numbers. #}
|
||||
range. A moment series (*_timestamp_seconds, *_time_seconds) charts as
|
||||
moments, not numbers. #}
|
||||
{% extends "base.html" %}
|
||||
{% from "_macros.html" import crumbs, page_header %}
|
||||
{% block title %}{{ metric }} — {{ target.name }} — Steward{% endblock %}
|
||||
|
||||
@@ -12,7 +12,10 @@
|
||||
{% block content %}
|
||||
{% set admin = session.user_role == 'admin' %}
|
||||
{% call page_header(target.name, target.url) %}
|
||||
{% if admin %}<a href="/plugins/prometheus/targets/{{ target.id }}/edit" class="btn btn-sm btn-ghost">Edit</a>{% endif %}
|
||||
{% if admin %}<a href="/plugins/prometheus/targets/{{ target.id }}/edit" class="btn btn-sm btn-ghost">Edit</a>
|
||||
<form method="post" action="/plugins/prometheus/targets/{{ target.id }}/toggle">{{ csrf_field() }}
|
||||
<button type="submit" class="btn btn-sm btn-ghost">{{ "Pause" if target.enabled else "Resume" }}</button>
|
||||
</form>{% endif %}
|
||||
{% endcall %}
|
||||
|
||||
<p class="page-verdict">
|
||||
@@ -20,7 +23,7 @@
|
||||
{% elif target.reach == 'down' %}{{ status_badge('down', 'Not answering') }} <span class="tone-crit">{{ target.says }}</span>
|
||||
{% if target.ok_at %}Last answered {{ target.ok_at|ago }}; the values below are from then.{% else %}It has never answered.{% endif %}
|
||||
{% elif target.reach == 'stale' %}{{ status_badge('stale', 'Not scraped') }} {{ target.says }}
|
||||
{% elif target.reach == 'off' %}{{ status_badge('stale', 'Turned off') }} {{ target.says }}
|
||||
{% elif target.reach == 'paused' %}{{ status_badge('paused') }} {{ target.says }}
|
||||
{% else %}{{ status_badge('pending', 'Not scraped yet') }} The first scrape runs within seconds of saving.{% endif %}
|
||||
</p>
|
||||
{% if target.capped %}
|
||||
|
||||
@@ -39,3 +39,13 @@ def get_audit_entities() -> dict:
|
||||
"""Audit rows about a device name it and link to its page."""
|
||||
from .models import SnmpDevice
|
||||
return {"snmp_device": (SnmpDevice, "/plugins/snmp/devices/{}")}
|
||||
|
||||
|
||||
def register_mcp_tools(register) -> None:
|
||||
from .mcp_tools import register_tools
|
||||
register_tools(register)
|
||||
|
||||
|
||||
async def mcp_overview(db) -> list[dict]:
|
||||
from .mcp_tools import mcp_overview as findings
|
||||
return await findings(db)
|
||||
|
||||
@@ -0,0 +1,105 @@
|
||||
"""The snmp plugin's MCP tools and its get_overview findings (#5840).
|
||||
|
||||
Registered through register_mcp_tools() in __init__.py, so they exist only
|
||||
while the plugin is enabled. They read what the poller stored; nothing asks a
|
||||
device anything, and a device's community and v3 keys are never returned.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from sqlalchemy import select
|
||||
|
||||
from steward.core.metric_series import points
|
||||
from steward.mcp._context import mcp_app
|
||||
from steward.mcp.tools._shape import age_s, db_session, iso, lookback, now_utc, pick, summarize
|
||||
from steward.mcp.tools.overview import finding
|
||||
from steward.models.users import UserRole
|
||||
|
||||
from .models import SnmpDevice
|
||||
from .readings import stored_unit
|
||||
from .routes import _latest, shown_readings
|
||||
from .service import device_state, readings_for
|
||||
|
||||
REACHES = ("down", "stale", "pending", "up")
|
||||
_ORDER = {r: i for i, r in enumerate(REACHES)}
|
||||
|
||||
|
||||
def _poll_seconds() -> int:
|
||||
return int(mcp_app().config["PLUGINS"]["snmp"].get("poll_interval_seconds", 60))
|
||||
|
||||
|
||||
def _device_view(d: SnmpDevice, values: dict, now, poll: int) -> dict:
|
||||
state = device_state(d, poll, now)
|
||||
names = {r.key: r.name for r in readings_for(d)}
|
||||
return {"device_id": d.id, "name": d.name, "address": d.address, "port": d.port, "version": d.version,
|
||||
"host_id": d.host_id, "reach": state.reach, "says": state.says,
|
||||
"polled_at": iso(d.last_polled_at), "ok_at": iso(d.last_ok_at), "ok_age_s": age_s(d.last_ok_at, now),
|
||||
"readings": [{"key": r["key"], "name": r["name"], "value": r["text"], "counter": r["counter"]}
|
||||
for r in shown_readings(d, values)],
|
||||
"missing": [names.get(k, k) for k in d.missing or []]}
|
||||
|
||||
|
||||
async def list_snmp_devices(reach: str = "") -> dict:
|
||||
"""The devices Steward polls over SNMP (switches, UPSes, printers, NAS
|
||||
boxes), not answering first.
|
||||
|
||||
reach: "down" (the last poll failed; `says` is why), "stale" (not polled
|
||||
recently: the plugin may be off), "pending" (never polled), "up"; empty
|
||||
for all.
|
||||
|
||||
Each device gives its newest readings in their units (counters as
|
||||
rates), and `missing`: readings it is configured for that the device
|
||||
didn't return. get_snmp_device gives a device's history.
|
||||
"""
|
||||
if reach and reach not in REACHES:
|
||||
raise ValueError(f"reach must be one of {', '.join(REACHES)}, or empty for all.")
|
||||
now, poll = now_utc(), _poll_seconds()
|
||||
async with db_session() as db:
|
||||
devices = list((await db.execute(select(SnmpDevice).order_by(SnmpDevice.name))).scalars())
|
||||
values = await _latest(db, [d.name for d in devices])
|
||||
rows = sorted((_device_view(d, values.get(d.name, {}), now, poll) for d in devices),
|
||||
key=lambda v: (_ORDER[v["reach"]], v["name"].lower()))
|
||||
return {"devices": [r for r in rows if not reach or r["reach"] == reach], "total": len(rows)}
|
||||
|
||||
|
||||
async def get_snmp_device(device: str, range: str = "24h") -> dict:
|
||||
"""One SNMP device: its state, newest readings, and each reading's
|
||||
history over `range` (min/avg/max/last and ≤60 points, in the unit the
|
||||
reading is stored in: `unit`).
|
||||
|
||||
device: its name or id (list_snmp_devices).
|
||||
range: "1h", "6h", "24h" (default), "7d" or "30d".
|
||||
"""
|
||||
since, key = lookback(range)
|
||||
now, poll = now_utc(), _poll_seconds()
|
||||
async with db_session() as db:
|
||||
devices = list((await db.execute(select(SnmpDevice))).scalars())
|
||||
d = pick(device, devices, kind="SNMP device", list_tool="list_snmp_devices")
|
||||
values = (await _latest(db, [d.name])).get(d.name, {})
|
||||
history = {r.key: (stored_unit(r), await points(db, "snmp", d.name, r.key, since))
|
||||
for r in readings_for(d)}
|
||||
out = _device_view(d, values, now, poll)
|
||||
out["range"] = key
|
||||
out["history"] = {k: {"unit": unit, **summarize(pts)} for k, (unit, pts) in history.items()}
|
||||
return out
|
||||
|
||||
|
||||
def device_findings(views: list[dict]) -> list[dict]:
|
||||
"""A device whose last poll failed. A stale one is the plugin or poller,
|
||||
not the device, so it is left out."""
|
||||
return [finding("warning", "snmp_device_down", v["name"],
|
||||
f"SNMP device {v['name']} ({v['address']}) isn't answering: {v['says']}",
|
||||
since=v["_ok_at"], ids={"device_id": v["device_id"]},
|
||||
next=f'get_snmp_device(device="{v["name"]}")')
|
||||
for v in views if v["reach"] == "down"]
|
||||
|
||||
|
||||
async def mcp_overview(db) -> list[dict]:
|
||||
now, poll = now_utc(), _poll_seconds()
|
||||
devices = list((await db.execute(select(SnmpDevice))).scalars())
|
||||
views = [_device_view(d, {}, now, poll) | {"_ok_at": d.last_ok_at} for d in devices]
|
||||
return device_findings(views)
|
||||
|
||||
|
||||
def register_tools(register) -> None:
|
||||
for fn in (list_snmp_devices, get_snmp_device):
|
||||
register(fn, role=UserRole.viewer, read_only=True)
|
||||
@@ -0,0 +1,31 @@
|
||||
"""SNMP devices keep the rows of their vendor tables, and states in words
|
||||
|
||||
A NAS preset reads a row per disk and volume, found by walking the device's
|
||||
tables; the rows found, when, and each state reading's newest word are kept
|
||||
on the device (milestone 530).
|
||||
|
||||
Revision ID: snmp_002_table_rows
|
||||
Revises: snmp_001_devices
|
||||
Create Date: 2026-10-17
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "snmp_002_table_rows"
|
||||
down_revision: Union[str, None] = "snmp_001_devices"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("snmp_devices", sa.Column("tables", sa.JSON, nullable=False, server_default="{}"))
|
||||
op.add_column("snmp_devices", sa.Column("tables_at", sa.DateTime(timezone=True), nullable=True))
|
||||
op.add_column("snmp_devices", sa.Column("texts", sa.JSON, nullable=False, server_default="{}"))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("snmp_devices", "texts")
|
||||
op.drop_column("snmp_devices", "tables_at")
|
||||
op.drop_column("snmp_devices", "tables")
|
||||
@@ -0,0 +1,27 @@
|
||||
"""SNMP devices keep the name each reports (sysName)
|
||||
|
||||
A device whose syslog lines arrive through Docker's address is placed by the
|
||||
name its lines carry; the name the device reports over SNMP is how that name
|
||||
finds the device (#6096).
|
||||
|
||||
Revision ID: snmp_003_sys_name
|
||||
Revises: snmp_002_table_rows
|
||||
Create Date: 2026-10-19
|
||||
"""
|
||||
from typing import Sequence, Union
|
||||
|
||||
import sqlalchemy as sa
|
||||
from alembic import op
|
||||
|
||||
revision: str = "snmp_003_sys_name"
|
||||
down_revision: Union[str, None] = "snmp_002_table_rows"
|
||||
branch_labels: Union[str, Sequence[str], None] = None
|
||||
depends_on: Union[str, Sequence[str], None] = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.add_column("snmp_devices", sa.Column("sys_name", sa.String(255), nullable=False, server_default=""))
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.drop_column("snmp_devices", "sys_name")
|
||||
@@ -16,6 +16,9 @@ class SnmpDevice(Base):
|
||||
Secrets (the community, the v3 keys) are stored encrypted. The last_*
|
||||
columns are the newest poll's outcome, written by the poller, so a page
|
||||
can say why a device isn't answering without asking the device itself.
|
||||
`tables` is the rows the poller found in the presets' vendor tables (a
|
||||
disk or volume each), as of `tables_at`; `texts` is each state reading's
|
||||
newest answer in the device's own word.
|
||||
"""
|
||||
__tablename__ = "snmp_devices"
|
||||
|
||||
@@ -40,3 +43,9 @@ class SnmpDevice(Base):
|
||||
last_ok_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
last_error: Mapped[str | None] = mapped_column(Text, nullable=True)
|
||||
missing: Mapped[list] = mapped_column(JSON, nullable=False, default=list)
|
||||
tables: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||
tables_at: Mapped[datetime | None] = mapped_column(DateTime(timezone=True), nullable=True)
|
||||
texts: Mapped[dict] = mapped_column(JSON, nullable=False, default=dict)
|
||||
# The name the device reports (sysName), asked with every poll: how a
|
||||
# device whose syslog comes through Docker's address is found (#6096).
|
||||
sys_name: Mapped[str] = mapped_column(String(255), nullable=False, default="")
|
||||
|
||||
+102
-5
@@ -48,6 +48,13 @@ class PollResult:
|
||||
readings: dict[str, float] = field(default_factory=dict)
|
||||
error: str | None = None # the device didn't answer, and why
|
||||
missing: list[str] = field(default_factory=list) # keys it answered without
|
||||
texts: dict[str, str] = field(default_factory=dict) # keys answered in words, not a number
|
||||
|
||||
|
||||
@dataclass
|
||||
class TableScan:
|
||||
rows: dict[str, list[dict]] = field(default_factory=dict) # table id -> [{"index", "label", "columns"}]
|
||||
error: str | None = None
|
||||
|
||||
|
||||
def _pysnmp_available() -> bool:
|
||||
@@ -149,9 +156,10 @@ async def poll_device(address: str, port: int, creds: Credentials,
|
||||
oids: list[tuple[str, str]]) -> PollResult:
|
||||
"""GET every (oid, key) of a device, a few dozen to a request.
|
||||
|
||||
Returns the numeric answers by key, the keys the device answered without
|
||||
(no such object, or not a number), and an error in words when it didn't
|
||||
answer at all. Never raises: a broken device must not stop the others.
|
||||
Returns the numeric answers by key, the answers in words (a vendor's
|
||||
status), the keys the device answered without, and an error in words when
|
||||
it didn't answer at all. Never raises: a broken device must not stop the
|
||||
others.
|
||||
"""
|
||||
result = PollResult()
|
||||
if not oids:
|
||||
@@ -198,8 +206,12 @@ async def poll_device(address: str, port: int, creds: Credentials,
|
||||
try:
|
||||
result.readings[key] = float(val)
|
||||
except (TypeError, ValueError):
|
||||
result.missing.append(key)
|
||||
if not result.readings and result.missing:
|
||||
text = str(val).strip()
|
||||
if text:
|
||||
result.texts[key] = text
|
||||
else:
|
||||
result.missing.append(key)
|
||||
if not result.readings and not result.texts and result.missing:
|
||||
result.error = "The device answered but has none of these readings."
|
||||
return result
|
||||
except Exception as exc:
|
||||
@@ -210,6 +222,91 @@ async def poll_device(address: str, port: int, creds: Credentials,
|
||||
_close_engine(engine)
|
||||
|
||||
|
||||
# Rows kept of one table: enough for any NAS's disks and volumes.
|
||||
ROWS_PER_TABLE = 64
|
||||
# Entries walked of one column, before rows_like keeps the physical disks: a
|
||||
# Synology's UCD-DISKIO lists RAM disks, loops, partitions and md arrays ahead
|
||||
# of a disk added late, so the bound is on the walk, not on the rows kept, and
|
||||
# it only stops a device that answers a walk forever.
|
||||
ENTRIES_PER_COLUMN = 1024
|
||||
|
||||
|
||||
async def _walk_column(api, engine, auth, transport, column: str) -> dict[str, object] | str:
|
||||
"""{row index: value} for one column, or the error in words when the
|
||||
device didn't answer. A column the device lacks is an empty dict."""
|
||||
found: dict[str, object] = {}
|
||||
async for ei, es, _, rows in api.walk(engine, auth, transport, api.hl.ContextData(),
|
||||
api.hl.ObjectType(api.hl.ObjectIdentity(column)),
|
||||
lexicographicMode=False, lookupMib=False):
|
||||
if ei:
|
||||
return str(ei)
|
||||
if es:
|
||||
break
|
||||
for name, val in rows:
|
||||
oid = str(name)
|
||||
if type(val).__name__ in _ABSENT or not oid.startswith(column + "."):
|
||||
continue
|
||||
found[oid[len(column) + 1:]] = val
|
||||
if len(found) >= ENTRIES_PER_COLUMN:
|
||||
break
|
||||
return found
|
||||
|
||||
|
||||
async def walk_tables(address: str, port: int, creds: Credentials, tables: list) -> TableScan:
|
||||
"""Which rows each vendor table has: each row's index, its label, and the
|
||||
columns it answered. A walk per column, so it is asked for by the
|
||||
scheduled poll when a device's rows are unknown or an hour old, never on a
|
||||
page load. Never raises."""
|
||||
scan = TableScan()
|
||||
if not tables:
|
||||
return scan
|
||||
if not _pysnmp_available():
|
||||
scan.error = "pysnmp isn't installed in this image, so SNMP polling is off."
|
||||
return scan
|
||||
api = _api()
|
||||
engine = api.hl.SnmpEngine()
|
||||
try:
|
||||
try:
|
||||
transport = await _transport(api, address, port)
|
||||
except Exception as exc:
|
||||
scan.error = f"Can't reach {address}:{port}: {exc}"
|
||||
return scan
|
||||
auth = _auth_data(api, creds)
|
||||
for table in tables:
|
||||
labels: dict[str, object] = {}
|
||||
if table.label:
|
||||
got = await _walk_column(api, engine, auth, transport, table.label)
|
||||
if isinstance(got, str):
|
||||
scan.error = explain(got, address, port, creds)
|
||||
return scan
|
||||
labels = got
|
||||
answered: dict[str, set[str]] = {}
|
||||
for column in table.columns:
|
||||
got = await _walk_column(api, engine, auth, transport, column.oid)
|
||||
if isinstance(got, str):
|
||||
scan.error = explain(got, address, port, creds)
|
||||
return scan
|
||||
for index in got:
|
||||
answered.setdefault(index, set()).add(column.key)
|
||||
indexes = labels if table.label else answered
|
||||
rows = []
|
||||
for index in sorted(indexes, key=lambda i: [int(p) for p in i.split(".") if p.isdigit()]):
|
||||
label = str(labels.get(index, "")).strip()
|
||||
if table.label and not table.keeps(label):
|
||||
continue
|
||||
columns = [c.key for c in table.columns if c.key in answered.get(index, ())]
|
||||
if columns:
|
||||
rows.append({"index": index, "label": label, "columns": columns})
|
||||
scan.rows[table.id] = rows[:ROWS_PER_TABLE]
|
||||
return scan
|
||||
except Exception as exc:
|
||||
logger.warning("SNMP table walk of %s:%s failed: %s", address, port, exc)
|
||||
scan.error = f"SNMP table walk failed: {exc}"
|
||||
return scan
|
||||
finally:
|
||||
_close_engine(engine)
|
||||
|
||||
|
||||
SYS_DESCR, SYS_UPTIME, SYS_NAME = "1.3.6.1.2.1.1.1.0", "1.3.6.1.2.1.1.3.0", "1.3.6.1.2.1.1.5.0"
|
||||
IF_DESCR, IF_NAME = "1.3.6.1.2.1.2.2.1.2", "1.3.6.1.2.1.31.1.1.1.1"
|
||||
INTERFACES_LISTED = 128
|
||||
|
||||
+288
-17
@@ -6,11 +6,25 @@ lines. Each reading has a key (the metric name it is stored and alerted on),
|
||||
a name a person reads, and a unit. A counter (an interface's byte count, any
|
||||
"total so far") is stored as a rate: the poller turns two samples into a
|
||||
per-second figure, so a chart and an alert see traffic, not a lifetime total.
|
||||
|
||||
A preset may also read a vendor's tables, a row per disk or volume (Table).
|
||||
Which rows a device has is discovered from the device by the scheduled poll
|
||||
and stored on its row, so every reader builds the same readings from it.
|
||||
|
||||
A vendor's status (a code, or a word) is a "state" reading: stored as a level
|
||||
(0 OK, 1 busy, 2 warning, 3 failed), so one alert rule reads any vendor's,
|
||||
and shown in the device's own word.
|
||||
|
||||
A reading may be worked out from others (`inputs`, combined by `combine`):
|
||||
the device is asked for its inputs, each read in its own unit (a counter as
|
||||
its rate), and only the result is stored and shown. CPU waiting on disk is
|
||||
one counter's share of the CPU's.
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
import re
|
||||
from dataclasses import dataclass
|
||||
from dataclasses import dataclass, field
|
||||
from typing import Callable
|
||||
|
||||
from steward.core.formatting import human_bytes, human_duration
|
||||
|
||||
@@ -23,6 +37,9 @@ class Reading:
|
||||
unit: str = "number"
|
||||
scale: float = 1.0
|
||||
offset: float = 0.0
|
||||
states: str = "" # a state reading's codes: a STATE_CODES name, or "words"
|
||||
inputs: tuple[Reading, ...] = ()
|
||||
combine: Callable[[dict], float | None] | None = field(default=None, compare=False)
|
||||
|
||||
@property
|
||||
def counter(self) -> bool:
|
||||
@@ -31,7 +48,8 @@ class Reading:
|
||||
|
||||
# A counter's unit names what it counts; it is stored as the rate unit it maps
|
||||
# to, multiplied by the factor (a byte counter is stored as bits per second).
|
||||
COUNTER_UNITS = {"octets": ("bits_per_second", 8.0), "count": ("per_second", 1.0)}
|
||||
COUNTER_UNITS = {"octets": ("bits_per_second", 8.0), "byte_count": ("bytes_per_second", 1.0),
|
||||
"count": ("per_second", 1.0)}
|
||||
|
||||
STATUS_WORDS = {
|
||||
"if_status": {1: "up", 2: "down", 3: "testing", 4: "unknown", 5: "dormant",
|
||||
@@ -39,6 +57,49 @@ STATUS_WORDS = {
|
||||
"ups_battery": {1: "unknown", 2: "normal", 3: "low", 4: "depleted"},
|
||||
}
|
||||
|
||||
# A state reading is stored as one of these levels; an alert rule on "level
|
||||
# at least 2" catches any vendor's degraded or failed.
|
||||
LEVELS = {0: "OK", 1: "Busy", 2: "Warning", 3: "Failed"}
|
||||
|
||||
# A vendor's status codes: code -> (the vendor's word, level). Synology's are
|
||||
# from its MIB guide (SYNOLOGY-SYSTEM-, -DISK- and -RAID-MIB).
|
||||
STATE_CODES: dict[str, dict[int, tuple[str, int]]] = {
|
||||
"synology_ok": {1: ("Normal", 0), 2: ("Failed", 3)},
|
||||
"synology_disk": {1: ("Normal", 0), 2: ("Initialized", 0), 3: ("Not initialized", 2),
|
||||
4: ("System partition failed", 3), 5: ("Crashed", 3)},
|
||||
"synology_health": {1: ("Normal", 0), 2: ("Warning", 2), 3: ("Critical", 3), 4: ("Failing", 3)},
|
||||
"synology_raid": {1: ("Normal", 0), 2: ("Repairing", 1), 3: ("Migrating", 1), 4: ("Expanding", 1),
|
||||
5: ("Deleting", 1), 6: ("Creating", 1), 7: ("Syncing", 1), 8: ("Parity checking", 1),
|
||||
9: ("Assembling", 1), 10: ("Canceling", 1), 11: ("Degraded", 2), 12: ("Crashed", 3),
|
||||
13: ("Data scrubbing", 1), 14: ("Deploying", 1), 15: ("Undeploying", 1),
|
||||
16: ("Mounting cache", 1), 17: ("Unmounting cache", 1), 18: ("Expanding", 1),
|
||||
19: ("Converting to a storage pool", 1), 20: ("Migrating SHR1 to SHR2", 1),
|
||||
21: ("Unknown", 2)},
|
||||
}
|
||||
|
||||
# A vendor that answers in words (Asustor) is read by the words' beginnings,
|
||||
# worst first: "Unhealthy" is failed before "healthy" can call it OK.
|
||||
_WORD_LEVELS = (
|
||||
(3, re.compile(r"\b(fail|crash|critical|bad|error|abnormal|unhealthy|broken|removed|missing|offline)", re.I)),
|
||||
(2, re.compile(r"\b(degrad|warn|unknown)", re.I)),
|
||||
(1, re.compile(r"\b(sync|resync|rebuild|repair|recover|scrub|check|migrat|expand|creat|initiali|build)",
|
||||
re.I)),
|
||||
(0, re.compile(r"\b(normal|good|healthy|ok|ready|active|online|clean|pass)", re.I)),
|
||||
)
|
||||
|
||||
|
||||
def state_of(reading: Reading, raw: float | str) -> tuple[str, int | None]:
|
||||
"""A state reading's answer as (the device's word, level). The level is
|
||||
None for a code or word Steward doesn't know: it is shown, not stored."""
|
||||
if reading.states == "words":
|
||||
word = str(raw).strip()
|
||||
return word, next((level for level, rx in _WORD_LEVELS if rx.search(word)), None)
|
||||
try:
|
||||
code = int(float(raw))
|
||||
except (TypeError, ValueError):
|
||||
return str(raw).strip(), None
|
||||
return STATE_CODES.get(reading.states, {}).get(code, (f"code {code}", None))
|
||||
|
||||
# The units a custom line may name, with how each one reads, for the form's hint.
|
||||
UNITS = {
|
||||
"number": "a plain number",
|
||||
@@ -51,12 +112,114 @@ UNITS = {
|
||||
"centiseconds": "a span in hundredths of a second (sysUpTime)",
|
||||
"bytes": "a size in bytes",
|
||||
"kilobytes": "a size in KiB",
|
||||
"rpm": "revolutions per minute (a fan)",
|
||||
"octets": "a byte counter, shown as traffic (bit/s)",
|
||||
"byte_count": "a byte counter, shown as bytes a second (disk I/O)",
|
||||
"count": "any other counter, shown per second",
|
||||
}
|
||||
|
||||
_UPTIME = Reading("1.3.6.1.2.1.1.3.0", "uptime", "Uptime", "centiseconds")
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Column:
|
||||
"""One column of a vendor table: a row's reading is this OID plus the
|
||||
row's index."""
|
||||
oid: str
|
||||
key: str
|
||||
name: str
|
||||
unit: str = "number"
|
||||
scale: float = 1.0
|
||||
states: str = ""
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Table:
|
||||
"""A vendor table with a row per disk, volume, fan or sensor.
|
||||
|
||||
`label` is the column naming each row ("Disk 1", "Volume 1"); a row's
|
||||
readings are keyed by prefix, index and column ("disk0_status") and named
|
||||
by its label and column ("Disk 1 status"). A table with no label column
|
||||
(one temperature sensor, one memory) is keyed and named by its columns
|
||||
alone while it has one row. `rows_like` keeps only rows whose label
|
||||
matches it (physical disks, not partitions and loop devices).
|
||||
`by_index` names each row by its noun and index instead ("Disk 1"), for
|
||||
a device whose own label doesn't say which bay it is (ADM's "Disk0")."""
|
||||
id: str
|
||||
prefix: str
|
||||
label: str
|
||||
noun: str
|
||||
columns: tuple[Column, ...]
|
||||
rows_like: str = ""
|
||||
by_index: bool = False
|
||||
|
||||
def column_oids(self) -> list[str]:
|
||||
return ([self.label] if self.label else []) + [c.oid for c in self.columns]
|
||||
|
||||
def keeps(self, label: str) -> bool:
|
||||
return not self.rows_like or re.fullmatch(self.rows_like, label) is not None
|
||||
|
||||
|
||||
def table_readings(table: Table, rows: list[dict]) -> list[Reading]:
|
||||
"""The readings of a table's discovered rows: [{"index", "label",
|
||||
"columns"}], each asked only for the columns it answered."""
|
||||
out: list[Reading] = []
|
||||
alone = not table.label and len(rows) == 1
|
||||
for row in rows:
|
||||
index, label = str(row["index"]), str(row.get("label") or "")
|
||||
if table.by_index:
|
||||
label = f"{table.noun} {index}"
|
||||
elif label.isdigit() or (table.label and not label):
|
||||
label = f"{table.noun} {label or index}"
|
||||
for c in table.columns:
|
||||
if c.key not in row.get("columns", ()):
|
||||
continue
|
||||
if table.label:
|
||||
key, name = f"{table.prefix}{index.replace('.', '_')}_{c.key}", f"{label} {c.name}"
|
||||
elif alone:
|
||||
key, name = c.key, c.name
|
||||
else:
|
||||
key, name = f"{c.key}{index.replace('.', '_')}", f"{c.name} ({table.noun.lower()} {index})"
|
||||
out.append(Reading(f"{c.oid}.{index}", key, name, c.unit, scale=c.scale, states=c.states))
|
||||
return out
|
||||
|
||||
|
||||
def _syn(oid: str) -> str:
|
||||
return f"1.3.6.1.4.1.6574.{oid}"
|
||||
|
||||
|
||||
def _asus(oid: str) -> str:
|
||||
return f"1.3.6.1.4.1.44738.{oid}"
|
||||
|
||||
|
||||
_GIB = float(2 ** 30)
|
||||
|
||||
|
||||
def _ucd(oid: str) -> str:
|
||||
return f"1.3.6.1.4.1.2021.{oid}"
|
||||
|
||||
|
||||
# UCD-SNMP-MIB's CPU tick counters. On Linux ssCpuRawSystem already holds the
|
||||
# interrupt time, so these five are the whole.
|
||||
_CPU_TICKS = tuple(Reading(_ucd(f"11.{n}.0"), f"cpu_ticks_{part}", f"CPU ticks {part}", "count")
|
||||
for n, part in ((50, "user"), (51, "nice"), (52, "system"), (53, "idle"), (54, "wait")))
|
||||
|
||||
|
||||
def _wait_share(v: dict) -> float | None:
|
||||
total = sum(v.values())
|
||||
return 100.0 * v["cpu_ticks_wait"] / total if total > 0 else None
|
||||
|
||||
|
||||
_CPU_WAIT = Reading("", "cpu_iowait", "CPU waiting on disk", "percent", inputs=_CPU_TICKS,
|
||||
combine=_wait_share)
|
||||
# What the kernel could hand a program without swapping: free, plus the
|
||||
# buffers and page cache it gives back on demand.
|
||||
_MEMORY_AVAILABLE = Reading(
|
||||
"", "memory_available", "Memory available", "kilobytes",
|
||||
inputs=tuple(Reading(_ucd(f"4.{n}.0"), f"memory_{part}_kb", f"Memory {part}", "kilobytes")
|
||||
for n, part in ((6, "free"), (14, "buffers"), (15, "cached"))),
|
||||
combine=lambda v: sum(v.values()))
|
||||
|
||||
# id: (label, what it is for, readings). Interface traffic is per interface
|
||||
# and built by interface_readings from the numbers on the form.
|
||||
PRESETS: dict[str, tuple[str, str, tuple[Reading, ...]]] = {
|
||||
@@ -70,18 +233,93 @@ PRESETS: dict[str, tuple[str, str, tuple[Reading, ...]]] = {
|
||||
Reading("1.3.6.1.2.1.33.1.4.4.1.5.1", "load", "Load", "percent"),
|
||||
Reading("1.3.6.1.2.1.33.1.3.3.1.3.1", "input_voltage", "Input", "volts"),
|
||||
Reading("1.3.6.1.2.1.33.1.2.2.0", "on_battery_for", "On battery", "battery_seconds"))),
|
||||
"linux": ("Linux server", "CPU, memory and load from net-snmp (snmpd's UCD-SNMP-MIB).",
|
||||
(Reading("1.3.6.1.4.1.2021.11.11.0", "cpu_used", "CPU used", "percent", scale=-1.0, offset=100.0),
|
||||
Reading("1.3.6.1.4.1.2021.10.1.5.1", "load_1m", "Load (1m)", "number", scale=0.01),
|
||||
Reading("1.3.6.1.4.1.2021.4.6.0", "memory_free", "Memory free", "kilobytes"),
|
||||
Reading("1.3.6.1.4.1.2021.4.5.0", "memory_total", "Memory total", "kilobytes"))),
|
||||
"linux": ("Linux server", "CPU, how much of it waits on disk, memory and load from net-snmp (snmpd's "
|
||||
"UCD-SNMP-MIB), and how busy each disk has been over the last minute "
|
||||
"(UCD-DISKIO-MIB). Most NAS boxes answer it too.",
|
||||
(Reading(_ucd("11.11.0"), "cpu_used", "CPU used", "percent", scale=-1.0, offset=100.0),
|
||||
_CPU_WAIT,
|
||||
Reading(_ucd("10.1.5.1"), "load_1m", "Load (1m)", "number", scale=0.01),
|
||||
Reading(_ucd("4.6.0"), "memory_free", "Memory free", "kilobytes"),
|
||||
_MEMORY_AVAILABLE,
|
||||
Reading(_ucd("4.5.0"), "memory_total", "Memory total", "kilobytes"))),
|
||||
"synology": ("Synology NAS", "System, power and fan status and temperature; each disk's status, health, "
|
||||
"temperature, bad sectors and reconnects, and what it reads and writes; "
|
||||
"each volume's state (scrubbing, rebuilding, degraded), space, reads and "
|
||||
"writes. Tick Linux server too for CPU, memory and disk load.",
|
||||
(Reading(_syn("1.1.0"), "system_status", "System", "state", states="synology_ok"),
|
||||
Reading(_syn("1.2.0"), "temperature", "Temperature", "celsius"),
|
||||
Reading(_syn("1.3.0"), "power_status", "Power", "state", states="synology_ok"),
|
||||
Reading(_syn("1.4.1.0"), "system_fan", "System fan", "state", states="synology_ok"),
|
||||
Reading(_syn("1.4.2.0"), "cpu_fan", "CPU fan", "state", states="synology_ok"))),
|
||||
"asustor": ("Asustor NAS", "Each disk's status, SMART verdict and temperature; each volume's status and "
|
||||
"space; CPU and system temperature, free memory and fan speed (ADM's "
|
||||
"ASUSTOR-DISK- and -SYSTEM-MIB). Tick Linux server too for CPU, load and disk load.",
|
||||
()),
|
||||
}
|
||||
|
||||
PRESET_ORDER = ("system", "interfaces", "ups", "linux")
|
||||
def _io_columns(mib: int) -> tuple[Column, ...]:
|
||||
return (Column(_syn(f"{mib}.1.1.12"), "read", "read", "byte_count"),
|
||||
Column(_syn(f"{mib}.1.1.13"), "written", "written", "byte_count"),
|
||||
Column(_syn(f"{mib}.1.1.5"), "reads", "reads", "count"),
|
||||
Column(_syn(f"{mib}.1.1.6"), "writes", "writes", "count"),
|
||||
Column(_syn(f"{mib}.1.1.8"), "load", "load", "percent"))
|
||||
|
||||
|
||||
# A preset's vendor tables, read as one row per disk, volume, fan or sensor.
|
||||
TABLES: dict[str, tuple[Table, ...]] = {
|
||||
"linux": (Table("ucd_diskio", "diskio", "1.3.6.1.4.1.2021.13.15.1.1.2", "Disk",
|
||||
(Column("1.3.6.1.4.1.2021.13.15.1.1.9", "busy", "busy", "percent"),),
|
||||
rows_like=r"(sd[a-z]+|hd[a-z]+|vd[a-z]+|xvd[a-z]+|nvme\d+n\d+|sata\d+)"),),
|
||||
"synology": (
|
||||
Table("synology_disks", "disk", _syn("2.1.1.2"), "Disk",
|
||||
(Column(_syn("2.1.1.5"), "status", "status", "state", states="synology_disk"),
|
||||
Column(_syn("2.1.1.13"), "health", "health", "state", states="synology_health"),
|
||||
Column(_syn("2.1.1.6"), "temp", "temperature", "celsius"),
|
||||
Column(_syn("2.1.1.9"), "bad_sectors", "bad sectors"),
|
||||
# How often DSM has had to reconnect to the disk, and how often
|
||||
# the disk couldn't find a sector it was asked for (IDNF).
|
||||
Column(_syn("2.1.1.8"), "retries", "reconnects"),
|
||||
Column(_syn("2.1.1.10"), "identify_fails", "sectors not found"))),
|
||||
Table("synology_volumes", "raid", _syn("3.1.1.2"), "Volume",
|
||||
(Column(_syn("3.1.1.3"), "status", "status", "state", states="synology_raid"),
|
||||
Column(_syn("3.1.1.4"), "free", "free", "bytes"),
|
||||
Column(_syn("3.1.1.5"), "size", "size", "bytes"))),
|
||||
# SYNOLOGY-STORAGEIO-MIB, a row per disk, and -SPACEIO-MIB, a row per
|
||||
# volume: bytes from the 64-bit counters, requests a second, and the
|
||||
# load DSM gives it (%). A volume slow to answer NFS shows here first.
|
||||
Table("synology_disk_io", "storageio", _syn("101.1.1.2"), "Disk", _io_columns(101),
|
||||
rows_like=r"(sd[a-z]+|sata\d+|nvme\d+n\d+)"),
|
||||
Table("synology_volume_io", "spaceio", _syn("102.1.1.2"), "Volume", _io_columns(102)),
|
||||
),
|
||||
"asustor": (
|
||||
Table("asustor_disks", "disk", _asus("4.1.1.2"), "Disk",
|
||||
(Column(_asus("4.1.1.5"), "status", "status", "state", states="words"),
|
||||
Column(_asus("4.1.1.6"), "smart", "SMART", "state", states="words"),
|
||||
Column(_asus("4.1.1.7"), "temp", "temperature", "celsius")), by_index=True),
|
||||
Table("asustor_volumes", "volume", _asus("5.1.1.2"), "Volume",
|
||||
(Column(_asus("5.1.1.4"), "status", "status", "state", states="words"),
|
||||
Column(_asus("5.1.1.7"), "free", "free", "bytes", scale=_GIB),
|
||||
Column(_asus("5.1.1.6"), "size", "size", "bytes", scale=_GIB))),
|
||||
Table("asustor_temperatures", "", "", "Sensor",
|
||||
(Column(_asus("2.5.1.2"), "cpu_temp", "CPU temperature", "celsius"),
|
||||
Column(_asus("2.5.1.3"), "system_temp", "System temperature", "celsius"))),
|
||||
Table("asustor_memory", "", "", "Memory",
|
||||
(Column(_asus("2.6.1.4"), "memory_free_pct", "Memory free", "percent"),)),
|
||||
Table("asustor_fans", "", "", "Fan",
|
||||
(Column(_asus("2.4.1.2"), "fan", "Fan speed", "rpm"),)),
|
||||
),
|
||||
}
|
||||
|
||||
PRESET_ORDER = ("system", "interfaces", "ups", "linux", "synology", "asustor")
|
||||
INTERFACES_LABEL = ("Interface traffic", "Traffic in and out and link state for the interfaces numbered "
|
||||
"below. Test the device to see its interfaces and their numbers.")
|
||||
|
||||
|
||||
def tables_for(presets: list[str]) -> list[Table]:
|
||||
"""The vendor tables the ticked presets read, in preset order."""
|
||||
return [t for pid in PRESET_ORDER if pid in (presets or []) for t in TABLES.get(pid, ())]
|
||||
|
||||
|
||||
def parse_interfaces(text: str) -> list[int]:
|
||||
"""'1, 2, 5-7' → [1, 2, 5, 6, 7]. Raises ValueError naming what it can't read."""
|
||||
out: list[int] = []
|
||||
@@ -99,9 +337,10 @@ def parse_interfaces(text: str) -> list[int]:
|
||||
|
||||
|
||||
def interface_readings(numbers: list[int], version: str) -> list[Reading]:
|
||||
"""In, out and link state per interface. v2c and v3 read the 64-bit
|
||||
counters (ifHCInOctets), which don't wrap on a fast link; v1 has only the
|
||||
32-bit ones (ifInOctets)."""
|
||||
"""In, out and link state per interface, and the packets it got wrong or
|
||||
had to throw away. v2c and v3 read the 64-bit counters (ifHCInOctets),
|
||||
which don't wrap on a fast link; v1 has only the 32-bit ones
|
||||
(ifInOctets)."""
|
||||
hc = version != "1"
|
||||
out: list[Reading] = []
|
||||
for n in numbers:
|
||||
@@ -109,7 +348,12 @@ def interface_readings(numbers: list[int], version: str) -> list[Reading]:
|
||||
tx = f"1.3.6.1.2.1.31.1.1.1.10.{n}" if hc else f"1.3.6.1.2.1.2.2.1.16.{n}"
|
||||
out += [Reading(f"1.3.6.1.2.1.2.2.1.8.{n}", f"if{n}_status", f"Interface {n}", "if_status"),
|
||||
Reading(rx, f"if{n}_in", f"Interface {n} in", "octets"),
|
||||
Reading(tx, f"if{n}_out", f"Interface {n} out", "octets")]
|
||||
Reading(tx, f"if{n}_out", f"Interface {n} out", "octets"),
|
||||
Reading(f"1.3.6.1.2.1.2.2.1.14.{n}", f"if{n}_in_errors", f"Interface {n} errors in", "count"),
|
||||
Reading(f"1.3.6.1.2.1.2.2.1.20.{n}", f"if{n}_out_errors", f"Interface {n} errors out", "count"),
|
||||
Reading(f"1.3.6.1.2.1.2.2.1.13.{n}", f"if{n}_in_discards", f"Interface {n} discards in", "count"),
|
||||
Reading(f"1.3.6.1.2.1.2.2.1.19.{n}", f"if{n}_out_discards", f"Interface {n} discards out",
|
||||
"count")]
|
||||
return out
|
||||
|
||||
|
||||
@@ -142,9 +386,13 @@ def parse_custom(text: str) -> list[Reading]:
|
||||
return out
|
||||
|
||||
|
||||
def device_readings(presets: list[str], interfaces: list[int], custom: str, version: str) -> list[Reading]:
|
||||
"""Every reading a device is asked for, presets in their order then custom
|
||||
lines. Raises ValueError when two readings share a name."""
|
||||
def device_readings(presets: list[str], interfaces: list[int], custom: str, version: str,
|
||||
tables: dict | None = None) -> list[Reading]:
|
||||
"""Every reading a device is asked for: presets in their order, the rows
|
||||
discovered in their tables (`tables`, {table id: rows}), then custom
|
||||
lines. Raises ValueError when a custom line repeats a preset's name; a
|
||||
table row a custom line already names is left to the custom line, since
|
||||
rows appear after the form was saved."""
|
||||
out: list[Reading] = []
|
||||
for pid in PRESET_ORDER:
|
||||
if pid == "interfaces":
|
||||
@@ -152,7 +400,14 @@ def device_readings(presets: list[str], interfaces: list[int], custom: str, vers
|
||||
out += interface_readings(interfaces, version)
|
||||
elif pid in presets:
|
||||
out += PRESETS[pid][2]
|
||||
out += parse_custom(custom)
|
||||
custom_readings = parse_custom(custom)
|
||||
taken = {r.key for r in out} | {r.key for r in custom_readings}
|
||||
for table in tables_for(presets):
|
||||
for r in table_readings(table, (tables or {}).get(table.id, [])):
|
||||
if r.key not in taken:
|
||||
out.append(r)
|
||||
taken.add(r.key)
|
||||
out += custom_readings
|
||||
seen: set[str] = set()
|
||||
for r in out:
|
||||
if r.key in seen:
|
||||
@@ -177,6 +432,8 @@ def format_value(unit: str, value: float | None) -> str:
|
||||
"""A stored value as a person reads it, in its unit."""
|
||||
if value is None:
|
||||
return "—"
|
||||
if unit == "state":
|
||||
return LEVELS.get(int(value), f"level {value:.0f}")
|
||||
if unit in STATUS_WORDS:
|
||||
return STATUS_WORDS[unit].get(int(value), f"code {value:.0f}")
|
||||
if unit == "centiseconds":
|
||||
@@ -202,8 +459,12 @@ def format_value(unit: str, value: float | None) -> str:
|
||||
return human_bytes(value * 1024)
|
||||
if unit == "bits_per_second":
|
||||
return _bits(value)
|
||||
if unit == "bytes_per_second":
|
||||
return f"{human_bytes(value)}/s"
|
||||
if unit == "per_second":
|
||||
return f"{value:.3g}/s"
|
||||
if unit == "rpm":
|
||||
return f"{value:,.0f} rpm"
|
||||
return f"{value:,.0f}" if float(value).is_integer() else f"{value:.4g}"
|
||||
|
||||
|
||||
@@ -214,4 +475,14 @@ def chart_axis(unit: str) -> tuple[str, float]:
|
||||
"minutes": ("minutes", 1.0), "percent": ("%", 1.0), "celsius": ("°C", 1.0),
|
||||
"volts": ("V", 1.0), "decivolts": ("V", 0.1), "bytes": ("MiB", 1 / 1_048_576),
|
||||
"kilobytes": ("MiB", 1 / 1024), "bits_per_second": ("Mbit/s", 1e-6),
|
||||
"per_second": ("per second", 1.0)}.get(unit, ("", 1.0))
|
||||
"bytes_per_second": ("MiB/s", 1 / 1_048_576),
|
||||
"per_second": ("per second", 1.0), "rpm": ("rpm", 1.0),
|
||||
"state": ("0 OK · 1 busy · 2 warning · 3 failed", 1.0)}.get(unit, ("", 1.0))
|
||||
|
||||
|
||||
def reading_text(reading: Reading, value: float | None, texts: dict | None) -> str:
|
||||
"""What a page shows for a reading: a state in the device's own word, as
|
||||
its newest poll answered it; anything else in its unit."""
|
||||
if reading.unit == "state" and (texts or {}).get(reading.key):
|
||||
return texts[reading.key]
|
||||
return format_value(stored_unit(reading), value)
|
||||
|
||||
+10
-9
@@ -17,8 +17,7 @@ from steward.models.metrics import PluginMetric, PluginMetricLatest
|
||||
from steward.models.users import UserRole
|
||||
|
||||
from .models import SnmpDevice
|
||||
from .readings import (INTERFACES_LABEL, PRESETS, PRESET_ORDER, UNITS, chart_axis, format_value,
|
||||
stored_unit)
|
||||
from .readings import INTERFACES_LABEL, PRESETS, PRESET_ORDER, UNITS, chart_axis, reading_text, stored_unit
|
||||
from .service import (FormError, device_state, form_credentials, form_values, parse_form,
|
||||
readings_for)
|
||||
|
||||
@@ -40,10 +39,10 @@ async def _latest(db, names: list[str]) -> dict[str, dict]:
|
||||
|
||||
|
||||
def shown_readings(device: SnmpDevice, values: dict) -> list[dict]:
|
||||
"""The device's readings in its own order, each named and in its unit;
|
||||
"—" for one with no value yet."""
|
||||
"""The device's readings in its own order, each named and in its unit (a
|
||||
state in the device's own word); "—" for one with no value yet."""
|
||||
return [{"key": r.key, "name": r.name, "counter": r.counter,
|
||||
"text": format_value(stored_unit(r), values.get(r.key))}
|
||||
"text": reading_text(r, values.get(r.key), device.texts)}
|
||||
for r in readings_for(device)]
|
||||
|
||||
|
||||
@@ -51,6 +50,7 @@ def view(device: SnmpDevice, values: dict, now: datetime) -> dict:
|
||||
state = device_state(device, _poll_seconds(), now)
|
||||
names = {r.key: r.name for r in readings_for(device)}
|
||||
return {"id": device.id, "name": device.name, "address": device.address, "port": device.port,
|
||||
"host_id": device.host_id,
|
||||
"version": device.version, "reach": state.reach, "says": state.says,
|
||||
"polled_at": device.last_polled_at, "ok_at": device.last_ok_at,
|
||||
"readings": shown_readings(device, values),
|
||||
@@ -168,9 +168,10 @@ async def save_device(device_id: str):
|
||||
for column, value in values.items():
|
||||
setattr(device, column, value)
|
||||
# What it is asked, or how, may have changed: the last outcome no
|
||||
# longer describes it, so the page says "not polled yet" until the next poll.
|
||||
device.last_polled_at = device.last_ok_at = device.last_error = None
|
||||
device.missing = []
|
||||
# longer describes it, so the page says "not polled yet" until the
|
||||
# next poll, which also walks its vendor tables again.
|
||||
device.last_polled_at = device.last_ok_at = device.last_error = device.tables_at = None
|
||||
device.missing, device.texts = [], {}
|
||||
if old_name != device.name:
|
||||
# Its history is stored under its name; move it with the rename.
|
||||
for model in (PluginMetric, PluginMetricLatest):
|
||||
@@ -263,7 +264,7 @@ async def device_detail(device_id: str):
|
||||
unit = stored_unit(r)
|
||||
axis, factor = chart_axis(unit)
|
||||
charts.append({"key": r.key, "name": r.name, "axis": axis,
|
||||
"now": format_value(unit, latest.get(device.name, {}).get(r.key)),
|
||||
"now": reading_text(r, latest.get(device.name, {}).get(r.key), device.texts),
|
||||
"points": [(t, v * factor) for t, v in hist.get(r.key, [])]})
|
||||
return await render_template("snmp/device.html", device=view(device, latest.get(device.name, {}), now),
|
||||
charts=charts, charts_json=json.dumps(charts), hours=hours, ranges=RANGES)
|
||||
|
||||
+197
-41
@@ -3,7 +3,9 @@ from __future__ import annotations
|
||||
|
||||
import asyncio
|
||||
import logging
|
||||
from datetime import datetime, timezone
|
||||
from dataclasses import dataclass, field
|
||||
from datetime import datetime, timedelta, timezone
|
||||
from types import SimpleNamespace
|
||||
from typing import TYPE_CHECKING
|
||||
|
||||
from sqlalchemy import select
|
||||
@@ -18,6 +20,20 @@ logger = logging.getLogger(__name__)
|
||||
# Counters' previous samples, for their rates (service.RateKeeper).
|
||||
RATES = None
|
||||
|
||||
# How long a device's discovered table rows stand before they are walked
|
||||
# again: a disk swapped or a volume added shows within the hour, and a NAS is
|
||||
# walked 24 times a day, not 1,440.
|
||||
TABLES_REFRESH = timedelta(hours=1)
|
||||
|
||||
|
||||
def tables_due(device, now: datetime) -> bool:
|
||||
"""Whether this poll walks the device's vendor tables: it reads some, it
|
||||
answered its last poll (a device that isn't answering is only asked its
|
||||
GET), and its rows are unknown, reset by a save, or an hour old."""
|
||||
from .readings import tables_for
|
||||
return (bool(tables_for(device.presets or [])) and not device.last_error
|
||||
and (device.tables_at is None or now - device.tables_at >= TABLES_REFRESH))
|
||||
|
||||
|
||||
def make_poll_task(app: "Quart") -> ScheduledTask:
|
||||
interval = app.config["PLUGINS"]["snmp"].get("poll_interval_seconds", 60)
|
||||
@@ -33,58 +49,198 @@ def make_poll_task(app: "Quart") -> ScheduledTask:
|
||||
)
|
||||
|
||||
|
||||
async def _do_poll(app: "Quart", poll=None) -> None:
|
||||
"""Poll every device at once, then write each one's outcome to its row
|
||||
and its answers to the metric tables. `poll` stands in for
|
||||
poller.poll_device in tests."""
|
||||
global RATES
|
||||
from steward.core.alerts import MetricBatch
|
||||
# Polls collected but not yet stored, written one store at a time (#5995): a
|
||||
# stall of the storage under Postgres delays them instead of losing them. Two
|
||||
# hours at the default one-minute poll.
|
||||
HELD_POLLS = 120
|
||||
# How long the device list may take to read before the last one read stands
|
||||
# in, so a stalled database doesn't stop the polling it is about to explain.
|
||||
DEVICES_READ_S = 10.0
|
||||
# How long a poll waits for its own store before collecting on.
|
||||
STORE_WAIT_S = 20.0
|
||||
|
||||
# Each device as last read: plain copies, so a poll can go on without the
|
||||
# database, and a walk's rows found meanwhile can be kept on them.
|
||||
DEVICES: list | None = None
|
||||
|
||||
|
||||
@dataclass
|
||||
class Polled:
|
||||
"""One device's poll, collected and waiting to be stored."""
|
||||
at: datetime
|
||||
device_id: str
|
||||
name: str
|
||||
failed: str | None = None # the poll raised: why, in words
|
||||
error: str | None = None
|
||||
scan: object = None # a TableScan when the tables were walked
|
||||
answered: bool = False
|
||||
missing: list = field(default_factory=list)
|
||||
texts: dict = field(default_factory=dict)
|
||||
values: list = field(default_factory=list) # (metric, value)
|
||||
sys_name: str | None = None
|
||||
|
||||
|
||||
def _snapshot(device) -> SimpleNamespace:
|
||||
from sqlalchemy import inspect as sa_inspect
|
||||
return SimpleNamespace(**{a.key: getattr(device, a.key)
|
||||
for a in sa_inspect(type(device)).column_attrs})
|
||||
|
||||
|
||||
async def _devices(app: "Quart") -> list:
|
||||
"""The devices to poll: read now, or as last read when the database
|
||||
doesn't answer within DEVICES_READ_S."""
|
||||
global DEVICES
|
||||
from .models import SnmpDevice
|
||||
from .poller import poll_device
|
||||
|
||||
async def read() -> list:
|
||||
async with app.db_sessionmaker() as session:
|
||||
return [_snapshot(d) for d in (await session.execute(select(SnmpDevice))).scalars()]
|
||||
|
||||
try:
|
||||
DEVICES = await asyncio.wait_for(read(), DEVICES_READ_S)
|
||||
except Exception as exc:
|
||||
if DEVICES is None:
|
||||
logger.warning("SNMP devices not read (%s); nothing to poll yet", exc or type(exc).__name__)
|
||||
return []
|
||||
logger.warning("SNMP devices not read within %.0f s (%s); polling the %d last read",
|
||||
DEVICES_READ_S, exc or type(exc).__name__, len(DEVICES))
|
||||
return DEVICES
|
||||
|
||||
|
||||
async def _do_poll(app: "Quart", poll=None, walk=None) -> None:
|
||||
"""Poll every device at once, hold what each answered, and store it: the
|
||||
device's outcome on its row, its answers in the metric tables, each at
|
||||
the time it was collected. A device whose vendor tables are due is walked
|
||||
first, so a new disk is read in the same poll. When the database doesn't
|
||||
take the store within STORE_WAIT_S the poll returns and the next one
|
||||
collects on; what is held is stored, oldest first, once it does (#5995).
|
||||
`poll` and `walk` stand in for poller.poll_device and poller.walk_tables
|
||||
in tests."""
|
||||
global RATES
|
||||
from steward.core.holding import holding
|
||||
|
||||
from .poller import SYS_NAME, poll_device, walk_tables
|
||||
from .readings import state_of, tables_for
|
||||
from .service import RateKeeper, credentials, readings_for
|
||||
|
||||
poll = poll or poll_device
|
||||
walk = walk or walk_tables
|
||||
if RATES is None:
|
||||
RATES = RateKeeper()
|
||||
held = holding(app, "SNMP poll", store=lambda rounds: _store(app, rounds), limit=HELD_POLLS)
|
||||
|
||||
async with app.db_sessionmaker() as session:
|
||||
devices = (await session.execute(select(SnmpDevice))).scalars().all()
|
||||
if not devices:
|
||||
return
|
||||
devices = await _devices(app)
|
||||
if devices:
|
||||
started = datetime.now(timezone.utc)
|
||||
scans, asked = {}, {}
|
||||
|
||||
asked = {d.id: readings_for(d) for d in devices}
|
||||
results = await asyncio.gather(*(
|
||||
poll(d.address, d.port, credentials(d), [(r.oid, r.key) for r in asked[d.id]])
|
||||
for d in devices), return_exceptions=True)
|
||||
async def one(d):
|
||||
creds = credentials(d)
|
||||
if tables_due(d, started):
|
||||
scans[d.id] = await walk(d.address, d.port, creds, tables_for(d.presets or []))
|
||||
found = scans.get(d.id)
|
||||
asked[d.id] = readings_for(d, found.rows if found is not None and found.error is None else None)
|
||||
# The device's own name rides along in the same GET.
|
||||
return await poll(d.address, d.port, creds,
|
||||
[(r.oid, r.key) for r in _asks(asked[d.id])] + [(SYS_NAME, SYS_NAME_KEY)])
|
||||
|
||||
results = await asyncio.gather(*(one(d) for d in devices), return_exceptions=True)
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
polls = []
|
||||
for device, result in zip(devices, results):
|
||||
if isinstance(result, BaseException):
|
||||
logger.warning("SNMP poll of %s failed: %s", device.name, result)
|
||||
polls.append(Polled(now, device.id, device.name, failed=f"SNMP poll failed: {result}"))
|
||||
device.last_error = polls[-1].failed
|
||||
continue
|
||||
sys_name = result.texts.pop(SYS_NAME_KEY, None)
|
||||
if SYS_NAME_KEY in result.missing:
|
||||
result.missing.remove(SYS_NAME_KEY)
|
||||
p = Polled(now, device.id, device.name, error=result.error, scan=scans.get(device.id), sys_name=sys_name,
|
||||
answered=bool(result.readings or result.texts), missing=list(result.missing))
|
||||
if p.scan is not None and p.scan.error is None:
|
||||
# Kept on the copy too, so a stall doesn't walk it again every poll.
|
||||
device.tables, device.tables_at = p.scan.rows, now
|
||||
device.last_error = result.error
|
||||
missing = set(result.missing)
|
||||
|
||||
def read(reading):
|
||||
value = result.readings.get(reading.key)
|
||||
if reading.unit == "state":
|
||||
# Its word is shown as answered; its level is stored,
|
||||
# unless Steward doesn't know the word (level None).
|
||||
raw = value if value is not None else result.texts.get(reading.key)
|
||||
if raw is None:
|
||||
return None
|
||||
p.texts[reading.key], value = state_of(reading, raw)
|
||||
return value
|
||||
if value is None:
|
||||
if reading.key in result.texts: # a word where a number was asked for
|
||||
missing.add(reading.key)
|
||||
return None
|
||||
if reading.counter:
|
||||
return RATES.rate(device.id, reading, value, now)
|
||||
return value * reading.scale + reading.offset
|
||||
|
||||
for reading in asked[device.id]:
|
||||
if reading.inputs:
|
||||
# Every input is read, so each counter keeps its last sample.
|
||||
got = {i.key: read(i) for i in reading.inputs}
|
||||
if any(i.key in missing for i in reading.inputs):
|
||||
missing -= {i.key for i in reading.inputs}
|
||||
missing.add(reading.key)
|
||||
value = None if None in got.values() else reading.combine(got)
|
||||
else:
|
||||
value = read(reading)
|
||||
if value is not None:
|
||||
p.values.append((reading.key, value))
|
||||
p.missing = sorted(missing)
|
||||
polls.append(p)
|
||||
held.hold(polls)
|
||||
await held.flush(STORE_WAIT_S)
|
||||
|
||||
|
||||
# The key the device's sysName is asked under: never a reading's.
|
||||
SYS_NAME_KEY = "_sys_name"
|
||||
|
||||
|
||||
def _asks(readings: list) -> list:
|
||||
"""What the device is asked for: each reading, or the inputs of one
|
||||
worked out from others."""
|
||||
return [i for r in readings for i in (r.inputs or (r,))]
|
||||
|
||||
|
||||
async def _store(app: "Quart", rounds: list[list[Polled]]) -> None:
|
||||
"""Write held polls, oldest first, in one transaction."""
|
||||
from steward.core.alerts import MetricBatch
|
||||
|
||||
from .models import SnmpDevice
|
||||
|
||||
now = datetime.now(timezone.utc)
|
||||
async with app.db_sessionmaker() as session:
|
||||
async with session.begin():
|
||||
batch = MetricBatch()
|
||||
for device, result in zip(devices, results):
|
||||
row = await session.get(SnmpDevice, device.id)
|
||||
if row is None: # deleted while it was being polled
|
||||
continue
|
||||
row.last_polled_at = now
|
||||
if isinstance(result, BaseException):
|
||||
logger.warning("SNMP poll of %s failed: %s", device.name, result)
|
||||
row.last_error = f"SNMP poll failed: {result}"
|
||||
continue
|
||||
row.last_error = result.error
|
||||
row.missing = sorted(set(result.missing))
|
||||
if result.readings:
|
||||
row.last_ok_at = now
|
||||
for reading in asked[device.id]:
|
||||
value = result.readings.get(reading.key)
|
||||
if value is None:
|
||||
for polls in rounds:
|
||||
for p in polls:
|
||||
row = await session.get(SnmpDevice, p.device_id)
|
||||
if row is None: # deleted since it was polled
|
||||
continue
|
||||
if reading.counter:
|
||||
value = RATES.rate(device.id, reading, value, now)
|
||||
if value is None:
|
||||
continue
|
||||
else:
|
||||
value = value * reading.scale + reading.offset
|
||||
batch.add(source_module="snmp", resource_name=device.name,
|
||||
metric_name=reading.key, value=value, recorded_at=now)
|
||||
row.last_polled_at = p.at
|
||||
if p.failed:
|
||||
row.last_error = p.failed
|
||||
continue
|
||||
if p.scan is not None and p.scan.error is None:
|
||||
row.tables, row.tables_at = p.scan.rows, p.at
|
||||
row.last_error = p.error
|
||||
if p.answered:
|
||||
row.last_ok_at = p.at
|
||||
if p.sys_name:
|
||||
row.sys_name = p.sys_name[:255]
|
||||
# A failed poll keeps the words it had; one that answered says them afresh.
|
||||
texts = dict(row.texts or {}) if p.error else {}
|
||||
texts.update(p.texts)
|
||||
row.missing, row.texts = p.missing, texts
|
||||
for key, value in p.values:
|
||||
batch.add(source_module="snmp", resource_name=p.name,
|
||||
metric_name=key, value=value, recorded_at=p.at)
|
||||
await batch.record(session)
|
||||
|
||||
Some files were not shown because too many files have changed in this diff Show More
Reference in New Issue
Block a user