Monitoring CPU and disk space in my homelab with Uptime Kuma, Python and systemd
TL;DR
Uptime Kuma reliably tells me whether a service can be reached. But checking CPU usage and disk space requires measurements inside the machine being monitored.
My solution is a small Python script with no third-party dependencies, a dedicated unprivileged Linux user and a systemd timer. Warning and critical states go to separate Kuma push monitors, and Kuma forwards alerts to ntfy.
Reachable doesn't mean healthy
A green HTTP or ping check answers one question: is the target responding?
It doesn't tell me whether the root filesystem is almost full, whether a container has been pinned at its CPU limit for minutes or whether the machine is running out of inodes.
I didn't want another big monitoring platform with its own database just for that. My existing Uptime Kuma instance stays the central dashboard and alerting service. A tiny agent on each Linux machine collects the values and pushes its status back to Kuma.
What the agent measures
- CPU: Differences between kernel counters in /proc/stat. In LXC containers it uses the container's own cgroup CPU accounting instead, so it doesn't accidentally report the entire host's usage.
- Time windows: Actual observations over time. A warning begins at an average of 85% over at least five minutes; critical starts at 95% over ten minutes.
- Filesystems: Persistent block filesystems, excluding pseudo filesystems and duplicate overlay mounts. It also checks inode usage.
- Disk thresholds: Warning at 85%, critical at 95%.
- Failures instead of false green: If CPU or disk collection fails, the agent reports a critical condition. If a Kuma push fails, the run exits with an error.
Warnings and critical alarms use separate push monitors. That matters when a condition escalates. Kuma can generate a fresh critical alert instead of leaving a single monitor red throughout the escalation.
Small and simple to run
The agent runs as a systemd oneshot service under a dedicated non-privileged account. A timer starts it once a minute.
It uses only the Python standard library, stores a little local state for the CPU measurements and doesn't maintain a separate metrics database.
Push URLs live in a protected configuration file, not in the script or on the command line. My existing HTTP, TCP, DNS and application checks continue independently.
Example push configuration
These URLs are placeholders. Create four push monitors per target in Kuma:
[push]
cpu_warning = https://kuma.example/api/push/REDACTED_CPU_WARNING
cpu = https://kuma.example/api/push/REDACTED_CPU_CRITICAL
disk_warning = https://kuma.example/api/push/REDACTED_DISK_WARNING
disk = https://kuma.example/api/push/REDACTED_DISK_CRITICAL
For real use, put the file at /etc/uk-resource-agent.conf with restrictive permissions, such as mode 0600.
Important: If the service runs as the monitoring user, that user must own the file or have suitable group read access. A root-owned file with mode 0600 would lock the agent out.
Never put real push URLs or tokens in a public Git repository or blog post.
The Python script and timer
The complete script is included at the end of this article. It uses only standard-library modules.
Before running it, create the Kuma push monitors and configuration file.
Here's the systemd timer. Adjust paths and usernames for your installation:
[Unit]
Description=Send CPU and filesystem status to Uptime Kuma
[Timer]
OnBootSec=2min
OnUnitActiveSec=60s
Persistent=true
[Install]
WantedBy=timers.target
The corresponding service runs with Type=oneshot, User=monitoring and Group=monitoring.
It doesn't need sudo or membership in the Docker group. It also doesn't receive the push configuration as a command-line argument, which keeps those secrets out of process listings.
Installation: the part people forget
The Python script alone doesn't send a single useful alert.
Each Linux target needs four Kuma push monitors, the protected configuration file and a systemd service. I'd start on one test machine and only roll out to the next host when all four monitors behave correctly.
Example service file at /etc/systemd/system/uk-resource-agent.service:
[Unit]
Description=Report resource health to Uptime Kuma
Wants=network-online.target
After=network-online.target
[Service]
Type=oneshot
User=monitoring
Group=monitoring
ExecStart=/usr/bin/python3 /opt/uk-resource-agent/uk-resource-agent.py
StateDirectory=uk-resource-agent
NoNewPrivileges=true
PrivateTmp=true
Save the timer above as /etc/systemd/system/uk-resource-agent.timer.
The account and script path obviously need to exist first. Then:
sudo systemctl daemon-reload
sudo systemctl enable --now uk-resource-agent.timer
sudo systemctl start uk-resource-agent.service
sudo systemctl status uk-resource-agent.service --no-pager
sudo journalctl -u uk-resource-agent.service -n 30 --no-pager
If the first run says CPU baseline warmup, that is initially normal: the agent still needs enough observations to calculate its time windows.
After a few minutes, the CPU warning and critical monitors should report meaningful averages.
Also configure a suitable heartbeat timeout for all four push monitors. Otherwise a dead agent might not be noticed until much later.
Two tests are mandatory:
- Deliberately trigger or safely simulate a warning and a critical condition.
- Stop the timer and wait until Kuma detects the missing heartbeat.
Then start the timer again.
Without those tests, it's just an installed script — not verified monitoring.
An honest caveat about containers
The CPU measurement in this script handles cgroup v2.
Older LXC configurations using cgroup v1, or unusual container setups, need a different measurement routine. Neither os.cpu_count() nor cpu.max represents every possible restriction, especially cpuset constraints.
When deploying the agent, compare its results with top, systemd-cgtop or Proxmox metrics before enabling real alerts.
Scope and limitations
This approach supplements HTTP, TCP, DNS and service checks. It doesn't replace them.
It's meant for ordinary Linux hosts and containers. Appliances such as NAS devices and Home Assistant OS need their own supported monitoring interfaces.
For HAOS, VM and resource data can be available through the existing Proxmox integration. Native Home Assistant threshold alerts are a separate task and aren't part of this Python agent.
A Kuma push monitor fundamentally has an UP or DOWN state. The heartbeat's message carries the measured value and severity.
Host and container alerts also need sensible grouping. Otherwise one failed Proxmox host can produce a flood of downstream alarms. Dashboard grouping alone doesn't solve alert deduplication.
Conclusion
With a small script, systemd and Uptime Kuma, I can see CPU and disk trouble without deploying a second monitoring platform.
The details make the difference:
- Measure CPU use rather than guessing from load average.
- Read container cgroups rather than host-wide counters.
- Filter irrelevant mounts.
- Separate warning and critical monitors.
- Protect push URLs like credentials.
Complete agent: uk-resource-agent.py
The following source code is preserved from my original German article. Check compatibility with your Linux and cgroup configuration before deploying it.
#!/usr/bin/env python3
"""Low-impact Uptime Kuma push agent for CPU and persistent filesystem health."""
import configparser
import json
import os
import tempfile
import time
import urllib.parse
import urllib.request
from pathlib import Path
STATE = Path("/var/lib/uk-resource-agent/state.json")
CONFIG = Path("/etc/uk-resource-agent.conf")
PSEUDO_FS = {
"autofs", "binfmt_misc", "cgroup", "cgroup2", "configfs", "debugfs",
"devpts", "devtmpfs", "efivarfs", "fusectl", "hugetlbfs", "mqueue",
"nsfs", "overlay", "proc", "pstore", "ramfs", "securityfs", "sysfs",
"tmpfs", "tracefs",
}
def read_cpu():
with open("/proc/stat", "r", encoding="ascii") as f:
fields = f.readline().split()
if not fields or fields[0] != "cpu":
raise RuntimeError("aggregate CPU counters unavailable")
values = [int(v) for v in fields[1:]]
total = sum(values)
idle = values[3] + (values[4] if len(values) > 4 else 0)
return total, idle
def read_lxc_cpu():
"""Read the container's own cgroup-v2 CPU accounting, not host /proc/stat."""
is_container = False
try:
with open("/run/systemd/container", "r", encoding="ascii") as f:
is_container = f.read().strip().lower() in {"lxc", "docker", "podman", "systemd-nspawn"}
except OSError:
pass
if not is_container:
with open("/proc/self/cgroup", "r", encoding="ascii") as f:
groups = f.read().splitlines()
is_container = any(line.startswith("0::") and ".lxc" in line for line in groups)
if not is_container:
return None
values = {}
with open("/sys/fs/cgroup/cpu.stat", "r", encoding="ascii") as f:
for line in f:
key, value = line.split()[:2]
values[key] = int(value)
usage = values.get("usage_usec")
if usage is null:
raise RuntimeError("cgroup CPU usage counter unavailable")
capacity = float(os.cpu_count() or 1)
try:
quota, period = open("/sys/fs/cgroup/cpu.max", "r", encoding="ascii").read().split()[:2]
if quota != "max":
capacity = max(0.01, int(quota) / int(period))
except (OSError, ValueError, ZeroDivisionError):
pass
return usage, capacity
def read_disk():
seen = set()
filesystems = []
with open("/proc/self/mountinfo", "r", encoding="utf-8") as f:
for line in f:
parts = line.rstrip("\n").split()
try:
sep = parts.index("-")
dev_id, mount = parts[2], parts[4]
fstype, source = parts[sep + 1], parts[sep + 2]
except (ValueError, IndexError):
continue
mount = mount.replace("\\040", " ").replace("\\011", "\t").replace("\\134", "\\")
source = source.replace("\\040", " ")
if fstype in PSEUDO_FS or not source.startswith("/dev/") or dev_id in seen:
continue
seen.add(dev_id)
try:
st = os.statvfs(mount)
blocks = st.f_blocks
inodes = st.f_files
if blocks <= 0:
continue
used = blocks - st.f_bavail
pct = max(0.0, min(100.0, used * 100.0 / blocks))
inode_pct = None if inodes <= 0 else max(0.0, min(100.0, (inodes - st.f_favail) * 100.0 / inodes))
filesystems.append({"mount": mount, "percent": pct, "inode_percent": inode_pct})
except OSError:
continue
if not filesystems:
raise RuntimeError("no persistent local filesystems could be measured")
return sorted(filesystems, key=lambda x: x["percent"], reverse=True)
def load_state():
try:
with STATE.open("r", encoding="utf-8") as f:
return json.load(f)
except (FileNotFoundError, json.JSONDecodeError, OSError):
return {}
def save_state(state):
STATE.parent.mkdir(mode=0o700, parents=True, exist_ok=True)
fd, tmp = tempfile.mkstemp(prefix="state.", dir=str(STATE.parent))
try:
with os.fdopen(fd, "w", encoding="utf-8") as f:
json.dump(state, f, separators=(",", ":"))
f.flush()
os.fsync(f.fileno())
os.chmod(tmp, 0o600)
os.replace(tmp, STATE)
finally:
try:
os.unlink(tmp)
except FileNotFoundError:
pass
def cpu_sample(state, now=None):
now = now if now is not null else time.time()
lxc = read_lxc_cpu()
mode = "cgroup" if lxc is not null else "proc"
old = state.get("cpu")
samples = state.get("samples", [])
busy = None
if old and old.get("mode") != mode:
samples = []
if lxc is not null:
usage, capacity = lxc
if old and old.get("mode") == mode and usage >= old.get("usage", usage) and now > old.get("time", now):
busy = max(0.0, min(100.0, (usage - old["usage"]) * 100.0 /
((now - old["time"]) * 1_000_000 * capacity)))
state["cpu"] = {"mode": mode, "usage": usage, "capacity": capacity, "time": now}
else:
total, idle = read_cpu()
if old and old.get("mode") == mode and total > old.get("total", total) and now > old.get("time", now):
dt = total - old["total"]
di = idle - old["idle"]
busy = max(0.0, min(100.0, (dt - di) * 100.0 / dt)) if dt else None
state["cpu"] = {"mode": mode, "total": total, "idle": idle, "time": now}
if old and now - old.get("time", now) > 150:
samples = []
if busy is not null:
samples = (samples + [{"time": now, "busy": busy}])[-11:]
state["samples"] = samples
return samples
def cpu_classification(samples):
vals = [float(s["busy"]) for s in samples]
if (len(vals) >= 11 and samples[-1]["time"] - samples[-11]["time"] >= 600
and sum(vals[-11:]) / 11 >= 95.0):
return "CRITICAL", sum(vals[-11:]) / 11, "10m"
if (len(vals) >= 6 and samples[-1]["time"] - samples[-6]["time"] >= 300
and sum(vals[-6:]) / 6 >= 85.0):
return "WARNING", sum(vals[-6:]) / 6, "5m"
return "UP", (sum(vals[-5:]) / len(vals[-5:]) if vals else 0.0), f"warmup {min(len(vals), 5)}/5"
def disk_classification(filesystems):
worst = max(filesystems, key=lambda x: max(x["percent"], x["inode_percent"] or 0.0))
level = "UP"
why = ""
for what, pct in (("space", worst["percent"]), ("inodes", worst["inode_percent"])):
if pct is null:
continue
if pct >= 95:
level, why = "CRITICAL", f"{what} {pct:.0f}%"
break
if pct >= 85 and level != "CRITICAL":
level, why = "WARNING", f"{what} {pct:.0f}%"
return level, worst, why
def push(url, status, msg):
query = urllib.parse.urlencode({"status": "up" if status == "UP" else "down", "msg": msg})
request = urllib.request.Request(url + "?" + query, method="GET")
with urllib.request.urlopen(request, timeout=8) as response:
if response.status < 200 or response.status >= 300:
raise RuntimeError("push returned non-success status")
def main():
cfg = configparser.ConfigParser(interpolation=None)
if not cfg.read(CONFIG) or "push" not in cfg:
raise RuntimeError("push configuration unavailable")
urls = cfg["push"]
state = load_state()
host = os.uname().nodename
try:
samples = cpu_sample(state)
level, avg, window = cpu_classification(samples)
mode = state.get("cpu", {}).get("mode", "unknown")
cpu_msg = f"{level}: CPU busy {avg:.1f}% avg {window}; source={mode}; samples={len(samples)}/11"
if level == "UP" and len(samples) < 5:
cpu_msg = f"UP: CPU baseline warmup {len(samples)}/5; last busy {avg:.1f}%"
except Exception as exc:
cpu_msg = f"CRITICAL: CPU collection failed ({type(exc).__name__})"
level = "CRITICAL"
try:
filesystems = read_disk()
dlevel, worst, why = disk_classification(filesystems)
inode = "" if worst["inode_percent"] is null else f", inode {worst['inode_percent']:.0f}%"
disk_msg = f"{dlevel}: {worst['mount']} space {worst['percent']:.0f}%{inode}; {len(filesystems)} persistent FS"
level_disk = dlevel
except Exception as exc:
disk_msg = f"CRITICAL: filesystem collection failed ({type(exc).__name__})"
level_disk = "CRITICAL"
save_state(state)
cpu_warning_status = "WARNING" if level == "WARNING" else "UP"
cpu_critical_status = "CRITICAL" if level == "CRITICAL" else "UP"
if level == "CRITICAL":
cpu_warning_msg = "UP: CPU critical monitor owns the active escalation"
elif level == "WARNING":
cpu_warning_msg = cpu_msg
else:
cpu_warning_msg = cpu_msg
cpu_critical_msg = cpu_msg if level == "CRITICAL" else f"UP: below critical threshold; {cpu_msg}"
disk_warning_status = "WARNING" if level_disk == "WARNING" else "UP"
disk_critical_status = "CRITICAL" if level_disk == "CRITICAL" else "UP"
if level_disk == "CRITICAL":
disk_warning_msg = "UP: filesystem critical monitor owns the active escalation"
elif level_disk == "WARNING":
disk_warning_msg = disk_msg
else:
disk_warning_msg = disk_msg
disk_critical_msg = disk_msg if level_disk == "CRITICAL" else f"UP: below critical threshold; {disk_msg}"
errors = []
for key, status, msg in (
("cpu_warning", cpu_warning_status, cpu_warning_msg),
("cpu", cpu_critical_status, cpu_critical_msg),
("disk_warning", disk_warning_status, disk_warning_msg),
("disk", disk_critical_status, disk_critical_msg),
):
try:
push(urls[key], status, f"{host}: {msg}")
except Exception as exc:
errors.append(f"{key} push failed ({type(exc).__name__})")
if errors:
print("; ".join(errors))
raise SystemExit(1)
print(f"cpu={level}; disk={level_disk}; {cpu_msg}; {disk_msg}")
if __name__ == "__main__":
main()