From f924ce42c3ff0a1f4d8b65c5dcf4baef96668368 Mon Sep 17 00:00:00 2001 From: Jared Vititoe Date: Wed, 25 Nov 2026 19:51:46 -0500 Subject: [PATCH] Thor contract, part 1: [gandalf] title tag and a read-only API key for Thor Titles move to the shared standard [source][auto][gandalf][network] Summary [scope][production][issue], built in one place (ticket_text.title). Checked by running Tinker's TicketHash.php: every Gandalf title shape hashes the same as before, so open tickets keep matching. Thor can read /api/status, /api/events, /api/attention and /api/suppressions with a machine key (Authorization: Bearer, only its SHA-256 in config, read-only, optional source CIDRs; a wrong key is a 401 and never falls back to identity headers). /api/suppressions ?include_ended=1&hours=N returns every suppression in force in the window with start, planned end, actual end and who ended it: new ended_at/ended_by columns, added automatically. Refs #66 (items 1 and 2) Co-Authored-By: Claude Opus 5.5 --- README.md | 37 ++++++++++++++++- app.py | 82 +++++++++++++++++++++++++++++++++++-- db.py | 85 +++++++++++++++++++++++++++++++++++++-- monitor.py | 24 +++++------ tests/test_app.py | 73 ++++++++++++++++++++++++++++++++- tests/test_db.py | 59 +++++++++++++++++++++++++++ tests/test_monitor.py | 6 +-- tests/test_ticket_text.py | 32 +++++++++++++++ ticket_text.py | 18 +++++++++ 9 files changed, 391 insertions(+), 25 deletions(-) diff --git a/README.md b/README.md index 4c1b6e5..b069a50 100644 --- a/README.md +++ b/README.md @@ -492,7 +492,13 @@ whatever Gandalf knows around the problem: - **Other active alerts** on the same device, with their ticket numbers - **Links** to the device in Gandalf (from `gandalf.public_url`) -Titles keep the `[target][auto][production]...` tag format, which Tinker uses to spot duplicates. +Titles follow the shared standard used by Gandalf, hwmonDaemon and Thor (thor#1): +`[source][auto][gandalf][network] Summary [scope][production][issue]`, for example +`[monitor-01][auto][gandalf][network] Interface enp3s0 link-down [single-node][production][issue]`. +Tinker spots duplicates from the first tag, `[auto]`, the scope and environment tags and the text +outside the tags, so this hashes exactly like the older `[source][auto][production][issue][network][scope] Summary` +form (checked against `helpers/TicketHash.php`): existing tickets keep matching. Build titles with +`ticket_text.title()`. ### Unused interfaces @@ -641,6 +647,35 @@ Expired suppressions are checked at evaluation time: no background cleanup neede --- +## API for other apps (machine keys) + +Thor (and any later app) reads Gandalf's state with a read-only key instead of a signed-in user +(gandalf#66). Send `Authorization: Bearer ` straight to the LXC, `http://10.10.10.61/api/...` +(not through `gandalf.lotusguild.org`, where Authelia would stop it). + +| Route | Gives | +|---|---| +| `GET /api/status` | Summary counts, last check time, active events with suppression flags | +| `GET /api/events` | Active events (`?status=resolved` or `?status=all` for recent resolved ones); includes the `cluster_hosts_stalled` warning naming hosts with OOM kills, Thor's cue | +| `GET /api/attention` | The dashboard's Needs attention list | +| `GET /api/suppressions` | Active suppressions. With `?include_ended=1&hours=N` (default 24, max 744): every suppression in force in that window with `started_at`, `started_by`, `expires_at`, `ended_at`, `ended_by`, `state` (`active`, `ended`, `expired`) and `end_known` | + +A key can't sign in as anyone, can't reach any other route, and can't write: an unknown or wrong +key is refused with 401 even if identity headers are present. Config holds only the key's SHA-256: + +```json +"api_keys": [ + { "name": "thor", "sha256": "", "scopes": ["read"], "sources": ["10.10.10.0/24"] } +] +``` + +`sources` is optional (CIDRs the key may be used from). To make a key: +`python3 -c "import secrets,hashlib; k=secrets.token_urlsafe(32); print(k); print(hashlib.sha256(k.encode()).hexdigest())"`. +Give the first line to the other app and put the second in `config.json`. + +Suppressions record when they ended and who ended them (a user, `gandalf` for its own modem +restart silence, or `expired`). Ones removed by hand before this was added show `end_known: false`. + ## Configuration (`config.json`) Shared by both processes. Located in the working directory (`/var/www/html/prod/`). diff --git a/app.py b/app.py index 3f703c6..ebe8c2f 100644 --- a/app.py +++ b/app.py @@ -5,6 +5,7 @@ management UI. Authentication via Authelia forward-auth headers. All monitoring and alerting is handled by the separate monitor.py daemon. """ import hashlib +import hmac import html import ipaddress import json @@ -15,7 +16,7 @@ import tempfile import threading import time import uuid -from datetime import datetime, timezone +from datetime import datetime, timedelta, timezone from functools import wraps from typing import Optional from urllib.parse import quote, urlparse @@ -237,6 +238,63 @@ def require_auth(f): return wrapper +# Machine keys (gandalf#66): another app, Thor first, reads Gandalf's state with +# Authorization: Bearer +# config: "api_keys": [{"name": "thor", "sha256": "", "scopes": ["read"], +# "sources": ["10.10.10.0/24"]}] (sources optional) +# Only the digest is kept in config. A key grants read-only access to the routes marked +# @allow_machine_key, never identity, admin, or anything that writes. +def _machine_key() -> Optional[str]: + """The name of the machine key on this request, '' if none was sent, None if it is invalid.""" + header = request.headers.get('Authorization', '') + if not header.startswith('Bearer '): + return '' + digest = hashlib.sha256(header[7:].strip().encode()).hexdigest() + for entry in _config().get('api_keys') or []: + want = str(entry.get('sha256') or '').lower() + if not want or not hmac.compare_digest(digest, want) or 'read' not in (entry.get('scopes') or []): + continue + sources = entry.get('sources') or [] + if sources and not _source_in(_request_source(), sources): + logger.warning(f'Machine key {entry.get("name")!r} used from {_request_source()!r}, outside its sources') + return None + return str(entry.get('name') or 'machine') + return None + + +def _source_in(source: str, networks: list) -> bool: + try: + addr = ipaddress.ip_address(source) + except ValueError: + return False + for net in networks: + try: + if addr in ipaddress.ip_network(net, strict=False): + return True + except ValueError: + logger.error(f'Ignoring invalid api_keys source {net!r}') + return False + + +def allow_machine_key(f): + """Let a read-only machine key through, in place of a signed-in user. Use above @require_auth. + + A request with no Authorization header goes on to the normal sign-in check; one with a bad + or unknown key is refused outright, so a typo never falls back to someone else's identity. + """ + @wraps(f) + def wrapper(*args, **kwargs): + name = _machine_key() + if name is None: + return jsonify({'error': 'Invalid API key'}), 401 + if name: + if request.method != 'GET': + return jsonify({'error': 'API keys are read-only'}), 403 + return f.__wrapped__(*args, **kwargs) + return f(*args, **kwargs) + return wrapper + + def require_admin(f): """Decorator: require require_auth AND membership in the 'admin' group.""" @wraps(f) @@ -487,6 +545,7 @@ def suppressions_page(): # --------------------------------------------------------------------------- @app.route('/api/status') +@allow_machine_key @require_auth def api_status(): active = db.get_active_events(limit=_PAGE_LIMIT) @@ -623,7 +682,7 @@ def api_modem_restart(): db.set_state('modem_restart', {'at': time.time(), 'by': user, 'result': 'failed', 'finished_at': time.time(), 'back': False, 'smart_power_paused': paused, 'smart_power_error': err}) - db.deactivate_suppression(sup_id) + db.deactivate_suppression(sup_id, ended_by=user) if kuma_on: try: kuma.set_maintenance(kuma_cfg, False) @@ -708,6 +767,7 @@ def api_device(name: str): @app.route('/api/events') +@allow_machine_key @require_auth def api_events(): try: @@ -729,9 +789,22 @@ def api_events(): @app.route('/api/suppressions', methods=['GET']) +@allow_machine_key @require_auth def api_get_suppressions(): - return jsonify(db.get_active_suppressions()) + """Active suppressions; with ?include_ended=1, every one in force in the last `hours` (default + 24, at most 31 days), with start, planned end, actual end, who and scope (see + db.get_suppression_windows). Thor reads the second form to tell planned windows from outages.""" + if request.args.get('include_ended') not in ('1', 'true'): + return jsonify(db.get_active_suppressions()) + try: + hours = float(request.args.get('hours', 24)) + except ValueError: + return jsonify({'error': 'hours must be a number'}), 400 + if not 0 < hours <= 31 * 24: + return jsonify({'error': 'hours must be between 0 and 744 (31 days)'}), 400 + since = datetime.now(timezone.utc).replace(tzinfo=None) - timedelta(hours=hours) + return jsonify({'since': since.isoformat() + 'Z', 'suppressions': db.get_suppression_windows(since)}) @app.route('/api/suppressions', methods=['POST']) @@ -788,7 +861,7 @@ def api_create_suppression(): @require_admin def api_delete_suppression(sup_id: int): user = _get_user() - db.deactivate_suppression(sup_id) + db.deactivate_suppression(sup_id, ended_by=user['username']) logger.info(f'Suppression #{sup_id} removed by {user["username"]}') return jsonify({'success': True}) @@ -1440,6 +1513,7 @@ def api_topology(): @app.route('/api/attention') +@allow_machine_key @require_auth def api_attention(): """Everything that needs looking at, from every page, for the dashboard (see attention.build).""" diff --git a/db.py b/db.py index 4859485..98c1d50 100644 --- a/db.py +++ b/db.py @@ -397,21 +397,100 @@ def create_suppression( return cur.lastrowid -def deactivate_suppression(sup_id: int) -> None: +_suppression_schema_ready = False + + +def ensure_suppression_schema() -> None: + """Add ended_at/ended_by (gandalf#66), so a removed suppression keeps its end time. + + Thor decides from history whether a window was planned, so it needs every suppression's + start and end, not only the active ones. Runs once per process; no manual migration. + """ + global _suppression_schema_ready + if _suppression_schema_ready: + return + with get_conn() as conn: + with conn.cursor() as cur: + cur.execute('SHOW COLUMNS FROM suppression_rules') + have = {r['Field'] for r in cur.fetchall()} + if 'ended_at' not in have: + cur.execute('ALTER TABLE suppression_rules ADD COLUMN ended_at TIMESTAMP NULL') + # Expired ones already ended at their expiry; ones removed by hand before this + # column existed keep ended_at NULL: their end time was never recorded + cur.execute('UPDATE suppression_rules SET ended_at=expires_at ' + 'WHERE active=FALSE AND expires_at IS NOT NULL AND expires_at <= NOW()') + if 'ended_by' not in have: + cur.execute("ALTER TABLE suppression_rules ADD COLUMN ended_by VARCHAR(255) NOT NULL DEFAULT ''") + _suppression_schema_ready = True + + +def deactivate_suppression(sup_id: int, ended_by: str = '') -> None: + ensure_suppression_schema() with get_conn() as conn: with conn.cursor() as cur: cur.execute( - 'UPDATE suppression_rules SET active=FALSE WHERE id=%s', (sup_id,) + 'UPDATE suppression_rules SET active=FALSE, ended_at=NOW(), ended_by=%s ' + 'WHERE id=%s AND active=TRUE', + (ended_by or '', sup_id), ) +def get_suppression_windows(since: datetime) -> list: + """Every suppression in force at any point since `since` (naive UTC), oldest first. + + Each: id, target_type, target_name, target_detail, reason, started_at, started_by, + expires_at (planned end, None = until removed), ended_at, ended_by, state + ('active', 'ended' or 'expired'), end_known. Times are ISO 8601 UTC with a Z. + """ + ensure_suppression_schema() + with get_conn() as conn: + with conn.cursor() as cur: + cur.execute( + """SELECT * FROM suppression_rules + WHERE (active=TRUE AND (expires_at IS NULL OR expires_at > NOW())) + OR COALESCE(ended_at, expires_at) >= %s + OR (ended_at IS NULL AND expires_at IS NULL AND created_at >= %s) + ORDER BY created_at""", + (since, since), + ) + rows = cur.fetchall() + now = datetime.now(timezone.utc).replace(tzinfo=None) + out = [] + for r in rows: + expires, ended = r.get('expires_at'), r.get('ended_at') + live = bool(r.get('active')) and (expires is None or expires > now) + if live: + state, end = 'active', None + elif ended is not None: + # Removed by hand, or by Gandalf's own restart flow, before or at expiry + state, end = ('expired' if expires is not None and ended >= expires else 'ended'), ended + elif expires is not None and expires <= now: + state, end = 'expired', expires + else: + state, end = 'ended', None # removed before end times were recorded + out.append({ + 'id': r['id'], 'target_type': r['target_type'], 'target_name': r.get('target_name') or '', + 'target_detail': r.get('target_detail') or '', 'reason': r.get('reason') or '', + 'started_at': _iso_z(r.get('created_at')), 'started_by': r.get('suppressed_by') or '', + 'expires_at': _iso_z(expires), 'ended_at': _iso_z(end), + 'ended_by': r.get('ended_by') or ('expired' if state == 'expired' else ''), + 'state': state, 'end_known': live or end is not None, + }) + return out + + +def _iso_z(value) -> Optional[str]: + return value.isoformat() + 'Z' if value is not None and hasattr(value, 'isoformat') else None + + def cleanup_expired_suppressions() -> int: """Mark expired time-limited suppressions as inactive. Returns count deactivated.""" + ensure_suppression_schema() with get_conn() as conn: with conn.cursor() as cur: cur.execute( """UPDATE suppression_rules - SET active=FALSE + SET active=FALSE, ended_at=expires_at, ended_by='expired' WHERE active=TRUE AND expires_at IS NOT NULL AND expires_at <= NOW()""" ) n = cur.rowcount diff --git a/monitor.py b/monitor.py index d51ee57..f51ca06 100644 --- a/monitor.py +++ b/monitor.py @@ -1638,7 +1638,7 @@ class NetworkMonitor: grace = reboots.grace_for(host, self.cfg.get('monitor', {})) self._open_ticket( event_id, 'host_metrics_missing', host, instance, - title=f'[{host}][auto][production][issue][network][single-node] Planned reboot did not come back', + title=ticket_text.title(host, 'Planned reboot did not come back'), heading='Host Reboot Alert', facts=[('Host', host), ('Prometheus instance', instance), ('Shutdown requested', f'{_fmt_ts(shutdown["at"])} ({shutdown["kind"]})'), @@ -1695,8 +1695,7 @@ class NetworkMonitor: shared = sorted({u['switch'] for h in hosts for u in self._uplinks_for(h, switches)[0]}) self._open_ticket( event_id, 'cluster_network_issue', self.cluster_name, '', - title=(f'[{self.cluster_name}][auto][production][issue][network][cluster-wide] ' - f'Multiple hosts reporting interface failures'), + title=ticket_text.title(self.cluster_name, 'Multiple hosts reporting interface failures', 'cluster-wide'), heading='Cluster Network Alert', facts=[('Affected hosts', ', '.join(hosts)), ('Switches they connect through', ', '.join(shared)), @@ -1715,7 +1714,7 @@ class NetworkMonitor: ) -> None: self._open_ticket( event_id, 'host_metrics_missing', host, instance, - title=f'[{host}][auto][production][issue][network][single-node] No metrics from host', + title=ticket_text.title(host, 'No metrics from host'), heading='Host Metrics Alert', facts=[('Host', host), ('Prometheus instance', instance), ('Detected', _now_utc()), ('Consecutive check failures', str(consec)), @@ -1745,7 +1744,7 @@ class NetworkMonitor: if not sup and consec >= self.fail_thresh and not ticket_id: self._open_ticket( event_id, 'monitor_source_unavailable', 'prometheus', '', - title='[prometheus][auto][production][issue][network][cluster-wide] Gandalf has no Prometheus data', + title=ticket_text.title('prometheus', 'Gandalf has no Prometheus data', 'cluster-wide'), heading='Monitoring Source Alert', facts=[('Prometheus URL', self.prom.url), ('Detected', _now_utc()), ('Consecutive check failures', str(consec))], @@ -1763,7 +1762,7 @@ class NetworkMonitor: ) -> None: self._open_ticket( event_id, 'interface_down', host, iface, - title=f'[{host}][auto][production][issue][network][single-node] Interface {iface} link-down', + title=ticket_text.title(host, f'Interface {iface} link-down'), heading='Network Interface Alert', facts=[('Host', host), ('Interface', f'`{iface}`'), ('Detected', _now_utc()), ('Consecutive check failures', str(consec))], @@ -1802,7 +1801,7 @@ class NetworkMonitor: name = device['name'] self._open_ticket( event_id, 'unifi_device_offline', name, device.get('type', ''), - title=f'[{name}][auto][production][issue][network][single-node] UniFi device offline', + title=ticket_text.title(name, 'UniFi device offline'), heading='UniFi Device Alert', facts=[('Device', name), ('Type', device.get('type', 'unknown')), ('Model', device.get('model', '')), ('Last known IP', device.get('ip', 'unknown')), ('Detected', _now_utc())], @@ -1851,8 +1850,7 @@ class NetworkMonitor: url = ticket_text.cutsheet_url(self._base_url(), p['cable_id']) self._open_ticket( event_id, 'cable_mismatch', p['switch'], p['key'], - title=(f'[{p["switch"]}][auto][production][issue][network][single-node] ' - f'Cable {p["label"]} does not match the cutsheet'), + title=ticket_text.title(p['switch'], f'Cable {p["label"]} does not match the cutsheet'), heading='Cutsheet Mismatch', facts=[('Cable', ticket_text.link(p['label'], url)), ('Switch port', f'{p["switch"]} port {p["port"]}'), ('Problem', p['detail']), ('Documented path', p['path']), ('Detected', _now_utc())], @@ -1893,7 +1891,7 @@ class NetworkMonitor: ) -> None: self._open_ticket( event_id, 'host_unreachable', name, ip, - title=f'[{name}][auto][production][issue][network][single-node] Host unreachable', + title=ticket_text.title(name, 'Host unreachable'), heading='Host Reachability Alert', facts=[('Host', name), ('IP', ip), ('Detected', _now_utc()), ('Consecutive check failures', str(consec)), @@ -1927,7 +1925,7 @@ class NetworkMonitor: if not sup and consec >= self.modem_fail_thresh and not ticket_id: self._queue_wan_ticket({ 'event_id': event_id, 'event_type': event_type, 'detail': detail, - 'title': f'[{name}][auto][production][issue][network][cluster-wide] {heading}', + 'title': ticket_text.title(name, heading, 'cluster-wide'), 'name': heading, 'heading': 'WAN Modem Alert', 'facts': [('Modem', f'{name} ({self.modem.base_url})'), ('Detected', _now_utc()), ('Consecutive check failures', str(consec))], @@ -2155,7 +2153,7 @@ class NetworkMonitor: if not db.check_suppressed(suppressions, 'host', name) and not ticket_id: self._queue_wan_ticket({ 'event_id': event_id, 'event_type': event_type, 'detail': '', - 'title': f'[{name}][auto][production][issue][network][cluster-wide] {heading}', + 'title': ticket_text.title(name, heading, 'cluster-wide'), 'name': heading, 'heading': 'WAN Event', 'facts': [('Modem', name), ('Reported', _now_utc())], 'summary': description, 'checks': [advice], 'priority': priority, 'recovers': False, @@ -2346,7 +2344,7 @@ class NetworkMonitor: return # try again next cycle state['kuma_error'] = str(e) if state.get('suppression_id'): - db.deactivate_suppression(state['suppression_id']) + db.deactivate_suppression(state['suppression_id'], ended_by='gandalf') if state.get('smart_power_paused'): self._restore_smart_power(state) state.update(finished_at=now, back=bool(back), rebooted=rebooted, diff --git a/tests/test_app.py b/tests/test_app.py index 44f0555..570995f 100644 --- a/tests/test_app.py +++ b/tests/test_app.py @@ -135,6 +135,77 @@ class TestPagesAndNav: assert client.get('/api/links', headers=AUTH).status_code == 200 +import hashlib # noqa: E402 + +THOR_KEY = 'test-thor-key-not-real' +KEYS = [{'name': 'thor', 'sha256': hashlib.sha256(THOR_KEY.encode()).hexdigest(), 'scopes': ['read']}] +BEARER = {'Authorization': f'Bearer {THOR_KEY}'} + + +@pytest.fixture +def key_client(client): + with patch.object(gandalf, '_cfg', dict(CONFIG, api_keys=KEYS)): + yield client + + +class TestMachineKey: + """gandalf#66: Thor reads status, events, attention and suppressions with a read-only key.""" + + def test_reads_with_the_key(self, key_client): + for url in ('/api/status', '/api/events', '/api/attention', '/api/suppressions'): + assert key_client.get(url, headers=BEARER).status_code == 200, url + + def test_wrong_key_is_refused_even_with_identity_headers(self, key_client): + resp = key_client.get('/api/status', headers=dict(AUTH, Authorization='Bearer nope')) + assert resp.status_code == 401 and resp.get_json()['error'] == 'Invalid API key' + + def test_key_opens_only_the_marked_routes(self, key_client): + assert key_client.get('/api/devices', headers=BEARER).status_code == 401 + assert key_client.get('/', headers=BEARER).status_code == 401 + + def test_key_cannot_write(self, key_client): + resp = key_client.post('/api/suppressions', headers=BEARER, json={'target_type': 'all', 'reason': 'x'}) + assert resp.status_code in (401, 403, 405) + assert not gandalf.db.create_suppression.called + + def test_no_key_configured_means_no_key_works(self, client): + assert client.get('/api/status', headers=BEARER).status_code == 401 + + def test_key_without_read_scope(self, client): + keys = [dict(KEYS[0], scopes=[])] + with patch.object(gandalf, '_cfg', dict(CONFIG, api_keys=keys)): + assert client.get('/api/status', headers=BEARER).status_code == 401 + + def test_source_restriction(self, client): + keys = [dict(KEYS[0], sources=['10.10.10.0/24'])] + with patch.object(gandalf, '_cfg', dict(CONFIG, api_keys=keys)): + inside = client.get('/api/status', headers=BEARER, environ_base={'REMOTE_ADDR': '10.10.10.70'}) + outside = client.get('/api/status', headers=BEARER, environ_base={'REMOTE_ADDR': '192.168.1.5'}) + assert inside.status_code == 200 and outside.status_code == 401 + + def test_users_still_sign_in_as_before(self, key_client): + assert key_client.get('/api/status', headers=AUTH).status_code == 200 + assert key_client.get('/api/status').status_code == 401 + + def test_ended_suppressions_for_thor(self, key_client): + gandalf.db.get_suppression_windows.return_value = [{'id': 2, 'state': 'expired'}] + data = key_client.get('/api/suppressions?include_ended=1&hours=48', headers=BEARER).get_json() + assert data['suppressions'] == [{'id': 2, 'state': 'expired'}] and data['since'].endswith('Z') + since = gandalf.db.get_suppression_windows.call_args.args[0] + assert 47.9 < (datetime.utcnow() - since).total_seconds() / 3600 < 48.1 + + def test_ended_suppressions_bad_hours(self, key_client): + for h in ('x', '0', '800'): + assert key_client.get(f'/api/suppressions?include_ended=1&hours={h}', headers=BEARER).status_code == 400 + + def test_stalled_cluster_warning_reaches_thor(self, key_client): + stalled = {'event_type': 'cluster_hosts_stalled', 'severity': 'warning', 'target_name': 'proxmox-cluster', + 'target_detail': '', 'description': '3 hosts stopped answering ... OOM kills on compute-storage-01'} + gandalf.db.get_active_events.return_value = [stalled] + events = key_client.get('/api/events', headers=BEARER).get_json()['active'] + assert events[0]['event_type'] == 'cluster_hosts_stalled' and 'OOM' in events[0]['description'] + + class TestDeviceApi: def test_requires_auth(self, client): assert client.get('/api/devices').status_code == 401 @@ -974,7 +1045,7 @@ class TestModemRestart: def test_failed_restart_undoes_the_silence(self, client): resp, km, _ = self._post(client, restart=gandalf.modem_api.ModemUnreachable('timeout')) assert resp.status_code == 502 - gandalf.db.deactivate_suppression.assert_called_once_with(42) + gandalf.db.deactivate_suppression.assert_called_once_with(42, ended_by='jared') assert km.call_args_list[-1].args == (self.CFG['uptime_kuma'], False) def test_one_at_a_time(self, client): diff --git a/tests/test_db.py b/tests/test_db.py index 1863cc2..9674f1e 100644 --- a/tests/test_db.py +++ b/tests/test_db.py @@ -84,3 +84,62 @@ class TestPowerFeeds: 'updated_at': NOW}]) with patcher: assert db.get_power_feeds()[0]['updated_at'] == '2026-11-14T12:00:00Z' + + +class TestSuppressionWindows: + """gandalf#66: Thor reads every suppression with its start and end to tell planned windows + from outages. 2026-11-25: the only record the rack maintenance was planned was row 2.""" + + @staticmethod + def _row(i, created_h, expires_h=None, ended_h=None, active=False, ended_by=''): + now = datetime.utcnow() + at = lambda h: None if h is None else now - timedelta(hours=h) # noqa: E731 + return {'id': i, 'target_type': 'all', 'target_name': '', 'target_detail': '', 'reason': 'switch update', + 'suppressed_by': 'jared', 'created_at': at(created_h), 'expires_at': at(expires_h), + 'ended_at': at(ended_h), 'ended_by': ended_by, 'active': active} + + def _windows(self, rows): + db._suppression_schema_ready = True + patcher, cur = _fake_conn(rows) + with patcher: + return db.get_suppression_windows(datetime.utcnow() - timedelta(hours=24)) + + def test_expired_window_has_its_end(self): + [w] = self._windows([self._row(2, 12, expires_h=11.5, ended_h=11.5, ended_by='expired')]) + assert w['state'] == 'expired' and w['end_known'] and w['ended_by'] == 'expired' + assert w['started_at'].endswith('Z') and w['ended_at'] == w['expires_at'] + + def test_removed_by_hand_before_expiry(self): + [w] = self._windows([self._row(3, 5, expires_h=1, ended_h=4, ended_by='jared')]) + assert w['state'] == 'ended' and w['ended_by'] == 'jared' and w['ended_at'] != w['expires_at'] + + def test_active_has_no_end(self): + [w] = self._windows([self._row(4, 1, active=True)]) + assert w['state'] == 'active' and w['ended_at'] is None and w['end_known'] + + def test_expired_but_not_yet_cleaned_up(self): + [w] = self._windows([self._row(5, 3, expires_h=2, active=True)]) + assert w['state'] == 'expired' and w['ended_at'] == w['expires_at'] and w['ended_by'] == 'expired' + + def test_removed_before_end_times_were_recorded(self): + [w] = self._windows([self._row(6, 6)]) + assert w['state'] == 'ended' and not w['end_known'] and w['ended_at'] is None + + def test_deactivate_records_who_and_when(self): + db._suppression_schema_ready = True + patcher, cur = _fake_conn([]) + with patcher: + db.deactivate_suppression(7, ended_by='jared') + sql, args = cur.execute.call_args.args + assert 'ended_at=NOW()' in sql and 'ended_by=%s' in sql and args == ('jared', 7) + + def test_schema_adds_the_columns_once(self): + db._suppression_schema_ready = False + patcher, cur = _fake_conn([{'Field': 'id'}, {'Field': 'active'}]) + with patcher: + db.ensure_suppression_schema() + db.ensure_suppression_schema() + sqls = [c.args[0] for c in cur.execute.call_args_list] + assert sum('ADD COLUMN ended_at' in q for q in sqls) == 1 + assert sum('ADD COLUMN ended_by' in q for q in sqls) == 1 + assert db._suppression_schema_ready diff --git a/tests/test_monitor.py b/tests/test_monitor.py index 72c5abc..0ce8db8 100644 --- a/tests/test_monitor.py +++ b/tests/test_monitor.py @@ -1096,7 +1096,7 @@ class TestTicketContext: mon.unifi_fail_thresh = 3 self._mon(mon)._ticket_unifi(1, {'name': 'ap1', 'type': 'uap', 'model': 'U6', 'ip': '1.2.3.4'}) assert mon.tickets.create.call_args.args[0] == \ - '[ap1][auto][production][issue][network][single-node] UniFi device offline' + '[ap1][auto][gandalf][network] UniFi device offline [single-node][production][issue]' def test_remember_uplinks_saves_only_on_change(self, mon, db): self._mon(mon) @@ -1487,7 +1487,7 @@ class TestFinishModemRestart: def test_back_ends_kuma_and_the_silence(self, mon, db): out, km = self._run(mon, db, self._restart(300), {'reachable': True, 'wan_problems': [], 'uptime_s': 200}) km.assert_called_once_with({'url': 'http://kuma.test'}, False) - db.deactivate_suppression.assert_called_once_with(9) + db.deactivate_suppression.assert_called_once_with(9, ended_by='gandalf') assert out['back'] and out['rebooted'] and out['back_after_s'] == 300 and out['finished_at'] == self.NOW def test_waits_while_the_modem_is_down(self, mon, db): @@ -1505,7 +1505,7 @@ class TestFinishModemRestart: def test_gives_up_after_half_an_hour(self, mon, db): out, km = self._run(mon, db, self._restart(1900), {'reachable': False}) assert out['back'] is False and out['back_after_s'] is None and km.called - db.deactivate_suppression.assert_called_once_with(9) + db.deactivate_suppression.assert_called_once_with(9, ended_by='gandalf') def test_kuma_failure_retries_next_cycle(self, mon, db): out, _ = self._run(mon, db, self._restart(300), {'reachable': True, 'wan_problems': [], 'uptime_s': 200}, diff --git a/tests/test_ticket_text.py b/tests/test_ticket_text.py index ab27e5e..a09a4f0 100644 --- a/tests/test_ticket_text.py +++ b/tests/test_ticket_text.py @@ -1,8 +1,11 @@ """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 @@ -62,3 +65,32 @@ def test_recovery_comment(): 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') diff --git a/ticket_text.py b/ticket_text.py index 40ee78d..9ec1b25 100644 --- a/ticket_text.py +++ b/ticket_text.py @@ -9,6 +9,24 @@ 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]' + + def duration(seconds) -> str: seconds = max(0, int(seconds)) if seconds < 60: -- 2.47.3