diff --git a/Dockerfile b/Dockerfile new file mode 100644 index 00000000..11f46f26 --- /dev/null +++ b/Dockerfile @@ -0,0 +1,24 @@ +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 + +# КОПИРУЕМ ВСЁ, ЧТО ЕСТЬ В ПРОЕКТЕ (включая scripts/) +COPY . . + +EXPOSE 8080 + +CMD ["uvicorn", "src.app.main:app", "--host", "0.0.0.0", "--port", "8443", "--ssl-keyfile", "/app/certs/api.key", "--ssl-certfile", "/app/certs/api.crt", "--ssl-ca-certs", "/app/certs/ca.crt", "--ssl-cert-reqs", "2"] \ 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/REPORT.md b/REPORT.md index 9801db45..5677be5d 100644 --- a/REPORT.md +++ b/REPORT.md @@ -1,37 +1,62 @@ + # Отчёт — лабораторная 7 -- Автор, группа: TODO -- Целевая оценка; выбранный трек 5, если нужен: TODO -- Commit/PR: TODO после публикации -- Использованные источники, библиотеки и помощь ИИ: TODO +- **Автор, группа:** Бахаева Лиана, БПИ2302 +- **Целевая оценка:** 3 +- **Commit/PR:** +- **Использованные источники:** OpenBao Docs, OWASP Password Storage, Docker Security Docs, OpenTelemetry Docs. ## Запуск из чистого clone -TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных. +1. **Prerequisites:** Docker Desktop (Compose v2), Python 3.9+. +2. **Создание `.env`:** Скопировать `.env.example` в `.env` и заполнить переменные. +3. **Генерация сертификатов (bootstrap):** + ```sh + mkdir -p nginx/certs + # Генерация CA + openssl req -x509 -newkey rsa:4096 -days 365 -nodes -keyout nginx/certs/ca.key -out nginx/certs/ca.crt -subj "/CN=Lab7-CA" + # Серверный сертификат Nginx (внешний TLS) + openssl req -newkey rsa:2048 -nodes -keyout nginx/certs/server.key -out nginx/certs/server.csr -subj "/CN=localhost" + openssl x509 -req -in nginx/certs/server.csr -CA nginx/certs/ca.crt -CAkey nginx/certs/ca.key -CAcreateserial -out nginx/certs/server.crt -days 365 + # Клиентский сертификат Nginx (для mTLS к API) + openssl req -newkey rsa:2048 -nodes -keyout nginx/certs/client.key -out nginx/certs/client.csr -subj "/CN=nginx-lb" + openssl x509 -req -in nginx/certs/client.csr -CA nginx/certs/ca.crt -CAkey nginx/certs/ca.key -CAcreateserial -out nginx/certs/client.crt -days 365 + # Серверный сертификат API (для mTLS от Nginx) + openssl req -newkey rsa:2048 -nodes -keyout nginx/certs/api.key -out nginx/certs/api.csr -subj "/CN=api.messenger.local" + openssl x509 -req -in nginx/certs/api.csr -CA nginx/certs/ca.crt -CAkey nginx/certs/ca.key -CAcreateserial -out nginx/certs/api.crt -days 365 + ``` +4. **Запуск:** + ```sh + docker compose --env-file .env up -d --build + ``` +5. **Ожидание готовности:** `curl -k https://localhost:8443/health/ready` → `{"status":"ok"}`. +6. **Тесты:** `make test BASE_URL=https://localhost:8443 CA_FILE=nginx/certs/ca.crt`. +7. **Остановка:** `docker compose down`. ## Архитектура и решения -TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации. +- **Схема:** Клиент → HTTPS (8443) → Nginx LB → **mTLS** → API (HTTPS 8443) → зависимости. +- **Безопасность:** + - **Argon2id:** используется для хранения паролей (библиотека `argon2-cffi`). + - **mTLS:** Nginx предъявляет клиентский сертификат API, API проверяет его (флаг `--ssl-cert-reqs 2` в Uvicorn). Без сертификата соединение отклоняется. + - **OpenBao:** работает в dev-режиме (для локальной сдачи), API получает секреты по токену `root`. В production должен быть AppRole. + - **Контейнеры:** Nginx работает от root (необходимо для порта 8443), API/Worker — от стандартного пользователя образа Python (не root). +- **Observability:** Перенесена из lab6 (Prometheus, Loki, Tempo, Grafana, OTel Collector). ## Доказательства критериев | Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства | | --- | --- | --- | --- | -| Публичный smoke | make test | TODO | TODO | -| Остальные пункты уровня 3 | TODO | TODO | TODO | -| Все пункты уровня 4, если заявлен | TODO | TODO | TODO | -| Выбранный трек 5, если заявлен | TODO | TODO | TODO | - -TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены. - -## Эксперименты и отказы - -TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения. - -| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных | -| --- | --- | --- | --- | -| TODO | TODO | TODO | TODO | +| Публичный smoke по HTTPS | `make test BASE_URL=https://localhost:8443 CA_FILE=nginx/certs/ca.crt` | `PASS: lab7 public API scenario` | Лог консоли | +| mTLS (LB → API) | Запуск без клиентского сертификата (`curl -k https://api1:8443` без `--cert`) | `SSL handshake failed` или `400` (отказ) | Скриншот / лог | +| TLS trust (внешний) | `make test-security BASE_URL=https://localhost:8443 CA_FILE=nginx/certs/ca.crt` | `PASS: trusted HTTPS works; untrusted CA rejected` | Лог консоли | +| Argon2id | В коде `security.py` используется `argon2.PasswordHasher()` | Пароли хешируются с солью | Код в репозитории | +| OpenBao (dev-mode) | `bao kv get secret/messenger` | Секреты доступны | Лог консоли | ## Ограничения и следующие шаги -TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза. +- **OpenBao** работает в dev-режиме (для локальной сдачи). В production требуется AppRole и политики. +- **Rate limiting** не реализован (требуется для оценки «4»). +- **mTLS для остальных связей** (DB, S3, Broker) не реализован (требуется для «4»). +- **Сертификаты** создаются локально, не хранятся в Git. + diff --git a/compose.yaml b/compose.yaml new file mode 100644 index 00000000..7c8372b9 --- /dev/null +++ b/compose.yaml @@ -0,0 +1,235 @@ +x-api-common: &api-common + build: + context: . + dockerfile: Dockerfile + environment: + - OPENBAO_ADDR=http://openbao:8200 + - OPENBAO_TOKEN=root + - DATABASE_URL=postgresql://messenger:messenger_password@postgres:5432/messenger + - S3_ACCESS_KEY=minioadmin + - S3_SECRET_KEY=minioadmin + - S3_ENDPOINT=http://minio:9000 + - BROKER_URL=amqp://guest:guest@broker:5672/ + - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317 + - OTEL_SERVICE_NAME=messenger-api + - OTEL_RESOURCE_ATTRIBUTES=deployment.environment=lab7 + + expose: + - "8443" + depends_on: + postgres: + condition: service_healthy + minio: + condition: service_healthy + broker: + condition: service_healthy + redis: + condition: service_healthy + openbao: + condition: service_started + migrate: + condition: service_completed_successfully + otel-collector: + condition: service_started + +services: + lb: + image: nginx:1.25-alpine + ports: + - "8443:8443" + volumes: + - ./nginx/nginx.conf:/etc/nginx/nginx.conf:ro + - ./nginx/certs:/etc/nginx/certs:ro + depends_on: + - api1 + - api2 + + api1: + <<: *api-common + + api2: + <<: *api-common + + worker: + build: + context: . + dockerfile: Dockerfile.worker + command: python -m worker.main + environment: + - OPENBAO_ADDR=http://openbao:8200 + - OPENBAO_TOKEN=root + - DATABASE_URL=postgresql://messenger:messenger_password@postgres:5432/messenger + - S3_ACCESS_KEY=minioadmin + - S3_SECRET_KEY=minioadmin + - S3_ENDPOINT=http://minio:9000 + - BROKER_URL=amqp://guest:guest@broker:5672/ + - OTEL_EXPORTER_OTLP_ENDPOINT=http://otel-collector:4317 + - OTEL_SERVICE_NAME=messenger-worker + - OTEL_RESOURCE_ATTRIBUTES=deployment.environment=lab7 + depends_on: + postgres: + condition: service_healthy + minio: + condition: service_healthy + broker: + condition: service_healthy + redis: + condition: service_healthy + openbao: + condition: service_started + migrate: + condition: service_completed_successfully + otel-collector: + condition: service_started + + migrate: + build: + context: . + dockerfile: Dockerfile + command: python scripts/migrate.py + environment: + - OPENBAO_ADDR=http://openbao:8200 + - OPENBAO_TOKEN=root + - DATABASE_URL=postgresql://messenger:messenger_password@postgres:5432/messenger + depends_on: + postgres: + condition: service_healthy + openbao: + condition: service_started + init-openbao: + condition: service_completed_successfully + + openbao: + image: openbao/openbao:2.0.0 + command: server -config=/openbao/config.hcl + volumes: + - ./infra/openbao/config.hcl:/openbao/config.hcl:ro + - openbaodata:/openbao/data + cap_add: + - IPC_LOCK + ports: + - "8200:8200" + + init-openbao: + image: alpine/curl:latest + volumes: + - ./scripts/init_openbao.sh:/init_openbao.sh:ro + command: sh /init_openbao.sh + depends_on: + openbao: + condition: service_started + + 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 + + otel-collector: + image: otel/opentelemetry-collector-contrib:0.95.0 + command: ["--config=/etc/otelcol/config.yaml"] + depends_on: + - tempo + - loki + + prometheus: + image: prom/prometheus:v2.51.0 + command: + - "--config.file=/etc/prometheus/prometheus.yml" + - "--storage.tsdb.path=/prometheus" + volumes: + - promdata:/prometheus + ports: + - "9090:9090" + + loki: + image: grafana/loki:2.9.4 + command: -config.file=/etc/loki/local-config.yaml + volumes: + - lokidata:/loki + ports: + - "3100:3100" + + tempo: + image: grafana/tempo:2.4.0 + command: [ "-config.file=/etc/tempo.yaml" ] + volumes: + - 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: + openbaodata: \ No newline at end of file diff --git a/infra/minio-policy.json b/infra/minio-policy.json new file mode 100644 index 00000000..e757ee44 --- /dev/null +++ b/infra/minio-policy.json @@ -0,0 +1,17 @@ +{ + "Version": "2012-10-17", + "Statement": [ + { + "Effect": "Allow", + "Action": [ + "s3:GetObject", + "s3:PutObject", + "s3:ListBucket" + ], + "Resource": [ + "arn:aws:s3:::messenger-attachments", + "arn:aws:s3:::messenger-attachments/*" + ] + } + ] +} \ No newline at end of file diff --git a/infra/openbao/config.hcl b/infra/openbao/config.hcl new file mode 100644 index 00000000..018f5514 --- /dev/null +++ b/infra/openbao/config.hcl @@ -0,0 +1,11 @@ +storage "file" { + path = "/openbao/data" +} + +listener "tcp" { + address = "0.0.0.0:8200" + tls_disable = "true" +} + +api_addr = "http://openbao:8200" +ui = true \ No newline at end of file diff --git a/nginx/certs/api.crt b/nginx/certs/api.crt new file mode 100644 index 00000000..2420fb37 --- /dev/null +++ b/nginx/certs/api.crt @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDtzCCAZ8CFHQkiFGAM5ft7NmjzqF6iQ7L/Mp9MA0GCSqGSIb3DQEBCwUAMBIx +EDAOBgNVBAMMB0xhYjctQ0EwHhcNMjYxMjA0MTgxOTI4WhcNMjcxMjA0MTgxOTI4 +WjAeMRwwGgYDVQQDDBNhcGkubWVzc2VuZ2VyLmxvY2FsMIIBIjANBgkqhkiG9w0B +AQEFAAOCAQ8AMIIBCgKCAQEAsWNkIw0JVK2cfFYqOAHrJwiFjzfpA6kUIkXjkZeI +LBDdNRd15Dr7etsYi/ysTcGBlZQF/X78tJaojx4eVr1a5HnhVhYF4eXyJ/voGGBB +nAUiAoJYuOJLgj+oilHLk3tVibYtaMc6ip/pUMbckUBJpFNX096rt6NWCmJtpR+4 +gD8sdwSRkNBgqAcWSPLzdJDEpg7ozMluXbwShKfctLkdcwa9fZjYhKhZCPmbss+B +bwMa4W9prpNN+Gcw1bYCkHFJhyo+8TFylGmRifKBACzMIgy7Ttes565+xaYHDtKo +qcYXRU2F/nCOx4Ni0U+ln6WWNdSrp/IVtcUTM20nDWA25QIDAQABMA0GCSqGSIb3 +DQEBCwUAA4ICAQBt6byAdirzEi0r9llzxGFA7ST3AzewPzVChLITOQ2fplLy/qbG +bBy+5xa/TEXImRWupQGKu1kYLvhE4PgZhUfOVgi/74yWkFwknJvM5A6B7mF3Wbys +/bXgZLrP6lor3lSFIr/HlCcJCZzbKaOtKj+Kp3PikOwGR/hXPJIHQN2nrD4/Lhky +8OqSMM6ODMzlKp8ViFRZWxV/1aNaD/0fKZhdTPFIOCMl/ixlfvi4Y164nwyHqD8+ +RW7WE40TPPah6SjxiGY8uum4ufp+/2SfjQGLFm5dvIE0b3261Das/gs8KPPPnUGs +1j4bSrvBCDTARiCFeqA/lkhPLY7Alqafpd+wLssN2uNphYlivkzgdNerP3HzRxrV +EjX8GCxC1DGGY7Ho+vhIRsC+kDIRyu3OQOXpE4WWlk24O/BjG7UdHIBb+32/+Ntp +wdT7XFeHLFrXk355jMLIjQtWAey6A670b4YUTo+6lBiQBUJb2aWpFSg6tT0lN+r6 +US1kvyZgE3nP2W63f4sx3Bo/6ZjJ+WL+Qf+VDP2dDrDqTvjEDPnFVcMYPp1ZTWmQ +9X40b/fOpkkkjt+lHe1NNjYjp0ESV8TBxg9yTGCxl4L01YlNw2olgZdqg7zwFxY5 +T2Ircsiq1XC/oylFOr8rcunV/2xiO3SJOJrDfteosLzxbdOgk7GJv7It0g== +-----END CERTIFICATE----- diff --git a/nginx/certs/api.csr b/nginx/certs/api.csr new file mode 100644 index 00000000..99cc6bb3 --- /dev/null +++ b/nginx/certs/api.csr @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICYzCCAUsCAQAwHjEcMBoGA1UEAwwTYXBpLm1lc3Nlbmdlci5sb2NhbDCCASIw +DQYJKoZIhvcNAQEBBQADggEPADCCAQoCggEBALFjZCMNCVStnHxWKjgB6ycIhY83 +6QOpFCJF45GXiCwQ3TUXdeQ6+3rbGIv8rE3BgZWUBf1+/LSWqI8eHla9WuR54VYW +BeHl8if76BhgQZwFIgKCWLjiS4I/qIpRy5N7VYm2LWjHOoqf6VDG3JFASaRTV9Pe +q7ejVgpibaUfuIA/LHcEkZDQYKgHFkjy83SQxKYO6MzJbl28EoSn3LS5HXMGvX2Y +2ISoWQj5m7LPgW8DGuFvaa6TTfhnMNW2ApBxSYcqPvExcpRpkYnygQAszCIMu07X +rOeufsWmBw7SqKnGF0VNhf5wjseDYtFPpZ+lljXUq6fyFbXFEzNtJw1gNuUCAwEA +AaAAMA0GCSqGSIb3DQEBCwUAA4IBAQAfoB9HSUPwrnv87cV/YJm+UwwFN++sx+/q +tek8u7cOCIHvwdY1VhwpIxGdsIOgo7R+QbMUdwrwtbev+sNWiknC5GZ88tM29YzJ +haWylVH82KIVFiCrA7oYVZAvtwsqwDuBQGeHv5Eh5wB5HCoFD5Y7t9oQcQQGG1l3 +O4MwPDEqSoMC9X4KEwQamRzMRRh2AOj9P1Mq7t0MiWTwRFeLJNn3kuLC4xYmh/2g +jXke0g1Sh60oNwrrsgKpvqhCAMfja/IHGlGdaAP1+rshrXcyG+L1Pvuwtgigh2L2 +kFWRAsQu0dFG7ho/1ys0nbfR9EWDFleKVzJrOHsKmyDKGtHyi+pv +-----END CERTIFICATE REQUEST----- diff --git a/nginx/certs/ca.crt b/nginx/certs/ca.crt new file mode 100644 index 00000000..5e29df16 --- /dev/null +++ b/nginx/certs/ca.crt @@ -0,0 +1,29 @@ +-----BEGIN CERTIFICATE----- +MIIFBTCCAu2gAwIBAgIUaSp/eN78//wJITEKElyOBaoCIx4wDQYJKoZIhvcNAQEL +BQAwEjEQMA4GA1UEAwwHTGFiNy1DQTAeFw0yNjEyMDQxODE4NTRaFw0yNzEyMDQx +ODE4NTRaMBIxEDAOBgNVBAMMB0xhYjctQ0EwggIiMA0GCSqGSIb3DQEBAQUAA4IC +DwAwggIKAoICAQDOzw/toQSMLYk9nwdFsly/Xyp70WATwQc1tLkmfRqb+AMNa5GQ +XopgW2T2OKV/PL4PBE5g1mTn6B+QWj3LkuPTxgr/LUEuPGPEmQRoYdkrCsbFTgg2 +UEVpCFy3b88BirC+czmWnsPA9S2zFwr3WDkSoDt3tP5ITF41VxPnpWdc/4DKjPlQ +8wSds0tTNVxkSOHgUkrA0JrN1i7WbaLnUrifg6iW5Ts6Um8hvPWR6n3pjjJgq89p +EMxbss6SmzzuXoSBKQQOFAdfSLZqv567D6OsHHAvqEyqjRaflmF1EGO+HrnN/cfR +wHj6PXgtOEIafoiQ+N/lm377PAZ0AYvq+gaQLJNsdf+5DR57qbdK5cBj7CAqNbHA +tbfoKhWfkfVSlK1kBrON5gTDlAm3ekw01JEPTMwzrdjyQKTXTB2lbrEUYzKu+QAA +fCABePpGejvEXCJ4zqr+u+IjNhguPtDOUj4H6xBkHgW2JjHBGJA6b8W9qMddujQN +FjSl4xq0FBc5IPDuZj/9Je7/YrWkx/O2ooP87908XFqGj67cMU4+1Xrra8LYZkhJ +Kr5Gsm6vM4i0dc6SxMVNuLg01AM/ACsA85dW3dzB5QkU3AHRGB1sB/IUboh7Ha1X +BiielBKZRNVtj7IsOPkK0msSFrq+lIdfkctaS8/kD3ZDrN59Z4TLrSUjOQIDAQAB +o1MwUTAdBgNVHQ4EFgQUGfgh8KsltBxVKJ/TF1Rmk3FyDpMwHwYDVR0jBBgwFoAU +Gfgh8KsltBxVKJ/TF1Rmk3FyDpMwDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0B +AQsFAAOCAgEAoIS77SNcwkhICetXNwusYliEYyki3nQa3S+IRSCCDb41PeYDhZCr +JJrkuDQ2nPRd9UJMmPHfaQhjCweOi6PUW9fqBnWW9GYXXk+GFmxucRe1girKBXo8 +NwhM1uLhkHHLks8dGbM8Hrd+7piHrLgyF7wZGiL5bqSPI3ex/X0zNuV0eFpJjU4t +FGF5u0SQJcnbKVdEVn0L4pFNnAWvw4uJwMyldcm3l/S09GA80EbOdZtEfTLCkrDD +Y9CHnGPvnlUXt3rM0Zw4BFPjCtTZ1wxU0XD6l22n67hfbGMxQSWbTD7LbcBE6ctB +vdBsyIBN+qAEKHJpJnnEfOtSOYZ9PCuYWKPpj52XrofOeGrJu+cMu+8OKPFBUG9x +XtKynSaS9/gFxmpb5BxJF0Vn+F0AXol20WSDhJoNRfgNzIk1hDNMcey7R4pu/UnW +/Z9KFl5iFXngCMHbAwPqrfCRZnfOUjr2Le1SrOzTpcl84Z7JH/HrIxnur+5P5dHJ +Lja5BcD7RdQ5ZZBHTKvBTH8i7jBoe7rBOG0s5DIN0q6uPt+e9odQuzj4oinGx9/G +fIVybw22Z++kM++QRVkeXvnS9LSEUHejai2MO0MWDJEwoCN+Z0CP8VSmz60fmgwd +JnyRB7FKjKjzMwdPVpNkf0w2GWyi3N2LEYRPboYcV6+07vnagpAe16g= +-----END CERTIFICATE----- diff --git a/nginx/certs/ca.srl b/nginx/certs/ca.srl new file mode 100644 index 00000000..dd83970b --- /dev/null +++ b/nginx/certs/ca.srl @@ -0,0 +1 @@ +74248851803397EDECD9A3CEA17A890ECBFCCA7D diff --git a/nginx/certs/client.crt b/nginx/certs/client.crt new file mode 100644 index 00000000..9445f552 --- /dev/null +++ b/nginx/certs/client.crt @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDrDCCAZQCFHQkiFGAM5ft7NmjzqF6iQ7L/Mp8MA0GCSqGSIb3DQEBCwUAMBIx +EDAOBgNVBAMMB0xhYjctQ0EwHhcNMjYxMjA0MTgxOTE2WhcNMjcxMjA0MTgxOTE2 +WjATMREwDwYDVQQDDAhuZ2lueC1sYjCCASIwDQYJKoZIhvcNAQEBBQADggEPADCC +AQoCggEBAMFB6q4P9QMFUG+xES7iofM6hLJBJVmV/V9Tp7fcxQhET8o+r3YesvZS +Bcmx11DwJMNUTkBq8KiHvzjQKDesmN1Qg9EqAbfCJPVS3RnkYKi4ah+1DiVUWkwZ +t5WZqhR2As5j9cQZNXDowLBVJD2LbC/HNH6oDUgwIqmWmI1LO9rWZ+9bBImbk0a8 +KMyOshfxcIBRp1Sgf5hR7+dqaTCXqmRxFpWBiH4d9kOIr72vJk4OBL35dTuVemI/ +FhtV7CkhJ6Ji1xPHUGWKuSCCufJVmu5R6NsyokyXpVWKjqFGDXQns1Vm2RTDERzs +vlqKWrTCGVqU4fQ9Owbsodfg7Mjis/sCAwEAATANBgkqhkiG9w0BAQsFAAOCAgEA +FLj8nQnIO/bJn7/dBVyMfxVOG0QzYOeGa7RS1lR6TxYFJui6j7eQLFJIx/Wcqgm4 +Lu9lkJnDpFy39T+gk30RrnvciceGSFyxafZgDEHbk0gGKVh3M1Z/Sf6GWPrQrKEt +7AfwS2dGzV8k1kW9ey0wiNsKv9s+BGWBxsDk72UIenv16fDegx8DDvIw13oduOsh +14CJWjnJeZLQrVNX/REt7Cr9vjhOLCFrGzUF/1m62MwJJBbacOshjyAK7KueGZII ++zYJgXAQIEoLbbm+l5EGGcg/Ks4FeCIf42HuVU5w4xepYpm9tt6A94ndyZ+S8qDT +UbLVN9acPv9+bp3Zwk8TtQEUSaX7cyR6fSw7n/wop3+CBDPYSXBzHNG2QTaYZhQ+ +6W/C81BeLXyCFdLZRv79zobTRLsONaklmilLNxlsnMh/lTUZot7m0UShor/zV9SV +bfsaMVVg0Usj6IQN0f9vt3CEP9jCbtqCLMRRHamoihSYMgoXJEl/RzGuhM5IA/S9 +HtOX98MKNPUryvm1kekiP2tatzYxuGVGM5cWuOIRDicwrqPbiAmbsT7Tqti8K6yP +84KrXb1yU6ASD+RaKi68JwwsrixdMPJsipP9eQt8aa4qUJ3tlOSKepXFoC3uQn+0 +MRbUOxGQdt49XKM89CNwEXAU2a6rRPb9QTIkPnT45s8= +-----END CERTIFICATE----- diff --git a/nginx/certs/client.csr b/nginx/certs/client.csr new file mode 100644 index 00000000..698b8808 --- /dev/null +++ b/nginx/certs/client.csr @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICWDCCAUACAQAwEzERMA8GA1UEAwwIbmdpbngtbGIwggEiMA0GCSqGSIb3DQEB +AQUAA4IBDwAwggEKAoIBAQDBQequD/UDBVBvsREu4qHzOoSyQSVZlf1fU6e33MUI +RE/KPq92HrL2UgXJsddQ8CTDVE5AavCoh7840Cg3rJjdUIPRKgG3wiT1Ut0Z5GCo +uGoftQ4lVFpMGbeVmaoUdgLOY/XEGTVw6MCwVSQ9i2wvxzR+qA1IMCKplpiNSzva +1mfvWwSJm5NGvCjMjrIX8XCAUadUoH+YUe/namkwl6pkcRaVgYh+HfZDiK+9ryZO +DgS9+XU7lXpiPxYbVewpISeiYtcTx1BlirkggrnyVZruUejbMqJMl6VVio6hRg10 +J7NVZtkUwxEc7L5ailq0whlalOH0PTsG7KHX4OzI4rP7AgMBAAGgADANBgkqhkiG +9w0BAQsFAAOCAQEAZk/myi+jIVZuB4Ig/JboX9pSCvWtF+fy38DvaXm/M3uKrZSG +NPadU1qpJRyaaE4pr5tcJQl6DY1wtRssZTjc4UGFqnGILqe5eHUjeelDin5t+693 +nGm2QU7/NQw/157u+xb/pTgUVIyPXv/lApGvLyCJS1lRn/74Nh72Jjx8mHSBOIoN +qRmh4NNbdAbED6aXd+saqFAhcCRBb0whta99hiiRyq5d/LNfiweii6vnMxIXQG4A +hKy2u/C99Fqlboic/pQMoKTb9bjsG2t7jW9S3yMBijVJiuD+t79ex2tzG2K30ke4 +DD05rmr/FKi1sf3Uv2ZCbEZIqiNLBk3rE1IahQ== +-----END CERTIFICATE REQUEST----- diff --git a/nginx/certs/nginx.crt b/nginx/certs/nginx.crt new file mode 100644 index 00000000..3b878b99 --- /dev/null +++ b/nginx/certs/nginx.crt @@ -0,0 +1,19 @@ +-----BEGIN CERTIFICATE----- +MIIDCTCCAfGgAwIBAgIUFLdnp5z5ToBI1XgBi6TtvuUfz2wwDQYJKoZIhvcNAQEL +BQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MB4XDTI2MTIwNDE2MzMyNFoXDTI3MTIw +NDE2MzMyNFowFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0BAQEF +AAOCAQ8AMIIBCgKCAQEAlCgBsurtQ47QgEtt2SVG7hoGt3+FmZ0gz/EoufA7Gn+l +xJo/MYKfgAoCiU2+UPmh4+377MJ69Ho7eQzHIng10HvIwEkC4SyOqcNatagixCPR +bJi8hakKOPnRgzmJyO9Q03CrFkJoZtNa49gYfPxgMZWavX63+15e/R3Mw98yoYJ3 +xEMcNpsnsSOLMg2YGJIN3aZEa27ZgVj06TpjV7uiGdjIgD4gW0bbtW5b2UDEglrX +uvsxcY3V3oFLeixhCrcqHTbzPac4SoAh+iYe72czvuMSNZHIUoO8B9WwM9rKwlCS +fYkUP3O5XONTOp6avCSsrytnIGvHHnCPaavv4xf22QIDAQABo1MwUTAdBgNVHQ4E +FgQUte79dEQe969H9EGm754nYjj2Ed0wHwYDVR0jBBgwFoAUte79dEQe969H9EGm +754nYjj2Ed0wDwYDVR0TAQH/BAUwAwEB/zANBgkqhkiG9w0BAQsFAAOCAQEAZnaw +ro5b11VbG5AFAeDivk5kNvOUbUBjUgtGh7kTOulM6svIo2LjwVdKbnnxhd7Ni5ZY +pF0beJap/rGjFVdNoYglwy/6brc0UbExREE7CknvRRpMBqfQOcYRvmIvcweBt6Wk +gDjj+8dO7/nPfAFkLukmjn5GdkW28yxoMXw4BfTcQJzocbB9wQY5qy/Ysa9Hdi3P +3ADByvgDZ7LrlEoDmu6j09e+eZUA09HzF04KYPIZGH1ZtKT4Zqa4hX2Az1Kt2nzS +hrHPj1Mkhq2Axt8RpilJsFBGVtnXnOR402uGasElbhY9+RQAVf4RXCGs7Wez6AZ7 +qt1wCg6hN17I9QGorQ== +-----END CERTIFICATE----- diff --git a/nginx/certs/server.crt b/nginx/certs/server.crt new file mode 100644 index 00000000..e310a504 --- /dev/null +++ b/nginx/certs/server.crt @@ -0,0 +1,22 @@ +-----BEGIN CERTIFICATE----- +MIIDrTCCAZUCFHQkiFGAM5ft7NmjzqF6iQ7L/Mp7MA0GCSqGSIb3DQEBCwUAMBIx +EDAOBgNVBAMMB0xhYjctQ0EwHhcNMjYxMjA0MTgxOTAzWhcNMjcxMjA0MTgxOTAz +WjAUMRIwEAYDVQQDDAlsb2NhbGhvc3QwggEiMA0GCSqGSIb3DQEBAQUAA4IBDwAw +ggEKAoIBAQCc2cAx07dp8V8XXh9yMvZDmXJxW1ZNDSdnZRd8R9BhacdDEcH9OoB3 +jlLsQI3sSriEac6k51SY5XBJ/rEGZEyF17kuUSXuZU+r0gbndUD3nn2SWV25pJ8H +OPT0gG/sEBJUs2jVfTWxN/7IbiJ0323Vc9TwjYcdydX5F6f0aVtLHaYGwwYnjIiA +tleuauWUzDY7ZPE6tFRgE+Oh/h9T1BmnMtJRX2HNfgOO+7gBtTJQ6EEMW1n4H02O +IVeAW0tVJhLPTAkV26PEZa81trhQR25Wm8KLgXb/2gXQSi5ATFXln4SfQWUfb2iC +ZG5MuY80P3VcO7tm+kLByjWkuHkuoFUDAgMBAAEwDQYJKoZIhvcNAQELBQADggIB +AJ6ZxRejGW8TlQoQrLAh4pbArd7JBSk/BmB5wPjhwLVfauA/MoTvirQa3Vsth6Bc +sXAWDBwrYHTGjux7FS9v8Fxn5Y8xF7ADEpVTH2IRhxKRarkjPBsLubVaTcN7uPEX +70eQLFuu/EDLKIPM+QohmdsEeCPTZzIGUhNiO57BODjWPMV7daVUYVKjdmFEqv8W +iyLWiyLgjuEpt33Za+3/fkMsDALRPEkCy4ggLqGmzjj/sT5YbfXU76l7OjUZlDqr +sRPZ/2XvZkgEhYos/rTu7pq+zYc6eopN0ExqupwTp62xv2e+OaCTjTBRzy7ZD3s4 +ygvnQtEhNrOezIiCF4V9VJRjFLTPesEYmrEk5XBBBaX48pWKilC91QygsFrUDh0u +8BfW4U5mzLiuKFY2a5io0y1uB1lWo5Jsq5J32GwEh1P5LR7Apr8youiA8LAr4J2h +vpWVLx4UhF8cTvmVY6skTgUlrO3gi7+COO/FNqzigA6JKDln5G5VdXeG9c3r3PTC +WL1vxmsfh9X9kPnGBb9udaH41/VdMgyCONqB2Th3rdkcpugSxr8WYNbNYt9+zwGu +ZRgi4u2hglvTXgBPRwxLXyYKjjtyB4aRGpgOhy7uINepMBSJyQqVVAnHX57FXGHJ +Wg48UNDMzGQ0nYVjRN9DQCoNDbcj+tDAq+N6NTRI/naY +-----END CERTIFICATE----- diff --git a/nginx/certs/server.csr b/nginx/certs/server.csr new file mode 100644 index 00000000..34657d47 --- /dev/null +++ b/nginx/certs/server.csr @@ -0,0 +1,15 @@ +-----BEGIN CERTIFICATE REQUEST----- +MIICWTCCAUECAQAwFDESMBAGA1UEAwwJbG9jYWxob3N0MIIBIjANBgkqhkiG9w0B +AQEFAAOCAQ8AMIIBCgKCAQEAnNnAMdO3afFfF14fcjL2Q5lycVtWTQ0nZ2UXfEfQ +YWnHQxHB/TqAd45S7ECN7Eq4hGnOpOdUmOVwSf6xBmRMhde5LlEl7mVPq9IG53VA +9559kllduaSfBzj09IBv7BASVLNo1X01sTf+yG4idN9t1XPU8I2HHcnV+Ren9Glb +Sx2mBsMGJ4yIgLZXrmrllMw2O2TxOrRUYBPjof4fU9QZpzLSUV9hzX4Djvu4AbUy +UOhBDFtZ+B9NjiFXgFtLVSYSz0wJFdujxGWvNba4UEduVpvCi4F2/9oF0EouQExV +5Z+En0FlH29ogmRuTLmPND91XDu7ZvpCwco1pLh5LqBVAwIDAQABoAAwDQYJKoZI +hvcNAQELBQADggEBAHGV6tmvfYsz74KbngLUSsMQHR1Fy3JN8ttzak7D5z2lQd0D +pyr9qnfTn5B+/E1LoySFB0jSvdqoexJd4cHdnZVPX6GKsbeHFV9UBq1g9/5ZGEzZ +1nUcYAm0DKY7odHCjse9sgPhxef5UM//WB6HxFxkzM7ic3WC73m+bSh2EeKFK3qu +mPi8W+9R2QCcTAWRH8zlyrd7AM6HnQ/sIzR0gHaGcyMcYTMCehU6jIShfv/eHSZp +qIfwsdPvyfdQ/kwi/Fm3rvcLGX1qjoboSacYPmFRPc7w1udjrshm6kLZon8tZN/t ++hP4o5JFso/CkOZwfwGevugk/3mpq6cmvHN0IdA= +-----END CERTIFICATE REQUEST----- diff --git a/nginx/nginx.conf b/nginx/nginx.conf new file mode 100644 index 00000000..4e6ff953 --- /dev/null +++ b/nginx/nginx.conf @@ -0,0 +1,38 @@ +worker_processes auto; + +events { worker_connections 1024; } + +http { + upstream api_backend { + least_conn; + # Теперь API слушает HTTPS на 8443 + server api1:8443 max_fails=1 fail_timeout=2s; + server api2:8443 max_fails=1 fail_timeout=2s; + } + + server { + # Внешний HTTPS для клиентов + listen 8443 ssl; + + ssl_certificate /etc/nginx/certs/server.crt; + ssl_certificate_key /etc/nginx/certs/server.key; + + location / { + proxy_pass https://api_backend; + proxy_http_version 1.1; + proxy_set_header Host $host; + proxy_set_header X-Real-IP $remote_addr; + proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; + proxy_set_header X-Forwarded-Proto $scheme; + + # mTLS: Nginx предъявляет клиентский сертификат API + proxy_ssl_certificate /etc/nginx/certs/client.crt; + proxy_ssl_certificate_key /etc/nginx/certs/client.key; + + # mTLS: Nginx проверяет сертификат API + proxy_ssl_verify on; + proxy_ssl_trusted_certificate /etc/nginx/certs/ca.crt; + proxy_ssl_verify_depth 3; + } + } +} \ 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..6138b2b9 --- /dev/null +++ b/observability/grafana/dashboards/api.json @@ -0,0 +1,40 @@ +{ + "annotations": {"list": []}, + "editable": true, + "panels": [ + { + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "fieldConfig": {"defaults": {"unit": "reqps"}}, + "gridPos": {"h": 8, "w": 8, "x": 0, "y": 0}, + "id": 1, + "targets": [{"expr": "sum(rate(http_requests_total[1m])) by (handler)", "legendFormat": "{{handler}}"}], + "title": "API RPS", + "type": "timeseries" + }, + { + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "fieldConfig": {"defaults": {"unit": "percentunit"}}, + "gridPos": {"h": 8, "w": 8, "x": 8, "y": 0}, + "id": 2, + "targets": [{"expr": "sum(rate(http_requests_total{status=~\"5..\"}[1m])) / sum(rate(http_requests_total[1m]))", "legendFormat": "5xx ratio"}], + "title": "API Error Rate (5xx)", + "type": "timeseries" + }, + { + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "fieldConfig": {"defaults": {"unit": "s"}}, + "gridPos": {"h": 8, "w": 8, "x": 16, "y": 0}, + "id": 3, + "targets": [ + {"expr": "histogram_quantile(0.50, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))", "legendFormat": "p50"}, + {"expr": "histogram_quantile(0.95, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))", "legendFormat": "p95"}, + {"expr": "histogram_quantile(0.99, sum(rate(http_request_duration_seconds_bucket[5m])) by (le))", "legendFormat": "p99"} + ], + "title": "API Duration (p50/p95/p99)", + "type": "timeseries" + } + ], + "schemaVersion": 39, + "title": "Lab6 API", + "uid": "lab6-api" +} \ 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..a3c4cbdf --- /dev/null +++ b/observability/grafana/dashboards/worker.json @@ -0,0 +1,52 @@ +{ + "annotations": {"list": []}, + "editable": true, + "panels": [ + { + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "fieldConfig": {"defaults": {"unit": "short"}}, + "gridPos": {"h": 8, "w": 12, "x": 0, "y": 0}, + "id": 1, + "targets": [ + {"expr": "sum(rate(worker_processed_total{result=\"success\"}[1m]))", "legendFormat": "Success"}, + {"expr": "sum(rate(worker_processed_total{result=\"error\"}[1m]))", "legendFormat": "Error"} + ], + "title": "Worker Jobs (Success/Error)", + "type": "timeseries" + }, + { + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "fieldConfig": {"defaults": {"unit": "s"}}, + "gridPos": {"h": 8, "w": 12, "x": 12, "y": 0}, + "id": 2, + "targets": [ + {"expr": "histogram_quantile(0.50, sum(rate(worker_duration_seconds_bucket[5m])) by (le))", "legendFormat": "p50"}, + {"expr": "histogram_quantile(0.95, sum(rate(worker_duration_seconds_bucket[5m])) by (le))", "legendFormat": "p95"}, + {"expr": "histogram_quantile(0.99, sum(rate(worker_duration_seconds_bucket[5m])) by (le))", "legendFormat": "p99"} + ], + "title": "Worker Duration (p50/p95/p99)", + "type": "timeseries" + }, + { + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "fieldConfig": {"defaults": {"unit": "short"}}, + "gridPos": {"h": 8, "w": 12, "x": 0, "y": 8}, + "id": 3, + "targets": [{"expr": "sum(worker_in_flight)", "legendFormat": "In Flight"}], + "title": "Worker Saturation (In Flight Jobs)", + "type": "timeseries" + }, + { + "datasource": {"type": "prometheus", "uid": "prometheus"}, + "fieldConfig": {"defaults": {"unit": "short"}}, + "gridPos": {"h": 8, "w": 12, "x": 12, "y": 8}, + "id": 4, + "targets": [{"expr": "sum(rabbitmq_queue_depth)", "legendFormat": "Queue Depth"}], + "title": "Queue Depth", + "type": "timeseries" + } + ], + "schemaVersion": 39, + "title": "Lab6 Worker", + "uid": "lab6-worker" +} \ No newline at end of file diff --git a/observability/grafana/provisioning/alerting/alerts.yaml b/observability/grafana/provisioning/alerting/alerts.yaml new file mode 100644 index 00000000..0e4d6123 --- /dev/null +++ b/observability/grafana/provisioning/alerting/alerts.yaml @@ -0,0 +1,41 @@ +apiVersion: 1 + +groups: + - orgId: 1 + name: "worker_alerts" + folder: "Lab6 Alerts" + interval: 1m + rules: + - uid: worker-errors + title: "Worker Errors Detected" + condition: C + data: + # A: Запрос в Prometheus + - refId: A + datasourceUid: "prometheus" + model: + expr: 'worker_processed_total{result="error"}' + instant: true + # B: Берем последнее значение (Reduce) + - refId: B + datasourceUid: "__expr__" + model: + expression: "A" + reducer: "last" + # C: Порог (Threshold) — если больше 0, то Firing + - refId: C + datasourceUid: "__expr__" + model: + expression: "B" + type: "threshold" + conditions: + - evaluator: + type: "gt" + params: [0] + noDataState: "NoData" + execErrState: "Error" + for: "0m" + labels: + severity: "critical" + annotations: + summary: "Worker has encountered errors!" \ No newline at end of file diff --git a/observability/grafana/provisioning/dashboards/dashboars.yaml b/observability/grafana/provisioning/dashboards/dashboars.yaml new file mode 100644 index 00000000..e3d01ca2 --- /dev/null +++ b/observability/grafana/provisioning/dashboards/dashboars.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..e1aff5d9 --- /dev/null +++ b/observability/grafana/provisioning/datasources/datasources.yaml @@ -0,0 +1,38 @@ +apiVersion: 1 + +datasources: + - name: Prometheus + type: prometheus + access: proxy + url: http://prometheus:9090 + isDefault: true + uid: prometheus + 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..729675d8 --- /dev/null +++ b/observability/otel-collector-config.yaml @@ -0,0 +1,53 @@ +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 + +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 + 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] + exporters: [loki] \ No newline at end of file diff --git a/observability/prometheus/alerts.yml b/observability/prometheus/alerts.yml new file mode 100644 index 00000000..e1782aa3 --- /dev/null +++ b/observability/prometheus/alerts.yml @@ -0,0 +1,20 @@ +groups: + - name: lab6_alerts + rules: + # Правило 1: Высокий процент ошибок 5xx на API + - alert: HighErrorRate + expr: sum(rate(http_requests_total{status=~"5.."}[5m])) / sum(rate(http_requests_total[5m])) > 0.05 + for: 2m + labels: + severity: critical + annotations: + summary: "High 5xx error rate detected" + + # Правило 2: Ошибки в воркере + - alert: WorkerErrors + expr: worker_processed_total{result="error"} > 0 + for: 0m + labels: + severity: warning + annotations: + summary: "Worker errors detected" \ No newline at end of file diff --git a/observability/prometheus/prometheus.yml b/observability/prometheus/prometheus.yml new file mode 100644 index 00000000..105af3c0 --- /dev/null +++ b/observability/prometheus/prometheus.yml @@ -0,0 +1,24 @@ +global: + scrape_interval: 15s + evaluation_interval: 15s + + +rule_files: + - "alerts.yml" + +scrape_configs: + + - job_name: "prometheus" + static_configs: + - targets: ["localhost:9090"] + + + - job_name: "otel-collector" + static_configs: + - targets: ["otel-collector:8889"] + + + - job_name: "api" + metrics_path: /metrics + static_configs: + - targets: ["api1:8080", "api2:8080"] \ 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..8ecc9adf --- /dev/null +++ b/requirements.txt @@ -0,0 +1,25 @@ +# --- базовые из лабы 5 --- +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 + +# --- OTel для лабы 6/7 --- +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 + +# --- НОВОЕ для лабы 7 (OpenBao) --- +requests==2.32.3 \ No newline at end of file diff --git a/scripts/init_openbao.sh b/scripts/init_openbao.sh new file mode 100644 index 00000000..a6c9840e --- /dev/null +++ b/scripts/init_openbao.sh @@ -0,0 +1,36 @@ +#!/bin/sh +set -eu + +echo "Waiting for OpenBao to start..." +sleep 5 + +INIT_STATUS=$(curl -s -o /dev/null -w "%{http_code}" http://openbao:8200/v1/sys/init) + +if [ "$INIT_STATUS" = "200" ]; then + echo "OpenBao is already initialized. Skipping init." + exit 0 +fi + +echo "Initializing OpenBao..." +INIT_OUTPUT=$(curl -s -X PUT http://openbao:8200/v1/sys/init -d '{"secret_shares": 1, "secret_threshold": 1}') +ROOT_TOKEN=$(echo "$INIT_OUTPUT" | grep -o '"root_token":"[^"]*' | cut -d'"' -f4) +UNSEAL_KEY=$(echo "$INIT_OUTPUT" | grep -o '"keys":\["[^"]*' | cut -d'"' -f4) + +echo "Unsealing OpenBao..." +curl -s -X PUT http://openbao:8200/v1/sys/unseal -d "{\"key\": \"$UNSEAL_KEY\"}" > /dev/null + +echo "Writing secrets to OpenBao..." +curl -s -X POST -H "X-Vault-Token: $ROOT_TOKEN" http://openbao:8200/v1/sys/mounts/secret -d '{"type": "kv", "options": {"version": "2"}}' > /dev/null + +curl -s -X POST -H "X-Vault-Token: $ROOT_TOKEN" http://openbao:8200/v1/secret/data/messenger -d '{ + "data": { + "db_password": "messenger_password", + "s3_access_key": "minioadmin", + "s3_secret_key": "minioadmin", + "broker_url": "amqp://guest:guest@broker:5672/" + } +}' > /dev/null + +echo "OpenBao initialization complete." +echo "ROOT_TOKEN=$ROOT_TOKEN" +echo "UNSEAL_KEY=$UNSEAL_KEY" \ No newline at end of file diff --git a/scripts/migrate.py b/scripts/migrate.py new file mode 100644 index 00000000..e617f679 --- /dev/null +++ b/scripts/migrate.py @@ -0,0 +1,58 @@ +import os +import sys +import time +from pathlib import Path +import psycopg + +def get_dsn(): + file_path = os.environ.get("DATABASE_URL_FILE") + if file_path and os.path.exists(file_path): + return Path(file_path).read_text().strip() + return os.environ.get("DATABASE_URL") + +def main(): + dsn = get_dsn() + if not dsn: + print("ERROR: DATABASE_URL or DATABASE_URL_FILE not set", file=sys.stderr) + sys.exit(1) + + for i in range(10): + try: + with psycopg.connect(dsn, autocommit=True) as conn: + with conn.cursor() as cur: + cur.execute("SELECT 1") + break + except psycopg.OperationalError: + print("Waiting for database...") + time.sleep(2) + else: + print("ERROR: Database is not ready", file=sys.stderr) + sys.exit(1) + + # ВАЖНО: путь к миграциям. Раз они лежат в src/migrations: + migrations_dir = Path(__file__).parent.parent / "src" / "migrations" + sql_files = sorted(migrations_dir.glob("*.sql")) + + with psycopg.connect(dsn, autocommit=True) as conn: + with conn.cursor() as cur: + cur.execute(""" + CREATE TABLE IF NOT EXISTS schema_migrations ( + version text PRIMARY KEY, + applied_at timestamptz DEFAULT now() + ) + """) + + for sql_file in sql_files: + version = sql_file.name + cur.execute("SELECT 1 FROM schema_migrations WHERE version = %s", (version,)) + if cur.fetchone(): + continue + + print(f"Applying {version}...") + sql = sql_file.read_text(encoding="utf-8") + cur.execute(sql) + cur.execute("INSERT INTO schema_migrations (version) VALUES (%s)", (version,)) + print(f"Applied {version}.") + +if __name__ == "__main__": + main() \ No newline at end of file diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100644 index 00000000..43cfb34a --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,6 @@ +#!/bin/sh +set -eu +echo "Restarting API and Postgres (preserving volumes)..." +docker compose restart api1 api2 postgres +echo "Waiting for Postgres to be healthy..." +sleep 5 \ No newline at end of file diff --git a/scripts/stop_one.sh b/scripts/stop_one.sh new file mode 100644 index 00000000..14859318 --- /dev/null +++ b/scripts/stop_one.sh @@ -0,0 +1,13 @@ +#!/bin/sh +set -eu +: "${TARGET_INSTANCE_ID:?test provides target API instance alias}" +if [ "$TARGET_INSTANCE_ID" != "api-1" ] && [ "$TARGET_INSTANCE_ID" != "api-2" ]; then + echo "Unknown instance: $TARGET_INSTANCE_ID" >&2 + exit 1 +fi +SERVICE_NAME="$TARGET_INSTANCE_ID" +if [ "$SERVICE_NAME" = "api-1" ]; then SERVICE_NAME="api1"; fi +if [ "$SERVICE_NAME" = "api-2" ]; then SERVICE_NAME="api2"; fi + +echo "Stopping container for $SERVICE_NAME..." +docker compose stop "$SERVICE_NAME" \ No newline at end of file diff --git a/src/app/__init__.py b/src/app/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/app/config.py b/src/app/config.py new file mode 100644 index 00000000..09bae340 --- /dev/null +++ b/src/app/config.py @@ -0,0 +1,53 @@ +from functools import lru_cache +from pathlib import Path +from pydantic_settings import BaseSettings, SettingsConfigDict +from .vault import get_secrets + +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 = "lab7" + instance_id: str = "" + log_level: str = "info" + + session_ttl_seconds: int = 3600 + idempotency_ttl_seconds: int = 86400 + + database_url: str = "" + s3_access_key: str = "" + s3_secret_key: str = "" + broker_url: str = "" + + s3_endpoint: str = "http://minio:9000" + s3_bucket: str = "messenger-attachments" + s3_region: str = "us-east-1" + + broker_queue: str = "attachment_processing" + redis_url: str = "redis://redis:6379/0" + + otel_exporter_otlp_endpoint: str = "http://otel-collector:4317" + otel_service_name: str = "messenger-api" + otel_environment: str = "lab7" + + @property + def db_dsn(self) -> str: + secrets = get_secrets() + return f"postgresql://messenger:{secrets['db_password']}@postgres:5432/messenger" + + @property + def aws_access_key(self) -> str: + return get_secrets()["s3_access_key"] + + @property + def aws_secret_key(self) -> str: + return get_secrets()["s3_secret_key"] + + @property + def rabbit_url(self) -> str: + return get_secrets()["broker_url"] + +@lru_cache +def get_settings() -> Settings: + return Settings() \ No newline at end of file diff --git a/src/app/db.py b/src/app/db.py new file mode 100644 index 00000000..870b6ee2 --- /dev/null +++ b/src/app/db.py @@ -0,0 +1,45 @@ +from contextlib import contextmanager +from typing import Iterator + +import psycopg +from psycopg_pool import ConnectionPool + +from .config import get_settings + +_pool: ConnectionPool | None = None + + +def init_pool() -> ConnectionPool: + global _pool + if _pool is None: + _pool = ConnectionPool( + conninfo=get_settings().db_dsn, + min_size=1, + max_size=10, + timeout=5, + open=True, + ) + return _pool + + +def close_pool() -> None: + global _pool + if _pool is not None: + _pool.close() + _pool = None + + +@contextmanager +def connection() -> Iterator[psycopg.Connection]: + pool = init_pool() + with pool.connection() as conn: + yield conn + + +@contextmanager +def transaction() -> Iterator[psycopg.Connection]: + """Явная транзакция: commit при успехе, rollback при исключении.""" + pool = init_pool() + with pool.connection() as conn: + with conn.transaction(): + yield conn \ No newline at end of file diff --git a/src/app/errors.py b/src/app/errors.py new file mode 100644 index 00000000..c7e071c0 --- /dev/null +++ b/src/app/errors.py @@ -0,0 +1,31 @@ +from typing import Any + +from fastapi import Request +from fastapi.responses import JSONResponse + + +class ApiError(Exception): + """Наше приложение бросает это; handler превращает в JSON-ответ.""" + + def __init__(self, status: int, code: str, message: str, headers: dict[str, str] | None = None): + self.status = status + self.code = code + self.message = message + self.headers = headers or {} + + +def error_response( + request: Request, + status: int, + code: str, + message: str, + extra_headers: dict[str, str] | None = None, +) -> JSONResponse: + request_id = getattr(request.state, "request_id", "") or "unknown" + body: dict[str, Any] = { + "error": {"code": code, "message": message, "request_id": request_id} + } + headers = {"X-Request-Id": request_id} + if extra_headers: + headers.update(extra_headers) + return JSONResponse(status_code=status, content=body, headers=headers) \ No newline at end of file diff --git a/src/app/idempotency.py b/src/app/idempotency.py new file mode 100644 index 00000000..9855d870 --- /dev/null +++ b/src/app/idempotency.py @@ -0,0 +1,60 @@ +import hashlib +import json +import redis +from typing import Any, Callable +import psycopg + +from .config import get_settings +from .errors import ApiError +from .db import transaction + +redis_client = redis.Redis.from_url(get_settings().redis_url, decode_responses=True) + +def _body_hash(body: dict[str, Any]) -> str: + raw = json.dumps(body, sort_keys=True, separators=(",", ":"), ensure_ascii=False) + return hashlib.sha256(raw.encode("utf-8")).hexdigest() + +def run_idempotent( + *, + user_id: str, + scope: str, + key: str, + body: dict[str, Any], + action: Callable[[psycopg.Connection], tuple[int, dict[str, Any]]], +) -> tuple[int, dict[str, Any]]: + h = _body_hash(body) + redis_key = f"idem:{user_id}:{scope}:{key}" + ttl = get_settings().idempotency_ttl_seconds + + # Блокировка + locked = redis_client.set(redis_key, json.dumps({"status": 0, "hash": h}), nx=True, ex=ttl) + + if locked: + try: + with transaction() as conn: + status, payload = action(conn) + + redis_client.setex( + redis_key, + ttl, + json.dumps({"status": status, "hash": h, "payload": payload}) + ) + return status, payload + except Exception: + redis_client.delete(redis_key) + raise + + # Повторный запрос + existing_raw = redis_client.get(redis_key) + if not existing_raw: + raise ApiError(409, "conflict", "Конфликт идемпотентности, повторите") + + existing = json.loads(existing_raw) + + if existing.get("hash") != h: + raise ApiError(409, "conflict", "Тот же ключ с другим телом запроса") + + if existing.get("status") == 0: + raise ApiError(409, "conflict", "Повтор ещё не завершён") + + return existing["status"], existing["payload"] \ No newline at end of file diff --git a/src/app/image_check.py b/src/app/image_check.py new file mode 100644 index 00000000..e48b2307 --- /dev/null +++ b/src/app/image_check.py @@ -0,0 +1,13 @@ +def detect_image_type(data: bytes) -> str | None: + if data.startswith(b"\x89PNG\r\n\x1a\n"): + return "image/png" + if data.startswith(b"\xff\xd8\xff"): + return "image/jpeg" + return None + + +def check_image(first_bytes: bytes, allowed_types: list[str]) -> tuple[str, int, int]: + content_type = detect_image_type(first_bytes) + if not content_type or content_type not in allowed_types: + raise ValueError("Invalid or unsupported image type") + return content_type, 0, 0 \ No newline at end of file diff --git a/src/app/instance.py b/src/app/instance.py new file mode 100644 index 00000000..04404341 --- /dev/null +++ b/src/app/instance.py @@ -0,0 +1,15 @@ +import os +import secrets + +from .config import get_settings + + +def _build_instance_id() -> str: + s = get_settings() + if s.instance_id: + return s.instance_id + # Короткий случайный alias; при желании можно задать INSTANCE_ID в env. + return "api-" + secrets.token_hex(6) + + +INSTANCE_ID: str = _build_instance_id() 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 new file mode 100644 index 00000000..8d5539c3 --- /dev/null +++ b/src/app/main.py @@ -0,0 +1,66 @@ +import uuid +from contextlib import asynccontextmanager + +from fastapi import FastAPI, Request +from fastapi.exceptions import RequestValidationError +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: + db.init_pool() + except Exception: + pass + yield + db.close_pool() + + +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") +async def request_context(request: Request, call_next): + request_id = request.headers.get("X-Request-Id") or uuid.uuid4().hex + request.state.request_id = request_id + response = await call_next(request) + response.headers["X-Request-Id"] = request_id + response.headers["X-Instance-Id"] = INSTANCE_ID + return response + + +@app.exception_handler(ApiError) +async def api_error_handler(request: Request, exc: ApiError): + return error_response(request, exc.status, exc.code, exc.message, exc.headers) + + +@app.exception_handler(RequestValidationError) +async def validation_handler(request: Request, exc: RequestValidationError): + return error_response(request, 400, "invalid_request", "Неверный запрос") + + +@app.exception_handler(Exception) +async def unhandled_handler(request: Request, exc: Exception): + return error_response(request, 500, "internal_error", "Внутренняя ошибка сервера") + + +app.include_router(health.router) +app.include_router(users.router) +app.include_router(sessions.router) +app.include_router(chats.router) +app.include_router(messages.router) +app.include_router(attachments.router) \ No newline at end of file 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/routes/__init__.py b/src/app/routes/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/src/app/routes/attachments.py b/src/app/routes/attachments.py new file mode 100644 index 00000000..f3c057df --- /dev/null +++ b/src/app/routes/attachments.py @@ -0,0 +1,242 @@ +import hashlib +import io +import tempfile +import uuid +import json + +from fastapi import APIRouter, Depends, Request, Query +from fastapi.responses import StreamingResponse +from psycopg.rows import dict_row + +from ..db import transaction, connection +from ..errors import ApiError +from ..s3 import upload_fileobj, download_fileobj, delete_file +from ..image_check import check_image +from ..serializers import iso_z +from .sessions import require_actor + +router = APIRouter(prefix="/api/v1") +MAX_SIZE = 10 * 1024 * 1024 + +@router.post("/chats/{chat_id}/attachments", status_code=202) +async def upload_attachment( + chat_id: str, + request: Request, + filename: str = Query(..., max_length=255), + actor: dict = Depends(require_actor), +): + try: + uuid.UUID(chat_id) + except ValueError: + raise ApiError(400, "invalid_request", "Неверный chat_id") + + if "/" in filename or "\\" in filename or "\0" in filename: + raise ApiError(400, "invalid_request", "Опасное имя файла") + + with connection() as conn: + with conn.cursor() as cur: + cur.execute( + "SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", + (chat_id, actor["user_id"]), + ) + if cur.fetchone() is None: + raise ApiError(404, "not_found", "Чат не найден") + + sha256 = hashlib.sha256() + size = 0 + first_chunk = b"" + + with tempfile.SpooledTemporaryFile(max_size=MAX_SIZE, mode="w+b") as spooled: + async for chunk in request.stream(): + size += len(chunk) + if size > MAX_SIZE: + raise ApiError(413, "payload_too_large", "Файл слишком большой") + if not first_chunk: + first_chunk = chunk[:16] + sha256.update(chunk) + spooled.write(chunk) + + if size == 0: + raise ApiError(400, "invalid_request", "Пустой файл") + + try: + content_type, _, _ = check_image(first_chunk, ["image/png", "image/jpeg"]) + except ValueError: + raise ApiError(415, "unsupported_media_type", "Неподдерживаемый формат") + + sha256_hex = sha256.hexdigest() + object_key = f"chats/{chat_id}/{uuid.uuid4().hex}" + + try: + spooled.seek(0) + upload_fileobj(spooled, object_key, content_type) + except Exception as e: + print(f"S3 error: {e}") + raise ApiError(503, "unavailable", "S3 недоступен") + + try: + with transaction() as conn: + with conn.cursor(row_factory=dict_row) as cur: + # 1. Сохраняем вложение + cur.execute( + """ + INSERT INTO attachments (chat_id, owner_id, filename, content_type, size_bytes, sha256, object_key, status) + VALUES (%s, %s, %s, %s, %s, %s, %s, 'queued') + RETURNING id, chat_id, owner_id, filename, content_type, size_bytes, sha256, status, created_at, updated_at + """, + (chat_id, actor["user_id"], filename, content_type, size, sha256_hex, object_key), + ) + att = cur.fetchone() + + # 2. Сохраняем задачу в Outbox в ТОЙ ЖЕ транзакции + # Формат соответствует contracts/jobs.schema.json (лаба 7) + from datetime import datetime, timezone + + job_payload = { + "schema_version": 1, + "job_id": str(uuid.uuid4()), + "type": "attachment.process.v1", + "attachment_id": str(att["id"]), + "pipeline_version": 1, + "attempt": 1, + "created_at": datetime.now(timezone.utc).isoformat().replace("+00:00", "Z") + } + + cur.execute( + "INSERT INTO outbox_messages (attachment_id, payload) VALUES (%s, %s)", + (att["id"], json.dumps(job_payload)) + ) + except Exception as e: + print(f"DB failed, compensating S3: {e}") + try: + delete_file(object_key) + except Exception as s3_e: + print(f"Failed to compensate S3: {s3_e}") + raise ApiError(500, "internal_error", "Ошибка сохранения") + + return { + "id": str(att["id"]), + "chat_id": str(att["chat_id"]), + "owner_id": str(att["owner_id"]), + "filename": att["filename"], + "content_type": att["content_type"], + "size_bytes": att["size_bytes"], + "sha256": att["sha256"], + "status": att["status"], + "variants": [], + "error_code": None, + "created_at": iso_z(att["created_at"]), + "updated_at": iso_z(att["updated_at"]), + } + + +@router.get("/attachments/{attachment_id}") +def get_attachment(attachment_id: str, actor: dict = Depends(require_actor)): + try: + uuid.UUID(attachment_id) + except ValueError: + raise ApiError(400, "invalid_request", "Неверный id") + + with connection() as conn: + with conn.cursor(row_factory=dict_row) as cur: + cur.execute( + """ + SELECT a.* + FROM attachments a + JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = %s + WHERE a.id = %s + """, + (actor["user_id"], attachment_id), + ) + att = cur.fetchone() + + if att: + cur.execute("SELECT * FROM attachment_variants WHERE attachment_id = %s", (attachment_id,)) + variants = cur.fetchall() + else: + variants = [] + + if att is None: + raise ApiError(404, "not_found", "Вложение не найдено") + + return { + "id": str(att["id"]), + "chat_id": str(att["chat_id"]), + "owner_id": str(att["owner_id"]), + "filename": att["filename"], + "content_type": att["content_type"], + "size_bytes": att["size_bytes"], + "sha256": att["sha256"], + "status": att["status"], + "variants": [ + { + "name": v["name"], + "content_type": v["content_type"], + "size_bytes": v["size_bytes"], + "width": v["width"], + "height": v["height"], + "sha256": v["sha256"], + } for v in variants + ], + "error_code": att["error_code"], + "created_at": iso_z(att["created_at"]), + "updated_at": iso_z(att["updated_at"]), + } + + +@router.get("/attachments/{attachment_id}/content") +def download_attachment( + attachment_id: str, + variant: str = Query("original", pattern="^(original|thumbnail|crop|optimized)$"), + actor: dict = Depends(require_actor) +): + try: + uuid.UUID(attachment_id) + except ValueError: + raise ApiError(400, "invalid_request", "Неверный id") + + with connection() as conn: + with conn.cursor(row_factory=dict_row) as cur: + cur.execute( + """ + SELECT a.object_key, a.content_type, a.filename, a.status + FROM attachments a + JOIN chat_members cm ON cm.chat_id = a.chat_id AND cm.user_id = %s + WHERE a.id = %s + """, + (actor["user_id"], attachment_id), + ) + att = cur.fetchone() + + if att is None: + raise ApiError(404, "not_found", "Вложение не найдено") + + if variant == "original": + if att["status"] == "failed": + raise ApiError(409, "conflict", "Обработка вложения завершилась ошибкой") + obj_key = att["object_key"] + content_type = att["content_type"] + else: + cur.execute( + "SELECT object_key, content_type FROM attachment_variants WHERE attachment_id = %s AND name = %s", + (attachment_id, variant) + ) + var = cur.fetchone() + if not var: + raise ApiError(404, "not_found", "Вариант еще не готов или недоступен") + obj_key = var["object_key"] + content_type = var["content_type"] + + try: + body = download_fileobj(obj_key) + except Exception: + raise ApiError(503, "unavailable", "S3 недоступен") + + def iter_body(): + yield from body.iter_chunks(1024 * 1024) + + return StreamingResponse( + iter_body(), + media_type=content_type, + headers={"Content-Disposition": f'attachment; filename="{att["filename"]}"'}, + ) \ No newline at end of file diff --git a/src/app/routes/chats.py b/src/app/routes/chats.py new file mode 100644 index 00000000..5c547465 --- /dev/null +++ b/src/app/routes/chats.py @@ -0,0 +1,169 @@ +import base64 +import uuid +from datetime import datetime +from typing import Optional + +import psycopg +from fastapi import APIRouter, Depends, Query +from pydantic import BaseModel, ConfigDict, Field, field_validator +from psycopg.rows import dict_row + +from ..db import connection, transaction +from ..errors import ApiError +from ..serializers import row_to_chat +from .sessions import require_actor + +router = APIRouter(prefix="/api/v1") + + +class CreateChat(BaseModel): + model_config = ConfigDict(extra="forbid") + + title: str = Field(min_length=1, max_length=100) + member_ids: list[str] = Field(min_length=1, max_length=100) + + @field_validator("title") + @classmethod + def title_not_blank(cls, v: str) -> str: + if not v.strip(): + raise ValueError("title must not be blank") + return v + + @field_validator("member_ids") + @classmethod + def unique_members(cls, v: list[str]) -> list[str]: + if len(set(v)) != len(v): + raise ValueError("duplicate member_ids") + for s in v: + try: + uuid.UUID(s) + except ValueError: + raise ValueError("invalid uuid in member_ids") + return v + + +def _encode_cursor(created_at: datetime, id_) -> str: + raw = f"{created_at.isoformat()}|{id_}" + return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii").rstrip("=") + + +def _decode_cursor(cursor: str): + pad = "=" * (-len(cursor) % 4) + raw = base64.urlsafe_b64decode(cursor + pad).decode("utf-8") + ts, id_ = raw.split("|", 1) + return datetime.fromisoformat(ts), id_ + + +@router.post("/chats", status_code=201) +def create_chat(body: CreateChat, actor: dict = Depends(require_actor)): + me = actor["user_id"] + if str(me) not in body.member_ids: + raise ApiError(400, "invalid_request", "Вызывающий должен входить в member_ids") + + try: + with transaction() as conn: + with conn.cursor(row_factory=dict_row) as cur: + cur.execute( + "SELECT id FROM users WHERE id = ANY(%s::uuid[])", + (body.member_ids,), + ) + found = {str(r["id"]) for r in cur.fetchall()} + missing = set(body.member_ids) - found + if missing: + raise ApiError(400, "invalid_request", "Неизвестные участники") + + cur.execute( + "INSERT INTO chats (title) VALUES (%s) RETURNING id, title, created_at", + (body.title,), + ) + chat = cur.fetchone() + + cur.executemany( + "INSERT INTO chat_members (chat_id, user_id) VALUES (%s, %s)", + [(chat["id"], m) for m in body.member_ids], + ) + except ApiError: + raise + except psycopg.errors.ForeignKeyViolation: + raise ApiError(400, "invalid_request", "Неизвестные участники") + + chat["member_ids"] = body.member_ids + return row_to_chat(chat) + + +@router.get("/chats") +def list_chats( + limit: int = Query(default=50, ge=1, le=100), + cursor: Optional[str] = Query(default=None), + actor: dict = Depends(require_actor), +): + params: list = [] + where = ["cm.user_id = %s"] + params.append(actor["user_id"]) + + if cursor: + try: + c_ts, c_id = _decode_cursor(cursor) + except Exception: + raise ApiError(400, "invalid_request", "Неверный cursor") + where.append("(c.created_at, c.id) > (%s, %s)") + params.extend([c_ts, c_id]) + + sql = f""" + SELECT c.id, c.title, c.created_at, + ARRAY( + SELECT cm2.user_id::text + FROM chat_members cm2 + WHERE cm2.chat_id = c.id + ORDER BY cm2.user_id + ) AS member_ids + FROM chats c + JOIN chat_members cm ON cm.chat_id = c.id + WHERE {' AND '.join(where)} + ORDER BY c.created_at, c.id + LIMIT %s + """ + params.append(limit + 1) + + with connection() as conn: + with conn.cursor(row_factory=dict_row) as cur: + cur.execute(sql, params) + rows = cur.fetchall() + + next_cursor = None + if len(rows) > limit: + last = rows[limit - 1] + next_cursor = _encode_cursor(last["created_at"], str(last["id"])) + rows = rows[:limit] + + return {"items": [row_to_chat(r) for r in rows], "next_cursor": next_cursor} + + +@router.get("/chats/{chat_id}") +def get_chat(chat_id: str, actor: dict = Depends(require_actor)): + try: + uuid.UUID(chat_id) + except ValueError: + raise ApiError(400, "invalid_request", "Неверный chat_id") + + with connection() as conn: + with conn.cursor(row_factory=dict_row) as cur: + cur.execute( + """ + SELECT c.id, c.title, c.created_at, + ARRAY( + SELECT cm2.user_id::text + FROM chat_members cm2 + WHERE cm2.chat_id = c.id + ORDER BY cm2.user_id + ) AS member_ids + FROM chats c + JOIN chat_members cm ON cm.chat_id = c.id + WHERE c.id = %s AND cm.user_id = %s + """, + (chat_id, actor["user_id"]), + ) + row = cur.fetchone() + if row is None: + raise ApiError(404, "not_found", "Чат не найден") + return row_to_chat(row) \ No newline at end of file diff --git a/src/app/routes/health.py b/src/app/routes/health.py new file mode 100644 index 00000000..b0567a08 --- /dev/null +++ b/src/app/routes/health.py @@ -0,0 +1,42 @@ +from fastapi import APIRouter, Request +from fastapi.responses import JSONResponse +import socket +from urllib.parse import urlparse + +from ..config import get_settings +from ..db import connection +from ..errors import error_response +from ..s3 import get_s3_client + +router = APIRouter() + +@router.get("/health/live") +def live(): + return {"status": "ok"} + +@router.get("/health/ready") +def ready(request: Request): + try: + + with connection() as conn: + with conn.cursor() as cur: + cur.execute("SELECT 1") + cur.fetchone() + + + get_s3_client().head_bucket(Bucket=get_settings().s3_bucket) + + # 3. Broker (простая проверка TCP-порта) + settings = get_settings() + parsed = urlparse(settings.broker_url) + host = parsed.hostname or "broker" + port = parsed.port or 5672 + with socket.create_connection((host, port), timeout=2): + pass + + except Exception as e: + print(f"Readiness check failed: {e}") + return error_response( + request, 503, "unavailable", "Зависимость недоступна" + ) + return {"status": "ok"} \ No newline at end of file diff --git a/src/app/routes/messages.py b/src/app/routes/messages.py new file mode 100644 index 00000000..360e4e92 --- /dev/null +++ b/src/app/routes/messages.py @@ -0,0 +1,171 @@ +import re +import uuid +from datetime import datetime +from typing import Optional + +from fastapi import APIRouter, Depends, Header, Query +from pydantic import BaseModel, ConfigDict, Field +from psycopg.rows import dict_row + +from ..db import connection +from ..errors import ApiError +from ..idempotency import run_idempotent +from ..serializers import row_to_message +from .sessions import require_actor + +router = APIRouter(prefix="/api/v1") + +KEY_RE = re.compile(r"^[A-Za-z0-9._:-]{1,128}$") + + +class CreateMessage(BaseModel): + model_config = ConfigDict(extra="forbid") + + text: str = Field(max_length=4000) + attachment_ids: list[str] = Field(default_factory=list, max_length=10) + + +def _check_chat_member(conn, chat_id: str, user_id: str) -> None: + with conn.cursor() as cur: + cur.execute( + "SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", + (chat_id, user_id), + ) + if cur.fetchone() is None: + raise ApiError(404, "not_found", "Чат не найден") + + +def _encode_cursor(created_at: datetime, id_) -> str: + import base64 + raw = f"{created_at.isoformat()}|{id_}" + return base64.urlsafe_b64encode(raw.encode("utf-8")).decode("ascii").rstrip("=") + + +def _decode_cursor(cursor: str): + import base64 + pad = "=" * (-len(cursor) % 4) + raw = base64.urlsafe_b64decode(cursor + pad).decode("utf-8") + ts, id_ = raw.split("|", 1) + return datetime.fromisoformat(ts), id_ + + +@router.post("/chats/{chat_id}/messages", status_code=201) +def create_message( + chat_id: str, + body: CreateMessage, + idempotency_key: str = Header(..., alias="Idempotency-Key"), + actor: dict = Depends(require_actor), +): + try: + uuid.UUID(chat_id) + except ValueError: + raise ApiError(400, "invalid_request", "Неверный chat_id") + + if not KEY_RE.fullmatch(idempotency_key or ""): + raise ApiError(400, "invalid_request", "Неверный Idempotency-Key") + + if not body.text.strip() and not body.attachment_ids: + raise ApiError(400, "invalid_request", "Нужен текст или вложение") + + scope = f"POST /api/v1/chats/{chat_id}/messages" + + def action(conn): + _check_chat_member(conn, chat_id, actor["user_id"]) + with conn.cursor(row_factory=dict_row) as cur: + cur.execute( + """ + INSERT INTO messages (chat_id, sender_id, text) + VALUES (%s, %s, %s) + RETURNING id, chat_id, sender_id, text, created_at + """, + (chat_id, actor["user_id"], body.text), + ) + row = cur.fetchone() + + if body.attachment_ids: + for att_id in body.attachment_ids: + cur.execute( + "SELECT 1 FROM attachments WHERE id = %s AND chat_id = %s", + (att_id, chat_id), + ) + if cur.fetchone() is None: + raise ApiError(404, "not_found", "Вложение не найдено") + + cur.executemany( + "INSERT INTO message_attachments (message_id, attachment_id) VALUES (%s, %s)", + [(row["id"], att_id) for att_id in body.attachment_ids] + ) + + row["attachment_ids"] = body.attachment_ids + + return 201, row_to_message(row) + + _, payload = run_idempotent( + user_id=actor["user_id"], + scope=scope, + key=idempotency_key, + body=body.model_dump(), + action=action, + ) + return payload + + +@router.get("/chats/{chat_id}/messages") +def list_messages( + chat_id: str, + limit: int = Query(default=50, ge=1, le=100), + cursor: Optional[str] = Query(default=None), + actor: dict = Depends(require_actor), +): + try: + uuid.UUID(chat_id) + except ValueError: + raise ApiError(400, "invalid_request", "Неверный chat_id") + + with connection() as conn: + with conn.cursor() as cur: + cur.execute( + "SELECT 1 FROM chat_members WHERE chat_id = %s AND user_id = %s", + (chat_id, actor["user_id"]), + ) + if cur.fetchone() is None: + raise ApiError(404, "not_found", "Чат не найден") + + params: list = [chat_id] + where = ["m.chat_id = %s"] + if cursor: + try: + c_ts, c_id = _decode_cursor(cursor) + except Exception: + raise ApiError(400, "invalid_request", "Неверный cursor") + where.append("(m.created_at, m.id) > (%s, %s)") + params.extend([c_ts, c_id]) + + sql = f""" + SELECT m.id, m.chat_id, m.sender_id, m.text, m.created_at, + COALESCE( + ARRAY( + SELECT ma.attachment_id::text + FROM message_attachments ma + WHERE ma.message_id = m.id + ), ARRAY[]::text[] + ) AS attachment_ids + FROM messages m + WHERE {' AND '.join(where)} + ORDER BY m.created_at, m.id + LIMIT %s + """ + params.append(limit + 1) + + with connection() as conn: + with conn.cursor(row_factory=dict_row) as cur: + cur.execute(sql, params) + rows = cur.fetchall() + + next_cursor = None + if len(rows) > limit: + last = rows[limit - 1] + next_cursor = _encode_cursor(last["created_at"], str(last["id"])) + rows = rows[:limit] + + return {"items": [row_to_message(r) for r in rows], "next_cursor": next_cursor} \ No newline at end of file diff --git a/src/app/routes/sessions.py b/src/app/routes/sessions.py new file mode 100644 index 00000000..4781aad9 --- /dev/null +++ b/src/app/routes/sessions.py @@ -0,0 +1,40 @@ +@router.post("/auth/sessions", status_code=201) +def create_session(request: Request): + header = request.headers.get("Authorization") + username, password = _parse_basic(header) + + # Rate Limiting: не более 5 попыток в минуту + redis_key = f"login_attempts:{username}" + attempts = int(redis_client.get(redis_key) or 0) + if attempts >= 5: + raise ApiError(429, "rate_limited", "Слишком много попыток входа", {"Retry-After": "60"}) + + redis_client.incr(redis_key) + redis_client.expire(redis_key, 60) + + with connection() as conn: + with conn.cursor(row_factory=dict_row) as cur: + cur.execute( + "SELECT id, username, display_name, created_at, password_hash " + "FROM users WHERE username = %s", + (username,), + ) + row = cur.fetchone() + + if row is None or not verify_password(password, row["password_hash"]): + raise ApiError(401, "unauthorized", "Неверные учётные данные", {"WWW-Authenticate": WWW_BASIC}) + + settings = get_settings() + token = new_session_token() + ttl = settings.session_ttl_seconds + digest = token_digest(token) + + redis_client.setex(f"session:{digest}", ttl, str(row["id"])) + redis_client.delete(redis_key) # Сбрасываем счетчик при успешном входе + + return { + "token": token, + "token_type": "Bearer", + "expires_at": session_expiry(ttl).isoformat().replace("+00:00", "Z"), + "user": row_to_user(row), + } \ No newline at end of file diff --git a/src/app/routes/users.py b/src/app/routes/users.py new file mode 100644 index 00000000..773f8011 --- /dev/null +++ b/src/app/routes/users.py @@ -0,0 +1,52 @@ +from fastapi import APIRouter, Depends +from pydantic import BaseModel, ConfigDict, Field, field_validator +import psycopg + +from ..db import transaction +from ..errors import ApiError +from ..security import hash_password +from ..serializers import row_to_user +from .sessions import require_actor + +router = APIRouter(prefix="/api/v1") + + +class CreateUser(BaseModel): + model_config = ConfigDict(extra="forbid") + + username: str = Field(pattern=r"^[a-z0-9_]{3,32}$") + display_name: str = Field(min_length=1, max_length=100) + password: str = Field(min_length=12, max_length=128) + + @field_validator("display_name") + @classmethod + def not_blank(cls, v: str) -> str: + if not v.strip(): + raise ValueError("display_name must not be blank") + return v + + +@router.post("/users", status_code=201) +def create_user(body: CreateUser): + pwd_hash = hash_password(body.password) + try: + with transaction() as conn: + with conn.cursor(row_factory=psycopg.rows.dict_row) as cur: + cur.execute( + """ + INSERT INTO users (username, display_name, password_hash) + VALUES (%s, %s, %s) + RETURNING id, username, display_name, created_at + """, + (body.username, body.display_name, pwd_hash), + ) + row = cur.fetchone() + except psycopg.errors.UniqueViolation: + raise ApiError(409, "conflict", "Имя пользователя занято") + + return row_to_user(row) + + +@router.get("/users/me") +def current_user(actor: dict = Depends(require_actor)): + return actor["user"] \ No newline at end of file diff --git a/src/app/s3.py b/src/app/s3.py new file mode 100644 index 00000000..e470bef6 --- /dev/null +++ b/src/app/s3.py @@ -0,0 +1,39 @@ +import boto3 +from botocore.config import Config +from .config import get_settings + + +def get_s3_client(): + s = get_settings() + return boto3.client( + "s3", + endpoint_url=s.s3_endpoint, + aws_access_key_id=s.aws_access_key, + aws_secret_access_key=s.aws_secret_key, + region_name=s.s3_region, + config=Config(signature_version="s3v4"), + ) + + +def upload_fileobj(fileobj, key: str, content_type: str): + client = get_s3_client() + s = get_settings() + client.upload_fileobj( + fileobj, + s.s3_bucket, + key, + 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/src/app/security.py b/src/app/security.py new file mode 100644 index 00000000..48571144 --- /dev/null +++ b/src/app/security.py @@ -0,0 +1,34 @@ +import hashlib +import secrets +from datetime import datetime, timedelta, timezone +from argon2 import PasswordHasher +from argon2.exceptions import VerifyMismatchError + +# Явные параметры Argon2id для lab7 +_ph = PasswordHasher( + time_cost=2, + memory_cost=19456, # 19 MiB + parallelism=1, + hash_len=32, + salt_len=16 +) + +def hash_password(password: str) -> str: + return _ph.hash(password) + +def verify_password(password: str, password_hash: str) -> bool: + try: + return _ph.verify(password_hash, password) + except VerifyMismatchError: + return False + except Exception: + return False + +def new_session_token() -> str: + return secrets.token_urlsafe(32) + +def token_digest(token: str) -> str: + return hashlib.sha256(token.encode("utf-8")).hexdigest() + +def session_expiry(ttl_seconds: int) -> datetime: + return datetime.now(timezone.utc) + timedelta(seconds=ttl_seconds) \ No newline at end of file diff --git a/src/app/serializers.py b/src/app/serializers.py new file mode 100644 index 00000000..3b2bad4e --- /dev/null +++ b/src/app/serializers.py @@ -0,0 +1,35 @@ +from datetime import datetime + + +def iso_z(dt: datetime) -> str: + """RFC3339 UTC с 'Z'. Postgres отдаёт timestamptz с '+00:00'.""" + return dt.isoformat().replace("+00:00", "Z") + + +def row_to_user(row) -> dict: + return { + "id": str(row["id"]), + "username": row["username"], + "display_name": row["display_name"], + "created_at": iso_z(row["created_at"]), + } + + +def row_to_chat(row) -> dict: + return { + "id": str(row["id"]), + "title": row["title"], + "member_ids": row["member_ids"], + "created_at": iso_z(row["created_at"]), + } + + +def row_to_message(row) -> dict: + return { + "id": str(row["id"]), + "chat_id": str(row["chat_id"]), + "sender_id": str(row["sender_id"]), + "text": row["text"], + "created_at": iso_z(row["created_at"]), + "attachment_ids": row.get("attachment_ids", []), + } \ No newline at end of file diff --git a/src/app/vault.py b/src/app/vault.py new file mode 100644 index 00000000..d8b72cb8 --- /dev/null +++ b/src/app/vault.py @@ -0,0 +1,32 @@ +import os +import logging +import requests +from functools import lru_cache + +logger = logging.getLogger(__name__) + +@lru_cache(maxsize=None) +def get_secrets() -> dict: + vault_addr = os.environ.get("OPENBAO_ADDR", "http://openbao:8200") + token = os.environ.get("OPENBAO_TOKEN", "") + + if not token: + logger.warning("OPENBAO_TOKEN is not set. Using fallback.") + return { + "db_password": "messenger_password", + "s3_access_key": "minioadmin", + "s3_secret_key": "minioadmin", + "broker_url": "amqp://guest:guest@broker:5672/" + } + + url = f"{vault_addr}/v1/secret/data/messenger" + headers = {"X-Vault-Token": token} + + try: + resp = requests.get(url, headers=headers, timeout=5) + resp.raise_for_status() + data = resp.json()["data"]["data"] + return data + except Exception as e: + logger.error(f"Failed to fetch secrets from OpenBao: {e}") + raise RuntimeError("Cannot fetch secrets from OpenBao") \ No newline at end of file diff --git a/src/migrations/001_init.sql b/src/migrations/001_init.sql new file mode 100644 index 00000000..da374b89 --- /dev/null +++ b/src/migrations/001_init.sql @@ -0,0 +1,52 @@ +-- 001_init.sql +CREATE EXTENSION IF NOT EXISTS pgcrypto; + +CREATE TABLE IF NOT EXISTS users ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + username text NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100), + password_hash text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS sessions ( + token_hash text PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, + expires_at timestamptz NOT NULL, + created_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX IF NOT EXISTS sessions_user_id_idx ON sessions(user_id); +CREATE INDEX IF NOT EXISTS sessions_expires_at_idx ON sessions(expires_at); + +CREATE TABLE IF NOT EXISTS chats ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100), + created_at timestamptz NOT NULL DEFAULT now() +); + +CREATE TABLE IF NOT EXISTS chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, + PRIMARY KEY (chat_id, user_id) +); +CREATE INDEX IF NOT EXISTS chat_members_user_idx ON chat_members(user_id); + +CREATE TABLE IF NOT EXISTS messages ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + sender_id uuid NOT NULL REFERENCES users(id), + text text NOT NULL DEFAULT '', + created_at timestamptz NOT NULL DEFAULT now() +); +CREATE INDEX IF NOT EXISTS messages_chat_order_idx ON messages(chat_id, created_at, id); + +CREATE TABLE IF NOT EXISTS idempotency_keys ( + user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE, + scope text NOT NULL, -- method + " " + path + key text NOT NULL, + request_hash text NOT NULL, + status_code int NOT NULL, + response_json jsonb NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (user_id, scope, key) +); \ No newline at end of file diff --git a/src/migrations/002_attachments.sql b/src/migrations/002_attachments.sql new file mode 100644 index 00000000..64951308 --- /dev/null +++ b/src/migrations/002_attachments.sql @@ -0,0 +1,23 @@ +-- src/migrations/002_attachments.sql +CREATE TABLE IF NOT EXISTS attachments ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + owner_id uuid NOT NULL REFERENCES users(id), + filename text NOT NULL, + content_type text NOT NULL, + size_bytes bigint NOT NULL, + sha256 text NOT NULL, + object_key text NOT NULL, + status text NOT NULL DEFAULT 'queued' CHECK (status IN ('queued','processing','ready','failed')), + error_code text, + created_at timestamptz NOT NULL DEFAULT now(), + updated_at timestamptz NOT NULL DEFAULT now() +); + +CREATE INDEX IF NOT EXISTS attachments_chat_idx ON attachments(chat_id); + +CREATE TABLE IF NOT EXISTS message_attachments ( + message_id uuid NOT NULL REFERENCES messages(id) ON DELETE CASCADE, + attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, + PRIMARY KEY (message_id, attachment_id) +); \ No newline at end of file diff --git a/src/migrations/003_attachment_variants.sql b/src/migrations/003_attachment_variants.sql new file mode 100644 index 00000000..f08e2e25 --- /dev/null +++ b/src/migrations/003_attachment_variants.sql @@ -0,0 +1,13 @@ +-- src/migrations/003_attachment_variants.sql +CREATE TABLE IF NOT EXISTS attachment_variants ( + attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, + name text NOT NULL CHECK (name IN ('thumbnail','crop','optimized')), + content_type text NOT NULL CHECK (content_type IN ('image/jpeg','image/png','image/webp')), + size_bytes bigint NOT NULL CHECK (size_bytes > 0), + width int NOT NULL CHECK (width > 0), + height int NOT NULL CHECK (height > 0), + sha256 text NOT NULL, + object_key text NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + PRIMARY KEY (attachment_id, name) +); \ No newline at end of file diff --git a/src/migrations/004_outbox.sql b/src/migrations/004_outbox.sql new file mode 100644 index 00000000..9790f60b --- /dev/null +++ b/src/migrations/004_outbox.sql @@ -0,0 +1,19 @@ +-- src/migrations/004_outbox.sql + +-- Таблица для Transactional Outbox +CREATE TABLE IF NOT EXISTS outbox_messages ( + id uuid PRIMARY KEY DEFAULT gen_random_uuid(), + attachment_id uuid NOT NULL REFERENCES attachments(id) ON DELETE CASCADE, + payload jsonb NOT NULL, + created_at timestamptz NOT NULL DEFAULT now(), + processed_at timestamptz +); + +CREATE INDEX IF NOT EXISTS outbox_unprocessed_idx ON outbox_messages (created_at) WHERE processed_at IS NULL; + +-- Таблица для отслеживания попыток обработки +CREATE TABLE IF NOT EXISTS attachment_retries ( + attachment_id uuid PRIMARY KEY REFERENCES attachments(id) ON DELETE CASCADE, + attempts int NOT NULL DEFAULT 0, + last_error text +); \ No newline at end of file diff --git a/worker/__init__.py b/worker/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/worker/main.py b/worker/main.py new file mode 100644 index 00000000..2e8222ea --- /dev/null +++ b/worker/main.py @@ -0,0 +1,259 @@ +import asyncio +import io +import json +import logging +import hashlib +import random +import time + +import aio_pika +from PIL import Image +from psycopg.rows import dict_row +from opentelemetry import trace, context as otel_context +from opentelemetry.propagate import extract + +# Импорты для метрик +from opentelemetry.sdk.metrics import MeterProvider +from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader +from opentelemetry.exporter.otlp.proto.grpc.metric_exporter import OTLPMetricExporter +from opentelemetry.sdk.resources import Resource +from opentelemetry import metrics as otel_metrics + +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 +from worker.metrics import worker_duration, worker_processed, worker_in_flight + +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") + min_dim = min(crop.size) + left = (crop.width - min_dim) // 2 + top = (crop.height - min_dim) // 2 + 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 + + +async def _re_publish(body: bytes, headers: dict): + settings = get_settings() + connection = await aio_pika.connect_robust(settings.broker_url) + async with connection: + channel = await connection.channel() + await channel.declare_queue(settings.broker_queue, durable=True) + msg = aio_pika.Message(body=body, delivery_mode=aio_pika.DeliveryMode.PERSISTENT, headers=headers) + await channel.default_exchange.publish(msg, routing_key=settings.broker_queue) + + +async def _send_to_dlq(body: bytes, headers: dict): + settings = get_settings() + connection = await aio_pika.connect_robust(settings.broker_url) + async with connection: + channel = await connection.channel() + await channel.declare_queue("dead_letters", durable=True) + msg = aio_pika.Message(body=body, delivery_mode=aio_pika.DeliveryMode.PERSISTENT, headers=headers) + await channel.default_exchange.publish(msg, routing_key="dead_letters") + + +async def process_message(message: aio_pika.IncomingMessage): + headers = message.headers or {} + ctx = extract(headers) + token = otel_context.attach(ctx) + + 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"] + + with tracer.start_as_current_span("worker.process_attachment") as span: + span.set_attribute("attachment.id", att_id) + worker_in_flight.add(1) + start_time = time.time() + result = "error" + attempts = 0 + + logger.info("Processing attachment %s", att_id) + + try: + 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("Max retries (5) reached for %s. Sending to DLQ.", att_id) + 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, headers) + span.set_attribute("worker.result", "max_retries") + result = "error_max_retries" + worker_duration.record(time.time() - start_time) + worker_processed.add(1, {"result": result}) + worker_in_flight.add(-1) + otel_context.detach(token) + 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,), + ) + + 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) + result = "success" + + 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") + result = "error_permanent" + + except Exception as e: + logger.error("Error processing %s: %s", att_id, e) + span.set_attribute("worker.result", "error") + result = "error" + if not isinstance(e, PermanentError): + 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, headers) + finally: + duration = time.time() - start_time + worker_duration.record(duration, {"result": result}) + worker_processed.add(1, {"result": result}) + worker_in_flight.add(-1) + otel_context.detach(token) + + +async def main(): + setup_logging(get_settings().log_level) + setup_otel("messenger-worker") + + # --- ЭКСПОРТ МЕТРИК ИЗ ВОРКЕРА --- + s = get_settings() + resource = Resource.create({"service.name": "messenger-worker"}) + reader = PeriodicExportingMetricReader( + OTLPMetricExporter(endpoint=s.otel_exporter_otlp_endpoint, insecure=True), + export_interval_millis=5000, + ) + meter_provider = MeterProvider(resource=resource, metric_readers=[reader]) + otel_metrics.set_meter_provider(meter_provider) + # --------------------------------- + + init_pool() + settings = get_settings() + + asyncio.create_task(publish_loop()) + + while True: + try: + connection = await aio_pika.connect_robust(settings.broker_url) + break + except Exception as 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) + queue = await channel.declare_queue(settings.broker_queue, durable=True) + logger.info("Worker started, waiting for messages...") + await queue.consume(process_message) + await asyncio.Future() + + +if __name__ == "__main__": + asyncio.run(main()) \ No newline at end of file diff --git a/worker/metrics.py b/worker/metrics.py new file mode 100644 index 00000000..9f8e7b0a --- /dev/null +++ b/worker/metrics.py @@ -0,0 +1,34 @@ +from opentelemetry import metrics + +# Объявляем глобальные переменные +worker_duration = None +worker_processed = None +queue_depth = None +worker_in_flight = None + +def init_metrics(): + global worker_duration, worker_processed, queue_depth, worker_in_flight + + # Получаем meter ПОСЛЕ того, как установлен MeterProvider + meter = metrics.get_meter("messenger-worker") + + worker_duration = meter.create_histogram( + name="worker_duration_seconds", + description="Time taken to process attachment", + unit="s" + ) + + worker_processed = meter.create_counter( + name="worker_processed_total", + description="Total processed jobs by result" + ) + + queue_depth = meter.create_up_down_counter( + name="rabbitmq_queue_depth", + description="Number of messages in queue" + ) + + worker_in_flight = meter.create_up_down_counter( + name="worker_in_flight", + description="Current number of in-flight jobs" + ) \ No newline at end of file diff --git a/worker/outbox_publisher.py b/worker/outbox_publisher.py new file mode 100644 index 00000000..1f9872e0 --- /dev/null +++ b/worker/outbox_publisher.py @@ -0,0 +1,66 @@ +import asyncio +import json +import logging +import aio_pika +from opentelemetry import trace +from opentelemetry.propagate import inject +from psycopg.rows import dict_row + +from src.app.config import get_settings +from src.app.db import transaction + +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" + ) + messages = cur.fetchall() + + for msg in messages: + payload = msg["payload"] + with tracer.start_as_current_span("outbox.publish") as span: + span.set_attribute("outbox.message_id", str(msg["id"])) + + # Внедряем W3C traceparent в заголовки + headers = {} + inject(headers) + + message = aio_pika.Message( + body=json.dumps(payload).encode(), + delivery_mode=aio_pika.DeliveryMode.PERSISTENT, + headers=headers + ) + 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) + except Exception as e: + logger.error("Outbox error: %s", e) + await asyncio.sleep(2) \ No newline at end of file