feat: alert on Sia hostd usage instead of df for /mnt/sia
Lint / Python (flake8) (push) Successful in 2m6s
Lint / Notify on failure (push) Skipped
Security / Python Security (bandit) (push) Failing after 2m8s
Lint / Python (flake8) (pull_request) Successful in 1m22s
Lint / Notify on failure (pull_request) Skipped
Security / Python Security (bandit) (pull_request) Failing after 1m24s
Test / Python Tests (pytest) (pull_request) Successful in 1m21s
Test / Python Tests (pytest) (push) Successful in 1m19s
Lint / Python (flake8) (push) Successful in 2m6s
Lint / Notify on failure (push) Skipped
Security / Python Security (bandit) (push) Failing after 2m8s
Lint / Python (flake8) (pull_request) Successful in 1m22s
Lint / Notify on failure (pull_request) Skipped
Security / Python Security (bandit) (pull_request) Failing after 1m24s
Test / Python Tests (pytest) (pull_request) Successful in 1m21s
Test / Python Tests (pytest) (push) Successful in 1m19s
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 <noreply@anthropic.com>
This commit is contained in:
1 parent
86c7782b61
commit
d8f707ade7
3 files changed
+196
-10
No files matched your search
+103
-10
@@ -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:
|
||||
|
||||
Reference in new issue
Block a user