From 50c7e427d92bc8ca665c7c34d8d7a5571c1f8d55 Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Sat, 28 Nov 2026 13:54:31 -0500 Subject: [PATCH] feat: tag tickets [hwmon] and add per-check ticket switches (#42) Part 1 of #42: titles now carry the reporting app, [source][auto][hwmon][area] Summary [scope][env][type], and descriptions end with a footer naming hwmonDaemon and the host. Checked against Tinker's TicketHash.php: the tag matches no category keyword, isn't an environment tag, and network keys already strip bracketed tags, so no existing ticket is re-keyed. Tinker updates the title of an open duplicate silently. Part 5 of #42: CPU_ENABLED, LXC_STORAGE_ENABLED and NETWORK_ENABLED in /etc/hwmonDaemon/.env, default on. Off means the check still runs and reports metrics but opens no tickets and doesn't count toward P1 escalation, so each check can be handed to thor with no gap and never two writers. An unrecognised value logs a warning and leaves the check on. Co-Authored-By: Claude Opus 5.5 --- README.md | 16 +++++++- hwmonDaemon.py | 71 +++++++++++++++++++++++++++------ tests/test_hwmon.py | 97 +++++++++++++++++++++++++++++++++++++++++++++ 3 files changed, 170 insertions(+), 14 deletions(-) diff --git a/README.md b/README.md index 9a4d21e..c5699ba 100644 --- a/README.md +++ b/README.md @@ -140,6 +140,19 @@ The daemon monitors: - Automatic duplicate ticket prevention - Enhanced logging with debug capabilities +### Per-check ticket switches + +Checks that can be seen from outside the host are moving to thor (#40, #42). Each one has a switch in `/etc/hwmonDaemon/.env`, so it can be turned off the day thor takes it over: + +| Setting | Controls | +|---|---| +| `CPU_ENABLED` | "CPU usage sustained above threshold" tickets | +| `LXC_STORAGE_ENABLED` | LXC container storage tickets | +| `NETWORK_ENABLED` | "Management/Ceph network is unreachable" tickets | +| `CEPH_ENABLED` | All Ceph checks (this one skips the check entirely) | + +All default to on. Accepted values are `true`/`false`, `1`/`0`, `yes`/`no` and `on`/`off`. Anything else logs a warning and leaves the check on. When `CPU_ENABLED`, `LXC_STORAGE_ENABLED` or `NETWORK_ENABLED` is off, the check still runs and reports its metrics (dry-run summary, Prometheus), but it opens no tickets and no longer counts toward P1 escalation. + ## Data Storage The daemon creates and maintains: @@ -155,7 +168,8 @@ The daemon creates and maintains: The daemon automatically creates tickets with: -- Standardized titles including hostname, hardware type, and scope +- Standardized titles: `[source][auto][hwmon][area] Summary [scope][environment][type]`, e.g. `[compute-storage-01][auto][hwmon][hardware] Drive WD-WCC4N2FYYCXP has SMART issues [single-node][production][problem]`. The `[hwmon]` tag names the app that opened the ticket and isn't part of Tinker's dedup hash. +- A footer naming hwmonDaemon and the reporting host - Detailed descriptions of detected issues with drive specifications - Priority levels based on severity (P2-P4) - Proper categorization and status tracking diff --git a/hwmonDaemon.py b/hwmonDaemon.py index 8f3d50d..057bf10 100644 --- a/hwmonDaemon.py +++ b/hwmonDaemon.py @@ -152,6 +152,12 @@ class SystemHealthMonitor: 'HISTORY_RETENTION_DAYS': 30, 'INCLUDE_INFO_TICKETS': False, # Set True to create P5 tickets for INFO alerts 'PRIORITY_ESCALATION_THRESHOLD': 3, # Number of criticals to trigger P1 + # Per-check ticket switches (#42). Off means the check still runs and reports + # metrics, but opens no tickets and doesn't count toward P1 escalation, so a + # check can be switched off the day thor takes it over. + 'CPU_ENABLED': True, # "CPU usage sustained above threshold" tickets + 'LXC_STORAGE_ENABLED': True, # LXC container storage usage tickets + 'NETWORK_ENABLED': True, # Management / Ceph network reachability tickets # Ceph monitoring settings 'CEPH_ENABLED': True, # Enable/disable Ceph health monitoring 'CEPH_TICKET_NODE': None, # Hostname of node designated to create cluster-wide Ceph tickets @@ -182,6 +188,22 @@ class SystemHealthMonitor: 'PBS_ZFS_CRITICAL': 90 # ZFS pool usage critical threshold % } + CHECK_SWITCHES = ('CPU_ENABLED', 'LXC_STORAGE_ENABLED', 'NETWORK_ENABLED') + + @staticmethod + def _parse_switch(value: str) -> Optional[bool]: + """Parse an on/off .env value. None if unrecognised, so a typo can't + silently switch a default-on check off.""" + v = value.strip().lower() + if v in ('true', '1', 'yes', 'on'): + return True + if v in ('false', '0', 'no', 'off'): + return False + return None + + def _ticketing_enabled(self, switch: str) -> bool: + return bool(self.CONFIG.get(switch, True)) + @classmethod def load_env_config(cls): """Load configuration from .env file in /etc/hwmonDaemon/""" @@ -213,6 +235,14 @@ class SystemHealthMonitor: elif key == 'TICKET_API_URL': cls.CONFIG['TICKET_API_URL'] = value logger.info(f"✓ Loaded TICKET_API_URL: {value}") + elif key in cls.CHECK_SWITCHES: + parsed = cls._parse_switch(value) + if parsed is None: + logger.warning(f"Invalid {key} value: {value!r} - leaving it " + f"{'on' if cls.CONFIG[key] else 'off'}") + else: + cls.CONFIG[key] = parsed + logger.info(f"✓ Loaded {key}: {parsed}") # Ceph settings elif key == 'CEPH_ENABLED': cls.CONFIG['CEPH_ENABLED'] = value.lower() in ('true', '1', 'yes') @@ -298,6 +328,9 @@ class SystemHealthMonitor: 'AUTO': '[auto]', 'MANUAL': '[manual]' }, + # Reporting app, so tickets say which monitor opened them (#42). Not part of + # Tinker's dedup hash, so adding it doesn't re-key existing tickets. + 'APP': '[hwmon]', 'ENVIRONMENT': { 'PRODUCTION': '[production]' }, @@ -1065,6 +1098,10 @@ class SystemHealthMonitor: for line in self._format_lxc_dry_run(health_report.get('lxc_health', {})): logger.info(line) + switched_off = [s for s in self.CHECK_SWITCHES if not self._ticketing_enabled(s)] + if switched_off: + logger.info(f"\nTicketing switched off (checks still run): {', '.join(switched_off)}") + # PBS status pbs = health_report.get('pbs_health', {}) if pbs.get('is_pbs_node'): @@ -1772,6 +1809,7 @@ class SystemHealthMonitor: description += f"Free Space: {partition['free_space']}\n" description += f"Usage Percent: {partition['usage_percent']}%\n" + description += f"\n\nReported automatically by hwmonDaemon on {hostname}.\n" return description def _count_critical_issues(self, health_report: Dict[str, Any]) -> int: @@ -1798,15 +1836,17 @@ class SystemHealthMonitor: if health_report.get('memory_health', {}).get('status') == 'CRITICAL': count += 1 - # Count network failures - net = health_report.get('network_health', {}) - if net.get('management_network', {}).get('status') == 'CRITICAL': - count += 1 - if net.get('ceph_network', {}).get('status') == 'CRITICAL': - count += 1 + # Count network failures (a switched-off check doesn't escalate other tickets) + if self._ticketing_enabled('NETWORK_ENABLED'): + net = health_report.get('network_health', {}) + if net.get('management_network', {}).get('status') == 'CRITICAL': + count += 1 + if net.get('ceph_network', {}).get('status') == 'CRITICAL': + count += 1 # Count LXC critical issues - if health_report.get('lxc_health', {}).get('status') == 'CRITICAL': + if (self._ticketing_enabled('LXC_STORAGE_ENABLED') + and health_report.get('lxc_health', {}).get('status') == 'CRITICAL'): count += 1 return count @@ -2118,6 +2158,7 @@ class SystemHealthMonitor: ticket_title = ( f"{ticket_source}" f"{action_type['AUTO']}" + f"{self.TICKET_TEMPLATES['APP']}" f"{issue_tag}" f"{issue_separator}" f"{clean_issue}" @@ -2237,19 +2278,23 @@ class SystemHealthMonitor: # _check_cpu_usage) so transient spikes don't raise/reopen a CPU ticket. The message # is kept stable (threshold constant, no measured value) so the title doesn't churn # every run; the measured load is recorded in the ticket description instead. + # CPU_ENABLED / NETWORK_ENABLED / LXC_STORAGE_ENABLED switch ticketing off for + # checks thor has taken over; the checks still run for metrics (#42). cpu_health = health_report.get('cpu_health', {}) - if cpu_health.get('sustained_high'): + if self._ticketing_enabled('CPU_ENABLED') and cpu_health.get('sustained_high'): threshold = self.CONFIG['THRESHOLDS']['CPU_WARNING'] issues.append(f"CPU usage sustained above threshold of {threshold}%") # Check for network-related issues - network_health = health_report.get('network_health', {}) - for network in ['management_network', 'ceph_network']: - if network_health.get(network, {}).get('issues'): - issues.extend(network_health[network]['issues']) + if self._ticketing_enabled('NETWORK_ENABLED'): + network_health = health_report.get('network_health', {}) + for network in ['management_network', 'ceph_network']: + if network_health.get(network, {}).get('issues'): + issues.extend(network_health[network]['issues']) lxc_health = health_report.get('lxc_health', {}) - if lxc_health.get('status') in ['WARNING', 'CRITICAL']: + if (self._ticketing_enabled('LXC_STORAGE_ENABLED') + and lxc_health.get('status') in ['WARNING', 'CRITICAL']): issues.extend(lxc_health.get('issues', [])) # Check for system-level drive issues diff --git a/tests/test_hwmon.py b/tests/test_hwmon.py index 22dd2f8..98b0610 100644 --- a/tests/test_hwmon.py +++ b/tests/test_hwmon.py @@ -697,3 +697,100 @@ class TestManagedVolumes: 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 -- 2.47.3