"""Ask Thor whether a problem is already covered before Gandalf opens a ticket (gandalf#66). Thor is the only correlator between Gandalf, hwmonDaemon and Thor's own checks. Before Gandalf opens a host-, cluster- or source-level ticket without network evidence, it asks Thor's covering endpoint. When Thor names a ticket, Gandalf comments there instead. Fail open: no config, a timeout, any HTTP error or a reply that doesn't parse all mean "not covered", so Gandalf opens its ticket as normal and never loses one. Config: "thor": {"url": "http://10.10.10.86", "api_key": "..."} Call the CT directly; thor.lotusguild.org is behind Authelia. The key is Gandalf's own, kept in config.json only; Thor's operator gets its SHA-256. Spec: thor docs/contract.md. """ import logging from typing import List, Optional import requests logger = logging.getLogger('gandalf.thor') TIMEOUT_S = 4 def _answer(covered: bool = False, ticket_id: Optional[str] = None, shadow: Optional[List[str]] = None, error: str = '') -> dict: return {'covered': covered, 'ticket_id': ticket_id, 'shadow': shadow or [], 'error': error} class ThorClient: def __init__(self, cfg: Optional[dict]): cfg = cfg or {} self.url = (cfg.get('url') or '').rstrip('/') self.api_key = cfg.get('api_key') or '' @property def configured(self) -> bool: return bool(self.url and self.api_key) def covering(self, host: Optional[str] = None, scope: Optional[str] = None) -> dict: """{'covered', 'ticket_id', 'shadow': [incident keys], 'error'}. Never raises. covered is true only when Thor names a ticket to comment on. Shadow incidents never cover anything; their keys are returned so they can be logged beside Gandalf's ticket. """ if not self.configured: return _answer(error='not configured') params = {'host': host} if host else {'scope': scope} try: resp = requests.get(f'{self.url}/api/incidents/covering', params=params, headers={'Authorization': f'Bearer {self.api_key}'}, timeout=TIMEOUT_S) if resp.status_code != 200: logger.warning(f'Thor covering check {params} returned HTTP {resp.status_code}; ' 'opening the ticket as normal') return _answer(error=f'HTTP {resp.status_code}') data = resp.json() except Exception as e: logger.warning(f'Thor covering check {params} failed ({e}); opening the ticket as normal') return _answer(error=str(e)[:200]) if not isinstance(data, dict): return _answer(error='unexpected reply') shadow = [str(i.get('key')) for i in data.get('incidents') or [] if isinstance(i, dict) and i.get('mode') == 'shadow' and i.get('key')] ticket_id = data.get('ticket_id') if data.get('covered') is True and ticket_id: return _answer(True, str(ticket_id), shadow) return _answer(shadow=shadow)