From b6a7a85ed38319bc9d52b1b3483ccfd88a2d821b Mon Sep 17 00:00:00 2001 From: vasyukova Date: Fri, 30 Oct 2026 18:22:19 +0300 Subject: [PATCH] =?UTF-8?q?=D0=A1=D0=BE=D0=B7=D0=B4=D0=B0=D0=BB=D0=B0=20.y?= =?UTF-8?q?aml-=D1=84=D0=B0=D0=B9=D0=BB=D1=8B=20infra\grafana\provisioning?= =?UTF-8?q?\alerting?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- compose.yaml | 1 + .../provisioning/alerting/contactpoints.yaml | 13 +++ .../provisioning/alerting/policies.yaml | 9 ++ .../grafana/provisioning/alerting/rules.yaml | 109 ++++++++++++++++++ infra/prometheus/rules/alerts.yaml | 10 +- src/app/api/health.py | 12 +- src/app/main.py | 3 + 7 files changed, 149 insertions(+), 8 deletions(-) create mode 100644 infra/grafana/provisioning/alerting/contactpoints.yaml create mode 100644 infra/grafana/provisioning/alerting/policies.yaml create mode 100644 infra/grafana/provisioning/alerting/rules.yaml diff --git a/compose.yaml b/compose.yaml index 962f006..9f1b633 100644 --- a/compose.yaml +++ b/compose.yaml @@ -434,6 +434,7 @@ services: GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_ADMIN_PASSWORD:-admin} volumes: - ./infra/grafana/provisioning:/etc/grafana/provisioning:ro + - ./infra/grafana/provisioning/alerting:/etc/grafana/provisioning/alerting:ro - grafana-data:/var/lib/grafana ports: - "127.0.0.1:3000:3000" diff --git a/infra/grafana/provisioning/alerting/contactpoints.yaml b/infra/grafana/provisioning/alerting/contactpoints.yaml new file mode 100644 index 0000000..c781d18 --- /dev/null +++ b/infra/grafana/provisioning/alerting/contactpoints.yaml @@ -0,0 +1,13 @@ +apiVersion: 1 + +contactPoints: + - orgId: 1 + name: messenger-local + receivers: + - uid: messenger-local-webhook + type: webhook + disableResolveMessage: false + settings: + # Доставка наружу не требуется; локальный no-op endpoint. + url: http://127.0.0.1:9/messenger-alerts + httpMethod: POST \ No newline at end of file diff --git a/infra/grafana/provisioning/alerting/policies.yaml b/infra/grafana/provisioning/alerting/policies.yaml new file mode 100644 index 0000000..99f974f --- /dev/null +++ b/infra/grafana/provisioning/alerting/policies.yaml @@ -0,0 +1,9 @@ +apiVersion: 1 + +policies: + - orgId: 1 + receiver: messenger-local + group_by: ['alertname'] + group_wait: 10s + group_interval: 1m + repeat_interval: 4h \ No newline at end of file diff --git a/infra/grafana/provisioning/alerting/rules.yaml b/infra/grafana/provisioning/alerting/rules.yaml new file mode 100644 index 0000000..b509cc8 --- /dev/null +++ b/infra/grafana/provisioning/alerting/rules.yaml @@ -0,0 +1,109 @@ +apiVersion: 1 + +groups: + - orgId: 1 + name: messenger-alerts + folder: Messenger + interval: 1m + rules: + - uid: messenger-high-error-rate + title: MessengerHighErrorRate + condition: C + data: + - refId: A + relativeTimeRange: + from: 60 + to: 0 + datasourceUid: prometheus + model: + editorMode: code + expr: sum(rate(http_requests_total{http_status_class="5xx"}[1m])) / clamp_min(sum(rate(http_requests_total[1m])), 1e-9) + instant: true + intervalMs: 1000 + maxDataPoints: 43200 + range: false + refId: A + - refId: C + datasourceUid: __expr__ + model: + conditions: + - evaluator: + params: [0.05] + type: gt + operator: + type: and + query: + params: [C] + reducer: + params: [] + type: last + type: query + datasource: + type: __expr__ + uid: __expr__ + expression: A + intervalMs: 1000 + maxDataPoints: 43200 + refId: C + type: threshold + for: 30s + annotations: + summary: "API error rate > 5% over 1m" + description: "5xx ratio exceeds SLO 5% for 30 seconds." + runbook: "infra/runbooks/high-error-rate.md" + labels: + severity: warning + noDataState: NoData + execErrState: Error + isPaused: false + + - uid: messenger-jobs-backlog-growing + title: MessengerJobsBacklogGrowing + condition: C + data: + - refId: A + relativeTimeRange: + from: 600 + to: 0 + datasourceUid: prometheus + model: + editorMode: code + expr: sum(increase(jobs_processed_total{outcome="retry"}[10m])) - sum(increase(jobs_processed_total{outcome="success"}[10m])) + instant: true + intervalMs: 1000 + maxDataPoints: 43200 + range: false + refId: A + - refId: C + datasourceUid: __expr__ + model: + conditions: + - evaluator: + params: [5] + type: gt + operator: + type: and + query: + params: [C] + reducer: + params: [] + type: last + type: query + datasource: + type: __expr__ + uid: __expr__ + expression: A + intervalMs: 1000 + maxDataPoints: 43200 + refId: C + type: threshold + for: 5m + annotations: + summary: "Retries outpace successes" + description: "Worker retry count exceeds successes by >5 for 5m." + runbook: "infra/runbooks/queue-lag.md" + labels: + severity: warning + noDataState: NoData + execErrState: Error + isPaused: false \ No newline at end of file diff --git a/infra/prometheus/rules/alerts.yaml b/infra/prometheus/rules/alerts.yaml index 4c027c6..99e97de 100644 --- a/infra/prometheus/rules/alerts.yaml +++ b/infra/prometheus/rules/alerts.yaml @@ -4,16 +4,16 @@ groups: rules: - alert: MessengerHighErrorRate expr: | - sum(rate(http_requests_total{http_status_class="5xx"}[5m])) + sum(rate(http_requests_total{http_status_class="5xx"}[1m])) / - sum(rate(http_requests_total[5m])) + sum(rate(http_requests_total[1m])) > 0.05 - for: 2m + for: 30s labels: severity: warning annotations: - summary: "API error rate > 5% over 5m" - description: "5xx ratio exceeds SLO 5% for 2 minutes." + summary: "API error rate > 5% over 1m" + description: "5xx ratio exceeds SLO 5% for 30 seconds." runbook: "infra/runbooks/high-error-rate.md" - alert: MessengerJobsBacklogGrowing diff --git a/src/app/api/health.py b/src/app/api/health.py index 9676c2b..908b481 100644 --- a/src/app/api/health.py +++ b/src/app/api/health.py @@ -30,9 +30,15 @@ def readiness() -> Health: main.py конвертирует его в 503 с телом Error из contracts/openapi.json. Все проверки — с короткими таймаутами, чтобы не зависать надолго. """ - with _db.connection() as conn, conn.cursor() as cur: - cur.execute("SELECT 1") - cur.fetchone() + try: + with _db.connection() as conn, conn.cursor() as cur: + cur.execute("SELECT 1") + cur.fetchone() + except Exception as exc: # noqa: BLE001 + # Пул уже проверяет живость соединения (check_connection) и короткий + # timeout=3.0; здесь лишь превращаем любую ошибку БД в 503, чтобы + # после рестарта PostgreSQL readiness быстро возвращался в 200. + raise RuntimeError("db_unavailable: %s" % type(exc).__name__) from exc # Redis (в режиме redis) if _store() == "redis": _redis_client().ping() diff --git a/src/app/main.py b/src/app/main.py index b2258cf..8ff9209 100644 --- a/src/app/main.py +++ b/src/app/main.py @@ -200,6 +200,9 @@ async def db_unavailable_handler(request: Request, exc: psycopg.OperationalError async def runtime_error_handler(request: Request, exc: RuntimeError): request_id = getattr(request.state, "request_id", uuid.uuid4().hex) text = str(exc) + if "db_unavailable" in text: + logger.error("event=db_unavailable request_id=%s", request_id) + return _error_response(503, "Зависимость недоступна", request_id, request.url.path) if "redis_unavailable" in text: logger.error("event=redis_unavailable request_id=%s", request_id) return _error_response(503, "Зависимость недоступна", request_id, request.url.path)