Send Tinker dedup_key with every recognised issue #44

Merged
jared merged 2 commits from feat/hwmon-dedup-key into main 2026-11-28 14:18:38 -05:00
4 changed files with 504 additions and 8 deletions

No files matched your search

+28
View File
@@ -170,6 +170,34 @@ The daemon automatically creates tickets with:
- 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
- A `dedup_key` (tinker_tickets#123) that decides which ticket a report lands on, so Tinker no longer guesses from the title
### Dedup keys
Keys are `scope:subject:kind` and come from `SystemHealthMonitor.dedup_key_for`:
| Issue | Key |
|---|---|
| Drive SMART / temperature | `drive:<serial>:smart`, `drive:<serial>:temperature` (no serial: `host:<host>:drive_sdX:smart`) |
| ECC | `host:<host>:ecc` |
| CPU | `host:<host>:cpu` |
| Network reachability | `host:<host>:mgmt_net_unreachable`, `host:<host>:ceph_net_unreachable` |
| LXC storage | `lxc:<vmid>:storage:<mount>` (`/` is `root`) |
| Kernel log errors | `host:<host>:syslog:<error kind>` |
| Ceph health warning | `cluster:ceph:<CODE>`, the same key Thor uses, so Thor can adopt the ticket |
| Ceph usage / HEALTH_ERR / OSD down | `cluster:ceph:usage`, `cluster:ceph:HEALTH_ERR`, `cluster:ceph_osd:osd.N:down` |
| PBS | `pbs:zfs:<pool>:state` / `usage` / `errors`, `pbs:task:<type>:failed` |
An issue that matches none of these is sent without a key and keeps Tinker's title hash.
**Changing a key re-keys tickets.** Existing tickets have to be given their keys in Tinker, or the next report opens a duplicate. Hosts run `main` straight from Gitea every hour, so merging is the deploy, and the backfill has to land between the merge and the next hourly run:
1. Just after an hourly run finishes (a few minutes past the hour), merge.
2. Build the map from Tinker (read only; uses `TICKET_API_KEY` from `/etc/hwmonDaemon/.env`, or set `TICKET_API_KEY` in the environment):
`python3 scripts/dedup_key_map.py --out hwmon-keys.json`
It lists every key, older tickets left alone, and any ticket it couldn't map (exit 1 if there are any).
3. On the Tinker host: `php scripts/backfill_dedup_keys.php --map=hwmon-keys.json --dry-run`, check it, then run it without `--dry-run`.
4. After the next run, reports should come back as `updated`/`deduplicated`, not `created`. If the backfill can't be done before the hour, revert the merge instead.
- Detailed descriptions of detected issues with drive specifications
- Priority levels based on severity (P2-P4)
- Proper categorization and status tracking
+119 -8
View File
@@ -190,6 +190,109 @@ class SystemHealthMonitor:
CHECK_SWITCHES = ('CPU_ENABLED', 'LXC_STORAGE_ENABLED', 'NETWORK_ENABLED')
# Ceph health-check codes for HEALTH_WARN messages. The daemon reads the real
# code from `ceph health`; this table only exists so scripts/dedup_key_map.py can
# recover the code from an old ticket title, which holds just the message.
# Order matters: more specific patterns first.
CEPH_MESSAGE_CODES = [
(r'slow operations in BlueStore', 'BLUESTORE_SLOW_OP_ALERT'),
(r'stalled read', 'DB_DEVICE_STALLED_READ_ALERT'),
(r'spurious read errors', 'BLUESTORE_SPURIOUS_READ_ERRORS'),
(r'recently crashed', 'RECENT_CRASH'),
(r'not deep-scrubbed in time', 'PG_NOT_DEEP_SCRUBBED'),
(r'not scrubbed in time', 'PG_NOT_SCRUBBED'),
(r'Degraded data redundancy', 'PG_DEGRADED'),
(r'Reduced data availability', 'PG_AVAILABILITY'),
(r'Possible data damage', 'PG_DAMAGED'),
(r'scrub errors', 'OSD_SCRUB_ERRORS'),
(r'insufficient standby MDS', 'MDS_INSUFFICIENT_STANDBY'),
(r'failing to respond to capability release', 'MDS_CLIENT_LATE_RELEASE'),
(r'clock skew', 'MON_CLOCK_SKEW'),
(r'\bhost\b.*\bdown\b', 'OSD_HOST_DOWN'),
(r'\bosds? down\b', 'OSD_DOWN'),
(r'\bmons? down\b|out of quorum', 'MON_DOWN'),
(r'low on available space', 'MON_DISK_LOW'),
(r'flag\(s\) set', 'OSDMAP_FLAGS'),
(r'nearfull osd', 'OSD_NEARFULL'),
(r'pool\(s\) nearfull', 'POOL_NEARFULL'),
(r'slow ops', 'SLOW_OPS'),
(r'application not enabled', 'POOL_APP_NOT_ENABLED'),
]
@staticmethod
def _key_part(text: str) -> str:
"""Make text safe as one part of a Tinker dedup_key (A-Za-z0-9_.- only)."""
return re.sub(r'[^A-Za-z0-9_.-]+', '_', text).strip('_') or 'none'
@classmethod
def dedup_key_for(cls, issue: str, hostname: str, ceph_code: Optional[str] = None) -> Optional[str]:
"""Tinker dedup_key (scope:subject:kind, tinker_tickets#123) for an issue.
Works on both a raw issue string and the summary part of an old ticket
title (volatile values stripped), so scripts/dedup_key_map.py can give
existing tickets the same key the daemon now sends. Returns None for an
issue it doesn't recognise; that ticket keeps Tinker's title-based hash.
"""
text = re.sub(r'\[(?:cluster-wide|ceph|pbs)\]\s*', '', issue).strip()
host = cls._key_part(hostname)
def slug(s: str) -> str:
return cls._key_part(s.lower())[:60]
m = re.match(r'Drive (\S+) (has SMART issues|temperature is high)', text)
if m:
drive, kind = m.group(1), 'smart' if 'SMART' in m.group(2) else 'temperature'
if drive.startswith('/dev/'):
# No serial: the device path is only meaningful on this host
return f"host:{host}:drive_{cls._key_part(drive[5:])}:{kind}"
return f"drive:{cls._key_part(drive)}:{kind}"
if re.search(r'ECC errors detected|Error checking ECC', text):
return f"host:{host}:ecc"
if re.match(r'CPU usage (?:sustained|is) above threshold', text): # "is": pre-July 2026 wording
return f"host:{host}:cpu"
if text.startswith('Management network is unreachable'):
return f"host:{host}:mgmt_net_unreachable"
if text.startswith('Ceph network is unreachable'):
return f"host:{host}:ceph_net_unreachable"
m = re.match(r'LXC (\d+) .*storage usage.* on (/\S*)$', text)
if m:
mount = 'root' if m.group(2) == '/' else cls._key_part(m.group(2))
return f"lxc:{m.group(1)}:storage:{mount}"
if re.search(r'System log check timed out|Failed to check system logs', text):
return f"host:{host}:syslog_check_failed"
m = re.match(r'(?:CRITICAL|WARNING|ERROR|INFO): (.+?) in system logs', text)
if m:
return f"host:{host}:syslog:{slug(m.group(1))}"
m = re.match(r'Ceph HEALTH_WARN: (.*)', text)
if m:
code = ceph_code or next(
(c for pattern, c in cls.CEPH_MESSAGE_CODES if re.search(pattern, m.group(1), re.IGNORECASE)),
None)
return f"cluster:ceph:{cls._key_part(code)}" if code else None
if text.startswith('Ceph cluster HEALTH_ERR'):
return "cluster:ceph:HEALTH_ERR"
if text.startswith('Ceph cluster usage'):
return "cluster:ceph:usage"
m = re.match(r'Ceph OSD (osd\.\d+) is DOWN', text)
if m:
return f"cluster:ceph_osd:{m.group(1)}:down"
if re.search(r'Ceph health check timed out|Error checking Ceph health', text):
return f"host:{host}:ceph_check_failed"
m = re.search(r"ZFS pool '([^']+)' (state|usage|has errors)", text)
if m:
kind = {'state': 'state', 'usage': 'usage', 'has errors': 'errors'}[m.group(2)]
return f"pbs:zfs:{cls._key_part(m.group(1))}:{kind}"
m = re.match(r'PBS (\S+) failed', text)
if m:
return f"pbs:task:{cls._key_part(m.group(1))}:failed"
return None
@staticmethod
def _parse_switch(value: str) -> Optional[bool]:
"""Parse an on/off .env value. None if unrecognised, so a typo can't
@@ -2168,10 +2271,14 @@ class SystemHealthMonitor:
)
description = self._generate_detailed_description(issue, health_report, priority)
# NOTE: The ticket API (create_ticket_api.php) deduplicates using a SHA-256 hash of:
# issue_category + environment_tags + hostname (excluded for [cluster-wide]) + serial
# Serial is preferred over device path — it remains stable across reboots and
# device-letter reassignments. Falls back to /dev/sdX for non-SMART-capable devices.
# dedup_key (tinker_tickets#123, #42) decides which ticket a report lands on;
# Tinker then ignores the title. Issues without a key fall back to Tinker's
# title hash: issue_category + environment_tags + hostname (excluded for
# [cluster-wide]) + serial.
raw_ceph = re.sub(r'\[(?:cluster-wide|ceph)\]\s*', '', issue).strip()
ceph_code = health_report.get('ceph_health', {}).get('check_codes', {}).get(raw_ceph)
dedup_key = self.dedup_key_for(issue, hostname, ceph_code=ceph_code)
ticket_payload = {
"title": ticket_title,
"description": description,
@@ -2181,6 +2288,8 @@ class SystemHealthMonitor:
"type": ticket_type,
"serial": issue_serial, # drive serial for stable dedup; None for non-drive issues
}
if dedup_key:
ticket_payload["dedup_key"] = dedup_key
if self.dry_run:
logger.info("Dry-run mode enabled. Simulating ticket creation:")
@@ -3519,7 +3628,8 @@ class SystemHealthMonitor:
'osd_status': [],
'mon_status': [],
'issues': [],
'cluster_wide_issues': [] # Issues affecting entire cluster; use CLUSTER_NAME for dedup
'cluster_wide_issues': [], # Issues affecting entire cluster; use CLUSTER_NAME for dedup
'check_codes': {}, # HEALTH_WARN issue text -> Ceph health-check code
}
# Check if Ceph monitoring is enabled
@@ -3568,9 +3678,10 @@ class SystemHealthMonitor:
logger.debug(f"Ignoring standing Ceph flags: {message}")
continue
warned = True
ceph_health['cluster_wide_issues'].append(
f"Ceph HEALTH_WARN: {message}"
)
issue_text = f"Ceph HEALTH_WARN: {message}"
ceph_health['cluster_wide_issues'].append(issue_text)
# Health-check code for the ticket's dedup_key (#42)
ceph_health['check_codes'][issue_text] = check_name
if warned and ceph_health['status'] != 'CRITICAL':
ceph_health['status'] = 'WARNING'
except json.JSONDecodeError as e:
+144
View File
@@ -0,0 +1,144 @@
#!/usr/bin/env python3
"""Build the dedup_key backfill map for hwmonDaemon's existing tickets (#42).
Once hwmonDaemon sends dedup_key, Tinker hashes its reports on the key instead
of the title, so every existing ticket needs the same key or the next report
opens a duplicate. This reads hwmonDaemon's tickets from Tinker (read only),
recovers the host and summary from each title, and computes the key with the
same function the daemon uses (SystemHealthMonitor.dedup_key_for). When several
tickets share a key, a ticket that isn't Closed wins (reports land on it today),
then the newest.
Output is the JSON map tinker_tickets' backfill script takes:
python3 scripts/dedup_key_map.py --out hwmon-keys.json
php scripts/backfill_dedup_keys.php --map=hwmon-keys.json --dry-run # on Tinker
php scripts/backfill_dedup_keys.php --map=hwmon-keys.json
The API URL and key default to TICKET_API_URL / TICKET_API_KEY from
/etc/hwmonDaemon/.env. --from-json reads a saved list instead of the API.
Exits 1 if any hwmonDaemon ticket couldn't be mapped, so the operator looks.
"""
import argparse
import json
import os
import re
import sys
from typing import Dict, Iterable, List, Optional, Tuple
sys.path.insert(0, os.path.dirname(os.path.dirname(os.path.abspath(__file__))))
from hwmonDaemon import SystemHealthMonitor # noqa: E402
STATUSES = 'Open,In Progress,Pending,Closed'
TITLE = re.compile(r'^((?:\[[^\]]*\])+)\s*(.*?)\s*((?:\[[^\]]*\])+)$')
def parse_title(title: str) -> Optional[Tuple[str, str]]:
"""(source, summary) from an automated hwmonDaemon title, or None.
"[host][auto][hwmon][hardware][3.00 TB] Drive X has SMART issues[single-node][production][problem]"
-> ("host", "Drive X has SMART issues")
"""
m = TITLE.match(title.strip())
if not m or '[auto]' not in m.group(1):
return None
source = m.group(1)[1:].split(']', 1)[0]
return source, m.group(2)
def build_map(tickets: Iterable[dict]) -> Tuple[Dict[str, str], List[dict], List[dict]]:
"""Returns (map, unmapped tickets, superseded tickets)."""
winners: Dict[str, dict] = {}
unmapped, superseded = [], []
# Not-Closed first (that's where reports land today), then newest
ordered = sorted(tickets, key=lambda t: (t.get('status') != 'Closed', str(t.get('created_at') or ''),
str(t['ticket_id'])), reverse=True)
for t in ordered:
parsed = parse_title(t.get('title') or '')
key = SystemHealthMonitor.dedup_key_for(parsed[1], parsed[0]) if parsed else None
if not key:
unmapped.append(t)
elif key in winners:
superseded.append(dict(t, dedup_key=key, kept=winners[key]['ticket_id']))
else:
winners[key] = t
return {str(t['ticket_id']): k for k, t in winners.items()}, unmapped, superseded
def read_env(path: str) -> Dict[str, str]:
env = {}
try:
with open(path) as f:
for line in f:
line = line.strip()
if line and not line.startswith('#') and '=' in line:
k, v = line.split('=', 1)
env[k.strip()] = v.strip()
except OSError:
pass
return env
def fetch_tickets(list_url: str, api_key: str, source: str) -> List[dict]:
import requests
tickets, page = [], 1
while True:
r = requests.get(list_url, params={'source': source, 'status': STATUSES, 'limit': 100, 'page': page},
headers={'Authorization': f'Bearer {api_key}'}, timeout=30)
r.raise_for_status()
data = r.json()
if not data.get('success'):
raise RuntimeError(f"Tinker list API error: {data.get('error')}")
tickets.extend(data.get('tickets', []))
if page >= int(data.get('pages') or 1):
return tickets
page += 1
def main(argv: Optional[List[str]] = None) -> int:
p = argparse.ArgumentParser(description=__doc__.split('\n\n')[0])
p.add_argument('--env', default='/etc/hwmonDaemon/.env', help='hwmonDaemon .env with TICKET_API_URL/KEY')
p.add_argument('--url', help='Tinker list API URL (default: derived from TICKET_API_URL)')
p.add_argument('--source', default='hwmonDaemon', help="tickets.source to read (default: hwmonDaemon)")
p.add_argument('--from-json', help='read tickets from this file (a list, or a list API response) instead')
p.add_argument('--out', help='write the map here (default: stdout)')
args = p.parse_args(argv)
if args.from_json:
with open(args.from_json) as f:
data = json.load(f)
tickets = data.get('tickets', []) if isinstance(data, dict) else data
else:
env = read_env(args.env)
api_key = os.environ.get('TICKET_API_KEY') or env.get('TICKET_API_KEY')
if not api_key:
p.error(f'no TICKET_API_KEY in the environment or {args.env}')
create_url = env.get('TICKET_API_URL', SystemHealthMonitor.CONFIG['TICKET_API_URL'])
url = args.url or create_url.rsplit('/', 1)[0] + '/api/tickets_api.php'
tickets = fetch_tickets(url, api_key, args.source)
key_map, unmapped, superseded = build_map(tickets)
out = json.dumps(key_map, indent=2, sort_keys=True) + '\n'
if args.out:
with open(args.out, 'w') as f:
f.write(out)
else:
sys.stdout.write(out)
by_id = {str(t['ticket_id']): t for t in tickets}
log = sys.stderr
print(f"{len(tickets)} tickets read, {len(key_map)} keyed, {len(superseded)} older duplicates left alone, "
f"{len(unmapped)} unmapped", file=log)
for tid, key in sorted(key_map.items(), key=lambda kv: kv[1]):
print(f" {key:<45} {tid} [{by_id[tid].get('status')}]", file=log)
for t in superseded:
print(f" older {t['ticket_id']} [{t.get('status')}] same key as {t['kept']}: {t['dedup_key']}", file=log)
for t in unmapped:
print(f" UNMAPPED {t['ticket_id']} [{t.get('status')}] {t.get('title')}", file=log)
return 1 if unmapped else 0
if __name__ == '__main__':
sys.exit(main())
+213
View File
@@ -2,6 +2,8 @@
import sys
import os
import subprocess
import json
import re
import pytest
@@ -794,3 +796,214 @@ class TestSwitchEnvParsing:
_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