Skip to content

Commit beed949

Browse files
committed
/homelab: the host's CPU temperature, with an optional alert
1 parent d4d28f4 commit beed949

10 files changed

Lines changed: 388 additions & 11 deletions

File tree

‎.env.example‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,6 +56,10 @@ AUTHORIZED_USER_IDS=your-telegram-user-id
5656
# BACKUP_DIR=/srv/backups
5757
# Hours without a completed backup before /homelab warns. Default: 26
5858
# BACKUP_MAX_AGE_HOURS=26
59+
# Alert when the host's CPU reaches this temperature, in whole °C from 40 to
60+
# 110. /homelab shows the temperature either way, if the host has a sensor.
61+
# Unset: no temperature alert.
62+
# HOMELAB_TEMP_ALERT_C=85
5963
# Where /homelab asks Docker for its containers: unix:///<socket> or
6064
# tcp://<host>:<port>. Default: unix:///var/run/docker.sock
6165
# DOCKER_HOST=unix:///run/docker-proxy/docker.sock

‎CHANGELOG.md‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,8 @@ The first versioned release.
2020
- Homelab health in `/homelab`: disks, failed services, Docker containers,
2121
updates, pending reboots and backups, with alerts when something goes wrong
2222
and when it clears.
23+
- The host's CPU temperature in `/homelab`, from its thermal zones or CPU
24+
sensor, with an optional alert (`HOMELAB_TEMP_ALERT_C`).
2325
- Internet outages: noticed, timed and reported when the connection is back.
2426
- A daily summary and a weekly report, sent at times you choose.
2527
- Logs in the chat: recent lines, or everything as a file.

‎README.md‎

Lines changed: 12 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,9 @@ in 8s"), not just that it sent a command. It also watches the server itself.
4848
- **Timers**: shut down at 22:30, wake in 8 hours; with a warning before a shutdown.
4949
- **Several machines**: Windows, and Linux and macOS (**experimental**), picked
5050
by name or with a button.
51-
- **Homelab health**: disks, failed services, Docker containers, updates, pending
52-
reboots and backups, with alerts when something goes wrong and when it clears.
51+
- **Homelab health**: disks, temperature, failed services, Docker containers,
52+
updates, pending reboots and backups, with alerts when something goes wrong and
53+
when it clears.
5354
- **Internet outages**: noticed, timed and reported when the connection is back.
5455
- **A daily summary and a weekly report**, sent at times you choose.
5556
- **Logs in the chat**: recent lines, or everything as a file.
@@ -247,6 +248,7 @@ exit code 2 and a list of the variable names, never their values.
247248
| `HOMELAB_DISKS` | `/` | Disks `/homelab` watches; paths other than `/` must stay mounted. |
248249
| `BACKUP_DIR` | off | Where your backup job writes its snapshot folders. |
249250
| `BACKUP_MAX_AGE_HOURS` | `26` | Hours without a completed backup before a warning. |
251+
| `HOMELAB_TEMP_ALERT_C` | off | Alert when the host's CPU reaches this many °C (40 to 110). |
250252
| `DOCKER_HOST` | `unix:///var/run/docker.sock` | Docker's API for the container list (`unix://` or `tcp://`). |
251253
| `INTERNET_CHECK_TARGETS` | `1.1.1.1:443,9.9.9.9:443` | Where the internet check connects (1 to 5). |
252254
| `CANDYGOOGY_IN_CONTAINER` | `0` | `1` in a container (the image sets it): host-only checks are skipped. |
@@ -268,7 +270,7 @@ exit code 2 and a list of the variable names, never their values.
268270
| `/schedule_shutdown [when]` | Power off later: `45m`, `2h`, `1h30m`, `22:30`. Asks when if no time is given. |
269271
| `/schedule_wake [when]` | Power on later: `8h`, `06:45`. Asks when if no time is given. |
270272
| `/timers` | Pending timers, with Cancel (and +30m for a shutdown). |
271-
| `/homelab` | The bot's host: uptime, load, RAM, disks, services, containers, updates, backups. |
273+
| `/homelab` | The bot's host: uptime, load, temperature, RAM, disks, services, containers, updates, backups. |
272274
| `/net` | Internet outages in the last 7 days. |
273275
| `/summary` | The daily summary, now. |
274276
| `/week` | The weekly report, now. |
@@ -324,14 +326,15 @@ as missed, not run late.
324326
<details>
325327
<summary><b>Homelab health and alerts</b></summary>
326328

