#!/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())