Merge pull request 'feat: alert on Sia hostd usage instead of df for /mnt/sia' (#34) from feat/lxc-managed-volume-usage into main
Lint / Python (flake8) (push) Successful in 1m49s
Security / Python Security (bandit) (push) Successful in 1m51s
Lint / Notify on failure (push) Skipped
Test / Python Tests (pytest) (push) Successful in 1m8s

This commit was merged in pull request #34.
This commit is contained in:
jared committed 2026-11-06 13:03:02 -05:00
commit 30b28677e8
3 files changed
+207 -10

No files matched your search

+10
View File
@@ -179,6 +179,16 @@ The following paths are automatically excluded from monitoring:
- `/opt/metube_downloads` - `/opt/metube_downloads`
- Pattern-based exclusions for media and download directories - Pattern-based exclusions for media and download directories
## Application-Managed Volumes
Some mounts are expected to read nearly full, so `df` is the wrong signal. Sia's hostd
allocates its whole `data.dat` over time, then reuses freed slots. For mounts listed in
`LXC_MANAGED_VOLUMES` (currently `/mnt/sia` on LXC 141):
- The usual LXC thresholds apply to hostd's used/total sectors, read from its database in read-only mode.
- A critical ticket is created if the filesystem has less than `min_free_bytes` (20 GiB) left.
- If hostd's usage can't be read, the daemon logs a warning and only checks the free-space floor.
## Service Configuration ## Service Configuration
The daemon runs: The daemon runs:
+105 -10
View File
@@ -14,7 +14,7 @@ import fcntl
import textwrap import textwrap
import shutil import shutil
from concurrent.futures import ThreadPoolExecutor, as_completed from concurrent.futures import ThreadPoolExecutor, as_completed
from typing import Dict, Any, List from typing import Dict, Any, List, Optional
# ============================================================================= # =============================================================================
# LOGGING SETUP # LOGGING SETUP
@@ -104,6 +104,8 @@ class SystemHealthMonitor:
'PBS_SYNC_FAILED': PRIORITIES['MEDIUM'] # P3 - Sync job failed 'PBS_SYNC_FAILED': PRIORITIES['MEDIUM'] # P3 - Sync job failed
} }
HOSTD_SECTOR_BYTES = 4 * 1024 ** 2 # Sia sectors are a fixed 4 MiB
CONFIG = { CONFIG = {
'TICKET_API_URL': 'http://10.10.10.45/create_ticket_api.php', 'TICKET_API_URL': 'http://10.10.10.45/create_ticket_api.php',
'TICKET_API_KEY': None, # Will be loaded from .env file 'TICKET_API_KEY': None, # Will be loaded from .env file
@@ -133,6 +135,19 @@ class SystemHealthMonitor:
r'.*mediafs.*', r'.*mediafs.*',
r'.*/downloads.*' r'.*/downloads.*'
], ],
# Mounts whose filesystem is expected to read nearly full because an
# application allocates its whole data file over time. df says nothing
# about these, so thresholds apply to the application's own usage instead.
# min_free_bytes still alerts if the filesystem itself is about to run out.
'LXC_MANAGED_VOLUMES': [
{
'vmid': '141',
'mountpoint': '/mnt/sia',
'type': 'hostd',
'db_path': '/var/lib/hostd/hostd.sqlite3',
'min_free_bytes': 20 * 1024 ** 3
}
],
'HISTORY_DIR': '/var/log/hwmonDaemon', 'HISTORY_DIR': '/var/log/hwmonDaemon',
'HISTORY_RETENTION_DAYS': 30, 'HISTORY_RETENTION_DAYS': 30,
'INCLUDE_INFO_TICKETS': False, # Set True to create P5 tickets for INFO alerts 'INCLUDE_INFO_TICKETS': False, # Set True to create P5 tickets for INFO alerts
@@ -4087,6 +4102,90 @@ class SystemHealthMonitor:
lines.append(f"\nLXC Storage: check error ({len(lxc_health.get('issues', []))} issue(s))") lines.append(f"\nLXC Storage: check error ({len(lxc_health.get('issues', []))} issue(s))")
return lines return lines
def _apply_lxc_thresholds(self, vmid: str, mountpoint: str, usage_percent: float,
lxc_health: Dict[str, Any]) -> None:
"""Record a WARNING or CRITICAL issue if usage crosses the LXC thresholds."""
if usage_percent >= self.CONFIG['THRESHOLDS']['LXC_CRITICAL']:
lxc_health['status'] = 'CRITICAL'
issue = f"LXC {vmid} critical storage usage: {usage_percent:.1f}% on {mountpoint}"
lxc_health['issues'].append(issue)
elif usage_percent >= self.CONFIG['THRESHOLDS']['LXC_WARNING']:
if lxc_health['status'] != 'CRITICAL':
lxc_health['status'] = 'WARNING'
issue = f"LXC {vmid} high storage usage: {usage_percent:.1f}% on {mountpoint}"
lxc_health['issues'].append(issue)
def _find_managed_volume(self, vmid: str, mountpoint: str) -> Optional[Dict[str, Any]]:
"""Return the LXC_MANAGED_VOLUMES entry for this mount, if there is one."""
for managed in self.CONFIG['LXC_MANAGED_VOLUMES']:
if managed['vmid'] == vmid and managed['mountpoint'] == mountpoint:
return managed
return None
def _get_hostd_volume_usage(self, vmid: str, managed: Dict[str, Any]) -> Optional[Dict[str, int]]:
"""Read a Sia hostd volume's used and total bytes from its database, read-only.
Reading the database avoids needing the hostd API password on every node.
Returns None if the usage cannot be read.
"""
query = "SELECT disk_path, used_sectors, total_sectors FROM storage_volumes;"
try:
result = subprocess.run(
['pct', 'exec', vmid, '--', 'sqlite3', f"file:{managed['db_path']}?mode=ro", query],
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
text=True,
timeout=30
)
if result.returncode != 0:
logger.warning(f"Could not read hostd usage for LXC {vmid}: {result.stderr.strip()}")
return None
used_sectors = total_sectors = 0
for row in result.stdout.splitlines():
disk_path, used, total = row.rsplit('|', 2)
if disk_path.startswith(f"{managed['mountpoint']}/"):
used_sectors += int(used)
total_sectors += int(total)
except (subprocess.SubprocessError, OSError, ValueError) as e:
logger.warning(f"Could not read hostd usage for LXC {vmid}: {e}")
return None
if total_sectors <= 0:
logger.warning(f"hostd reported no volumes on {managed['mountpoint']} in LXC {vmid}")
return None
return {
'used_bytes': used_sectors * self.HOSTD_SECTOR_BYTES,
'total_bytes': total_sectors * self.HOSTD_SECTOR_BYTES
}
def _check_managed_volume(self, vmid: str, filesystem: Dict[str, Any], managed: Dict[str, Any],
lxc_health: Dict[str, Any]) -> None:
"""Alert on an application's own usage, not the df usage of its mount.
Replaces the filesystem's figures with the application's, so tickets and
metrics report the same number the alert was based on. If those figures
cannot be read, only the free-space floor is checked.
"""
mountpoint = filesystem['mountpoint']
if filesystem['available'] < managed['min_free_bytes']:
lxc_health['status'] = 'CRITICAL'
lxc_health['issues'].append(
f"LXC {vmid} critical storage usage: filesystem nearly out of space on {mountpoint}"
)
usage = self._get_hostd_volume_usage(vmid, managed)
if usage is None:
return
usage_percent = usage['used_bytes'] / usage['total_bytes'] * 100
filesystem.update({
'total_space': usage['total_bytes'],
'used_space': usage['used_bytes'],
'available': usage['total_bytes'] - usage['used_bytes'],
'usage_percent': usage_percent
})
self._apply_lxc_thresholds(vmid, mountpoint, usage_percent, lxc_health)
def _check_lxc_storage(self) -> Dict[str, Any]: def _check_lxc_storage(self) -> Dict[str, Any]:
""" """
Check storage utilization for all running LXC containers Check storage utilization for all running LXC containers
@@ -4187,15 +4286,11 @@ class SystemHealthMonitor:
container_info['filesystems'].append(filesystem) container_info['filesystems'].append(filesystem)
# Check thresholds # Check thresholds
if usage_percent >= self.CONFIG['THRESHOLDS']['LXC_CRITICAL']: managed = self._find_managed_volume(vmid, mountpoint)
lxc_health['status'] = 'CRITICAL' if managed:
issue = f"LXC {vmid} critical storage usage: {usage_percent:.1f}% on {mountpoint}" self._check_managed_volume(vmid, filesystem, managed, lxc_health)
lxc_health['issues'].append(issue) else:
elif usage_percent >= self.CONFIG['THRESHOLDS']['LXC_WARNING']: self._apply_lxc_thresholds(vmid, mountpoint, usage_percent, lxc_health)
if lxc_health['status'] != 'CRITICAL':
lxc_health['status'] = 'WARNING'
issue = f"LXC {vmid} high storage usage: {usage_percent:.1f}% on {mountpoint}"
lxc_health['issues'].append(issue)
logger.debug(f"Filesystem details: {filesystem}") logger.debug(f"Filesystem details: {filesystem}")
except Exception as e: except Exception as e:
+92
View File
@@ -1,6 +1,7 @@
"""Tests for SystemHealthMonitor pure methods — no external processes or filesystem.""" """Tests for SystemHealthMonitor pure methods — no external processes or filesystem."""
import sys import sys
import os import os
import subprocess
import pytest import pytest
@@ -605,3 +606,94 @@ class TestCpuSustainedGating:
h = monitor._check_cpu_usage() h = monitor._check_cpu_usage()
assert h['status'] == 'WARNING' assert h['status'] == 'WARNING'
assert h['load15_per_core_percent'] is None assert h['load15_per_core_percent'] is None
# ── LXC managed volumes (Sia hostd) ──────────────────────────────────────────
TIB = 1024 ** 4
GIB = 1024 ** 3
SIA_DF = "mp0 storj-pool:vm-141-disk-0 15.5T 14.8T 700.0G 95.5 /mnt/sia\n"
def _run_lxc_check(monitor, df_rows, hostd_stdout='/mnt/sia/d.dat|1|2\n', hostd_returncode=0, hostd_error=None):
"""Run _check_lxc_storage against canned pct output; return (health, pct exec calls)."""
exec_calls = []
def fake_run(cmd, **kwargs):
if cmd[:2] == ['pct', 'list']:
return MagicMock(stdout="VMID Status Lock Name\n141 running sia-node\n")
if cmd[:2] == ['pct', 'df']:
return MagicMock(stdout="MP Volume Size Used Avail Use% Path\n" + df_rows)
if cmd[:2] == ['pct', 'exec']:
exec_calls.append(cmd)
if hostd_error:
raise hostd_error
return MagicMock(stdout=hostd_stdout, stderr='boom', returncode=hostd_returncode)
raise AssertionError(f"unexpected command: {cmd}")
with patch.dict(monitor._available_tools, {'pct': True}), \
patch('subprocess.run', side_effect=fake_run):
return monitor._check_lxc_storage(), exec_calls
class TestManagedVolumes:
def test_full_mount_with_low_hostd_usage_cuts_no_ticket(self, monitor):
"""The mount reads 95.5% full but hostd only uses 3.4 of 15 TiB."""
health, calls = _run_lxc_check(monitor, SIA_DF, hostd_stdout='/mnt/sia/hostd-data/data.dat|895045|3932160\n')
assert health['status'] == 'OK'
assert health['issues'] == []
fs = health['containers'][0]['filesystems'][0]
assert fs['usage_percent'] == pytest.approx(22.76, abs=0.01)
assert fs['total_space'] == 15 * TIB
assert 'mode=ro' in calls[0][5]
def test_warns_when_hostd_usage_crosses_warning(self, monitor):
health, _ = _run_lxc_check(monitor, SIA_DF, hostd_stdout='/mnt/sia/hostd-data/data.dat|3342336|3932160\n')
assert health['status'] == 'WARNING'
assert health['issues'] == ['LXC 141 high storage usage: 85.0% on /mnt/sia']
def test_critical_when_hostd_usage_crosses_critical(self, monitor):
health, _ = _run_lxc_check(monitor, SIA_DF, hostd_stdout='/mnt/sia/hostd-data/data.dat|3800000|3932160\n')
assert health['status'] == 'CRITICAL'
assert health['issues'] == ['LXC 141 critical storage usage: 96.6% on /mnt/sia']
def test_critical_when_filesystem_is_nearly_out_of_space(self, monitor):
"""A real out-of-space risk must alert even with low hostd usage."""
df = "mp0 storj-pool:vm-141-disk-0 15.5T 15.4T 10.0G 99.9 /mnt/sia\n"
health, _ = _run_lxc_check(monitor, df, hostd_stdout='/mnt/sia/hostd-data/data.dat|895045|3932160\n')
assert health['status'] == 'CRITICAL'
assert health['issues'] == ['LXC 141 critical storage usage: filesystem nearly out of space on /mnt/sia']
@pytest.mark.parametrize('kwargs', [
{'hostd_returncode': 1, 'hostd_stdout': ''},
{'hostd_stdout': 'garbage'},
{'hostd_stdout': ''},
{'hostd_stdout': '/mnt/other/data.dat|3800000|3932160\n'},
{'hostd_error': subprocess.TimeoutExpired('pct', 30)},
])
def test_unreadable_hostd_usage_does_not_fall_back_to_df(self, monitor, kwargs):
health, _ = _run_lxc_check(monitor, SIA_DF, **kwargs)
assert health['status'] == 'OK'
assert health['issues'] == []
def test_floor_still_applies_when_hostd_usage_is_unreadable(self, monitor):
df = "mp0 storj-pool:vm-141-disk-0 15.5T 15.4T 10.0G 99.9 /mnt/sia\n"
health, _ = _run_lxc_check(monitor, df, hostd_returncode=1, hostd_stdout='')
assert health['status'] == 'CRITICAL'
assert len(health['issues']) == 1
def test_sums_only_volumes_on_this_mount(self, monitor):
stdout = ('/mnt/sia/a.dat|100|1000\n'
'/mnt/sia/b.dat|800|1000\n'
'/mnt/sia-other/c.dat|1000|1000\n')
health, _ = _run_lxc_check(monitor, SIA_DF, hostd_stdout=stdout)
assert health['containers'][0]['filesystems'][0]['usage_percent'] == pytest.approx(45.0)
assert health['status'] == 'OK'
def test_other_mounts_still_use_df(self, monitor):
"""The container's rootfs, and other containers, keep normal df alerting."""
df = "rootfs sia-nvme:vm-141-disk-0 125.9G 115.0G 5.0G 91.3 /\n"
health, calls = _run_lxc_check(monitor, df)
assert health['status'] == 'CRITICAL'
assert health['issues'] == ['LXC 141 critical storage usage: 91.3% on /']
assert calls == []