Security / Python Security (bandit) (push) Successful in 1m3s
Lint / Python (flake8) (push) Successful in 1m5s
Lint / Notify on failure (push) Skipped
Lint / Python (flake8) (pull_request) Successful in 1m16s
Lint / Notify on failure (pull_request) Skipped
Test / Python Tests (pytest) (push) Successful in 3m47s
Security / Python Security (bandit) (pull_request) Successful in 1m10s
Test / Python Tests (pytest) (pull_request) Successful in 1m45s
Running the map against Tinker's 140 hwmonDaemon tickets showed open ticket 357934698 (pbs ZFS DEGRADED) losing its key to a newer closed ticket for the same pool, which would have made the next report open a duplicate. Reports land on the open ticket today, so not-Closed now wins, then newest. Co-Authored-By: Claude Opus 5.5 <[email protected]>
1010 lines
50 KiB
Python
1010 lines
50 KiB
Python
"""Tests for SystemHealthMonitor pure methods — no external processes or filesystem."""
|
|
import sys
|
|
import os
|
|
import subprocess
|
|
import json
|
|
import re
|
|
|
|
import pytest
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
|
|
|
from unittest.mock import patch, MagicMock # noqa: E402
|
|
from hwmonDaemon import SystemHealthMonitor # noqa: E402
|
|
|
|
|
|
@pytest.fixture(scope='module')
|
|
def monitor():
|
|
"""Create a minimal monitor instance with all external side-effects patched out."""
|
|
with patch.object(SystemHealthMonitor, 'load_env_config'), \
|
|
patch.object(SystemHealthMonitor, '_check_tool_availability', return_value={}), \
|
|
patch('os.makedirs'):
|
|
return SystemHealthMonitor(dry_run=True)
|
|
|
|
|
|
# ── _format_bytes_human ──────────────────────────────────────────────────────
|
|
|
|
class TestFormatBytesHuman:
|
|
def test_bytes(self, monitor):
|
|
assert monitor._format_bytes_human(512) == '512.0 B'
|
|
|
|
def test_kilobytes(self, monitor):
|
|
assert monitor._format_bytes_human(1024) == '1.0 KB'
|
|
|
|
def test_megabytes(self, monitor):
|
|
assert monitor._format_bytes_human(1024 ** 2) == '1.0 MB'
|
|
|
|
def test_gigabytes(self, monitor):
|
|
assert monitor._format_bytes_human(1024 ** 3) == '1.0 GB'
|
|
|
|
def test_terabytes(self, monitor):
|
|
assert monitor._format_bytes_human(1024 ** 4) == '1.0 TB'
|
|
|
|
def test_fractional(self, monitor):
|
|
assert monitor._format_bytes_human(1536) == '1.5 KB'
|
|
|
|
def test_zero(self, monitor):
|
|
assert monitor._format_bytes_human(0) == '0.0 B'
|
|
|
|
|
|
# ── _parse_size ───────────────────────────────────────────────────────────────
|
|
|
|
class TestParseSize:
|
|
def test_gigabytes(self, monitor):
|
|
result = monitor._parse_size('15.7G')
|
|
assert abs(result - 15.7 * 1024**3) < 1
|
|
|
|
def test_terabytes(self, monitor):
|
|
result = monitor._parse_size('21.8T')
|
|
assert abs(result - 21.8 * 1024**4) < 1
|
|
|
|
def test_megabytes(self, monitor):
|
|
result = monitor._parse_size('512M')
|
|
assert result == 512 * 1024**2
|
|
|
|
def test_kilobytes(self, monitor):
|
|
result = monitor._parse_size('100K')
|
|
assert result == 100 * 1024
|
|
|
|
def test_bytes(self, monitor):
|
|
result = monitor._parse_size('100B')
|
|
assert result == 100
|
|
|
|
def test_invalid_returns_zero(self, monitor):
|
|
assert monitor._parse_size('notasize') == 0.0
|
|
|
|
def test_non_string_returns_zero(self, monitor):
|
|
assert monitor._parse_size(None) == 0.0
|
|
assert monitor._parse_size(42) == 0.0
|
|
|
|
|
|
# ── _parse_smart_value ────────────────────────────────────────────────────────
|
|
|
|
class TestParseSmartValue:
|
|
def test_plain_integer(self, monitor):
|
|
assert monitor._parse_smart_value('42') == 42
|
|
|
|
def test_temperature_with_celsius(self, monitor):
|
|
assert monitor._parse_smart_value('38 °C') == 38
|
|
|
|
def test_time_format(self, monitor):
|
|
assert monitor._parse_smart_value('15589h+17m+33.939s') == 15589
|
|
|
|
def test_hex_value(self, monitor):
|
|
assert monitor._parse_smart_value('0x0a') == 10
|
|
|
|
def test_invalid_returns_zero(self, monitor):
|
|
assert monitor._parse_smart_value('not_a_number') == 0
|
|
|
|
|
|
# ── _detect_manufacturer ──────────────────────────────────────────────────────
|
|
|
|
class TestDetectManufacturer:
|
|
def test_western_digital(self, monitor):
|
|
assert monitor._detect_manufacturer('WDC WD40EFRX') == 'Western Digital'
|
|
|
|
def test_hgst(self, monitor):
|
|
assert monitor._detect_manufacturer('HGST HUH728080ALE604') == 'Western Digital'
|
|
|
|
def test_seagate(self, monitor):
|
|
assert monitor._detect_manufacturer('ST4000DM004') == 'Seagate'
|
|
|
|
def test_samsung(self, monitor):
|
|
assert monitor._detect_manufacturer('Samsung SSD 870 EVO') == 'Samsung'
|
|
|
|
def test_intel(self, monitor):
|
|
assert monitor._detect_manufacturer('INTEL SSDSC2KB480G8') == 'Intel'
|
|
|
|
def test_micron(self, monitor):
|
|
assert monitor._detect_manufacturer('Crucial CT500MX500SSD1') == 'Micron'
|
|
|
|
def test_toshiba(self, monitor):
|
|
assert monitor._detect_manufacturer('TOSHIBA MG06ACA10TE') == 'Toshiba'
|
|
|
|
def test_unknown(self, monitor):
|
|
assert monitor._detect_manufacturer('GENERICDRIVE XYZ') == 'Unknown'
|
|
|
|
def test_empty_model(self, monitor):
|
|
assert monitor._detect_manufacturer('') == 'Unknown'
|
|
|
|
def test_none_model(self, monitor):
|
|
assert monitor._detect_manufacturer(None) == 'Unknown'
|
|
|
|
|
|
# ── _check_thermal_health ─────────────────────────────────────────────────────
|
|
|
|
class TestCheckThermalHealth:
|
|
def test_hdd_ok_temperature(self, monitor):
|
|
issues = monitor._check_thermal_health('sda', 45, 'HDD')
|
|
assert issues == []
|
|
|
|
def test_hdd_info_temperature(self, monitor):
|
|
issues = monitor._check_thermal_health('sda', 62, 'HDD')
|
|
assert len(issues) == 1
|
|
assert 'INFO' in issues[0]
|
|
|
|
def test_hdd_warning_temperature(self, monitor):
|
|
issues = monitor._check_thermal_health('sda', 66, 'HDD')
|
|
assert len(issues) == 1
|
|
assert 'WARNING' in issues[0]
|
|
|
|
def test_hdd_critical_temperature(self, monitor):
|
|
issues = monitor._check_thermal_health('sda', 76, 'HDD')
|
|
assert len(issues) == 1
|
|
assert 'CRITICAL' in issues[0]
|
|
|
|
def test_ssd_has_higher_warning_threshold(self, monitor):
|
|
# HDD warning=65°C, SSD warning=70°C; at 67°C:
|
|
# HDD → WARNING, SSD → INFO (above optimal_max=65 but below warning=70)
|
|
issues_hdd = monitor._check_thermal_health('sda', 67, 'HDD')
|
|
issues_ssd = monitor._check_thermal_health('sda', 67, 'SSD')
|
|
assert any('WARNING' in i for i in issues_hdd)
|
|
assert not any('WARNING' in i for i in issues_ssd)
|
|
assert any('INFO' in i for i in issues_ssd)
|
|
|
|
def test_none_temperature_returns_empty(self, monitor):
|
|
issues = monitor._check_thermal_health('sda', None, 'HDD')
|
|
assert issues == []
|
|
|
|
|
|
# ── _is_excluded_mount ────────────────────────────────────────────────────────
|
|
|
|
class TestIsExcludedMount:
|
|
def test_exact_excluded_mount(self, monitor):
|
|
assert monitor._is_excluded_mount('/media') is True
|
|
|
|
def test_pattern_excluded(self, monitor):
|
|
assert monitor._is_excluded_mount('/media/external') is True
|
|
|
|
def test_downloads_excluded(self, monitor):
|
|
assert monitor._is_excluded_mount('/mnt/data/downloads') is True
|
|
|
|
def test_normal_mount_not_excluded(self, monitor):
|
|
assert monitor._is_excluded_mount('/') is False
|
|
assert monitor._is_excluded_mount('/var') is False
|
|
assert monitor._is_excluded_mount('/mnt/ceph') is False
|
|
|
|
|
|
# ── _is_new_drive ─────────────────────────────────────────────────────────────
|
|
|
|
class TestIsNewDrive:
|
|
def test_brand_new_drive(self, monitor):
|
|
assert monitor._is_new_drive(0) is True
|
|
|
|
def test_one_hour_drive(self, monitor):
|
|
assert monitor._is_new_drive(1) is True
|
|
|
|
def test_under_threshold(self, monitor):
|
|
assert monitor._is_new_drive(719) is True
|
|
|
|
def test_at_threshold_is_not_new(self, monitor):
|
|
assert monitor._is_new_drive(720) is False
|
|
|
|
def test_old_drive(self, monitor):
|
|
assert monitor._is_new_drive(50000) is False
|
|
|
|
|
|
# ── _is_physical_disk ────────────────────────────────────────────────────────
|
|
|
|
class TestIsPhysicalDisk:
|
|
def test_real_sata_disk(self, monitor):
|
|
# /dev/sda should pass (no exclusion pattern matches)
|
|
# Note: _is_physical_disk also checks os.path.exists and reads sysfs,
|
|
# but the exclusion logic runs first and can return False early.
|
|
# We test the exclusion cases which are pure.
|
|
assert monitor._is_physical_disk('/dev/mapper/data') is False
|
|
|
|
def test_device_mapper_excluded(self, monitor):
|
|
assert monitor._is_physical_disk('/dev/dm-0') is False
|
|
|
|
def test_loop_device_excluded(self, monitor):
|
|
assert monitor._is_physical_disk('/dev/loop0') is False
|
|
|
|
def test_partition_excluded(self, monitor):
|
|
assert monitor._is_physical_disk('/dev/sda1') is False
|
|
|
|
def test_rbd_excluded(self, monitor):
|
|
assert monitor._is_physical_disk('/dev/rbd0') is False
|
|
|
|
|
|
# ── _get_manufacturer_profile ────────────────────────────────────────────────
|
|
|
|
class TestGetManufacturerProfile:
|
|
def test_seagate_model_matched(self, monitor):
|
|
profile = monitor._get_manufacturer_profile('ST4000DM004')
|
|
assert 'High_Fly_Writes' in profile['attributes']
|
|
|
|
def test_seagate_command_timeout_disabled(self, monitor):
|
|
profile = monitor._get_manufacturer_profile('ST4000DM004')
|
|
assert profile['attributes']['Command_Timeout']['monitor'] is False
|
|
|
|
def test_wd_model_matched(self, monitor):
|
|
profile = monitor._get_manufacturer_profile('WDC WD40EFRX')
|
|
assert profile['attributes']['Command_Timeout']['monitor'] is False
|
|
|
|
def test_samsung_model_matched(self, monitor):
|
|
profile = monitor._get_manufacturer_profile('Samsung SSD 870 EVO')
|
|
assert 'Program_Fail_Cnt_Total' in profile['attributes']
|
|
assert profile['attributes']['Program_Fail_Cnt_Total']['monitor'] is False
|
|
|
|
def test_samsung_erase_fail_chip_disabled(self, monitor):
|
|
profile = monitor._get_manufacturer_profile('Samsung SSD 870 EVO')
|
|
assert profile['attributes']['Erase_Fail_Count_Chip']['monitor'] is False
|
|
|
|
def test_toshiba_mg08_model_matched_by_prefix(self, monitor):
|
|
# MG08 prefix — model string without "TOSHIBA" word
|
|
profile = monitor._get_manufacturer_profile('MG08ACP16TE')
|
|
assert profile['attributes']['Command_Timeout']['monitor'] is True
|
|
assert profile['attributes']['Command_Timeout']['warning_threshold'] == 1000
|
|
|
|
def test_toshiba_command_timeout_raised_threshold(self, monitor):
|
|
profile = monitor._get_manufacturer_profile('TOSHIBA MG06ACA10TE')
|
|
assert profile['attributes']['Command_Timeout']['critical_threshold'] == 5000
|
|
|
|
def test_oos_model_matched(self, monitor):
|
|
profile = monitor._get_manufacturer_profile('OOS14000G')
|
|
assert profile['attributes']['Command_Timeout']['monitor'] is False
|
|
assert profile['attributes']['Seek_Error_Rate']['monitor'] is False
|
|
|
|
def test_ridata_firmware_match(self, monitor):
|
|
profile = monitor._get_manufacturer_profile('SSD 512GB', firmware='HT3618B7')
|
|
assert profile['attributes']['Erase_Fail_Count_Chip']['monitor'] is False
|
|
|
|
def test_unknown_model_returns_generic(self, monitor):
|
|
profile = monitor._get_manufacturer_profile('GENERICDRIVE XYZ')
|
|
assert profile is monitor.MANUFACTURER_SMART_PROFILES['Generic']
|
|
|
|
|
|
# ── _should_monitor_attribute ────────────────────────────────────────────────
|
|
|
|
class TestShouldMonitorAttribute:
|
|
def test_disabled_attribute_returns_false(self, monitor):
|
|
seagate = monitor._get_manufacturer_profile('ST4000DM004')
|
|
assert monitor._should_monitor_attribute('Command_Timeout', seagate) is False
|
|
|
|
def test_enabled_attribute_returns_true(self, monitor):
|
|
seagate = monitor._get_manufacturer_profile('ST4000DM004')
|
|
assert monitor._should_monitor_attribute('High_Fly_Writes', seagate) is True
|
|
|
|
def test_unknown_attribute_defaults_to_true(self, monitor):
|
|
seagate = monitor._get_manufacturer_profile('ST4000DM004')
|
|
assert monitor._should_monitor_attribute('Some_Unknown_Attr', seagate) is True
|
|
|
|
def test_none_profile_defaults_to_true(self, monitor):
|
|
assert monitor._should_monitor_attribute('Anything', None) is True
|
|
|
|
def test_samsung_program_fail_total_disabled(self, monitor):
|
|
samsung = monitor._get_manufacturer_profile('Samsung SSD 870 EVO')
|
|
assert monitor._should_monitor_attribute('Program_Fail_Cnt_Total', samsung) is False
|
|
|
|
|
|
# ── _get_attribute_thresholds ────────────────────────────────────────────────
|
|
|
|
class TestGetAttributeThresholds:
|
|
def test_seagate_high_fly_writes_thresholds(self, monitor):
|
|
seagate = monitor._get_manufacturer_profile('ST4000DM004')
|
|
t = monitor._get_attribute_thresholds('High_Fly_Writes', seagate)
|
|
assert t['warning'] == 100
|
|
assert t['critical'] == 500
|
|
|
|
def test_toshiba_command_timeout_thresholds(self, monitor):
|
|
toshiba = monitor._get_manufacturer_profile('MG08ACP16TE')
|
|
t = monitor._get_attribute_thresholds('Command_Timeout', toshiba)
|
|
assert t['warning'] == 1000
|
|
assert t['critical'] == 5000
|
|
|
|
def test_base_threshold_reallocated_sector(self, monitor):
|
|
generic = monitor.MANUFACTURER_SMART_PROFILES['Generic']
|
|
t = monitor._get_attribute_thresholds('Reallocated_Sector_Ct', generic)
|
|
assert t['warning'] == 5
|
|
assert t['critical'] == 10
|
|
|
|
def test_base_threshold_high_fly_writes_raised(self, monitor):
|
|
# Default (non-Seagate) High_Fly_Writes threshold is now 100/500
|
|
generic = monitor.MANUFACTURER_SMART_PROFILES['Generic']
|
|
t = monitor._get_attribute_thresholds('High_Fly_Writes', generic)
|
|
assert t['warning'] == 100
|
|
assert t['critical'] == 500
|
|
|
|
def test_unknown_attribute_returns_none(self, monitor):
|
|
generic = monitor.MANUFACTURER_SMART_PROFILES['Generic']
|
|
assert monitor._get_attribute_thresholds('Made_Up_Attribute', generic) is None
|
|
|
|
def test_behavior_defaults_to_countup(self, monitor):
|
|
generic = monitor.MANUFACTURER_SMART_PROFILES['Generic']
|
|
t = monitor._get_attribute_thresholds('Reallocated_Sector_Ct', generic)
|
|
assert t['behavior'] == 'countup'
|
|
|
|
|
|
# ── _get_issue_type ───────────────────────────────────────────────────────────
|
|
|
|
class TestGetIssueType:
|
|
def test_smart_issue(self, monitor):
|
|
assert monitor._get_issue_type('SMART attribute warning on /dev/sda') == 'SMART Health Issue'
|
|
|
|
def test_drive_issue(self, monitor):
|
|
assert monitor._get_issue_type('Drive /dev/sdb has reallocated sectors') == 'Storage Issue'
|
|
|
|
def test_ceph_issue(self, monitor):
|
|
assert monitor._get_issue_type('Ceph cluster is HEALTH_WARN') == 'Ceph Cluster Issue'
|
|
|
|
def test_ecc_issue(self, monitor):
|
|
assert monitor._get_issue_type('ECC memory errors detected') == 'Memory Issue'
|
|
|
|
def test_cpu_issue(self, monitor):
|
|
assert monitor._get_issue_type('CPU usage at 95%') == 'Performance Issue'
|
|
|
|
def test_network_issue(self, monitor):
|
|
assert monitor._get_issue_type('Network interface eth0 down') == 'Network Issue'
|
|
|
|
def test_lxc_issue(self, monitor):
|
|
assert monitor._get_issue_type('LXC container storage usage at 90%') == 'Container Storage Issue'
|
|
|
|
def test_unknown_defaults_to_hardware(self, monitor):
|
|
assert monitor._get_issue_type('Something completely unknown') == 'Hardware Issue'
|
|
|
|
|
|
# ── _get_impact_level ─────────────────────────────────────────────────────────
|
|
|
|
class TestGetImpactLevel:
|
|
def test_critical_issue(self, monitor):
|
|
level = monitor._get_impact_level('CRITICAL: drive failure imminent')
|
|
assert '[CRIT]' in level
|
|
|
|
def test_unhealthy_is_critical(self, monitor):
|
|
level = monitor._get_impact_level('Ceph is UNHEALTHY')
|
|
assert '[CRIT]' in level
|
|
|
|
def test_warning_issue(self, monitor):
|
|
level = monitor._get_impact_level('WARNING: temperature elevated')
|
|
assert '[WARN]' in level
|
|
|
|
def test_storage_usage_is_warn_not_crit(self, monitor):
|
|
# "STORAGE USAGE" keyword takes priority over "CRITICAL" substring check
|
|
level = monitor._get_impact_level('CRITICAL storage usage at 95%')
|
|
assert '[WARN]' in level
|
|
|
|
def test_cpu_usage_is_warn(self, monitor):
|
|
level = monitor._get_impact_level('CPU usage at 80% threshold exceeded')
|
|
assert '[WARN]' in level
|
|
|
|
def test_low_priority(self, monitor):
|
|
level = monitor._get_impact_level('Informational: drive age notification')
|
|
assert '[LOW]' in level
|
|
|
|
def test_health_err_is_critical(self, monitor):
|
|
level = monitor._get_impact_level('Ceph status: HEALTH_ERR')
|
|
assert '[CRIT]' in level
|
|
|
|
def test_down_is_warning(self, monitor):
|
|
level = monitor._get_impact_level('OSD.3 is DOWN')
|
|
assert '[WARN]' in level
|
|
|
|
|
|
# ── _categorize_issue ─────────────────────────────────────────────────────────
|
|
|
|
class TestCategorizeIssue:
|
|
def test_smart_critical_is_hardware_issue(self, monitor):
|
|
cat, ttype, _, _ = monitor._categorize_issue('SMART critical error on /dev/sda')
|
|
assert cat == monitor.TICKET_CATEGORIES['HARDWARE']
|
|
assert ttype == monitor.TICKET_TYPES['ISSUE']
|
|
|
|
def test_smart_warning_is_hardware_problem(self, monitor):
|
|
cat, ttype, _, _ = monitor._categorize_issue('SMART warning: High_Fly_Writes elevated')
|
|
assert cat == monitor.TICKET_CATEGORIES['HARDWARE']
|
|
assert ttype == monitor.TICKET_TYPES['PROBLEM']
|
|
|
|
def test_lxc_critical_is_software_issue(self, monitor):
|
|
cat, ttype, _, _ = monitor._categorize_issue('LXC container storage critical')
|
|
assert cat == monitor.TICKET_CATEGORIES['SOFTWARE']
|
|
assert ttype == monitor.TICKET_TYPES['ISSUE']
|
|
|
|
def test_temperature_is_hardware(self, monitor):
|
|
cat, _, _, _ = monitor._categorize_issue('temperature warning on /dev/sdb')
|
|
assert cat == monitor.TICKET_CATEGORIES['HARDWARE']
|
|
|
|
def test_nvme_is_hardware(self, monitor):
|
|
cat, _, _, _ = monitor._categorize_issue('NVMe drive warning on /dev/nvme0')
|
|
assert cat == monitor.TICKET_CATEGORIES['HARDWARE']
|
|
|
|
|
|
# ── _check_system_drive_indicators (dmesg scan) ───────────────────────────────
|
|
|
|
def _dmesg(monitor, lines):
|
|
"""Run _check_system_drive_indicators with a faked `dmesg` output."""
|
|
fake = MagicMock(returncode=0, stdout='\n'.join(lines), stderr='')
|
|
with patch('subprocess.run', return_value=fake):
|
|
return monitor._check_system_drive_indicators()
|
|
|
|
|
|
class TestSystemDriveIndicators:
|
|
def test_rbd_buffer_io_errors_are_ignored(self, monitor):
|
|
"""Ceph RBD Buffer I/O errors are storage-connectivity, not local hardware —
|
|
they must not raise a CRITICAL drive alert (regression for the false
|
|
'[hardware] CRITICAL: Buffer I/O errors' ticket)."""
|
|
lines = [
|
|
f'[Wed Jul 15 03:2{i}:51 2026] Buffer I/O error on dev rbd2, '
|
|
'logical block 8999, lost sync page write'
|
|
for i in range(75)
|
|
]
|
|
res = _dmesg(monitor, lines)
|
|
assert res['status'] == 'OK'
|
|
assert res['issues'] == []
|
|
|
|
def test_local_disk_buffer_io_errors_still_counted(self, monitor):
|
|
"""Genuine local-disk Buffer I/O errors must still be reported."""
|
|
lines = [
|
|
f'[Wed Jul 15 03:30:0{i} 2026] Buffer I/O error on dev sda1, '
|
|
'logical block 42, lost async page write'
|
|
for i in range(5)
|
|
]
|
|
res = _dmesg(monitor, lines)
|
|
assert res['status'] == 'CRITICAL'
|
|
assert any('Buffer I/O errors' in i and '5 occurrences' in i for i in res['issues'])
|
|
|
|
def test_rbd_noise_does_not_inflate_real_errors(self, monitor):
|
|
"""RBD errors mixed with real disk errors: only the real ones count."""
|
|
lines = [f'Buffer I/O error on dev rbd4, logical block {i}, lost sync page write'
|
|
for i in range(75)]
|
|
lines += [
|
|
'Buffer I/O error on dev sda1, logical block 1, lost async page write',
|
|
'Buffer I/O error on dev sda1, logical block 2, lost async page write',
|
|
]
|
|
res = _dmesg(monitor, lines)
|
|
# 2 real occurrences → WARNING (>=2), not CRITICAL (>=5)
|
|
assert res['status'] == 'WARNING'
|
|
assert any('Buffer I/O errors' in i and '2 occurrences' in i for i in res['issues'])
|
|
|
|
def test_device_mapper_and_loop_ignored(self, monitor):
|
|
"""Device-mapper and loop devices are also non-physical and ignored."""
|
|
lines = [
|
|
'Buffer I/O error on dev dm-3, logical block 5, lost sync page write',
|
|
'Buffer I/O error on dev loop0, logical block 6, lost sync page write',
|
|
]
|
|
res = _dmesg(monitor, lines)
|
|
assert res['status'] == 'OK'
|
|
assert res['issues'] == []
|
|
|
|
|
|
# ── _get_attribute_thresholds (drive age is not ticketed) ─────────────────────
|
|
|
|
class TestAttributeThresholds:
|
|
def test_power_on_hours_has_no_threshold(self, monitor):
|
|
"""Drive age must not raise a ticket: we run to hard-failure (Ceph redundancy +
|
|
PBS backups), so Power_On_Hours has no warning/critical threshold. Regression for
|
|
the '[hardware] Drive ... has SMART issues: Warning Power_On_Hours' age tickets."""
|
|
assert monitor._get_attribute_thresholds('Power_On_Hours', {}) is None
|
|
|
|
def test_real_failure_predictors_still_alert(self, monitor):
|
|
"""Genuine failure-predictor attributes must keep their thresholds."""
|
|
for attr in ('Reallocated_Sector_Ct', 'Current_Pending_Sector',
|
|
'Offline_Uncorrectable', 'Reported_Uncorrect'):
|
|
th = monitor._get_attribute_thresholds(attr, {})
|
|
assert th is not None and 'warning' in th and 'critical' in th
|
|
|
|
def test_power_on_hours_still_recorded_for_new_drive_logic(self, monitor):
|
|
"""Age is still *tracked* (just not ticketed) — new-drive detection must work."""
|
|
assert monitor._is_new_drive(100) is True # ~4 days
|
|
assert monitor._is_new_drive(64860) is False # ~7.4 years
|
|
|
|
|
|
# ── _format_lxc_dry_run (LXC storage shown in --dry-run summary; issue #23) ────
|
|
|
|
class TestLxcDryRunSummary:
|
|
def test_includes_container_usage_and_flags_over_threshold(self, monitor):
|
|
"""Regression for issue #23: dry-run summary must surface LXC storage."""
|
|
lxc = {
|
|
'status': 'WARNING',
|
|
'issues': ['LXC 105 high storage usage: 84.0% on /'],
|
|
'containers': [
|
|
{'vmid': '105', 'filesystems': [{'mountpoint': '/', 'usage_percent': 84.0}]},
|
|
],
|
|
}
|
|
text = '\n'.join(monitor._format_lxc_dry_run(lxc))
|
|
assert 'LXC Storage:' in text
|
|
assert 'CT105 /' in text and '84.0% used' in text
|
|
assert '⚠️' in text # flagged: over the 80% warning threshold
|
|
assert 'Issues: 1 found' in text
|
|
|
|
def test_healthy_container_not_flagged(self, monitor):
|
|
lxc = {'status': 'OK', 'issues': [],
|
|
'containers': [{'vmid': '119', 'filesystems': [{'mountpoint': '/', 'usage_percent': 26.0}]}]}
|
|
text = '\n'.join(monitor._format_lxc_dry_run(lxc))
|
|
assert 'CT119 /' in text and '26.0% used' in text
|
|
assert '⚠️' not in text
|
|
|
|
def test_empty_when_no_containers(self, monitor):
|
|
assert monitor._format_lxc_dry_run({'status': 'OK', 'containers': [], 'issues': []}) == []
|
|
|
|
def test_error_status_is_reported(self, monitor):
|
|
lines = monitor._format_lxc_dry_run({'status': 'ERROR', 'containers': [], 'issues': ['boom']})
|
|
assert any('check error' in ln for ln in lines)
|
|
|
|
|
|
# ── _check_cpu_usage (ticket on sustained load, not transient spikes) ──────────
|
|
|
|
def _cpu(monitor, instantaneous, load15, cpu_count=4):
|
|
"""Run _check_cpu_usage with mocked psutil + load average."""
|
|
with patch('psutil.cpu_percent', return_value=instantaneous), \
|
|
patch('psutil.cpu_count', return_value=cpu_count), \
|
|
patch('os.getloadavg', return_value=(load15, load15, load15)):
|
|
return monitor._check_cpu_usage()
|
|
|
|
|
|
def _report_with_cpu(cpu_health):
|
|
"""Minimal health_report skeleton (all sections empty) with cpu_health overridden,
|
|
sufficient for _detect_issues which direct-indexes several sections for logging."""
|
|
return {
|
|
'drives_health': {'drives': [], 'overall_status': 'HEALTHY'},
|
|
'memory_health': {'status': 'OK'},
|
|
'cpu_health': cpu_health,
|
|
'network_health': {'management_network': {}, 'ceph_network': {}},
|
|
'ceph_health': {},
|
|
'lxc_health': {'status': 'OK', 'issues': []},
|
|
'system_health': {'status': 'OK', 'issues': []},
|
|
'pbs_health': {},
|
|
}
|
|
|
|
|
|
class TestCpuSustainedGating:
|
|
def test_transient_spike_does_not_warn(self, monitor):
|
|
"""Instantaneous 100% but low 15-min load (e.g. 0.4/core = 10%) -> OK, no ticket."""
|
|
h = _cpu(monitor, instantaneous=100.0, load15=1.6, cpu_count=4) # 1.6/4 = 40%/core
|
|
assert h['status'] == 'OK'
|
|
assert h['sustained_high'] is False
|
|
assert h['cpu_usage_percent'] == 100.0 # still reported for context
|
|
assert h['load15_per_core_percent'] == 40.0
|
|
|
|
def test_sustained_high_load_warns(self, monitor):
|
|
"""15-min load 3.9/4 cores = 97.5%/core >= 95% threshold -> WARNING."""
|
|
h = _cpu(monitor, instantaneous=20.0, load15=3.9, cpu_count=4)
|
|
assert h['status'] == 'WARNING'
|
|
assert h['sustained_high'] is True
|
|
assert h['load15_per_core_percent'] == 97.5
|
|
|
|
def test_detect_issues_ignores_transient_spike(self, monitor):
|
|
"""A high instantaneous sample with sustained_high False must not create a CPU issue."""
|
|
report = _report_with_cpu({'cpu_usage_percent': 99.0, 'sustained_high': False,
|
|
'load15_per_core_percent': 30.0, 'status': 'OK'})
|
|
issues = monitor._detect_issues(report)
|
|
assert not any('CPU' in i for i in issues)
|
|
|
|
def test_detect_issues_flags_sustained(self, monitor):
|
|
"""sustained_high True must create exactly one stable, value-free CPU issue."""
|
|
report = _report_with_cpu({'cpu_usage_percent': 96.0, 'sustained_high': True,
|
|
'load15_per_core_percent': 98.0, 'status': 'WARNING'})
|
|
issues = monitor._detect_issues(report)
|
|
cpu_issues = [i for i in issues if 'CPU' in i]
|
|
assert len(cpu_issues) == 1
|
|
# Title-stable: no measured value baked into the message (only the threshold constant)
|
|
assert '98' not in cpu_issues[0]
|
|
assert 'sustained' in cpu_issues[0].lower()
|
|
|
|
def test_falls_back_to_instantaneous_without_loadavg(self, monitor):
|
|
"""If os.getloadavg is unavailable, don't go silent — use the instantaneous sample."""
|
|
with patch('psutil.cpu_percent', return_value=97.0), \
|
|
patch('psutil.cpu_count', return_value=4), \
|
|
patch('os.getloadavg', side_effect=OSError):
|
|
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='/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 == []
|
|
|
|
|
|
# ── #42: [hwmon] title tag, footer, per-check ticket switches ────────────────
|
|
|
|
def _report(**overrides):
|
|
report = _report_with_cpu({'cpu_usage_percent': 10.0, 'sustained_high': False,
|
|
'load15_per_core_percent': 10.0, 'status': 'OK'})
|
|
report.update(overrides)
|
|
return report
|
|
|
|
|
|
def _sent_payloads(monitor, issues, report=None):
|
|
"""Run _create_tickets_for_issues for real (not dry-run) with the API mocked."""
|
|
response = MagicMock()
|
|
response.json.return_value = {'success': True, 'ticket_id': '1'}
|
|
with patch.object(monitor, 'dry_run', False), \
|
|
patch.object(monitor, '_detect_issues', return_value=issues), \
|
|
patch('socket.gethostname', return_value='node-a'), \
|
|
patch('requests.post', return_value=response) as post:
|
|
monitor._create_tickets_for_issues(report or _report())
|
|
return [c.kwargs['json'] for c in post.call_args_list]
|
|
|
|
|
|
NET_DOWN = {
|
|
'management_network': {'status': 'CRITICAL', 'issues': ['Management network is unreachable']},
|
|
'ceph_network': {'status': 'OK', 'issues': []},
|
|
}
|
|
LXC_CRIT = {'status': 'CRITICAL', 'issues': ['LXC 101 critical storage usage on /']}
|
|
CPU_HIGH = {'cpu_usage_percent': 99.0, 'sustained_high': True,
|
|
'load15_per_core_percent': 99.0, 'status': 'WARNING'}
|
|
|
|
|
|
class TestHwmonTitleTag:
|
|
def test_title_has_app_tag_after_auto(self, monitor):
|
|
[payload] = _sent_payloads(monitor, ['CPU usage sustained above threshold of 95%'])
|
|
assert payload['title'].startswith('[node-a][auto][hwmon][software] ')
|
|
|
|
def test_cluster_wide_title_keeps_cluster_source(self, monitor):
|
|
[payload] = _sent_payloads(monitor, ['[cluster-wide] [ceph] Ceph HEALTH_WARN: clock skew detected'])
|
|
assert payload['title'].startswith('[proxmox-cluster][auto][hwmon][ceph] ')
|
|
|
|
def test_description_footer_names_hwmon(self, monitor):
|
|
[payload] = _sent_payloads(monitor, ['CPU usage sustained above threshold of 95%'])
|
|
assert payload['description'].rstrip().endswith('Reported automatically by hwmonDaemon on node-a.')
|
|
|
|
|
|
class TestCheckSwitches:
|
|
@pytest.mark.parametrize('switch, section, value, needle', [
|
|
('CPU_ENABLED', 'cpu_health', CPU_HIGH, 'CPU usage'),
|
|
('NETWORK_ENABLED', 'network_health', NET_DOWN, 'Management network'),
|
|
('LXC_STORAGE_ENABLED', 'lxc_health', LXC_CRIT, 'LXC 101'),
|
|
])
|
|
def test_switch_controls_tickets(self, monitor, switch, section, value, needle):
|
|
report = _report(**{section: value})
|
|
assert any(needle in i for i in monitor._detect_issues(report))
|
|
with patch.dict(SystemHealthMonitor.CONFIG, {switch: False}):
|
|
assert not any(needle in i for i in monitor._detect_issues(report))
|
|
|
|
def test_switches_default_on(self):
|
|
assert all(SystemHealthMonitor.CONFIG[s] is True for s in SystemHealthMonitor.CHECK_SWITCHES)
|
|
|
|
def test_disabled_checks_do_not_escalate(self, monitor):
|
|
report = _report(network_health=NET_DOWN, lxc_health=LXC_CRIT)
|
|
assert monitor._count_critical_issues(report) == 2
|
|
with patch.dict(SystemHealthMonitor.CONFIG, {'NETWORK_ENABLED': False, 'LXC_STORAGE_ENABLED': False}):
|
|
assert monitor._count_critical_issues(report) == 0
|
|
|
|
def test_other_checks_unaffected(self, monitor):
|
|
report = _report(memory_health={'status': 'CRITICAL', 'has_ecc': True,
|
|
'ecc_errors': ['ECC errors detected']})
|
|
with patch.dict(SystemHealthMonitor.CONFIG, {s: False for s in SystemHealthMonitor.CHECK_SWITCHES}):
|
|
assert 'ECC errors detected' in monitor._detect_issues(report)
|
|
|
|
|
|
def _load_env(text):
|
|
from unittest.mock import mock_open
|
|
with patch('os.path.exists', return_value=True), \
|
|
patch('builtins.open', mock_open(read_data=text)):
|
|
SystemHealthMonitor.load_env_config()
|
|
|
|
|
|
class TestSwitchEnvParsing:
|
|
@pytest.mark.parametrize('raw, expected', [
|
|
('false', False), ('0', False), ('no', False), ('OFF', False),
|
|
('true', True), ('1', True), ('Yes', True), ('on', True),
|
|
])
|
|
def test_values(self, raw, expected):
|
|
with patch.dict(SystemHealthMonitor.CONFIG):
|
|
SystemHealthMonitor.CONFIG['CPU_ENABLED'] = not expected
|
|
_load_env(f'CPU_ENABLED={raw}\n')
|
|
assert SystemHealthMonitor.CONFIG['CPU_ENABLED'] is expected
|
|
|
|
def test_typo_leaves_check_on(self):
|
|
with patch.dict(SystemHealthMonitor.CONFIG):
|
|
_load_env('LXC_STORAGE_ENABLED=flase\nNETWORK_ENABLED=false\n')
|
|
assert SystemHealthMonitor.CONFIG['LXC_STORAGE_ENABLED'] is True
|
|
assert SystemHealthMonitor.CONFIG['NETWORK_ENABLED'] is False
|
|
|
|
|
|
# ── #42 part 4: dedup_key ────────────────────────────────────────────────────
|
|
|
|
sys.path.insert(0, os.path.join(os.path.dirname(os.path.dirname(__file__)), 'scripts'))
|
|
import dedup_key_map # noqa: E402
|
|
|
|
KEY_CASES = [
|
|
# (raw issue as _detect_issues produces it, ceph code the daemon reads, expected key)
|
|
('Drive WD-WCC4N2FYYCXP has SMART issues: Warning Reallocated_Sector_Ct: 8', None,
|
|
'drive:WD-WCC4N2FYYCXP:smart'),
|
|
('Drive /dev/sdb has SMART issues: SMART overall health check failed', None, 'host:node-a:drive_sdb:smart'),
|
|
('Drive S3Z1NB0K123456 temperature is high: 66°C', None, 'drive:S3Z1NB0K123456:temperature'),
|
|
('Uncorrectable ECC errors detected in mc0: 3', None, 'host:node-a:ecc'),
|
|
('Correctable ECC errors detected in mc1: 12', None, 'host:node-a:ecc'),
|
|
('CPU usage sustained above threshold of 95%', None, 'host:node-a:cpu'),
|
|
('Management network is unreachable', None, 'host:node-a:mgmt_net_unreachable'),
|
|
('Ceph network is unreachable', None, 'host:node-a:ceph_net_unreachable'),
|
|
('LXC 101 high storage usage: 83.2% on /', None, 'lxc:101:storage:root'),
|
|
('LXC 141 critical storage usage: 96.0% on /mnt/sia', None, 'lxc:141:storage:mnt_sia'),
|
|
('LXC 141 critical storage usage: filesystem nearly out of space on /mnt/sia', None, 'lxc:141:storage:mnt_sia'),
|
|
('CRITICAL: ATA command failures in system logs (7 occurrences)', None, 'host:node-a:syslog:ata_command_failures'),
|
|
('WARNING: ATA command failures in system logs (2 occurrences)', None, 'host:node-a:syslog:ata_command_failures'),
|
|
('[cluster-wide] [ceph] Ceph HEALTH_WARN: 2 OSD(s) experiencing slow operations in BlueStore',
|
|
'BLUESTORE_SLOW_OP_ALERT', 'cluster:ceph:BLUESTORE_SLOW_OP_ALERT'),
|
|
('[cluster-wide] [ceph] Ceph HEALTH_WARN: 2 daemons have recently crashed', 'RECENT_CRASH',
|
|
'cluster:ceph:RECENT_CRASH'),
|
|
('[cluster-wide] [ceph] Ceph HEALTH_WARN: 1 pgs not scrubbed in time', 'PG_NOT_SCRUBBED',
|
|
'cluster:ceph:PG_NOT_SCRUBBED'),
|
|
('[cluster-wide] [ceph] Ceph HEALTH_WARN: 4 pgs not deep-scrubbed in time', 'PG_NOT_DEEP_SCRUBBED',
|
|
'cluster:ceph:PG_NOT_DEEP_SCRUBBED'),
|
|
('[cluster-wide] [ceph] Ceph HEALTH_WARN: Degraded data redundancy: 1/9 objects degraded (11%), 3 pgs degraded',
|
|
'PG_DEGRADED', 'cluster:ceph:PG_DEGRADED'),
|
|
('[cluster-wide] [ceph] Ceph HEALTH_WARN: insufficient standby MDS daemons available',
|
|
'MDS_INSUFFICIENT_STANDBY', 'cluster:ceph:MDS_INSUFFICIENT_STANDBY'),
|
|
('[cluster-wide] [ceph] Ceph HEALTH_WARN: 1 host (7 osds) down', 'OSD_HOST_DOWN', 'cluster:ceph:OSD_HOST_DOWN'),
|
|
('[cluster-wide] [ceph] Ceph HEALTH_WARN: 7 osds down', 'OSD_DOWN', 'cluster:ceph:OSD_DOWN'),
|
|
('[cluster-wide] [ceph] Ceph HEALTH_WARN: 1/3 mons down, quorum a,b', 'MON_DOWN', 'cluster:ceph:MON_DOWN'),
|
|
('[cluster-wide] [ceph] Ceph cluster usage warning: 72.4%', None, 'cluster:ceph:usage'),
|
|
('[cluster-wide] [ceph] Ceph cluster HEALTH_ERR: Unknown error', None, 'cluster:ceph:HEALTH_ERR'),
|
|
('[cluster-wide] [ceph] Ceph OSD osd.12 is DOWN', None, 'cluster:ceph_osd:osd.12:down'),
|
|
('[ceph] Ceph health check timed out', None, 'host:node-a:ceph_check_failed'),
|
|
("[pbs] ZFS pool 'halfTbNVMeMirror' state: DEGRADED", None, 'pbs:zfs:halfTbNVMeMirror:state'),
|
|
("[pbs] ZFS pool 'halfTbNVMeMirror' usage high: 84.0%", None, 'pbs:zfs:halfTbNVMeMirror:usage'),
|
|
("[pbs] ZFS pool 'tank' has errors: errors: 2 data errors", None, 'pbs:zfs:tank:errors'),
|
|
('[pbs] PBS backup failed: UPID:pbs:1 - error', None, 'pbs:task:backup:failed'),
|
|
]
|
|
|
|
|
|
def _sent_with_codes(monitor, issue, code):
|
|
report = _report(ceph_health={'check_codes': {re.sub(r'\[(?:cluster-wide|ceph)\]\s*', '', issue).strip(): code}}
|
|
if code else {})
|
|
with patch.object(monitor, '_get_drive_details', return_value={'serial': None, 'capacity': None}):
|
|
[payload] = _sent_payloads(monitor, [issue], report)
|
|
return payload
|
|
|
|
|
|
class TestDedupKey:
|
|
@pytest.mark.parametrize('issue, code, expected', KEY_CASES)
|
|
def test_key(self, issue, code, expected):
|
|
assert SystemHealthMonitor.dedup_key_for(issue, 'node-a', ceph_code=code) == expected
|
|
|
|
@pytest.mark.parametrize('issue, code, expected', KEY_CASES)
|
|
def test_daemon_sends_key(self, monitor, issue, code, expected):
|
|
assert _sent_with_codes(monitor, issue, code)['dedup_key'] == expected
|
|
|
|
@pytest.mark.parametrize('issue, code, expected', KEY_CASES)
|
|
def test_backfill_recovers_same_key_from_title(self, monitor, issue, code, expected):
|
|
"""The key the map script derives from a title must equal the key the daemon sent,
|
|
or the first keyed report opens a duplicate of the backfilled ticket."""
|
|
payload = _sent_with_codes(monitor, issue, code)
|
|
for title in (payload['title'], payload['title'].replace('[hwmon]', '')): # new and pre-#43 titles
|
|
source, summary = dedup_key_map.parse_title(title)
|
|
assert SystemHealthMonitor.dedup_key_for(summary, source) == payload['dedup_key']
|
|
|
|
def test_daemon_uses_live_ceph_code_over_table(self, monitor):
|
|
payload = _sent_with_codes(monitor, '[cluster-wide] [ceph] Ceph HEALTH_WARN: something new', 'NEW_CHECK')
|
|
assert payload['dedup_key'] == 'cluster:ceph:NEW_CHECK'
|
|
|
|
def test_unknown_issue_sends_no_key(self, monitor):
|
|
assert SystemHealthMonitor.dedup_key_for('Something nobody planned for', 'node-a') is None
|
|
assert 'dedup_key' not in _sent_with_codes(monitor, 'Something nobody planned for', None)
|
|
|
|
def test_keys_are_valid_for_tinker(self):
|
|
pattern = re.compile(r'^[A-Za-z0-9_.:-]{1,128}$') # TicketHash::KEY_PATTERN
|
|
weird = SystemHealthMonitor.dedup_key_for('Drive AB/12:x has SMART issues', 'host name')
|
|
assert weird == 'drive:AB_12_x:smart'
|
|
assert pattern.match(weird)
|
|
for issue, code, _ in KEY_CASES:
|
|
assert pattern.match(SystemHealthMonitor.dedup_key_for(issue, 'node-a', ceph_code=code))
|
|
|
|
|
|
def _t(tid, title, created, status='Open'):
|
|
return {'ticket_id': tid, 'title': title, 'created_at': created, 'status': status}
|
|
|
|
|
|
CPU_TITLE = '[{h}][auto][software] CPU usage sustained above threshold of 95%[single-node][production][problem]'
|
|
|
|
|
|
class TestDedupKeyMap:
|
|
def test_parse_title_with_size_tag_and_pbs_marker(self):
|
|
assert dedup_key_map.parse_title(
|
|
'[cs-01][auto][hwmon][hardware][3.00 TB] Drive WD-X has SMART issues[single-node][production][problem]'
|
|
) == ('cs-01', 'Drive WD-X has SMART issues')
|
|
assert dedup_key_map.parse_title(
|
|
"[pbs][auto][hardware] [pbs] ZFS pool 'p' state: DEGRADED[single-node][production][problem]"
|
|
) == ('pbs', "[pbs] ZFS pool 'p' state: DEGRADED")
|
|
|
|
def test_manual_tickets_are_not_parsed(self):
|
|
assert dedup_key_map.parse_title('[storage-01][manual][hardware] Platform swap [single-node][production]') is None
|
|
|
|
def test_newest_ticket_gets_the_key(self):
|
|
key_map, unmapped, superseded = dedup_key_map.build_map([
|
|
_t('111', CPU_TITLE.format(h='a'), '2026-01-01 00:00:00', 'Closed'),
|
|
_t('222', CPU_TITLE.format(h='a'), '2026-06-01 00:00:00'),
|
|
_t('333', CPU_TITLE.format(h='b'), '2026-03-01 00:00:00', 'Closed'),
|
|
])
|
|
assert key_map == {'222': 'host:a:cpu', '333': 'host:b:cpu'}
|
|
assert [(s['ticket_id'], s['kept']) for s in superseded] == [('111', '222')]
|
|
assert unmapped == []
|
|
|
|
def test_open_ticket_beats_newer_closed_one(self):
|
|
"""An open ticket is where reports land today, so it keeps the key even when a
|
|
newer closed ticket has the same one (pbs ZFS DEGRADED, 2026-11-28)."""
|
|
zfs = "[pbs][auto][hardware] [pbs] ZFS pool 'p' state: DEGRADED[single-node][production][problem]"
|
|
key_map, _, superseded = dedup_key_map.build_map([
|
|
_t('357934698', zfs, '2026-02-10 13:29:04', 'Open'),
|
|
_t('883031791', zfs, '2026-04-06 18:00:37', 'Closed'),
|
|
])
|
|
assert key_map == {'357934698': 'pbs:zfs:p:state'}
|
|
assert superseded[0]['ticket_id'] == '883031791'
|
|
|
|
def test_unmapped_reported_and_exit_code(self, tmp_path, capsys):
|
|
f = tmp_path / 'tickets.json'
|
|
f.write_text(json.dumps({'tickets': [
|
|
_t('1', CPU_TITLE.format(h='a'), '2026-01-01'),
|
|
_t('2', '[a][auto][software] Ceph HEALTH_WARN: brand new warning[cluster-wide][production][problem]',
|
|
'2026-01-02'),
|
|
]}))
|
|
out = tmp_path / 'map.json'
|
|
assert dedup_key_map.main(['--from-json', str(f), '--out', str(out)]) == 1
|
|
assert json.loads(out.read_text()) == {'1': 'host:a:cpu'}
|
|
assert 'UNMAPPED 2' in capsys.readouterr().err
|
|
|
|
|
|
# Real titles from Tinker (2026-11-28), including pre-#43 and pre-July wording
|
|
REAL_TITLES = [
|
|
('[proxmox-cluster][auto][ceph] Ceph HEALTH_WARN: OSD(s) experiencing slow operations in BlueStore'
|
|
'[cluster-wide][production][problem]', 'cluster:ceph:BLUESTORE_SLOW_OP_ALERT'),
|
|
('[proxmox-cluster][auto][software] Ceph HEALTH_WARN: 2 daemons have recently crashed[cluster-wide][production][problem]',
|
|
'cluster:ceph:RECENT_CRASH'),
|
|
('[proxmox-cluster][auto][ceph] Ceph HEALTH_WARN: Degraded data redundancy: 12892962/53384008 objects degraded '
|
|
'(24.151%), 359 pgs degraded, 359 pgs undersized[cluster-wide][production][problem]', 'cluster:ceph:PG_DEGRADED'),
|
|
('[proxmox-cluster][auto][ceph] Ceph HEALTH_WARN: OSD(s) experiencing stalled read in db device of BlueFS'
|
|
'[cluster-wide][production][problem]', 'cluster:ceph:DB_DEVICE_STALLED_READ_ALERT'),
|
|
('[proxmox-cluster][auto][ceph] Ceph HEALTH_WARN: Reduced data availability: 47 pgs inactive, 15 pgs down'
|
|
'[cluster-wide][production][issue]', 'cluster:ceph:PG_AVAILABILITY'),
|
|
('[proxmox-cluster][auto][ceph] Ceph HEALTH_WARN: 1/3 mons down, quorum storage-01,compute-storage-gpu-01'
|
|
'[cluster-wide][production][issue]', 'cluster:ceph:MON_DOWN'),
|
|
('[proxmox-cluster][auto][ceph] Ceph HEALTH_WARN: 1 host (7 osds) down[cluster-wide][production][issue]',
|
|
'cluster:ceph:OSD_HOST_DOWN'),
|
|
('[proxmox-cluster][auto][ceph] Ceph HEALTH_WARN: 7 osds down[cluster-wide][production][issue]',
|
|
'cluster:ceph:OSD_DOWN'),
|
|
('[proxmox-cluster][auto][ceph] Ceph HEALTH_WARN: noout,norebalance flag(s) set[cluster-wide][production][problem]',
|
|
'cluster:ceph:OSDMAP_FLAGS'),
|
|
('[proxmox-cluster][auto][ceph] Ceph HEALTH_WARN: 4 pool(s) nearfull[cluster-wide][production][problem]',
|
|
'cluster:ceph:POOL_NEARFULL'),
|
|
('[proxmox-cluster][auto][ceph] Ceph HEALTH_WARN: 1 nearfull osd(s)[cluster-wide][production][problem]',
|
|
'cluster:ceph:OSD_NEARFULL'),
|
|
('[proxmox-cluster][auto][software] Ceph HEALTH_WARN: 7 slow ops, oldest one blocked for 82 sec, daemons '
|
|
'[osd.14,osd.27,osd.35,osd.36,osd.6] have slow ops.[cluster-wide][production][problem]', 'cluster:ceph:SLOW_OPS'),
|
|
('[proxmox-cluster][auto][ceph] Ceph HEALTH_WARN: 1 clients failing to respond to capability release'
|
|
'[cluster-wide][production][problem]', 'cluster:ceph:MDS_CLIENT_LATE_RELEASE'),
|
|
('[proxmox-cluster][auto][ceph] Ceph HEALTH_WARN: clock skew detected on mon.compute-storage-01'
|
|
'[cluster-wide][production][problem]', 'cluster:ceph:MON_CLOCK_SKEW'),
|
|
('[proxmox-cluster][auto][ceph] Ceph cluster HEALTH_ERR: Unknown error[cluster-wide][production][issue]',
|
|
'cluster:ceph:HEALTH_ERR'),
|
|
('[proxmox-cluster][auto][ceph] Ceph OSD osd.5 is DOWN[cluster-wide][production][issue]',
|
|
'cluster:ceph_osd:osd.5:down'),
|
|
('[compute-storage-01][auto][hardware][3.00 TB] Drive WD-WCC4N2FYYCXP has SMART issues[single-node][production][problem]',
|
|
'drive:WD-WCC4N2FYYCXP:smart'),
|
|
('[storage-01][auto][hardware][1.00 TB] Drive WD-WCAW32197980 has SMART issues, Critical Offline_Uncorrectable: 4'
|
|
'[single-node][production][issue]', 'drive:WD-WCAW32197980:smart'),
|
|
('[large1][auto][hardware][1.00 TB] Drive /dev/sdk has SMART issues: Warning High_Fly_Writes: 1'
|
|
'[single-node][production][problem]', 'host:large1:drive_sdk:smart'),
|
|
("[pbs][auto][hardware] [pbs] ZFS pool 'halfTbNVMeMirror' state: DEGRADED[single-node][production][problem]",
|
|
'pbs:zfs:halfTbNVMeMirror:state'),
|
|
("[pbs][auto][hardware] [pbs] ZFS pool 'halfTbNVMeMirror' usage high[single-node][production][problem]",
|
|
'pbs:zfs:halfTbNVMeMirror:usage'),
|
|
('[storage-01][auto][software] CPU usage sustained above threshold of 95%[single-node][production][problem]',
|
|
'host:storage-01:cpu'),
|
|
('[pbs][auto][software] CPU usage is above threshold of 95%[single-node][production][problem]', 'host:pbs:cpu'),
|
|
('[storage-01][auto][network] Ceph network is unreachable[single-node][production][issue]',
|
|
'host:storage-01:ceph_net_unreachable'),
|
|
('[monitor-01][auto][network] Management network is unreachable[single-node][production][issue]',
|
|
'host:monitor-01:mgmt_net_unreachable'),
|
|
('[compute-storage-gpu-01][auto][software]LXC 130 high storage usage: 80.7% on /[single-node][production][maintenance]',
|
|
'lxc:130:storage:root'),
|
|
('[large1][auto][software] LXC 141 high storage usage on /mnt/sia[single-node][production][problem]',
|
|
'lxc:141:storage:mnt_sia'),
|
|
('[storage-01][auto][hardware] WARNING: ATA command failures in system logs (4 occurrences)'
|
|
'[single-node][production][problem]', 'host:storage-01:syslog:ata_command_failures'),
|
|
('[monitor-02][auto][hardware] CRITICAL: Buffer I/O errors in system logs (75 occurrences)'
|
|
'[single-node][production][problem]', 'host:monitor-02:syslog:buffer_i_o_errors'),
|
|
]
|
|
|
|
|
|
@pytest.mark.parametrize('title, expected', REAL_TITLES)
|
|
def test_real_tinker_titles_map(title, expected):
|
|
source, summary = dedup_key_map.parse_title(title)
|
|
assert SystemHealthMonitor.dedup_key_for(summary, source) == expected
|