gandalf#66 items 3, 4 and 5. - thor.py: ThorClient.covering() calls Thor's /api/incidents/covering with a 4 s timeout. No config, any error, a timeout or a shadow-only answer all mean "not covered" (fail open). - No metrics from host, planned reboot didn't come back and ping host unreachable ask Thor by host, only when every switch port of the host is up. A port down is Gandalf's network evidence, so it keeps the ticket. - No Prometheus data asks with scope=source:prometheus. - Interface and cluster network tickets never ask: they are network evidence, so they are Gandalf's under the contract. - When Thor names a ticket, Gandalf posts its report there as an "Also seen by Gandalf" comment and tracks that ticket for the alert. - Every ticket sends a dedup_key (ticket_text.dedup_key, scheme in the README). scripts/dedup_key_map.py prints the keys for Gandalf's open tickets, for Tinker's backfill_dedup_keys.php. Co-Authored-By: Claude Opus 5.5 <[email protected]>
136 lines
6.8 KiB
Python
136 lines
6.8 KiB
Python
"""Tests for ticket_text.py: the Markdown Gandalf puts in tickets."""
|
|
import os
|
|
import re
|
|
import sys
|
|
from datetime import datetime, timedelta
|
|
|
|
import pytest
|
|
|
|
sys.path.insert(0, os.path.dirname(os.path.dirname(__file__)))
|
|
|
|
import ticket_text as tt # noqa: E402
|
|
|
|
NOW = datetime(2026, 11, 10, 18, 0)
|
|
|
|
|
|
def test_duration():
|
|
assert tt.duration(42) == '42 s'
|
|
assert tt.duration(600) == '10 min'
|
|
assert tt.duration(3600) == '1 h'
|
|
assert tt.duration(3 * 3600 + 120) == '3 h 2 min'
|
|
assert tt.duration(3 * 86400 + 7200) == '3 d 2 h'
|
|
|
|
|
|
def test_speed():
|
|
assert tt.speed(100) == '100 Mbps'
|
|
assert tt.speed(2500) == '2.5 Gbps'
|
|
assert tt.speed(10000) == '10 Gbps'
|
|
assert tt.speed(0) == ''
|
|
|
|
|
|
def test_device_url_escapes_names():
|
|
assert tt.device_url('https://g', 'USW Flex Mini', 3) == 'https://g/device/USW%20Flex%20Mini#port-3'
|
|
assert tt.device_url('', 'x') == ''
|
|
|
|
|
|
def test_port_text():
|
|
assert tt.port_text('sw', 'Port 4', {'port_idx': 4, 'up': True, 'speed_mbps': 1000, 'poe_power': 4.21}) == \
|
|
'sw port 4: up at 1 Gbps, PoE 4.2 W'
|
|
assert tt.port_text('sw', 'Cam', {'port_idx': 9, 'up': False,
|
|
'sfp': {'found': True, 'kind': 'optic', 'part': 'SR', 'rx_fault': True}}) == \
|
|
'sw port 9 "Cam": down, module: optic SR, **module reports a fault**'
|
|
|
|
|
|
def test_description_skips_empty_facts_and_sections():
|
|
text = tt.description('Alert', [('Host', 'a'), ('Blank', '')], 'Summary.', ['One', 'Two'],
|
|
[('Empty', []), ('Links', ['- x'])])
|
|
assert text.startswith('## Alert\n\n- **Host:** a\n\nSummary.')
|
|
assert 'Blank' not in text and '### Empty' not in text
|
|
assert '1. One\n2. Two' in text and '### Links\n- x' in text
|
|
|
|
|
|
def test_history_lines():
|
|
assert tt.history_lines({'last_7d': 0, 'last_30d': 0}, NOW) == ['- First time in the last 30 days.']
|
|
lines = tt.history_lines({'last_7d': 1, 'last_30d': 2, 'last_first_seen': NOW - timedelta(hours=26),
|
|
'last_resolved_at': NOW - timedelta(hours=25, minutes=55)}, NOW)
|
|
assert lines[0].startswith('- Happened 1 time in the last 7 days and 2')
|
|
assert lines[1] == '- Last cleared 2026-11-09 16:05 UTC (25 h 55 min ago), after 5 min.'
|
|
|
|
|
|
def test_recovery_comment():
|
|
text = tt.recovery_comment({'event_type': 'interface_down', 'target_name': 'large1', 'target_detail': 'eno1',
|
|
'first_seen': NOW - timedelta(minutes=7), 'resolved_at': NOW,
|
|
'consecutive_failures': 3}, NOW, 'https://g/device/large1')
|
|
assert text.startswith('**✅ Cleared**: interface down on large1 eno1.')
|
|
assert '- **Lasted:** 7 min (first seen 2026-11-10 17:53 UTC)' in text
|
|
assert '- **Gandalf:** https://g/device/large1' in text
|
|
assert 'leaves this ticket open' in text
|
|
|
|
|
|
class TestTitle:
|
|
"""The shared title standard (thor#1, gandalf#66): [source][auto][app][area] Summary [scope][env][type]."""
|
|
|
|
@staticmethod
|
|
def _hash_parts(title):
|
|
# What Tinker's TicketHash.php reads from an automated network title: the first tag, the
|
|
# environment and scope tags, and the text outside the tags. Same title parts, same ticket.
|
|
tags = re.findall(r'\[([^\]]+)\]', title)
|
|
env = sorted(t for t in tags if t in ('production', 'development', 'staging', 'single-node', 'cluster-wide'))
|
|
heading = re.sub(r'\[[^\]]*\]', '', title).strip(' -\t')
|
|
return tags[0], '[auto]' in title, 'network' in title.lower(), env, heading
|
|
|
|
def test_format(self):
|
|
assert tt.title('monitor-01', 'Interface enp3s0 link-down') == \
|
|
'[monitor-01][auto][gandalf][network] Interface enp3s0 link-down [single-node][production][issue]'
|
|
assert tt.title('att-modem', 'WAN down', 'cluster-wide').endswith('WAN down [cluster-wide][production][issue]')
|
|
|
|
def test_hashes_like_the_old_format(self):
|
|
for source, summary, scope in (('monitor-01', 'Interface enp3s0 link-down', 'single-node'),
|
|
('att-modem', 'Internet degraded (high latency or packet loss)', 'cluster-wide'),
|
|
('24RJ45-POE', 'Cable C07 does not match the cutsheet', 'single-node')):
|
|
old = f'[{source}][auto][production][issue][network][{scope}] {summary}'
|
|
assert self._hash_parts(tt.title(source, summary, scope)) == self._hash_parts(old)
|
|
|
|
def test_unknown_scope_is_refused(self):
|
|
with pytest.raises(ValueError):
|
|
tt.title('x', 'y', 'rack')
|
|
|
|
|
|
class TestDedupKey:
|
|
def test_scheme(self):
|
|
k = tt.dedup_key
|
|
assert k('interface_down', 'monitor-01', 'enp3s0') == 'host:monitor-01:iface_down:enp3s0'
|
|
assert k('host_metrics_missing', 'storage-01', '10.10.10.11:9100') == 'host:storage-01:metrics_missing'
|
|
assert k('host_unreachable', 'pbs', '10.10.10.3') == 'device:pbs:unreachable'
|
|
assert k('unifi_device_offline', 'USW Pro 24 PoE', '') == 'device:usw-pro-24-poe:offline'
|
|
assert k('cable_mismatch', 'agg', 'cable 12') == 'device:agg:cable_mismatch:cable-12'
|
|
assert k('cluster_network_issue', 'proxmox-cluster', '') == 'cluster:network:failure'
|
|
assert k('monitor_source_unavailable', 'prometheus', '') == 'source:prometheus:unavailable'
|
|
assert k('wan_down', 'att-modem', '') == 'site:wan:wan_down'
|
|
assert k('fiber_signal_alarm', 'att-modem', 'rx_power') == 'site:wan:fiber_signal_alarm:rx_power'
|
|
|
|
def test_unknown_type_has_no_key(self):
|
|
assert tt.dedup_key('host_rebooting', 'alpha', '') is None
|
|
|
|
def test_keys_fit_tinkers_format(self):
|
|
key = tt.dedup_key('interface_down', 'Weird Host/Name' * 20, 'eth0@if12')
|
|
assert re.fullmatch(r'[a-z0-9_.:-]{1,128}', key)
|
|
|
|
|
|
class TestDedupKeyMap:
|
|
def test_open_tickets_only_and_the_first_event_wins(self):
|
|
events = [
|
|
{'id': 2, 'event_type': 'wan_degraded', 'target_name': 'att-modem', 'target_detail': '',
|
|
'first_seen': datetime(2026, 11, 20, 10, 5), 'ticket_id': '500'},
|
|
{'id': 1, 'event_type': 'wan_down', 'target_name': 'att-modem', 'target_detail': '',
|
|
'first_seen': datetime(2026, 11, 20, 10, 0), 'ticket_id': '500'},
|
|
{'id': 3, 'event_type': 'interface_down', 'target_name': 'monitor-01', 'target_detail': 'enp3s0',
|
|
'first_seen': datetime(2026, 11, 21), 'ticket_id': '600'},
|
|
{'id': 4, 'event_type': 'interface_down', 'target_name': 'beta', 'target_detail': 'eth0',
|
|
'first_seen': datetime(2026, 11, 1), 'ticket_id': '700'}, # closed in Tinker
|
|
{'id': 5, 'event_type': 'host_rebooting', 'target_name': 'gamma', 'target_detail': '',
|
|
'first_seen': None, 'ticket_id': '800'}, # no key for this type
|
|
]
|
|
assert tt.dedup_key_map(events, ['500', '600', '800']) == {
|
|
'500': 'site:wan:wan_down', '600': 'host:monitor-01:iface_down:enp3s0'}
|