327-
`/homelab` reads `/proc`, the disks in `HOMELAB_DISKS`, failed systemd units,
328-
Docker's container list (`GET /containers/json` on its API), `apt list
329-
--upgradable`, `/run/reboot-required` and the backups folder; it changes
330-
nothing. It warns when a disk has under 10% free, when a disk other than `/`
329+
`/homelab` reads `/proc`, the CPU temperature in `/sys`, the disks in
330+
`HOMELAB_DISKS`, failed systemd units, Docker's container list (`GET
331+
/containers/json` on its API), `apt list --upgradable`, `/run/reboot-required`
332+
and the backups folder; it changes nothing. It warns when a disk has under 10% free, when a disk other than `/`
331333
isn't mounted, when a service has failed, when a container is stopped,
332334
restarting or unhealthy, when a reboot is required, and when no backup has
333-
completed for `BACKUP_MAX_AGE_HOURS`. Waiting updates are listed but aren't a
334-
problem on their own.
335+
completed for `BACKUP_MAX_AGE_HOURS`. With `HOMELAB_TEMP_ALERT_C` set, it also
336+
warns when the CPU reaches that temperature; the alert clears once it is 5 °C
337+
below. Waiting updates are listed but aren't a problem on their own.
335338

336339
Every 10 minutes the bot checks the same things and sends one message when a
337340
problem appears and one ("back to normal") when it clears. Something that can't

‎candygoogy/config.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -52,6 +52,8 @@
5252
# The host's / as mounted in a container (e.g. /host), for disks and
5353
# /run/reboot-required; None: this process's own /.
5454
HOMELAB_HOST_ROOT = SETTINGS.homelab_host_root
55+
# /homelab alerts when the host's CPU reaches this many °C; None: never.
56+
HOMELAB_TEMP_ALERT_C = SETTINGS.homelab_temp_alert_c
5557
# Docker Engine's API, which /homelab asks for the containers: "unix:///<path>"
5658
# or "tcp://<host>:<port>".
5759
DOCKER_HOST = SETTINGS.docker_host

‎candygoogy/homelab.py‎

Lines changed: 75 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@
2121
BACKUP_MAX_AGE_HOURS,
2222
HOMELAB_DISKS,
2323
HOMELAB_HOST_ROOT,
24+
HOMELAB_TEMP_ALERT_C,
2425
IN_CONTAINER,
2526
REPO_DIR,
2627
STATE_DIR,
@@ -54,6 +55,24 @@
5455
# e.g. /host. Disks, mount checks and RUN are read under it; /proc needs no
5556
# prefix, since uptime, load and memory are the host's anyway.
5657
HOST_ROOT = HOMELAB_HOST_ROOT
58+
# Temperature sensors, read from this process's own /sys and never under
59+
# HOST_ROOT: sysfs is a mount of its own, so a bind mount of the host's / usually
60+
# doesn't contain it, while Docker mounts the host's sysfs read-only into the
61+
# container without masking class/thermal or class/hwmon.
62+
SYS = Path("/sys")
63+
# hwmon drivers for the CPU's (or SoC's) temperature, read only when no thermal
64+
# zone has a reading (e.g. AMD's k10temp); others (nvme, iwlwifi, ...) never are.
65+
CPU_HWMON_DRIVERS = frozenset({"coretemp", "k10temp", "zenpower", "cpu_thermal", "soc_thermal"})
66+
# Above this a reading is junk; at or below 0 °C it's a sensor's "no value"
67+
# (some zones say -273200).
68+
MAX_PLAUSIBLE_C = 150
69+
# HOMELAB_TEMP_ALERT_C: alert at or above it (None: never). An open alert clears
70+
# only TEMP_HYSTERESIS_C below it, so a reading hovering there doesn't alert and
71+
# clear every check.
72+
TEMP_ALERT_C = HOMELAB_TEMP_ALERT_C
73+
TEMP_HYSTERESIS_C = 5
74+
# Sensor labels come from sysfs; longer ones are cut.
75+
MAX_SENSOR_LABEL_CHARS = 40
5776

5877

5978
def on_host(path: str) -> str:
@@ -90,6 +109,7 @@ class Health:
90109
containers: list[Container] | None = None # None if Docker couldn't be asked
91110
updates: list[str] | None = None # upgradable packages; None if apt couldn't be asked
92111
reboot: list[str] | None = None # packages waiting for a reboot; None if none is
112+
temperature: tuple[str, float] | None = None # (sensor label, °C); None: no sensor
93113
# Programs that aren't installed ("systemctl", "apt"), or "docker" if
94114
# nothing answers at DOCKER_HOST: their reading is None, and the card says
95115
# so instead of "Couldn't check".
@@ -135,6 +155,42 @@ def read_memory() -> tuple[float, float] | None:
135155
return fields["MemTotal"] - fields["MemAvailable"], fields["MemTotal"]
136156

137157

158+
def read_sys(path: Path) -> str | None:
159+
"""A sysfs file's text; None if unreadable (some zones answer EINVAL)."""
160+
try:
161+
return path.read_text().strip()
162+
except (OSError, UnicodeDecodeError):
163+
return None
164+
165+
166+
def celsius(millidegrees: str | None) -> float | None:
167+
"""A sensor's millidegrees as °C, or None if it isn't a plausible reading."""
168+
if millidegrees is None or not is_number(millidegrees) or len(millidegrees) > 9:
169+
return None # also "-273200": is_number() takes digits only
170+
value = int(millidegrees) / 1000
171+
return value if 0 < value <= MAX_PLAUSIBLE_C else None
172+
173+
174+
def read_temperature() -> tuple[str, float] | None:
175+
"""The hottest plausible CPU temperature as (sensor label, °C): from the
176+
thermal zones, else from the CPU's hwmon driver. None if there's no sensor."""
177+
readings: list[tuple[str, float]] = []
178+
for zone in sorted((SYS / "class" / "thermal").glob("thermal_zone*")):
179+
if (value := celsius(read_sys(zone / "temp"))) is not None:
180+
readings.append((read_sys(zone / "type") or zone.name, value))
181+
if not readings:
182+
for hwmon in sorted((SYS / "class" / "hwmon").glob("hwmon*")):
183+
if (name := read_sys(hwmon / "name")) not in CPU_HWMON_DRIVERS:
184+
continue
185+
for sensor in sorted(hwmon.glob("temp*_input")):
186+
if (value := celsius(read_sys(sensor))) is not None:
187+
readings.append((name, value))
188+
if not readings:
189+
return None
190+
label, value = max(readings, key=lambda reading: reading[1])
191+
return label[:MAX_SENSOR_LABEL_CHARS], value
192+
193+
138194
def disk_space(path: str) -> tuple[float, float] | None:
139195
try:
140196
usage = shutil.disk_usage(path)
@@ -288,6 +344,7 @@ async def read_health() -> Health:
288344
containers=docker,
289345
updates=updates,
290346
reboot=reboot,
347+
temperature=read_temperature(),
291348
missing=frozenset(missing),
292349
in_container=IN_CONTAINER,
293350
host_root=HOST_ROOT is not None,
@@ -359,6 +416,16 @@ def problems(health: Health, now: float) -> tuple[dict[str, Problem], set[str]]:
359416
if health.reboot
360417
else "An update installed since the last boot needs it.",
361418
)
419+
if TEMP_ALERT_C is None or health.temperature is None:
420+
unknown.add("temp") # no alert set, or no sensor: an open alert stays as it is
421+
else:
422+
label, value = health.temperature
423+
if value >= TEMP_ALERT_C:
424+
found["temp"] = Problem(
425+
"Running hot", f"{escape(label)} at {value:.0f} °C (alert at {TEMP_ALERT_C} °C)."
426+
)
427+
elif value >= TEMP_ALERT_C - TEMP_HYSTERESIS_C:
428+
unknown.add("temp") # just below the alert: neither opens nor clears one
362429
b = health.backups
363430
if b is None: # backup monitoring is off
364431
unknown.add("backup")
@@ -446,6 +513,9 @@ def health_lines(health: Health, now: float) -> list[str]:
446513
if health.load is not None:
447514
one, five, fifteen = health.load
448515
up.append(f"load {one:.2f} {five:.2f} {fifteen:.2f} ({os.cpu_count() or '?'} cores)")
516+
# A temperature that's alerting is described once, by the warning below.
517+
if health.temperature is not None and "temp" not in found:
518+
up.append(f"{health.temperature[1]:.0f} °C")
449519
if up:
450520
lines.append(" · ".join(up))
451521
if health.memory is not None:
@@ -602,10 +672,13 @@ def incidents_since(start: float) -> list[Incident]:
602672

603673

604674
def switched_off(key: str) -> bool:
605-
"""An alert whose check is turned off: backups without BACKUP_DIR; units, and
606-
reboots without HOMELAB_HOST_ROOT, in a container."""
675+
"""An alert whose check is turned off: backups without BACKUP_DIR; the
676+
temperature without HOMELAB_TEMP_ALERT_C; units, and reboots without
677+
HOMELAB_HOST_ROOT, in a container."""
607678
if key == "backup":
608679
return BACKUP_DIR is None
680+
if key == "temp":
681+
return TEMP_ALERT_C is None
609682
if key == "reboot":
610683
return IN_CONTAINER and HOST_ROOT is None
611684
return IN_CONTAINER and key.startswith("unit:")

‎candygoogy/settings.py‎

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -68,6 +68,7 @@
6868
"WEEKLY_REPORT",
6969
"HOMELAB_DISKS",
7070
"HOMELAB_HOST_ROOT",
71+
"HOMELAB_TEMP_ALERT_C",
7172
"BACKUP_DIR",
7273
"INTERNET_CHECK_TARGETS",
7374
"DOCKER_HOST",
@@ -160,6 +161,8 @@ class Settings:
160161
# The host's / as mounted in a container (e.g. /host); None: read / itself.
161162
homelab_host_root: str | None = None
162163
commit: str | None = None # CANDYGOOGY_COMMIT: the image's commit, for /about
164+
# /homelab alerts at or above this many °C; None: no temperature alert.
165+
homelab_temp_alert_c: int | None = None
163166

164167

165168
def key_path(value: str | None, label: str, default: str, problems: list[str]) -> str | None:
@@ -567,6 +570,13 @@ def hours(text: str) -> float:
567570
return value
568571

569572

573+
def temp_limit(text: str) -> int:
574+
"""Whole degrees Celsius from 40 to 110; ValueError (without the value) if not."""
575+
if not is_number(text) or len(text) > 3 or not 40 <= int(text) <= 110:
576+
raise ValueError("must be a whole number of °C from 40 to 110, e.g. 85")
577+
return int(text)
578+
579+
570580
def load_settings(env: Mapping[str, str]) -> Settings:
571581
"""Every setting, checked. Raises ConfigError listing all problems at once."""
572582
problems: list[str] = []
@@ -658,6 +668,12 @@ def load_settings(env: Mapping[str, str]) -> Settings:
658668
host_root = posix_path(root_text)
659669
except ValueError as e:
660670
problems.append(f"HOMELAB_HOST_ROOT {e}.")
671+
temp_alert = None
672+
if temp_text := env.get("HOMELAB_TEMP_ALERT_C", "").strip(): # unset or empty: no alert
673+
try:
674+
temp_alert = temp_limit(temp_text)
675+
except ValueError as e:
676+
problems.append(f"HOMELAB_TEMP_ALERT_C {e}.")
661677
docker = DEFAULT_DOCKER_HOST
662678
if docker_text := env.get("DOCKER_HOST", "").strip():
663679
try:
@@ -701,4 +717,5 @@ def load_settings(env: Mapping[str, str]) -> Settings:
701717
docker_host=docker,
702718
homelab_host_root=host_root,
703719
commit=build_commit,
720+
homelab_temp_alert_c=temp_alert,
704721
)

‎tests/__init__.py‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,7 @@
3232
"MACHINES_FILE",
3333
"SSH_KNOWN_HOSTS",
3434
"HOMELAB_HOST_ROOT",
35+
"HOMELAB_TEMP_ALERT_C",
3536
"DOCKER_HOST",
3637
):
3738
_ = os.environ.pop(name, None)

‎tests/conftest.py‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -166,6 +166,8 @@ def isolated_homelab_alerts(tmp_path: Path, monkeypatch: pytest.MonkeyPatch) ->
166166
monkeypatch.setattr(homelab, "ALERTS_FILE", tmp_path / "homelab_alerts.json")
167167
monkeypatch.setattr(homelab, "REBOOT_FILE", tmp_path / "homelab_reboot.json")
168168
monkeypatch.setattr(homelab, "INCIDENTS_FILE", tmp_path / "homelab_history.json")
169+
# Never the machine's own sensors (a CI runner has some): no /sys at all.
170+
monkeypatch.setattr(homelab, "SYS", tmp_path / "no-sys")
169171
homelab._open_alerts.clear() # pyright: ignore[reportPrivateUsage]
170172
homelab._incidents.clear() # pyright: ignore[reportPrivateUsage]
171173

‎tests/helpers.py‎

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -307,6 +307,11 @@ def __init__(self, tmp_path: Path, monkeypatch: pytest.MonkeyPatch, run: FakeRun
307307
self.run_dir: Path = tmp_path / "run"
308308
self.run_dir.mkdir()
309309
monkeypatch.setattr(homelab, "RUN", str(self.run_dir))
310+
# sysfs with no temperature sensors until zone() or hwmon() adds some.
311+
self.sys: Path = tmp_path / "sys"
312+
(self.sys / "class" / "thermal").mkdir(parents=True)
313+
(self.sys / "class" / "hwmon").mkdir()
314+
monkeypatch.setattr(homelab, "SYS", self.sys)
310315
# Docker's API: what it answers, and every request it got.
311316
self.docker_answer: httpx.Response | Exception = httpx.Response(200, json=[])
312317
self.docker_requests: list[httpx.Request] = []
@@ -344,6 +349,29 @@ def reboot_required(self, *packages: str, listed: bool = True) -> None:
344349
"".join(f"{p}\n" for p in packages)
345350
)
346351

352+
def zone(self, kind: str, temp: str | None) -> Path:
353+
"""A thermal zone of type `kind` whose temp file says `temp` (None:
354+
unreadable, as a zone answering EINVAL is)."""
355+
zones = self.sys / "class" / "thermal"
356+
folder = zones / f"thermal_zone{len(list(zones.iterdir()))}"
357+
folder.mkdir()
358+
_ = (folder / "type").write_text(f"{kind}\n")
359+
if temp is None:
360+
(folder / "temp").mkdir() # reading a directory fails like EINVAL
361+
else:
362+
_ = (folder / "temp").write_text(f"{temp}\n")
363+
return folder
364+
365+
def hwmon(self, name: str, *temps: str) -> Path:
366+
"""An hwmon device of driver `name` with temp1_input, temp2_input, ..."""
367+
devices = self.sys / "class" / "hwmon"
368+
folder = devices / f"hwmon{len(list(devices.iterdir()))}"
369+
folder.mkdir()
370+
_ = (folder / "name").write_text(f"{name}\n")
371+
for n, temp in enumerate(temps, start=1):
372+
_ = (folder / f"temp{n}_input").write_text(f"{temp}\n")
373+
return folder
374+
347375
def snapshot(
348376
self, name: str, age_hours: float = 1, size: int = 1024, complete: bool = True
349377
) -> Path:

0 commit comments

Comments
 (0)