forked from mtusi2026/mtusi2026lab6
solution
This commit is contained in:
+11
-4
@@ -1,7 +1,14 @@
|
||||
# Инфраструктура студента
|
||||
# Инфраструктура
|
||||
|
||||
Здесь разместите конфигурации выбранных сервисов; основную топологию — в корневом compose.yaml/stack.yaml. `compose.example.yaml` — только worksheet ролей и намеренно не запускается. `contracts/infrastructure.json` задаёт минимальные роли, не готовые образы/пароли.
|
||||
Две реплики API работают за Nginx. PostgreSQL хранит сообщения и задания,
|
||||
Redis — сессии, RabbitMQ доставляет задания, приватный MinIO хранит вложения.
|
||||
Publisher подтверждает доставку через брокер, worker фиксирует результат
|
||||
до подтверждения обработки. Настройки берутся из `.env`, секреты передаются
|
||||
файлами из `secrets/`. Миграции и настройка MinIO выполняются автоматически.
|
||||
|
||||
В REPORT.md сопоставьте роль → service name → версия/digest → health/readiness → volume → сеть/порт → способ передачи credentials. Приведите bootstrap (schema, bucket, broker topology, а с lab6 provisioning) и безопасное повторение этих команд.
|
||||
Collector принимает телеметрию и отправляет её в Prometheus, Loki и Tempo.
|
||||
Дашборд и настройки источников Grafana лежат в [otel](otel/README.md).
|
||||
|
||||
Приложение строится из исходников. Не используйте заранее существующий образ преподавательского сервера вместо своей реализации. Restart hook перезапускает все соответствующие stores с volumes; failover hook останавливает только заданную API-реплику.
|
||||
Проверка через `py -3.12 -X utf8 scripts/test.py` использует отдельный
|
||||
временный Docker-стенд. PostgreSQL и Redis доступны тестам только внутри
|
||||
временной среды. Сводка и журналы сохраняются в `evidence/lab6/`.
|
||||
|
||||
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
export RABBITMQ_DEFAULT_PASS="$(cat "${BROKER_PASSWORD_FILE:?}")"
|
||||
export RABBITMQ_DEFAULT_USER="${BROKER_USER:?}"
|
||||
export RABBITMQ_DEFAULT_VHOST="${BROKER_VHOST:?}"
|
||||
export RABBITMQ_NODE_PORT="${BROKER_PORT:?}"
|
||||
exec /usr/local/bin/docker-entrypoint.sh rabbitmq-server
|
||||
@@ -0,0 +1,22 @@
|
||||
FROM golang:1.24.8-bookworm AS compiler
|
||||
ENV CGO_ENABLED=0 GOTOOLCHAIN=local GOBIN=/out GOMAXPROCS=4
|
||||
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \
|
||||
go install -p 4 -ldflags='-s -w -X github.com/minio/minio/cmd.Version=RELEASE.2025-10-15T17-29-55Z -X github.com/minio/minio/cmd.ReleaseTag=RELEASE.2025-10-15T17-29-55Z' github.com/minio/minio@RELEASE.2025-10-15T17-29-55Z
|
||||
RUN --mount=type=cache,target=/go/pkg/mod --mount=type=cache,target=/root/.cache/go-build \
|
||||
go install -p 4 -ldflags='-s -w' github.com/minio/mc@RELEASE.2025-08-13T08-35-41Z
|
||||
|
||||
FROM python:3.12.15-slim-bookworm AS runtime
|
||||
RUN useradd --system --uid 10001 --no-create-home minio && mkdir /data && chown minio /data
|
||||
USER minio
|
||||
|
||||
FROM runtime AS server
|
||||
COPY --from=compiler /out/minio /usr/local/bin/minio
|
||||
LABEL org.opencontainers.image.source="https://github.com/minio/minio" \
|
||||
org.opencontainers.image.version="RELEASE.2025-10-15T17-29-55Z"
|
||||
VOLUME ["/data"]
|
||||
ENTRYPOINT ["/usr/local/bin/minio"]
|
||||
|
||||
FROM runtime AS bootstrap
|
||||
COPY --from=compiler /out/mc /usr/local/bin/mc
|
||||
COPY infra/minio/bootstrap.py /bootstrap.py
|
||||
ENTRYPOINT ["python", "/bootstrap.py"]
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Идемпотентный private bucket и отдельная ограниченная учётная запись API."""
|
||||
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
from tempfile import TemporaryDirectory
|
||||
import time
|
||||
from urllib.request import urlopen
|
||||
|
||||
|
||||
def secret(name):
|
||||
value = Path(os.environ[name.upper() + "_FILE"]).read_text().strip()
|
||||
if not value:
|
||||
raise ValueError("Пустой файл секрета")
|
||||
return value
|
||||
|
||||
|
||||
def main():
|
||||
endpoint = os.environ["S3_ENDPOINT"]
|
||||
bucket = os.environ["S3_BUCKET"]
|
||||
root_user, root_password = secret("minio_root_user"), secret("minio_root_password")
|
||||
access, password = secret("s3_access_key_id"), secret("s3_secret_access_key")
|
||||
if access == root_user:
|
||||
raise ValueError("API не должен использовать root credentials")
|
||||
deadline = time.monotonic() + 60
|
||||
while True:
|
||||
try:
|
||||
with urlopen(endpoint + "/minio/health/ready", timeout=2) as response:
|
||||
if response.status == 200:
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError("MinIO не готов за 60 секунд")
|
||||
time.sleep(1)
|
||||
with TemporaryDirectory(prefix="minio-bootstrap-") as directory:
|
||||
config = Path(directory)
|
||||
|
||||
config_file = config / "config.json"
|
||||
config_file.write_text(
|
||||
json.dumps(
|
||||
{
|
||||
"version": "10",
|
||||
"aliases": {
|
||||
"storage": {
|
||||
"url": endpoint,
|
||||
"accessKey": root_user,
|
||||
"secretKey": root_password,
|
||||
"api": "S3v4",
|
||||
"path": "auto",
|
||||
}
|
||||
},
|
||||
}
|
||||
)
|
||||
)
|
||||
config_file.chmod(0o600)
|
||||
|
||||
def mc(*args):
|
||||
result = subprocess.run(
|
||||
["mc", "--config-dir", directory, *args],
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL,
|
||||
timeout=30,
|
||||
)
|
||||
if result.returncode:
|
||||
raise RuntimeError(
|
||||
"Ошибка bootstrap MinIO; значения credentials скрыты"
|
||||
)
|
||||
|
||||
mc("mb", "--ignore-existing", "storage/" + bucket)
|
||||
mc("anonymous", "set", "none", "storage/" + bucket)
|
||||
policy = {
|
||||
"Version": "2012-10-17",
|
||||
"Statement": [
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetBucketLocation", "s3:ListBucket"],
|
||||
"Resource": [f"arn:aws:s3:::{bucket}"],
|
||||
},
|
||||
{
|
||||
"Effect": "Allow",
|
||||
"Action": ["s3:GetObject", "s3:PutObject", "s3:DeleteObject"],
|
||||
"Resource": [
|
||||
f"arn:aws:s3:::{bucket}/{prefix}/*"
|
||||
for prefix in ("originals", "staging", "variants")
|
||||
],
|
||||
},
|
||||
],
|
||||
}
|
||||
policy_file = config / "policy.json"
|
||||
policy_file.write_text(json.dumps(policy))
|
||||
mc(
|
||||
"admin",
|
||||
"policy",
|
||||
"create",
|
||||
"storage",
|
||||
"messenger-attachments",
|
||||
str(policy_file),
|
||||
)
|
||||
|
||||
mc("admin", "user", "add", "storage", access, password)
|
||||
mc(
|
||||
"admin",
|
||||
"policy",
|
||||
"attach",
|
||||
"storage",
|
||||
"messenger-attachments",
|
||||
"--user",
|
||||
access,
|
||||
)
|
||||
print("MinIO private bucket and API policy configured", flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Exception as error:
|
||||
print("MinIO bootstrap failed: " + type(error).__name__, flush=True)
|
||||
raise SystemExit(1) from None
|
||||
@@ -0,0 +1,124 @@
|
||||
|
||||
worker_processes 2;
|
||||
|
||||
events {
|
||||
worker_connections 1024;
|
||||
}
|
||||
|
||||
http {
|
||||
map $upstream_http_x_request_id $response_request_id {
|
||||
"" $request_id;
|
||||
default $upstream_http_x_request_id;
|
||||
}
|
||||
|
||||
log_format requests escape=json
|
||||
'{"time":"$time_iso8601","request_id":"$response_request_id",'
|
||||
'"method":"$request_method","uri":"$uri","status":$status,'
|
||||
'"bytes":$body_bytes_sent,"request_time":$request_time,'
|
||||
'"upstream":"$upstream_addr","upstream_status":"$upstream_status",'
|
||||
'"upstream_time":"$upstream_response_time",'
|
||||
'"instance_id":"$upstream_http_x_instance_id",'
|
||||
'"limit_status":"$limit_req_status"}';
|
||||
|
||||
access_log /dev/stdout requests;
|
||||
error_log /dev/stderr warn;
|
||||
server_tokens off;
|
||||
|
||||
resolver 127.0.0.11 valid=5s ipv6=off;
|
||||
resolver_timeout 1s;
|
||||
|
||||
limit_req_zone $binary_remote_addr zone=per_client:10m rate=50r/s;
|
||||
|
||||
gzip on;
|
||||
gzip_vary on;
|
||||
gzip_min_length 1024;
|
||||
gzip_comp_level 3;
|
||||
gzip_types application/json;
|
||||
|
||||
upstream api_backend {
|
||||
zone api_backend 64k;
|
||||
server api:8080 resolve max_fails=1 fail_timeout=5s;
|
||||
|
||||
keepalive 16;
|
||||
keepalive_timeout 4s;
|
||||
}
|
||||
|
||||
server {
|
||||
listen 8080;
|
||||
|
||||
client_header_timeout 10s;
|
||||
client_body_timeout 10s;
|
||||
client_max_body_size 0;
|
||||
client_body_buffer_size 64k;
|
||||
send_timeout 10s;
|
||||
keepalive_timeout 30s;
|
||||
|
||||
proxy_http_version 1.1;
|
||||
proxy_set_header Connection "";
|
||||
proxy_set_header Host $host;
|
||||
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||
proxy_set_header X-Forwarded-Proto $scheme;
|
||||
|
||||
proxy_connect_timeout 500ms;
|
||||
proxy_send_timeout 10s;
|
||||
proxy_read_timeout 10s;
|
||||
|
||||
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||
proxy_next_upstream_tries 2;
|
||||
proxy_next_upstream_timeout 2s;
|
||||
|
||||
proxy_intercept_errors off;
|
||||
error_page 429 = @rate_limited;
|
||||
error_page 502 503 504 = @unavailable;
|
||||
|
||||
location = /lb-health {
|
||||
access_log off;
|
||||
default_type text/plain;
|
||||
return 200 "ok\n";
|
||||
}
|
||||
|
||||
location /health/ {
|
||||
proxy_pass http://api_backend;
|
||||
}
|
||||
|
||||
location / {
|
||||
limit_req zone=per_client burst=100 nodelay;
|
||||
limit_req_status 429;
|
||||
limit_req_log_level warn;
|
||||
proxy_pass http://api_backend;
|
||||
}
|
||||
|
||||
location ~ ^/api/v1/chats/[^/]+/attachments$ {
|
||||
limit_req zone=per_client burst=100 nodelay;
|
||||
limit_req_status 429;
|
||||
proxy_request_buffering off;
|
||||
proxy_buffering off;
|
||||
proxy_read_timeout 65s;
|
||||
proxy_send_timeout 15s;
|
||||
proxy_next_upstream off;
|
||||
proxy_pass http://api_backend;
|
||||
}
|
||||
|
||||
location ~ ^/api/v1/attachments/[^/]+/content$ {
|
||||
limit_req zone=per_client burst=100 nodelay;
|
||||
limit_req_status 429;
|
||||
proxy_buffering off;
|
||||
proxy_read_timeout 65s;
|
||||
proxy_pass http://api_backend;
|
||||
}
|
||||
|
||||
location @rate_limited {
|
||||
default_type application/json;
|
||||
add_header X-Request-Id $request_id always;
|
||||
add_header Retry-After 1 always;
|
||||
return 429 '{"error":{"code":"rate_limited","message":"Request rate exceeded","request_id":"$request_id"}}';
|
||||
}
|
||||
|
||||
location @unavailable {
|
||||
default_type application/json;
|
||||
add_header X-Request-Id $request_id always;
|
||||
add_header Retry-After 1 always;
|
||||
return 503 '{"error":{"code":"unavailable","message":"API temporarily unavailable","request_id":"$request_id"}}';
|
||||
}
|
||||
}
|
||||
}
|
||||
+17
-4
@@ -1,7 +1,20 @@
|
||||
# Конфигурация наблюдаемости — реализовать
|
||||
# Наблюдаемость Messenger
|
||||
|
||||
Добавьте `collector.yaml` с OTLP receivers, processors и exporters выбранной версии Collector. Укажите явные bind endpoints, внутренние сети, memory limits/batch и поведение при backpressure по уровню. Сопоставьте все три pipeline с реально развёрнутыми backend.
|
||||
API, publisher и worker экспортируют OTLP HTTP/protobuf в Collector (:4318).
|
||||
Метрики выдаются Prometheus на :8889, логи отправляются в native OTLP Loki,
|
||||
traces — в Tempo. Grafana читает три хранилища через provisioned datasources.
|
||||
|
||||
Добавьте конфигурации storage, Grafana provisioning/datasources, provisioning/dashboards и импортируемые dashboard JSON. На 4 — alert rules и runbooks. Пустой dashboard или debug exporter, который только печатает данные в stdout, не заменяют хранилища/доказательства из `contracts/observability.md`.
|
||||
Конфиги backend, Collector, dashboard и provisioning находятся в этом каталоге.
|
||||
Dashboard UID: `messenger-overview`. Метрики — в секундах и счётчиках попыток;
|
||||
точные запросы/единицы находятся в JSON. Resource environment берётся из APP_ENV.
|
||||
В Loki индексируются service.name и окружение; instance ID — structured metadata.
|
||||
Строка лога содержит trace/span ID, ссылка TraceID открывает Tempo.
|
||||
|
||||
Не публикуйте OTLP/metrics/административные ports в общую сеть без необходимости. В lab7 реализуйте TLS/mTLS по trust matrix; экспорт Authorization и message bodies запрещён.
|
||||
История хранится в prometheusdata/lokidata/tempodata, retention 3 дня;
|
||||
grafanadata содержит настройки Grafana. Внешний порт имеет только Grafana,
|
||||
по умолчанию 127.0.0.1:13000. Её healthcheck проверяет также Loki, Tempo и Collector.
|
||||
Бизнес-readiness API от этих сервисов не зависит.
|
||||
|
||||
Полный прогон со сценариями отказов запускается командой
|
||||
`py -3.12 -X utf8 scripts/test.py`. Правила оповещений, запросы и шаги
|
||||
диагностики приведены в [отчёте](../../REPORT.md).
|
||||
|
||||
@@ -0,0 +1,18 @@
|
||||
groups:
|
||||
- name: messenger
|
||||
interval: 5s
|
||||
rules:
|
||||
- alert: MessengerHighErrorRate
|
||||
expr: |
|
||||
sum(increase(messenger_http_requests_total{http_response_status_class="5xx",http_route!~"/health/.*"}[30s]))
|
||||
/ clamp_min(sum(increase(messenger_http_requests_total{http_route!~"/health/.*"}[30s])), 1) > 0.05
|
||||
for: 5s
|
||||
annotations:
|
||||
summary: "Более 5% бизнес-запросов завершились HTTP 5xx за 30 секунд"
|
||||
runbook: "REPORT.md#диагностика-инцидентов"
|
||||
- alert: MessengerQueueLag
|
||||
expr: max(messenger_queue_oldest_seconds) > 15 and max(messenger_queue_depth_ratio) > 0
|
||||
for: 5s
|
||||
annotations:
|
||||
summary: "Старейшее ожидающее задание находится в очереди более 15 секунд"
|
||||
runbook: "REPORT.md#диагностика-инцидентов"
|
||||
@@ -0,0 +1,61 @@
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
processors:
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 192
|
||||
spike_limit_mib: 32
|
||||
batch:
|
||||
timeout: 1s
|
||||
send_batch_size: 128
|
||||
send_batch_max_size: 256
|
||||
exporters:
|
||||
prometheus:
|
||||
endpoint: 0.0.0.0:8889
|
||||
resource_to_telemetry_conversion:
|
||||
enabled: true
|
||||
otlphttp/loki:
|
||||
endpoint: http://loki:3100/otlp
|
||||
timeout: 3s
|
||||
sending_queue:
|
||||
queue_size: 256
|
||||
num_consumers: 2
|
||||
retry_on_failure:
|
||||
max_elapsed_time: 30s
|
||||
otlphttp/tempo:
|
||||
endpoint: http://tempo:4318
|
||||
timeout: 3s
|
||||
sending_queue:
|
||||
queue_size: 256
|
||||
num_consumers: 2
|
||||
retry_on_failure:
|
||||
max_elapsed_time: 30s
|
||||
extensions:
|
||||
health_check:
|
||||
endpoint: 0.0.0.0:13133
|
||||
service:
|
||||
telemetry:
|
||||
metrics:
|
||||
readers:
|
||||
- pull:
|
||||
exporter:
|
||||
prometheus:
|
||||
host: 0.0.0.0
|
||||
port: 8888
|
||||
extensions: [health_check]
|
||||
pipelines:
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlphttp/loki]
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlphttp/tempo]
|
||||
@@ -0,0 +1,617 @@
|
||||
{
|
||||
"uid": "messenger-overview",
|
||||
"title": "Messenger — наблюдаемость",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"tags": [
|
||||
"messenger",
|
||||
"observability"
|
||||
],
|
||||
"timezone": "browser",
|
||||
"refresh": "5s",
|
||||
"time": {
|
||||
"from": "now-15m",
|
||||
"to": "now"
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "API: запросы в секунду",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 9
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (http_request_method, http_route) (rate(messenger_http_requests_total{http_route!~\"/health/.*\"}[1m]))",
|
||||
"legendFormat": "{{http_request_method}} {{http_route}}"
|
||||
}
|
||||
],
|
||||
"description": "",
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "reqps"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "API: доля 5xx",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 9
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "(sum(rate(messenger_http_requests_total{http_response_status_class=\"5xx\",http_route!~\"/health/.*\"}[1m])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total{http_route!~\"/health/.*\"}[1m])), 0.000001)",
|
||||
"legendFormat": "5xx / все бизнес-запросы"
|
||||
}
|
||||
],
|
||||
"description": "Ошибки сервера: 5xx / все запросы, кроме health. 4xx не считаются отказом сервера.",
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "API: время ответа p50/p95/p99",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 9,
|
||||
"w": 12,
|
||||
"h": 9
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.5, sum by (le) (rate(messenger_http_duration_seconds_bucket{http_route!~\"/health/.*\"}[1m])))",
|
||||
"legendFormat": "p50"
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_http_duration_seconds_bucket{http_route!~\"/health/.*\"}[1m])))",
|
||||
"legendFormat": "p95"
|
||||
},
|
||||
{
|
||||
"refId": "C",
|
||||
"expr": "histogram_quantile(0.99, sum by (le) (rate(messenger_http_duration_seconds_bucket{http_route!~\"/health/.*\"}[1m])))",
|
||||
"legendFormat": "p99"
|
||||
}
|
||||
],
|
||||
"description": "Histogram в секундах, buckets суммируются по репликам.",
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"title": "Worker: попытки в секунду по исходу",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 9,
|
||||
"w": 12,
|
||||
"h": 9
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (outcome) (rate(messenger_job_attempts_total[1m]))",
|
||||
"legendFormat": "{{outcome}}"
|
||||
}
|
||||
],
|
||||
"description": "success — результат записан; error — попытка не удалась; deferred — истёк lease. Дубли без обработки не считаются.",
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "ops"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"title": "Worker: время обработки p95",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 18,
|
||||
"w": 12,
|
||||
"h": 9
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.95, sum by (le, outcome) (rate(messenger_job_duration_seconds_bucket[1m])))",
|
||||
"legendFormat": "{{outcome}}"
|
||||
}
|
||||
],
|
||||
"description": "Одна фактическая попытка, включая S3, преобразования и фиксацию metadata.",
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"title": "Worker: обработанные попытки",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 18,
|
||||
"w": 12,
|
||||
"h": 9
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (outcome) (messenger_job_attempts_total)",
|
||||
"legendFormat": "{{outcome}}"
|
||||
}
|
||||
],
|
||||
"description": "",
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"title": "API: структурные логи",
|
||||
"type": "logs",
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "loki"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 27,
|
||||
"w": 12,
|
||||
"h": 9
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "{service_name=\"messenger-api\"} | json",
|
||||
"queryType": "range"
|
||||
}
|
||||
],
|
||||
"description": "",
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"title": "Worker: структурные логи",
|
||||
"type": "logs",
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "loki"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 27,
|
||||
"w": 12,
|
||||
"h": 9
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "{service_name=\"messenger-worker\"} | json",
|
||||
"queryType": "range"
|
||||
}
|
||||
],
|
||||
"description": "",
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"id": 9,
|
||||
"title": "Реальные server/consumer traces",
|
||||
"type": "table",
|
||||
"datasource": {
|
||||
"type": "tempo",
|
||||
"uid": "tempo"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 36,
|
||||
"w": 12,
|
||||
"h": 9
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"queryType": "traceqlSearch",
|
||||
"query": "{ resource.service.name =~ \"messenger-api|messenger-worker\" }",
|
||||
"limit": 20
|
||||
}
|
||||
],
|
||||
"description": "Открыть trace в Explore; ссылка TraceID из строки Loki ведёт к той же трассе.",
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {}
|
||||
},
|
||||
{
|
||||
"id": 10,
|
||||
"title": "API: число 5xx бизнес-запросов",
|
||||
"type": "stat",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 36,
|
||||
"w": 12,
|
||||
"h": 9
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum(messenger_http_requests_total{http_response_status_class=\"5xx\",http_route!~\"/health/.*\"}) or vector(0)",
|
||||
"instant": true
|
||||
}
|
||||
],
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"options": {
|
||||
"reduceOptions": {
|
||||
"calcs": [
|
||||
"lastNotNull"
|
||||
],
|
||||
"fields": "",
|
||||
"values": false
|
||||
}
|
||||
},
|
||||
"description": "Накопленное число 5xx: показывает и первую ошибку нового ряда, когда rate ещё не имеет двух разных точек."
|
||||
},
|
||||
{
|
||||
"id": 11,
|
||||
"title": "Очередь: ожидающие задания",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 45
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "max by (queue_name) (messenger_queue_depth_ratio)",
|
||||
"legendFormat": "Глубина {{service_name}}{{queue_name}}{{exporter}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 12,
|
||||
"title": "Очередь: возраст старейшей задачи",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 45
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "max by (queue_name) (messenger_queue_oldest_seconds)",
|
||||
"legendFormat": "Возраст {{service_name}}{{queue_name}}{{exporter}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 13,
|
||||
"title": "PostgreSQL: соединения и ожидающие",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 53
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (service_name) (messenger_db_pool_used_ratio)",
|
||||
"legendFormat": "Занято {{service_name}}{{queue_name}}{{exporter}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
}
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "sum by (service_name) (messenger_db_pool_waiting_ratio)",
|
||||
"legendFormat": "Ожидают {{service_name}}{{queue_name}}{{exporter}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 14,
|
||||
"title": "Worker: доля занятых слотов",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 53
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum(messenger_worker_busy_ratio) / sum(messenger_worker_capacity_ratio)",
|
||||
"legendFormat": "Загрузка {{service_name}}{{queue_name}}{{exporter}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 15,
|
||||
"title": "Процессы: CPU в ядрах",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 61
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (service_name) (rate(messenger_process_cpu_seconds_total[1m]))",
|
||||
"legendFormat": "CPU {{service_name}}{{queue_name}}{{exporter}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 16,
|
||||
"title": "Процессы: резидентная память",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 61
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "bytes"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (service_name) (messenger_process_rss_bytes)",
|
||||
"legendFormat": "RSS {{service_name}}{{queue_name}}{{exporter}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 17,
|
||||
"title": "Вложения: p95 времени до ready",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 0,
|
||||
"y": 69
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "histogram_quantile(0.95, sum by (le) (rate(messenger_job_time_to_ready_seconds_bucket[5m])))",
|
||||
"legendFormat": "p95 {{service_name}}{{queue_name}}{{exporter}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 18,
|
||||
"title": "Collector: очереди экспорта",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"h": 8,
|
||||
"w": 12,
|
||||
"x": 12,
|
||||
"y": 69
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "max by (exporter) (otelcol_exporter_queue_size)",
|
||||
"legendFormat": "Размер {{service_name}}{{queue_name}}{{exporter}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
}
|
||||
},
|
||||
{
|
||||
"refId": "B",
|
||||
"expr": "max by (exporter) (otelcol_exporter_queue_capacity)",
|
||||
"legendFormat": "Ёмкость {{service_name}}{{queue_name}}{{exporter}}",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
}
|
||||
}
|
||||
]
|
||||
}
|
||||
],
|
||||
"annotations": {
|
||||
"list": []
|
||||
},
|
||||
"templating": {
|
||||
"list": []
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
apiVersion: 1
|
||||
providers:
|
||||
- name: Messenger
|
||||
folder: Messenger
|
||||
type: file
|
||||
disableDeletion: true
|
||||
editable: false
|
||||
updateIntervalSeconds: 10
|
||||
options:
|
||||
path: /var/lib/grafana/dashboards
|
||||
@@ -0,0 +1,36 @@
|
||||
apiVersion: 1
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: http://loki:3100
|
||||
editable: false
|
||||
jsonData:
|
||||
derivedFields:
|
||||
- name: TraceID
|
||||
matcherRegex: '"trace_id":\s*"([0-9a-f]{32})"'
|
||||
datasourceUid: tempo
|
||||
url: '$${__value.raw}'
|
||||
urlDisplayLabel: Open trace
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: http://tempo:3200
|
||||
editable: false
|
||||
jsonData:
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
spanStartTimeShift: '-1m'
|
||||
spanEndTimeShift: '1m'
|
||||
tags: [{key: service.name, value: service_name}]
|
||||
filterByTraceID: true
|
||||
filterBySpanID: false
|
||||
@@ -0,0 +1,39 @@
|
||||
auth_enabled: false
|
||||
server:
|
||||
http_listen_port: 3100
|
||||
common:
|
||||
path_prefix: /loki
|
||||
replication_factor: 1
|
||||
ring:
|
||||
kvstore:
|
||||
store: inmemory
|
||||
storage:
|
||||
filesystem:
|
||||
chunks_directory: /loki/chunks
|
||||
rules_directory: /loki/rules
|
||||
schema_config:
|
||||
configs:
|
||||
- from: 2024-01-01
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index:
|
||||
prefix: index_
|
||||
period: 24h
|
||||
limits_config:
|
||||
allow_structured_metadata: true
|
||||
retention_period: 72h
|
||||
otlp_config:
|
||||
resource_attributes:
|
||||
ignore_defaults: true
|
||||
attributes_config:
|
||||
- action: index_label
|
||||
attributes: [service.name, deployment.environment.name]
|
||||
- action: structured_metadata
|
||||
attributes: [service.version, service.instance.id]
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
analytics:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,11 @@
|
||||
global:
|
||||
scrape_interval: 5s
|
||||
evaluation_interval: 5s
|
||||
scrape_configs:
|
||||
- job_name: messenger
|
||||
static_configs:
|
||||
- targets: [otel-collector:8889]
|
||||
- job_name: collector
|
||||
static_configs:
|
||||
- targets: [otel-collector:8888]
|
||||
rule_files: [/etc/prometheus/alerts.yaml]
|
||||
@@ -0,0 +1,22 @@
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
ingester:
|
||||
max_block_duration: 1m
|
||||
compactor:
|
||||
compaction:
|
||||
block_retention: 72h
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
local:
|
||||
path: /var/tempo/blocks
|
||||
usage_report:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,5 @@
|
||||
dir /data
|
||||
appendonly yes
|
||||
appendfsync always
|
||||
maxmemory 256mb
|
||||
maxmemory-policy noeviction
|
||||
@@ -0,0 +1,10 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
|
||||
password_hash=$(tr -d '\r\n' </run/secrets/redis_password | sha256sum | cut -d ' ' -f 1)
|
||||
mkdir -p /run/redis
|
||||
umask 077
|
||||
printf 'user default reset on #%s ~* &* +@all\n' "$password_hash" >/run/redis/users.acl
|
||||
chown redis:redis /run/redis/users.acl
|
||||
chmod 600 /run/redis/users.acl
|
||||
exec /usr/local/bin/docker-entrypoint.sh redis-server /usr/local/etc/redis/redis.conf --aclfile /run/redis/users.acl
|
||||
@@ -0,0 +1,10 @@
|
||||
FROM docker:29.1.3-cli AS dockercli
|
||||
FROM python:3.12.15-slim-bookworm
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PYTHONUTF8=1 PIP_NO_CACHE_DIR=1
|
||||
COPY --from=dockercli /usr/local/bin/docker /usr/local/bin/docker
|
||||
COPY --from=dockercli /usr/local/libexec/docker/cli-plugins /usr/local/libexec/docker/cli-plugins
|
||||
WORKDIR /workspace
|
||||
COPY requirements.txt requirements-dev.txt ./
|
||||
RUN pip install -r requirements.txt -r requirements-dev.txt
|
||||
COPY scripts/container_tests.py /usr/local/bin/container_tests.py
|
||||
CMD ["python3", "/usr/local/bin/container_tests.py"]
|
||||
Reference in New Issue
Block a user