Files
gandalf/ticket_text.py
jaredandClaude Opus 5.5 c9919017dc
CI / Lint (JS) (pull_request) Successful in 14s
CI / Lint (Python) (pull_request) Successful in 41s
CI / Test (pull_request) Successful in 1m8s
CI / Security (pull_request) Successful in 42s
CI / Scan (pull_request) Successful in 21s
CI / Deploy (pull_request) Skipped
CI / Notify (pull_request) Skipped
Gateway reachability from each host, taken over from hwmonDaemon (#66 item 7)
The SSH session Gandalf already opens on each host through Pulse (for
ethtool) now also pings each gateway in monitor.reachability 3 times,
0.2 s apart, e.g. {"management": "10.10.10.1", "ceph": "10.10.90.1"}.

- All 3 lost raises network_unreachable (host, network); partial loss
  doesn't, and a host whose SSH collection failed neither alerts nor
  clears. A P2 ticket after failure_threshold checks in a row, where
  hwmonDaemon pinged once and ticketed on a single miss.
- One host: hwmonDaemon's own keys (host:<host>:ceph_net_unreachable,
  host:<host>:mgmt_net_unreachable), so its open tickets carry on.
- Several hosts losing the same network in one check share one
  cluster-wide ticket (cluster:<network>_net:unreachable): the switch,
  VLAN or router is the likely cause, not each host.
- Results are kept in link_stats.reachability.

Checked from all six hosts: both gateways answer, and the output parses.
hwmonDaemon's NETWORK_ENABLED switch turns its version off once this is
live with monitor.reachability set.

Co-Authored-By: Claude Opus 5.5 <[email protected]>
2026-11-29 03:44:39 -05:00

266 lines
11 KiB
Python

