Repository navigation
Expand file tree
/
Copy pathcheck_versions.py
More file actions
executable file
·516 lines (443 loc) · 22.3 KB
/
Copy pathcheck_versions.py
File metadata and controls
executable file
·516 lines (443 loc) · 22.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
#!/usr/bin/env python3
"""Check the OS versions the documents claim against the ones the hosts report.
`check_docs.py` already asserts that `hardware.md` and `network.md` agree with
each other about every host's OS. That assertion passed for a full pfSense
release while both documents said `FreeBSD 15` and `morpheus` ran FreeBSD 16,
because it compares the two copies and both copies were stale together. Its own
`POINT_RELEASE` comment describes the same failure one round earlier, with the
two laptops recorded as 24.04.3 while running 24.04.4.
So this is the other half, and it is deliberately NOT in `check_docs.py`: that
script compares documents to files in the repository and runs in CI, where
there is no route to the stack. This one asks the running system and can only
run where Prometheus is reachable — the monitoring host. It fails on the fact
rather than on the two copies agreeing.
Sources, one per host, all already collected:
* `morpheus` sysDescr over SNMP. pfSense sets it explicitly rather than
taking bsnmpd's default, so it carries both versions:
"pfSense morpheus.matrix.elysium 2.9.0-RELEASE FreeBSD
16.0-CURRENT amd64". This is the host that needed it — it runs
no node_exporter, being the FreeBSD appliance that cannot run
Alloy, so until #292 its OS version had no live counterpart at
all.
* everything `node_os_info`, from the Alloy agents that produce the rest of
else this stack's host metrics.
Comparison is on family and release line, never the full string, because that
is the convention `check_docs.py` enforces in the tables: they record `FreeBSD
16.0`, the box reports `16.0-CURRENT`, and both mean the same release. A point
release in a table is rejected by `check_docs.py` and is not this script's
business.
Usage:
scripts/check_versions.py check every host it can
scripts/check_versions.py --prometheus URL default http://localhost:9090
scripts/check_versions.py --list show what each source reports
"""
from __future__ import annotations
import argparse
import json
import re
import sys
import urllib.error
import urllib.parse
import urllib.request
sys.path.insert(0, str(__import__("pathlib").Path(__file__).resolve().parent))
from check_docs import (
HARDWARE_MD,
NETWORK_MD,
network_sections,
os_key,
strip_md,
tables_under,
)
GREEN, RED, YELLOW, BLUE, BOLD, OFF = (
"\033[0;32m",
"\033[0;31m",
"\033[0;33m",
"\033[0;34m",
"\033[1m",
"\033[0m",
)
def release_line(key: tuple[str, str]) -> tuple[str, str]:
"""('ubuntu', '24.04.4') -> ('ubuntu', '24.04').
The tables record the release line and `check_docs.py` rejects a point
release in them, but the hosts report point releases: `node_os_info` says
"Ubuntu 24.04.4 LTS" where the documents correctly say "Ubuntu 24.04 LTS".
Comparing the full strings would fail on every Linux host the day after any
of them took an update, which is the opposite of useful — the check would
be noise, and noise is what gets a check switched off.
"""
family, version = key
return family, ".".join(version.split(".")[:2])
def pass_(msg: str) -> None:
print(f"{GREEN} PASS{OFF} {msg}")
def fail(msg: str) -> None:
print(f"{RED} FAIL{OFF} {msg}")
def skip(msg: str) -> None:
print(f"{YELLOW} SKIP{OFF} {msg}")
def info(msg: str) -> None:
print(f"{BLUE}--{OFF} {msg}")
# `Saruman` used to be the one host with a live counterpart that could not be
# compared. node_os_info reports "Debian GNU/Linux 13 (trixie)" because that is
# what Proxmox VE 9 is built on, and the documents record the product rather
# than its base — correctly, since "Debian 13" would not tell a reader what the
# box is. node_uname_info's "7.0.14-12-pve" confirms Proxmox but carries the
# KERNEL version, not the product's. So the claim "Proxmox VE 9" had nothing to
# be checked against, which is the condition #292 existed to remove.
#
# scripts/collect-pve-version.sh now writes pve_version_info on the hypervisor
# itself, through the textfile collector the Alloy agent already reads — it
# cannot be pulled, because the monitoring host cannot open TCP/22 to VLAN 30
# (#311). running_versions() picks it up below and Saruman is compared like
# everything else.
#
# The dict stays, empty, because the NEXT host with this shape should be named
# here rather than silently passing. An empty exceptions table is a statement
# that there are currently none.
#
# `smaug` WAS the next host with this shape (#616), and it is not in the dict,
# for the reason #311 gave: an entry here DESCRIBES a gap, and a product with a
# collector can have the self-clearing skip in PRODUCT_SOURCES below, which says
# what to run. TrueNAS SCALE's /etc/os-release is the Debian it is built on —
# "Debian GNU/Linux 12 (bookworm)" against a documented "TrueNAS 25.10" — and
# scripts/collect-truenas-version.sh reads /etc/version instead.
NO_COMPARABLE_SOURCE: dict[str, str] = {}
# Appliance products whose node_os_info is their Debian base, each with the
# metric its own collector writes and what to do when only node_os_info
# reports the host. Keyed on a word in the DOCUMENTED cell, because that is the
# claim being checked: a host the documents call "TrueNAS" is not failed for
# reporting Debian, it is skipped with the instruction until its collector
# answers — and the moment it does, the source changes and it is compared like
# any other host. A table rather than a second hand-written branch, because
# Proxmox's was the first and this is the second.
PRODUCT_SOURCES = (
{
"word": "proxmox",
"product": "Proxmox VE",
"metric": "pve_version_info",
"remedy": "make install-agent-collectors AGENT=root@<host> ARGS='--only pve-version'",
},
{
"word": "truenas",
"product": "TrueNAS",
"metric": "truenas_version_info",
"remedy": "the root cron job in docs/runbooks/build-the-nas.md §6.7",
},
)
def query(prom: str, expr: str) -> list[dict]:
url = f"{prom.rstrip('/')}/api/v1/query?" + urllib.parse.urlencode({"query": expr})
try:
with urllib.request.urlopen(url, timeout=10) as response:
payload = json.load(response)
except (urllib.error.URLError, TimeoutError, json.JSONDecodeError) as exc:
raise SystemExit(
f"{RED}error:{OFF} cannot reach Prometheus at {prom}: {exc}\n"
f" this check reads the running system; it only works where "
f"the stack is."
) from exc
if payload.get("status") != "success":
raise SystemExit(f"{RED}error:{OFF} query failed: {expr}")
return payload["data"]["result"]
def running_versions(prom: str) -> dict[str, tuple[str, str]]:
"""host -> (os string as reported, source name)."""
found: dict[str, tuple[str, str]] = {}
for series in query(prom, "node_os_info"):
metric = series["metric"]
host = metric.get("instance", "")
pretty = metric.get("pretty_name", "")
if host and pretty:
found[host.lower()] = (pretty, "node_os_info")
# Proxmox VE and TrueNAS, which report their product versions through a
# textfile rather than through node_os_info (#311, #616). Taken AFTER
# node_os_info on purpose: both exist for these hosts, and the Debian
# underneath is not the answer the documents record.
for series in query(prom, "pve_version_info"):
metric = series["metric"]
host = metric.get("host") or metric.get("instance", "")
# The RELEASE label, not `version`. Proxmox's release line is a single
# number — the documents say "Proxmox VE 9" and the host reports 9.2.11 —
# so the full version cannot be compared against them. release_line()
# cannot reduce it either: it keeps two components because Ubuntu's line
# is "24.04", and applied here that would leave "9.2" against a
# documented "9" and fail on every point release.
#
# The collector already computes it, so this reads the fact rather than
# re-deriving it. `version` stays on the metric because it is the fact;
# `release` is the claim.
release = metric.get("release", "")
if host and release:
found[host.lower()] = (f"Proxmox VE {release}", "pve_version_info")
# TrueNAS's release line is two components — "TrueNAS 25.10" against a
# running 25.10.7 — which release_line() reduces to on its own, so the
# `release` label is read here for symmetry with the block above rather
# than out of necessity. Written on the NAS by a root cron job into the
# directory node_exporter serves (build-the-nas.md §6.7), so `host` and
# `instance` agree; `host` is still preferred, as above.
for series in query(prom, "truenas_version_info"):
metric = series["metric"]
host = metric.get("host") or metric.get("instance", "")
release = metric.get("release", "")
if host and release:
found[host.lower()] = (f"TrueNAS {release}", "truenas_version_info")
# sysDescr is one string holding two versions. The FreeBSD half is what the
# OS columns record; the pfSense half is checked separately below, against
# the runbook rather than the tables.
for series in query(prom, "sysDescr"):
metric = series["metric"]
host = metric.get("device") or metric.get("instance", "")
descr = metric.get("sysDescr", "")
match = re.search(r"(FreeBSD\s+\S+)", descr)
if host and match:
found[host.lower()] = (match.group(1), "sysDescr")
return found
def documented_versions() -> dict[str, list[tuple[str, str]]]:
"""host -> [(document, cell)], every row that states an OS.
Keyed on the Compute table in `hardware.md`, which is the list of hosts this
estate runs rather than every device that holds a lease. `network.md` also
names eeros, televisions and phones; none of them reports an OS, none is
expected to, and listing twenty-five SKIP lines for them would bury the one
line that matters. A managed host that stops reporting still shows up,
because it stays in the Compute table.
"""
out: dict[str, list[tuple[str, str]]] = {}
tables = tables_under(HARDWARE_MD.read_text(encoding="utf-8"), re.compile(r"^##\s+Compute"))
if not tables:
raise SystemExit(f"{RED}error:{OFF} docs/hardware.md has no Compute table")
for row in tables[0][1:]:
if len(row) >= 6:
out.setdefault(strip_md(row[0]).lower(), []).append(("docs/hardware.md", strip_md(row[5])))
managed = set(out)
# Every row, not the first per host: `morpheus` appears in all seven segment
# tables, and a version edited into only the sixth must not be invisible.
seen: set[tuple[str, str]] = set()
for rows in network_sections(NETWORK_MD.read_text(encoding="utf-8")).values():
for row in rows[1:]:
if len(row) >= 5:
host, cell = strip_md(row[0]).lower(), strip_md(row[4])
if host not in managed:
continue
if cell and cell != "—" and (host, cell) not in seen:
seen.add((host, cell))
out.setdefault(host, []).append(("docs/network.md", cell))
return out
# The Suricata runbook carries the only prose claim about what pfSense version
# the box is on right now — "`morpheus` now runs 2.9.0-RELEASE". It was written
# by the change that fixed the drift this script exists to catch, so it is
# exactly the kind of line that goes stale next.
RUNBOOK = "docs/runbooks/enable-suricata.md"
RUNBOOK_CLAIM = re.compile(r"`morpheus`\s+now\s+runs\s+([0-9][^\s,]*)")
# The claim is about one box, so the series is selected by device rather than by
# being the first that parses. sysDescr is NOT morpheus-only: the ilo module
# walks it too, and `shiva` answers "Integrated Lights-Out 4 2.82 Feb 06 2023" —
# which sorts first in the query result today and is skipped only because 2.82
# has two components rather than three. An iLO firmware numbered 2.82.1, or any
# future device in a module that walks sysDescr, would otherwise have this
# comparing the runbook's pfSense claim against the wrong machine, and reporting
# it under morpheus's name.
PFSENSE_DEVICE = "morpheus"
PFSENSE_VERSION = re.compile(r"\b(\d+\.\d+\.\d+-\S+)")
# ---------------------------------------------------------------------------
# Devices with a checkable version that are NOT in hardware.md's Compute table
# ---------------------------------------------------------------------------
#
# That table is the list of hosts this estate runs, and `shiva` is correctly not
# in it: it is the iLO BMC on the same physical box as `Saruman`, not a host.
# But it is the only device outside the table with both halves of a checkable
# claim — a live `sysDescr` and a documented version — so the only thing making
# it unchecked was a scoping line (#309).
#
# A TABLE RATHER THAN A THIRD BESPOKE FUNCTION. `morpheus` already needs its own
# extraction, because pfSense packs two versions into one string; this is the
# second, and writing it as another hand-rolled comparison is how a script grows
# a fourth. Each row says where the running value comes from, how to get a
# version out of both sides, and what to call it.
#
# WHY THE GENERIC PARSER CANNOT DO THIS. os_key() takes the first word as the
# family and the first number as the version:
#
# 'Integrated Lights-Out 4 2.82 Feb 06 2023' -> ('integrated', '4')
# 'iLO 2.82' -> ('ilo', '2.82')
#
# Both halves disagree, and the running side is wrong in the way that matters:
# the 4 is the iLO GENERATION and 2.82 is the firmware. A naive comparison would
# fail every run, and a check that fails every run gets switched off — which is
# the argument this script already makes about point releases.
#
# `neo` was not here while it was the MokerLink: its sysDescr was the literal
# string "Switch" with a trailing NUL (#309, #310), so there was nothing to
# compare. The CRS326 that replaced it on 2026-11-05 (#444) reports its
# RouterOS release, measured 2026-11-07:
#
# 'RouterOS CRS326-24G-2S+ 7.24.6 (long-term)' -> 7
#
# so it has a row. The model is matched as one token and discarded. Only the
# major release is compared, because network.md's OS column records the
# release line, not the point release (check_docs.py holds it to that): a
# point update must not fail this, and a move to RouterOS 8 must.
OUT_OF_BAND = (
{
"device": "shiva",
"label": "iLO firmware",
# "Integrated Lights-Out 4 2.82 Feb 06 2023" -> 2.82. The generation is
# matched and discarded deliberately: anchoring on it is what stops the
# pattern latching onto the 4 when the firmware is absent.
"running": re.compile(r"Integrated Lights-Out\s+\d+\s+(\d+\.\d+)"),
# network.md:273 gives shiva the OS cell "iLO 2.82".
"documented": re.compile(r"^iLO\s+(\d+\.\d+(?:\.\d+)*)$"),
},
{
"device": "neo",
"label": "RouterOS release",
"running": re.compile(r"^RouterOS\s+\S+\s+(\d+)\."),
# network.md gives neo the OS cell "RouterOS 7".
"documented": re.compile(r"^RouterOS\s+(\d+)$"),
},
)
def documented_cells(device: str) -> list[tuple[str, str]]:
"""(document, cell) for one device's OS column in network.md.
documented_versions() above deliberately filters to the Compute table, so it
cannot answer for a device that is not a host. This asks the same question
without that filter, for the handful of devices OUT_OF_BAND names.
"""
found: list[tuple[str, str]] = []
seen: set[str] = set()
for rows in network_sections(NETWORK_MD.read_text(encoding="utf-8")).values():
for row in rows[1:]:
if len(row) >= 5 and strip_md(row[0]).lower() == device:
cell = strip_md(row[4])
if cell and cell != "—" and cell not in seen:
seen.add(cell)
found.append(("docs/network.md", cell))
return found
def check_out_of_band_versions(prom: str, failures: list[str]) -> None:
"""Compare each OUT_OF_BAND device's documented version against sysDescr."""
reported = {
(entry["metric"].get("device") or entry["metric"].get("instance") or "").lower(): entry["metric"].get(
"sysDescr", ""
)
for entry in query(prom, "sysDescr")
}
for row in OUT_OF_BAND:
device, label = row["device"], row["label"]
descr = reported.get(device)
if descr is None:
# Not "everything agrees". Nothing is being collected, which is a
# collection fault wearing a clean bill of health — the distinction
# this script makes for morpheus too.
skip(f"{label} — nothing reports sysDescr for {device}")
continue
match = row["running"].search(descr)
if match is None:
fail(f"{label} — {device} reports sysDescr {descr!r}, which carries no version this can read")
failures.append(f"sysDescr:{device}")
continue
running = match.group(1)
cells = documented_cells(device)
if not cells:
skip(f"{label} — no document states a version for {device}")
continue
for document, cell in cells:
claim = row["documented"].match(cell)
if claim is None:
fail(f"{document} gives {device} the OS {cell!r}, which this cannot read as an {label}")
failures.append(f"{document}:{device}")
elif claim.group(1) == running:
pass_(f"{document} says {device} runs {cell!r}; sysDescr agrees")
else:
fail(f"{document} says {device} runs {cell!r}; sysDescr reports {running}")
failures.append(f"{document}:{device}")
def check_runbook_pfsense_version(prom: str, failures: list[str]) -> None:
descr = None
for entry in query(prom, "sysDescr"):
metric = entry["metric"]
device = (metric.get("device") or metric.get("instance") or "").lower()
if device == PFSENSE_DEVICE:
descr = metric.get("sysDescr", "")
break
if descr is None:
skip(f"pfSense version — nothing reports sysDescr for {PFSENSE_DEVICE}")
return
match = PFSENSE_VERSION.search(descr)
if match is None:
fail(f"pfSense version — {PFSENSE_DEVICE} reports sysDescr {descr!r}, which carries no version this can read")
failures.append(f"sysDescr:{PFSENSE_DEVICE}")
return
running = match.group(1)
path = HARDWARE_MD.parent.parent / RUNBOOK
claim = RUNBOOK_CLAIM.search(path.read_text(encoding="utf-8"))
if claim is None:
skip(f"pfSense version — {RUNBOOK} makes no claim about it")
return
if claim.group(1) == running:
pass_(f"{RUNBOOK} says morpheus runs {running}; it does")
else:
fail(f"{RUNBOOK} says morpheus runs {claim.group(1)}; sysDescr says {running}")
failures.append(RUNBOOK)
def main() -> int:
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("--prometheus", default="http://localhost:9090")
parser.add_argument("--list", action="store_true", help="print what each source reports")
args = parser.parse_args()
running = running_versions(args.prometheus)
if args.list:
info("what the hosts report")
for host, (value, source) in sorted(running.items()):
print(f" {host:<12} {value:<34} ({source})")
return 0
documented = documented_versions()
failures: list[str] = []
print(f"\n{BOLD}OS versions, documents against the running hosts{OFF}")
for host in sorted(documented):
if host in NO_COMPARABLE_SOURCE:
skip(f"{host} — {NO_COMPARABLE_SOURCE[host]}")
continue
if host not in running:
skip(f"{host} — nothing reports an OS for it")
continue
# An appliance host whose only source is node_os_info is not a
# disagreement, it is a collector that has not been installed yet.
# node_os_info reports the Debian underneath — "Debian GNU/Linux 13"
# against a documented "Proxmox VE 9", "Debian GNU/Linux 12" against
# "TrueNAS 25.10" — and failing on that would make this check red for a
# known, listed reason until somebody is at the right console, which is
# how a check stops being read. #616 was exactly that: two FAILs every
# week and ScheduledJobFailed firing for three days, over a NAS that
# runs precisely what the documents say.
#
# SELF-CLEARING on purpose: the moment the product's metric exists the
# source changes and the comparison happens like any other host. This
# says what to run rather than describing a gap (#311).
product = next(
(p for p in PRODUCT_SOURCES if any(p["word"] in cell.lower() for _, cell in documented[host])),
None,
)
if product is not None and running[host][1] == "node_os_info":
skip(
f"{host} — documented as {product['product']} and only "
f"node_os_info reports it, which is the Debian underneath. "
f"{product['metric']} is what compares it; install the "
f"collector:\n {product['remedy']}"
)
continue
value, source = running[host]
want = release_line(os_key(value))
for document, cell in documented[host]:
if release_line(os_key(cell)) == want:
pass_(f"{document} says {host} runs {cell!r}; {source} agrees")
else:
fail(f"{document} says {host} runs {cell!r}; {source} reports {value!r}")
failures.append(f"{document}:{host}")
print(f"\n{BOLD}Devices outside the Compute table{OFF}")
check_out_of_band_versions(args.prometheus, failures)
print(f"\n{BOLD}The one version claim in prose{OFF}")
check_runbook_pfsense_version(args.prometheus, failures)
print()
sys.stdout.flush()
if failures:
print(
f"{RED}{len(failures)} document(s) disagree with the running system{OFF}",
file=sys.stderr,
)
return 1
print(f"{GREEN}versions OK — every documented OS matches the host{OFF}")
return 0
if __name__ == "__main__":
sys.exit(main())