diff --git a/Makefile b/Makefile index b13e0161..893d1024 100644 --- a/Makefile +++ b/Makefile @@ -543,6 +543,14 @@ recipient-state: ## Record which age recipients can open the secrets, and when e @# is what sets a proof. ./scripts/key-recipients.sh --record --stack $(STACK) +.PHONY: workflow-state +workflow-state: ## Record whether GitHub still runs the scheduled workflows, and the audit token's expiry + @# Asks GitHub's public API, anonymously, for each scheduled workflow's state + @# and newest finished scheduled run, and writes github-workflows.prom into + @# the textfile dir. ScheduledWorkflowStale, ScheduledWorkflowDisabled and + @# AuditTokenExpiringSoon read it. ARGS=--stdout prints instead of writing. + ./scripts/collect-workflow-state.py $(ARGS) + .PHONY: ca-key-state ca-key-state: ## Record the estate CA key's fingerprint and when a copy of it was last proved (#496) @# The CA-key twin of recipient-state. Reads the PUBLIC certificate, hashes diff --git a/README.md b/README.md index c9b3bb2c..d5ac7c9e 100644 --- a/README.md +++ b/README.md @@ -101,7 +101,7 @@ documents for different readers. can't run an agent (firewall, switch, UPS, iLO). One agent config, deployed identically everywhere. [How](docs/architecture.md#observability-data-flow) - **Dashboards and alerting as code.** 8 provisioned dashboards, 156 panels, and - 215 alert rules — 187 metric-based in Prometheus, 28 log-based in Loki — sharing + 218 alert rules — 190 metric-based in Prometheus, 28 log-based in Loki — sharing one Alertmanager routing tree. No dashboard exists only in a database. - **Secrets encrypted in-repo with SOPS + age.** Per-device credentials, decrypted at deploy time into gitignored paths, with `git log` showing which @@ -207,7 +207,7 @@ inbound passes may still reach it. Data flow and the maintained Mermaid topology . ├── stacks/ │ ├── observability/ # the estate's stack on prometheus — ten services -│ │ ├── prometheus/ # config, file_sd targets, 187 alert rules +│ │ ├── prometheus/ # config, file_sd targets, 190 alert rules │ │ ├── alertmanager/ # routing and inhibition │ │ ├── loki/ # single-binary config + 28 LogQL rules │ │ ├── alloy/ # the agent config directory, shipped to every host diff --git a/docs/changelog.md b/docs/changelog.md index e8716e58..cc0e0dd7 100644 --- a/docs/changelog.md +++ b/docs/changelog.md @@ -28,6 +28,23 @@ docstring gives: it is a record, not a claim about now. service is named in its stack's README, and the alert counts, scrape jobs, dashboards, Alertmanager receivers and the ports and paths that runbooks name in `stacks/` all matched. Ledger: `docs/audit/FINDINGS.md`. + +- **The scheduled GitHub workflows have a heartbeat.** cve-scan, digests, the + weekly audit, wiki-watch and Scorecard run only on GitHub's schedule. + GitHub stops a public repository's schedules after 60 days without + activity and tells nobody. A new daily job, `workflow-state` + (`scripts/collect-workflow-state.py`), records each workflow's state and + newest finished scheduled run from the public API. Three warnings read it: + `ScheduledWorkflowStale`, `ScheduledWorkflowDisabled`, and + `AuditTokenExpiringSoon`, which fires 30 days before the audit's one-year + `CLAUDE_CODE_OAUTH_TOKEN` lapses. The issue date in the script is + 2026-11-26, the day the audit was added (#1773). The clock is "last run", + not "last success": the first live read found `digests` had failed on each + of the four Mondays since 2026-11-02. Each failure was reported, and none + of them means the schedule stopped. 190 Prometheus rules now, 218 in all. + [`schedule-maintenance.md`](runbooks/schedule-maintenance.md#the-workflows-github-runs-and-the-audits-token) + has the rotation steps. + - **Weekly docs audit, week 2026-48, stacks (second pass).** Three current-state documents still called MakeMKV undeployed after the 2026-11-28 entry recorded it deployed and its `Allow 5800 to smaug` pass created: diff --git a/docs/observability.md b/docs/observability.md index 295b1978..1ee03a89 100644 --- a/docs/observability.md +++ b/docs/observability.md @@ -352,7 +352,7 @@ separates a quiet stream from a stopped one. ## Alerting -215 rules in total: 187 metric-based in `prometheus/rules/`, and 28 log-based in +218 rules in total: 190 metric-based in `prometheus/rules/`, and 28 log-based in `loki/rules/`. ### Log-based (Loki ruler) @@ -551,7 +551,7 @@ argument and for what to do when it exits 1. ### Metric-based (Prometheus) -187 rules across 13 files in `prometheus/rules/`: +190 rules across 13 files in `prometheus/rules/`: | File | Covers | | --- | --- | @@ -563,7 +563,7 @@ argument and for what to do when it exits 1. | `watchdog.rules.yaml` | One rule that always fires, so that its absence is detectable | | `blackbox.rules.yaml` | Whether an endpoint can actually be reached, from outside the service, and how many days its certificate has left — the sensitive tier's seven-day ACME leaves excepted, which an hours pair watches for a stalled renewal instead — `TlsAcmeRenewalLate` at 48h, `TlsAcmeRenewalStalled` at 36h ([#426](https://github.com/Gerrrt/HomeLab/issues/426)) — Grafana and the wiki verified against the lab CA ([#847](https://github.com/Gerrrt/HomeLab/issues/847)), the APC card's verified against the same CA since 2026-11-24, Prometheus, Loki and Alertmanager over plain http (the switch UI's probes were removed on 2026-09-06, `targets/blackbox.yaml`), each of the household sites behind `trinity`'s Caddy, verified against the tier's root, paging as `SiteDown` after ten minutes so a `make up` restart does not ([#855](https://github.com/Gerrrt/HomeLab/issues/855)), and — the other way round — that the ingest proxy on `10.0.99.20:9090` and `:3100` still refuses a request with no token (`IngestAuthNotEnforced`, [#182](https://github.com/Gerrrt/HomeLab/issues/182)). `EeroUnreachable` is a warning for an eero unit that has not answered ping for five minutes, from the `blackbox-eero` job, through one Winterfell pass in force since 2026-11-11 ([#1228](https://github.com/Gerrrt/HomeLab/issues/1228), [ADR-0112](adr/0112-probe-the-eeros-by-icmp-from-prometheus.md)). The iLO and pfSense UIs are written into `targets/blackbox.yaml` and left disabled: each needs a firewall pass from `10.0.99.20` that is a segmentation decision, not a monitoring one ([#91](https://github.com/Gerrrt/HomeLab/issues/91)). Their certificates' expiry is watched without that pass, from `host.rules.yaml` ([#857](https://github.com/Gerrrt/HomeLab/issues/857)) | | `dns.rules.yaml` | Whether the house is still filtering DNS, asked directly at AdGuard Home on port 53 rather than through pfSense. Since [ADR-0055](adr/0055-forward-to-adguard-alone.md) AdGuard is the only forwarder, so `AdGuardNotAnswering` is **critical** at five minutes: the house cannot resolve outside names. `AdGuardNotFiltering` stays a warning, because a filter that fails open is a convenience lost, not an outage. The targets in `targets/blackbox-dns.yaml` are live since 2026-09-28, against AdGuard on `trinity` ([#126](https://github.com/Gerrrt/HomeLab/issues/126), [#404](https://github.com/Gerrrt/HomeLab/issues/404)) | -| `backup.rules.yaml` | Whether the scheduled maintenance jobs are still being run at all — staleness, failure, never-ran, and the page: `ScheduledJobStaleCritical` at three of a job's own periods and never under a day, because the warning reaches only the in-house channel and a backup that stopped in week one was otherwise a notification repeating on the same network for as long as nobody acted (2026-10-14) — whether the CA key's offline copy has been proved lately ([#496](https://github.com/Gerrrt/HomeLab/issues/496)), and whether the newest backup sets have been carried onto the offsite drive within ninety days ([ADR-0048](adr/0048-carry-the-estates-backup-sets-with-the-second-recipient.md), [ADR-0132](adr/0132-carry-the-offsite-copy-on-the-spare-drive.md)) | +| `backup.rules.yaml` | Whether the scheduled maintenance jobs are still being run at all — staleness, failure, never-ran, and the page: `ScheduledJobStaleCritical` at three of a job's own periods and never under a day, because the warning reaches only the in-house channel and a backup that stopped in week one was otherwise a notification repeating on the same network for as long as nobody acted (2026-10-14) — whether the CA key's offline copy has been proved lately ([#496](https://github.com/Gerrrt/HomeLab/issues/496)), and whether the newest backup sets have been carried onto the offsite drive within ninety days ([ADR-0048](adr/0048-carry-the-estates-backup-sets-with-the-second-recipient.md), [ADR-0132](adr/0132-carry-the-offsite-copy-on-the-spare-drive.md)). Also whether GitHub still runs the five scheduled workflows, which no timer here runs: `ScheduledWorkflowStale` when no scheduled run has finished in nine days, `ScheduledWorkflowDisabled` when GitHub has turned a schedule off, and `AuditTokenExpiringSoon` 30 days before the weekly audit's one-year Claude token lapses, all from `scripts/collect-workflow-state.py` | | `deploy.rules.yaml` | Whether each host that pulls — `prometheus` and `trinity` ([#533](https://github.com/Gerrrt/HomeLab/issues/533)) — is running what the repository says: an uncommitted edit made on the host, a revision that did not verify, and how far behind `main` it is, and a host whose record stopped arriving. Reads the record `scripts/converge.sh` writes hourly ([#99](https://github.com/Gerrrt/HomeLab/issues/99), [ADR-0021](adr/0021-converge-on-a-timer-instead-of-deploying-over-ssh.md)). Also whether convergence had to start a stack service that something stopped — `DeployServiceRevived` — and whether one has been left stopped for two hours, held or under a backup — `DeployServicesStopped` ([ADR-0087](adr/0087-start-a-stopped-stack-service-from-the-converge-timer.md)) | | `internet.rules.yaml` | Why the internet is slow ([#914](https://github.com/Gerrrt/HomeLab/issues/914)): three scheduled speed tests in a row under 400 Mbit/s down or 100 up, the WAN held above 85% of what it can carry, frames arriving corrupted on the WAN port — `WanReceiveErrors`, the fault found the day these were written, when a cable between the XB7 and `morpheus` cut downloads to ~2 Mbit/s — and `speedtest-tracker` itself going quiet or unreachable. Also records `homelab_wan_bits_per_second` from pf's own em0 counters. Download thresholds are against the ~940 Mbit/s the 1000baseT WAN port can carry, not the plan's 2000. `speedtest-tracker` is left out of `InstanceDown`, so its outage is a warning and not a page | | `range.rules.yaml` | The range host `gandalf`'s own controls, now that it stays on ([ADR-0126](adr/0126-monitor-gandalf-now-that-it-stays-on.md), [#1651](https://github.com/Gerrrt/HomeLab/issues/1651)): the `vmbr1_host_in` ingress barrier, `vmbr0` forwarding and `sshd` forwarding being off (`build-the-playground.md` §2, §4), and the attack-VM stop timer (ADR-0125) — read by `scripts/collect-range-state.sh`. `PveFirewallZeroRules` is here too: the firewall collector exports the rule count but no other rule reads it | @@ -588,7 +588,7 @@ as loaded and healthy and could not fire for any input ([#63](https://github.com `prometheus/tests/*.test.yaml` holds `promtool test rules` unit tests, which feed a rule synthetic series and assert it fires — paired with a case asserting it stays quiet, because a test that only ever expects silence would have passed -against the broken rule too. Coverage is 187 rules of 187 so far ([#843](https://github.com/Gerrrt/HomeLab/issues/843)) — all twelve +against the broken rule too. Coverage is 190 rules of 190 so far ([#843](https://github.com/Gerrrt/HomeLab/issues/843)) — all twelve in `blackbox.rules.yaml`, all three in `dns.rules.yaml`, all seven in `range.rules.yaml`, `GatewayFilesystemCritical`, `ContainerHighMemory`, `ContainerNearMemoryLimit`, `ContainerRestartLoop`, `ContainerCpuThrottled`, the three container-state rules from diff --git a/docs/runbooks/deploy-stack.md b/docs/runbooks/deploy-stack.md index b9950d8a..32d80f18 100644 --- a/docs/runbooks/deploy-stack.md +++ b/docs/runbooks/deploy-stack.md @@ -151,7 +151,7 @@ Then in the UI: 1. **Prometheus → Status → Targets.** Every job `UP`. The four `snmp` targets take up to 45 seconds on their first scrape. 2. **Prometheus → Status → Rules.** Every rule loaded, none in error. The - page lists 193: the 187 alert rules this repository counts everywhere + page lists 196: the 190 alert rules this repository counts everywhere else, plus the six recording rules: `homelab_suricata_expected_interface`, `homelab_battery_runtime_seconds`, and the two directions each of diff --git a/docs/runbooks/schedule-maintenance.md b/docs/runbooks/schedule-maintenance.md index ad8d1501..d26115a0 100644 --- a/docs/runbooks/schedule-maintenance.md +++ b/docs/runbooks/schedule-maintenance.md @@ -119,6 +119,7 @@ the host. | `gateway-state` | `make gateway-state` | every 15 minutes | 90 minutes | | `silence-state` | `make silence-state` | every 15 minutes | 90 minutes | | `prune-images` | `make prune-images` | Mondays 04:00 | 14 days | +| `workflow-state` | `make workflow-state` | daily 10:00 | 2 days | | `verify-ca-key-backup` | **you**, `make certs-verify-backup KEY=…` | no timer | 90 days | | `offsite-copy` | **you**, `make backup-offsite DEST=…` | no timer | 90 days | | `neo`'s HTTPS leaf | **you**, `make certs ARGS="--host neo.matrix.elysium --ip 10.7.7.2 --force"`, then import it on the switch | no timer; once, before **2029-01-06** | **nothing alerts** | @@ -724,6 +725,31 @@ it. Both checks then apply to it, with nothing else to change. --- +### The workflows GitHub runs, and the audit's token + +Five workflows run on GitHub's schedule rather than on a timer here: +`cve-scan`, `digests`, `weekly-audit`, `wiki-watch` and `scorecard`. A failed +run is its own notification, because GitHub emails it. A schedule that has +stopped firing sends nothing, and GitHub stops a public repository's schedules +after 60 days with no activity. `workflow-state` asks the public API every day +for each workflow's state and its newest finished scheduled run, whatever the +conclusion. `digests` fails on purpose when it finds drift, so "last success" +would be the wrong clock. The job writes `github-workflows.prom`. A new +scheduled workflow must be added to `WORKFLOWS` in +`scripts/collect-workflow-state.py`, and its self-test fails until it is. + +The same job carries the expiry of `CLAUDE_CODE_OAUTH_TOKEN`, which the weekly +audit uses. `claude setup-token` issues it for one year, and +`AuditTokenExpiringSoon` fires 30 days before it lapses. To rotate it: + +1. On a machine signed in to Claude, run `claude setup-token`. +2. `gh secret set CLAUDE_CODE_OAUTH_TOKEN` and paste the token. Do not put it + in a file or a commit. +3. In a PR, change `CLAUDE_OAUTH_TOKEN_ISSUED` in + `scripts/collect-workflow-state.py` to today's date. The alert clears the + day after converge brings that commit here. +4. `gh workflow run weekly-audit.yml` proves the new token. + ## Install ```bash @@ -945,6 +971,9 @@ expected rather than a second fault. | `ScheduledJobStaleCritical` | A job has gone three of its own periods without a success — one and a half of the allowance in the `JOBS` table, which is twice the period; a weekly backup three weeks stale, a nightly one three nights, and never under a day for the hourly collectors — and the `ScheduledJobStale` warning for it has been repeating on the in-house channel unanswered | The same first look as the warning: `systemctl list-timers 'homelab-*'`, then `journalctl -u homelab-.service`. The rows below name the usual cause per job. The page holds the warning back while it is up, so a job that recovers clears both at once | | `OffsiteCopyStale` | Ninety days since the newest sets were last copied to the offsite drive, the spare `HOUSEHOLD` drive ([ADR-0132](../adr/0132-carry-the-offsite-copy-on-the-spare-drive.md)), and proved there | Bring it back, mount it and run `make backup-offsite DEST=…` — [`copy-the-backups-offsite.md`](copy-the-backups-offsite.md). `--list`, `--verify-only` and `--prune` do not clear it, on purpose | | `CaKeyBackupUnproven` | No offline copy of `certificates/ca-key.pem` has been proved in ninety days — or ever, or not since the CA was re-minted, which the fingerprint label tells apart | Mount the medium and `make certs-verify-backup KEY=…` ([`back-up-the-ca-key.md`](back-up-the-ca-key.md)). After a re-mint, copy the new key there first; the old copy is refused | +| `ScheduledWorkflowDisabled` | GitHub stopped a workflow's schedule after 60 days with no repository activity, or someone turned it off | `gh workflow enable `. Nothing ran in the gap, so run it once by hand too: `gh workflow run ` | +| `ScheduledWorkflowStale` | The workflow is enabled but no scheduled run has finished in nine days | Open its page under Actions. A run stuck *queued* is a GitHub Actions incident; no runs at all means the `cron:` line has changed or gone. A failing run does not cause this alert | +| `AuditTokenExpiringSoon` | `CLAUDE_CODE_OAUTH_TOKEN` is within 30 days of its one-year expiry, or past it | Rotate it as [The workflows GitHub runs, and the audit's token](#the-workflows-github-runs-and-the-audits-token) says. The alert clears only once the date in `collect-workflow-state.py` changes | | `ScheduledJobMetricsAbsent` | Nothing from the textfile directory has reached Prometheus in six hours | This is the whole directory, not one file — check Alloy is up and the directory still exists. A single malformed file shows as `node_textfile_scrape_error 1` and costs only that file | | One job's series missing, `node_textfile_scrape_error` is 1 | That job's `.prom` failed to parse — a truncated write, or something wrote it without the temp-then-rename | The other files are unaffected. Re-run the job; if it recurs, something is writing the file directly instead of through `run-scheduled.sh` | | Every `homelab_job_*` series missing, no scrape error | The `textfile` block in `config.alloy` is not reading the right path | It must carry the `ALLOY_ROOTFS` prefix (`/rootfs` in the container). `rootfs_path` does **not** apply to that argument, and a wrong path reports an empty directory rather than an error | diff --git a/docs/security.md b/docs/security.md index 5f94ff0b..c982bb9f 100644 --- a/docs/security.md +++ b/docs/security.md @@ -36,7 +36,7 @@ What this network is actually built to survive: | Someone on Winterfell or Hicks logging in to `prometheus` | **Key-only `sshd` since 2026-11-23; no host firewall by decision.** `prometheus` holds the estate's CA key and the age key that opens every volume backup set, and converge runs as the operator, who is in `sudo` and `docker`. Its `sshd` answers all of Hicks (by `morpheus`'s pass for `22` to the segment) and every host on VLAN 99. The audit's root-only reads on 2026-11-23 found it taking passwords, with X11 forwarding on and `ufw` inactive. [ADR-0128](adr/0128-give-prometheus-a-key-only-sshd-and-no-host-firewall.md) makes `sshd` key-only through a drop-in that outranks cloud-init's, refusing root and X11 forwarding ([`restore-the-stack.md`](runbooks/restore-the-stack.md#make-sshd-key-only)). It adds no host firewall, because Docker's rules run ahead of `ufw`'s for the published ports, so a policy would cover `22` alone. Those ports stay fenced as before: by `morpheus` by destination, by the ingest proxy's tokens on `9090` and `3100`, and on `6514` by the syslog listener's pinned client certificate and its sender list. The step was applied the same day. `sshd -T` read `no` for all four settings, a password login and a keyboard-interactive login were each refused with `Permission denied (publickey)`, and a key login from Hicks succeeded after the reload. | | Someone on Hicks or Winterfell logging in to `smaug` | **Key-only `sshd` since 2026-11-24.** `smaug` holds the household's media and the `erebor` pool. Two hosts reach its `22`, each by a host-scoped pass on `morpheus` ([`network.md`](network.md)): `prometheus`, as the read-only backup user `frodo`, and `desktop-02` on Hicks, as the administrator `gerrrt`. From 2026-11-13 `gerrrt` logged in by password, allowed both on the user and in the SSH service's *Password Login Groups*, while the documents said `frodo` was the only user. Both settings were cleared in the TrueNAS UI on 2026-11-24. `sshd_config` then had no `Match` block left, and a connection as `gerrrt` or `root` was offered `publickey` alone. `gerrrt` is kept by [ADR-0138](adr/0138-keep-gerrrt-as-smaugs-administrator-account.md): `FULL_ADMIN` and sudo for all commands, with the password asked every time, and a checkout of this repository that can neither push nor decrypt. Its key and its password together are root on `smaug`; that is the residual. [ADR-0139](adr/0139-keep-the-mcp-servers-api-key-on-smaug.md) keeps `ClaudeCode2`, an API key on `truenas_admin` with no expiry, which the TrueNAS MCP server on the operator's Windows desktop uses. The key alone is `FULL_ADMIN` over the API. The UI allowlist is meant to limit it to Hicks, which has not been tested from CasaBonita. | | Someone with the trusted Wi-Fi key quietly joining | Kea's lease log reaches Loki; `UnknownDeviceOnTrustedSegment` fires the first time a MAC appears on VLAN 50 in seven days ([ADR-0019](adr/0019-read-device-joins-from-the-dhcp-server.md)) | -| Losing visibility of a failure | 215 alert rules, 30 days of metrics and logs | +| Losing visibility of a failure | 218 alert rules, 30 days of metrics and logs | | Someone on a reachable VLAN silencing an alert to hide a failure | Alertmanager binds to `127.0.0.1`; silences go through authenticated Grafana | | Mains power loss | **The rack, yes; the monitoring path, yes — on two laptop cells that were measured for the first time on 2026-09-12.** A pack fitted to `mjolnir` on 2026-08-28 passed its self-test; the TP-Link carrying `prometheus` and `oracle` has been on UPS power since 2026-09-08 ([#110](https://github.com/Gerrrt/HomeLab/issues/110)); the laptops ride a cut out on their own batteries, which `HostBatteryHealthLow` in `host.rules.yaml` now reads — `prometheus`'s cell was replaced on 2026-09-18 and reads 101 % of design, `oracle`'s was replaced on 2026-09-29 and reads 100 %, its design figure rather than a learned one ([#531](https://github.com/Gerrrt/HomeLab/issues/531)) — and **each runtime was measured once: `prometheus`'s on 2026-09-19, about 2.5 hours from full at the stack's load, and `oracle`'s on 2026-09-29, about 5.2 hours**; since the same day the projection is recorded on every cut and pages under thirty minutes (`HostBatteryRuntimeLow`, [#532](https://github.com/Gerrrt/HomeLab/issues/532)), but neither pack reports a moving cell temperature, so this row is answered for both hosts' runtime and for neither's cell temperature — see below. **What happens when the cut outlasts the pack is configured and accepted without a live test.** Since 2026-09-23 the firewall's NUT server reads `mjolnir`, and `Saruman` and `smaug` subscribe to it on their own gateway addresses, so a real cut would now try to run the sequence [ADR-0049](adr/0049-shut-down-on-the-ups-from-a-nut-server-on-the-firewall.md) decides: `Saruman` and `smaug` halt first and `morpheus` last. Since the move into the 32U rack on 2026-11-06 the PDU also carries `trinity`, `gandalf` (off until its build) and the console, with `smaug` racked and on the PDU directly rather than by its old long cord to the media room. [ADR-0107](adr/0107-subscribe-trinity-to-the-ups-and-bound-saruman-s-guest-stop.md) makes `trinity` a third subscriber and bounds `Saruman`'s guest stop. `Saruman`'s half was applied on 2026-11-13 (`down=90` on the four ordered guests, and its monitor stays logged in until they are down); `trinity`'s subscription, `HOSTSYNC 600` on `morpheus` and the card's 16-minute threshold followed on 2026-11-20, so all three subscribers would now halt before the pack empties; `gandalf`, the console and `neo` are left to the pack by decision. The pack itself is unmeasured: about 47 minutes at 21 % load is the card's own estimate. Neither the forced-shutdown proof nor a mains pull will be run ([ADR-0121](adr/0121-accept-the-ups-shutdown-without-a-live-test.md)) | | The estate being down while the person who runs it is unavailable | **Documentation, yes; data, no copy outside the house, by decision.** ADR-0011 puts the emergency tier on paper; [ADR-0023](adr/0023-keep-the-household-recovery-path-outside-the-estate.md) extends the same reasoning to the sensitive tier's data. That tier has held real photographs since 2026-09-28. [ADR-0122](adr/0122-drop-the-household-copy.md) dropped their copy outside the estate, so a loss of the house loses them — see below | diff --git a/scripts/collect-workflow-state.py b/scripts/collect-workflow-state.py new file mode 100755 index 00000000..6b8d1fea --- /dev/null +++ b/scripts/collect-workflow-state.py @@ -0,0 +1,354 @@ +#!/usr/bin/env python3 +"""Record whether GitHub is still running this repository's scheduled workflows. + +WHY THIS EXISTS + +Four workflows run only on a schedule: cve-scan, digests, the weekly docs +audit and wiki-watch, and the Scorecard workflow too once it lands. Each one's +failure is its notification: GitHub emails a failed run. A schedule that has +stopped firing sends nothing at all, and that silence looks exactly like a +quiet week. GitHub stops a public repository's schedules silently after 60 +days without activity (digests.yml says so in its header), and a schedule can +also be turned off by hand and forgotten. + +So this measures whether each schedule still FIRES, not whether it passes. The +newest completed scheduled run counts, whatever its conclusion. digests.yml +fails on purpose whenever it finds drift, and on 2026-11-29 it had failed four +Mondays running; a "last success" clock would page on it forever and say +nothing GitHub's own failure emails had not. + +The weekly audit has a second clock: CLAUDE_CODE_OAUTH_TOKEN comes from +`claude setup-token`, which issues a token valid for one year. Nothing warned +before it lapsed, and the audit would just start failing on the Monday after. + +This collector turns both into series that Prometheus can alert on, the way +run-scheduled.sh does for the timers on this host. ScheduledWorkflowStale, +ScheduledWorkflowDisabled and AuditTokenExpiringSoon in backup.rules.yaml +read them. + +WHAT IT ASKS + +For each workflow in WORKFLOWS, two anonymous calls to GitHub's public REST +API: + /actions/workflows/ its state + /actions/workflows//runs?event=schedule&status=completed&per_page=1 + its newest finished scheduled run +The repository is public, so no token is needed, and the job makes about ten +calls a day against an anonymous limit of 60 an hour. GITHUB_TOKEN is used if +set, as check-ruleset.sh uses it, and is sent as a header, never in an +argument. + +A workflow that has never had a scheduled run is counted from the day the +workflow was created, not from 0. A newly added workflow is not stale before +its first Monday, but one whose schedule never fires still ages out. + +WHERE THE OUTPUT GOES + +/github-workflows.prom, written to a temp file in the same +directory and renamed, for the reason run-scheduled.sh gives. The file is not +named workflow-state.prom: run-scheduled.sh writes .prom for the timer's +job, workflow-state, and a collector sharing that name is the #360 failure. +On any API error the script exits 1 and leaves the previous file in place, +so the wrapper records a failure and ScheduledJobStale ages it out. + +THE TOKEN DATE + +CLAUDE_OAUTH_TOKEN_ISSUED is the day the secret was last set. It is not a +secret. `gh secret list` shows it in its "updated" column. When you rotate the +token (`claude setup-token`, then `gh secret set CLAUDE_CODE_OAUTH_TOKEN`), +change the date here in the same PR. docs/runbooks/schedule-maintenance.md has +the steps. + +Usage: + scripts/collect-workflow-state.py collect and write the .prom + scripts/collect-workflow-state.py --stdout collect and print, write nothing + scripts/collect-workflow-state.py --self-test run the fixtures + +Environment: + TEXTFILE_DIR where the .prom goes (default /var/lib/node_exporter/textfile_collector) + GITHUB_TOKEN optional; lifts the anonymous rate limit +""" + +from __future__ import annotations + +import datetime as dt +import json +import os +import re +import sys +import tempfile +import urllib.error +import urllib.request +from pathlib import Path + +REPO = "Gerrrt/HomeLab" +API = "https://api.github.com" +OUTPUT = "github-workflows.prom" + +DAY = 86400 +# Nine days for a weekly schedule, a little over the period. A slip of a few +# hours does not fire it, but a second missed Monday does. GitHub delays +# scheduled runs under load, sometimes by an hour or more. +WEEKLY = 9 * DAY + +# Every workflow in .github/workflows that has a `schedule:` trigger must be +# listed here. The self-test reads the directory and fails if one is missing, +# so a new scheduled workflow cannot go unwatched. An entry whose file does +# not exist yet (GitHub answers 404) is skipped with a warning. +WORKFLOWS: dict[str, int] = { + "cve-scan.yml": WEEKLY, + "digests.yml": WEEKLY, + "scorecard.yml": WEEKLY, + "weekly-audit.yml": WEEKLY, + "wiki-watch.yml": WEEKLY, +} + +# The day CLAUDE_CODE_OAUTH_TOKEN was last set (see THE TOKEN DATE above). +# 2026-11-26 is the day the weekly audit was added (#1773). +CLAUDE_OAUTH_TOKEN_ISSUED = "2026-11-26" +TOKEN_LIFETIME_DAYS = 365 + +REPO_ROOT = Path(__file__).resolve().parent.parent + + +class ApiError(Exception): + pass + + +class NotFound(ApiError): + pass + + +def fetch(path: str) -> dict: + req = urllib.request.Request( + API + path, + headers={ + "Accept": "application/vnd.github+json", + "X-GitHub-Api-Version": "2022-11-28", + "User-Agent": "homelab-collect-workflow-state", + }, + ) + token = os.environ.get("GITHUB_TOKEN") + if token: + req.add_header("Authorization", f"Bearer {token}") + try: + with urllib.request.urlopen(req, timeout=20) as resp: + return json.load(resp) + except urllib.error.HTTPError as exc: + if exc.code == 404: + raise NotFound(path) from exc + raise ApiError(f"{path}: HTTP {exc.code}") from exc + except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc: + raise ApiError(f"{path}: {exc}") from exc + + +def parse_time(stamp: str) -> int: + """GitHub's ISO 8601 UTC stamp ('2026-11-23T06:41:02Z') as Unix seconds.""" + return int(dt.datetime.fromisoformat(stamp).timestamp()) + + +def token_expiry(issued: str, days: int = TOKEN_LIFETIME_DAYS) -> int: + day = dt.date.fromisoformat(issued) + start = dt.datetime(day.year, day.month, day.day, tzinfo=dt.UTC) + return int((start + dt.timedelta(days=days)).timestamp()) + + +def workflow_state(name: str, get=fetch) -> tuple[int, int] | None: + """(active 0/1, last scheduled run Unix time) for one workflow, or None if absent.""" + try: + wf = get(f"/repos/{REPO}/actions/workflows/{name}") + except NotFound: + return None + active = 1 if wf.get("state") == "active" else 0 + runs = ( + get(f"/repos/{REPO}/actions/workflows/{name}/runs?event=schedule&status=completed&per_page=1").get( + "workflow_runs" + ) + or [] + ) + if runs: + last = parse_time(runs[0]["updated_at"]) + else: + last = parse_time(wf["created_at"]) + return active, last + + +def render(states: dict[str, tuple[int, int]], ages: dict[str, int], expiry: int) -> str: + lines = [ + "# HELP homelab_workflow_active 1 when GitHub reports the workflow's state as active.", + "# TYPE homelab_workflow_active gauge", + ] + lines += [f'homelab_workflow_active{{workflow="{n}"}} {a}' for n, (a, _) in sorted(states.items())] + lines += [ + ( + "# HELP homelab_workflow_last_run_timestamp_seconds Unix time the newest finished" + " scheduled run, whatever its conclusion, or of the workflow's creation if it has none." + ), + "# TYPE homelab_workflow_last_run_timestamp_seconds gauge", + ] + lines += [ + f'homelab_workflow_last_run_timestamp_seconds{{workflow="{n}"}} {t}' for n, (_, t) in sorted(states.items()) + ] + lines += [ + "# HELP homelab_workflow_max_age_seconds How old the newest finished scheduled run may be.", + "# TYPE homelab_workflow_max_age_seconds gauge", + ] + lines += [f'homelab_workflow_max_age_seconds{{workflow="{n}"}} {ages[n]}' for n in sorted(states)] + lines += [ + ( + "# HELP homelab_audit_token_expiry_timestamp_seconds Unix time the weekly audit's" + " Claude OAuth token stops working." + ), + "# TYPE homelab_audit_token_expiry_timestamp_seconds gauge", + f'homelab_audit_token_expiry_timestamp_seconds{{secret="CLAUDE_CODE_OAUTH_TOKEN"}} {expiry}', + ] + return "\n".join(lines) + "\n" + + +def collect(get=fetch) -> str: + states: dict[str, tuple[int, int]] = {} + for name in WORKFLOWS: + got = workflow_state(name, get) + if got is None: + print(f"warning: {name} is declared but GitHub has no such workflow; skipped", file=sys.stderr) + continue + states[name] = got + return render(states, WORKFLOWS, token_expiry(CLAUDE_OAUTH_TOKEN_ISSUED)) + + +def write_atomically(directory: Path, text: str) -> Path: + target = directory / OUTPUT + # Same directory, so the rename is atomic, and a name that does not end in + # .prom, so the collector never parses the half-written temp. + fd, tmp = tempfile.mkstemp(dir=directory, prefix=f".{OUTPUT}.", suffix=".tmp") + try: + with os.fdopen(fd, "w", encoding="utf-8") as fh: + fh.write(text) + os.chmod(tmp, 0o644) + os.replace(tmp, target) + except BaseException: + Path(tmp).unlink(missing_ok=True) + raise + return target + + +SCHEDULE = re.compile(r"^\s*schedule\s*:", re.MULTILINE) + + +def scheduled_workflows(root: Path = REPO_ROOT) -> set[str]: + wf_dir = root / ".github" / "workflows" + return {p.name for p in sorted(wf_dir.glob("*.y*ml")) if SCHEDULE.search(p.read_text(encoding="utf-8"))} + + +def self_test() -> int: + failed = 0 + + def check(label: str, got, expected) -> None: + nonlocal failed + if got == expected: + print(f"\033[0;32m PASS\033[0m {label}") + else: + print(f"\033[0;31m FAIL\033[0m {label}\n got {got!r}\n expected {expected!r}") + failed = 1 + + def fake(answers: dict[str, object]): + def get(path: str) -> dict: + for key, value in answers.items(): + if key in path: + if isinstance(value, Exception): + raise value + return value # type: ignore[return-value] + raise NotFound(path) + + return get + + created = {"state": "active", "created_at": "2026-11-01T00:00:00Z"} + green = {"workflow_runs": [{"updated_at": "2026-11-23T06:41:02Z"}]} + + got = workflow_state("a.yml", fake({"runs?": green, "workflows/a.yml": created})) + check("an active workflow with a finished run", got, (1, parse_time("2026-11-23T06:41:02Z"))) + + disabled = dict(created, state="disabled_inactivity") + got = workflow_state("a.yml", fake({"runs?": green, "workflows/a.yml": disabled})) + check("disabled_inactivity is not active", got[0] if got else None, 0) + + manual = dict(created, state="disabled_manually") + got = workflow_state("a.yml", fake({"runs?": green, "workflows/a.yml": manual})) + check("disabled_manually is not active", got[0] if got else None, 0) + + got = workflow_state("a.yml", fake({"runs?": {"workflow_runs": []}, "workflows/a.yml": created})) + check("no scheduled run yet counts from creation", got, (1, parse_time("2026-11-01T00:00:00Z"))) + + got = workflow_state("gone.yml", fake({})) + check("a workflow GitHub does not have is skipped", got, None) + + try: + workflow_state("a.yml", fake({"workflows/a.yml": ApiError("HTTP 403")})) + check("an API error is raised, not swallowed", "no error", "ApiError") + except NotFound: + check("an API error is raised, not swallowed", "NotFound", "ApiError") + except ApiError: + check("an API error is raised, not swallowed", "ApiError", "ApiError") + + check( + "the token expires a year after it was set", + token_expiry("2026-11-26"), + int(dt.datetime(2027, 11, 26, tzinfo=dt.UTC).timestamp()), + ) + try: + token_expiry("2026-13-01") + check("a malformed token date is refused", "accepted", "ValueError") + except ValueError: + check("a malformed token date is refused", "ValueError", "ValueError") + check("the declared token date parses", isinstance(token_expiry(CLAUDE_OAUTH_TOKEN_ISSUED), int), True) + + text = render({"b.yml": (0, 20), "a.yml": (1, 10)}, {"a.yml": 5, "b.yml": 6}, 99) + check( + "one active sample per workflow, sorted", + [ln for ln in text.splitlines() if ln.startswith("homelab_workflow_active")], + ['homelab_workflow_active{workflow="a.yml"} 1', 'homelab_workflow_active{workflow="b.yml"} 0'], + ) + check("the label is workflow, never job (run-scheduled.sh says why)", "job=" in text, False) + check( + "the expiry sample is present", + 'homelab_audit_token_expiry_timestamp_seconds{secret="CLAUDE_CODE_OAUTH_TOKEN"} 99' in text, + True, + ) + + with tempfile.TemporaryDirectory() as d: + path = write_atomically(Path(d), "x 1\n") + mode = "0o644" if os.name == "nt" else oct(path.stat().st_mode & 0o777) + check("the file lands under its own name, 0644", (path.name, mode), (OUTPUT, "0o644")) + check("no temp file is left behind", sorted(p.name for p in Path(d).iterdir()), [OUTPUT]) + + undeclared = sorted(scheduled_workflows() - set(WORKFLOWS)) + check("every scheduled workflow in .github/workflows is declared in WORKFLOWS", undeclared, []) + + return failed + + +def main(argv: list[str]) -> int: + if "--self-test" in argv: + return self_test() + if any(a in ("-h", "--help") for a in argv): + print(__doc__) + return 0 + try: + text = collect() + except ApiError as exc: + print(f"error: {exc}; the previous {OUTPUT} is left as it was", file=sys.stderr) + return 1 + if "--stdout" in argv: + sys.stdout.write(text) + return 0 + directory = Path(os.environ.get("TEXTFILE_DIR", "/var/lib/node_exporter/textfile_collector")) + if not directory.is_dir(): + print(f"error: no textfile directory at {directory}", file=sys.stderr) + return 1 + target = write_atomically(directory, text) + print(f"-- wrote {target}") + return 0 + + +if __name__ == "__main__": + sys.exit(main(sys.argv[1:])) diff --git a/scripts/install-timers.sh b/scripts/install-timers.sh index fbb5dd16..ac92c31a 100755 --- a/scripts/install-timers.sh +++ b/scripts/install-timers.sh @@ -154,6 +154,7 @@ JOBS=( "silence-state homelab-silence-state 5400 silence-state" "port-state homelab-port-state 5400 port-state" "prune-images homelab-prune-images 1209600 prune-images" + "workflow-state homelab-workflow-state 172800 workflow-state" "verify-ca-key-backup - 7776000 certs-verify-backup" "offsite-copy - 7776000 backup-offsite" ) diff --git a/stacks/observability/README.md b/stacks/observability/README.md index e4ad3161..2a3b54b6 100644 --- a/stacks/observability/README.md +++ b/stacks/observability/README.md @@ -67,7 +67,7 @@ prometheus/ targets/snmp.yaml SNMP targets — hot-reloaded, no restart needed targets/node.yaml node_exporter scrapes, for the host that runs no Alloy (smaug) targets/blackbox*.yaml probe targets, http, dns and latency — hot-reloaded, no restart - rules/*.rules.yaml 187 alert rules: host, network, ups, containers, blackbox, + rules/*.rules.yaml 190 alert rules: host, network, ups, containers, blackbox, dns, backup, ids, deploy, stack, internet, watchdog and range tests/*.test.yaml promtool unit tests — assert the rules can fire blackbox/blackbox.yaml probe modules — reachability, and what a resolver said diff --git a/stacks/observability/prometheus/rules/backup.rules.yaml b/stacks/observability/prometheus/rules/backup.rules.yaml index 14d55e43..ae1d006d 100644 --- a/stacks/observability/prometheus/rules/backup.rules.yaml +++ b/stacks/observability/prometheus/rules/backup.rules.yaml @@ -330,3 +330,83 @@ groups: `make backup-offsite DEST=`; it re-verifies what is there, copies the newest of each kind and proves the copy: docs/runbooks/copy-the-backups-offsite.md. + + - alert: ScheduledWorkflowStale + # The GitHub half of ScheduledJobStale. cve-scan, digests, the weekly + # docs audit, wiki-watch and Scorecard run only on a schedule, on + # GitHub's runners, and a schedule that stops firing sends nothing: + # no failed run, so no email. scripts/collect-workflow-state.py + # records each one's newest FINISHED scheduled run, whatever its + # conclusion. A failing run is its own notification, and digests.yml + # fails on purpose whenever it finds drift, so a "last success" clock + # would fire on it every week (the collector's header has the date). + # + # Disabled workflows are left to ScheduledWorkflowDisabled, which + # names the cause and the one-line fix, so the two do not both fire + # for the same workflow. + # + # The labels are `workflow`, not `job`, for the reason run-scheduled.sh + # gives for `homelab_job`. + expr: | + ((time() - homelab_workflow_last_run_timestamp_seconds) + > on(workflow, instance) group_left() homelab_workflow_max_age_seconds) + and on(workflow, instance) homelab_workflow_active == 1 + for: 1h + labels: + component: backup + severity: warning + category: correctness + annotations: + summary: "GitHub has not run {{ $labels.workflow }} on its schedule in {{ $value | humanizeDuration }}" + description: >- + The workflow is enabled but no scheduled run has finished inside + its window. Check + https://github.com/Gerrrt/HomeLab/actions/workflows/{{ $labels.workflow }}: + a run stuck queued, a cron line edited away, or a GitHub Actions + outage — docs/runbooks/schedule-maintenance.md. + + - alert: ScheduledWorkflowDisabled + # GitHub disables a public repository's scheduled workflows after 60 + # days with no activity, and says so to nobody (digests.yml's header). + # The state is also `disabled_manually` after someone turns one off + # from the Actions tab and forgets. Either way the schedule has + # stopped and nothing else here can see it. + expr: homelab_workflow_active == 0 + for: 1h + labels: + component: backup + severity: warning + category: correctness + annotations: + summary: "GitHub has disabled the scheduled workflow {{ $labels.workflow }}" + description: >- + Its schedule no longer fires. If the repository went 60 days + without activity GitHub did this by itself; otherwise someone + turned it off. Re-enable it with + `gh workflow enable {{ $labels.workflow }}` — + docs/runbooks/schedule-maintenance.md. + + - alert: AuditTokenExpiringSoon + # CLAUDE_CODE_OAUTH_TOKEN comes from `claude setup-token`, which + # issues a token for one year. When it lapses the weekly docs audit + # fails on its next Monday and every Monday after. The expiry is + # computed from the date declared in collect-workflow-state.py, so + # rotating the token means changing that date in the same PR; until + # then this keeps firing, which is the reminder. + # + # Thirty days ahead, and it stays firing past the date. A warning and + # not a page: nothing in the estate breaks, one weekly report stops. + expr: | + homelab_audit_token_expiry_timestamp_seconds < time() + 30 * 86400 + for: 1h + labels: + component: backup + severity: warning + category: correctness + annotations: + summary: "The weekly audit's {{ $labels.secret }} expires {{ $value | humanizeTimestamp }}" + description: >- + Run `claude setup-token`, set the result with + `gh secret set CLAUDE_CODE_OAUTH_TOKEN`, then change + CLAUDE_OAUTH_TOKEN_ISSUED in scripts/collect-workflow-state.py to + today — docs/runbooks/schedule-maintenance.md. diff --git a/stacks/observability/prometheus/tests/workflow-state.test.yaml b/stacks/observability/prometheus/tests/workflow-state.test.yaml new file mode 100644 index 00000000..0ee31131 --- /dev/null +++ b/stacks/observability/prometheus/tests/workflow-state.test.yaml @@ -0,0 +1,135 @@ +--- +# Unit tests for the three GitHub-workflow rules in backup.rules.yaml: +# ScheduledWorkflowStale, ScheduledWorkflowDisabled and AuditTokenExpiringSoon, +# fed the series scripts/collect-workflow-state.py writes. +# +# Every firing case is paired with a quiet one, per backup.test.yaml. Two +# cases guard specific mistakes: +# +# 1. THE JOIN. Two workflows with different windows sit in one series set, +# one over its window and one under. A rule that compared against a +# constant, or ignored on(workflow), would fire for both or neither. +# +# 2. NO DOUBLE FIRE. A disabled workflow is also stale. It must reach +# ScheduledWorkflowDisabled, which names the fix, and not +# ScheduledWorkflowStale as well. +# +# time() here is seconds since the start of the test, so the windows below are +# minutes and hours, not days. +rule_files: + - ../rules/backup.rules.yaml + +evaluation_interval: 1m + +tests: + - interval: 1m + input_series: + - series: 'homelab_workflow_last_run_timestamp_seconds{workflow="wf-stale.yml", instance="prometheus"}' + values: "0+0x300" + - series: 'homelab_workflow_last_run_timestamp_seconds{workflow="wf-fresh.yml", instance="prometheus"}' + values: "0+0x300" + - series: 'homelab_workflow_last_run_timestamp_seconds{workflow="wf-off.yml", instance="prometheus"}' + values: "0+0x300" + - series: 'homelab_workflow_max_age_seconds{workflow="wf-stale.yml", instance="prometheus"}' + values: "3600+0x300" + - series: 'homelab_workflow_max_age_seconds{workflow="wf-fresh.yml", instance="prometheus"}' + values: "100000+0x300" + - series: 'homelab_workflow_max_age_seconds{workflow="wf-off.yml", instance="prometheus"}' + values: "3600+0x300" + - series: 'homelab_workflow_active{workflow="wf-stale.yml", instance="prometheus"}' + values: "1+0x300" + - series: 'homelab_workflow_active{workflow="wf-fresh.yml", instance="prometheus"}' + values: "1+0x300" + - series: 'homelab_workflow_active{workflow="wf-off.yml", instance="prometheus"}' + values: "0+0x300" + # Expires at 30 days plus two hours, so it enters the 30-day window at + # t=2h and fires an hour later. + - series: 'homelab_audit_token_expiry_timestamp_seconds{secret="CLAUDE_CODE_OAUTH_TOKEN", instance="prometheus"}' + values: "2599200+0x300" + alert_rule_test: + # --- ScheduledWorkflowStale ------------------------------------------ + # Inside every window at 30m. + - eval_time: 30m + alertname: ScheduledWorkflowStale + exp_alerts: [] + + # Over wf-stale's window from 1h, pending until 2h: asserts the `for`. + - eval_time: 1h50m + alertname: ScheduledWorkflowStale + exp_alerts: [] + + # Only wf-stale. wf-fresh is inside its window (the join), and wf-off is + # over its window but disabled (no double fire). + - eval_time: 2h30m + alertname: ScheduledWorkflowStale + exp_alerts: + - exp_labels: + alertname: ScheduledWorkflowStale + workflow: wf-stale.yml + instance: prometheus + component: backup + severity: warning + category: correctness + exp_annotations: + summary: "GitHub has not run wf-stale.yml on its schedule in 2h 30m 0s" + description: >- + The workflow is enabled but no scheduled run has finished inside + its window. Check + https://github.com/Gerrrt/HomeLab/actions/workflows/wf-stale.yml: + a run stuck queued, a cron line edited away, or a GitHub Actions + outage — docs/runbooks/schedule-maintenance.md. + + # --- ScheduledWorkflowDisabled --------------------------------------- + # Pending for its first hour. + - eval_time: 50m + alertname: ScheduledWorkflowDisabled + exp_alerts: [] + + # Only wf-off; the two active workflows stay quiet. + - eval_time: 1h30m + alertname: ScheduledWorkflowDisabled + exp_alerts: + - exp_labels: + alertname: ScheduledWorkflowDisabled + workflow: wf-off.yml + instance: prometheus + component: backup + severity: warning + category: correctness + exp_annotations: + summary: "GitHub has disabled the scheduled workflow wf-off.yml" + description: >- + Its schedule no longer fires. If the repository went 60 days + without activity GitHub did this by itself; otherwise someone + turned it off. Re-enable it with + `gh workflow enable wf-off.yml` — + docs/runbooks/schedule-maintenance.md. + + # --- AuditTokenExpiringSoon ------------------------------------------ + # More than 30 days left until t=2h. + - eval_time: 1h + alertname: AuditTokenExpiringSoon + exp_alerts: [] + + # Inside the window from 2h, pending until 3h. + - eval_time: 2h30m + alertname: AuditTokenExpiringSoon + exp_alerts: [] + + - eval_time: 4h + alertname: AuditTokenExpiringSoon + exp_alerts: + - exp_labels: + alertname: AuditTokenExpiringSoon + secret: CLAUDE_CODE_OAUTH_TOKEN + instance: prometheus + component: backup + severity: warning + category: correctness + exp_annotations: + summary: "The weekly audit's CLAUDE_CODE_OAUTH_TOKEN expires 1970-01-31 02:00:00 +0000 UTC" + description: >- + Run `claude setup-token`, set the result with + `gh secret set CLAUDE_CODE_OAUTH_TOKEN`, then change + CLAUDE_OAUTH_TOKEN_ISSUED in scripts/collect-workflow-state.py to + today — docs/runbooks/schedule-maintenance.md. diff --git a/systemd/homelab-workflow-state.service b/systemd/homelab-workflow-state.service new file mode 100644 index 00000000..302cbedd --- /dev/null +++ b/systemd/homelab-workflow-state.service @@ -0,0 +1,44 @@ +# Daily check that GitHub is still running this repository's scheduled +# workflows, and how long the weekly audit's Claude token has left. +# +# cve-scan, digests, the weekly docs audit, wiki-watch and Scorecard run on +# GitHub's runners, not here, so nothing on this host ran them and nothing on +# this host noticed when a schedule stopped. GitHub disables a public +# repository's schedules after 60 days with no activity and tells nobody. +# scripts/collect-workflow-state.py asks the public API for each workflow's +# state and newest finished scheduled run, and writes github-workflows.prom; +# ScheduledWorkflowStale, ScheduledWorkflowDisabled and AuditTokenExpiringSoon +# read it. +# +# Needs the network (api.github.com, anonymously) and no secret, no lock and +# no docker. GITHUB_TOKEN in /etc/default/homelab-timers is used if present, +# but the anonymous limit is far above the ten calls this makes a day. +# +# See homelab-backup-volumes.service for why each directive below is set. +[Unit] +Description=HomeLab: check GitHub is still running the scheduled workflows +Documentation=file:///home/robo/code/Gerrrt/HomeLab/docs/runbooks/schedule-maintenance.md +Wants=network-online.target +After=network-online.target + +[Service] +Type=oneshot +User=robo +Group=robo +WorkingDirectory=/home/robo/code/Gerrrt/HomeLab +Environment=STACK=observability +EnvironmentFile=-/etc/default/homelab-timers +ExecStart=/home/robo/code/Gerrrt/HomeLab/scripts/run-scheduled.sh --job workflow-state -- /usr/bin/make -C /home/robo/code/Gerrrt/HomeLab workflow-state +TimeoutStartSec=120 +Restart=no +Nice=10 +ProtectHome=false +ProtectSystem=false +PrivateTmp=true +NoNewPrivileges=true +RestrictSUIDSGID=true +LockPersonality=true +RestrictRealtime=true +StandardOutput=journal +StandardError=journal +SyslogIdentifier=homelab-workflow-state diff --git a/systemd/homelab-workflow-state.timer b/systemd/homelab-workflow-state.timer new file mode 100644 index 00000000..c7db1fe9 --- /dev/null +++ b/systemd/homelab-workflow-state.timer @@ -0,0 +1,15 @@ +[Unit] +Description=HomeLab: daily scheduled-workflow and audit-token check +Documentation=file:///home/robo/code/Gerrrt/HomeLab/docs/runbooks/schedule-maintenance.md + +[Timer] +Unit=homelab-workflow-state.service +# 10:00 daily, after the morning collectors. Daily, though every workflow it +# watches is weekly: a disabled schedule is then seen within a day, not a week. +OnCalendar=*-*-* 10:00:00 +RandomizedDelaySec=900 +Persistent=true +AccuracySec=1m + +[Install] +WantedBy=timers.target