"""Markdown for the tickets Gandalf opens in Tinker Tickets, and the notes it adds to them.
Pure formatting only: monitor.py gathers the facts and passes them in.
"""
import re
from datetime import datetime, timezone
from typing import List, Optional, Sequence, Tuple
from urllib.parse import quote
Section = Tuple[str, List[str]]
# Gandalf's tag in the shared title standard (wiki, thor#1):
# [source][auto][app][area] Summary [scope][environment][type]
APP_TAG = 'gandalf'
SCOPES = ('single-node', 'cluster-wide')
def title(source: str, summary: str, scope: str = 'single-node') -> str:
"""A ticket title in the shared format. Every Gandalf ticket is in the network area.
Tinker's dedup hash reads the first tag, the [auto] tag, the environment and scope tags and
the text outside the tags, so this order hashes the same as the old
[source][auto][production][issue][network][scope] Summary (checked against TicketHash.php).
"""
if scope not in SCOPES:
raise ValueError(f'scope must be one of {SCOPES}')
return f'[{source}][auto][{APP_TAG}][network] {summary} [{scope}][production][issue]'
# dedup_key for each event type, sent to Tinker so it matches "the same problem" exactly
# (tinker_tickets#123). Convention scope:subject:kind; t is the target, d the detail.
_DEDUP_KEYS = {
'interface_down': 'host:{t}:iface_down:{d}',
'host_metrics_missing': 'host:{t}:metrics_missing',
'host_unreachable': 'device:{t}:unreachable',
'unifi_device_offline': 'device:{t}:offline',
'cable_mismatch': 'device:{t}:cable_mismatch:{d}',
'cluster_network_issue': 'cluster:network:failure',
'monitor_source_unavailable': 'source:{t}:unavailable',
}
# Modem and WAN events: one site, so the key is the event type (and its detail, if any)
WAN_EVENTS = ('modem_unreachable', 'modem_data_invalid', 'wan_down', 'wan_degraded', 'wan_unstable',
'modem_power_cycled', 'fiber_signal_alarm', 'fiber_signal_warning', 'fiber_rx_drift',
'inbound_flood')
_KEY_BAD = re.compile(r'[^a-z0-9_.:-]+')
def _key_part(text) -> str:
return _KEY_BAD.sub('-', str(text or '').strip().lower()).strip('-')
def _net_key(name: str) -> str:
return {'management': 'mgmt'}.get(name, name)
def network_down_key(network: str) -> str:
"""Key for one ticket covering several hosts that lost the same network at once."""
return f'cluster:{_net_key(_key_part(network))}_net:unreachable'[:128]
def dedup_key(event_type: str, target: str, detail: str = '') -> Optional[str]:
"""Tinker's dedup_key for an event, or None for a type without one (Tinker then hashes
the title, as before). Format ^[a-z0-9_.:-]{1,128}$."""
t, d = _key_part(target), _key_part(detail)
if event_type == 'network_unreachable':
# hwmonDaemon's keys, so its open tickets carry on (gandalf#66 item 7)
return f'host:{t}:{_net_key(d)}_net_unreachable'[:128]
if event_type in WAN_EVENTS:
key = f'site:wan:{event_type}' + (f':{d}' if d else '')
elif event_type in _DEDUP_KEYS:
key = _DEDUP_KEYS[event_type].format(t=t, d=d)
else:
return None
return key[:128]
def also_seen_comment(ticket_title: str, description: str) -> str:
"""Gandalf's report, posted on the ticket Thor says covers it instead of a ticket of its own."""
return (f'**Also seen by Gandalf:** {ticket_title}\n\n'
'Thor says this ticket already covers it, so Gandalf did not open its own. '
"Gandalf's report:\n\n" + description)
def duration(seconds) -> str:
seconds = max(0, int(seconds))
if seconds < 60:
return f'{seconds} s'
minutes = seconds // 60
if minutes < 60:
return f'{minutes} min'
hours, minutes = divmod(minutes, 60)
if hours < 48:
return f'{hours} h {minutes} min' if minutes else f'{hours} h'
days, hours = divmod(hours, 24)
return f'{days} d {hours} h' if hours else f'{days} d'
def utc(dt: Optional[datetime]) -> str:
"""Database times are naive UTC."""
if dt is None:
return 'unknown'
if dt.tzinfo is not None:
dt = dt.astimezone(timezone.utc).replace(tzinfo=None)
return dt.strftime('%Y-%m-%d %H:%M UTC')
def speed(mbps) -> str:
if not mbps:
return ''
mbps = int(mbps)
if mbps >= 1000:
gbps = mbps / 1000
return f'{gbps:g} Gbps'
return f'{mbps} Mbps'
def device_url(base: str, name: str, port_idx=None) -> str:
if not base or not name:
return ''
url = f'{base}/device/{quote(name, safe="")}'
return f'{url}#port-{port_idx}' if port_idx not in (None, '') else url
def history_url(base: str, target: str) -> str:
return f'{base}/events?target={quote(target, safe="")}&range=90d' if base and target else ''
def cutsheet_url(base: str, cable_id) -> str:
return f'{base}/cutsheet#cable-{cable_id}' if base else ''
def link(text: str, url: str) -> str:
return f'[{text}]({url})' if url else text
def port_text(switch: str, port_name: str, port: dict) -> str:
"""'8SFP-AGG port 7 "compute-storage-02": up at 10 Gbps, DAC'"""
idx = port.get('port_idx')
text = f'{switch} port {idx}' if idx is not None else f'{switch} {port_name}'
if port_name and idx is not None and port_name != f'Port {idx}':
text += f' "{port_name}"'
state = []
if port.get('up'):
rate = speed(port.get('speed_mbps'))
state.append(f'up at {rate}' if rate else 'up')
else:
state.append('down')
if port.get('poe_power'):
state.append(f'PoE {float(port["poe_power"]):.1f} W')
sfp = port.get('sfp') or {}
if sfp.get('found'):
kind = 'DAC' if sfp.get('kind') == 'dac' else sfp.get('kind', '')
module = ' '.join(p for p in (kind, sfp.get('part', '')) if p)
if module:
state.append(f'module: {module}')
if sfp.get('rx_fault') or sfp.get('tx_fault'):
state.append('**module reports a fault**')
return f'{text}: {", ".join(state)}'
def description(heading: str, facts: Sequence[Tuple[str, str]], summary: str,
checks: Sequence[str], sections: Sequence[Section] = (), recovers: bool = True) -> str:
lines = [f'## {heading}', '']
lines += [f'- **{key}:** {value}' for key, value in facts if value not in (None, '')]
lines += ['', summary.strip()]
if checks:
lines += ['', '### What to check']
lines += [f'{n}. {check}' for n, check in enumerate(checks, 1)]
for title, body in sections:
if body:
lines += ['', f'### {title}'] + list(body)
if recovers:
lines += ['', '_Opened automatically by Gandalf. It adds a note here when the problem clears, '
'but leaves closing the ticket to you._']
else:
lines += ['', '_Reported automatically by Gandalf. This already happened, so there will be no '
'recovery note._']
return '\n'.join(lines)
def history_lines(stats: dict, now: datetime) -> List[str]:
week, month = stats.get('last_7d', 0), stats.get('last_30d', 0)
if not month:
lines = ['- First time in the last 30 days.']
else:
lines = [f'- Happened {week} time{"s" if week != 1 else ""} in the last 7 days '
f'and {month} in the last 30 (not counting this one).']
if week >= 3:
lines.append('- **This keeps coming back**: look for a cause that comes and goes '
'(a loose cable, a failing optic, power, or a scheduled job).')
first, resolved = stats.get('last_first_seen'), stats.get('last_resolved_at')
if resolved:
took = duration((resolved - first).total_seconds()) if first else 'unknown'
ago = duration((now - resolved).total_seconds())
lines.append(f'- Last cleared {utc(resolved)} ({ago} ago), after {took}.')
return lines
ISSUE_FIXED = {
'cable_mismatch': 'The cable now matches the cutsheet (or the cutsheet was updated).',
'monitor_source_unavailable': 'Prometheus is returning data again; host and interface alerting has resumed.',
}
def recovery_comment(event: dict, now: datetime, url: str = '', evidence: str = '') -> str:
"""The note Gandalf adds to a ticket when its alert clears. *evidence*: an extra paragraph
on what Gandalf measured during it (the side-by-side pings for a slow internet)."""
first, resolved = event.get('first_seen'), event.get('resolved_at') or now
target = event['target_name'] + (f' {event["target_detail"]}' if event.get('target_detail') else '')
lines = [f'**✅ Cleared**: {event["event_type"].replace("_", " ")} on {target}.', '']
lines.append(f'- **Cleared:** {utc(resolved)}')
if first:
lines.append(f'- **Lasted:** {duration((resolved - first).total_seconds())} '
f'(first seen {utc(first)})')
if event.get('consecutive_failures'):
lines.append(f'- **Failed checks:** {event["consecutive_failures"]}')
if url:
lines.append(f'- **Gandalf:** {url}')
lines += ['', ISSUE_FIXED.get(event['event_type'], 'Gandalf no longer sees the problem.')]
if evidence:
lines += ['', '### What the side-by-side tests showed', '', evidence]
lines += ['', '_Gandalf leaves this ticket open. Close it once you know why it happened, '
'or leave it open if it needs follow-up._']
return '\n'.join(lines)
def incident_comment(name: str, summary: str, checks: Sequence[str], when: str) -> str:
"""A further report that belongs to the incident this ticket is already about."""
lines = [f'**Also seen: {name}** ({when})', '', summary.strip()]
if checks:
lines += ['', '**What to check**'] + [f'{n}. {check}' for n, check in enumerate(checks, 1)]
lines += ['', '_Gandalf added this here instead of opening another ticket, since it is part of '
'the same incident._']
return '\n'.join(lines)
def update_comment(label: str, when: str, lookback_min: int, hold_min: int) -> str:
"""Note on a ticket that a UniFi update finished around the time it was opened."""
return '\n'.join([
f'**UniFi update:** {label} finished at {when}.', '',
f'This ticket was opened within {lookback_min} minutes of that update, which UniFi logs once '
f'it is done. Updating the Network app or the gateway firmware can drop the WAN, and Smart '
f'Power may then power-cycle the modem, so the update is the likely cause.', '',
f'_Gandalf holds new modem and WAN tickets for {hold_min} minutes after an update; anything '
f'still wrong after that gets its own ticket._',
])
def dedup_key_map(events: Sequence[dict], open_ids) -> dict:
"""{ticket_id: dedup_key} for Tinker's backfill_dedup_keys.php, from Gandalf's events.
Only tickets still open in Tinker are listed. When several events share a ticket (a WAN
incident, or a recurrence Tinker folded in), the earliest one opened it, so its key wins.
Events of a type with no key are left out.
"""
open_ids = {str(t) for t in open_ids}
first: dict = {}
for e in sorted(events, key=lambda e: (e.get('first_seen') or datetime.min, e.get('id') or 0)):
tid = str(e.get('ticket_id') or '')
if tid in open_ids and tid not in first:
key = dedup_key(e.get('event_type') or '', e.get('target_name') or '', e.get('target_detail') or '')
if key:
first[tid] = key
return first