|
| 1 | +"""Grafana deployment-annotations query tool for change correlation.""" |
| 2 | + |
| 3 | +from __future__ import annotations |
| 4 | + |
| 5 | +import time |
| 6 | +from datetime import UTC, datetime |
| 7 | +from typing import Any |
| 8 | + |
| 9 | +from app.services.grafana.base import _epoch_ms_to_iso, _map_annotation |
| 10 | +from app.tools.GrafanaLogsTool import ( |
| 11 | + _grafana_available, |
| 12 | + _grafana_creds, |
| 13 | + _grafana_source, |
| 14 | + _resolve_grafana_client, |
| 15 | +) |
| 16 | +from app.tools.tool_decorator import tool |
| 17 | + |
| 18 | + |
| 19 | +def _query_grafana_annotations_extract_params(sources: dict[str, dict]) -> dict[str, Any]: |
| 20 | + grafana = _grafana_source(sources) |
| 21 | + return { |
| 22 | + "time_range_minutes": grafana.get("time_range_minutes", 60), |
| 23 | + "grafana_backend": grafana.get("_backend"), |
| 24 | + **_grafana_creds(grafana), |
| 25 | + } |
| 26 | + |
| 27 | + |
| 28 | +def _query_grafana_annotations_available(sources: dict[str, dict]) -> bool: |
| 29 | + return _grafana_available(sources) |
| 30 | + |
| 31 | + |
| 32 | +def _normalize_backend_annotations(raw: Any) -> list[dict[str, Any]]: |
| 33 | + """Normalize fixture/backend ``/api/annotations`` arrays to the client shape.""" |
| 34 | + if not isinstance(raw, list): |
| 35 | + return [] |
| 36 | + return [_map_annotation(item) for item in raw if isinstance(item, dict)] |
| 37 | + |
| 38 | + |
| 39 | +def _iso_to_epoch_ms(value: str) -> int: |
| 40 | + """Parse an ISO 8601 timestamp to epoch milliseconds (UTC). Raises ValueError if invalid. |
| 41 | +
|
| 42 | + A timezone-naive value (no ``Z`` / offset) is interpreted as UTC, not host-local time. |
| 43 | + """ |
| 44 | + dt = datetime.fromisoformat(value.replace("Z", "+00:00")) |
| 45 | + if dt.tzinfo is None: |
| 46 | + dt = dt.replace(tzinfo=UTC) |
| 47 | + return int(dt.timestamp() * 1000) |
| 48 | + |
| 49 | + |
| 50 | +@tool( |
| 51 | + name="query_grafana_annotations", |
| 52 | + display_name="Grafana annotations", |
| 53 | + source="grafana", |
| 54 | + description=( |
| 55 | + "Query Grafana deployment/config-change annotations to correlate changes with " |
| 56 | + "an incident — the source-agnostic 'what changed and when' marker." |
| 57 | + ), |
| 58 | + use_cases=[ |
| 59 | + "Checking whether a deploy or config change preceded an alert", |
| 60 | + "Correlating incidents with ArgoCD/Flux/Helm/Terraform/manual changes emitted as annotations", |
| 61 | + "Building a source-agnostic change timeline alongside the GitHub deploy timeline", |
| 62 | + ], |
| 63 | + requires=[], |
| 64 | + input_schema={ |
| 65 | + "type": "object", |
| 66 | + "properties": { |
| 67 | + "from": { |
| 68 | + "type": "string", |
| 69 | + "description": "ISO 8601 window start (overrides time_range_minutes)", |
| 70 | + }, |
| 71 | + "to": { |
| 72 | + "type": "string", |
| 73 | + "description": "ISO 8601 window end (overrides time_range_minutes)", |
| 74 | + }, |
| 75 | + "tags": {"type": "array", "items": {"type": "string"}}, |
| 76 | + "time_range_minutes": {"type": "integer", "default": 60}, |
| 77 | + "limit": {"type": "integer", "default": 100}, |
| 78 | + "grafana_endpoint": {"type": "string"}, |
| 79 | + "grafana_api_key": {"type": "string"}, |
| 80 | + }, |
| 81 | + "required": [], |
| 82 | + }, |
| 83 | + is_available=_query_grafana_annotations_available, |
| 84 | + extract_params=_query_grafana_annotations_extract_params, |
| 85 | +) |
| 86 | +def query_grafana_annotations( |
| 87 | + tags: list[str] | None = None, |
| 88 | + time_range_minutes: int = 60, |
| 89 | + limit: int = 100, |
| 90 | + grafana_endpoint: str | None = None, |
| 91 | + grafana_api_key: str | None = None, |
| 92 | + grafana_username: str = "", |
| 93 | + grafana_password: str = "", |
| 94 | + grafana_backend: Any = None, |
| 95 | + **_kwargs: Any, |
| 96 | +) -> dict: |
| 97 | + """Query Grafana annotations to correlate deploys/config changes with an incident. |
| 98 | +
|
| 99 | + ``from``/``to`` are accepted via the schema (ISO 8601); they are read from |
| 100 | + ``_kwargs`` because ``from`` is a Python keyword and cannot be a parameter name. |
| 101 | + When absent, the window defaults to the last ``time_range_minutes``. |
| 102 | + """ |
| 103 | + if grafana_backend is not None: |
| 104 | + raw = grafana_backend.query_annotations(tags=tags, limit=limit) |
| 105 | + annotations = _normalize_backend_annotations(raw) |
| 106 | + return { |
| 107 | + "source": "grafana_annotations", |
| 108 | + "available": True, |
| 109 | + "annotations": annotations, |
| 110 | + "total": len(annotations), |
| 111 | + "raw": raw, |
| 112 | + } |
| 113 | + |
| 114 | + client = _resolve_grafana_client( |
| 115 | + grafana_endpoint, grafana_api_key, grafana_username, grafana_password |
| 116 | + ) |
| 117 | + if not client or not client.is_configured: |
| 118 | + return { |
| 119 | + "source": "grafana_annotations", |
| 120 | + "available": False, |
| 121 | + "error": "Grafana integration not configured", |
| 122 | + "annotations": [], |
| 123 | + } |
| 124 | + |
| 125 | + now_ms = int(time.time() * 1000) |
| 126 | + try: |
| 127 | + from_iso, to_iso = _kwargs.get("from"), _kwargs.get("to") |
| 128 | + to_ts = _iso_to_epoch_ms(to_iso) if to_iso else now_ms |
| 129 | + # Default the window to end at `to` (now if unset), so a `to`-only call still |
| 130 | + # yields a valid [to - window, to] range rather than from_ts > to_ts. |
| 131 | + from_ts = _iso_to_epoch_ms(from_iso) if from_iso else to_ts - time_range_minutes * 60 * 1000 |
| 132 | + except (ValueError, TypeError, AttributeError) as e: |
| 133 | + return { |
| 134 | + "source": "grafana_annotations", |
| 135 | + "available": False, |
| 136 | + "error": f"Invalid timestamp: {e}", |
| 137 | + "annotations": [], |
| 138 | + } |
| 139 | + |
| 140 | + annotations = client.query_annotations(from_ts=from_ts, to_ts=to_ts, tags=tags, limit=limit) |
| 141 | + return { |
| 142 | + "source": "grafana_annotations", |
| 143 | + "available": True, |
| 144 | + "annotations": annotations, |
| 145 | + "total": len(annotations), |
| 146 | + "tags_filter": tags, |
| 147 | + "from": _epoch_ms_to_iso(from_ts), |
| 148 | + "to": _epoch_ms_to_iso(to_ts), |
| 149 | + } |
0 commit comments