From d8b193f62b85d38c6d8d901d64df192c866d5759 Mon Sep 17 00:00:00 2001 From: caramelteawithmint <146834163+caramelteawithmint@users.noreply.github.com> Date: Fri, 27 Nov 2026 07:52:15 +0300 Subject: [PATCH] 3_grade --- .env.example | 47 ++-- Dockerfile | 24 ++ Dockerfile.worker | 20 ++ compose.yaml | 222 ++++++++++++++++++ observability/grafana/dashboards/api.json | 87 +++++++ observability/grafana/dashboards/worker.json | 66 ++++++ .../provisioning/dashboards/dashboards.yaml | 13 + .../provisioning/datasources/datasources.yaml | 37 +++ observability/loki/loki-config.yaml | 37 +++ observability/otel-collector-config.yaml | 61 +++++ observability/prometheus/prometheus.yml | 17 ++ observability/tempo/tempo-config.yaml | 31 +++ requirements.txt | 23 ++ src/app/config.py | 17 +- src/app/logging_config.py | 60 +++++ src/app/main.py | 14 +- src/app/otel.py | 75 ++++++ src/app/s3.py | 12 + worker/main.py | 204 +++++++++------- worker/outbox_publisher.py | 49 ++-- 20 files changed, 966 insertions(+), 150 deletions(-) create mode 100644 Dockerfile create mode 100644 Dockerfile.worker create mode 100644 compose.yaml create mode 100644 observability/grafana/dashboards/api.json create mode 100644 observability/grafana/dashboards/worker.json create mode 100644 observability/grafana/provisioning/dashboards/dashboards.yaml create mode 100644 observability/grafana/provisioning/datasources/datasources.yaml create mode 100644 observability/loki/loki-config.yaml create mode 100644 observability/otel-collector-config.yaml create mode 100644 observability/prometheus/prometheus.yml create mode 100644 observability/tempo/tempo-config.yaml create mode 100644 requirements.txt create mode 100644 src/app/logging_config.py create mode 100644 src/app/otel.py diff --git a/.env.example b/.env.example index 2b326558..37e690a7 100644 --- a/.env.example +++ b/.env.example @@ -1,30 +1,21 @@ -# Copy to .env for your LOCAL synthetic test environment; never commit .env. -# These are logical interface suggestions; map actual framework names in REPORT.md. -APP_HOST=0.0.0.0 -APP_PORT=8080 -APP_ENV=lab -SESSION_TTL_SECONDS=3600 -# Choose credentials locally. File paths contain no secret values. -DATABASE_URL_FILE=/run/secrets/database_url -# Optional on 3, required use on 4 in lab2; Redis OR Valkey: -SESSION_STORE=postgres -CACHE_URL_FILE=/run/secrets/cache_url -API_REPLICAS=2 -IDEMPOTENCY_TTL_SECONDS=86400 -S3_ENDPOINT=http://s3:9000 -S3_REGION=us-east-1 +# --- App --- +APP_ENV=lab6 +LOG_LEVEL=info + +# --- Database --- +DATABASE_URL=postgresql://messenger:messenger_password@postgres:5432/messenger + +# --- S3 / MinIO --- +S3_ENDPOINT=http://minio:9000 +S3_ACCESS_KEY=minioadmin +S3_SECRET_KEY=minioadmin S3_BUCKET=messenger-attachments -S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id -S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key -MAX_UPLOAD_BYTES=10485760 -MAX_IMAGE_PIXELS=40000000 -BROKER_URL_FILE=/run/secrets/broker_url -WORKER_CONCURRENCY=2 -JOB_MAX_ATTEMPTS=5 -JOB_TIMEOUT_SECONDS=60 -STAGING_RETENTION_SECONDS=86400 + +# --- Broker / Redis --- +BROKER_URL=amqp://guest:guest@broker:5672/ +REDIS_URL=redis://redis:6379/0 + +# --- OTel (лаба 6) --- +OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317 OTEL_SERVICE_NAME=messenger-api -# Worker must set a distinct service.name. -OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4318 -OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf -OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab +OTEL_RESOURCE_ATTRIBUTES=deployment.environment=lab6 \ No newline at end of file diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..a425947d --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +# Фиксируем версию, как требует infrastructure.json +FROM python:3.11-slim-bookworm + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PYTHONPATH=/app + +WORKDIR /app + +# Системные зависимости (нужны для Pillow, psycopg и т.д.) +RUN apt-get update && apt-get install -y --no-install-recommends \ + curl \ + build-essential \ + libpq-dev \ + && rm -rf /var/lib/apt/lists/* + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . + +EXPOSE 8080 + +CMD ["uvicorn", "src.app.main:app", "--host", "0.0.0.0", "--port", "8080"] \ No newline at end of file diff --git a/Dockerfile.worker b/Dockerfile.worker new file mode 100644 index 00000000..2717c18b --- /dev/null +++ b/Dockerfile.worker @@ -0,0 +1,20 @@ +FROM python:3.11-slim-bookworm + +ENV PYTHONDONTWRITEBYTECODE=1 \ + PYTHONUNBUFFERED=1 \ + PYTHONPATH=/app + +WORKDIR /app + +RUN apt-get update && apt-get install -y --no-install-recommends \ + curl \ + build-essential \ + libpq-dev \ + && rm -rf /var/lib/apt/lists/* + +COPY requirements.txt . +RUN pip install --no-cache-dir -r requirements.txt + +COPY . . + +CMD ["python", "-m", "worker.main"] \ No newline at end of file diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..81fbc510 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,222 @@ +x-api-common: &api-common + build: + context: . + dockerfile: Dockerfile + environment: + - DATABASE_URL=postgresql://messenger:messenger_password@postgres:5432/messenger + - S3_ENDPOINT=http://minio:9000 + - S3_ACCESS_KEY=minioadmin + - S3_SECRET_KEY=minioadmin + - S3_BUCKET=messenger-attachments + - BROKER_URL=amqp://guest:guest@broker:5672/ + - REDIS_URL=redis://redis:6379/0 + - APP_ENV=lab6 + - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317 + - OTEL_SERVICE_NAME=messenger-api + - OTEL_RESOURCE_ATTRIBUTES=deployment.environment=lab6 + depends_on: + postgres: + condition: service_healthy + minio: + condition: service_healthy + broker: + condition: service_healthy + redis: + condition: service_healthy + migrate: + condition: service_completed_successfully + otel-collector: + condition: service_started + +services: + # --- Load Balancer --- + lb: + image: nginx:1.25-alpine + ports: + - "8080:8080" + volumes: + - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro + depends_on: + - api1 + - api2 + + # --- API Реплики --- + api1: + <<: *api-common + expose: + - "8080" + + api2: + <<: *api-common + expose: + - "8080" + + # --- Worker --- + worker: + build: + context: . + dockerfile: Dockerfile.worker + command: python -m worker.main + environment: + - DATABASE_URL=postgresql://messenger:messenger_password@postgres:5432/messenger + - S3_ENDPOINT=http://minio:9000 + - S3_ACCESS_KEY=minioadmin + - S3_SECRET_KEY=minioadmin + - S3_BUCKET=messenger-attachments + - BROKER_URL=amqp://guest:guest@broker:5672/ + - REDIS_URL=redis://redis:6379/0 + - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317 + - OTEL_SERVICE_NAME=messenger-worker + - OTEL_RESOURCE_ATTRIBUTES=deployment.environment=lab6 + depends_on: + postgres: + condition: service_healthy + minio: + condition: service_healthy + broker: + condition: service_healthy + redis: + condition: service_healthy + migrate: + condition: service_completed_successfully + otel-collector: + condition: service_started + + # --- Миграции --- + migrate: + build: + context: . + dockerfile: Dockerfile + command: python scripts/migrate.py + environment: + - DATABASE_URL=postgresql://messenger:messenger_password@postgres:5432/messenger + - REDIS_URL=redis://redis:6379/0 + depends_on: + postgres: + condition: service_healthy + redis: + condition: service_healthy + + # --- Инфраструктура --- + postgres: + image: postgres:16-alpine + environment: + - POSTGRES_USER=messenger + - POSTGRES_PASSWORD=messenger_password + - POSTGRES_DB=messenger + volumes: + - pgdata:/var/lib/postgresql/data + healthcheck: + test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"] + interval: 5s + timeout: 5s + retries: 5 + + minio: + image: pgsty/silo:latest + command: server /data --console-address ":9001" + environment: + - MINIO_ROOT_USER=minioadmin + - MINIO_ROOT_PASSWORD=minioadmin + volumes: + - s3data:/data + healthcheck: + test: ["CMD", "curl", "-f", "http://localhost:9000/minio/health/live"] + interval: 5s + timeout: 5s + retries: 5 + ports: + - "9000:9000" + - "9001:9001" + + broker: + image: rabbitmq:3.13-alpine + environment: + - RABBITMQ_DEFAULT_USER=guest + - RABBITMQ_DEFAULT_PASS=guest + volumes: + - brokerdata:/var/lib/rabbitmq + healthcheck: + test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"] + interval: 5s + timeout: 5s + retries: 5 + + redis: + image: redis:7-alpine + command: redis-server --appendonly yes + volumes: + - redisdata:/data + healthcheck: + test: ["CMD", "redis-cli", "ping"] + interval: 5s + timeout: 5s + retries: 5 + + # ========================================== + # НОВОЕ ДЛЯ ЛАБЫ 6 (Observability) + # ========================================== + + otel-collector: + image: otel/opentelemetry-collector-contrib:0.95.0 + command: ["--config=/etc/otelcol/config.yaml"] + volumes: + - ./observability/otel-collector-config.yaml:/etc/otelcol/config.yaml:ro + depends_on: + - tempo + - loki + + prometheus: + image: prom/prometheus:v2.51.0 + command: + - "--config.file=/etc/prometheus/prometheus.yml" + - "--storage.tsdb.path=/prometheus" + volumes: + - ./observability/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro + - promdata:/prometheus + ports: + - "9090:9090" + + loki: + image: grafana/loki:2.9.4 + command: -config.file=/etc/loki/local-config.yaml + volumes: + - ./observability/loki/loki-config.yaml:/etc/loki/local-config.yaml:ro + - lokidata:/loki + ports: + - "3100:3100" + + tempo: + image: grafana/tempo:2.4.0 + command: [ "-config.file=/etc/tempo.yaml" ] + volumes: + - ./observability/tempo/tempo-config.yaml:/etc/tempo.yaml:ro + - tempodata:/var/tempo + ports: + - "3200:3200" + + grafana: + image: grafana/grafana:10.4.1 + environment: + - GF_AUTH_ANONYMOUS_ENABLED=true + - GF_AUTH_ANONYMOUS_ORG_ROLE=Admin + - GF_AUTH_DISABLE_LOGIN_FORM=true + - GF_PATHS_DASHBOARDS=/var/lib/grafana/dashboards + volumes: + - grafanadata:/var/lib/grafana + ports: + - "3000:3000" + depends_on: + - prometheus + - loki + - tempo + +volumes: + pgdata: + s3data: + brokerdata: + redisdata: + promdata: + lokidata: + tempodata: + grafanadata: \ No newline at end of file diff --git a/observability/grafana/dashboards/api.json b/observability/grafana/dashboards/api.json new file mode 100644 index 00000000..abd7a828 --- /dev/null +++ b/observability/grafana/dashboards/api.json @@ -0,0 +1,87 @@ +{ + "annotations": {"list": []}, + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 0, + "id": null, + "links": [], + "panels": [ + { + "datasource": {"type": "prometheus", "uid": "${DS_PROMETHEUS}"}, + "fieldConfig": {"defaults": {"unit": "reqps"}, "overrides": []}, + "gridPos": {"h": 8, "w": 12, "x": 0, "y": 0}, + "id": 1, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + { + "expr": "sum(rate(http_requests_total[1m])) by (handler)", + "legendFormat": "{{handler}}", + "refId": "A" + } + ], + "title": "API RPS", + "type": "timeseries" + }, + { + "datasource": {"type": "prometheus", "uid": "${DS_PROMETHEUS}"}, + "fieldConfig": {"defaults": {"unit": "percentunit"}, "overrides": []}, + "gridPos": {"h": 8, "w": 12, "x": 12, "y": 0}, + "id": 2, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + { + "expr": "sum(rate(http_requests_total{status=~\"5..\"}[1m])) / sum(rate(http_requests_total[1m]))", + "legendFormat": "5xx ratio", + "refId": "A" + } + ], + "title": "API Error Rate (5xx)", + "type": "timeseries" + }, + { + "datasource": {"type": "prometheus", "uid": "${DS_PROMETHEUS}"}, + "fieldConfig": {"defaults": {"unit": "s"}, "overrides": []}, + "gridPos": {"h": 8, "w": 24, "x": 0, "y": 8}, + "id": 3, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + { + "expr": "histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le, handler))", + "legendFormat": "p95 {{handler}}", + "refId": "A" + }, + { + "expr": "histogram_quantile(0.50, sum(rate(http_request_duration_seconds_bucket[5m])) by (le, handler))", + "legendFormat": "p50 {{handler}}", + "refId": "B" + } + ], + "title": "API Duration p50/p95", + "type": "timeseries" + } + ], + "schemaVersion": 39, + "tags": ["lab6"], + "templating": { + "list": [ + { + "current": {}, + "hide": 0, + "includeAll": false, + "label": "Prometheus", + "multi": false, + "name": "DS_PROMETHEUS", + "options": [], + "query": "prometheus", + "refresh": 1, + "regex": "", + "skipUrlSync": false, + "type": "datasource" + } + ] + }, + "time": {"from": "now-15m", "to": "now"}, + "title": "Lab6 API", + "uid": "lab6-api", + "version": 1 +} \ No newline at end of file diff --git a/observability/grafana/dashboards/worker.json b/observability/grafana/dashboards/worker.json new file mode 100644 index 00000000..409385ac --- /dev/null +++ b/observability/grafana/dashboards/worker.json @@ -0,0 +1,66 @@ +{ + "annotations": {"list": []}, + "editable": true, + "fiscalYearStartMonth": 0, + "graphTooltip": 0, + "id": null, + "links": [], + "panels": [ + { + "datasource": {"type": "prometheus", "uid": "${DS_PROMETHEUS}"}, + "fieldConfig": {"defaults": {"unit": "short"}, "overrides": []}, + "gridPos": {"h": 8, "w": 12, "x": 0, "y": 0}, + "id": 1, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + { + "expr": "sum(rate(worker_processed_total[1m])) by (result)", + "legendFormat": "{{result}}", + "refId": "A" + } + ], + "title": "Worker Jobs (success/fail)", + "type": "timeseries" + }, + { + "datasource": {"type": "prometheus", "uid": "${DS_PROMETHEUS}"}, + "fieldConfig": {"defaults": {"unit": "s"}, "overrides": []}, + "gridPos": {"h": 8, "w": 12, "x": 12, "y": 0}, + "id": 2, + "options": {"legend": {"displayMode": "list", "placement": "bottom"}}, + "targets": [ + { + "expr": "histogram_quantile(0.95, sum(rate(worker_duration_seconds_bucket[5m])) by (le))", + "legendFormat": "p95 duration", + "refId": "A" + } + ], + "title": "Worker Duration p95", + "type": "timeseries" + } + ], + "schemaVersion": 39, + "tags": ["lab6"], + "templating": { + "list": [ + { + "current": {}, + "hide": 0, + "includeAll": false, + "label": "Prometheus", + "multi": false, + "name": "DS_PROMETHEUS", + "options": [], + "query": "prometheus", + "refresh": 1, + "regex": "", + "skipUrlSync": false, + "type": "datasource" + } + ] + }, + "time": {"from": "now-15m", "to": "now"}, + "title": "Lab6 Worker", + "uid": "lab6-worker", + "version": 1 +} \ No newline at end of file diff --git a/observability/grafana/provisioning/dashboards/dashboards.yaml b/observability/grafana/provisioning/dashboards/dashboards.yaml new file mode 100644 index 00000000..e3d01ca2 --- /dev/null +++ b/observability/grafana/provisioning/dashboards/dashboards.yaml @@ -0,0 +1,13 @@ +apiVersion: 1 + +providers: + - name: "default" + orgId: 1 + folder: "MTUSI Lab6" + type: file + disableDeletion: false + updateIntervalSeconds: 10 + allowUiUpdates: true + options: + path: /var/lib/grafana/dashboards + foldersFromFilesStructure: false \ No newline at end of file diff --git a/observability/grafana/provisioning/datasources/datasources.yaml b/observability/grafana/provisioning/datasources/datasources.yaml new file mode 100644 index 00000000..8862598a --- /dev/null +++ b/observability/grafana/provisioning/datasources/datasources.yaml @@ -0,0 +1,37 @@ +apiVersion: 1 + +datasources: + - name: Prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + editable: false + + - name: Loki + type: loki + access: proxy + url: http://loki:3100 + editable: false + jsonData: + derivedFields: + - datasourceUid: tempo + matcherRegex: '"trace_id":"([a-f0-9]+)"' + name: TraceID + url: "$${__value.raw}" + + - name: Tempo + type: tempo + access: proxy + url: http://tempo:3200 + editable: false + jsonData: + tracesToLogs: + datasourceUid: loki + tags: ["service.name"] + mappedTags: [{ key: "service.name", value: "service_name" }] + mapTagNamesEnabled: true + spanStartTimeShift: "-5m" + spanEndTimeShift: "5m" + filterByTraceID: true + filterBySpanID: false \ No newline at end of file diff --git a/observability/loki/loki-config.yaml b/observability/loki/loki-config.yaml new file mode 100644 index 00000000..7973dccc --- /dev/null +++ b/observability/loki/loki-config.yaml @@ -0,0 +1,37 @@ +auth_enabled: false + +server: + http_listen_port: 3100 + grpc_listen_port: 9096 + +common: + instance_addr: 127.0.0.1 + path_prefix: /loki + storage: + filesystem: + chunks_directory: /loki/chunks + rules_directory: /loki/rules + replication_factor: 1 + ring: + kvstore: + store: inmemory + +schema_config: + configs: + - from: 2024-01-01 + store: tsdb + object_store: filesystem + schema: v13 + index: + prefix: index_ + period: 24h + +limits_config: + retention_period: 168h + reject_old_samples: true + reject_old_samples_max_age: 168h + +compactor: + working_directory: /loki/compactor + retention_enabled: true + delete_request_store: filesystem \ No newline at end of file diff --git a/observability/otel-collector-config.yaml b/observability/otel-collector-config.yaml new file mode 100644 index 00000000..ed381be0 --- /dev/null +++ b/observability/otel-collector-config.yaml @@ -0,0 +1,61 @@ +receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 + +processors: + memory_limiter: + check_interval: 1s + limit_mib: 256 + spike_limit_mib: 64 + batch: + timeout: 5s + send_batch_size: 1024 + resourcedetection: + detectors: [env, system] + timeout: 2s + # ГЛАВНОЕ: Добавляем хинт для Loki через атрибуты + attributes: + actions: + # Говорим Loki: "эй, возьми ресурсный атрибут service.name и сделай из него метку" + - key: loki.resource.labels + value: service.name + action: insert + +exporters: + prometheus: + endpoint: "0.0.0.0:8889" + resource_to_telemetry_conversion: + enabled: true + loki: + endpoint: http://loki:3100/loki/api/v1/push + tls: + insecure: true + # Убираем labels, так как их больше нет в 0.95.0 + otlp/tempo: + endpoint: tempo:4317 + tls: + insecure: true + +extensions: + health_check: + endpoint: 0.0.0.0:13133 + +service: + extensions: [health_check] + pipelines: + traces: + receivers: [otlp] + processors: [memory_limiter, batch, resourcedetection] + exporters: [otlp/tempo] + metrics: + receivers: [otlp] + processors: [memory_limiter, batch, resourcedetection] + exporters: [prometheus] + logs: + receivers: [otlp] + processors: [memory_limiter, batch, resourcedetection, attributes] + exporters: [loki] \ No newline at end of file diff --git a/observability/prometheus/prometheus.yml b/observability/prometheus/prometheus.yml new file mode 100644 index 00000000..dcecd4bb --- /dev/null +++ b/observability/prometheus/prometheus.yml @@ -0,0 +1,17 @@ +global: + scrape_interval: 15s + evaluation_interval: 15s + +scrape_configs: + - job_name: "otel-collector" + static_configs: + - targets: ["otel-collector:8889"] + + - job_name: "api" + metrics_path: /metrics + static_configs: + - targets: ["api1:8080", "api2:8080"] + + - job_name: "prometheus" + static_configs: + - targets: ["localhost:9090"] \ No newline at end of file diff --git a/observability/tempo/tempo-config.yaml b/observability/tempo/tempo-config.yaml new file mode 100644 index 00000000..7038efa4 --- /dev/null +++ b/observability/tempo/tempo-config.yaml @@ -0,0 +1,31 @@ +server: + http_listen_port: 3200 + grpc_listen_port: 9095 + +distributor: + receivers: + otlp: + protocols: + grpc: + endpoint: 0.0.0.0:4317 + http: + endpoint: 0.0.0.0:4318 + +storage: + trace: + backend: local + local: + path: /var/tempo/traces + wal: + path: /var/tempo/wal + +compactor: + compaction: + block_retention: 24h + +metrics_generator: + registry: + external_labels: + source: tempo + storage: + path: /var/tempo/generator/wal \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 00000000..4bc71071 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,23 @@ + +fastapi==0.111.0 +uvicorn[standard]==0.30.1 +psycopg[binary,pool]==3.2.1 +pydantic-settings==2.3.4 +boto3==1.34.144 +argon2-cffi==23.1.0 +aio-pika==9.4.3 +Pillow==10.4.0 +redis==5.0.7 +python-multipart==0.0.9 +python-logging-loki + + +opentelemetry-api==1.25.0 +opentelemetry-sdk==1.25.0 +opentelemetry-exporter-otlp==1.25.0 +opentelemetry-instrumentation-fastapi==0.46b0 +opentelemetry-instrumentation-psycopg==0.46b0 +opentelemetry-instrumentation-requests==0.46b0 +opentelemetry-instrumentation-aio-pika==0.46b0 +prometheus-fastapi-instrumentator==7.0.0 +python-json-logger==2.0.7 \ No newline at end of file diff --git a/src/app/config.py b/src/app/config.py index 6c93b09b..ed2aba9c 100644 --- a/src/app/config.py +++ b/src/app/config.py @@ -4,7 +4,6 @@ from pydantic_settings import BaseSettings, SettingsConfigDict def _read_secret(path: str | None) -> str | None: - """Прочитать секрет из файла, если задан путь. Иначе None.""" if not path: return None p = Path(path) @@ -16,34 +15,34 @@ def _read_secret(path: str | None) -> str | None: class Settings(BaseSettings): model_config = SettingsConfigDict(env_file=None, extra="ignore") - # Основные настройки приложения app_host: str = "0.0.0.0" app_port: int = 8080 - app_env: str = "lab" - instance_id: str = "" # пусто -> сгенерируется в instance.py + app_env: str = "lab6" + instance_id: str = "" log_level: str = "info" - # Сессии и идемпотентность session_ttl_seconds: int = 3600 idempotency_ttl_seconds: int = 86400 - # Postgres: либо прямая строка, либо файл-секрет (приоритет у файла). database_url: str = "" database_url_file: str = "/run/secrets/database_url" - # S3 / MinIO s3_endpoint: str = "http://minio:9000" s3_access_key: str = "minioadmin" s3_secret_key: str = "minioadmin" s3_bucket: str = "messenger-attachments" s3_region: str = "us-east-1" - # Брокер (RabbitMQ) broker_url: str = "amqp://guest:guest@broker:5672/" broker_queue: str = "attachment_processing" - + redis_url: str = "redis://redis:6379/0" + # --- OTel (лаба 6) --- + otel_exporter_otlp_endpoint: str = "http://otel-collector:4317" + otel_service_name: str = "messenger-api" + otel_environment: str = "lab6" + @property def db_dsn(self) -> str: from_file = _read_secret(self.database_url_file) diff --git a/src/app/logging_config.py b/src/app/logging_config.py new file mode 100644 index 00000000..8b874b03 --- /dev/null +++ b/src/app/logging_config.py @@ -0,0 +1,60 @@ +import logging +import sys +import os +from pythonjsonlogger import jsonlogger +from opentelemetry import trace + +try: + from logging_loki import LokiHandler + LOKI_AVAILABLE = True +except ImportError: + LOKI_AVAILABLE = False + + +class TraceIdFilter(logging.Filter): + def filter(self, record: logging.LogRecord) -> bool: + span = trace.get_current_span() + ctx = span.get_span_context() + if ctx and ctx.trace_id: + record.trace_id = format(ctx.trace_id, "032x") + record.span_id = format(ctx.span_id, "016x") + else: + record.trace_id = "" + record.span_id = "" + return True + + +def setup_logging(level: str = "INFO", service_name: str = "messenger-api"): + root = logging.getLogger() + root.handlers.clear() + root.setLevel(level.upper()) + + # 1. Консольный JSON-лог (в docker logs) + console_handler = logging.StreamHandler(sys.stdout) + formatter = jsonlogger.JsonFormatter( + "%(asctime)s %(levelname)s %(name)s %(message)s %(trace_id)s %(span_id)s", + rename_fields={"asctime": "timestamp", "levelname": "level"}, + ) + console_handler.setFormatter(formatter) + console_handler.addFilter(TraceIdFilter()) + root.addHandler(console_handler) + + # 2. Прямая отправка в Loki + if LOKI_AVAILABLE: + try: + loki_url = os.environ.get("LOKI_URL", "http://loki:3100/loki/api/v1/push") + handler = LokiHandler( + url=loki_url, + tags={"application": service_name}, + version="1", + ) + # Нам нужно, чтобы trace_id тоже уходил в метки (или хотя бы в лог) + handler.setFormatter(formatter) + handler.addFilter(TraceIdFilter()) + root.addHandler(handler) + logging.getLogger(__name__).info("LokiHandler подключен для %s", service_name) + except Exception as e: + logging.getLogger(__name__).warning("Не удалось подключить LokiHandler: %s", e) + + for noisy in ("uvicorn.access", "botocore", "boto3", "s3transfer", "urllib3"): + logging.getLogger(noisy).setLevel(logging.WARNING) \ No newline at end of file diff --git a/src/app/main.py b/src/app/main.py index d665be63..8d5539c3 100644 --- a/src/app/main.py +++ b/src/app/main.py @@ -3,13 +3,20 @@ from contextlib import asynccontextmanager from fastapi import FastAPI, Request from fastapi.exceptions import RequestValidationError -from fastapi.responses import JSONResponse +from prometheus_fastapi_instrumentator import Instrumentator from . import db +from .config import get_settings from .errors import ApiError, error_response from .instance import INSTANCE_ID +from .logging_config import setup_logging +from .otel import setup_otel from .routes import health, users, sessions, chats, messages, attachments +setup_logging(get_settings().log_level) +setup_otel("messenger-api") + + @asynccontextmanager async def lifespan(app: FastAPI): try: @@ -20,7 +27,10 @@ async def lifespan(app: FastAPI): db.close_pool() -app = FastAPI(title="MTUSI Messenger", version="1.4.0", lifespan=lifespan) +app = FastAPI(title="MTUSI Messenger", version="1.6.0", lifespan=lifespan) + +# Prometheus /metrics (в дополнение к OTLP) +Instrumentator().instrument(app).expose(app, endpoint="/metrics", include_in_schema=False) @app.middleware("http") diff --git a/src/app/otel.py b/src/app/otel.py new file mode 100644 index 00000000..bc11f821 --- /dev/null +++ b/src/app/otel.py @@ -0,0 +1,75 @@ +import logging +from opentelemetry import trace, metrics +from opentelemetry.sdk.resources import Resource +from opentelemetry.sdk.trace import TracerProvider +from opentelemetry.sdk.trace.export import BatchSpanProcessor +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader +from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler +from opentelemetry.sdk._logs.export import BatchLogRecordProcessor +from opentelemetry.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter +from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter +from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter + +from .config import get_settings + +logger = logging.getLogger(__name__) + +_initialized = False + + +def setup_otel(service_name: str | None = None) -> None: + global _initialized + if _initialized: + return + + s = get_settings() + svc = service_name or s.otel_service_name + endpoint = s.otel_exporter_otlp_endpoint + + resource = Resource.create( + { + "service.name": svc, + "deployment.environment": s.otel_environment, + } + ) + + # --- Traces --- + tracer_provider = TracerProvider(resource=resource) + tracer_provider.add_span_processor( + BatchSpanProcessor(OTLPSpanExporter(endpoint=endpoint, insecure=True)) + ) + trace.set_tracer_provider(tracer_provider) + + # --- Metrics --- + reader = PeriodicExportingMetricReader( + OTLPMetricExporter(endpoint=endpoint, insecure=True), + export_interval_millis=5000, + ) + meter_provider = MeterProvider(resource=resource, metric_readers=[reader]) + metrics.set_meter_provider(meter_provider) + + # --- Logs --- + logger_provider = LoggerProvider(resource=resource) + logger_provider.add_log_record_processor( + BatchLogRecordProcessor(OTLPLogExporter(endpoint=endpoint, insecure=True)) + ) + handler = LoggingHandler(level=logging.INFO, logger_provider=logger_provider) + logging.getLogger().addHandler(handler) + + # --- Автоинструментация --- + try: + from opentelemetry.instrumentation.fastapi import FastAPIInstrumentor + from opentelemetry.instrumentation.psycopg import PsycopgInstrumentor + from opentelemetry.instrumentation.requests import RequestsInstrumentor + from opentelemetry.instrumentation.aio_pika import AioPikaInstrumentor + + FastAPIInstrumentor().instrument() + PsycopgInstrumentor().instrument() + RequestsInstrumentor().instrument() + AioPikaInstrumentor().instrument() + except Exception as e: + logger.warning("OTel auto-instrumentation partial failure: %s", e) + + _initialized = True + logger.info("OTel initialized for service=%s endpoint=%s", svc, endpoint) \ No newline at end of file diff --git a/src/app/s3.py b/src/app/s3.py index f68327f8..79c65916 100644 --- a/src/app/s3.py +++ b/src/app/s3.py @@ -25,3 +25,15 @@ def upload_fileobj(fileobj, key: str, content_type: str): ExtraArgs={"ContentType": content_type}, ) + +def download_fileobj(key: str): + client = get_s3_client() + s = get_settings() + obj = client.get_object(Bucket=s.s3_bucket, Key=key) + return obj["Body"] + + +def delete_file(key: str): + client = get_s3_client() + s = get_settings() + client.delete_object(Bucket=s.s3_bucket, Key=key) \ No newline at end of file diff --git a/worker/main.py b/worker/main.py index d6d6a112..c6ea0861 100644 --- a/worker/main.py +++ b/worker/main.py @@ -8,34 +8,37 @@ import random import aio_pika from PIL import Image from psycopg.rows import dict_row +from opentelemetry import trace from src.app.config import get_settings from src.app.db import init_pool, transaction from src.app.s3 import download_fileobj, upload_fileobj +from src.app.otel import setup_otel +from src.app.logging_config import setup_logging -# ИМПОРТ ФОНОВОГО ПРОЦЕССА OUTBOX from worker.outbox_publisher import publish_loop logging.basicConfig(level=logging.INFO) logger = logging.getLogger("worker") +tracer = trace.get_tracer("messenger-worker") + MAX_PIXELS = 40_000_000 class PermanentError(Exception): - """Ошибка, которую нет смысла повторять (битый файл).""" pass def generate_variants(img: Image.Image): variants = {} - + thumb = img.copy() if thumb.mode in ("RGBA", "P"): thumb = thumb.convert("RGB") thumb.thumbnail((256, 256)) variants["thumbnail"] = (thumb, "image/jpeg", "JPEG", {"quality": 85}) - + crop = img.copy() if crop.mode in ("RGBA", "P"): crop = crop.convert("RGB") @@ -45,13 +48,13 @@ def generate_variants(img: Image.Image): crop = crop.crop((left, top, left + min_dim, top + min_dim)) crop = crop.resize((128, 128), Image.Resampling.LANCZOS) variants["crop"] = (crop, "image/jpeg", "JPEG", {"quality": 85}) - + opt = img.copy() if opt.mode in ("RGBA", "P", "L"): opt = opt.convert("RGB") opt.info.clear() variants["optimized"] = (opt, "image/webp", "WEBP", {"quality": 80, "method": 4}) - + return variants @@ -76,111 +79,130 @@ async def _send_to_dlq(body: bytes): async def process_message(message: aio_pika.IncomingMessage): - async with message.process(requeue=False, reject_on_redelivered=False): + async with message.process(requeue=False, reject_on_redelivered=False): data = json.loads(message.body) att_id = data["attachment_id"] obj_key = data["object_key"] - - logger.info(f"Processing attachment {att_id}") - - with transaction() as conn: - with conn.cursor(row_factory=dict_row) as cur: - cur.execute("SELECT attempts FROM attachment_retries WHERE attachment_id = %s", (att_id,)) - row = cur.fetchone() - attempts = row["attempts"] if row else 0 - - if attempts >= 5: - logger.error(f"Max retries (5) reached for {att_id}. Sending to DLQ.") - cur.execute("UPDATE attachments SET status='failed', error_code='max_retries_exceeded', updated_at=now() WHERE id=%s", (att_id,)) - await _send_to_dlq(message.body) - return - cur.execute( - """ - INSERT INTO attachment_retries (attachment_id, attempts) - VALUES (%s, 1) - ON CONFLICT (attachment_id) DO UPDATE SET attempts = attachment_retries.attempts + 1 - """, (att_id,) - ) - cur.execute("UPDATE attachments SET status='processing', updated_at=now() WHERE id=%s", (att_id,)) - - try: - body = download_fileobj(obj_key) - img = Image.open(body) - - width, height = img.size - if width * height > MAX_PIXELS: - raise PermanentError(f"Image too large: {width}x{height} pixels") - - img.load() - - variants = generate_variants(img) + with tracer.start_as_current_span("worker.process_attachment") as span: + span.set_attribute("attachment.id", att_id) + logger.info("Processing attachment %s", att_id) with transaction() as conn: - with conn.cursor() as cur: - for name, (var_img, ct, fmt, save_args) in variants.items(): - buf = io.BytesIO() - var_img.save(buf, format=fmt, **save_args) - - var_bytes = buf.getvalue() - sha256 = hashlib.sha256(var_bytes).hexdigest() - var_key = f"chats/{att_id}/variants/{name}" - - upload_fileobj(io.BytesIO(var_bytes), var_key, ct) - + with conn.cursor(row_factory=dict_row) as cur: + cur.execute( + "SELECT attempts FROM attachment_retries WHERE attachment_id = %s", + (att_id,), + ) + row = cur.fetchone() + attempts = row["attempts"] if row else 0 + + if attempts >= 5: + logger.error("Max retries (5) reached for %s. Sending to DLQ.", att_id) cur.execute( - """ - INSERT INTO attachment_variants (attachment_id, name, content_type, size_bytes, width, height, sha256, object_key) - VALUES (%s, %s, %s, %s, %s, %s, %s, %s) - ON CONFLICT (attachment_id, name) DO UPDATE SET - content_type = EXCLUDED.content_type, - size_bytes = EXCLUDED.size_bytes, - width = EXCLUDED.width, - height = EXCLUDED.height, - sha256 = EXCLUDED.sha256, - object_key = EXCLUDED.object_key - """, - (att_id, name, ct, len(var_bytes), var_img.width, var_img.height, sha256, var_key) + "UPDATE attachments SET status='failed', error_code='max_retries_exceeded', updated_at=now() WHERE id=%s", + (att_id,), ) - - cur.execute("UPDATE attachments SET status='ready', error_code=NULL, updated_at=now() WHERE id=%s", (att_id,)) - cur.execute("DELETE FROM attachment_retries WHERE attachment_id = %s", (att_id,)) + await _send_to_dlq(message.body) + span.set_attribute("worker.result", "max_retries") + return - logger.info(f"Successfully processed {att_id}") - - except PermanentError as e: - logger.error(f"Permanent error for {att_id}: {e}") - with transaction() as conn: - with conn.cursor() as cur: - cur.execute("UPDATE attachments SET status='failed', error_code=%s, updated_at=now() WHERE id=%s", ("invalid_image", att_id)) - - except Exception as e: - logger.error(f"Temporary error for {att_id}: {e}") - - delay = min(2 ** attempts, 60) - jitter = random.uniform(0, 3) - total_delay = delay + jitter - - logger.info(f"Retrying {att_id} in {total_delay:.2f} seconds (attempt {attempts+1}/5)") - await asyncio.sleep(total_delay) - await _re_publish(message.body) + cur.execute( + """ + INSERT INTO attachment_retries (attachment_id, attempts) + VALUES (%s, 1) + ON CONFLICT (attachment_id) DO UPDATE SET attempts = attachment_retries.attempts + 1 + """, + (att_id,), + ) + cur.execute( + "UPDATE attachments SET status='processing', updated_at=now() WHERE id=%s", + (att_id,), + ) + + try: + body = download_fileobj(obj_key) + img = Image.open(body) + + width, height = img.size + if width * height > MAX_PIXELS: + raise PermanentError(f"Image too large: {width}x{height} pixels") + + img.load() + variants = generate_variants(img) + + with transaction() as conn: + with conn.cursor() as cur: + for name, (var_img, ct, fmt, save_args) in variants.items(): + buf = io.BytesIO() + var_img.save(buf, format=fmt, **save_args) + var_bytes = buf.getvalue() + sha256 = hashlib.sha256(var_bytes).hexdigest() + var_key = f"chats/{att_id}/variants/{name}" + upload_fileobj(io.BytesIO(var_bytes), var_key, ct) + cur.execute( + """ + INSERT INTO attachment_variants (attachment_id, name, content_type, size_bytes, width, height, sha256, object_key) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s) + ON CONFLICT (attachment_id, name) DO UPDATE SET + content_type = EXCLUDED.content_type, + size_bytes = EXCLUDED.size_bytes, + width = EXCLUDED.width, + height = EXCLUDED.height, + sha256 = EXCLUDED.sha256, + object_key = EXCLUDED.object_key + """, + (att_id, name, ct, len(var_bytes), var_img.width, var_img.height, sha256, var_key), + ) + cur.execute( + "UPDATE attachments SET status='ready', error_code=NULL, updated_at=now() WHERE id=%s", + (att_id,), + ) + cur.execute("DELETE FROM attachment_retries WHERE attachment_id = %s", (att_id,)) + + span.set_attribute("worker.result", "ready") + logger.info("Successfully processed %s", att_id) + + except PermanentError as e: + logger.error("Permanent error for %s: %s", att_id, e) + with transaction() as conn: + with conn.cursor() as cur: + cur.execute( + "UPDATE attachments SET status='failed', error_code=%s, updated_at=now() WHERE id=%s", + ("invalid_image", att_id), + ) + span.set_attribute("worker.result", "permanent_error") + + except Exception as e: + logger.error("Temporary error for %s: %s", att_id, e) + span.set_attribute("worker.result", "retry") + delay = min(2 ** attempts, 60) + jitter = random.uniform(0, 3) + total_delay = delay + jitter + logger.info( + "Retrying %s in %.2f seconds (attempt %s/5)", att_id, total_delay, attempts + 1 + ) + await asyncio.sleep(total_delay) + await _re_publish(message.body) async def main(): + setup_logging(get_settings().log_level) + setup_otel("messenger-worker") + init_pool() settings = get_settings() - - # ЗАПУСК ФОНОВОГО ПРОЦЕССА OUTBOX + asyncio.create_task(publish_loop()) - + while True: try: connection = await aio_pika.connect_robust(settings.broker_url) break except Exception as e: - logger.warning(f"Broker not ready, waiting 5 seconds... ({e})") + logger.warning("Broker not ready, waiting 5 seconds... (%s)", e) await asyncio.sleep(5) - + async with connection: channel = await connection.channel() await channel.set_qos(prefetch_count=1) @@ -189,6 +211,6 @@ async def main(): await queue.consume(process_message) await asyncio.Future() - + if __name__ == "__main__": asyncio.run(main()) \ No newline at end of file diff --git a/worker/outbox_publisher.py b/worker/outbox_publisher.py index 14a7a8c1..2d6b8514 100644 --- a/worker/outbox_publisher.py +++ b/worker/outbox_publisher.py @@ -2,51 +2,60 @@ import asyncio import json import logging import aio_pika -from src.app.config import get_settings -from src.app.db import transaction +from opentelemetry import trace from psycopg.rows import dict_row +from src.app.config import get_settings +from src.app.db import transaction +from src.app.otel import setup_otel +from src.app.logging_config import setup_logging + logger = logging.getLogger("outbox") +tracer = trace.get_tracer("messenger-outbox") + async def publish_loop(): settings = get_settings() - - # Ждем брокер + while True: try: connection = await aio_pika.connect_robust(settings.broker_url) break except Exception: await asyncio.sleep(5) - + async with connection: channel = await connection.channel() await channel.declare_queue(settings.broker_queue, durable=True) while True: try: - # Забираем необработанные сообщения with transaction() as conn: with conn.cursor(row_factory=dict_row) as cur: cur.execute( - "SELECT id, payload FROM outbox_messages WHERE processed_at IS NULL ORDER BY created_at LIMIT 10 FOR UPDATE SKIP LOCKED" + "SELECT id, payload FROM outbox_messages " + "WHERE processed_at IS NULL ORDER BY created_at LIMIT 10 FOR UPDATE SKIP LOCKED" ) messages = cur.fetchall() - + for msg in messages: payload = msg["payload"] - # Отправляем в RabbitMQ - message = aio_pika.Message( - body=json.dumps(payload).encode(), - delivery_mode=aio_pika.DeliveryMode.PERSISTENT - ) - await channel.default_exchange.publish(message, routing_key=settings.broker_queue) - - # Помечаем как обработанное - cur.execute("UPDATE outbox_messages SET processed_at = now() WHERE id = %s", (msg["id"],)) - + with tracer.start_as_current_span("outbox.publish") as span: + span.set_attribute("outbox.message_id", str(msg["id"])) + message = aio_pika.Message( + body=json.dumps(payload).encode(), + delivery_mode=aio_pika.DeliveryMode.PERSISTENT, + ) + await channel.default_exchange.publish( + message, routing_key=settings.broker_queue + ) + cur.execute( + "UPDATE outbox_messages SET processed_at = now() WHERE id = %s", + (msg["id"],), + ) + if not messages: - await asyncio.sleep(1) # Если пусто, ждем секунду + await asyncio.sleep(1) except Exception as e: - logger.error(f"Outbox error: {e}") + logger.error("Outbox error: %s", e) await asyncio.sleep(2) \ No newline at end of file