From d8f707ade7c6e87522a0b43b15fb3ae353b1dbdc Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Fri, 6 Nov 2026 12:36:22 -0500 Subject: [PATCH 1/2] feat: alert on Sia hostd usage instead of df for /mnt/sia hostd allocates its whole data.dat over time and then reuses freed slots, so df on the mount is expected to read nearly full and says nothing about real usage. Alert on hostd's used/total sectors for mounts listed in LXC_MANAGED_VOLUMES, and keep a critical free-space floor for a real out-of-space risk. Co-Authored-By: Claude Opus 5.5 --- README.md | 10 ++++ hwmonDaemon.py | 113 ++++++++++++++++++++++++++++++++++++++++---- tests/test_hwmon.py | 83 ++++++++++++++++++++++++++++++++ 3 files changed, 196 insertions(+), 10 deletions(-) diff --git a/README.md b/README.md index 16bed7e..9a4d21e 100644 --- a/README.md +++ b/README.md @@ -179,6 +179,16 @@ The following paths are automatically excluded from monitoring: - `/opt/metube_downloads` - 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 The daemon runs: diff --git a/hwmonDaemon.py b/hwmonDaemon.py index afc238d..d09f56b 100644 --- a/hwmonDaemon.py +++ b/hwmonDaemon.py @@ -14,7 +14,7 @@ import fcntl import textwrap import shutil from concurrent.futures import ThreadPoolExecutor, as_completed -from typing import Dict, Any, List +from typing import Dict, Any, List, Optional # ============================================================================= # LOGGING SETUP @@ -104,6 +104,8 @@ class SystemHealthMonitor: 'PBS_SYNC_FAILED': PRIORITIES['MEDIUM'] # P3 - Sync job failed } + HOSTD_SECTOR_BYTES = 4 * 1024 ** 2 # Sia sectors are a fixed 4 MiB + CONFIG = { 'TICKET_API_URL': 'http://10.10.10.45/create_ticket_api.php', 'TICKET_API_KEY': None, # Will be loaded from .env file @@ -133,6 +135,19 @@ class SystemHealthMonitor: r'.*mediafs.*', 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_RETENTION_DAYS': 30, 'INCLUDE_INFO_TICKETS': False, # Set True to create P5 tickets for INFO alerts @@ -4087,6 +4102,88 @@ class SystemHealthMonitor: lines.append(f"\nLXC Storage: check error ({len(lxc_health.get('issues', []))} issue(s))") 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 COALESCE(SUM(used_sectors), 0), COALESCE(SUM(total_sectors), 0) " + f"FROM storage_volumes WHERE disk_path LIKE '{managed['mountpoint']}/%';" + ) + 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 = (int(value) for value in result.stdout.strip().split('|')) + 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]: """ Check storage utilization for all running LXC containers @@ -4187,15 +4284,11 @@ class SystemHealthMonitor: container_info['filesystems'].append(filesystem) # Check 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) + managed = self._find_managed_volume(vmid, mountpoint) + if managed: + self._check_managed_volume(vmid, filesystem, managed, lxc_health) + else: + self._apply_lxc_thresholds(vmid, mountpoint, usage_percent, lxc_health) logger.debug(f"Filesystem details: {filesystem}") except Exception as e: diff --git a/tests/test_hwmon.py b/tests/test_hwmon.py index 0147dc7..bb9e46e 100644 --- a/tests/test_hwmon.py +++ b/tests/test_hwmon.py @@ -1,6 +1,7 @@ """Tests for SystemHealthMonitor pure methods — no external processes or filesystem.""" import sys import os +import subprocess import pytest @@ -605,3 +606,85 @@ class TestCpuSustainedGating: h = monitor._check_cpu_usage() assert h['status'] == 'WARNING' 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='1|2', 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='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='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='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='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': '0|0\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_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 == [] From 99d4350f4d223897ccf61a6963b1174363046b91 Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Fri, 6 Nov 2026 12:57:52 -0500 Subject: [PATCH 2/2] fix: filter hostd volumes in Python to avoid building SQL from a string Bandit 1.9.4 in CI flagged the query (B608). Select every volume with a static query and match the mountpoint in Python instead. Also stops a mount like /mnt/sia-other from matching /mnt/sia. Co-Authored-By: Claude Opus 5.5 --- hwmonDaemon.py | 12 +++++++----- tests/test_hwmon.py | 21 +++++++++++++++------ 2 files changed, 22 insertions(+), 11 deletions(-) diff --git a/hwmonDaemon.py b/hwmonDaemon.py index d09f56b..5a3fec9 100644 --- a/hwmonDaemon.py +++ b/hwmonDaemon.py @@ -4128,10 +4128,7 @@ class SystemHealthMonitor: Reading the database avoids needing the hostd API password on every node. Returns None if the usage cannot be read. """ - query = ( - "SELECT COALESCE(SUM(used_sectors), 0), COALESCE(SUM(total_sectors), 0) " - f"FROM storage_volumes WHERE disk_path LIKE '{managed['mountpoint']}/%';" - ) + 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], @@ -4143,7 +4140,12 @@ class SystemHealthMonitor: if result.returncode != 0: logger.warning(f"Could not read hostd usage for LXC {vmid}: {result.stderr.strip()}") return None - used_sectors, total_sectors = (int(value) for value in result.stdout.strip().split('|')) + 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 diff --git a/tests/test_hwmon.py b/tests/test_hwmon.py index bb9e46e..22dd2f8 100644 --- a/tests/test_hwmon.py +++ b/tests/test_hwmon.py @@ -615,7 +615,7 @@ 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='1|2', hostd_returncode=0, hostd_error=None): +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 = [] @@ -639,7 +639,7 @@ def _run_lxc_check(monitor, df_rows, hostd_stdout='1|2', hostd_returncode=0, hos 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='895045|3932160\n') + 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] @@ -648,26 +648,27 @@ class TestManagedVolumes: 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='3342336|3932160\n') + 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='3800000|3932160\n') + 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='895045|3932160\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': '0|0\n'}, + {'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): @@ -681,6 +682,14 @@ class TestManagedVolumes: 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"