forked from mtusi2026/mtusi2026lab7
Compare commits
2
Commits
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
1850512b57 | ||
|
|
38d908afc9 |
@@ -18,3 +18,7 @@ __pycache__
|
|||||||
node_modules
|
node_modules
|
||||||
evidence
|
evidence
|
||||||
.DS_Store
|
.DS_Store
|
||||||
|
|
||||||
|
secrets/
|
||||||
|
.env
|
||||||
|
.env.*
|
||||||
|
|||||||
+11
@@ -0,0 +1,11 @@
|
|||||||
|
FROM python:3.12.9-slim
|
||||||
|
WORKDIR /app
|
||||||
|
COPY requirements.txt ./
|
||||||
|
RUN pip install --no-cache-dir -r requirements.txt
|
||||||
|
COPY main.py migrate.py queueing.py worker.py telemetry.py ./
|
||||||
|
COPY migrations/ ./migrations/
|
||||||
|
COPY scripts/ ./scripts/
|
||||||
|
RUN useradd -u 10001 -m app
|
||||||
|
USER 10001
|
||||||
|
EXPOSE 8080
|
||||||
|
CMD ["uvicorn", "main:app", "--host", "0.0.0.0", "--port", "8080", "--timeout-graceful-shutdown", "8"]
|
||||||
@@ -1,37 +1,105 @@
|
|||||||
# Отчёт — лабораторная 7
|
# Лабораторная работа №7 — безопасность, mTLS и OpenBao
|
||||||
|
## Автор, группа: Магазейщикова Дарья, бпи2304
|
||||||
|
## Оценка: 3
|
||||||
|
|
||||||
- Автор, группа: TODO
|
## Реализация
|
||||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
|
||||||
- Commit/PR: TODO после публикации
|
|
||||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
|
||||||
|
|
||||||
## Запуск из чистого clone
|
Перенесена функциональность ЛР6.
|
||||||
|
Настроены HTTPS, внутренний mTLS, TLS для PostgreSQL,
|
||||||
|
RabbitMQ, S3 и компонентов телеметрии.
|
||||||
|
Реализованы Argon2id, ограничение частоты авторизации,
|
||||||
|
разграничение доступа и получение секретов через OpenBao.
|
||||||
|
|
||||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
## Стек
|
||||||
|
|
||||||
## Архитектура и решения
|
FastAPI, PostgreSQL, RabbitMQ, SeaweedFS, Nginx,
|
||||||
|
OpenBao, OpenTelemetry, Prometheus, Loki, Tempo, Grafana,
|
||||||
|
Docker Compose.
|
||||||
|
|
||||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
## Запуск
|
||||||
|
|
||||||
## Доказательства критериев
|
1. python scripts/bootstrap.py
|
||||||
|
2. docker compose up -d bao postgres broker
|
||||||
|
3. Выполнить инициализацию и unseal OpenBao.
|
||||||
|
4. python scripts/configure_bao.py
|
||||||
|
5. docker compose run --rm migrate
|
||||||
|
6. python scripts/setup_roles.py
|
||||||
|
7. python scripts/setup_broker_roles.py
|
||||||
|
8. docker compose up -d --build --wait
|
||||||
|
|
||||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
Root token и ключи unseal хранятся отдельно.
|
||||||
| --- | --- | --- | --- |
|
После перезапуска OpenBao требуется повторный unseal.
|
||||||
| Публичный smoke | make test | TODO | TODO |
|
|
||||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
|
||||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
|
||||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
|
||||||
|
|
||||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
## Результаты проверок
|
||||||
|
|
||||||
## Эксперименты и отказы
|
- Smoke: PASS.
|
||||||
|
- Security: PASS.
|
||||||
|
- Persistence: PASS.
|
||||||
|
- Failover: PASS.
|
||||||
|
- Offline contract: PASS.
|
||||||
|
- mTLS обеих реплик: доверенный LB — 200,
|
||||||
|
worker — 403, чужой сертификат и отсутствие сертификата — 400.
|
||||||
|
- OpenBao: доступ к собственным секретам разрешён,
|
||||||
|
к чужим запрещён. TTL токена — 600 секунд.
|
||||||
|
- PostgreSQL: TLS 1.3, незашифрованное подключение запрещено.
|
||||||
|
- Worker не имеет доступа к таблице users.
|
||||||
|
- RabbitMQ: TLS 1.3, непривилегированный пользователь.
|
||||||
|
- Телеметрия: шесть проверенных соединений TLS 1.3.
|
||||||
|
- Argon2id: m=19456 KiB, t=2, p=1.
|
||||||
|
- Хеширование: 32,91 мс, проверка: 37,26 мс.
|
||||||
|
- Rate limiting: HTTP 429, Retry-After.
|
||||||
|
- Истечение сессии: HTTP 401.
|
||||||
|
|
||||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
Failover: две реплики, 80 успешных записей,
|
||||||
|
одна неудачная попытка, восстановление за 2,022 секунды.
|
||||||
|
|
||||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
## Команды проверки
|
||||||
| --- | --- | --- | --- |
|
|
||||||
| TODO | TODO | TODO | TODO |
|
|
||||||
|
|
||||||
## Ограничения и следующие шаги
|
python scripts/check_contract.py
|
||||||
|
|
||||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
python tests/smoke.py --base-url https://localhost:8443 --ca-file secrets/ca.crt
|
||||||
|
|
||||||
|
python tests/security.py --base-url https://localhost:8443 --ca-file secrets/ca.crt
|
||||||
|
|
||||||
|
python tests/resilience.py --base-url https://localhost:8443 --ca-file secrets/ca.crt --mode persistence --action-script scripts/restart.cmd
|
||||||
|
|
||||||
|
python tests/resilience.py --base-url https://localhost:8443 --ca-file secrets/ca.crt --mode failover --action-script scripts/stop-one.cmd
|
||||||
|
|
||||||
|
## Модель угроз
|
||||||
|
|
||||||
|
- Перехват трафика: TLS и проверка сертификатов.
|
||||||
|
- Подмена балансировщика: mTLS и проверка identity.
|
||||||
|
- Подбор пароля: Argon2id и rate limiting.
|
||||||
|
- Кража секретов: OpenBao и ограниченные политики.
|
||||||
|
- Несанкционированный доступ: ACL и ограниченные роли БД.
|
||||||
|
- Отказ реплики: балансировка и сохранение данных.
|
||||||
|
|
||||||
|
## Матрица доверия
|
||||||
|
|
||||||
|
| Соединение | Защита |
|
||||||
|
|---|---|
|
||||||
|
| Client - LB | HTTPS, CA, hostname |
|
||||||
|
| LB - API | mTLS, проверка identity |
|
||||||
|
| API/Worker - PostgreSQL | TLS verify-full |
|
||||||
|
| Worker - RabbitMQ | AMQPS, CA, hostname |
|
||||||
|
| API/Worker - S3 | HTTPS, CA |
|
||||||
|
| Application - Collector | TLS |
|
||||||
|
| Collector - Loki/Tempo | TLS |
|
||||||
|
| Prometheus - Collector | HTTPS |
|
||||||
|
| Application - OpenBao | HTTPS, сертификат сервиса |
|
||||||
|
|
||||||
|
## Ограничения
|
||||||
|
|
||||||
|
Чистое развёртывание после последних изменений полностью
|
||||||
|
не проверено. Сканирование уязвимостей не выполнено.
|
||||||
|
Grafana доступна локально по HTTP.
|
||||||
|
Worker и dispatcher используют общую сервисную роль.
|
||||||
|
Миграции выполняются с повышенными правами.
|
||||||
|
OpenBao выдаёт статические credentials при запуске.
|
||||||
|
Отзыв токена не отзывает уже полученные credentials.
|
||||||
|
|
||||||
|
|
||||||
|
## Источники
|
||||||
|
|
||||||
|
Материалы лабораторной работы, реализация ЛР6,
|
||||||
|
документация используемых технологий.
|
||||||
|
|||||||
+451
@@ -0,0 +1,451 @@
|
|||||||
|
services:
|
||||||
|
broker:
|
||||||
|
image: rabbitmq:3.13.7-alpine
|
||||||
|
environment:
|
||||||
|
RABBITMQ_DEFAULT_USER: lab
|
||||||
|
RABBITMQ_DEFAULT_PASS: ${BROKER_PASSWORD:?run bootstrap}
|
||||||
|
volumes:
|
||||||
|
- broker_data:/var/lib/rabbitmq
|
||||||
|
- ./infra/rabbitmq.conf:/etc/rabbitmq/rabbitmq.conf:ro
|
||||||
|
- ./secrets/broker:/tls/server:ro
|
||||||
|
- ./secrets/ca.crt:/tls/ca.crt:ro
|
||||||
|
restart: unless-stopped
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
dispatcher:
|
||||||
|
build: .
|
||||||
|
environment:
|
||||||
|
S3_ENDPOINT: https://s3:8443
|
||||||
|
S3_BUCKET: messenger-attachments
|
||||||
|
OTEL_SERVICE_NAME: messenger-worker
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4317
|
||||||
|
DEPLOYMENT_ENV: lab
|
||||||
|
BAO_ROLE: worker
|
||||||
|
BAO_ADDR: https://bao:8200
|
||||||
|
depends_on: &id001
|
||||||
|
s3-init:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
migrate:
|
||||||
|
condition: service_completed_successfully
|
||||||
|
otel-collector:
|
||||||
|
condition: service_started
|
||||||
|
bao:
|
||||||
|
condition: service_started
|
||||||
|
restart: unless-stopped
|
||||||
|
stop_grace_period: 12s
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- worker.py
|
||||||
|
- dispatch
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
volumes:
|
||||||
|
- ./secrets/ca.crt:/tls/ca.crt:ro
|
||||||
|
- ./secrets/worker:/identity:ro
|
||||||
|
entrypoint:
|
||||||
|
- python
|
||||||
|
- scripts/bao_exec.py
|
||||||
|
worker:
|
||||||
|
build: .
|
||||||
|
environment:
|
||||||
|
S3_ENDPOINT: https://s3:8443
|
||||||
|
S3_BUCKET: messenger-attachments
|
||||||
|
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||||
|
OTEL_SERVICE_NAME: messenger-worker
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4317
|
||||||
|
DEPLOYMENT_ENV: lab
|
||||||
|
BAO_ROLE: worker
|
||||||
|
BAO_ADDR: https://bao:8200
|
||||||
|
depends_on: *id001
|
||||||
|
restart: unless-stopped
|
||||||
|
stop_grace_period: 12s
|
||||||
|
healthcheck:
|
||||||
|
disable: true
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- worker.py
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
volumes:
|
||||||
|
- ./secrets/ca.crt:/tls/ca.crt:ro
|
||||||
|
- ./secrets/worker:/identity:ro
|
||||||
|
entrypoint:
|
||||||
|
- python
|
||||||
|
- scripts/bao_exec.py
|
||||||
|
s3:
|
||||||
|
image: chrislusf/seaweedfs:3.80
|
||||||
|
command:
|
||||||
|
- server
|
||||||
|
- -dir=/data
|
||||||
|
- -ip=127.0.0.1
|
||||||
|
- -ip.bind=127.0.0.1
|
||||||
|
- -s3
|
||||||
|
- -s3.config=/etc/seaweedfs/s3.json
|
||||||
|
- -s3.port=8333
|
||||||
|
|
||||||
|
volumes:
|
||||||
|
- s3_data:/data
|
||||||
|
- ./secrets/s3.json:/etc/seaweedfs/s3.json:ro
|
||||||
|
- ./secrets/s3:/tls/server:ro
|
||||||
|
|
||||||
|
restart: unless-stopped
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
s3-tls:
|
||||||
|
image: nginx:1.27.5-alpine
|
||||||
|
network_mode: "service:s3"
|
||||||
|
depends_on:
|
||||||
|
- s3
|
||||||
|
volumes:
|
||||||
|
- ./infra/s3-tls.conf:/etc/nginx/conf.d/default.conf:ro
|
||||||
|
- ./secrets/s3:/tls/server:ro
|
||||||
|
restart: unless-stopped
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 128m
|
||||||
|
cpus: 0.5
|
||||||
|
s3-init:
|
||||||
|
build: .
|
||||||
|
volumes:
|
||||||
|
- ./scripts/init_bucket.py:/app/scripts/init_bucket.py:ro
|
||||||
|
- ./secrets/ca.crt:/tls/ca.crt:ro
|
||||||
|
- ./secrets/operator:/identity:ro
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- scripts/init_bucket.py
|
||||||
|
depends_on:
|
||||||
|
s3:
|
||||||
|
condition: service_started
|
||||||
|
bao:
|
||||||
|
condition: service_started
|
||||||
|
environment:
|
||||||
|
S3_ENDPOINT: https://s3:8443
|
||||||
|
S3_BUCKET: messenger-attachments
|
||||||
|
BAO_ROLE: operator
|
||||||
|
BAO_ADDR: https://bao:8200
|
||||||
|
restart: 'no'
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
entrypoint:
|
||||||
|
- python
|
||||||
|
- scripts/bao_exec.py
|
||||||
|
postgres:
|
||||||
|
image: postgres:16.8-alpine
|
||||||
|
environment:
|
||||||
|
POSTGRES_USER: ${POSTGRES_USER:-messenger}
|
||||||
|
POSTGRES_PASSWORD: ${POSTGRES_PASSWORD:?run bootstrap}
|
||||||
|
POSTGRES_DB: ${POSTGRES_DB:-messenger}
|
||||||
|
volumes:
|
||||||
|
- postgres_data:/var/lib/postgresql/data
|
||||||
|
- ./secrets/postgres:/tls:ro
|
||||||
|
- ./scripts/postgres-entrypoint.sh:/postgres-entrypoint.sh:ro
|
||||||
|
- ./infra/pg_hba.conf:/etc/pg_hba.conf:ro
|
||||||
|
entrypoint: ["/bin/sh", "/postgres-entrypoint.sh"]
|
||||||
|
command:
|
||||||
|
- postgres
|
||||||
|
- -c
|
||||||
|
- ssl=on
|
||||||
|
- -c
|
||||||
|
- hba_file=/etc/pg_hba.conf
|
||||||
|
- -c
|
||||||
|
- ssl_cert_file=/var/lib/postgresql/tls/server.crt
|
||||||
|
- -c
|
||||||
|
- ssl_key_file=/var/lib/postgresql/tls/server.key
|
||||||
|
healthcheck:
|
||||||
|
test:
|
||||||
|
- CMD-SHELL
|
||||||
|
- pg_isready -U $$POSTGRES_USER -d $$POSTGRES_DB
|
||||||
|
interval: 3s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 20
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
migrate:
|
||||||
|
build: .
|
||||||
|
command:
|
||||||
|
- python
|
||||||
|
- migrate.py
|
||||||
|
environment:
|
||||||
|
BAO_ROLE: operator
|
||||||
|
BAO_ADDR: https://bao:8200
|
||||||
|
depends_on:
|
||||||
|
postgres:
|
||||||
|
condition: service_healthy
|
||||||
|
bao:
|
||||||
|
condition: service_started
|
||||||
|
restart: 'no'
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
volumes:
|
||||||
|
- ./secrets/ca.crt:/tls/ca.crt:ro
|
||||||
|
- ./secrets/operator:/identity:ro
|
||||||
|
entrypoint:
|
||||||
|
- python
|
||||||
|
- scripts/bao_exec.py
|
||||||
|
api1:
|
||||||
|
build: .
|
||||||
|
environment:
|
||||||
|
INSTANCE_ID: api1
|
||||||
|
OTEL_SERVICE_NAME: messenger-api
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4317
|
||||||
|
DEPLOYMENT_ENV: lab
|
||||||
|
S3_ENDPOINT: https://s3:8443
|
||||||
|
S3_BUCKET: messenger-attachments
|
||||||
|
BAO_ROLE: api
|
||||||
|
BAO_ADDR: https://bao:8200
|
||||||
|
depends_on: *id001
|
||||||
|
restart: unless-stopped
|
||||||
|
stop_grace_period: 12s
|
||||||
|
healthcheck: &id002
|
||||||
|
test:
|
||||||
|
- CMD
|
||||||
|
- python
|
||||||
|
- -c
|
||||||
|
- import urllib.request; urllib.request.urlopen('http://127.0.0.1:8080/health/ready',timeout=2)
|
||||||
|
interval: 3s
|
||||||
|
timeout: 3s
|
||||||
|
retries: 5
|
||||||
|
start_period: 5s
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
volumes:
|
||||||
|
- ./secrets/ca.crt:/tls/ca.crt:ro
|
||||||
|
- ./secrets/api:/identity:ro
|
||||||
|
entrypoint:
|
||||||
|
- python
|
||||||
|
- scripts/bao_exec.py
|
||||||
|
command:
|
||||||
|
- uvicorn
|
||||||
|
- main:app
|
||||||
|
- --host
|
||||||
|
- 127.0.0.1
|
||||||
|
- --port
|
||||||
|
- '8080'
|
||||||
|
api2:
|
||||||
|
build: .
|
||||||
|
environment:
|
||||||
|
INSTANCE_ID: api2
|
||||||
|
OTEL_SERVICE_NAME: messenger-api
|
||||||
|
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4317
|
||||||
|
DEPLOYMENT_ENV: lab
|
||||||
|
S3_ENDPOINT: https://s3:8443
|
||||||
|
S3_BUCKET: messenger-attachments
|
||||||
|
BAO_ROLE: api
|
||||||
|
BAO_ADDR: https://bao:8200
|
||||||
|
depends_on: *id001
|
||||||
|
restart: unless-stopped
|
||||||
|
stop_grace_period: 12s
|
||||||
|
healthcheck: *id002
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
volumes:
|
||||||
|
- ./secrets/ca.crt:/tls/ca.crt:ro
|
||||||
|
- ./secrets/api:/identity:ro
|
||||||
|
entrypoint:
|
||||||
|
- python
|
||||||
|
- scripts/bao_exec.py
|
||||||
|
command:
|
||||||
|
- uvicorn
|
||||||
|
- main:app
|
||||||
|
- --host
|
||||||
|
- 127.0.0.1
|
||||||
|
- --port
|
||||||
|
- '8080'
|
||||||
|
otel-collector:
|
||||||
|
image: otel/opentelemetry-collector-contrib:0.120.0
|
||||||
|
command:
|
||||||
|
- --config=/etc/otelcol-contrib/config.yaml
|
||||||
|
volumes:
|
||||||
|
- ./infra/otel/collector.yaml:/etc/otelcol-contrib/config.yaml:ro
|
||||||
|
- ./secrets/otel-collector:/tls/server:ro
|
||||||
|
- ./secrets/ca.crt:/tls/ca.crt:ro
|
||||||
|
depends_on:
|
||||||
|
- prometheus
|
||||||
|
- loki
|
||||||
|
- tempo
|
||||||
|
restart: unless-stopped
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
prometheus:
|
||||||
|
image: prom/prometheus:v3.2.1
|
||||||
|
command:
|
||||||
|
- --config.file=/etc/prometheus/prometheus.yml
|
||||||
|
- --storage.tsdb.path=/prometheus
|
||||||
|
- --web.enable-lifecycle
|
||||||
|
- --web.config.file=/etc/prometheus/web.yml
|
||||||
|
volumes:
|
||||||
|
- ./secrets/prometheus:/tls/server:ro
|
||||||
|
- ./secrets/ca.crt:/tls/ca.crt:ro
|
||||||
|
- ./infra/prometheus/prometheus.yml:/etc/prometheus/prometheus.yml:ro
|
||||||
|
- ./infra/prometheus/alerts.yml:/etc/prometheus/alerts.yml:ro
|
||||||
|
- ./infra/prometheus/web.yml:/etc/prometheus/web.yml:ro
|
||||||
|
- prometheus_data:/prometheus
|
||||||
|
restart: unless-stopped
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
loki:
|
||||||
|
image: grafana/loki:3.4.2
|
||||||
|
command:
|
||||||
|
- -config.file=/etc/loki/local-config.yaml
|
||||||
|
volumes:
|
||||||
|
- ./secrets/loki:/tls/server:ro
|
||||||
|
- ./secrets/ca.crt:/tls/ca.crt:ro
|
||||||
|
- ./infra/loki/config.yaml:/etc/loki/local-config.yaml:ro
|
||||||
|
- loki_data:/loki
|
||||||
|
restart: unless-stopped
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
tempo:
|
||||||
|
image: grafana/tempo:2.7.2
|
||||||
|
command:
|
||||||
|
- -config.file=/etc/tempo/config.yaml
|
||||||
|
volumes:
|
||||||
|
- ./secrets/tempo:/tls/server:ro
|
||||||
|
- ./secrets/ca.crt:/tls/ca.crt:ro
|
||||||
|
- ./infra/tempo/config.yaml:/etc/tempo/config.yaml:ro
|
||||||
|
- tempo_data:/var/tempo
|
||||||
|
restart: unless-stopped
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
grafana:
|
||||||
|
image: grafana/grafana:11.5.2
|
||||||
|
environment:
|
||||||
|
GF_SECURITY_ADMIN_USER: ${GRAFANA_USER:-admin}
|
||||||
|
GF_SECURITY_ADMIN_PASSWORD: ${GRAFANA_PASSWORD:?run bootstrap}
|
||||||
|
GF_USERS_ALLOW_SIGN_UP: 'false'
|
||||||
|
volumes:
|
||||||
|
- grafana_data:/var/lib/grafana
|
||||||
|
- ./infra/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||||
|
- ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||||
|
depends_on:
|
||||||
|
- prometheus
|
||||||
|
- loki
|
||||||
|
- tempo
|
||||||
|
restart: unless-stopped
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
ports:
|
||||||
|
- 127.0.0.1:3007:3000
|
||||||
|
lb:
|
||||||
|
image: nginx:1.27.5-alpine
|
||||||
|
volumes:
|
||||||
|
- ./infra/nginx.conf:/etc/nginx/nginx.conf:ro
|
||||||
|
- ./secrets/ca.crt:/tls/ca.crt:ro
|
||||||
|
- ./secrets/lb:/tls/lb:ro
|
||||||
|
- ./secrets/ingress:/tls/ingress:ro
|
||||||
|
depends_on:
|
||||||
|
api1-tls:
|
||||||
|
condition: service_started
|
||||||
|
api2-tls:
|
||||||
|
condition: service_started
|
||||||
|
restart: unless-stopped
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 768m
|
||||||
|
cpus: 1.0
|
||||||
|
ports:
|
||||||
|
- 8443:8443
|
||||||
|
api1-tls:
|
||||||
|
image: nginx:1.27.5-alpine
|
||||||
|
network_mode: service:api1
|
||||||
|
depends_on:
|
||||||
|
api1:
|
||||||
|
condition: service_healthy
|
||||||
|
volumes:
|
||||||
|
- ./infra/api-tls.conf:/etc/nginx/nginx.conf:ro
|
||||||
|
- ./secrets/ca.crt:/tls/ca.crt:ro
|
||||||
|
- ./secrets/api-server:/tls/server:ro
|
||||||
|
restart: unless-stopped
|
||||||
|
mem_limit: 128m
|
||||||
|
cpus: 0.5
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
api2-tls:
|
||||||
|
image: nginx:1.27.5-alpine
|
||||||
|
network_mode: service:api2
|
||||||
|
depends_on:
|
||||||
|
api2:
|
||||||
|
condition: service_healthy
|
||||||
|
volumes:
|
||||||
|
- ./infra/api-tls.conf:/etc/nginx/nginx.conf:ro
|
||||||
|
- ./secrets/ca.crt:/tls/ca.crt:ro
|
||||||
|
- ./secrets/api-server:/tls/server:ro
|
||||||
|
restart: unless-stopped
|
||||||
|
mem_limit: 128m
|
||||||
|
cpus: 0.5
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
bao:
|
||||||
|
image: openbao/openbao:2.2.0
|
||||||
|
command:
|
||||||
|
- server
|
||||||
|
- -config=/bao/config.hcl
|
||||||
|
volumes:
|
||||||
|
- ./infra/openbao/config.hcl:/bao/config.hcl:ro
|
||||||
|
- ./secrets/bao:/tls:ro
|
||||||
|
- bao_data_v2:/bao/data
|
||||||
|
ports:
|
||||||
|
- 127.0.0.1:8200:8200
|
||||||
|
environment:
|
||||||
|
BAO_DISABLE_MLOCK: 'true'
|
||||||
|
cap_drop:
|
||||||
|
- ALL
|
||||||
|
cap_add:
|
||||||
|
- SETGID
|
||||||
|
- SETUID
|
||||||
|
security_opt:
|
||||||
|
- no-new-privileges:true
|
||||||
|
mem_limit: 256m
|
||||||
|
cpus: 0.5
|
||||||
|
volumes:
|
||||||
|
postgres_data: null
|
||||||
|
s3_data: null
|
||||||
|
broker_data: null
|
||||||
|
prometheus_data: null
|
||||||
|
loki_data: null
|
||||||
|
tempo_data: null
|
||||||
|
grafana_data: null
|
||||||
|
bao_data: null
|
||||||
|
bao_data_v2: null
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
events {}
|
||||||
|
http {
|
||||||
|
server {
|
||||||
|
listen 8443 ssl;
|
||||||
|
ssl_certificate /tls/server/cert.crt;
|
||||||
|
ssl_certificate_key /tls/server/cert.key;
|
||||||
|
ssl_client_certificate /tls/ca.crt;
|
||||||
|
ssl_verify_client on;
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
if ($ssl_client_s_dn != "CN=lab-lb") { return 403; }
|
||||||
|
client_max_body_size 10m;
|
||||||
|
location / { proxy_pass http://127.0.0.1:8080; proxy_set_header Host $host; }
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,21 @@
|
|||||||
|
{
|
||||||
|
"id": null,
|
||||||
|
"uid": "messenger-observability",
|
||||||
|
"title": "Messenger — Observability",
|
||||||
|
"tags": ["lab6", "opentelemetry"],
|
||||||
|
"timezone": "browser",
|
||||||
|
"schemaVersion": 39,
|
||||||
|
"version": 1,
|
||||||
|
"refresh": "5s",
|
||||||
|
"time": {"from": "now-1h", "to": "now"},
|
||||||
|
"panels": [
|
||||||
|
{"id": 1, "type": "timeseries", "title": "API requests / sec", "gridPos": {"h": 8, "w": 12, "x": 0, "y": 0}, "datasource": {"type": "prometheus", "uid": "prometheus"}, "targets": [{"expr": "sum by (http_route, http_status_class) (rate(otel_messenger_http_requests_total[1m]))", "legendFormat": "{{http_route}} {{http_status_class}}", "refId": "A"}]},
|
||||||
|
{"id": 2, "type": "timeseries", "title": "API duration p95 (seconds)", "gridPos": {"h": 8, "w": 12, "x": 12, "y": 0}, "datasource": {"type": "prometheus", "uid": "prometheus"}, "targets": [{"expr": "histogram_quantile(0.95, sum by (le) (rate(otel_messenger_http_request_duration_seconds_bucket[5m])))", "legendFormat": "p95", "refId": "A"}]},
|
||||||
|
{"id": 3, "type": "timeseries", "title": "Worker jobs / sec", "gridPos": {"h": 8, "w": 12, "x": 0, "y": 8}, "datasource": {"type": "prometheus", "uid": "prometheus"}, "targets": [{"expr": "sum by (outcome) (rate(otel_messenger_jobs_processed_total[1m]))", "legendFormat": "{{outcome}}", "refId": "A"}]},
|
||||||
|
{"id": 4, "type": "timeseries", "title": "Worker job duration p95 (seconds)", "gridPos": {"h": 8, "w": 12, "x": 12, "y": 8}, "datasource": {"type": "prometheus", "uid": "prometheus"}, "targets": [{"expr": "histogram_quantile(0.95, sum by (le) (rate(otel_messenger_job_processing_duration_seconds_bucket[5m])))", "legendFormat": "p95", "refId": "A"}]},
|
||||||
|
{"id": 5, "type": "logs", "title": "API + worker structured logs", "gridPos": {"h": 10, "w": 24, "x": 0, "y": 16}, "datasource": {"type": "loki", "uid": "loki"}, "targets": [{"expr": "{service_name=~\"messenger-api|messenger-worker\"}", "refId": "A"}]}
|
||||||
|
],
|
||||||
|
"annotations": {"list": []},
|
||||||
|
"templating": {"list": []},
|
||||||
|
"links": []
|
||||||
|
}
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
providers:
|
||||||
|
- name: Messenger
|
||||||
|
orgId: 1
|
||||||
|
folder: Laboratory 6
|
||||||
|
type: file
|
||||||
|
disableDeletion: false
|
||||||
|
editable: true
|
||||||
|
options:
|
||||||
|
path: /var/lib/grafana/dashboards
|
||||||
@@ -0,0 +1,117 @@
|
|||||||
|
apiVersion: 1
|
||||||
|
datasources:
|
||||||
|
- name: Prometheus
|
||||||
|
uid: prometheus
|
||||||
|
type: prometheus
|
||||||
|
access: proxy
|
||||||
|
url: https://prometheus:9090
|
||||||
|
isDefault: true
|
||||||
|
editable: false
|
||||||
|
jsonData:
|
||||||
|
tlsAuthWithCACert: true
|
||||||
|
tlsSkipVerify: false
|
||||||
|
secureJsonData:
|
||||||
|
tlsCACert: |
|
||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIEFTCCAn2gAwIBAgIUPJlpBqANeNOFtPnZUUVN8ivYWuIwDQYJKoZIhvcNAQEL
|
||||||
|
BQAwEjEQMA4GA1UEAwwHTGFiNyBDQTAeFw0yNjEyMDMxMTE4MDVaFw0yNzEyMDMx
|
||||||
|
MTE4MDVaMBIxEDAOBgNVBAMMB0xhYjcgQ0EwggGiMA0GCSqGSIb3DQEBAQUAA4IB
|
||||||
|
jwAwggGKAoIBgQDGav9hYFR8D74JhsjiyF0LC5FSKmx82ADoey7gVFDgX/woyWHH
|
||||||
|
jfTk2Vq21hh6sNINiNhUSh7onTa6PKrGFn+2tzG7HySBy1jPM1xGznWmeBMShieW
|
||||||
|
NagOboEWJRnrbcn2Tb1aU2HrYT9enka12QQd5/lpNKb2ssxZ4EOsLrQ35U1rErO7
|
||||||
|
I/O4DejMnUfoB0+IZHetZhPoUiqhlZCX1u07mKg9zqNgI/0zPMbnG/KSILNpy9wM
|
||||||
|
WlxpyVA5whTW0O14NfEo+EPCdkR2tw1b1Lw8xFJVFcMwHTqVdCSbr8EduRgohZPu
|
||||||
|
0pgSdJrXVd6dQUi1tPpKTP7jUVgH/huc/RFR3WB4QRrWJRdvFnYAdJ0Zcx2aPE5t
|
||||||
|
eXznVGjU09KXHSJGnrUpGcHq4TjPt+W1hF8hRLG1kyA5tbuG8XpEcLQjB4+8Sw1t
|
||||||
|
Mk9m5h7mwCkgaVexy6gzEcF9ig5m4U3+D97ADrwkqOh4uQTce6LibQ5AbC71O69A
|
||||||
|
E8yAY7nTh8m8ZbUCAwEAAaNjMGEwHwYDVR0jBBgwFoAUM2aF6O8X9b7krqrjFBXK
|
||||||
|
MQTT9nAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE
|
||||||
|
FDNmhejvF/W+5K6q4xQVyjEE0/ZwMA0GCSqGSIb3DQEBCwUAA4IBgQDCMvEfZ9id
|
||||||
|
NW/17npiGika7nwPqethM4l20fwJ/9qHKKwF3WX62JbCU6/63SimxoNTFv4ubrCC
|
||||||
|
5+SGg07u03xEPRE0Z6VrscsUPDbE9mTFmc9TBSqZeQzDMH2aJ4fv1Qe6GhxCcO0T
|
||||||
|
BVr2ETazNJpPwNrMZHdQkmoBC4xtxvKWc0NvDbPCwHvZ+WhqsZGEYTV5qgOkL836
|
||||||
|
GiJ47xlSCg1sn6hIGWe8lToBJKXJkkpshbtOWV/Nn9Tt3gTZ2BZswQVan8+d3YBB
|
||||||
|
eEmh9V7O5/NxdEvmJSZpFhL3P0dj5G1XI4VqBF6oSF0Puf/mB8XYLGlJ34jRij/r
|
||||||
|
95heIJh1Qsc4l5tnwU/KDzhTTn0T2tvrxImxvgUMaFVsahk5H65/Iav6anJVnI5Y
|
||||||
|
xo+BSe9g2RQUnrKMpDwsS5NnLXkg/UOtOoMLyG5rqhxTzS+/50e2fgVugbAcfhEd
|
||||||
|
RqVhoNcaEfv6e4Vo4i6ANQ8zWGpueWqRgXJo4Pr32+v4fhOf85vp9WA=
|
||||||
|
-----END CERTIFICATE-----
|
||||||
|
- name: Loki
|
||||||
|
uid: loki
|
||||||
|
type: loki
|
||||||
|
access: proxy
|
||||||
|
url: https://loki:3100
|
||||||
|
jsonData:
|
||||||
|
tlsAuthWithCACert: true
|
||||||
|
tlsSkipVerify: false
|
||||||
|
maxLines: 1000
|
||||||
|
editable: false
|
||||||
|
secureJsonData:
|
||||||
|
tlsCACert: |
|
||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIEFTCCAn2gAwIBAgIUPJlpBqANeNOFtPnZUUVN8ivYWuIwDQYJKoZIhvcNAQEL
|
||||||
|
BQAwEjEQMA4GA1UEAwwHTGFiNyBDQTAeFw0yNjEyMDMxMTE4MDVaFw0yNzEyMDMx
|
||||||
|
MTE4MDVaMBIxEDAOBgNVBAMMB0xhYjcgQ0EwggGiMA0GCSqGSIb3DQEBAQUAA4IB
|
||||||
|
jwAwggGKAoIBgQDGav9hYFR8D74JhsjiyF0LC5FSKmx82ADoey7gVFDgX/woyWHH
|
||||||
|
jfTk2Vq21hh6sNINiNhUSh7onTa6PKrGFn+2tzG7HySBy1jPM1xGznWmeBMShieW
|
||||||
|
NagOboEWJRnrbcn2Tb1aU2HrYT9enka12QQd5/lpNKb2ssxZ4EOsLrQ35U1rErO7
|
||||||
|
I/O4DejMnUfoB0+IZHetZhPoUiqhlZCX1u07mKg9zqNgI/0zPMbnG/KSILNpy9wM
|
||||||
|
WlxpyVA5whTW0O14NfEo+EPCdkR2tw1b1Lw8xFJVFcMwHTqVdCSbr8EduRgohZPu
|
||||||
|
0pgSdJrXVd6dQUi1tPpKTP7jUVgH/huc/RFR3WB4QRrWJRdvFnYAdJ0Zcx2aPE5t
|
||||||
|
eXznVGjU09KXHSJGnrUpGcHq4TjPt+W1hF8hRLG1kyA5tbuG8XpEcLQjB4+8Sw1t
|
||||||
|
Mk9m5h7mwCkgaVexy6gzEcF9ig5m4U3+D97ADrwkqOh4uQTce6LibQ5AbC71O69A
|
||||||
|
E8yAY7nTh8m8ZbUCAwEAAaNjMGEwHwYDVR0jBBgwFoAUM2aF6O8X9b7krqrjFBXK
|
||||||
|
MQTT9nAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE
|
||||||
|
FDNmhejvF/W+5K6q4xQVyjEE0/ZwMA0GCSqGSIb3DQEBCwUAA4IBgQDCMvEfZ9id
|
||||||
|
NW/17npiGika7nwPqethM4l20fwJ/9qHKKwF3WX62JbCU6/63SimxoNTFv4ubrCC
|
||||||
|
5+SGg07u03xEPRE0Z6VrscsUPDbE9mTFmc9TBSqZeQzDMH2aJ4fv1Qe6GhxCcO0T
|
||||||
|
BVr2ETazNJpPwNrMZHdQkmoBC4xtxvKWc0NvDbPCwHvZ+WhqsZGEYTV5qgOkL836
|
||||||
|
GiJ47xlSCg1sn6hIGWe8lToBJKXJkkpshbtOWV/Nn9Tt3gTZ2BZswQVan8+d3YBB
|
||||||
|
eEmh9V7O5/NxdEvmJSZpFhL3P0dj5G1XI4VqBF6oSF0Puf/mB8XYLGlJ34jRij/r
|
||||||
|
95heIJh1Qsc4l5tnwU/KDzhTTn0T2tvrxImxvgUMaFVsahk5H65/Iav6anJVnI5Y
|
||||||
|
xo+BSe9g2RQUnrKMpDwsS5NnLXkg/UOtOoMLyG5rqhxTzS+/50e2fgVugbAcfhEd
|
||||||
|
RqVhoNcaEfv6e4Vo4i6ANQ8zWGpueWqRgXJo4Pr32+v4fhOf85vp9WA=
|
||||||
|
-----END CERTIFICATE-----
|
||||||
|
- name: Tempo
|
||||||
|
uid: tempo
|
||||||
|
type: tempo
|
||||||
|
access: proxy
|
||||||
|
url: https://tempo:3200
|
||||||
|
jsonData:
|
||||||
|
tlsAuthWithCACert: true
|
||||||
|
tlsSkipVerify: false
|
||||||
|
tracesToLogsV2:
|
||||||
|
datasourceUid: loki
|
||||||
|
spanStartTimeShift: "-1h"
|
||||||
|
spanEndTimeShift: "1h"
|
||||||
|
filterByTraceID: true
|
||||||
|
filterBySpanID: false
|
||||||
|
nodeGraph:
|
||||||
|
enabled: true
|
||||||
|
editable: false
|
||||||
|
secureJsonData:
|
||||||
|
tlsCACert: |
|
||||||
|
-----BEGIN CERTIFICATE-----
|
||||||
|
MIIEFTCCAn2gAwIBAgIUPJlpBqANeNOFtPnZUUVN8ivYWuIwDQYJKoZIhvcNAQEL
|
||||||
|
BQAwEjEQMA4GA1UEAwwHTGFiNyBDQTAeFw0yNjEyMDMxMTE4MDVaFw0yNzEyMDMx
|
||||||
|
MTE4MDVaMBIxEDAOBgNVBAMMB0xhYjcgQ0EwggGiMA0GCSqGSIb3DQEBAQUAA4IB
|
||||||
|
jwAwggGKAoIBgQDGav9hYFR8D74JhsjiyF0LC5FSKmx82ADoey7gVFDgX/woyWHH
|
||||||
|
jfTk2Vq21hh6sNINiNhUSh7onTa6PKrGFn+2tzG7HySBy1jPM1xGznWmeBMShieW
|
||||||
|
NagOboEWJRnrbcn2Tb1aU2HrYT9enka12QQd5/lpNKb2ssxZ4EOsLrQ35U1rErO7
|
||||||
|
I/O4DejMnUfoB0+IZHetZhPoUiqhlZCX1u07mKg9zqNgI/0zPMbnG/KSILNpy9wM
|
||||||
|
WlxpyVA5whTW0O14NfEo+EPCdkR2tw1b1Lw8xFJVFcMwHTqVdCSbr8EduRgohZPu
|
||||||
|
0pgSdJrXVd6dQUi1tPpKTP7jUVgH/huc/RFR3WB4QRrWJRdvFnYAdJ0Zcx2aPE5t
|
||||||
|
eXznVGjU09KXHSJGnrUpGcHq4TjPt+W1hF8hRLG1kyA5tbuG8XpEcLQjB4+8Sw1t
|
||||||
|
Mk9m5h7mwCkgaVexy6gzEcF9ig5m4U3+D97ADrwkqOh4uQTce6LibQ5AbC71O69A
|
||||||
|
E8yAY7nTh8m8ZbUCAwEAAaNjMGEwHwYDVR0jBBgwFoAUM2aF6O8X9b7krqrjFBXK
|
||||||
|
MQTT9nAwDwYDVR0TAQH/BAUwAwEB/zAOBgNVHQ8BAf8EBAMCAQYwHQYDVR0OBBYE
|
||||||
|
FDNmhejvF/W+5K6q4xQVyjEE0/ZwMA0GCSqGSIb3DQEBCwUAA4IBgQDCMvEfZ9id
|
||||||
|
NW/17npiGika7nwPqethM4l20fwJ/9qHKKwF3WX62JbCU6/63SimxoNTFv4ubrCC
|
||||||
|
5+SGg07u03xEPRE0Z6VrscsUPDbE9mTFmc9TBSqZeQzDMH2aJ4fv1Qe6GhxCcO0T
|
||||||
|
BVr2ETazNJpPwNrMZHdQkmoBC4xtxvKWc0NvDbPCwHvZ+WhqsZGEYTV5qgOkL836
|
||||||
|
GiJ47xlSCg1sn6hIGWe8lToBJKXJkkpshbtOWV/Nn9Tt3gTZ2BZswQVan8+d3YBB
|
||||||
|
eEmh9V7O5/NxdEvmJSZpFhL3P0dj5G1XI4VqBF6oSF0Puf/mB8XYLGlJ34jRij/r
|
||||||
|
95heIJh1Qsc4l5tnwU/KDzhTTn0T2tvrxImxvgUMaFVsahk5H65/Iav6anJVnI5Y
|
||||||
|
xo+BSe9g2RQUnrKMpDwsS5NnLXkg/UOtOoMLyG5rqhxTzS+/50e2fgVugbAcfhEd
|
||||||
|
RqVhoNcaEfv6e4Vo4i6ANQ8zWGpueWqRgXJo4Pr32+v4fhOf85vp9WA=
|
||||||
|
-----END CERTIFICATE-----
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
auth_enabled: false
|
||||||
|
server:
|
||||||
|
http_listen_port: 3100
|
||||||
|
http_tls_config:
|
||||||
|
cert_file: /tls/server/cert.crt
|
||||||
|
key_file: /tls/server/cert.key
|
||||||
|
common:
|
||||||
|
path_prefix: /loki
|
||||||
|
replication_factor: 1
|
||||||
|
ring:
|
||||||
|
kvstore:
|
||||||
|
store: inmemory
|
||||||
|
storage:
|
||||||
|
filesystem:
|
||||||
|
chunks_directory: /loki/chunks
|
||||||
|
rules_directory: /loki/rules
|
||||||
|
schema_config:
|
||||||
|
configs:
|
||||||
|
- from: 2024-01-01
|
||||||
|
store: tsdb
|
||||||
|
object_store: filesystem
|
||||||
|
schema: v13
|
||||||
|
index:
|
||||||
|
prefix: index_
|
||||||
|
period: 24h
|
||||||
|
limits_config:
|
||||||
|
allow_structured_metadata: true
|
||||||
|
volume_enabled: true
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
events { worker_connections 1024; }
|
||||||
|
http {
|
||||||
|
limit_req_zone $binary_remote_addr zone=login:10m rate=2r/s;
|
||||||
|
map $uri $login_key { default ""; /api/v1/auth/sessions $binary_remote_addr; }
|
||||||
|
limit_req_zone $login_key zone=login_only:10m rate=2r/s;
|
||||||
|
upstream api_backend {
|
||||||
|
server api1:8443 max_fails=1 fail_timeout=2s;
|
||||||
|
server api2:8443 max_fails=1 fail_timeout=2s;
|
||||||
|
}
|
||||||
|
server {
|
||||||
|
listen 8443 ssl;
|
||||||
|
ssl_certificate /tls/ingress/cert.crt;
|
||||||
|
ssl_certificate_key /tls/ingress/cert.key;
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
client_max_body_size 10m;
|
||||||
|
error_page 429 = @limited;
|
||||||
|
location @limited { add_header Retry-After 1 always; default_type application/json; return 429 '{"error":{"code":"rate_limited","message":"Too many requests","request_id":"$request_id"}}'; }
|
||||||
|
location / {
|
||||||
|
limit_req zone=login_only burst=10 nodelay;
|
||||||
|
limit_req_status 429;
|
||||||
|
proxy_pass https://api_backend;
|
||||||
|
proxy_ssl_certificate /tls/lb/cert.crt;
|
||||||
|
proxy_ssl_certificate_key /tls/lb/cert.key;
|
||||||
|
proxy_ssl_trusted_certificate /tls/ca.crt;
|
||||||
|
proxy_ssl_verify on;
|
||||||
|
proxy_ssl_server_name on;
|
||||||
|
proxy_ssl_name api.internal;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_set_header Host $host;
|
||||||
|
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
|
||||||
|
proxy_connect_timeout 1s;
|
||||||
|
proxy_read_timeout 15s;
|
||||||
|
proxy_next_upstream error timeout http_502 http_503 http_504;
|
||||||
|
proxy_next_upstream_tries 2;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
path "secret/data/api" { capabilities = ["read"] }
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
ui = true
|
||||||
|
disable_mlock = true
|
||||||
|
storage "file" { path = "/bao/data" }
|
||||||
|
listener "tcp" {
|
||||||
|
address = "0.0.0.0:8200"
|
||||||
|
tls_cert_file = "/tls/cert.crt"
|
||||||
|
tls_key_file = "/tls/cert.key"
|
||||||
|
}
|
||||||
|
api_addr = "https://bao:8200"
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
path "secret/data/operator" { capabilities = ["read"] }
|
||||||
@@ -0,0 +1 @@
|
|||||||
|
path "secret/data/worker" { capabilities = ["read"] }
|
||||||
@@ -0,0 +1,48 @@
|
|||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
grpc:
|
||||||
|
endpoint: 0.0.0.0:4317
|
||||||
|
tls:
|
||||||
|
cert_file: /tls/server/cert.crt
|
||||||
|
key_file: /tls/server/cert.key
|
||||||
|
processors:
|
||||||
|
memory_limiter:
|
||||||
|
check_interval: 1s
|
||||||
|
limit_mib: 256
|
||||||
|
spike_limit_mib: 64
|
||||||
|
batch:
|
||||||
|
timeout: 5s
|
||||||
|
send_batch_size: 1024
|
||||||
|
exporters:
|
||||||
|
prometheus:
|
||||||
|
endpoint: 0.0.0.0:9464
|
||||||
|
tls:
|
||||||
|
cert_file: /tls/server/cert.crt
|
||||||
|
key_file: /tls/server/cert.key
|
||||||
|
namespace: otel
|
||||||
|
resource_to_telemetry_conversion:
|
||||||
|
enabled: true
|
||||||
|
otlp/tempo:
|
||||||
|
endpoint: tempo:4317
|
||||||
|
tls:
|
||||||
|
insecure: false
|
||||||
|
ca_file: /tls/ca.crt
|
||||||
|
otlphttp/loki:
|
||||||
|
endpoint: https://loki:3100/otlp
|
||||||
|
tls:
|
||||||
|
ca_file: /tls/ca.crt
|
||||||
|
service:
|
||||||
|
pipelines:
|
||||||
|
traces:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [otlp/tempo]
|
||||||
|
metrics:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [prometheus]
|
||||||
|
logs:
|
||||||
|
receivers: [otlp]
|
||||||
|
processors: [memory_limiter, batch]
|
||||||
|
exporters: [otlphttp/loki]
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
local all all trust
|
||||||
|
hostssl all all all scram-sha-256
|
||||||
@@ -0,0 +1,31 @@
|
|||||||
|
groups:
|
||||||
|
- name: messenger-observability
|
||||||
|
rules:
|
||||||
|
- alert: ApiHigh5xxRatio
|
||||||
|
expr: sum(rate(otel_messenger_http_requests_total{http_status_class="5xx"}[5m])) / clamp_min(sum(rate(otel_messenger_http_requests_total[5m])), 0.001) > 0.05
|
||||||
|
for: 2m
|
||||||
|
labels: {severity: warning}
|
||||||
|
annotations:
|
||||||
|
summary: "Доля HTTP 5xx выше 5%"
|
||||||
|
description: "Проверьте API traces и логи по route/request_id. Runbook: REPORT.md#инциденты."
|
||||||
|
- alert: ApiHighP95Latency
|
||||||
|
expr: histogram_quantile(0.95, sum by (le) (rate(otel_messenger_http_request_duration_seconds_bucket[5m]))) > 1
|
||||||
|
for: 3m
|
||||||
|
labels: {severity: warning}
|
||||||
|
annotations:
|
||||||
|
summary: "p95 API выше 1 секунды"
|
||||||
|
description: "Сравните server span с DB/S3 spans и проверьте saturation. Runbook: REPORT.md#инциденты."
|
||||||
|
- alert: WorkerJobFailures
|
||||||
|
expr: sum(rate(otel_messenger_jobs_processed_total{outcome="error"}[5m])) > 0
|
||||||
|
for: 1m
|
||||||
|
labels: {severity: warning}
|
||||||
|
annotations:
|
||||||
|
summary: "Worker фиксирует ошибки обработки"
|
||||||
|
description: "Откройте job.process trace и структурный лог job.failed. Runbook: REPORT.md#инциденты."
|
||||||
|
- alert: TelemetryCollectorUnavailable
|
||||||
|
expr: up{job="otel-collector"} == 0
|
||||||
|
for: 1m
|
||||||
|
labels: {severity: critical}
|
||||||
|
annotations:
|
||||||
|
summary: "Prometheus не видит OTel Collector"
|
||||||
|
description: "Проверьте контейнер Collector и OTLP pipeline. Runbook: REPORT.md#инциденты."
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
global:
|
||||||
|
scrape_interval: 5s
|
||||||
|
evaluation_interval: 5s
|
||||||
|
rule_files: ["/etc/prometheus/alerts.yml"]
|
||||||
|
scrape_configs:
|
||||||
|
- job_name: otel-collector
|
||||||
|
scheme: https
|
||||||
|
tls_config:
|
||||||
|
ca_file: /tls/ca.crt
|
||||||
|
static_configs:
|
||||||
|
- targets: ["otel-collector:9464"]
|
||||||
@@ -0,0 +1,3 @@
|
|||||||
|
tls_server_config:
|
||||||
|
cert_file: /tls/server/cert.crt
|
||||||
|
key_file: /tls/server/cert.key
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
listeners.tcp = none
|
||||||
|
listeners.ssl.default = 5671
|
||||||
|
|
||||||
|
ssl_options.cacertfile = /tls/ca.crt
|
||||||
|
ssl_options.certfile = /tls/server/cert.crt
|
||||||
|
ssl_options.keyfile = /tls/server/cert.key
|
||||||
|
|
||||||
|
ssl_options.verify = verify_none
|
||||||
|
ssl_options.fail_if_no_peer_cert = false
|
||||||
|
|
||||||
|
ssl_options.versions.1 = tlsv1.3
|
||||||
|
ssl_options.versions.2 = tlsv1.2
|
||||||
@@ -0,0 +1,16 @@
|
|||||||
|
server {
|
||||||
|
listen 8443 ssl;
|
||||||
|
ssl_certificate /tls/server/cert.crt;
|
||||||
|
ssl_certificate_key /tls/server/cert.key;
|
||||||
|
ssl_protocols TLSv1.2 TLSv1.3;
|
||||||
|
|
||||||
|
client_max_body_size 20m;
|
||||||
|
|
||||||
|
location / {
|
||||||
|
proxy_pass http://127.0.0.1:8333;
|
||||||
|
proxy_set_header Host $http_host;
|
||||||
|
proxy_http_version 1.1;
|
||||||
|
proxy_request_buffering off;
|
||||||
|
proxy_buffering off;
|
||||||
|
}
|
||||||
|
}
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
server:
|
||||||
|
http_listen_port: 3200
|
||||||
|
http_tls_config:
|
||||||
|
cert_file: /tls/server/cert.crt
|
||||||
|
key_file: /tls/server/cert.key
|
||||||
|
distributor:
|
||||||
|
receivers:
|
||||||
|
otlp:
|
||||||
|
protocols:
|
||||||
|
grpc:
|
||||||
|
endpoint: 0.0.0.0:4317
|
||||||
|
tls:
|
||||||
|
cert_file: /tls/server/cert.crt
|
||||||
|
key_file: /tls/server/cert.key
|
||||||
|
ingester:
|
||||||
|
max_block_duration: 5m
|
||||||
|
trace_idle_period: 10s
|
||||||
|
compactor:
|
||||||
|
compaction:
|
||||||
|
block_retention: 48h
|
||||||
|
storage:
|
||||||
|
trace:
|
||||||
|
backend: local
|
||||||
|
wal:
|
||||||
|
path: /var/tempo/wal
|
||||||
|
local:
|
||||||
|
path: /var/tempo/blocks
|
||||||
@@ -0,0 +1,402 @@
|
|||||||
|
import base64
|
||||||
|
import hashlib
|
||||||
|
import hmac
|
||||||
|
import json
|
||||||
|
import os
|
||||||
|
import re
|
||||||
|
import secrets
|
||||||
|
import uuid
|
||||||
|
from datetime import datetime, timezone, timedelta
|
||||||
|
from contextlib import contextmanager
|
||||||
|
|
||||||
|
import psycopg
|
||||||
|
from psycopg.rows import dict_row
|
||||||
|
from fastapi import FastAPI, Request
|
||||||
|
from fastapi.exceptions import RequestValidationError
|
||||||
|
from fastapi.responses import JSONResponse, Response
|
||||||
|
from PIL import Image, UnidentifiedImageError
|
||||||
|
import io
|
||||||
|
import boto3
|
||||||
|
from botocore.config import Config
|
||||||
|
from botocore.exceptions import BotoCoreError, ClientError
|
||||||
|
from pydantic import BaseModel, ConfigDict, Field, field_validator
|
||||||
|
from opentelemetry import trace
|
||||||
|
from telemetry import http_requests, http_duration, event, propagator
|
||||||
|
import time
|
||||||
|
|
||||||
|
DATABASE_URL = os.environ.get('DATABASE_URL', 'postgresql://messenger:messenger@localhost:5432/messenger')
|
||||||
|
INSTANCE_ID = os.environ.get('INSTANCE_ID', 'api-local')
|
||||||
|
app = FastAPI(title='Messenger S3', version='1.4.0')
|
||||||
|
S3_BUCKET=os.environ.get('S3_BUCKET','messenger-attachments')
|
||||||
|
def s3():
|
||||||
|
return boto3.client(
|
||||||
|
's3',
|
||||||
|
endpoint_url=os.environ['S3_ENDPOINT'],
|
||||||
|
region_name='us-east-1',
|
||||||
|
aws_access_key_id=os.environ.get('S3_ACCESS_KEY_ID'),
|
||||||
|
aws_secret_access_key=os.environ.get('S3_SECRET_ACCESS_KEY'),
|
||||||
|
verify='/tls/ca.crt',
|
||||||
|
config=Config(
|
||||||
|
request_checksum_calculation='when_required',
|
||||||
|
response_checksum_validation='when_required'
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
def utc(value):
|
||||||
|
return value.astimezone(timezone.utc).isoformat(timespec='milliseconds').replace('+00:00','Z')
|
||||||
|
|
||||||
|
def db():
|
||||||
|
return psycopg.connect(DATABASE_URL, row_factory=dict_row)
|
||||||
|
|
||||||
|
@contextmanager
|
||||||
|
def transaction():
|
||||||
|
with db() as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
yield conn
|
||||||
|
|
||||||
|
def public_user(row):
|
||||||
|
return {k:(utc(row[k]) if k=='created_at' else str(row[k]) if k=='id' else row[k]) for k in ('id','username','display_name','created_at')}
|
||||||
|
|
||||||
|
def public_chat(conn, row):
|
||||||
|
members=conn.execute('SELECT user_id FROM chat_members WHERE chat_id=%s ORDER BY user_id',(row['id'],)).fetchall()
|
||||||
|
return {'id':str(row['id']),'title':row['title'],'member_ids':[str(x['user_id']) for x in members],'created_at':utc(row['created_at'])}
|
||||||
|
|
||||||
|
def public_message(row):
|
||||||
|
result={k:(utc(row[k]) if k=='created_at' else str(row[k]) if k in ('id','chat_id','sender_id') else row[k]) for k in ('id','chat_id','sender_id','text','created_at')}
|
||||||
|
result['attachment_ids']=[str(v) for v in row.get('attachment_ids',[])]
|
||||||
|
return result
|
||||||
|
|
||||||
|
def public_attachment(row):
|
||||||
|
result={k:(utc(row[k]) if k in ('created_at','updated_at') else str(row[k]) if k in ('id','chat_id','owner_id') else row[k]) for k in ('id','chat_id','owner_id','filename','content_type','size_bytes','sha256','status','created_at','updated_at')}
|
||||||
|
result.update(variants=row['variants'],error_code=row['error_code'])
|
||||||
|
return result
|
||||||
|
|
||||||
|
def err(request,status,code='invalid_request',message='Некорректный запрос',challenge=None):
|
||||||
|
headers={'WWW-Authenticate':challenge} if challenge else {}
|
||||||
|
return JSONResponse(status_code=status,headers=headers,content={'error':{'code':code,'message':message,'request_id':request.state.request_id}})
|
||||||
|
|
||||||
|
@app.middleware('http')
|
||||||
|
async def middleware(request:Request, call_next):
|
||||||
|
request.state.request_id=str(uuid.uuid4())
|
||||||
|
started=time.perf_counter()
|
||||||
|
tracer=trace.get_tracer('messenger.api')
|
||||||
|
with tracer.start_as_current_span('http.server') as span:
|
||||||
|
span.set_attribute('http.request.method', request.method)
|
||||||
|
try:
|
||||||
|
response=await call_next(request)
|
||||||
|
status=response.status_code
|
||||||
|
except Exception as exc:
|
||||||
|
response=err(request,500,'internal_error','Внутренняя ошибка сервера')
|
||||||
|
status=500
|
||||||
|
span.set_attribute("error.type", type(exc).__name__)
|
||||||
|
span.set_status(trace.Status(trace.StatusCode.ERROR))
|
||||||
|
event('http.unhandled_exception', 'ERROR', request_id=request.state.request_id, exception_type=type(exc).__name__)
|
||||||
|
route=getattr(request.scope.get('route'), 'path', None) or '/unmatched'
|
||||||
|
span.set_attribute('http.route', route)
|
||||||
|
span.set_attribute('http.response.status_code', status)
|
||||||
|
if status >= 500:
|
||||||
|
span.set_status(trace.Status(trace.StatusCode.ERROR))
|
||||||
|
duration=time.perf_counter()-started
|
||||||
|
attrs={'http_request_method':request.method,'http_route':route,'http_status_class':f'{status//100}xx'}
|
||||||
|
http_requests.add(1,attrs)
|
||||||
|
http_duration.record(duration,attrs)
|
||||||
|
event('http.request.completed', 'ERROR' if status>=500 else 'INFO', request_id=request.state.request_id, method=request.method, route=route, status_code=status, duration_seconds=round(duration,6))
|
||||||
|
response.headers['X-Request-Id']=request.state.request_id
|
||||||
|
response.headers['X-Instance-Id']=INSTANCE_ID
|
||||||
|
return response
|
||||||
|
|
||||||
|
@app.exception_handler(RequestValidationError)
|
||||||
|
async def validation(request,exc):
|
||||||
|
return err(request,400)
|
||||||
|
|
||||||
|
class Strict(BaseModel):
|
||||||
|
model_config=ConfigDict(extra='forbid')
|
||||||
|
class CreateUser(Strict):
|
||||||
|
username:str=Field(min_length=3,max_length=32,pattern=r'^[a-z0-9_]{3,32}$')
|
||||||
|
display_name:str=Field(min_length=1,max_length=100)
|
||||||
|
password:str=Field(min_length=8,max_length=128)
|
||||||
|
@field_validator('display_name')
|
||||||
|
@classmethod
|
||||||
|
def nonblank(cls,v):
|
||||||
|
if not v.strip(): raise ValueError('blank')
|
||||||
|
return v
|
||||||
|
class CreateChat(Strict):
|
||||||
|
title:str=Field(min_length=1,max_length=100)
|
||||||
|
member_ids:list[uuid.UUID]=Field(min_length=1,max_length=100)
|
||||||
|
@field_validator('title')
|
||||||
|
@classmethod
|
||||||
|
def nonblank(cls,v):
|
||||||
|
if not v.strip(): raise ValueError('blank')
|
||||||
|
return v
|
||||||
|
class CreateMessage(Strict):
|
||||||
|
text:str=Field(max_length=4000)
|
||||||
|
attachment_ids:list[uuid.UUID]=Field(default_factory=list,max_length=10)
|
||||||
|
@field_validator('text')
|
||||||
|
@classmethod
|
||||||
|
def nonblank(cls,v):
|
||||||
|
return v
|
||||||
|
|
||||||
|
from argon2 import PasswordHasher
|
||||||
|
from argon2.exceptions import VerificationError, InvalidHashError
|
||||||
|
ph = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1)
|
||||||
|
def password_hash(password):
|
||||||
|
return ph.hash(password)
|
||||||
|
def verify(password, encoded):
|
||||||
|
try:
|
||||||
|
if encoded.startswith('scrypt$'):
|
||||||
|
_, salt, digest = encoded.split('$')
|
||||||
|
return hmac.compare_digest(hashlib.scrypt(password.encode(), salt=bytes.fromhex(salt), n=16384,r=8,p=1), bytes.fromhex(digest))
|
||||||
|
return ph.verify(encoded,password)
|
||||||
|
except (VerificationError, InvalidHashError, ValueError, TypeError): return False
|
||||||
|
|
||||||
|
def actor(request,conn):
|
||||||
|
header=request.headers.get('authorization','')
|
||||||
|
if not header.startswith('Bearer '): return None
|
||||||
|
token=header[7:]
|
||||||
|
if not token: return None
|
||||||
|
digest=hashlib.sha256(token.encode()).hexdigest()
|
||||||
|
return conn.execute('SELECT u.* FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.token_hash=%s AND s.expires_at>now() AND s.revoked_at IS NULL',(digest,)).fetchone()
|
||||||
|
|
||||||
|
def require(request,conn):
|
||||||
|
user=actor(request,conn)
|
||||||
|
return user, None if user else err(request,401,'unauthorized','Требуется Bearer-сессия','Bearer')
|
||||||
|
|
||||||
|
def parse_uuid(value):
|
||||||
|
try: return uuid.UUID(value)
|
||||||
|
except (ValueError,TypeError): return None
|
||||||
|
|
||||||
|
def encode_cursor(resource,row):
|
||||||
|
payload=json.dumps({'resource':resource,'created_at':row['created_at'].astimezone(timezone.utc).isoformat(timespec='microseconds'),'id':str(row['id'])},separators=(',',':'))
|
||||||
|
return base64.urlsafe_b64encode(payload.encode()).decode().rstrip('=')
|
||||||
|
|
||||||
|
def decode_cursor(cursor,resource):
|
||||||
|
if cursor is None: return None
|
||||||
|
try:
|
||||||
|
d=json.loads(base64.urlsafe_b64decode(cursor+'='*(-len(cursor)%4)))
|
||||||
|
if set(d)!={'resource','created_at','id'} or d['resource']!=resource: return False
|
||||||
|
return (datetime.fromisoformat(d['created_at'].replace('Z','+00:00')),uuid.UUID(d['id']))
|
||||||
|
except Exception: return False
|
||||||
|
|
||||||
|
@app.get('/health/live')
|
||||||
|
def live(): return {'status':'ok'}
|
||||||
|
@app.get('/health/ready')
|
||||||
|
def ready():
|
||||||
|
with db() as conn: conn.execute('SELECT 1')
|
||||||
|
return {'status':'ok'}
|
||||||
|
|
||||||
|
@app.post('/api/v1/users',status_code=201)
|
||||||
|
def register(body:CreateUser,request:Request):
|
||||||
|
with transaction() as conn:
|
||||||
|
if conn.execute('SELECT 1 FROM users WHERE username=%s',(body.username,)).fetchone():
|
||||||
|
return err(request,409,'conflict','Имя пользователя занято')
|
||||||
|
row=conn.execute('INSERT INTO users(username,display_name,password_hash) VALUES (%s,%s,%s) RETURNING *',(body.username,body.display_name,password_hash(body.password))).fetchone()
|
||||||
|
return public_user(row)
|
||||||
|
|
||||||
|
@app.post('/api/v1/auth/sessions',status_code=201)
|
||||||
|
def login(request:Request):
|
||||||
|
auth=request.headers.get('authorization','')
|
||||||
|
try:
|
||||||
|
if not auth.startswith('Basic '): raise ValueError()
|
||||||
|
credentials=base64.b64decode(auth[6:],validate=True).decode('utf-8')
|
||||||
|
username,password=credentials.split(':',1)
|
||||||
|
except (ValueError,UnicodeError): return err(request,401,'unauthorized','Неверные учётные данные','Basic')
|
||||||
|
with transaction() as conn:
|
||||||
|
user=conn.execute('SELECT * FROM users WHERE username=%s',(username,)).fetchone()
|
||||||
|
if not user or not verify(password,user['password_hash']): return err(request,401,'unauthorized','Неверные учётные данные','Basic')
|
||||||
|
if ph.check_needs_rehash(user['password_hash']) if user['password_hash'].startswith('$argon2') else True:
|
||||||
|
conn.execute('UPDATE users SET password_hash=%s WHERE id=%s',(password_hash(password),user['id']))
|
||||||
|
token=secrets.token_urlsafe(48)
|
||||||
|
expires=datetime.now(timezone.utc)+timedelta(seconds=int(os.getenv("SESSION_TTL_SECONDS","3600")))
|
||||||
|
conn.execute('INSERT INTO sessions(user_id,token_hash,expires_at) VALUES (%s,%s,%s)',(user['id'],hashlib.sha256(token.encode()).hexdigest(),expires))
|
||||||
|
return {'token':token,'token_type':'Bearer','expires_at':utc(expires),'user':public_user(user)}
|
||||||
|
|
||||||
|
@app.delete('/api/v1/auth/sessions/current',status_code=204)
|
||||||
|
def logout(request:Request):
|
||||||
|
with transaction() as conn:
|
||||||
|
user,e=require(request,conn)
|
||||||
|
if e:return e
|
||||||
|
digest=hashlib.sha256(request.headers['authorization'][7:].encode()).hexdigest()
|
||||||
|
conn.execute('UPDATE sessions SET revoked_at=now() WHERE token_hash=%s',(digest,))
|
||||||
|
return Response(status_code=204)
|
||||||
|
|
||||||
|
@app.get('/api/v1/users/me')
|
||||||
|
def me(request:Request):
|
||||||
|
with db() as conn:
|
||||||
|
user,e=require(request,conn)
|
||||||
|
return e or public_user(user)
|
||||||
|
|
||||||
|
@app.post('/api/v1/chats',status_code=201)
|
||||||
|
def create_chat(body:CreateChat,request:Request):
|
||||||
|
with transaction() as conn:
|
||||||
|
user,e=require(request,conn)
|
||||||
|
if e:return e
|
||||||
|
members=body.member_ids
|
||||||
|
if len(set(members))!=len(members) or user['id'] not in members:
|
||||||
|
return err(request,400)
|
||||||
|
found=conn.execute('SELECT count(*) AS n FROM users WHERE id=ANY(%s)',(members,)).fetchone()['n']
|
||||||
|
if found!=len(members):return err(request,400)
|
||||||
|
row=conn.execute('INSERT INTO chats(title) VALUES (%s) RETURNING *',(body.title,)).fetchone()
|
||||||
|
for member in members: conn.execute('INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)',(row['id'],member))
|
||||||
|
return public_chat(conn,row)
|
||||||
|
|
||||||
|
def member_chat(conn,chat_id,user_id):
|
||||||
|
return conn.execute('SELECT c.* FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE c.id=%s AND cm.user_id=%s',(chat_id,user_id)).fetchone()
|
||||||
|
|
||||||
|
@app.get('/api/v1/chats')
|
||||||
|
def list_chats(request:Request,limit:int=50,cursor:str|None=None):
|
||||||
|
if not 1<=limit<=100:return err(request,400)
|
||||||
|
with db() as conn:
|
||||||
|
user,e=require(request,conn)
|
||||||
|
if e:return e
|
||||||
|
marker=decode_cursor(cursor,'chats:'+str(user['id']))
|
||||||
|
if marker is False:return err(request,400)
|
||||||
|
query='SELECT c.* FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE cm.user_id=%s'
|
||||||
|
params=[user['id']]
|
||||||
|
if marker:
|
||||||
|
query+=' AND (c.created_at,c.id)>(%s,%s)';params.extend(marker)
|
||||||
|
rows=conn.execute(query+' ORDER BY c.created_at,c.id LIMIT %s',(*params,limit+1)).fetchall()
|
||||||
|
page=rows[:limit]
|
||||||
|
return {'items':[public_chat(conn,r) for r in page],'next_cursor':encode_cursor('chats:'+str(user['id']),page[-1]) if len(rows)>limit else None}
|
||||||
|
|
||||||
|
@app.get('/api/v1/chats/{chat_id}')
|
||||||
|
def get_chat(chat_id:str,request:Request):
|
||||||
|
with db() as conn:
|
||||||
|
user,e=require(request,conn)
|
||||||
|
if e:return e
|
||||||
|
cid=parse_uuid(chat_id)
|
||||||
|
if cid is None:return err(request,400)
|
||||||
|
row=member_chat(conn,cid,user['id'])
|
||||||
|
return public_chat(conn,row) if row else err(request,404,'not_found','Чат не найден')
|
||||||
|
|
||||||
|
@app.post('/api/v1/chats/{chat_id}/messages',status_code=201)
|
||||||
|
def send(chat_id:str,body:CreateMessage,request:Request):
|
||||||
|
key=request.headers.get('Idempotency-Key','')
|
||||||
|
if not re.fullmatch(r'[A-Za-z0-9._:-]{1,128}',key,flags=re.ASCII):
|
||||||
|
return err(request,400,'invalid_request','Требуется корректный Idempotency-Key')
|
||||||
|
if not body.text.strip() and not body.attachment_ids:return err(request,400)
|
||||||
|
if len(set(body.attachment_ids))!=len(body.attachment_ids):return err(request,400)
|
||||||
|
with transaction() as conn:
|
||||||
|
user,e=require(request,conn)
|
||||||
|
if e:return e
|
||||||
|
cid=parse_uuid(chat_id)
|
||||||
|
if cid is None:return err(request,400)
|
||||||
|
if not member_chat(conn,cid,user['id']):return err(request,404,'not_found','Чат не найден')
|
||||||
|
if body.attachment_ids:
|
||||||
|
found=conn.execute('SELECT count(*) AS n FROM attachments WHERE id=ANY(%s) AND chat_id=%s ',(body.attachment_ids,cid)).fetchone()['n']
|
||||||
|
if found!=len(body.attachment_ids):return err(request,404,'not_found','Вложение не найдено')
|
||||||
|
if conn.execute("SELECT 1 FROM attachments WHERE id=ANY(%s) AND status='failed'",(body.attachment_ids,)).fetchone():return err(request,409,'conflict','Обработка не удалась')
|
||||||
|
# UNIQUE constraint serializes concurrent calls on all replicas.
|
||||||
|
# The message and idempotency record commit atomically.
|
||||||
|
fingerprint=hashlib.sha256(json.dumps({'text':body.text,'attachment_ids':[str(x) for x in body.attachment_ids]},sort_keys=True,separators=(',',':'),ensure_ascii=False).encode()).hexdigest()
|
||||||
|
conn.execute("""INSERT INTO message_idempotency(user_id,chat_id,key,fingerprint,message_id)
|
||||||
|
VALUES (%s,%s,%s,%s,NULL) ON CONFLICT DO NOTHING""",(user['id'],cid,key,fingerprint))
|
||||||
|
record=conn.execute("""SELECT fingerprint,message_id FROM message_idempotency
|
||||||
|
WHERE user_id=%s AND chat_id=%s AND key=%s FOR UPDATE""",(user['id'],cid,key)).fetchone()
|
||||||
|
if record['fingerprint']!=fingerprint:
|
||||||
|
return err(request,409,'conflict','Ключ уже использован для другого сообщения')
|
||||||
|
if record['message_id'] is not None:
|
||||||
|
row=conn.execute('SELECT * FROM messages WHERE id=%s',(record['message_id'],)).fetchone()
|
||||||
|
return public_message(row)
|
||||||
|
row=conn.execute('INSERT INTO messages(chat_id,sender_id,text,attachment_ids) VALUES (%s,%s,%s,%s) RETURNING *',(cid,user['id'],body.text,body.attachment_ids)).fetchone()
|
||||||
|
conn.execute("""UPDATE message_idempotency SET message_id=%s
|
||||||
|
WHERE user_id=%s AND chat_id=%s AND key=%s""",(row['id'],user['id'],cid,key))
|
||||||
|
return public_message(row)
|
||||||
|
|
||||||
|
@app.get('/api/v1/chats/{chat_id}/messages')
|
||||||
|
def list_messages(chat_id:str,request:Request,limit:int=50,cursor:str|None=None):
|
||||||
|
if not 1<=limit<=100:return err(request,400)
|
||||||
|
with db() as conn:
|
||||||
|
user,e=require(request,conn)
|
||||||
|
if e:return e
|
||||||
|
cid=parse_uuid(chat_id)
|
||||||
|
if cid is None:return err(request,400)
|
||||||
|
marker=decode_cursor(cursor,'messages:'+str(cid))
|
||||||
|
if marker is False:return err(request,400)
|
||||||
|
if not member_chat(conn,cid,user['id']):return err(request,404,'not_found','Чат не найден')
|
||||||
|
query='SELECT * FROM messages WHERE chat_id=%s';params=[cid]
|
||||||
|
if marker:
|
||||||
|
query+=' AND (created_at,id)>(%s,%s)';params.extend(marker)
|
||||||
|
rows=conn.execute(query+' ORDER BY created_at,id LIMIT %s',(*params,limit+1)).fetchall()
|
||||||
|
page=rows[:limit]
|
||||||
|
return {'items':[public_message(r) for r in page],'next_cursor':encode_cursor('messages:'+str(cid),page[-1]) if len(rows)>limit else None}
|
||||||
|
|
||||||
|
@app.post('/api/v1/chats/{chat_id}/attachments',status_code=202)
|
||||||
|
async def upload(chat_id:str,request:Request,filename:str=''):
|
||||||
|
if not filename or len(filename)>255 or filename in ('.','..') or '/' in filename or '\\' in filename or any(ord(c)<32 or ord(c)==127 for c in filename):
|
||||||
|
return err(request,400)
|
||||||
|
cid=parse_uuid(chat_id)
|
||||||
|
if cid is None:return err(request,400)
|
||||||
|
with db() as conn:
|
||||||
|
user,e=require(request,conn)
|
||||||
|
if e:return e
|
||||||
|
if not member_chat(conn,cid,user['id']):return err(request,404,'not_found','Чат не найден')
|
||||||
|
owner=user['id']
|
||||||
|
declared=request.headers.get('content-type','').split(';')[0].strip().lower()
|
||||||
|
if declared not in ('image/png','image/jpeg'):return err(request,415,'unsupported_media_type','Неверный формат')
|
||||||
|
if request.headers.get('content-length'):
|
||||||
|
try:
|
||||||
|
if int(request.headers['content-length'])>10485760:return err(request,413,'payload_too_large','Файл слишком большой')
|
||||||
|
except ValueError:return err(request,400)
|
||||||
|
data=bytearray()
|
||||||
|
async for chunk in request.stream():
|
||||||
|
if len(data)+len(chunk)>10485760:return err(request,413,'payload_too_large','Файл слишком большой')
|
||||||
|
data.extend(chunk)
|
||||||
|
if not data:return err(request,400)
|
||||||
|
try:
|
||||||
|
Image.MAX_IMAGE_PIXELS=40000000
|
||||||
|
with Image.open(io.BytesIO(data)) as img:
|
||||||
|
actual={'PNG':'image/png','JPEG':'image/jpeg'}.get(img.format)
|
||||||
|
if actual!=declared:return err(request,415,'unsupported_media_type','Неверный формат')
|
||||||
|
if img.width*img.height>40000000:return err(request,413,'payload_too_large','Слишком много пикселей')
|
||||||
|
img.verify()
|
||||||
|
except (Image.DecompressionBombError,Image.DecompressionBombWarning):return err(request,413,'payload_too_large','Слишком много пикселей')
|
||||||
|
except (UnidentifiedImageError,ValueError,OSError):return err(request,415,'unsupported_media_type','Неверный формат')
|
||||||
|
aid=uuid.uuid4()
|
||||||
|
object_key='staging/'+str(cid)+'/'+str(aid)
|
||||||
|
try:
|
||||||
|
s3().put_object(Bucket=S3_BUCKET,Key=object_key,Body=bytes(data),ContentType=actual)
|
||||||
|
except (BotoCoreError,ClientError,Exception):return err(request,503,'storage_unavailable','S3 недоступно')
|
||||||
|
try:
|
||||||
|
with transaction() as conn:
|
||||||
|
row=conn.execute('INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,status,object_key) VALUES (%s,%s,%s,%s,%s,%s,%s,%s,%s) RETURNING *',(aid,cid,owner,filename,actual,len(data),hashlib.sha256(data).hexdigest(),'queued',object_key)).fetchone()
|
||||||
|
carrier={}
|
||||||
|
propagator.inject(carrier)
|
||||||
|
conn.execute('INSERT INTO jobs(id,attachment_id,traceparent,tracestate) VALUES (%s,%s,%s,%s)',(aid,aid,carrier.get('traceparent'),carrier.get('tracestate')))
|
||||||
|
event('attachment.accepted', attachment_id=str(aid), job_type='attachment.process.v1')
|
||||||
|
return public_attachment(row)
|
||||||
|
except Exception:
|
||||||
|
return err(request,503,'storage_unavailable','Не удалось сохранить метаданные')
|
||||||
|
|
||||||
|
def get_attachment_row(request,attachment_id):
|
||||||
|
aid=parse_uuid(attachment_id)
|
||||||
|
if aid is None:return None,err(request,400)
|
||||||
|
with db() as conn:
|
||||||
|
user,e=require(request,conn)
|
||||||
|
if e:return None,e
|
||||||
|
row=conn.execute('SELECT a.* FROM attachments a JOIN chat_members cm ON cm.chat_id=a.chat_id WHERE a.id=%s AND cm.user_id=%s',(aid,user['id'])).fetchone()
|
||||||
|
if row is None:return None,err(request,404,'not_found','Вложение не найдено')
|
||||||
|
return row,None
|
||||||
|
|
||||||
|
@app.get('/api/v1/attachments/{attachment_id}')
|
||||||
|
def attachment_metadata(attachment_id:str,request:Request):
|
||||||
|
row,e=get_attachment_row(request,attachment_id)
|
||||||
|
return e or public_attachment(row)
|
||||||
|
|
||||||
|
@app.get('/api/v1/attachments/{attachment_id}/content')
|
||||||
|
def attachment_content(attachment_id:str,request:Request,variant:str='original'):
|
||||||
|
row,e=get_attachment_row(request,attachment_id)
|
||||||
|
if e:return e
|
||||||
|
if row['status']!='ready':return err(request,409,'conflict','Вложение не готово')
|
||||||
|
if variant!='original':
|
||||||
|
v=next((v for v in row['variants'] if v['name']==variant),None)
|
||||||
|
if v is None:return err(request,404,'not_found','Вариант не найден')
|
||||||
|
row={**row,**v,'object_key':row['object_key']+'/thumbnail'}
|
||||||
|
try:
|
||||||
|
obj=s3().get_object(Bucket=S3_BUCKET,Key=row['object_key'])
|
||||||
|
data=obj['Body'].read(10485761)
|
||||||
|
if len(data)!=row['size_bytes'] or hashlib.sha256(data).hexdigest()!=row['sha256']:
|
||||||
|
return err(request,503,'storage_unavailable','Неверная контрольная сумма')
|
||||||
|
except Exception:return err(request,503,'storage_unavailable','S3 недоступно')
|
||||||
|
return Response(content=data,media_type=row['content_type'],headers={'Cache-Control':'private, no-store','Content-Disposition':'attachment; filename="image"'})
|
||||||
+14
@@ -0,0 +1,14 @@
|
|||||||
|
import os
|
||||||
|
from pathlib import Path
|
||||||
|
import psycopg
|
||||||
|
url=os.environ['DATABASE_URL']
|
||||||
|
with psycopg.connect(url) as conn:
|
||||||
|
with conn.transaction():
|
||||||
|
conn.execute('CREATE TABLE IF NOT EXISTS schema_migrations(version text PRIMARY KEY, applied_at timestamptz NOT NULL DEFAULT now())')
|
||||||
|
conn.execute('SELECT pg_advisory_xact_lock(18202602)')
|
||||||
|
for path in sorted(Path(__file__).parent.joinpath('migrations').glob('*.sql')):
|
||||||
|
if not conn.execute('SELECT 1 FROM schema_migrations WHERE version=%s',(path.name,)).fetchone():
|
||||||
|
conn.execute(path.read_text())
|
||||||
|
conn.execute('INSERT INTO schema_migrations(version) VALUES (%s)',(path.name,))
|
||||||
|
print('Applied',path.name)
|
||||||
|
print('Migrations complete')
|
||||||
@@ -0,0 +1,37 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS users (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||||
|
display_name varchar(100) NOT NULL CHECK (length(trim(display_name)) > 0),
|
||||||
|
password_hash text NOT NULL,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE TABLE IF NOT EXISTS chats (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
title varchar(100) NOT NULL CHECK (length(trim(title)) > 0),
|
||||||
|
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 idx_chat_members_user ON chat_members(user_id,chat_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 varchar(4000) NOT NULL CHECK (length(trim(text)) > 0),
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
FOREIGN KEY (chat_id,sender_id) REFERENCES chat_members(chat_id,user_id)
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_messages_page ON messages(chat_id,created_at,id);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_chats_page ON chats(created_at,id);
|
||||||
|
CREATE TABLE IF NOT EXISTS sessions (
|
||||||
|
id uuid PRIMARY KEY DEFAULT gen_random_uuid(),
|
||||||
|
user_id uuid NOT NULL REFERENCES users(id) ON DELETE CASCADE,
|
||||||
|
token_hash char(64) NOT NULL UNIQUE,
|
||||||
|
expires_at timestamptz NOT NULL,
|
||||||
|
revoked_at timestamptz,
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_sessions_user ON sessions(user_id);
|
||||||
@@ -0,0 +1,9 @@
|
|||||||
|
CREATE TABLE IF NOT EXISTS message_idempotency (
|
||||||
|
user_id uuid NOT NULL REFERENCES users(id),
|
||||||
|
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||||
|
key varchar(128) NOT NULL,
|
||||||
|
fingerprint char(64) NOT NULL,
|
||||||
|
message_id uuid REFERENCES messages(id),
|
||||||
|
created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
PRIMARY KEY (user_id, chat_id, key)
|
||||||
|
);
|
||||||
@@ -0,0 +1,12 @@
|
|||||||
|
ALTER TABLE messages DROP CONSTRAINT IF EXISTS messages_text_check;
|
||||||
|
ALTER TABLE messages ADD COLUMN IF NOT EXISTS attachment_ids uuid[] NOT NULL DEFAULT '{}';
|
||||||
|
ALTER TABLE messages ADD CONSTRAINT messages_content_check CHECK (length(trim(text))>0 OR cardinality(attachment_ids)>0);
|
||||||
|
CREATE TABLE IF NOT EXISTS attachments (
|
||||||
|
id uuid PRIMARY KEY, chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE,
|
||||||
|
owner_id uuid NOT NULL REFERENCES users(id), filename varchar(255) NOT NULL,
|
||||||
|
content_type varchar(20) NOT NULL, size_bytes integer NOT NULL,
|
||||||
|
sha256 char(64) NOT NULL, status varchar(20) NOT NULL DEFAULT 'ready',
|
||||||
|
object_key text NOT NULL UNIQUE, created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
updated_at timestamptz NOT NULL DEFAULT now()
|
||||||
|
);
|
||||||
|
CREATE INDEX IF NOT EXISTS idx_attachments_chat ON attachments(chat_id);
|
||||||
@@ -0,0 +1,7 @@
|
|||||||
|
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS variants jsonb NOT NULL DEFAULT '[]';
|
||||||
|
ALTER TABLE attachments ADD COLUMN IF NOT EXISTS error_code text;
|
||||||
|
CREATE TABLE IF NOT EXISTS jobs (
|
||||||
|
id uuid PRIMARY KEY, attachment_id uuid UNIQUE NOT NULL REFERENCES attachments(id),
|
||||||
|
attempt integer NOT NULL DEFAULT 1, created_at timestamptz NOT NULL DEFAULT now(),
|
||||||
|
published boolean NOT NULL DEFAULT false
|
||||||
|
);
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
ALTER TABLE jobs ADD COLUMN IF NOT EXISTS traceparent text;
|
||||||
|
ALTER TABLE jobs ADD COLUMN IF NOT EXISTS tracestate text;
|
||||||
+28
@@ -0,0 +1,28 @@
|
|||||||
|
import os, json, ssl
|
||||||
|
import pika
|
||||||
|
from opentelemetry import trace
|
||||||
|
from telemetry import propagator
|
||||||
|
QUEUE = 'attachment.jobs'
|
||||||
|
def connect():
|
||||||
|
p = pika.URLParameters(os.environ['BROKER_URL'])
|
||||||
|
ctx = ssl.create_default_context(cafile='/tls/ca.crt')
|
||||||
|
p.ssl_options = pika.SSLOptions(ctx, p.host)
|
||||||
|
p.socket_timeout = 5
|
||||||
|
p.blocked_connection_timeout = 10
|
||||||
|
c = pika.BlockingConnection(p)
|
||||||
|
ch = c.channel()
|
||||||
|
ch.queue_declare(queue=QUEUE, durable=True)
|
||||||
|
ch.confirm_delivery()
|
||||||
|
return c, ch
|
||||||
|
|
||||||
|
def publish(ch, job):
|
||||||
|
payload=dict(schema_version=1,job_id=str(job['id']),type='attachment.process.v1',attachment_id=str(job['attachment_id']),pipeline_version=1,attempt=job['attempt'],created_at=job['created_at'].isoformat())
|
||||||
|
carrier={}
|
||||||
|
if job.get('traceparent'): carrier['traceparent']=job['traceparent']
|
||||||
|
if job.get('tracestate'): carrier['tracestate']=job['tracestate']
|
||||||
|
ctx=propagator.extract(carrier)
|
||||||
|
with trace.get_tracer('messenger.dispatcher').start_as_current_span('queue.publish', context=ctx) as span:
|
||||||
|
headers={}; propagator.inject(headers)
|
||||||
|
span.set_attribute('messaging.system','rabbitmq')
|
||||||
|
span.set_attribute('messaging.destination.name',QUEUE)
|
||||||
|
ch.basic_publish('',QUEUE,json.dumps(payload).encode(),properties=pika.BasicProperties(delivery_mode=2,content_type='application/json',headers=headers),mandatory=True)
|
||||||
@@ -0,0 +1,11 @@
|
|||||||
|
fastapi==0.115.12
|
||||||
|
uvicorn==0.34.2
|
||||||
|
pydantic==2.11.4
|
||||||
|
psycopg[binary]==3.2.6
|
||||||
|
boto3==1.37.38
|
||||||
|
Pillow==11.1.0
|
||||||
|
pika==1.3.2
|
||||||
|
opentelemetry-api==1.31.1
|
||||||
|
opentelemetry-sdk==1.31.1
|
||||||
|
opentelemetry-exporter-otlp==1.31.1
|
||||||
|
argon2-cffi==23.1.0
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import os,sys,ssl,json,time,urllib.request
|
||||||
|
ctx=ssl.create_default_context(cafile='/tls/ca.crt')
|
||||||
|
ctx.load_cert_chain('/identity/cert.crt','/identity/cert.key')
|
||||||
|
role=os.environ['BAO_ROLE']; base=os.environ['BAO_ADDR']
|
||||||
|
def call(path,body=None,token=None):
|
||||||
|
headers={'Content-Type':'application/json'}
|
||||||
|
if token: headers['X-Vault-Token']=token
|
||||||
|
req=urllib.request.Request(base+'/v1/'+path,data=json.dumps(body).encode() if body is not None else None,headers=headers)
|
||||||
|
with urllib.request.urlopen(req,context=ctx,timeout=5) as r: return json.load(r)
|
||||||
|
for i in range(120):
|
||||||
|
try:
|
||||||
|
token=call('auth/cert/login',{'name':role})['auth']['client_token']
|
||||||
|
values=call('secret/data/'+role,token=token)['data']['data']; break
|
||||||
|
except Exception:
|
||||||
|
time.sleep(2)
|
||||||
|
else: sys.exit('OpenBao unavailable or access denied')
|
||||||
|
os.environ.update(values); os.execvp(sys.argv[1],sys.argv[1:])
|
||||||
@@ -0,0 +1,13 @@
|
|||||||
|
import pathlib,subprocess,secrets,json,os
|
||||||
|
root=pathlib.Path('secrets'); root.mkdir(exist_ok=True)
|
||||||
|
def run(*args): subprocess.run(['openssl',*map(str,args)],check=True)
|
||||||
|
if (root/'ca.key').exists(): raise SystemExit('Existing CA; refusing overwrite')
|
||||||
|
run('req','-x509','-newkey','rsa:3072','-nodes','-days','365','-subj','/CN=Lab7 CA','-addext','basicConstraints=critical,CA:TRUE','-addext','keyUsage=critical,keyCertSign,cRLSign','-addext','subjectKeyIdentifier=hash','-keyout',root/'ca.key','-out',root/'ca.crt')
|
||||||
|
for role,cn,san in [('ingress','localhost','DNS:localhost,IP:127.0.0.1'),('lb','lab-lb','DNS:lab-lb'),('api-server','api.internal','DNS:api.internal'),('bao','bao','DNS:bao,DNS:localhost'),('api','api','DNS:api'),('worker','worker','DNS:worker'),('operator','operator','DNS:operator'), ('postgres','postgres','DNS:postgres'), ('broker','broker','DNS:broker'), ('s3','s3','DNS:s3'), ('otel-collector','otel-collector','DNS:otel-collector'), ('prometheus','prometheus','DNS:prometheus'), ('loki','loki','DNS:loki'), ('tempo','tempo','DNS:tempo')]:
|
||||||
|
d=root/role; d.mkdir(); run('req','-new','-newkey','rsa:2048','-nodes','-subj','/CN='+cn,'-keyout',d/'cert.key','-out',d/'cert.csr'); (d/'ext').write_text('subjectAltName='+san+'\nextendedKeyUsage=serverAuth,clientAuth\n'); run('x509','-req','-in',d/'cert.csr','-CA',root/'ca.crt','-CAkey',root/'ca.key','-CAcreateserial','-days','30','-extfile',d/'ext','-out',d/'cert.crt'); os.chmod(d/'cert.key',0o644)
|
||||||
|
values={k:secrets.token_hex(24) for k in ['POSTGRES_PASSWORD','BROKER_PASSWORD','GRAFANA_PASSWORD','S3_SECRET_ACCESS_KEY','DB_API_PASSWORD','DB_WORKER_PASSWORD','BROKER_WORKER_PASSWORD','S3_API_PASSWORD','S3_WORKER_PASSWORD']}; pathlib.Path('.env').write_text(''.join(f'{k}={v}\n' for k,v in values.items())); (root/'s3.json').write_text(json.dumps({'identities':[{'name':'lab','credentials':[{'accessKey':'lab','secretKey':values['S3_SECRET_ACCESS_KEY','DB_API_PASSWORD','DB_WORKER_PASSWORD','BROKER_WORKER_PASSWORD','S3_API_PASSWORD','S3_WORKER_PASSWORD']}],'actions':['Admin','Read','Write','List']}]}))
|
||||||
|
|
||||||
|
import shutil
|
||||||
|
shutil.copyfile(root/'ca.crt', root/'bao'/'ca.crt')
|
||||||
|
run('version')
|
||||||
|
subprocess.run([__import__('sys').executable, 'scripts/setup_s3_roles.py'], check=True)
|
||||||
@@ -0,0 +1,17 @@
|
|||||||
|
import json,ssl,urllib.request,pathlib,getpass
|
||||||
|
ctx=ssl.create_default_context(cafile='secrets/ca.crt'); token=getpass.getpass('Operator root token: ')
|
||||||
|
def post(path,data):
|
||||||
|
req=urllib.request.Request('https://localhost:8200/v1/'+path,data=json.dumps(data).encode(),headers={'X-Vault-Token':token,'Content-Type':'application/json'}); urllib.request.urlopen(req,context=ctx).close()
|
||||||
|
env=dict(x.split('=',1) for x in pathlib.Path('.env').read_text().splitlines())
|
||||||
|
try:
|
||||||
|
post('sys/auth/cert', {'type': 'cert'})
|
||||||
|
post('sys/mounts/secret', {'type': 'kv', 'options': {'version': '2'}})
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
print(e.read().decode())
|
||||||
|
raise SystemExit(1)
|
||||||
|
for role in ('api','worker','operator'):
|
||||||
|
post('sys/policies/acl/'+role,{'policy':pathlib.Path('infra/openbao/'+role+'.hcl').read_text()}); post('auth/cert/certs/'+role,{'certificate':pathlib.Path('secrets/'+role+'/cert.crt').read_text(),'token_policies':[role],'token_ttl':'10m','token_max_ttl':'30m'}); post('secret/data/'+role,{'data':{'DATABASE_URL':'postgresql://messenger:'+env['POSTGRES_PASSWORD']+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/tls/ca.crt','S3_ACCESS_KEY_ID':'lab','S3_SECRET_ACCESS_KEY':env['S3_SECRET_ACCESS_KEY'],'BROKER_URL':'amqps://lab:'+env['BROKER_PASSWORD']+'@broker:5671/%2F'}})
|
||||||
|
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
subprocess.run([sys.executable, 'scripts/update_roles_bao.py'], check=True)
|
||||||
@@ -0,0 +1,27 @@
|
|||||||
|
import os
|
||||||
|
import time
|
||||||
|
import boto3
|
||||||
|
from botocore.config import Config
|
||||||
|
|
||||||
|
client = boto3.client(
|
||||||
|
's3',
|
||||||
|
endpoint_url=os.environ['S3_ENDPOINT'],
|
||||||
|
region_name='us-east-1',
|
||||||
|
aws_access_key_id=os.environ['S3_ACCESS_KEY_ID'],
|
||||||
|
aws_secret_access_key=os.environ['S3_SECRET_ACCESS_KEY'],
|
||||||
|
verify='/tls/ca.crt',
|
||||||
|
config=Config(connect_timeout=3, read_timeout=5, retries={'max_attempts': 1}),
|
||||||
|
)
|
||||||
|
bucket = os.getenv('S3_BUCKET', 'messenger-attachments')
|
||||||
|
for attempt in range(60):
|
||||||
|
try:
|
||||||
|
buckets = [x['Name'] for x in client.list_buckets().get('Buckets', [])]
|
||||||
|
if bucket not in buckets:
|
||||||
|
client.create_bucket(Bucket=bucket)
|
||||||
|
print('Private S3 bucket ready:', bucket)
|
||||||
|
break
|
||||||
|
except Exception as exc:
|
||||||
|
print('Waiting for S3:', str(exc), flush=True)
|
||||||
|
if attempt == 59:
|
||||||
|
raise
|
||||||
|
time.sleep(2)
|
||||||
@@ -0,0 +1,8 @@
|
|||||||
|
#!/bin/sh
|
||||||
|
set -eu
|
||||||
|
mkdir -p /var/lib/postgresql/tls
|
||||||
|
cp /tls/cert.crt /var/lib/postgresql/tls/server.crt
|
||||||
|
cp /tls/cert.key /var/lib/postgresql/tls/server.key
|
||||||
|
chown postgres:postgres /var/lib/postgresql/tls/server.crt /var/lib/postgresql/tls/server.key
|
||||||
|
chmod 600 /var/lib/postgresql/tls/server.key
|
||||||
|
exec docker-entrypoint.sh "$@"
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
@echo off
|
||||||
|
cd /d "%~dp0.."
|
||||||
|
|
||||||
|
echo Restarting PostgreSQL and S3...
|
||||||
|
docker compose --env-file .env restart postgres s3
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
|
||||||
|
timeout /t 30 /nobreak >nul
|
||||||
|
|
||||||
|
echo Restarting API replicas...
|
||||||
|
docker compose --env-file .env restart api1 api2
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
|
||||||
|
echo Recreating TLS proxies...
|
||||||
|
docker compose --env-file .env up -d --force-recreate --no-deps api1-tls api2-tls s3-tls
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
|
||||||
|
echo Restarting load balancer...
|
||||||
|
docker compose --env-file .env restart lb
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
|
||||||
|
echo Waiting for services...
|
||||||
|
docker compose --env-file .env up -d --wait
|
||||||
|
if errorlevel 1 exit /b 1
|
||||||
|
|
||||||
|
timeout /t 10 /nobreak >nul
|
||||||
|
|
||||||
|
exit /b 0
|
||||||
@@ -0,0 +1,24 @@
|
|||||||
|
import pathlib
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
env = dict(x.split('=',1) for x in pathlib.Path('.env').read_text().splitlines() if '=' in x and not x.startswith('#'))
|
||||||
|
|
||||||
|
def run(*args):
|
||||||
|
subprocess.run(['docker','compose','exec','-T','broker','rabbitmqctl',*args],check=True)
|
||||||
|
|
||||||
|
users = subprocess.check_output(
|
||||||
|
['docker','compose','exec','-T','broker','rabbitmqctl','list_users'],
|
||||||
|
text=True
|
||||||
|
)
|
||||||
|
|
||||||
|
if 'messenger_worker' not in users:
|
||||||
|
run('add_user','messenger_worker',env['BROKER_WORKER_PASSWORD'])
|
||||||
|
else:
|
||||||
|
run('change_password','messenger_worker',env['BROKER_WORKER_PASSWORD'])
|
||||||
|
|
||||||
|
run('set_permissions','-p','/','messenger_worker',
|
||||||
|
r'^attachment\.jobs$',
|
||||||
|
r'^(attachment\.jobs|amq\.default)$',
|
||||||
|
r'^attachment\.jobs$')
|
||||||
|
|
||||||
|
print('PASS: RabbitMQ roles configured')
|
||||||
@@ -0,0 +1,45 @@
|
|||||||
|
import pathlib
|
||||||
|
import secrets
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
p = pathlib.Path('.env')
|
||||||
|
env = dict(x.split('=', 1) for x in p.read_text().splitlines() if '=' in x and not x.startswith('#'))
|
||||||
|
|
||||||
|
for key in ('DB_API_PASSWORD', 'DB_WORKER_PASSWORD', 'BROKER_WORKER_PASSWORD'):
|
||||||
|
env.setdefault(key, secrets.token_hex(24))
|
||||||
|
|
||||||
|
p.write_text(''.join(f'{k}={v}\n' for k,v in env.items()))
|
||||||
|
|
||||||
|
sql = f"""
|
||||||
|
DO $$
|
||||||
|
BEGIN
|
||||||
|
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname='messenger_api') THEN
|
||||||
|
CREATE ROLE messenger_api LOGIN;
|
||||||
|
END IF;
|
||||||
|
IF NOT EXISTS (SELECT FROM pg_roles WHERE rolname='messenger_worker') THEN
|
||||||
|
CREATE ROLE messenger_worker LOGIN;
|
||||||
|
END IF;
|
||||||
|
END
|
||||||
|
$$;
|
||||||
|
|
||||||
|
ALTER ROLE messenger_api PASSWORD '{env["DB_API_PASSWORD"]}';
|
||||||
|
ALTER ROLE messenger_worker PASSWORD '{env["DB_WORKER_PASSWORD"]}';
|
||||||
|
|
||||||
|
GRANT CONNECT ON DATABASE messenger TO messenger_api, messenger_worker;
|
||||||
|
GRANT USAGE ON SCHEMA public TO messenger_api, messenger_worker;
|
||||||
|
|
||||||
|
GRANT SELECT, INSERT, UPDATE ON
|
||||||
|
users, chats, chat_members, messages, sessions,
|
||||||
|
message_idempotency, attachments, jobs
|
||||||
|
TO messenger_api;
|
||||||
|
|
||||||
|
GRANT SELECT, UPDATE ON attachments, jobs TO messenger_worker;
|
||||||
|
"""
|
||||||
|
|
||||||
|
subprocess.run(
|
||||||
|
['docker','compose','exec','-T','postgres','psql',
|
||||||
|
'-U','messenger','-d','messenger','-v','ON_ERROR_STOP=1'],
|
||||||
|
input=sql, text=True, check=True
|
||||||
|
)
|
||||||
|
|
||||||
|
print('PASS: PostgreSQL roles configured')
|
||||||
@@ -0,0 +1,34 @@
|
|||||||
|
import pathlib
|
||||||
|
import secrets
|
||||||
|
import json
|
||||||
|
|
||||||
|
p = pathlib.Path('.env')
|
||||||
|
env = dict(x.split('=',1) for x in p.read_text().splitlines() if '=' in x and not x.startswith('#'))
|
||||||
|
|
||||||
|
for role in ('API', 'WORKER'):
|
||||||
|
env.setdefault('S3_'+role+'_PASSWORD', secrets.token_hex(24))
|
||||||
|
|
||||||
|
p.write_text(''.join(f'{k}={v}\n' for k,v in env.items()))
|
||||||
|
|
||||||
|
config = {
|
||||||
|
'identities': [
|
||||||
|
{
|
||||||
|
'name': 'operator',
|
||||||
|
'credentials': [{'accessKey':'lab','secretKey':env['S3_SECRET_ACCESS_KEY']}],
|
||||||
|
'actions': ['Admin','Read','Write','List']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'name': 'api',
|
||||||
|
'credentials': [{'accessKey':'messenger_api','secretKey':env['S3_API_PASSWORD']}],
|
||||||
|
'actions': ['Read:messenger-attachments','Write:messenger-attachments','List:messenger-attachments']
|
||||||
|
},
|
||||||
|
{
|
||||||
|
'name': 'worker',
|
||||||
|
'credentials': [{'accessKey':'messenger_worker','secretKey':env['S3_WORKER_PASSWORD']}],
|
||||||
|
'actions': ['Read:messenger-attachments','Write:messenger-attachments','List:messenger-attachments']
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
|
|
||||||
|
pathlib.Path('secrets/s3.json').write_text(json.dumps(config))
|
||||||
|
print('PASS: S3 identities configured')
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
@echo off
|
||||||
|
cd /d "%~dp0.."
|
||||||
|
|
||||||
|
if /I "%TARGET_INSTANCE_ID%"=="api1" (
|
||||||
|
docker compose --env-file .env stop api1 >nul 2>&1
|
||||||
|
exit /b %errorlevel%
|
||||||
|
)
|
||||||
|
|
||||||
|
if /I "%TARGET_INSTANCE_ID%"=="api2" (
|
||||||
|
docker compose --env-file .env stop api2 >nul 2>&1
|
||||||
|
exit /b %errorlevel%
|
||||||
|
)
|
||||||
|
|
||||||
|
exit /b 1
|
||||||
@@ -0,0 +1,60 @@
|
|||||||
|
import ssl
|
||||||
|
import json
|
||||||
|
import urllib.request
|
||||||
|
import urllib.error
|
||||||
|
|
||||||
|
base = "https://localhost:8200/v1/"
|
||||||
|
|
||||||
|
for role in ("api", "worker"):
|
||||||
|
ctx = ssl.create_default_context(cafile="secrets/ca.crt")
|
||||||
|
ctx.load_cert_chain(
|
||||||
|
f"secrets/{role}/cert.crt",
|
||||||
|
f"secrets/{role}/cert.key"
|
||||||
|
)
|
||||||
|
|
||||||
|
req = urllib.request.Request(
|
||||||
|
base + "auth/cert/login",
|
||||||
|
data=json.dumps({"name": role}).encode(),
|
||||||
|
headers={"Content-Type": "application/json"}
|
||||||
|
)
|
||||||
|
|
||||||
|
with urllib.request.urlopen(req, context=ctx) as r:
|
||||||
|
auth = json.load(r)["auth"]
|
||||||
|
|
||||||
|
token = auth["client_token"]
|
||||||
|
print(f"\n{role}: login OK, TTL={auth['lease_duration']}")
|
||||||
|
|
||||||
|
for target in ("api", "worker", "operator"):
|
||||||
|
req = urllib.request.Request(
|
||||||
|
base + "secret/data/" + target,
|
||||||
|
headers={"X-Vault-Token": token}
|
||||||
|
)
|
||||||
|
try:
|
||||||
|
with urllib.request.urlopen(req, context=ctx) as r:
|
||||||
|
print(f"{role} -> {target}: {r.status}")
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
print(f"{role} -> {target}: {e.code}")
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
|
||||||
|
req = urllib.request.Request(
|
||||||
|
base + "auth/token/revoke-self",
|
||||||
|
data=b"{}",
|
||||||
|
headers={"X-Vault-Token": token}
|
||||||
|
)
|
||||||
|
|
||||||
|
with urllib.request.urlopen(req, context=ctx) as r:
|
||||||
|
print(f"{role}: revoke -> {r.status}")
|
||||||
|
|
||||||
|
req = urllib.request.Request(
|
||||||
|
base + "secret/data/" + role,
|
||||||
|
headers={"X-Vault-Token": token}
|
||||||
|
)
|
||||||
|
|
||||||
|
try:
|
||||||
|
urllib.request.urlopen(req, context=ctx)
|
||||||
|
print("FAIL: revoked token still works")
|
||||||
|
except urllib.error.HTTPError as e:
|
||||||
|
print(f"{role}: after revoke -> {e.code}")
|
||||||
|
assert e.code == 403
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import sys
|
||||||
|
import subprocess
|
||||||
|
from pathlib import Path
|
||||||
|
from uuid import UUID
|
||||||
|
|
||||||
|
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||||
|
|
||||||
|
from client import Client
|
||||||
|
|
||||||
|
c = Client("https://localhost:8443", "secrets/ca.crt")
|
||||||
|
alice, bob, eve, chat = c.bootstrap()
|
||||||
|
|
||||||
|
c.call("GET", "/api/v1/users/me", 200, actor=alice)
|
||||||
|
print("Before expiry: 200 OK")
|
||||||
|
|
||||||
|
user_id = str(UUID(str(alice["id"])))
|
||||||
|
|
||||||
|
sql = (
|
||||||
|
"UPDATE sessions SET expires_at = now() - interval '1 second' "
|
||||||
|
f"WHERE user_id = '{user_id}';"
|
||||||
|
)
|
||||||
|
|
||||||
|
subprocess.run(
|
||||||
|
[
|
||||||
|
"docker", "compose", "exec", "-T", "postgres",
|
||||||
|
"sh", "-c",
|
||||||
|
'psql -v ON_ERROR_STOP=1 -U "$POSTGRES_USER" -d "$POSTGRES_DB"',
|
||||||
|
],
|
||||||
|
input=sql,
|
||||||
|
text=True,
|
||||||
|
check=True,
|
||||||
|
)
|
||||||
|
|
||||||
|
c.call("GET", "/api/v1/users/me", 401, actor=alice)
|
||||||
|
print("After expiry: 401 Unauthorized")
|
||||||
|
print("PASS: expired session rejected")
|
||||||
@@ -0,0 +1,36 @@
|
|||||||
|
import json
|
||||||
|
import ssl
|
||||||
|
import urllib.request
|
||||||
|
import pathlib
|
||||||
|
import getpass
|
||||||
|
|
||||||
|
ctx = ssl.create_default_context(cafile="secrets/ca.crt")
|
||||||
|
token = getpass.getpass("Operator root token: ")
|
||||||
|
|
||||||
|
for role in ("api", "worker", "operator"):
|
||||||
|
url = "https://localhost:8200/v1/secret/data/" + role
|
||||||
|
headers = {
|
||||||
|
"X-Vault-Token": token,
|
||||||
|
"Content-Type": "application/json"
|
||||||
|
}
|
||||||
|
|
||||||
|
req = urllib.request.Request(url, headers=headers)
|
||||||
|
with urllib.request.urlopen(req, context=ctx) as r:
|
||||||
|
data = json.load(r)["data"]["data"]
|
||||||
|
|
||||||
|
data["DATABASE_URL"] = data["DATABASE_URL"].split("?")[0]
|
||||||
|
data["DATABASE_URL"] += "?sslmode=verify-full&sslrootcert=/tls/ca.crt"
|
||||||
|
data["BROKER_URL"] = data["BROKER_URL"].replace(
|
||||||
|
"amqp://", "amqps://"
|
||||||
|
).replace("@broker:5672", "@broker:5671")
|
||||||
|
|
||||||
|
|
||||||
|
req = urllib.request.Request(
|
||||||
|
url,
|
||||||
|
data=json.dumps({"data": data}).encode(),
|
||||||
|
headers=headers,
|
||||||
|
method="POST"
|
||||||
|
)
|
||||||
|
|
||||||
|
with urllib.request.urlopen(req, context=ctx):
|
||||||
|
print(role + ": updated")
|
||||||
@@ -0,0 +1,28 @@
|
|||||||
|
import pathlib
|
||||||
|
import json
|
||||||
|
import ssl
|
||||||
|
import urllib.request
|
||||||
|
import getpass
|
||||||
|
|
||||||
|
env = dict(x.split('=',1) for x in pathlib.Path('.env').read_text().splitlines() if '=' in x and not x.startswith('#'))
|
||||||
|
ctx = ssl.create_default_context(cafile='secrets/ca.crt')
|
||||||
|
token = getpass.getpass('Operator root token: ')
|
||||||
|
|
||||||
|
for role in ('api','worker'):
|
||||||
|
values = {
|
||||||
|
'DATABASE_URL': f'postgresql://messenger_{role}:'+env['DB_'+role.upper()+'_PASSWORD']+'@postgres:5432/messenger?sslmode=verify-full&sslrootcert=/tls/ca.crt',
|
||||||
|
'S3_ACCESS_KEY_ID': 'messenger_'+role,
|
||||||
|
'S3_SECRET_ACCESS_KEY': env['S3_'+role.upper()+'_PASSWORD']
|
||||||
|
}
|
||||||
|
|
||||||
|
if role == 'worker':
|
||||||
|
values['BROKER_URL'] = 'amqps://messenger_worker:'+env['BROKER_WORKER_PASSWORD']+'@broker:5671/%2F'
|
||||||
|
|
||||||
|
req = urllib.request.Request(
|
||||||
|
'https://localhost:8200/v1/secret/data/'+role,
|
||||||
|
data=json.dumps({'data':values}).encode(),
|
||||||
|
headers={'X-Vault-Token':token,'Content-Type':'application/json'}
|
||||||
|
)
|
||||||
|
|
||||||
|
with urllib.request.urlopen(req,context=ctx) as response:
|
||||||
|
print(role, response.status)
|
||||||
@@ -0,0 +1,93 @@
|
|||||||
|
"""OpenTelemetry bootstrap and low-cardinality application signals."""
|
||||||
|
import os
|
||||||
|
import socket
|
||||||
|
import time
|
||||||
|
import uuid
|
||||||
|
import logging
|
||||||
|
import grpc
|
||||||
|
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.exporter.otlp.proto.grpc.trace_exporter import OTLPSpanExporter
|
||||||
|
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._logs import LoggerProvider, LoggingHandler
|
||||||
|
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||||
|
from opentelemetry.exporter.otlp.proto.grpc._log_exporter import OTLPLogExporter
|
||||||
|
from opentelemetry.trace.propagation.tracecontext import TraceContextTextMapPropagator
|
||||||
|
|
||||||
|
SERVICE = os.getenv('OTEL_SERVICE_NAME', 'messenger-api')
|
||||||
|
RESOURCE = Resource.create({
|
||||||
|
'service.name': SERVICE,
|
||||||
|
'service.version': '1.4.0',
|
||||||
|
'service.instance.id': os.getenv('INSTANCE_ID', socket.gethostname()),
|
||||||
|
'deployment.environment.name': os.getenv('DEPLOYMENT_ENV', 'lab'),
|
||||||
|
})
|
||||||
|
ENDPOINT = os.getenv('OTEL_EXPORTER_OTLP_ENDPOINT', 'https://otel-collector:4317')
|
||||||
|
|
||||||
|
def _endpoint():
|
||||||
|
return ENDPOINT.replace('http://', '').replace('https://', '')
|
||||||
|
|
||||||
|
with open('/tls/ca.crt', 'rb') as ca:
|
||||||
|
TLS_CREDENTIALS = grpc.ssl_channel_credentials(
|
||||||
|
root_certificates=ca.read()
|
||||||
|
)
|
||||||
|
|
||||||
|
trace_provider = TracerProvider(resource=RESOURCE)
|
||||||
|
trace_provider.add_span_processor(BatchSpanProcessor(OTLPSpanExporter(endpoint=_endpoint(), insecure=False, credentials=TLS_CREDENTIALS)))
|
||||||
|
trace.set_tracer_provider(trace_provider)
|
||||||
|
|
||||||
|
metric_reader = PeriodicExportingMetricReader(OTLPMetricExporter(endpoint=_endpoint(), insecure=False, credentials=TLS_CREDENTIALS), export_interval_millis=5000)
|
||||||
|
metrics.set_meter_provider(MeterProvider(resource=RESOURCE, metric_readers=[metric_reader]))
|
||||||
|
meter = metrics.get_meter('messenger.application', '1.0.0')
|
||||||
|
|
||||||
|
logger_provider = LoggerProvider(resource=RESOURCE)
|
||||||
|
logger_provider.add_log_record_processor(
|
||||||
|
BatchLogRecordProcessor(
|
||||||
|
OTLPLogExporter(endpoint=_endpoint(), insecure=False, credentials=TLS_CREDENTIALS)
|
||||||
|
)
|
||||||
|
)
|
||||||
|
|
||||||
|
otel_handler = LoggingHandler(
|
||||||
|
level=logging.NOTSET,
|
||||||
|
logger_provider=logger_provider
|
||||||
|
)
|
||||||
|
|
||||||
|
app_logger = logging.getLogger('messenger.application')
|
||||||
|
app_logger.setLevel(logging.INFO)
|
||||||
|
app_logger.addHandler(otel_handler)
|
||||||
|
app_logger.propagate = False
|
||||||
|
|
||||||
|
http_requests = meter.create_counter('messenger_http_requests', description='HTTP requests completed', unit='{request}')
|
||||||
|
http_duration = meter.create_histogram('messenger_http_request_duration_seconds', description='HTTP request duration', unit='s')
|
||||||
|
jobs_processed = meter.create_counter('messenger_jobs_processed', description='Jobs processed by worker', unit='{job}')
|
||||||
|
job_duration = meter.create_histogram('messenger_job_processing_duration_seconds', description='Job processing duration', unit='s')
|
||||||
|
|
||||||
|
propagator = TraceContextTextMapPropagator()
|
||||||
|
|
||||||
|
def event(name, severity='INFO', **attrs):
|
||||||
|
span = trace.get_current_span()
|
||||||
|
ctx = span.get_span_context()
|
||||||
|
|
||||||
|
attrs['event'] = name
|
||||||
|
|
||||||
|
if ctx.is_valid:
|
||||||
|
attrs['trace_id'] = format(ctx.trace_id, '032x')
|
||||||
|
attrs['span_id'] = format(ctx.span_id, '016x')
|
||||||
|
|
||||||
|
level = getattr(logging, severity.upper(), logging.INFO)
|
||||||
|
|
||||||
|
app_logger.log(
|
||||||
|
level,
|
||||||
|
name,
|
||||||
|
extra=attrs
|
||||||
|
)
|
||||||
|
|
||||||
|
def shutdown():
|
||||||
|
for provider in (trace_provider, metrics.get_meter_provider(), logger_provider):
|
||||||
|
try:
|
||||||
|
provider.force_flush(timeout_millis=3000)
|
||||||
|
except Exception:
|
||||||
|
pass
|
||||||
@@ -0,0 +1,108 @@
|
|||||||
|
import hashlib, io, json, os, time
|
||||||
|
from PIL import Image, ImageOps
|
||||||
|
from psycopg.types.json import Jsonb
|
||||||
|
from main import db, transaction, s3, S3_BUCKET
|
||||||
|
from queueing import connect, publish, QUEUE
|
||||||
|
from opentelemetry import trace
|
||||||
|
from telemetry import jobs_processed, job_duration, event, propagator
|
||||||
|
MAX_ATTEMPTS=int(os.getenv('JOB_MAX_ATTEMPTS','5'))
|
||||||
|
|
||||||
|
def dispatch():
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
c,ch=connect()
|
||||||
|
try:
|
||||||
|
with transaction() as conn:
|
||||||
|
jobs=conn.execute('SELECT * FROM jobs WHERE NOT published FOR UPDATE SKIP LOCKED LIMIT 20').fetchall()
|
||||||
|
for job in jobs:
|
||||||
|
publish(ch,job)
|
||||||
|
event('job.published', job_type='attachment.process.v1', outcome='published')
|
||||||
|
conn.execute('UPDATE jobs SET published=true WHERE id=%s',(job['id'],))
|
||||||
|
finally: c.close()
|
||||||
|
except Exception as e: print('dispatch retry:',type(e).__name__,flush=True)
|
||||||
|
time.sleep(0.5)
|
||||||
|
|
||||||
|
def _process(payload):
|
||||||
|
jid=payload['job_id']
|
||||||
|
# Session advisory lock spans processing and commit; released on worker death.
|
||||||
|
with db() as lock:
|
||||||
|
lock.execute('SELECT pg_advisory_lock(hashtextextended(%s,0))',(jid,))
|
||||||
|
with transaction() as conn:
|
||||||
|
job=conn.execute('SELECT * FROM jobs WHERE id=%s',(jid,)).fetchone()
|
||||||
|
if not job:return
|
||||||
|
row=conn.execute('SELECT * FROM attachments WHERE id=%s',(job['attachment_id'],)).fetchone()
|
||||||
|
if row['status'] in ('ready','failed') or payload['attempt']!=job['attempt']:return
|
||||||
|
conn.execute("UPDATE attachments SET status='processing',updated_at=now() WHERE id=%s",(row['id'],))
|
||||||
|
try:
|
||||||
|
client=s3(); data=client.get_object(Bucket=S3_BUCKET,Key=row['object_key'])['Body'].read()
|
||||||
|
if hashlib.sha256(data).hexdigest()!=row['sha256']:raise ValueError('checksum')
|
||||||
|
with Image.open(io.BytesIO(data)) as source:
|
||||||
|
img=ImageOps.exif_transpose(source).convert('RGBA')
|
||||||
|
w,h=img.size; scale=min(1,256/max(w,h)); size=(max(1,int(w*scale)),max(1,int(h*scale)))
|
||||||
|
img=img.resize(size,Image.Resampling.LANCZOS)
|
||||||
|
rgb=Image.new('RGB',size,'white'); rgb.paste(img,mask=img.getchannel('A'))
|
||||||
|
out=io.BytesIO(); rgb.save(out,format='JPEG',quality=85); thumb=out.getvalue()
|
||||||
|
key=f"attachments/{row['chat_id']}/{row['id']}"
|
||||||
|
client.put_object(Bucket=S3_BUCKET,Key=key,Body=data,ContentType=row['content_type'])
|
||||||
|
client.put_object(Bucket=S3_BUCKET,Key=key+'/thumbnail',Body=thumb,ContentType='image/jpeg')
|
||||||
|
v=dict(name='thumbnail',content_type='image/jpeg',width=size[0],height=size[1],size_bytes=len(thumb),sha256=hashlib.sha256(thumb).hexdigest())
|
||||||
|
with transaction() as conn:
|
||||||
|
conn.execute("UPDATE attachments SET status='ready',object_key=%s,variants=%s,error_code=NULL,updated_at=now() WHERE id=%s",(key,Jsonb([v]),row['id']))
|
||||||
|
try:client.delete_object(Bucket=S3_BUCKET,Key=row['object_key'])
|
||||||
|
except Exception:pass
|
||||||
|
except Exception as e:
|
||||||
|
print(
|
||||||
|
'processing error:',
|
||||||
|
type(e).__name__,
|
||||||
|
'checksum mismatch' if isinstance(e, ValueError) and str(e) == 'checksum' else 'other error',
|
||||||
|
flush=True
|
||||||
|
)
|
||||||
|
with transaction() as conn:
|
||||||
|
if conn.execute('SELECT status FROM attachments WHERE id=%s',(row['id'],)).fetchone()['status']=='ready':return
|
||||||
|
if job['attempt']>=MAX_ATTEMPTS:
|
||||||
|
conn.execute("UPDATE attachments SET status='failed',error_code='retry_exhausted',updated_at=now() WHERE id=%s AND status!='ready'",(row['id'],))
|
||||||
|
else:
|
||||||
|
conn.execute("UPDATE attachments SET status='queued',updated_at=now() WHERE id=%s AND status!='ready'",(row['id'],))
|
||||||
|
conn.execute('UPDATE jobs SET attempt=attempt+1,published=false WHERE id=%s',(jid,))
|
||||||
|
return 'failed' if job['attempt']>=MAX_ATTEMPTS else 'retry'
|
||||||
|
|
||||||
|
def process(payload, headers=None):
|
||||||
|
context=propagator.extract(headers or {})
|
||||||
|
tracer=trace.get_tracer('messenger.worker')
|
||||||
|
started=time.perf_counter()
|
||||||
|
outcome='success'
|
||||||
|
with tracer.start_as_current_span('job.process', context=context) as span:
|
||||||
|
span.set_attribute('messaging.system','rabbitmq')
|
||||||
|
span.set_attribute('messaging.destination.name',QUEUE)
|
||||||
|
span.set_attribute('messaging.operation','process')
|
||||||
|
span.set_attribute('job.type','attachment.process.v1')
|
||||||
|
try:
|
||||||
|
result=_process(payload)
|
||||||
|
if result in ('retry','failed'):
|
||||||
|
outcome='error'
|
||||||
|
span.set_attribute('job.outcome', result)
|
||||||
|
if result == 'failed': span.set_status(trace.Status(trace.StatusCode.ERROR))
|
||||||
|
except Exception as exc:
|
||||||
|
outcome='error'
|
||||||
|
span.record_exception(exc)
|
||||||
|
span.set_status(trace.Status(trace.StatusCode.ERROR))
|
||||||
|
raise
|
||||||
|
finally:
|
||||||
|
duration=time.perf_counter()-started
|
||||||
|
attrs={'job_type':'attachment.process.v1','outcome':outcome}
|
||||||
|
jobs_processed.add(1,attrs); job_duration.record(duration,attrs)
|
||||||
|
event('job.processed' if outcome=='success' else 'job.failed', 'ERROR' if outcome!='success' else 'INFO', job_type='attachment.process.v1', outcome=outcome, duration_seconds=round(duration,6))
|
||||||
|
|
||||||
|
def consume():
|
||||||
|
while True:
|
||||||
|
try:
|
||||||
|
c,ch=connect(); ch.basic_qos(prefetch_count=1)
|
||||||
|
def callback(channel,method,props,body):
|
||||||
|
try: process(json.loads(body), props.headers or {}); channel.basic_ack(method.delivery_tag)
|
||||||
|
except Exception: channel.basic_nack(method.delivery_tag,requeue=True); time.sleep(1)
|
||||||
|
ch.basic_consume(QUEUE,callback); ch.start_consuming()
|
||||||
|
except Exception as e: print('consumer reconnect:',type(e).__name__,flush=True); time.sleep(2)
|
||||||
|
|
||||||
|
if __name__=='__main__':
|
||||||
|
import sys
|
||||||
|
(dispatch if 'dispatch' in sys.argv else consume)()
|
||||||
Reference in New Issue
Block a user