forked from mtusi2026/mtusi2026lab7
Добавил защиту сервисов
This commit is contained in:
@@ -18,3 +18,7 @@ __pycache__
|
||||
node_modules
|
||||
evidence
|
||||
.DS_Store
|
||||
**/__pycache__
|
||||
**/*.py[cod]
|
||||
|
||||
runtime
|
||||
|
||||
+4
-40
@@ -1,41 +1,5 @@
|
||||
# Copy to .env for your LOCAL synthetic test environment; never commit .env.
|
||||
# These are logical interface suggestions; map actual framework names in REPORT.md.
|
||||
APP_HOST=0.0.0.0
|
||||
APP_PORT=8080
|
||||
APP_ENV=lab
|
||||
COMPOSE_PROJECT_NAME=mtusi-lab7
|
||||
HTTP_PORT=8443
|
||||
GRAFANA_PORT=3309
|
||||
BAO_PORT=18200
|
||||
SESSION_TTL_SECONDS=3600
|
||||
# Choose credentials locally. File paths contain no secret values.
|
||||
DATABASE_URL_FILE=/run/secrets/database_url
|
||||
# Optional on 3, required use on 4 in lab2; Redis OR Valkey:
|
||||
SESSION_STORE=postgres
|
||||
CACHE_URL_FILE=/run/secrets/cache_url
|
||||
API_REPLICAS=2
|
||||
IDEMPOTENCY_TTL_SECONDS=86400
|
||||
S3_ENDPOINT=https://s3:9000
|
||||
S3_REGION=us-east-1
|
||||
S3_BUCKET=messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE=/run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE=/run/secrets/s3_secret_access_key
|
||||
MAX_UPLOAD_BYTES=10485760
|
||||
MAX_IMAGE_PIXELS=40000000
|
||||
BROKER_URL_FILE=/run/secrets/broker_url
|
||||
WORKER_CONCURRENCY=2
|
||||
JOB_MAX_ATTEMPTS=5
|
||||
JOB_TIMEOUT_SECONDS=60
|
||||
STAGING_RETENTION_SECONDS=86400
|
||||
OTEL_SERVICE_NAME=messenger-api
|
||||
# Worker must set a distinct service.name.
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT=https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL=http/protobuf
|
||||
OTEL_RESOURCE_ATTRIBUTES=deployment.environment.name=lab
|
||||
# TLS and OpenBao: actual paths/ports depend on your implemented trust matrix.
|
||||
PUBLIC_BASE_URL=https://localhost:8443
|
||||
TLS_CA_FILE=/run/secrets/ca.crt
|
||||
TLS_CERT_FILE=/run/secrets/service.crt
|
||||
TLS_KEY_FILE=/run/secrets/service.key
|
||||
BAO_ADDR=https://openbao:8200
|
||||
BAO_CACERT=/run/secrets/bao-ca.crt
|
||||
# No root token here. Bootstrap operator -> short-lived service auth -> scoped token.
|
||||
ARGON2_MEMORY_KIB=19456
|
||||
ARGON2_ITERATIONS=2
|
||||
ARGON2_PARALLELISM=1
|
||||
|
||||
@@ -0,0 +1,8 @@
|
||||
* text=auto
|
||||
*.py text eol=lf
|
||||
*.sh text eol=lf
|
||||
*.yaml text eol=lf
|
||||
*.json text eol=lf
|
||||
*.md text eol=lf
|
||||
*.lock text eol=lf
|
||||
*.cmd text eol=crlf
|
||||
@@ -30,3 +30,5 @@ coverage/
|
||||
.vscode/
|
||||
# Keep small, sanitized evidence summaries in evidence/ under version control.
|
||||
# Inspect git diff --cached: ignore rules are not a secret scanner.
|
||||
|
||||
runtime/
|
||||
|
||||
+16
@@ -0,0 +1,16 @@
|
||||
FROM python:3.13.14-slim-bookworm@sha256:67a1e1f215ccda113cfc024e8639049257e88f273898f595b61476d128d387e8
|
||||
|
||||
ENV PYTHONDONTWRITEBYTECODE=1 PYTHONUNBUFFERED=1 PYTHONUTF8=1 \
|
||||
APP_HOST=0.0.0.0 APP_PORT=8080 APP_ENV=lab
|
||||
WORKDIR /app
|
||||
COPY requirements.lock .
|
||||
RUN python -m pip install --no-cache-dir -r requirements.lock \
|
||||
&& useradd --uid 10001 --create-home messenger
|
||||
COPY src ./src
|
||||
COPY migrations ./migrations
|
||||
COPY scripts/remote_probe.py /app/probe.py
|
||||
USER messenger
|
||||
EXPOSE 8080
|
||||
HEALTHCHECK --interval=5s --timeout=4s --start-period=10s --retries=6 \
|
||||
CMD python -c "import os,urllib.request; urllib.request.urlopen('http://127.0.0.1:'+os.environ['APP_PORT']+'/health/ready',timeout=3).close()"
|
||||
CMD ["python", "-m", "src"]
|
||||
@@ -1,37 +1,88 @@
|
||||
# Отчёт — лабораторная 7
|
||||
# ЛР7 — безопасность
|
||||
|
||||
- Автор, группа: TODO
|
||||
- Целевая оценка; выбранный трек 5, если нужен: TODO
|
||||
- Commit/PR: TODO после публикации
|
||||
- Использованные источники, библиотеки и помощь ИИ: TODO
|
||||
Югай Артур Рустамович, БПИ2304. На **3**.
|
||||
|
||||
## Запуск из чистого clone
|
||||
## Запуск
|
||||
|
||||
TODO: версии runtime/образов, prerequisites, команды создания локальных secrets/.env, build, миграций, запуска, ожидания готовности, тестов и остановки. Указать необходимые действия оператора. Не вставлять секреты. Отдельно указать безопасную остановку и команду намеренного удаления учебных данных.
|
||||
Нужны Docker Desktop (Linux containers), Compose v2+, Git и Python 3.13.
|
||||
В терминале VS Code, из папки репозитория:
|
||||
|
||||
## Архитектура и решения
|
||||
```powershell
|
||||
python -X utf8 scripts/lab.py setup
|
||||
python -X utf8 scripts/lab.py build
|
||||
python -X utf8 scripts/lab.py start
|
||||
python -X utf8 scripts/lab.py verify
|
||||
```
|
||||
|
||||
TODO: схема процессов/хранилищ, источник истины, транзакционные границы, ограничения. Что перенесено из lab6, что изменено в этой работе. Соответствие переменных из .env.example реальной конфигурации.
|
||||
API: https://127.0.0.1:8443. Grafana: https://127.0.0.1:3309, admin,
|
||||
пароль в `runtime/mtusi-lab7/grafana/password`. CA для клиентов:
|
||||
`runtime/mtusi-lab7/pki/ca.crt`. localhost тоже есть в SAN сертификатов.
|
||||
`setup` создаёт CA, сертификаты и конфиги через Python cryptography и сохраняет
|
||||
существующие настройки. Приватные файлы в Git не входят.
|
||||
|
||||
## Доказательства критериев
|
||||
Операторский профиль Windows зашифрован DPAPI в LOCALAPPDATA/Codex/Lab7,
|
||||
вне репозитория и контейнеров. На Linux используется AES-GCM/Scrypt и ввод
|
||||
passphrase оператором в терминале; полностью unattended запуск на Linux не заявляю.
|
||||
Для make-проверок передать BASE_URL и CA_FILE; OpenAPI validate запускать через .venv.
|
||||
|
||||
| Критерий README | Команда/сценарий | Наблюдаемый результат | Файл доказательства |
|
||||
| --- | --- | --- | --- |
|
||||
| Публичный smoke | make test | TODO | TODO |
|
||||
| Остальные пункты уровня 3 | TODO | TODO | TODO |
|
||||
| Все пункты уровня 4, если заявлен | TODO | TODO | TODO |
|
||||
| Выбранный трек 5, если заявлен | TODO | TODO | TODO |
|
||||
`stop` сохраняет данные. `bao-status`, `bao-unseal` — работа оператора с Bao.
|
||||
`restart` включает операторский unseal. `pki-renew` обновляет leaf с остановкой стенда.
|
||||
|
||||
TODO: добавить отдельную строку для каждого заявленного критерия. PASS без команды и наблюдения не является доказательством. Проверка инфраструктурного hook требует подтверждения, какие реальные процессы/хранилища перезапущены.
|
||||
## Что изменено
|
||||
|
||||
## Эксперименты и отказы
|
||||
Перенёс свою ЛР6: две API-реплики, PostgreSQL, S3, RabbitMQ, worker и наблюдаемость.
|
||||
Внешний HTTPS → HAProxy → mTLS Envoy → локальный API. Envoy проверяет CA и точный SAN lb.
|
||||
БД/брокер/Bao/Grafana используют native TLS; остальные HTTP-соединения защищены Envoy.
|
||||
Plaintext допускается внутри закрытого loopback namespace, не между сервисами.
|
||||
|
||||
TODO: гипотеза, hardware/лимиты, версии, объём данных, профиль нагрузки, concurrency/arrival rate, длительность/прогрев, повторы, успешные RPS, ошибки, p50/p95/p99, CPU/RAM. Сохранить raw summary без tokens и объяснить ограничения измерения.
|
||||
[Матрица всех связей](contracts/trust-matrix.md), [модель угроз](THREATS.md).
|
||||
Конфиги и policies создаются из версионируемых шаблонов в scripts/provision.py;
|
||||
compose.yaml описывает фактический стенд. Секретные runtime-конфиги не входят в образ.
|
||||
OpenBao 2.7.3, Envoy 1.40.2; остальные версии сохранены из ЛР6. Образы закреплены digest,
|
||||
Python-зависимости — lock-файлами.
|
||||
|
||||
| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |
|
||||
| --- | --- | --- | --- |
|
||||
| TODO | TODO | TODO | TODO |
|
||||
API/worker/cleanup получают свои KV bundles через cert auth, токены 15 минут/max 1 час,
|
||||
с renewal/re-auth. Первичный root token отозван. В приложении нет unseal shares или
|
||||
root credential. DB roles, S3 prefixes, producer/consumer и доступ к Collector разделены.
|
||||
SeaweedFS Write объединяет Put/Delete, поэтому cleanup ограничен префиксами,
|
||||
но отдельное delete-only право этой конфигурацией не заявляется.
|
||||
|
||||
## Ограничения и следующие шаги
|
||||
Argon2id — 19 MiB/t2/p1, два hash slot на API. Время hash/verify измеряется в Linux-образе
|
||||
приложения с одним CPU. Это исходный минимум задания; ограничение параллелизма сохраняет
|
||||
расход памяти на hash около 38 MiB на реплику сверх памяти приложения.
|
||||
Вход ограничен на LB: 20 запросов/сек с IP, 429/Retry-After. JSON — 64 KiB,
|
||||
изображения — прежние 10 MiB/40 млн пикселей. Client X-Forwarded-For перезаписывается.
|
||||
|
||||
TODO: какие отказы выдерживаются и какие нет; что не реализовано; где учебное упрощение; какое улучшение подтверждено, а какое пока гипотеза.
|
||||
## Проверки
|
||||
|
||||
```powershell
|
||||
python -X utf8 scripts/lab.py test
|
||||
python -X utf8 scripts/lab.py security-check
|
||||
python -X utf8 scripts/lab.py bao-check
|
||||
python -X utf8 scripts/lab.py telemetry-check
|
||||
```
|
||||
|
||||
| Сценарий | Результаты |
|
||||
| --- | --- |
|
||||
| Smoke и 38 собственных тестов, весь verify | [summary](evidence/summary.json), [лог](evidence/verification.txt) |
|
||||
| Нет cert / чужой CA / wrong identity / expired / правильный lb; оба API | [tls](evidence/tls.json) |
|
||||
| Policy allow/deny, отзыв токена, DB/S3/MQ/telemetry ACL | [policies](evidence/policies.json) |
|
||||
| Rate limit, JSON/chunked, измерения Argon2id | [limits](evidence/limits.json) |
|
||||
| Sealed Bao, короткий TTL, восстановление старой сессии | [bao expiry](evidence/bao-expiry.json) |
|
||||
| Сохранность и отказ реплик через HTTPS | [persistence](evidence/persistence.json), [failover](evidence/failover.json) |
|
||||
| Очередь и повторы | [queue](evidence/queue.json), [retry](evidence/retry.json) |
|
||||
| Метрики, логи, трассы, privacy и Grafana через TLS | [telemetry](evidence/telemetry.json) |
|
||||
|
||||
Логи и доказательства содержат синтетические ID и безопасные результаты.
|
||||
Пароли, токены, private keys, unseal shares и тексты сообщений туда не включаются.
|
||||
|
||||
## Ограничения
|
||||
|
||||
Учебный single-host стенд, оператор и Docker host доверенные. Stateful-компоненты
|
||||
не отказоустойчивы, OpenBao single-node. Динамические DB leases, расширенный mTLS
|
||||
брокера/Collector и исследование lifecycle уровня 4–5 не выполнялись.
|
||||
|
||||
Источники: [задание](README.md), [OpenBao cert auth](https://openbao.org/docs/auth/cert/),
|
||||
[policies](https://openbao.org/docs/concepts/policies/),
|
||||
[Envoy TLS](https://www.envoyproxy.io/docs/envoy/latest/start/quick-start/securing),
|
||||
[RabbitMQ permissions](https://www.rabbitmq.com/docs/access-control).
|
||||
|
||||
+23
@@ -0,0 +1,23 @@
|
||||
# Модель угроз
|
||||
|
||||
Активы: пароли, сессии, сообщения, изображения, очередь, рабочие credentials,
|
||||
CA key и материалы unseal. Участники: пользователь, посторонний пользователь,
|
||||
неавторизованный контейнер, API, worker, cleanup и доверенный оператор.
|
||||
|
||||
| Угроза | Контроль | Проверка |
|
||||
| --- | --- | --- |
|
||||
| Перехват пароля/токена | TLS, проверка CA и SAN | tls-check, tests/security.py |
|
||||
| Обход LB | API слушает loopback; сетевой Envoy требует mTLS | tls-check |
|
||||
| Чужая identity с нашим CA | allowlist SAN в Envoy и cert auth OpenBao | tls-check, policy-check |
|
||||
| Worker получает данные пользователей/админские secrets | Свои DB role, KV policy, S3 prefixes и RabbitMQ permissions | policy-check |
|
||||
| Пользователь читает чужой чат/вложение | Bearer identity и membership ACL, одинаковый 404 | test |
|
||||
| Подбор пароля/дорогой hash | Argon2id, два hash slot на API, лимит входа на LB | security-check |
|
||||
| Большое/повреждённое тело | JSON 64 KiB, изображение 10 MiB/40 млн пикселей | test, security-check |
|
||||
| Утечка через логи/образ/Git | Разрешённые поля логов, tmpfs, игнорирование runtime | telemetry-check и проверка публикации |
|
||||
| Истёк доступ к OpenBao | Короткий токен, renewal/re-auth, ограниченный cache и fail-closed | bao-check |
|
||||
|
||||
Оператор и Docker host доверенные. Компрометация host или ключа CA даёт возможность
|
||||
выдавать identities — это за пределами модели. TLS-sidecar и backend с общим network
|
||||
namespace составляют одну границу доверия; локальный plaintext внутри неё разрешён.
|
||||
Отказ зависимостей должен давать ограниченный отказ без утечки секретов и потери
|
||||
уже принятых данных. Данные в тестах синтетические.
|
||||
+689
@@ -0,0 +1,689 @@
|
||||
name: mtusi-lab7
|
||||
services:
|
||||
db:
|
||||
image: postgres:17.11-bookworm@sha256:665dc7b37ac52a17e298511414c21d23ffa4e6a6ef6225b3e5d59c7afb35e994
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/config/password
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/db:/run/config:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/server/db:/run/server:ro
|
||||
healthcheck:
|
||||
test:
|
||||
- CMD-SHELL
|
||||
- pg_isready -U messenger -d messenger
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
stop_grace_period: 10s
|
||||
mem_limit: 512m
|
||||
cpus: 1.0
|
||||
entrypoint:
|
||||
- /bin/sh
|
||||
- -c
|
||||
- install -o postgres -g postgres -m 600 /run/server/client.key /var/lib/postgresql/server.key;
|
||||
exec docker-entrypoint.sh postgres -c ssl=on -c ssl_cert_file=/run/server/client.crt
|
||||
-c ssl_key_file=/var/lib/postgresql/server.key -c hba_file=/run/config/pg_hba.conf
|
||||
s3-storage:
|
||||
image: chrislusf/seaweedfs:4.54@sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15
|
||||
command:
|
||||
- server
|
||||
- -filer
|
||||
- -dir=/data
|
||||
- -ip=127.0.0.1
|
||||
- -ip.bind=127.0.0.1
|
||||
- -master.volumeSizeLimitMB=128
|
||||
- -volume.max=64
|
||||
- -master.electionTimeout=1s
|
||||
- -master.heartbeatInterval=100ms
|
||||
volumes:
|
||||
- s3data:/data
|
||||
healthcheck:
|
||||
test:
|
||||
- CMD-SHELL
|
||||
- wget -q -O - http://127.0.0.1:9333/cluster/status | grep -q '"IsLeader":true'
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 45
|
||||
stop_grace_period: 10s
|
||||
mem_limit: 512m
|
||||
cpus: 1.0
|
||||
networks:
|
||||
default:
|
||||
aliases:
|
||||
- s3
|
||||
s3:
|
||||
image: chrislusf/seaweedfs:4.54@sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15
|
||||
command:
|
||||
- s3
|
||||
- -filer=127.0.0.1:8888
|
||||
- -port=9001
|
||||
- -ip.bind=127.0.0.1
|
||||
- -config=/run/config/config.json
|
||||
- -iam=false
|
||||
- -port.iceberg=0
|
||||
- -port.lance=0
|
||||
stop_grace_period: 3s
|
||||
mem_limit: 512m
|
||||
cpus: 1.0
|
||||
network_mode: service:s3-storage
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/s3:/run/config:ro
|
||||
depends_on:
|
||||
s3-storage:
|
||||
condition: service_healthy
|
||||
migrate:
|
||||
image: mtusi-messenger:lab7
|
||||
build: .
|
||||
environment:
|
||||
APP_HOST: 127.0.0.1
|
||||
APP_PORT: 8080
|
||||
APP_ENV: lab
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||
SERVICE_VERSION: lab7
|
||||
DATABASE_URL_FILE: /run/operator/database_url
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
S3_ENDPOINT: https://s3:9000
|
||||
S3_REGION: us-east-1
|
||||
S3_BUCKET: messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE: /run/operator/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/operator/s3_secret_access_key
|
||||
BROKER_URL_FILE: /run/runtime/broker_url
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
|
||||
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
|
||||
CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-30}
|
||||
CLEANUP_GRACE_SECONDS: ${CLEANUP_GRACE_SECONDS:-600}
|
||||
TLS_CA_FILE: /run/pki/ca.crt
|
||||
stop_grace_period: 20s
|
||||
command:
|
||||
- python
|
||||
- -m
|
||||
- src.migrate
|
||||
healthcheck:
|
||||
disable: true
|
||||
mem_limit: 512m
|
||||
cpus: 1.0
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/operator:/run/operator:ro
|
||||
bootstrap:
|
||||
image: mtusi-messenger:lab7
|
||||
build: .
|
||||
environment:
|
||||
APP_HOST: 127.0.0.1
|
||||
APP_PORT: 8080
|
||||
APP_ENV: lab
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||
SERVICE_VERSION: lab7
|
||||
DATABASE_URL_FILE: /run/operator/database_url
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
S3_ENDPOINT: https://s3:9000
|
||||
S3_REGION: us-east-1
|
||||
S3_BUCKET: messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE: /run/operator/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/operator/s3_secret_access_key
|
||||
BROKER_URL_FILE: /run/runtime/broker_url
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
|
||||
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
|
||||
CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-30}
|
||||
CLEANUP_GRACE_SECONDS: ${CLEANUP_GRACE_SECONDS:-600}
|
||||
TLS_CA_FILE: /run/pki/ca.crt
|
||||
S3_ADMIN_ACCESS_KEY_ID_FILE: /run/operator/s3_admin_access_key_id
|
||||
S3_ADMIN_SECRET_ACCESS_KEY_FILE: /run/operator/s3_admin_secret_access_key
|
||||
stop_grace_period: 20s
|
||||
command:
|
||||
- python
|
||||
- -m
|
||||
- src.bootstrap
|
||||
healthcheck:
|
||||
disable: true
|
||||
mem_limit: 512m
|
||||
cpus: 1.0
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/operator:/run/operator:ro
|
||||
broker:
|
||||
image: rabbitmq:4.4.1-management@sha256:61f90c401a5b5ed2486771973ea92ad66046471eacab9c9149f1a6e091c91677
|
||||
hostname: broker
|
||||
environment:
|
||||
RABBITMQ_CONFIG_FILE: /run/config/rabbitmq
|
||||
RABBITMQ_NODENAME: rabbit@broker
|
||||
RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS: -kernel inet_dist_use_interface {127,0,0,1}
|
||||
ERL_EPMD_ADDRESS: 127.0.0.1
|
||||
volumes:
|
||||
- brokerdata:/var/lib/rabbitmq
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/broker:/run/config:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/server/broker:/run/server:ro
|
||||
healthcheck:
|
||||
test:
|
||||
- CMD
|
||||
- rabbitmq-diagnostics
|
||||
- -q
|
||||
- ping
|
||||
interval: 3s
|
||||
timeout: 5s
|
||||
retries: 40
|
||||
stop_grace_period: 10s
|
||||
mem_limit: 512m
|
||||
cpus: 1.0
|
||||
extra_hosts:
|
||||
broker: 127.0.0.1
|
||||
worker:
|
||||
image: mtusi-messenger:lab7
|
||||
build: .
|
||||
environment:
|
||||
APP_HOST: 127.0.0.1
|
||||
APP_PORT: 8080
|
||||
APP_ENV: lab
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||
SERVICE_VERSION: lab7
|
||||
DATABASE_URL_FILE: /run/runtime/database_url
|
||||
CURSOR_SECRET_FILE: /run/runtime/cursor_key
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
S3_ENDPOINT: https://s3:9000
|
||||
S3_REGION: us-east-1
|
||||
S3_BUCKET: messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE: /run/runtime/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/runtime/s3_secret_access_key
|
||||
BROKER_URL_FILE: /run/runtime/broker_url
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
|
||||
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
|
||||
CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-30}
|
||||
CLEANUP_GRACE_SECONDS: ${CLEANUP_GRACE_SECONDS:-600}
|
||||
TLS_CA_FILE: /run/pki/ca.crt
|
||||
SERVICE_IDENTITY: worker
|
||||
SECRET_ROLE: worker
|
||||
stop_grace_period: 20s
|
||||
command:
|
||||
- python
|
||||
- -m
|
||||
- src.worker
|
||||
mem_limit: 768m
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
disable: true
|
||||
cpus: 1.0
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/client/worker:/run/identity:ro
|
||||
tmpfs:
|
||||
- /run/runtime:uid=10001,gid=10001,mode=0700
|
||||
- /tmp:uid=10001,gid=10001,mode=0700
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
api1:
|
||||
image: mtusi-messenger:lab7
|
||||
build: .
|
||||
environment:
|
||||
APP_HOST: 127.0.0.1
|
||||
APP_PORT: 8080
|
||||
APP_ENV: lab
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||
SERVICE_VERSION: lab7
|
||||
DATABASE_URL_FILE: /run/runtime/database_url
|
||||
CURSOR_SECRET_FILE: /run/runtime/cursor_key
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
S3_ENDPOINT: https://s3:9000
|
||||
S3_REGION: us-east-1
|
||||
S3_BUCKET: messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE: /run/runtime/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/runtime/s3_secret_access_key
|
||||
BROKER_URL_FILE: /run/runtime/broker_url
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
|
||||
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
|
||||
CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-30}
|
||||
CLEANUP_GRACE_SECONDS: ${CLEANUP_GRACE_SECONDS:-600}
|
||||
TLS_CA_FILE: /run/pki/ca.crt
|
||||
SERVICE_IDENTITY: api1
|
||||
SECRET_ROLE: api
|
||||
stop_grace_period: 20s
|
||||
mem_limit: 768m
|
||||
cpus: 1.0
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/client/api1:/run/identity:ro
|
||||
tmpfs:
|
||||
- /run/runtime:uid=10001,gid=10001,mode=0700
|
||||
- /tmp:uid=10001,gid=10001,mode=0700
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
api2:
|
||||
image: mtusi-messenger:lab7
|
||||
build: .
|
||||
environment:
|
||||
APP_HOST: 127.0.0.1
|
||||
APP_PORT: 8080
|
||||
APP_ENV: lab
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||
SERVICE_VERSION: lab7
|
||||
DATABASE_URL_FILE: /run/runtime/database_url
|
||||
CURSOR_SECRET_FILE: /run/runtime/cursor_key
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
S3_ENDPOINT: https://s3:9000
|
||||
S3_REGION: us-east-1
|
||||
S3_BUCKET: messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE: /run/runtime/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/runtime/s3_secret_access_key
|
||||
BROKER_URL_FILE: /run/runtime/broker_url
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
|
||||
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
|
||||
CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-30}
|
||||
CLEANUP_GRACE_SECONDS: ${CLEANUP_GRACE_SECONDS:-600}
|
||||
TLS_CA_FILE: /run/pki/ca.crt
|
||||
SERVICE_IDENTITY: api2
|
||||
SECRET_ROLE: api
|
||||
stop_grace_period: 20s
|
||||
mem_limit: 768m
|
||||
cpus: 1.0
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/client/api2:/run/identity:ro
|
||||
tmpfs:
|
||||
- /run/runtime:uid=10001,gid=10001,mode=0700
|
||||
- /tmp:uid=10001,gid=10001,mode=0700
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
cleanup:
|
||||
image: mtusi-messenger:lab7
|
||||
build: .
|
||||
environment:
|
||||
APP_HOST: 127.0.0.1
|
||||
APP_PORT: 8080
|
||||
APP_ENV: lab
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: https://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||
SERVICE_VERSION: lab7
|
||||
DATABASE_URL_FILE: /run/runtime/database_url
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
S3_ENDPOINT: https://s3:9000
|
||||
S3_REGION: us-east-1
|
||||
S3_BUCKET: messenger-attachments
|
||||
S3_ACCESS_KEY_ID_FILE: /run/runtime/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/runtime/s3_secret_access_key
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
|
||||
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
|
||||
CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-30}
|
||||
CLEANUP_GRACE_SECONDS: ${CLEANUP_GRACE_SECONDS:-600}
|
||||
TLS_CA_FILE: /run/pki/ca.crt
|
||||
SERVICE_IDENTITY: cleanup
|
||||
SECRET_ROLE: cleanup
|
||||
stop_grace_period: 20s
|
||||
command:
|
||||
- python
|
||||
- -m
|
||||
- src.cleanup
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
disable: true
|
||||
mem_limit: 512m
|
||||
cpus: 1.0
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/client/cleanup:/run/identity:ro
|
||||
tmpfs:
|
||||
- /run/runtime:uid=10001,gid=10001,mode=0700
|
||||
- /tmp:uid=10001,gid=10001,mode=0700
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
lb:
|
||||
image: haproxy:3.2.26@sha256:1242e4006ac3f1ed15871efadca3d8d089e76f720017a1c51747133ee40cc953
|
||||
ports:
|
||||
- 127.0.0.1:${HTTP_PORT:-8443}:8443
|
||||
volumes:
|
||||
- ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/server/lb:/run/server:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/client/lb:/run/identity:ro
|
||||
stop_grace_period: 3s
|
||||
mem_limit: 512m
|
||||
cpus: 1.0
|
||||
user: 99:99
|
||||
otel-collector:
|
||||
image: otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea
|
||||
command:
|
||||
- --config=/etc/otel/collector.yaml
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/otel/collector.yaml:/etc/otel/collector.yaml:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/client/collector:/run/identity:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/otel/htpasswd:/run/config/htpasswd:ro
|
||||
mem_limit: 256m
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 10s
|
||||
cpus: 1.0
|
||||
prometheus:
|
||||
image: prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06
|
||||
command:
|
||||
- --config.file=/etc/prometheus/prometheus.yaml
|
||||
- --storage.tsdb.path=/prometheus
|
||||
- --storage.tsdb.retention.time=24h
|
||||
- --storage.tsdb.retention.size=1GB
|
||||
- --web.listen-address=127.0.0.1:9091
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/otel/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro
|
||||
- prometheusdata:/prometheus
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/client/scraper:/run/identity:ro
|
||||
mem_limit: 512m
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 15s
|
||||
cpus: 1.0
|
||||
loki:
|
||||
image: grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7
|
||||
command:
|
||||
- -config.file=/etc/loki/loki.yaml
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/otel/loki.yaml:/etc/loki/loki.yaml:ro
|
||||
- lokidata:/loki
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
mem_limit: 512m
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 15s
|
||||
cpus: 1.0
|
||||
tempo:
|
||||
image: grafana/tempo:3.1.1@sha256:64e2fbd56d9c2b3412a4b430a58ea59e91a670b1e75f920a0c702213ad145044
|
||||
command:
|
||||
- -config.file=/etc/tempo/tempo.yaml
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/otel/tempo.yaml:/etc/tempo/tempo.yaml:ro
|
||||
- tempodata:/var/tempo
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
mem_limit: 768m
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 15s
|
||||
cpus: 1.0
|
||||
grafana:
|
||||
image: grafana/grafana:13.3.1@sha256:0615ec4fbd4072004b7d86b46ded63013a74b7d6eb1119273dd89e8fa25c13cf
|
||||
environment:
|
||||
GF_SECURITY_ADMIN_USER: admin
|
||||
GF_SECURITY_ADMIN_PASSWORD__FILE: /run/config/password
|
||||
GF_USERS_ALLOW_SIGN_UP: 'false'
|
||||
GF_AUTH_ANONYMOUS_ENABLED: 'false'
|
||||
GF_ANALYTICS_REPORTING_ENABLED: 'false'
|
||||
GF_ANALYTICS_CHECK_FOR_UPDATES: 'false'
|
||||
GF_SERVER_PROTOCOL: https
|
||||
GF_SERVER_CERT_FILE: /run/server/client.crt
|
||||
GF_SERVER_CERT_KEY: /run/server/client.key
|
||||
ports:
|
||||
- 127.0.0.1:${GRAFANA_PORT:-3309}:3000
|
||||
volumes:
|
||||
- grafanadata:/var/lib/grafana
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||
- ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/server/grafana:/run/server:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/grafana/password:/run/config/password:ro
|
||||
mem_limit: 384m
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 10s
|
||||
cpus: 1.0
|
||||
api1-tls:
|
||||
image: envoyproxy/envoy:v1.40.2@sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb
|
||||
user: 101:101
|
||||
network_mode: service:api1
|
||||
command:
|
||||
- envoy
|
||||
- -c
|
||||
- /etc/envoy/envoy.yaml
|
||||
- --concurrency
|
||||
- '2'
|
||||
- --disable-hot-restart
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/server/api1:/run/server:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/envoy/api1.yaml:/etc/envoy/envoy.yaml:ro
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: 128m
|
||||
cpus: 0.5
|
||||
depends_on:
|
||||
api1:
|
||||
condition: service_started
|
||||
stop_grace_period: 5s
|
||||
api2-tls:
|
||||
image: envoyproxy/envoy:v1.40.2@sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb
|
||||
user: 101:101
|
||||
network_mode: service:api2
|
||||
command:
|
||||
- envoy
|
||||
- -c
|
||||
- /etc/envoy/envoy.yaml
|
||||
- --concurrency
|
||||
- '2'
|
||||
- --disable-hot-restart
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/server/api2:/run/server:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/envoy/api2.yaml:/etc/envoy/envoy.yaml:ro
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: 128m
|
||||
cpus: 0.5
|
||||
depends_on:
|
||||
api2:
|
||||
condition: service_started
|
||||
stop_grace_period: 5s
|
||||
s3-tls:
|
||||
image: envoyproxy/envoy:v1.40.2@sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb
|
||||
user: 101:101
|
||||
network_mode: service:s3-storage
|
||||
command:
|
||||
- envoy
|
||||
- -c
|
||||
- /etc/envoy/envoy.yaml
|
||||
- --concurrency
|
||||
- '2'
|
||||
- --disable-hot-restart
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/server/s3:/run/server:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/envoy/s3.yaml:/etc/envoy/envoy.yaml:ro
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: 128m
|
||||
cpus: 0.5
|
||||
depends_on:
|
||||
s3-storage:
|
||||
condition: service_started
|
||||
stop_grace_period: 5s
|
||||
otel-collector-tls:
|
||||
image: envoyproxy/envoy:v1.40.2@sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb
|
||||
user: 101:101
|
||||
network_mode: service:otel-collector
|
||||
command:
|
||||
- envoy
|
||||
- -c
|
||||
- /etc/envoy/envoy.yaml
|
||||
- --concurrency
|
||||
- '2'
|
||||
- --disable-hot-restart
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/server/otel-collector:/run/server:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/envoy/otel-collector.yaml:/etc/envoy/envoy.yaml:ro
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: 128m
|
||||
cpus: 0.5
|
||||
depends_on:
|
||||
otel-collector:
|
||||
condition: service_started
|
||||
stop_grace_period: 5s
|
||||
prometheus-tls:
|
||||
image: envoyproxy/envoy:v1.40.2@sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb
|
||||
user: 101:101
|
||||
network_mode: service:prometheus
|
||||
command:
|
||||
- envoy
|
||||
- -c
|
||||
- /etc/envoy/envoy.yaml
|
||||
- --concurrency
|
||||
- '2'
|
||||
- --disable-hot-restart
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/server/prometheus:/run/server:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/envoy/prometheus.yaml:/etc/envoy/envoy.yaml:ro
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: 128m
|
||||
cpus: 0.5
|
||||
depends_on:
|
||||
prometheus:
|
||||
condition: service_started
|
||||
stop_grace_period: 5s
|
||||
loki-tls:
|
||||
image: envoyproxy/envoy:v1.40.2@sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb
|
||||
user: 101:101
|
||||
network_mode: service:loki
|
||||
command:
|
||||
- envoy
|
||||
- -c
|
||||
- /etc/envoy/envoy.yaml
|
||||
- --concurrency
|
||||
- '2'
|
||||
- --disable-hot-restart
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/server/loki:/run/server:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/envoy/loki.yaml:/etc/envoy/envoy.yaml:ro
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: 128m
|
||||
cpus: 0.5
|
||||
depends_on:
|
||||
loki:
|
||||
condition: service_started
|
||||
stop_grace_period: 5s
|
||||
tempo-tls:
|
||||
image: envoyproxy/envoy:v1.40.2@sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb
|
||||
user: 101:101
|
||||
network_mode: service:tempo
|
||||
command:
|
||||
- envoy
|
||||
- -c
|
||||
- /etc/envoy/envoy.yaml
|
||||
- --concurrency
|
||||
- '2'
|
||||
- --disable-hot-restart
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/server/tempo:/run/server:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/envoy/tempo.yaml:/etc/envoy/envoy.yaml:ro
|
||||
cap_drop:
|
||||
- ALL
|
||||
security_opt:
|
||||
- no-new-privileges:true
|
||||
mem_limit: 128m
|
||||
cpus: 0.5
|
||||
depends_on:
|
||||
tempo:
|
||||
condition: service_started
|
||||
stop_grace_period: 5s
|
||||
openbao:
|
||||
image: openbao/openbao:2.7.3@sha256:ba4b133eb9586630024e71a617e66f37f29cc3534cdd46a6233e098ceded8dc9
|
||||
command:
|
||||
- server
|
||||
- -config=/run/config/config.json
|
||||
volumes:
|
||||
- baodata:/bao/data
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/bao:/run/config:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/server/openbao:/run/server:ro
|
||||
ports:
|
||||
- 127.0.0.1:${BAO_PORT:-18200}:8200
|
||||
mem_limit: 512m
|
||||
cpus: 1.0
|
||||
environment:
|
||||
SKIP_SETCAP: 'true'
|
||||
cap_drop:
|
||||
- IPC_LOCK
|
||||
stop_grace_period: 10s
|
||||
depends_on:
|
||||
bao-volume-init:
|
||||
condition: service_completed_successfully
|
||||
bao-volume-init:
|
||||
image: mtusi-messenger:lab7
|
||||
user: 0:0
|
||||
network_mode: none
|
||||
volumes:
|
||||
- baodata:/bao/data
|
||||
command:
|
||||
- python
|
||||
- -c
|
||||
- import os; os.chown('/bao/data',100,1000)
|
||||
mem_limit: 64m
|
||||
cap_drop:
|
||||
- ALL
|
||||
cap_add:
|
||||
- CHOWN
|
||||
healthcheck:
|
||||
disable: true
|
||||
probe:
|
||||
image: mtusi-messenger:lab7
|
||||
profiles:
|
||||
- tools
|
||||
user: 0:0
|
||||
volumes:
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki:/run/all-pki:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro
|
||||
- ./runtime/${COMPOSE_PROJECT_NAME}/pki/client/operator:/run/identity:ro
|
||||
mem_limit: 256m
|
||||
cpus: 1.0
|
||||
healthcheck:
|
||||
disable: true
|
||||
volumes:
|
||||
pgdata: null
|
||||
s3data: null
|
||||
brokerdata: null
|
||||
prometheusdata: null
|
||||
lokidata: null
|
||||
tempodata: null
|
||||
grafanadata: null
|
||||
baodata: {}
|
||||
networks:
|
||||
default:
|
||||
ipam:
|
||||
config:
|
||||
- subnet: ${LAB7_APP_SUBNET:-10.240.70.0/24}
|
||||
+53
-27
@@ -1,37 +1,63 @@
|
||||
# Матрица доверия — заполнить в решении lab7
|
||||
# Матрица доверия — ЛР7
|
||||
|
||||
Это обязательная матрица покрытия. Для каждой строки укажите реальный порт, endpoint, CA, service identity, проверку SAN/ACL, срок жизни credentials и команду положительного/отрицательного теста. TLS шифрует и подтверждает сервер; mTLS также проверяет клиента. При доверенном CA всё равно нужно ограничивать разрешённую identity. Plaintext hop допустим только внутри закрытого локального transport/proxy boundary, без опубликованного обхода; границу и rationale нужно доказать.
|
||||
Общий публичный CA: `runtime/<project>/pki/ca.crt`. Leaf действуют 30 дней,
|
||||
CA — 365 дней. TLS проверяет CA и имя сервера. Для mTLS Envoy использует
|
||||
trusted_ca и match_typed_subject_alt_names с точным DNS SAN, без wildcard.
|
||||
|
||||
| Связь | Минимум на 3 | Дополнительно на 4 | Доказательство / конфиг |
|
||||
| Связь | Endpoint / серверная identity | Клиент / права | Проверка |
|
||||
| --- | --- | --- | --- |
|
||||
| Клиент → ingress/LB | TLS, CA + hostname, Bearer | Проверка expiry/revocation сессии и общего login rate limit | TODO |
|
||||
| LB → API (все реплики) | mTLS + allowlist LB identity | Ротация leaf без обхода проверки | TODO |
|
||||
| API/worker → PostgreSQL | TLS verify-full + раздельные ограниченные DB roles | Ротация credentials; mTLS — допустимое усиление | TODO |
|
||||
| API/worker → S3 | TLS + разные scoped credentials/prefix rights | Проверка denied prefix и ротация | TODO |
|
||||
| API/worker → broker | TLS + разные producer/consumer identities и ACL | mTLS + ограничение допустимых SAN/ролей | TODO |
|
||||
| API/worker → Collector | TLS; сеть/аутентификация запрещает произвольный ingest | mTLS с раздельными identities | TODO |
|
||||
| Collector → telemetry backends | TLS + scoped backend credentials или mTLS | Ротация и проверка least privilege | TODO |
|
||||
| Grafana → data sources | TLS с проверкой сервера, ограниченная identity | Отрицательные проверки доступа | TODO |
|
||||
| API/worker/agent → OpenBao | TLS + сервисный auth + scoped policy | Renewal/expiry/revocation | TODO |
|
||||
| Оператор → OpenBao/Grafana/S3 admin | TLS + authentication, доступ локальный/через защищённый канал | Разделение operator/application roles | TODO |
|
||||
| API → Redis/Valkey, если используется | TLS + ACL/пароль с минимальными правами | Ротация; mTLS по возможности | TODO |
|
||||
| Replication/кластерные каналы, если добавлены | TLS/mTLS либо подтверждённый шифрованный transport | Проверка заявленной модели отказа | TODO |
|
||||
| Клиент → LB | https://127.0.0.1:8443; SAN localhost/127.0.0.1 | Bearer, внешний client cert не нужен | tests/security.py, tls-check |
|
||||
| LB → API1/API2 | api1:8443, api2:8443; SAN api1/api2 | mTLS, только DNS SAN lb | tls-check: нет cert/чужой CA/wrong-role/expired/lb |
|
||||
| API/worker/cleanup → PostgreSQL | db:5432, SAN db | verify-full; роли api/worker/cleanup без DDL; мигратор messenger отдельно | policy-check, pg_stat_ssl |
|
||||
| API → S3 | https://s3:9000, SAN s3 | Write staging; Read originals/variants/system; List своего bucket | policy-check, test |
|
||||
| Worker → S3 | тот же | Read staging; Write originals/variants; без bucket Admin | policy-check |
|
||||
| Cleanup → S3 | тот же | Write staging/originals/variants для удаления, без Read/List/Admin | cleanup-сценарии |
|
||||
| API/worker → RabbitMQ | broker:5671, SAN broker | TLS; api публикует; worker читает и публикует retry; configure запрещён | policy-check, queue-check, retry-check |
|
||||
| API/worker → Collector | https://otel-collector:4318, SAN otel-collector | Разные Basic credentials поверх TLS; ingest | policy-check, telemetry-check |
|
||||
| Prometheus → Collector scrape | https://otel-collector:8889 | mTLS, только scraper/operator | telemetry-check |
|
||||
| Collector → Loki | https://loki:3100/otlp/v1/logs | mTLS SAN collector; только POST ingest | policy-check, telemetry-check |
|
||||
| Collector → Tempo | https://tempo:4318/v1/traces | mTLS SAN collector; выделенный OTLP listener | telemetry-check |
|
||||
| Grafana → Loki/Tempo/Prometheus | https://loki:3100, tempo:3200, prometheus:9090 | mTLS SAN grafana; query маршруты, без ingest/admin POST | policy-check, provisioning health |
|
||||
| API1/API2/worker/cleanup → OpenBao | https://openbao:8200, SAN openbao | cert auth, отдельный DNS SAN и role; свой KV path; TTL 900s/max 3600s | policy-check, bao-check |
|
||||
| Оператор → OpenBao | https://127.0.0.1:18200 | cert auth operator и operator policy; unseal с локального host | bao-status, restart-check |
|
||||
| Оператор → Grafana | https://127.0.0.1:3309 | admin/password, loopback публикация | telemetry-check |
|
||||
| Оператор → S3 admin | одноразовый bootstrap-клиент, HTTPS s3:9000 | Отдельный admin key; в приложение не монтируется | bootstrap, queue-check |
|
||||
| API → Redis/Valkey | N/A | Не используется, сессии в PostgreSQL | — |
|
||||
| Межузловая репликация | N/A | Кластеры не развёрнуты; OpenBao single-node Raft | — |
|
||||
|
||||
Нет выбранного компонента — отметьте N/A с причиной, а не оставляйте пустую строку. Внутренний публичный health listener, если нужен, минимален и изолирован; через него нельзя обращаться к бизнес-API без mTLS. Отдельно задокументируйте scrape/health/bootstrap каналы: они тоже не должны создавать обход.
|
||||
## Закрытые локальные hops
|
||||
|
||||
## Обязательные отрицательные проверки
|
||||
Envoy разделяет network namespace с backend, но не filesystem/pid namespace.
|
||||
API HTTP — 127.0.0.1:8080; Loki — 127.0.0.1:3101; Tempo query — 127.0.0.1:3201,
|
||||
OTLP — 127.0.0.1:4319; Prometheus — 127.0.0.1:9091; Collector OTLP — 127.0.0.1:4319,
|
||||
scrape — 127.0.0.1:8890, служебные health/metrics тоже loopback.
|
||||
Они не опубликованы и не доступны соседнему контейнеру по service IP.
|
||||
|
||||
1. HTTPS с правильным CA/hostname проходит; с пустым/чужим CA и неправильным hostname — ошибка верификации, не «сервер недоступен».
|
||||
2. LB→API: без client cert, с cert чужого CA, с запрещённой identity от доверенного CA — отказ; с разрешённой LB identity — успех.
|
||||
3. На 4 повторите набор для broker и Collector; ограничение на network policy не заменяет проверку identity.
|
||||
4. Пользователь вне чата не читает metadata/content и не прикрепляет чужой файл; поддельный X-User-Id не меняет Bearer identity.
|
||||
5. OpenBao app policy читает только свой secret/path; запись policy и чтение чужого path запрещены. Worker не получает admin credentials API/БД/S3.
|
||||
6. На 4 отзовите secret/cert и дождитесь контролируемого эффекта с учётом действующих соединений, TLS resumption и cache/TTL. Покажите новое подключение, иначе тест отзыва может ничего не проверить.
|
||||
SeaweedFS server/filer/volume и S3 gateway находятся в одном namespace и обращаются
|
||||
друг к другу через loopback. Единственный сетевой S3 listener — Envoy TLS 9000.
|
||||
Erlang distribution, epmd и служебные HTTP интерфейсы RabbitMQ ограничены loopback;
|
||||
локальное имя broker внутри самого контейнера разрешается в 127.0.0.1.
|
||||
PostgreSQL Unix socket используется операторскими psql/bootstrap командами.
|
||||
Docker health API проверяет локальный backend, а LB health проходит через mTLS.
|
||||
|
||||
## Bootstrap и эксплуатация
|
||||
## Bootstrap и жизненный цикл
|
||||
|
||||
В репозитории только открытые конфиги, policy templates и scripts. CA private key, leaf keys, root token, unseal shares и SecretID не коммитятся, не запекаются в образ и не печатаются в отчёте. Для локального стенда оператор создаёт их вне Git и передаёт через files/secrets с ограниченными правами. Опишите, кто имеет доступ к CA/unseal, что нужно после рестарта OpenBao и как восстановить работу.
|
||||
OpenBao не dev-mode, данные — в постоянном Raft volume. Init создаёт 5 shares с
|
||||
порогом 3. На Windows CA key/unseal находятся вне checkout в DPAPI-профиле текущего
|
||||
пользователя; на Linux профиль зашифрован AES-GCM с passphrase оператора.
|
||||
Все shares принадлежат одному доверенному оператору учебного стенда; разделение
|
||||
между независимыми хранителями не заявляется. Контейнеры профиль не получают.
|
||||
|
||||
OpenBao не использует dev-mode. Выберите persistent storage и auth метод (например AppRole с короткоживущим SecretID/response wrapping, cert auth или иная обоснованная identity). Не подменяйте root token постоянной переменной BAO_TOKEN в приложении. Рабочие tokens имеют policy, TTL и renewal/re-auth сценарий. Статические KV secrets на 3 допустимы при реальном чтении через сервисную identity; динамические DB credentials — хорошее расширение, но не обязательное название технологии.
|
||||
Первичный root token отзывается после настройки. API/worker получают KV через
|
||||
cert auth, а не через root token или постоянный общий BAO_TOKEN. Доступ API и worker
|
||||
разделён; токены обновляются, при max TTL выполняется новый cert login.
|
||||
При sealed/unavailable Bao загруженные значения используются только до deadline
|
||||
токена: затем ready/business → 503, worker откладывает новую обработку.
|
||||
После unseal сервисы восстанавливаются. Статические DB/S3/MQ credentials на сервере
|
||||
сами по себе не истекают вместе с токеном Bao — их ротация требует отдельных действий.
|
||||
|
||||
Разрешённый компромисс учебного стенда: ручной operator init/unseal, если он безопасно документирован и не нужен при каждом обычном рестарте API. Автоматическое хранение всех unseal shares рядом с OpenBao без защиты не считается решённым bootstrap.
|
||||
`restart` перезапускает реальные компоненты, затем host-оператор распечатывает Bao.
|
||||
`pki-renew` останавливает стенд, перевыпускает leaf, обновляет cert roles и запускает
|
||||
его заново. Это операция с перерывом, не zero-downtime rotation уровня 4.
|
||||
CA rollover и потеря операторского компьютера не автоматизированы: нужна резервная
|
||||
копия операторского профиля, runtime PKI и volumes. Корневой ключ не передаётся workload.
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"cases": [
|
||||
{
|
||||
"stopped_service": "api1",
|
||||
"upload_instance": "75b6aa7cb95540c999323767131cb1d7",
|
||||
"download_instance": "10e83d13717142dbaffa73dd6c83b489",
|
||||
"recovery_seconds": 6.104,
|
||||
"transitional_errors": 3,
|
||||
"same_original": true,
|
||||
"message_preserved": true
|
||||
},
|
||||
{
|
||||
"stopped_service": "api2",
|
||||
"upload_instance": "10e83d13717142dbaffa73dd6c83b489",
|
||||
"download_instance": "4dc62abfe2354262861e7fce54a323b1",
|
||||
"recovery_seconds": 6.194,
|
||||
"transitional_errors": 3,
|
||||
"same_original": true,
|
||||
"message_preserved": true
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"service_token_ttl": 2,
|
||||
"while_sealed": {
|
||||
"live": 200,
|
||||
"ready": 503,
|
||||
"business": 503
|
||||
},
|
||||
"after_unseal": 200,
|
||||
"old_session_preserved": true,
|
||||
"operator_unseal_outside_containers": true
|
||||
}
|
||||
@@ -0,0 +1,7 @@
|
||||
{
|
||||
"ttl_seconds": 2,
|
||||
"expiry_unchanged_on_restart": true,
|
||||
"before_restart": 200,
|
||||
"after_expiry_and_restart": 401,
|
||||
"new_login": 201
|
||||
}
|
||||
@@ -0,0 +1,525 @@
|
||||
{
|
||||
"public": {
|
||||
"service": "api1",
|
||||
"target_instance": "3fa4a84eb0b84c459736ab15b85ece29",
|
||||
"before": {
|
||||
"api1": {
|
||||
"instance_id": "3fa4a84eb0b84c459736ab15b85ece29",
|
||||
"container_id": "ca3d46860e5855de0d47b1c0104f2c4da75f2dd11b98e1fcff8108b9149854bf"
|
||||
},
|
||||
"api2": {
|
||||
"instance_id": "387a15e644694f798eab5c286d3553ee",
|
||||
"container_id": "941904ece80d85e8f8dc776043743d207c2bf9e91f232c1fdd8305d30c1b200b"
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"api1": {
|
||||
"id": "ca3d46860e5855de0d47b1c0104f2c4da75f2dd11b98e1fcff8108b9149854bf",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:44:46.319273654Z",
|
||||
"running": false,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"api1-tls": {
|
||||
"id": "a47b54dd359595c070f8dc7c742c36af3c30be869ea12a6aa43c3315608c4142",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:47.853720224Z",
|
||||
"running": false,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"api2": {
|
||||
"id": "941904ece80d85e8f8dc776043743d207c2bf9e91f232c1fdd8305d30c1b200b",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:44:46.474971556Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"api2-tls": {
|
||||
"id": "f59e183292726d51a0151178518fab1a6edb65974ae078e2421a7f69daed23ab",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:47.95930796Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"broker": {
|
||||
"id": "d63b0f66b7101e59d2d373723bbeef55daf22a826fad7b7cfdd8c22e3b814b0a",
|
||||
"image": "sha256:61f90c401a5b5ed2486771973ea92ad66046471eacab9c9149f1a6e091c91677",
|
||||
"started_at": "2026-12-02T15:44:29.009197972Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_brokerdata"
|
||||
]
|
||||
},
|
||||
"cleanup": {
|
||||
"id": "8c5fda1b136ffe7449b0166b8d81cce0804cb7d482300d56cf0298e66b4d1b08",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:44:46.651782642Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"db": {
|
||||
"id": "38ec3e0cab177127cb5118c3e5016caa5cdf126e9776538197c79a387c458d9b",
|
||||
"image": "sha256:665dc7b37ac52a17e298511414c21d23ffa4e6a6ef6225b3e5d59c7afb35e994",
|
||||
"started_at": "2026-12-02T15:44:29.216566482Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_pgdata"
|
||||
]
|
||||
},
|
||||
"grafana": {
|
||||
"id": "55891ceedff24a309e5bcfccf47b154bd8949908c2672c2f4536ef57fdaf7295",
|
||||
"image": "sha256:0615ec4fbd4072004b7d86b46ded63013a74b7d6eb1119273dd89e8fa25c13cf",
|
||||
"started_at": "2026-12-02T15:44:46.118740928Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "472",
|
||||
"volumes": [
|
||||
"mtusi-lab7_grafanadata"
|
||||
]
|
||||
},
|
||||
"lb": {
|
||||
"id": "08306c84b0bf1d2c9a40a7fe3d0c1f3713fbd7bca7fe4b7042f20d0cea0e8213",
|
||||
"image": "sha256:1242e4006ac3f1ed15871efadca3d8d089e76f720017a1c51747133ee40cc953",
|
||||
"started_at": "2026-12-02T15:44:47.207114455Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "99:99",
|
||||
"volumes": []
|
||||
},
|
||||
"loki": {
|
||||
"id": "20a8e0aedb4b395ec48515ce93e2e8c286928a7dc24faeed478af0c2517f96de",
|
||||
"image": "sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7",
|
||||
"started_at": "2026-12-02T15:44:47.41219432Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001",
|
||||
"volumes": [
|
||||
"mtusi-lab7_lokidata"
|
||||
]
|
||||
},
|
||||
"loki-tls": {
|
||||
"id": "43274e89343d6e7084748cce518e395fd0e26bf4533b6b82cd064f43a7529fe2",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:47.571999117Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"openbao": {
|
||||
"id": "eb1e14ebf03cc002f49792383e9bd917590954e70949b89f1eaea37462581c7a",
|
||||
"image": "sha256:ba4b133eb9586630024e71a617e66f37f29cc3534cdd46a6233e098ceded8dc9",
|
||||
"started_at": "2026-12-02T15:44:29.559090181Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "openbao",
|
||||
"volumes": [
|
||||
"mtusi-lab7_baodata"
|
||||
]
|
||||
},
|
||||
"otel-collector": {
|
||||
"id": "02e004fdf557d3671322ea1c22355c38e748758cfcee3339a00a620ce6c35764",
|
||||
"image": "sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea",
|
||||
"started_at": "2026-12-02T15:44:47.67769664Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001:10001",
|
||||
"volumes": []
|
||||
},
|
||||
"otel-collector-tls": {
|
||||
"id": "10ab06a075c8490e9db409381e57fb83444519308e375c8c1cd902edd33b7157",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:48.273502705Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"prometheus": {
|
||||
"id": "91d474d3250d8f3dab8dd99db3d2ee26c1d57005b189c11761a3e08081d19496",
|
||||
"image": "sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06",
|
||||
"started_at": "2026-12-02T15:44:46.822003752Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "nobody",
|
||||
"volumes": [
|
||||
"mtusi-lab7_prometheusdata"
|
||||
]
|
||||
},
|
||||
"prometheus-tls": {
|
||||
"id": "612d1f1509efb755145ff6ce6945316459cdc979defd03e9aa82944ad0c6e295",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:48.061973133Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"s3": {
|
||||
"id": "b2a89dd964d5b5fe45af06c27f322e6dd68b8e2a2d7a32003323746f3de3b7ce",
|
||||
"image": "sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15",
|
||||
"started_at": "2026-12-02T15:44:31.352056342Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"1432ccca7f9329bf205652067e548a1a9a523632f94d8bec600ed57a79bb09b3"
|
||||
]
|
||||
},
|
||||
"s3-storage": {
|
||||
"id": "a94fcd641d9e8ed28f946f940dcb06667c6b65be99413b9834aa519f437d7813",
|
||||
"image": "sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15",
|
||||
"started_at": "2026-12-02T15:44:28.674800296Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_s3data"
|
||||
]
|
||||
},
|
||||
"s3-tls": {
|
||||
"id": "0e93e3cbf64898c9c1b43a3062670bfafc8350bdadc40b16b73740234eca1a1d",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:29.422474882Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"tempo": {
|
||||
"id": "2ffad20b6acb5ae2990839fa93c39686b688544397685e77118c53d6e80cde77",
|
||||
"image": "sha256:64e2fbd56d9c2b3412a4b430a58ea59e91a670b1e75f920a0c702213ad145044",
|
||||
"started_at": "2026-12-02T15:44:47.015637558Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001:10001",
|
||||
"volumes": [
|
||||
"mtusi-lab7_tempodata"
|
||||
]
|
||||
},
|
||||
"tempo-tls": {
|
||||
"id": "bbb513a12be6f0114a2845ac6f835fbf19b42ddfb914c9bdcfbf1e9dbebf129e",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:48.170778392Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"worker": {
|
||||
"id": "6e0579589089c523aa597372e1460a8b2b2999fb86ea6b2e7cdaddad5b90986b",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:44:45.962419777Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
}
|
||||
},
|
||||
"stop_seconds": 1.27,
|
||||
"metrics": {
|
||||
"observed_instances_before": 2,
|
||||
"successful_writes": 107,
|
||||
"failed_attempts": 4,
|
||||
"first_recovery_seconds": 3.364
|
||||
}
|
||||
},
|
||||
"second_replica": {
|
||||
"service": "api2",
|
||||
"target_instance": "387a15e644694f798eab5c286d3553ee",
|
||||
"before": {
|
||||
"api1": {
|
||||
"instance_id": "75b6aa7cb95540c999323767131cb1d7",
|
||||
"container_id": "ca3d46860e5855de0d47b1c0104f2c4da75f2dd11b98e1fcff8108b9149854bf"
|
||||
},
|
||||
"api2": {
|
||||
"instance_id": "387a15e644694f798eab5c286d3553ee",
|
||||
"container_id": "941904ece80d85e8f8dc776043743d207c2bf9e91f232c1fdd8305d30c1b200b"
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"api1": {
|
||||
"id": "ca3d46860e5855de0d47b1c0104f2c4da75f2dd11b98e1fcff8108b9149854bf",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:45:13.977967932Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"api1-tls": {
|
||||
"id": "a47b54dd359595c070f8dc7c742c36af3c30be869ea12a6aa43c3315608c4142",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:45:14.51531666Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"api2": {
|
||||
"id": "941904ece80d85e8f8dc776043743d207c2bf9e91f232c1fdd8305d30c1b200b",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:44:46.474971556Z",
|
||||
"running": false,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"api2-tls": {
|
||||
"id": "f59e183292726d51a0151178518fab1a6edb65974ae078e2421a7f69daed23ab",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:45:14.56796726Z",
|
||||
"running": false,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"broker": {
|
||||
"id": "d63b0f66b7101e59d2d373723bbeef55daf22a826fad7b7cfdd8c22e3b814b0a",
|
||||
"image": "sha256:61f90c401a5b5ed2486771973ea92ad66046471eacab9c9149f1a6e091c91677",
|
||||
"started_at": "2026-12-02T15:44:29.009197972Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_brokerdata"
|
||||
]
|
||||
},
|
||||
"cleanup": {
|
||||
"id": "8c5fda1b136ffe7449b0166b8d81cce0804cb7d482300d56cf0298e66b4d1b08",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:44:46.651782642Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"db": {
|
||||
"id": "38ec3e0cab177127cb5118c3e5016caa5cdf126e9776538197c79a387c458d9b",
|
||||
"image": "sha256:665dc7b37ac52a17e298511414c21d23ffa4e6a6ef6225b3e5d59c7afb35e994",
|
||||
"started_at": "2026-12-02T15:44:29.216566482Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_pgdata"
|
||||
]
|
||||
},
|
||||
"grafana": {
|
||||
"id": "55891ceedff24a309e5bcfccf47b154bd8949908c2672c2f4536ef57fdaf7295",
|
||||
"image": "sha256:0615ec4fbd4072004b7d86b46ded63013a74b7d6eb1119273dd89e8fa25c13cf",
|
||||
"started_at": "2026-12-02T15:44:46.118740928Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "472",
|
||||
"volumes": [
|
||||
"mtusi-lab7_grafanadata"
|
||||
]
|
||||
},
|
||||
"lb": {
|
||||
"id": "08306c84b0bf1d2c9a40a7fe3d0c1f3713fbd7bca7fe4b7042f20d0cea0e8213",
|
||||
"image": "sha256:1242e4006ac3f1ed15871efadca3d8d089e76f720017a1c51747133ee40cc953",
|
||||
"started_at": "2026-12-02T15:44:47.207114455Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "99:99",
|
||||
"volumes": []
|
||||
},
|
||||
"loki": {
|
||||
"id": "20a8e0aedb4b395ec48515ce93e2e8c286928a7dc24faeed478af0c2517f96de",
|
||||
"image": "sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7",
|
||||
"started_at": "2026-12-02T15:44:47.41219432Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001",
|
||||
"volumes": [
|
||||
"mtusi-lab7_lokidata"
|
||||
]
|
||||
},
|
||||
"loki-tls": {
|
||||
"id": "43274e89343d6e7084748cce518e395fd0e26bf4533b6b82cd064f43a7529fe2",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:47.571999117Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"openbao": {
|
||||
"id": "eb1e14ebf03cc002f49792383e9bd917590954e70949b89f1eaea37462581c7a",
|
||||
"image": "sha256:ba4b133eb9586630024e71a617e66f37f29cc3534cdd46a6233e098ceded8dc9",
|
||||
"started_at": "2026-12-02T15:44:29.559090181Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "openbao",
|
||||
"volumes": [
|
||||
"mtusi-lab7_baodata"
|
||||
]
|
||||
},
|
||||
"otel-collector": {
|
||||
"id": "02e004fdf557d3671322ea1c22355c38e748758cfcee3339a00a620ce6c35764",
|
||||
"image": "sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea",
|
||||
"started_at": "2026-12-02T15:44:47.67769664Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001:10001",
|
||||
"volumes": []
|
||||
},
|
||||
"otel-collector-tls": {
|
||||
"id": "10ab06a075c8490e9db409381e57fb83444519308e375c8c1cd902edd33b7157",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:48.273502705Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"prometheus": {
|
||||
"id": "91d474d3250d8f3dab8dd99db3d2ee26c1d57005b189c11761a3e08081d19496",
|
||||
"image": "sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06",
|
||||
"started_at": "2026-12-02T15:44:46.822003752Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "nobody",
|
||||
"volumes": [
|
||||
"mtusi-lab7_prometheusdata"
|
||||
]
|
||||
},
|
||||
"prometheus-tls": {
|
||||
"id": "612d1f1509efb755145ff6ce6945316459cdc979defd03e9aa82944ad0c6e295",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:48.061973133Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"s3": {
|
||||
"id": "b2a89dd964d5b5fe45af06c27f322e6dd68b8e2a2d7a32003323746f3de3b7ce",
|
||||
"image": "sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15",
|
||||
"started_at": "2026-12-02T15:44:31.352056342Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"1432ccca7f9329bf205652067e548a1a9a523632f94d8bec600ed57a79bb09b3"
|
||||
]
|
||||
},
|
||||
"s3-storage": {
|
||||
"id": "a94fcd641d9e8ed28f946f940dcb06667c6b65be99413b9834aa519f437d7813",
|
||||
"image": "sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15",
|
||||
"started_at": "2026-12-02T15:44:28.674800296Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_s3data"
|
||||
]
|
||||
},
|
||||
"s3-tls": {
|
||||
"id": "0e93e3cbf64898c9c1b43a3062670bfafc8350bdadc40b16b73740234eca1a1d",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:29.422474882Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"tempo": {
|
||||
"id": "2ffad20b6acb5ae2990839fa93c39686b688544397685e77118c53d6e80cde77",
|
||||
"image": "sha256:64e2fbd56d9c2b3412a4b430a58ea59e91a670b1e75f920a0c702213ad145044",
|
||||
"started_at": "2026-12-02T15:44:47.015637558Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001:10001",
|
||||
"volumes": [
|
||||
"mtusi-lab7_tempodata"
|
||||
]
|
||||
},
|
||||
"tempo-tls": {
|
||||
"id": "bbb513a12be6f0114a2845ac6f835fbf19b42ddfb914c9bdcfbf1e9dbebf129e",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:48.170778392Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"worker": {
|
||||
"id": "6e0579589089c523aa597372e1460a8b2b2999fb86ea6b2e7cdaddad5b90986b",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:44:45.962419777Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
}
|
||||
},
|
||||
"stop_seconds": 1.292,
|
||||
"metrics": {
|
||||
"successful_writes": 106,
|
||||
"failed_attempts": 4,
|
||||
"first_recovery_seconds": 3.406,
|
||||
"replay_on_survivor": "PASS"
|
||||
}
|
||||
},
|
||||
"status": "PASS"
|
||||
}
|
||||
@@ -0,0 +1,502 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"started_at": 1796226476.8786554,
|
||||
"worker": {
|
||||
"started_at": 1796226508.3415306,
|
||||
"queued_jobs": [
|
||||
"3b02e417-85b1-48f0-9d13-e3eb40ce7a8c",
|
||||
"74c4fb02-d7ad-4a88-8cf3-8c4b8ac72735",
|
||||
"6e904651-188e-4bca-9b95-ee2fde11ae43"
|
||||
],
|
||||
"accepted_logs": [
|
||||
{
|
||||
"code_file_path": "/app/src/telemetry.py",
|
||||
"code_function_name": "event",
|
||||
"code_line_number": "119",
|
||||
"deployment_environment_name": "lab",
|
||||
"detected_level": "info",
|
||||
"event": "job.accepted",
|
||||
"flags": "3",
|
||||
"job_id": "3b02e417-85b1-48f0-9d13-e3eb40ce7a8c",
|
||||
"observed_timestamp": "1796226508513707900",
|
||||
"scope_name": "messenger",
|
||||
"service_instance_id": "dc39dce932da4ca69e34e13f7dfffd22",
|
||||
"service_name": "messenger-api",
|
||||
"service_version": "lab7",
|
||||
"severity_number": "9",
|
||||
"severity_text": "INFO",
|
||||
"span_id": "1130a776ec2a6ec9",
|
||||
"telemetry_sdk_language": "python",
|
||||
"telemetry_sdk_name": "opentelemetry",
|
||||
"telemetry_sdk_version": "1.45.2",
|
||||
"trace_id": "bb361763e074d10478006a3ceca0e4da",
|
||||
"timestamp_ns": "1796226508513559552",
|
||||
"body": "job.accepted"
|
||||
},
|
||||
{
|
||||
"code_file_path": "/app/src/telemetry.py",
|
||||
"code_function_name": "event",
|
||||
"code_line_number": "119",
|
||||
"deployment_environment_name": "lab",
|
||||
"detected_level": "info",
|
||||
"event": "job.accepted",
|
||||
"flags": "3",
|
||||
"job_id": "6e904651-188e-4bca-9b95-ee2fde11ae43",
|
||||
"observed_timestamp": "1796226509510836890",
|
||||
"scope_name": "messenger",
|
||||
"service_instance_id": "dc39dce932da4ca69e34e13f7dfffd22",
|
||||
"service_name": "messenger-api",
|
||||
"service_version": "lab7",
|
||||
"severity_number": "9",
|
||||
"severity_text": "INFO",
|
||||
"span_id": "ad8ed98eac7f26cc",
|
||||
"telemetry_sdk_language": "python",
|
||||
"telemetry_sdk_name": "opentelemetry",
|
||||
"telemetry_sdk_version": "1.45.2",
|
||||
"trace_id": "79e9251d01019f0911ab0ff5b47270d4",
|
||||
"timestamp_ns": "1796226509510674176",
|
||||
"body": "job.accepted"
|
||||
},
|
||||
{
|
||||
"code_file_path": "/app/src/telemetry.py",
|
||||
"code_function_name": "event",
|
||||
"code_line_number": "119",
|
||||
"deployment_environment_name": "lab",
|
||||
"detected_level": "info",
|
||||
"event": "job.accepted",
|
||||
"flags": "3",
|
||||
"job_id": "74c4fb02-d7ad-4a88-8cf3-8c4b8ac72735",
|
||||
"observed_timestamp": "1796226509006967348",
|
||||
"scope_name": "messenger",
|
||||
"service_instance_id": "dc39dce932da4ca69e34e13f7dfffd22",
|
||||
"service_name": "messenger-api",
|
||||
"service_version": "lab7",
|
||||
"severity_number": "9",
|
||||
"severity_text": "INFO",
|
||||
"span_id": "5c746e59454fe979",
|
||||
"telemetry_sdk_language": "python",
|
||||
"telemetry_sdk_name": "opentelemetry",
|
||||
"telemetry_sdk_version": "1.45.2",
|
||||
"trace_id": "3174a5fa24d59d8bd0f50639498409ec",
|
||||
"timestamp_ns": "1796226509006785024",
|
||||
"body": "job.accepted"
|
||||
}
|
||||
],
|
||||
"recovered_jobs": [
|
||||
{
|
||||
"trace_id": "65935a338658b11e2d8aa0974606a5a0",
|
||||
"span_id": "d79ac3a8893f696e",
|
||||
"event": "job.completed",
|
||||
"kind": "CONSUMER",
|
||||
"span_name": "attachment.process",
|
||||
"span_status": {},
|
||||
"span_duration_seconds": 0.805363066,
|
||||
"span_attributes": [
|
||||
{
|
||||
"key": "messaging.system",
|
||||
"value": {
|
||||
"stringValue": "rabbitmq"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messaging.operation.type",
|
||||
"value": {
|
||||
"stringValue": "process"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.type",
|
||||
"value": {
|
||||
"stringValue": "attachment.process.v1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.id",
|
||||
"value": {
|
||||
"stringValue": "3b02e417-85b1-48f0-9d13-e3eb40ce7a8c"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.attempt",
|
||||
"value": {
|
||||
"intValue": "1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.outcome",
|
||||
"value": {
|
||||
"stringValue": "success"
|
||||
}
|
||||
}
|
||||
],
|
||||
"log": {
|
||||
"attempt": "1",
|
||||
"code_file_path": "/app/src/telemetry.py",
|
||||
"code_function_name": "event",
|
||||
"code_line_number": "119",
|
||||
"deployment_environment_name": "lab",
|
||||
"detected_level": "info",
|
||||
"duration_seconds": "0.804816",
|
||||
"event": "job.completed",
|
||||
"flags": "3",
|
||||
"job_id": "3b02e417-85b1-48f0-9d13-e3eb40ce7a8c",
|
||||
"observed_timestamp": "1796226518359786942",
|
||||
"outcome": "success",
|
||||
"scope_name": "messenger",
|
||||
"service_instance_id": "57062dd2b8044a1091ea5df1f384dcdb",
|
||||
"service_name": "messenger-worker",
|
||||
"service_version": "lab7",
|
||||
"severity_number": "9",
|
||||
"severity_text": "INFO",
|
||||
"span_id": "d79ac3a8893f696e",
|
||||
"telemetry_sdk_language": "python",
|
||||
"telemetry_sdk_name": "opentelemetry",
|
||||
"telemetry_sdk_version": "1.45.2",
|
||||
"trace_id": "65935a338658b11e2d8aa0974606a5a0",
|
||||
"timestamp_ns": "1796226518359643392",
|
||||
"body": "job.completed"
|
||||
}
|
||||
},
|
||||
{
|
||||
"trace_id": "e86118811ffd13cb294d94f7b36caefe",
|
||||
"span_id": "d2f2981c1dede2b5",
|
||||
"event": "job.completed",
|
||||
"kind": "CONSUMER",
|
||||
"span_name": "attachment.process",
|
||||
"span_status": {},
|
||||
"span_duration_seconds": 1.206685474,
|
||||
"span_attributes": [
|
||||
{
|
||||
"key": "messaging.system",
|
||||
"value": {
|
||||
"stringValue": "rabbitmq"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messaging.operation.type",
|
||||
"value": {
|
||||
"stringValue": "process"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.type",
|
||||
"value": {
|
||||
"stringValue": "attachment.process.v1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.id",
|
||||
"value": {
|
||||
"stringValue": "74c4fb02-d7ad-4a88-8cf3-8c4b8ac72735"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.attempt",
|
||||
"value": {
|
||||
"intValue": "1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.outcome",
|
||||
"value": {
|
||||
"stringValue": "success"
|
||||
}
|
||||
}
|
||||
],
|
||||
"log": {
|
||||
"attempt": "1",
|
||||
"code_file_path": "/app/src/telemetry.py",
|
||||
"code_function_name": "event",
|
||||
"code_line_number": "119",
|
||||
"deployment_environment_name": "lab",
|
||||
"detected_level": "info",
|
||||
"duration_seconds": "1.206367",
|
||||
"event": "job.completed",
|
||||
"flags": "3",
|
||||
"job_id": "74c4fb02-d7ad-4a88-8cf3-8c4b8ac72735",
|
||||
"observed_timestamp": "1796226519577828107",
|
||||
"outcome": "success",
|
||||
"scope_name": "messenger",
|
||||
"service_instance_id": "57062dd2b8044a1091ea5df1f384dcdb",
|
||||
"service_name": "messenger-worker",
|
||||
"service_version": "lab7",
|
||||
"severity_number": "9",
|
||||
"severity_text": "INFO",
|
||||
"span_id": "d2f2981c1dede2b5",
|
||||
"telemetry_sdk_language": "python",
|
||||
"telemetry_sdk_name": "opentelemetry",
|
||||
"telemetry_sdk_version": "1.45.2",
|
||||
"trace_id": "e86118811ffd13cb294d94f7b36caefe",
|
||||
"timestamp_ns": "1796226519577670400",
|
||||
"body": "job.completed"
|
||||
}
|
||||
},
|
||||
{
|
||||
"trace_id": "ebbe8c873e80420fcf7bf77cb7529f78",
|
||||
"span_id": "e53c2ba89200924b",
|
||||
"event": "job.completed",
|
||||
"kind": "CONSUMER",
|
||||
"span_name": "attachment.process",
|
||||
"span_status": {},
|
||||
"span_duration_seconds": 1.207498941,
|
||||
"span_attributes": [
|
||||
{
|
||||
"key": "messaging.system",
|
||||
"value": {
|
||||
"stringValue": "rabbitmq"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messaging.operation.type",
|
||||
"value": {
|
||||
"stringValue": "process"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.type",
|
||||
"value": {
|
||||
"stringValue": "attachment.process.v1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.id",
|
||||
"value": {
|
||||
"stringValue": "6e904651-188e-4bca-9b95-ee2fde11ae43"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.attempt",
|
||||
"value": {
|
||||
"intValue": "1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.outcome",
|
||||
"value": {
|
||||
"stringValue": "success"
|
||||
}
|
||||
}
|
||||
],
|
||||
"log": {
|
||||
"attempt": "1",
|
||||
"code_file_path": "/app/src/telemetry.py",
|
||||
"code_function_name": "event",
|
||||
"code_line_number": "119",
|
||||
"deployment_environment_name": "lab",
|
||||
"detected_level": "info",
|
||||
"duration_seconds": "1.207224",
|
||||
"event": "job.completed",
|
||||
"flags": "3",
|
||||
"job_id": "6e904651-188e-4bca-9b95-ee2fde11ae43",
|
||||
"observed_timestamp": "1796226520807680901",
|
||||
"outcome": "success",
|
||||
"scope_name": "messenger",
|
||||
"service_instance_id": "57062dd2b8044a1091ea5df1f384dcdb",
|
||||
"service_name": "messenger-worker",
|
||||
"service_version": "lab7",
|
||||
"severity_number": "9",
|
||||
"severity_text": "INFO",
|
||||
"span_id": "e53c2ba89200924b",
|
||||
"telemetry_sdk_language": "python",
|
||||
"telemetry_sdk_name": "opentelemetry",
|
||||
"telemetry_sdk_version": "1.45.2",
|
||||
"trace_id": "ebbe8c873e80420fcf7bf77cb7529f78",
|
||||
"timestamp_ns": "1796226520807538176",
|
||||
"body": "job.completed"
|
||||
}
|
||||
}
|
||||
],
|
||||
"recovered_at": 1796226527.5980973
|
||||
},
|
||||
"postgresql": {
|
||||
"started_at": 1796226528.2498581,
|
||||
"request": {
|
||||
"trace_id": "f47cbed4814072f969480c158bf78af8",
|
||||
"span_id": "3439a36b55124d6a",
|
||||
"event": "http.completed",
|
||||
"kind": "SERVER",
|
||||
"span_name": "GET /api/v1/users/me",
|
||||
"span_status": {
|
||||
"code": "STATUS_CODE_ERROR"
|
||||
},
|
||||
"span_duration_seconds": 3.000927393,
|
||||
"span_attributes": [
|
||||
{
|
||||
"key": "http.request.method",
|
||||
"value": {
|
||||
"stringValue": "GET"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "http.route",
|
||||
"value": {
|
||||
"stringValue": "/api/v1/users/me"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.request_id",
|
||||
"value": {
|
||||
"stringValue": "a1326a13-0ccd-46b5-b639-7f570a10123c"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "http.response.status_code",
|
||||
"value": {
|
||||
"intValue": "503"
|
||||
}
|
||||
}
|
||||
],
|
||||
"log": {
|
||||
"code_file_path": "/app/src/telemetry.py",
|
||||
"code_function_name": "event",
|
||||
"code_line_number": "119",
|
||||
"deployment_environment_name": "lab",
|
||||
"detected_level": "info",
|
||||
"duration_seconds": "3.000811",
|
||||
"event": "http.completed",
|
||||
"flags": "3",
|
||||
"method": "GET",
|
||||
"observed_timestamp": "1796226531255024469",
|
||||
"request_id": "a1326a13-0ccd-46b5-b639-7f570a10123c",
|
||||
"route": "/api/v1/users/me",
|
||||
"scope_name": "messenger",
|
||||
"service_instance_id": "dc39dce932da4ca69e34e13f7dfffd22",
|
||||
"service_name": "messenger-api",
|
||||
"service_version": "lab7",
|
||||
"severity_number": "9",
|
||||
"severity_text": "INFO",
|
||||
"span_id": "3439a36b55124d6a",
|
||||
"status_code": "503",
|
||||
"telemetry_sdk_language": "python",
|
||||
"telemetry_sdk_name": "opentelemetry",
|
||||
"telemetry_sdk_version": "1.45.2",
|
||||
"trace_id": "f47cbed4814072f969480c158bf78af8",
|
||||
"timestamp_ns": "1796226531254957056",
|
||||
"body": "http.completed"
|
||||
}
|
||||
},
|
||||
"dependency_logs": [
|
||||
{
|
||||
"code_file_path": "/app/src/telemetry.py",
|
||||
"code_function_name": "event",
|
||||
"code_line_number": "119",
|
||||
"deployment_environment_name": "lab",
|
||||
"detected_level": "error",
|
||||
"event": "dependency.postgresql_unavailable",
|
||||
"flags": "3",
|
||||
"observed_timestamp": "1796226531254625285",
|
||||
"scope_name": "messenger",
|
||||
"service_instance_id": "dc39dce932da4ca69e34e13f7dfffd22",
|
||||
"service_name": "messenger-api",
|
||||
"service_version": "lab7",
|
||||
"severity_number": "17",
|
||||
"severity_text": "ERROR",
|
||||
"span_id": "3439a36b55124d6a",
|
||||
"telemetry_sdk_language": "python",
|
||||
"telemetry_sdk_name": "opentelemetry",
|
||||
"telemetry_sdk_version": "1.45.2",
|
||||
"trace_id": "f47cbed4814072f969480c158bf78af8",
|
||||
"timestamp_ns": "1796226531254500352",
|
||||
"body": "dependency.postgresql_unavailable"
|
||||
},
|
||||
{
|
||||
"code_file_path": "/app/src/telemetry.py",
|
||||
"code_function_name": "event",
|
||||
"code_line_number": "119",
|
||||
"deployment_environment_name": "lab",
|
||||
"detected_level": "error",
|
||||
"event": "dependency.postgresql_unavailable",
|
||||
"flags": "3",
|
||||
"observed_timestamp": "1796226531661176830",
|
||||
"scope_name": "messenger",
|
||||
"service_instance_id": "dc39dce932da4ca69e34e13f7dfffd22",
|
||||
"service_name": "messenger-api",
|
||||
"service_version": "lab7",
|
||||
"severity_number": "17",
|
||||
"severity_text": "ERROR",
|
||||
"span_id": "4549a5d264aa6678",
|
||||
"telemetry_sdk_language": "python",
|
||||
"telemetry_sdk_name": "opentelemetry",
|
||||
"telemetry_sdk_version": "1.45.2",
|
||||
"trace_id": "e10834d1f6ad2885c1f23c8305a34a40",
|
||||
"timestamp_ns": "1796226531661018368",
|
||||
"body": "dependency.postgresql_unavailable"
|
||||
},
|
||||
{
|
||||
"code_file_path": "/app/src/telemetry.py",
|
||||
"code_function_name": "event",
|
||||
"code_line_number": "119",
|
||||
"deployment_environment_name": "lab",
|
||||
"detected_level": "error",
|
||||
"event": "dependency.postgresql_unavailable",
|
||||
"flags": "3",
|
||||
"observed_timestamp": "1796226531698244207",
|
||||
"scope_name": "messenger",
|
||||
"service_instance_id": "4dc62abfe2354262861e7fce54a323b1",
|
||||
"service_name": "messenger-api",
|
||||
"service_version": "lab7",
|
||||
"severity_number": "17",
|
||||
"severity_text": "ERROR",
|
||||
"span_id": "cebc38ad0bda73a3",
|
||||
"telemetry_sdk_language": "python",
|
||||
"telemetry_sdk_name": "opentelemetry",
|
||||
"telemetry_sdk_version": "1.45.2",
|
||||
"trace_id": "8274d7e29f61255389a9c86ebeee0127",
|
||||
"timestamp_ns": "1796226531698030848",
|
||||
"body": "dependency.postgresql_unavailable"
|
||||
}
|
||||
],
|
||||
"error_series": [
|
||||
{
|
||||
"metric": {
|
||||
"__name__": "messenger_http_requests_total",
|
||||
"deployment_environment_name": "lab",
|
||||
"exported_instance": "dc39dce932da4ca69e34e13f7dfffd22",
|
||||
"exported_job": "messenger-api",
|
||||
"instance": "otel-collector:8889",
|
||||
"job": "messenger",
|
||||
"method": "GET",
|
||||
"otel_scope_name": "messenger",
|
||||
"route": "/api/v1/users/me",
|
||||
"service_instance_id": "dc39dce932da4ca69e34e13f7dfffd22",
|
||||
"service_name": "messenger-api",
|
||||
"service_version": "lab7",
|
||||
"status_class": "5xx",
|
||||
"telemetry_sdk_language": "python",
|
||||
"telemetry_sdk_name": "opentelemetry",
|
||||
"telemetry_sdk_version": "1.45.2"
|
||||
},
|
||||
"value": [
|
||||
1796226536.007,
|
||||
"1"
|
||||
]
|
||||
},
|
||||
{
|
||||
"metric": {
|
||||
"__name__": "messenger_http_requests_total",
|
||||
"deployment_environment_name": "lab",
|
||||
"exported_instance": "4dc62abfe2354262861e7fce54a323b1",
|
||||
"exported_job": "messenger-api",
|
||||
"instance": "otel-collector:8889",
|
||||
"job": "messenger",
|
||||
"method": "GET",
|
||||
"otel_scope_name": "messenger",
|
||||
"route": "/api/v1/users/me",
|
||||
"service_instance_id": "4dc62abfe2354262861e7fce54a323b1",
|
||||
"service_name": "messenger-api",
|
||||
"service_version": "lab7",
|
||||
"status_class": "5xx",
|
||||
"telemetry_sdk_language": "python",
|
||||
"telemetry_sdk_name": "opentelemetry",
|
||||
"telemetry_sdk_version": "1.45.2"
|
||||
},
|
||||
"value": [
|
||||
1796226536.007,
|
||||
"1"
|
||||
]
|
||||
}
|
||||
],
|
||||
"recovered_at": 1796226537.7263503,
|
||||
"recovered_status": 200
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"json_limit_bytes": 65536,
|
||||
"chunked_limit": "PASS",
|
||||
"login_429": 40,
|
||||
"retry_after": "PASS",
|
||||
"recovered_login": 201,
|
||||
"measurement_context": "Linux application image, one CPU",
|
||||
"argon2id": {
|
||||
"memory_kib": 19456,
|
||||
"t": 2,
|
||||
"p": 1,
|
||||
"timings": {
|
||||
"hash": {
|
||||
"p50_ms": 19.495,
|
||||
"p95_ms": 22.476,
|
||||
"samples": 30
|
||||
},
|
||||
"verify": {
|
||||
"p50_ms": 18.695,
|
||||
"p95_ms": 21.82,
|
||||
"samples": 30
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,17 @@
|
||||
{
|
||||
"lab": 7,
|
||||
"workload": "closed-loop POST messages; no automatic retries",
|
||||
"requested_duration_seconds": 30.0,
|
||||
"elapsed_seconds": 30.009,
|
||||
"concurrency": 4,
|
||||
"successful_requests": 6875,
|
||||
"failed_requests": 0,
|
||||
"error_ratio": 0.0,
|
||||
"successful_rps": 229.097,
|
||||
"successful_latency_ms": {
|
||||
"p50": 12.55,
|
||||
"p95": 35.115,
|
||||
"p99": 61.499
|
||||
},
|
||||
"note": "Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead."
|
||||
}
|
||||
@@ -0,0 +1,151 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"cases": [
|
||||
{
|
||||
"stopped": "otel-collector",
|
||||
"duration_seconds": 36.68,
|
||||
"confirmed_messages": 6,
|
||||
"ready_attachments": 6,
|
||||
"business_ready": 200,
|
||||
"telemetry_recovered": {
|
||||
"trace_id": "a3eeb183c009661694ecce6a90fd475b",
|
||||
"span_id": "b5ecd256d8a2302c",
|
||||
"event": "http.completed",
|
||||
"kind": "SERVER",
|
||||
"span_name": "GET /api/v1/users/me",
|
||||
"span_status": {},
|
||||
"span_duration_seconds": 0.003594574,
|
||||
"span_attributes": [
|
||||
{
|
||||
"key": "http.request.method",
|
||||
"value": {
|
||||
"stringValue": "GET"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "http.route",
|
||||
"value": {
|
||||
"stringValue": "/api/v1/users/me"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.request_id",
|
||||
"value": {
|
||||
"stringValue": "a1d722d5-8edd-4bd5-939b-b5893b344cbd"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "http.response.status_code",
|
||||
"value": {
|
||||
"intValue": "200"
|
||||
}
|
||||
}
|
||||
],
|
||||
"log": {
|
||||
"code_file_path": "/app/src/telemetry.py",
|
||||
"code_function_name": "event",
|
||||
"code_line_number": "119",
|
||||
"deployment_environment_name": "lab",
|
||||
"detected_level": "info",
|
||||
"duration_seconds": "0.00331",
|
||||
"event": "http.completed",
|
||||
"flags": "3",
|
||||
"method": "GET",
|
||||
"observed_timestamp": "1796226577238917343",
|
||||
"request_id": "a1d722d5-8edd-4bd5-939b-b5893b344cbd",
|
||||
"route": "/api/v1/users/me",
|
||||
"scope_name": "messenger",
|
||||
"service_instance_id": "4dc62abfe2354262861e7fce54a323b1",
|
||||
"service_name": "messenger-api",
|
||||
"service_version": "lab7",
|
||||
"severity_number": "9",
|
||||
"severity_text": "INFO",
|
||||
"span_id": "b5ecd256d8a2302c",
|
||||
"status_code": "200",
|
||||
"telemetry_sdk_language": "python",
|
||||
"telemetry_sdk_name": "opentelemetry",
|
||||
"telemetry_sdk_version": "1.45.2",
|
||||
"trace_id": "a3eeb183c009661694ecce6a90fd475b",
|
||||
"timestamp_ns": "1796226577238813440",
|
||||
"body": "http.completed"
|
||||
}
|
||||
}
|
||||
},
|
||||
{
|
||||
"stopped": "loki",
|
||||
"duration_seconds": 37.62,
|
||||
"confirmed_messages": 6,
|
||||
"ready_attachments": 6,
|
||||
"business_ready": 200,
|
||||
"telemetry_recovered": {
|
||||
"trace_id": "4bd56dba58a3516bf62e8d18a396a3b6",
|
||||
"span_id": "b9c8b1557bb07a24",
|
||||
"event": "http.completed",
|
||||
"kind": "SERVER",
|
||||
"span_name": "GET /api/v1/users/me",
|
||||
"span_status": {},
|
||||
"span_duration_seconds": 0.003001225,
|
||||
"span_attributes": [
|
||||
{
|
||||
"key": "messenger.request_id",
|
||||
"value": {
|
||||
"stringValue": "6092baa7-8398-4c33-8bc9-1adfae919923"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "http.request.method",
|
||||
"value": {
|
||||
"stringValue": "GET"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "http.response.status_code",
|
||||
"value": {
|
||||
"intValue": "200"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "http.route",
|
||||
"value": {
|
||||
"stringValue": "/api/v1/users/me"
|
||||
}
|
||||
}
|
||||
],
|
||||
"log": {
|
||||
"__stream_shard__": "4",
|
||||
"code_file_path": "/app/src/telemetry.py",
|
||||
"code_function_name": "event",
|
||||
"code_line_number": "119",
|
||||
"deployment_environment_name": "lab",
|
||||
"detected_level": "info",
|
||||
"duration_seconds": "0.002762",
|
||||
"event": "http.completed",
|
||||
"flags": "3",
|
||||
"method": "GET",
|
||||
"observed_timestamp": "1796226621911558335",
|
||||
"request_id": "6092baa7-8398-4c33-8bc9-1adfae919923",
|
||||
"route": "/api/v1/users/me",
|
||||
"scope_name": "messenger",
|
||||
"service_instance_id": "4dc62abfe2354262861e7fce54a323b1",
|
||||
"service_name": "messenger-api",
|
||||
"service_version": "lab7",
|
||||
"severity_number": "9",
|
||||
"severity_text": "INFO",
|
||||
"span_id": "b9c8b1557bb07a24",
|
||||
"status_code": "200",
|
||||
"telemetry_sdk_language": "python",
|
||||
"telemetry_sdk_name": "opentelemetry",
|
||||
"telemetry_sdk_version": "1.45.2",
|
||||
"trace_id": "4bd56dba58a3516bf62e8d18a396a3b6",
|
||||
"timestamp_ns": "1796226621911420928",
|
||||
"body": "http.completed"
|
||||
}
|
||||
}
|
||||
}
|
||||
],
|
||||
"history_after_restart": "PASS",
|
||||
"oom_killed": false,
|
||||
"preserved_trace_id": "028e536339a97e81faf441b4e4a37f3d",
|
||||
"same_volumes": true,
|
||||
"loss_policy": "Bounded in-memory SDK/Collector queues; telemetry during outage may be lost."
|
||||
}
|
||||
@@ -0,0 +1,22 @@
|
||||
{
|
||||
"idempotency_after_restart": "PASS",
|
||||
"public_persistence": "PASS",
|
||||
"cursor_after_restart": "PASS",
|
||||
"logout_after_restart": "PASS",
|
||||
"migration_replay": "PASS",
|
||||
"database": {
|
||||
"users": 270,
|
||||
"chats": 95,
|
||||
"members": 186,
|
||||
"messages": 289,
|
||||
"sessions": 261,
|
||||
"migrations": 4,
|
||||
"idempotency_keys": 287,
|
||||
"attachments": 52,
|
||||
"message_attachments": 20,
|
||||
"upload_intents": 0,
|
||||
"expiry_fingerprint": "19ca8e16e0a8d5e08d637a44f8ec3bdd",
|
||||
"passwords_are_argon2id": true,
|
||||
"session_hashes_only": true
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,82 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"results": {
|
||||
"wrong_certificate_role": 400,
|
||||
"local_boundaries": {
|
||||
"api1:8080": true,
|
||||
"api2:8080": true,
|
||||
"s3:7333": true,
|
||||
"s3:8080": true,
|
||||
"s3:8888": true,
|
||||
"s3:9333": true,
|
||||
"s3:19001": true,
|
||||
"broker:4369": true,
|
||||
"broker:5672": true,
|
||||
"broker:15672": true,
|
||||
"broker:15692": true,
|
||||
"broker:25672": true,
|
||||
"otel-collector:4319": true,
|
||||
"otel-collector:8890": true,
|
||||
"otel-collector:8888": true,
|
||||
"otel-collector:13133": true,
|
||||
"loki:3101": true,
|
||||
"loki:9095": true,
|
||||
"tempo:3201": true,
|
||||
"tempo:4319": true,
|
||||
"tempo:9095": true,
|
||||
"prometheus:9091": true,
|
||||
"openbao:8201": true
|
||||
},
|
||||
"api1": {
|
||||
"own_secret": true,
|
||||
"ttl_seconds": 900,
|
||||
"other_secret": 403,
|
||||
"write_policy": 403,
|
||||
"revoked_token": 403
|
||||
},
|
||||
"api2": {
|
||||
"own_secret": true,
|
||||
"ttl_seconds": 900,
|
||||
"other_secret": 403,
|
||||
"write_policy": 403,
|
||||
"revoked_token": 403
|
||||
},
|
||||
"worker": {
|
||||
"own_secret": true,
|
||||
"ttl_seconds": 900,
|
||||
"other_secret": 403,
|
||||
"write_policy": 403,
|
||||
"revoked_token": 403
|
||||
},
|
||||
"cleanup": {
|
||||
"own_secret": true,
|
||||
"ttl_seconds": 900,
|
||||
"other_secret": 403,
|
||||
"write_policy": 403,
|
||||
"revoked_token": 403
|
||||
},
|
||||
"database": {
|
||||
"api:tls": true,
|
||||
"api:ddl_denied": true,
|
||||
"worker:tls": true,
|
||||
"worker:ddl_denied": true,
|
||||
"worker:users_denied": true,
|
||||
"cleanup:tls": true,
|
||||
"cleanup:ddl_denied": true,
|
||||
"cleanup:users_denied": true
|
||||
},
|
||||
"dependencies": {
|
||||
"api:s3_denied": true,
|
||||
"api:bucket_admin_denied": true,
|
||||
"api:amqps": true,
|
||||
"api:broker_denied": true,
|
||||
"worker:s3_denied": true,
|
||||
"worker:bucket_admin_denied": true,
|
||||
"worker:amqps": true,
|
||||
"worker:broker_denied": true,
|
||||
"grafana_ingest": true,
|
||||
"collector_query": true,
|
||||
"anonymous_otlp": true
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,490 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"upload_with_stopped_worker": 202,
|
||||
"pending_content": 409,
|
||||
"same_attachment_after_api_broker_restart": true,
|
||||
"original_and_thumbnail": "PASS",
|
||||
"duplicate_noop": "PASS",
|
||||
"job_schema": "PASS",
|
||||
"anonymous_s3": 403,
|
||||
"before": {
|
||||
"api1": {
|
||||
"id": "ca3d46860e5855de0d47b1c0104f2c4da75f2dd11b98e1fcff8108b9149854bf",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:42:16.958154294Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"api1-tls": {
|
||||
"id": "a47b54dd359595c070f8dc7c742c36af3c30be869ea12a6aa43c3315608c4142",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:42:17.490348579Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"api2": {
|
||||
"id": "941904ece80d85e8f8dc776043743d207c2bf9e91f232c1fdd8305d30c1b200b",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:42:17.133460452Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"api2-tls": {
|
||||
"id": "f59e183292726d51a0151178518fab1a6edb65974ae078e2421a7f69daed23ab",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:42:17.603460556Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"broker": {
|
||||
"id": "d63b0f66b7101e59d2d373723bbeef55daf22a826fad7b7cfdd8c22e3b814b0a",
|
||||
"image": "sha256:61f90c401a5b5ed2486771973ea92ad66046471eacab9c9149f1a6e091c91677",
|
||||
"started_at": "2026-12-02T15:40:36.248343829Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_brokerdata"
|
||||
]
|
||||
},
|
||||
"cleanup": {
|
||||
"id": "8c5fda1b136ffe7449b0166b8d81cce0804cb7d482300d56cf0298e66b4d1b08",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:42:17.315671239Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"db": {
|
||||
"id": "38ec3e0cab177127cb5118c3e5016caa5cdf126e9776538197c79a387c458d9b",
|
||||
"image": "sha256:665dc7b37ac52a17e298511414c21d23ffa4e6a6ef6225b3e5d59c7afb35e994",
|
||||
"started_at": "2026-12-02T15:39:02.136046985Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_pgdata"
|
||||
]
|
||||
},
|
||||
"grafana": {
|
||||
"id": "55891ceedff24a309e5bcfccf47b154bd8949908c2672c2f4536ef57fdaf7295",
|
||||
"image": "sha256:0615ec4fbd4072004b7d86b46ded63013a74b7d6eb1119273dd89e8fa25c13cf",
|
||||
"started_at": "2026-12-02T15:39:22.550012775Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "472",
|
||||
"volumes": [
|
||||
"mtusi-lab7_grafanadata"
|
||||
]
|
||||
},
|
||||
"lb": {
|
||||
"id": "08306c84b0bf1d2c9a40a7fe3d0c1f3713fbd7bca7fe4b7042f20d0cea0e8213",
|
||||
"image": "sha256:1242e4006ac3f1ed15871efadca3d8d089e76f720017a1c51747133ee40cc953",
|
||||
"started_at": "2026-12-02T15:39:22.736582521Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "99:99",
|
||||
"volumes": []
|
||||
},
|
||||
"loki": {
|
||||
"id": "20a8e0aedb4b395ec48515ce93e2e8c286928a7dc24faeed478af0c2517f96de",
|
||||
"image": "sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7",
|
||||
"started_at": "2026-12-02T15:39:20.776200797Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001",
|
||||
"volumes": [
|
||||
"mtusi-lab7_lokidata"
|
||||
]
|
||||
},
|
||||
"loki-tls": {
|
||||
"id": "43274e89343d6e7084748cce518e395fd0e26bf4533b6b82cd064f43a7529fe2",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:39:20.994577576Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"openbao": {
|
||||
"id": "eb1e14ebf03cc002f49792383e9bd917590954e70949b89f1eaea37462581c7a",
|
||||
"image": "sha256:ba4b133eb9586630024e71a617e66f37f29cc3534cdd46a6233e098ceded8dc9",
|
||||
"started_at": "2026-12-02T15:39:02.414995416Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "openbao",
|
||||
"volumes": [
|
||||
"mtusi-lab7_baodata"
|
||||
]
|
||||
},
|
||||
"otel-collector": {
|
||||
"id": "02e004fdf557d3671322ea1c22355c38e748758cfcee3339a00a620ce6c35764",
|
||||
"image": "sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea",
|
||||
"started_at": "2026-12-02T15:39:21.648251483Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001:10001",
|
||||
"volumes": []
|
||||
},
|
||||
"otel-collector-tls": {
|
||||
"id": "10ab06a075c8490e9db409381e57fb83444519308e375c8c1cd902edd33b7157",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:39:23.037846109Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"prometheus": {
|
||||
"id": "91d474d3250d8f3dab8dd99db3d2ee26c1d57005b189c11761a3e08081d19496",
|
||||
"image": "sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06",
|
||||
"started_at": "2026-12-02T15:39:22.199383597Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "nobody",
|
||||
"volumes": [
|
||||
"mtusi-lab7_prometheusdata"
|
||||
]
|
||||
},
|
||||
"prometheus-tls": {
|
||||
"id": "612d1f1509efb755145ff6ce6945316459cdc979defd03e9aa82944ad0c6e295",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:39:23.372582305Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"s3": {
|
||||
"id": "b2a89dd964d5b5fe45af06c27f322e6dd68b8e2a2d7a32003323746f3de3b7ce",
|
||||
"image": "sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15",
|
||||
"started_at": "2026-12-02T15:39:04.630046545Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"1432ccca7f9329bf205652067e548a1a9a523632f94d8bec600ed57a79bb09b3"
|
||||
]
|
||||
},
|
||||
"s3-storage": {
|
||||
"id": "a94fcd641d9e8ed28f946f940dcb06667c6b65be99413b9834aa519f437d7813",
|
||||
"image": "sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15",
|
||||
"started_at": "2026-12-02T15:39:01.936671501Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_s3data"
|
||||
]
|
||||
},
|
||||
"s3-tls": {
|
||||
"id": "0e93e3cbf64898c9c1b43a3062670bfafc8350bdadc40b16b73740234eca1a1d",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:39:02.306911112Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"tempo": {
|
||||
"id": "2ffad20b6acb5ae2990839fa93c39686b688544397685e77118c53d6e80cde77",
|
||||
"image": "sha256:64e2fbd56d9c2b3412a4b430a58ea59e91a670b1e75f920a0c702213ad145044",
|
||||
"started_at": "2026-12-02T15:39:22.026980512Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001:10001",
|
||||
"volumes": [
|
||||
"mtusi-lab7_tempodata"
|
||||
]
|
||||
},
|
||||
"tempo-tls": {
|
||||
"id": "bbb513a12be6f0114a2845ac6f835fbf19b42ddfb914c9bdcfbf1e9dbebf129e",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:39:23.26244867Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"worker": {
|
||||
"id": "6e0579589089c523aa597372e1460a8b2b2999fb86ea6b2e7cdaddad5b90986b",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:42:16.775435092Z",
|
||||
"running": false,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"api1": {
|
||||
"id": "ca3d46860e5855de0d47b1c0104f2c4da75f2dd11b98e1fcff8108b9149854bf",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:43:00.195092255Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"api1-tls": {
|
||||
"id": "a47b54dd359595c070f8dc7c742c36af3c30be869ea12a6aa43c3315608c4142",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:43:00.92744986Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"api2": {
|
||||
"id": "941904ece80d85e8f8dc776043743d207c2bf9e91f232c1fdd8305d30c1b200b",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:43:00.286198193Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"api2-tls": {
|
||||
"id": "f59e183292726d51a0151178518fab1a6edb65974ae078e2421a7f69daed23ab",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:43:00.818021096Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"broker": {
|
||||
"id": "d63b0f66b7101e59d2d373723bbeef55daf22a826fad7b7cfdd8c22e3b814b0a",
|
||||
"image": "sha256:61f90c401a5b5ed2486771973ea92ad66046471eacab9c9149f1a6e091c91677",
|
||||
"started_at": "2026-12-02T15:42:59.960974844Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_brokerdata"
|
||||
]
|
||||
},
|
||||
"cleanup": {
|
||||
"id": "8c5fda1b136ffe7449b0166b8d81cce0804cb7d482300d56cf0298e66b4d1b08",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:42:17.315671239Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"db": {
|
||||
"id": "38ec3e0cab177127cb5118c3e5016caa5cdf126e9776538197c79a387c458d9b",
|
||||
"image": "sha256:665dc7b37ac52a17e298511414c21d23ffa4e6a6ef6225b3e5d59c7afb35e994",
|
||||
"started_at": "2026-12-02T15:39:02.136046985Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_pgdata"
|
||||
]
|
||||
},
|
||||
"grafana": {
|
||||
"id": "55891ceedff24a309e5bcfccf47b154bd8949908c2672c2f4536ef57fdaf7295",
|
||||
"image": "sha256:0615ec4fbd4072004b7d86b46ded63013a74b7d6eb1119273dd89e8fa25c13cf",
|
||||
"started_at": "2026-12-02T15:39:22.550012775Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "472",
|
||||
"volumes": [
|
||||
"mtusi-lab7_grafanadata"
|
||||
]
|
||||
},
|
||||
"lb": {
|
||||
"id": "08306c84b0bf1d2c9a40a7fe3d0c1f3713fbd7bca7fe4b7042f20d0cea0e8213",
|
||||
"image": "sha256:1242e4006ac3f1ed15871efadca3d8d089e76f720017a1c51747133ee40cc953",
|
||||
"started_at": "2026-12-02T15:39:22.736582521Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "99:99",
|
||||
"volumes": []
|
||||
},
|
||||
"loki": {
|
||||
"id": "20a8e0aedb4b395ec48515ce93e2e8c286928a7dc24faeed478af0c2517f96de",
|
||||
"image": "sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7",
|
||||
"started_at": "2026-12-02T15:39:20.776200797Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001",
|
||||
"volumes": [
|
||||
"mtusi-lab7_lokidata"
|
||||
]
|
||||
},
|
||||
"loki-tls": {
|
||||
"id": "43274e89343d6e7084748cce518e395fd0e26bf4533b6b82cd064f43a7529fe2",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:39:20.994577576Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"openbao": {
|
||||
"id": "eb1e14ebf03cc002f49792383e9bd917590954e70949b89f1eaea37462581c7a",
|
||||
"image": "sha256:ba4b133eb9586630024e71a617e66f37f29cc3534cdd46a6233e098ceded8dc9",
|
||||
"started_at": "2026-12-02T15:39:02.414995416Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "openbao",
|
||||
"volumes": [
|
||||
"mtusi-lab7_baodata"
|
||||
]
|
||||
},
|
||||
"otel-collector": {
|
||||
"id": "02e004fdf557d3671322ea1c22355c38e748758cfcee3339a00a620ce6c35764",
|
||||
"image": "sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea",
|
||||
"started_at": "2026-12-02T15:39:21.648251483Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001:10001",
|
||||
"volumes": []
|
||||
},
|
||||
"otel-collector-tls": {
|
||||
"id": "10ab06a075c8490e9db409381e57fb83444519308e375c8c1cd902edd33b7157",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:39:23.037846109Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"prometheus": {
|
||||
"id": "91d474d3250d8f3dab8dd99db3d2ee26c1d57005b189c11761a3e08081d19496",
|
||||
"image": "sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06",
|
||||
"started_at": "2026-12-02T15:39:22.199383597Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "nobody",
|
||||
"volumes": [
|
||||
"mtusi-lab7_prometheusdata"
|
||||
]
|
||||
},
|
||||
"prometheus-tls": {
|
||||
"id": "612d1f1509efb755145ff6ce6945316459cdc979defd03e9aa82944ad0c6e295",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:39:23.372582305Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"s3": {
|
||||
"id": "b2a89dd964d5b5fe45af06c27f322e6dd68b8e2a2d7a32003323746f3de3b7ce",
|
||||
"image": "sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15",
|
||||
"started_at": "2026-12-02T15:39:04.630046545Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"1432ccca7f9329bf205652067e548a1a9a523632f94d8bec600ed57a79bb09b3"
|
||||
]
|
||||
},
|
||||
"s3-storage": {
|
||||
"id": "a94fcd641d9e8ed28f946f940dcb06667c6b65be99413b9834aa519f437d7813",
|
||||
"image": "sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15",
|
||||
"started_at": "2026-12-02T15:39:01.936671501Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_s3data"
|
||||
]
|
||||
},
|
||||
"s3-tls": {
|
||||
"id": "0e93e3cbf64898c9c1b43a3062670bfafc8350bdadc40b16b73740234eca1a1d",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:39:02.306911112Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"tempo": {
|
||||
"id": "2ffad20b6acb5ae2990839fa93c39686b688544397685e77118c53d6e80cde77",
|
||||
"image": "sha256:64e2fbd56d9c2b3412a4b430a58ea59e91a670b1e75f920a0c702213ad145044",
|
||||
"started_at": "2026-12-02T15:39:22.026980512Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001:10001",
|
||||
"volumes": [
|
||||
"mtusi-lab7_tempodata"
|
||||
]
|
||||
},
|
||||
"tempo-tls": {
|
||||
"id": "bbb513a12be6f0114a2845ac6f835fbf19b42ddfb914c9bdcfbf1e9dbebf129e",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:39:23.26244867Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"worker": {
|
||||
"id": "6e0579589089c523aa597372e1460a8b2b2999fb86ea6b2e7cdaddad5b90986b",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:42:16.775435092Z",
|
||||
"running": false,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,483 @@
|
||||
{
|
||||
"before": {
|
||||
"api1": {
|
||||
"id": "ca3d46860e5855de0d47b1c0104f2c4da75f2dd11b98e1fcff8108b9149854bf",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:45:46.233277901Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"api1-tls": {
|
||||
"id": "a47b54dd359595c070f8dc7c742c36af3c30be869ea12a6aa43c3315608c4142",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:46:02.027441658Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"api2": {
|
||||
"id": "941904ece80d85e8f8dc776043743d207c2bf9e91f232c1fdd8305d30c1b200b",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:45:58.821948379Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"api2-tls": {
|
||||
"id": "f59e183292726d51a0151178518fab1a6edb65974ae078e2421a7f69daed23ab",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:46:02.029213485Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"broker": {
|
||||
"id": "d63b0f66b7101e59d2d373723bbeef55daf22a826fad7b7cfdd8c22e3b814b0a",
|
||||
"image": "sha256:61f90c401a5b5ed2486771973ea92ad66046471eacab9c9149f1a6e091c91677",
|
||||
"started_at": "2026-12-02T15:47:08.32356757Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_brokerdata"
|
||||
]
|
||||
},
|
||||
"cleanup": {
|
||||
"id": "8c5fda1b136ffe7449b0166b8d81cce0804cb7d482300d56cf0298e66b4d1b08",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:44:46.651782642Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"db": {
|
||||
"id": "38ec3e0cab177127cb5118c3e5016caa5cdf126e9776538197c79a387c458d9b",
|
||||
"image": "sha256:665dc7b37ac52a17e298511414c21d23ffa4e6a6ef6225b3e5d59c7afb35e994",
|
||||
"started_at": "2026-12-02T15:48:56.705657065Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_pgdata"
|
||||
]
|
||||
},
|
||||
"grafana": {
|
||||
"id": "55891ceedff24a309e5bcfccf47b154bd8949908c2672c2f4536ef57fdaf7295",
|
||||
"image": "sha256:0615ec4fbd4072004b7d86b46ded63013a74b7d6eb1119273dd89e8fa25c13cf",
|
||||
"started_at": "2026-12-02T15:44:46.118740928Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "472",
|
||||
"volumes": [
|
||||
"mtusi-lab7_grafanadata"
|
||||
]
|
||||
},
|
||||
"lb": {
|
||||
"id": "08306c84b0bf1d2c9a40a7fe3d0c1f3713fbd7bca7fe4b7042f20d0cea0e8213",
|
||||
"image": "sha256:1242e4006ac3f1ed15871efadca3d8d089e76f720017a1c51747133ee40cc953",
|
||||
"started_at": "2026-12-02T15:44:47.207114455Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "99:99",
|
||||
"volumes": []
|
||||
},
|
||||
"loki": {
|
||||
"id": "20a8e0aedb4b395ec48515ce93e2e8c286928a7dc24faeed478af0c2517f96de",
|
||||
"image": "sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7",
|
||||
"started_at": "2026-12-02T15:50:21.157322503Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001",
|
||||
"volumes": [
|
||||
"mtusi-lab7_lokidata"
|
||||
]
|
||||
},
|
||||
"loki-tls": {
|
||||
"id": "43274e89343d6e7084748cce518e395fd0e26bf4533b6b82cd064f43a7529fe2",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:50:21.762313218Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"openbao": {
|
||||
"id": "eb1e14ebf03cc002f49792383e9bd917590954e70949b89f1eaea37462581c7a",
|
||||
"image": "sha256:ba4b133eb9586630024e71a617e66f37f29cc3534cdd46a6233e098ceded8dc9",
|
||||
"started_at": "2026-12-02T15:44:29.559090181Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "openbao",
|
||||
"volumes": [
|
||||
"mtusi-lab7_baodata"
|
||||
]
|
||||
},
|
||||
"otel-collector": {
|
||||
"id": "02e004fdf557d3671322ea1c22355c38e748758cfcee3339a00a620ce6c35764",
|
||||
"image": "sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea",
|
||||
"started_at": "2026-12-02T15:49:36.548349519Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001:10001",
|
||||
"volumes": []
|
||||
},
|
||||
"otel-collector-tls": {
|
||||
"id": "10ab06a075c8490e9db409381e57fb83444519308e375c8c1cd902edd33b7157",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:49:37.127341933Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"prometheus": {
|
||||
"id": "91d474d3250d8f3dab8dd99db3d2ee26c1d57005b189c11761a3e08081d19496",
|
||||
"image": "sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06",
|
||||
"started_at": "2026-12-02T15:44:46.822003752Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "nobody",
|
||||
"volumes": [
|
||||
"mtusi-lab7_prometheusdata"
|
||||
]
|
||||
},
|
||||
"prometheus-tls": {
|
||||
"id": "612d1f1509efb755145ff6ce6945316459cdc979defd03e9aa82944ad0c6e295",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:48.061973133Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"s3": {
|
||||
"id": "b2a89dd964d5b5fe45af06c27f322e6dd68b8e2a2d7a32003323746f3de3b7ce",
|
||||
"image": "sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15",
|
||||
"started_at": "2026-12-02T15:46:59.409879523Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"1432ccca7f9329bf205652067e548a1a9a523632f94d8bec600ed57a79bb09b3"
|
||||
]
|
||||
},
|
||||
"s3-storage": {
|
||||
"id": "a94fcd641d9e8ed28f946f940dcb06667c6b65be99413b9834aa519f437d7813",
|
||||
"image": "sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15",
|
||||
"started_at": "2026-12-02T15:44:28.674800296Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_s3data"
|
||||
]
|
||||
},
|
||||
"s3-tls": {
|
||||
"id": "0e93e3cbf64898c9c1b43a3062670bfafc8350bdadc40b16b73740234eca1a1d",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:29.422474882Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"tempo": {
|
||||
"id": "2ffad20b6acb5ae2990839fa93c39686b688544397685e77118c53d6e80cde77",
|
||||
"image": "sha256:64e2fbd56d9c2b3412a4b430a58ea59e91a670b1e75f920a0c702213ad145044",
|
||||
"started_at": "2026-12-02T15:44:47.015637558Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001:10001",
|
||||
"volumes": [
|
||||
"mtusi-lab7_tempodata"
|
||||
]
|
||||
},
|
||||
"tempo-tls": {
|
||||
"id": "bbb513a12be6f0114a2845ac6f835fbf19b42ddfb914c9bdcfbf1e9dbebf129e",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:48.170778392Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"worker": {
|
||||
"id": "6e0579589089c523aa597372e1460a8b2b2999fb86ea6b2e7cdaddad5b90986b",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:50:45.73852243Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"api1": {
|
||||
"id": "ca3d46860e5855de0d47b1c0104f2c4da75f2dd11b98e1fcff8108b9149854bf",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:51:52.331305007Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"api1-tls": {
|
||||
"id": "a47b54dd359595c070f8dc7c742c36af3c30be869ea12a6aa43c3315608c4142",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:52:04.238478548Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"api2": {
|
||||
"id": "941904ece80d85e8f8dc776043743d207c2bf9e91f232c1fdd8305d30c1b200b",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:51:54.656631356Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"api2-tls": {
|
||||
"id": "f59e183292726d51a0151178518fab1a6edb65974ae078e2421a7f69daed23ab",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:52:04.909650226Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"broker": {
|
||||
"id": "d63b0f66b7101e59d2d373723bbeef55daf22a826fad7b7cfdd8c22e3b814b0a",
|
||||
"image": "sha256:61f90c401a5b5ed2486771973ea92ad66046471eacab9c9149f1a6e091c91677",
|
||||
"started_at": "2026-12-02T15:51:29.891170955Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_brokerdata"
|
||||
]
|
||||
},
|
||||
"cleanup": {
|
||||
"id": "8c5fda1b136ffe7449b0166b8d81cce0804cb7d482300d56cf0298e66b4d1b08",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:52:03.165581437Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"db": {
|
||||
"id": "38ec3e0cab177127cb5118c3e5016caa5cdf126e9776538197c79a387c458d9b",
|
||||
"image": "sha256:665dc7b37ac52a17e298511414c21d23ffa4e6a6ef6225b3e5d59c7afb35e994",
|
||||
"started_at": "2026-12-02T15:51:30.049470117Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_pgdata"
|
||||
]
|
||||
},
|
||||
"grafana": {
|
||||
"id": "55891ceedff24a309e5bcfccf47b154bd8949908c2672c2f4536ef57fdaf7295",
|
||||
"image": "sha256:0615ec4fbd4072004b7d86b46ded63013a74b7d6eb1119273dd89e8fa25c13cf",
|
||||
"started_at": "2026-12-02T15:51:58.159629582Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "472",
|
||||
"volumes": [
|
||||
"mtusi-lab7_grafanadata"
|
||||
]
|
||||
},
|
||||
"lb": {
|
||||
"id": "08306c84b0bf1d2c9a40a7fe3d0c1f3713fbd7bca7fe4b7042f20d0cea0e8213",
|
||||
"image": "sha256:1242e4006ac3f1ed15871efadca3d8d089e76f720017a1c51747133ee40cc953",
|
||||
"started_at": "2026-12-02T15:51:59.906448987Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "99:99",
|
||||
"volumes": []
|
||||
},
|
||||
"loki": {
|
||||
"id": "20a8e0aedb4b395ec48515ce93e2e8c286928a7dc24faeed478af0c2517f96de",
|
||||
"image": "sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7",
|
||||
"started_at": "2026-12-02T15:51:48.95654196Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001",
|
||||
"volumes": [
|
||||
"mtusi-lab7_lokidata"
|
||||
]
|
||||
},
|
||||
"loki-tls": {
|
||||
"id": "43274e89343d6e7084748cce518e395fd0e26bf4533b6b82cd064f43a7529fe2",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:51:50.849608111Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"openbao": {
|
||||
"id": "eb1e14ebf03cc002f49792383e9bd917590954e70949b89f1eaea37462581c7a",
|
||||
"image": "sha256:ba4b133eb9586630024e71a617e66f37f29cc3534cdd46a6233e098ceded8dc9",
|
||||
"started_at": "2026-12-02T15:51:30.376135535Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "openbao",
|
||||
"volumes": [
|
||||
"mtusi-lab7_baodata"
|
||||
]
|
||||
},
|
||||
"otel-collector": {
|
||||
"id": "02e004fdf557d3671322ea1c22355c38e748758cfcee3339a00a620ce6c35764",
|
||||
"image": "sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea",
|
||||
"started_at": "2026-12-02T15:52:02.12375437Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001:10001",
|
||||
"volumes": []
|
||||
},
|
||||
"otel-collector-tls": {
|
||||
"id": "10ab06a075c8490e9db409381e57fb83444519308e375c8c1cd902edd33b7157",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:52:06.600717393Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"prometheus": {
|
||||
"id": "91d474d3250d8f3dab8dd99db3d2ee26c1d57005b189c11761a3e08081d19496",
|
||||
"image": "sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06",
|
||||
"started_at": "2026-12-02T15:52:01.119031301Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "nobody",
|
||||
"volumes": [
|
||||
"mtusi-lab7_prometheusdata"
|
||||
]
|
||||
},
|
||||
"prometheus-tls": {
|
||||
"id": "612d1f1509efb755145ff6ce6945316459cdc979defd03e9aa82944ad0c6e295",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:52:05.842266443Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"s3": {
|
||||
"id": "b2a89dd964d5b5fe45af06c27f322e6dd68b8e2a2d7a32003323746f3de3b7ce",
|
||||
"image": "sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15",
|
||||
"started_at": "2026-12-02T15:51:32.24483327Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"1432ccca7f9329bf205652067e548a1a9a523632f94d8bec600ed57a79bb09b3"
|
||||
]
|
||||
},
|
||||
"s3-storage": {
|
||||
"id": "a94fcd641d9e8ed28f946f940dcb06667c6b65be99413b9834aa519f437d7813",
|
||||
"image": "sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15",
|
||||
"started_at": "2026-12-02T15:51:29.521826604Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_s3data"
|
||||
]
|
||||
},
|
||||
"s3-tls": {
|
||||
"id": "0e93e3cbf64898c9c1b43a3062670bfafc8350bdadc40b16b73740234eca1a1d",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:51:30.225754669Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"tempo": {
|
||||
"id": "2ffad20b6acb5ae2990839fa93c39686b688544397685e77118c53d6e80cde77",
|
||||
"image": "sha256:64e2fbd56d9c2b3412a4b430a58ea59e91a670b1e75f920a0c702213ad145044",
|
||||
"started_at": "2026-12-02T15:52:03.691000214Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001:10001",
|
||||
"volumes": [
|
||||
"mtusi-lab7_tempodata"
|
||||
]
|
||||
},
|
||||
"tempo-tls": {
|
||||
"id": "bbb513a12be6f0114a2845ac6f835fbf19b42ddfb914c9bdcfbf1e9dbebf129e",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:52:07.477118607Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"worker": {
|
||||
"id": "6e0579589089c523aa597372e1460a8b2b2999fb86ea6b2e7cdaddad5b90986b",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:51:47.914976394Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
}
|
||||
},
|
||||
"operator_unseal": true
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"transient_attempts": 2,
|
||||
"max_attempts": 5,
|
||||
"failed_content": 409,
|
||||
"failed_link": 409,
|
||||
"processing_observed": true,
|
||||
"permanent_error_attempts": 1,
|
||||
"worker_stopped_before_result_commit": true,
|
||||
"staging_retention_and_pending_protection": true,
|
||||
"redelivery_same_result": true
|
||||
}
|
||||
@@ -0,0 +1,255 @@
|
||||
{
|
||||
"service": "api2",
|
||||
"target_instance": "10e83d13717142dbaffa73dd6c83b489",
|
||||
"before": {
|
||||
"api1": {
|
||||
"instance_id": "4dc62abfe2354262861e7fce54a323b1",
|
||||
"container_id": "ca3d46860e5855de0d47b1c0104f2c4da75f2dd11b98e1fcff8108b9149854bf"
|
||||
},
|
||||
"api2": {
|
||||
"instance_id": "10e83d13717142dbaffa73dd6c83b489",
|
||||
"container_id": "941904ece80d85e8f8dc776043743d207c2bf9e91f232c1fdd8305d30c1b200b"
|
||||
}
|
||||
},
|
||||
"after": {
|
||||
"api1": {
|
||||
"id": "ca3d46860e5855de0d47b1c0104f2c4da75f2dd11b98e1fcff8108b9149854bf",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:45:46.233277901Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"api1-tls": {
|
||||
"id": "a47b54dd359595c070f8dc7c742c36af3c30be869ea12a6aa43c3315608c4142",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:45:46.778742852Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"api2": {
|
||||
"id": "941904ece80d85e8f8dc776043743d207c2bf9e91f232c1fdd8305d30c1b200b",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:45:33.689719679Z",
|
||||
"running": false,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"api2-tls": {
|
||||
"id": "f59e183292726d51a0151178518fab1a6edb65974ae078e2421a7f69daed23ab",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:45:46.850812705Z",
|
||||
"running": false,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"broker": {
|
||||
"id": "d63b0f66b7101e59d2d373723bbeef55daf22a826fad7b7cfdd8c22e3b814b0a",
|
||||
"image": "sha256:61f90c401a5b5ed2486771973ea92ad66046471eacab9c9149f1a6e091c91677",
|
||||
"started_at": "2026-12-02T15:44:29.009197972Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_brokerdata"
|
||||
]
|
||||
},
|
||||
"cleanup": {
|
||||
"id": "8c5fda1b136ffe7449b0166b8d81cce0804cb7d482300d56cf0298e66b4d1b08",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:44:46.651782642Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
},
|
||||
"db": {
|
||||
"id": "38ec3e0cab177127cb5118c3e5016caa5cdf126e9776538197c79a387c458d9b",
|
||||
"image": "sha256:665dc7b37ac52a17e298511414c21d23ffa4e6a6ef6225b3e5d59c7afb35e994",
|
||||
"started_at": "2026-12-02T15:44:29.216566482Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_pgdata"
|
||||
]
|
||||
},
|
||||
"grafana": {
|
||||
"id": "55891ceedff24a309e5bcfccf47b154bd8949908c2672c2f4536ef57fdaf7295",
|
||||
"image": "sha256:0615ec4fbd4072004b7d86b46ded63013a74b7d6eb1119273dd89e8fa25c13cf",
|
||||
"started_at": "2026-12-02T15:44:46.118740928Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "472",
|
||||
"volumes": [
|
||||
"mtusi-lab7_grafanadata"
|
||||
]
|
||||
},
|
||||
"lb": {
|
||||
"id": "08306c84b0bf1d2c9a40a7fe3d0c1f3713fbd7bca7fe4b7042f20d0cea0e8213",
|
||||
"image": "sha256:1242e4006ac3f1ed15871efadca3d8d089e76f720017a1c51747133ee40cc953",
|
||||
"started_at": "2026-12-02T15:44:47.207114455Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "99:99",
|
||||
"volumes": []
|
||||
},
|
||||
"loki": {
|
||||
"id": "20a8e0aedb4b395ec48515ce93e2e8c286928a7dc24faeed478af0c2517f96de",
|
||||
"image": "sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7",
|
||||
"started_at": "2026-12-02T15:44:47.41219432Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001",
|
||||
"volumes": [
|
||||
"mtusi-lab7_lokidata"
|
||||
]
|
||||
},
|
||||
"loki-tls": {
|
||||
"id": "43274e89343d6e7084748cce518e395fd0e26bf4533b6b82cd064f43a7529fe2",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:47.571999117Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"openbao": {
|
||||
"id": "eb1e14ebf03cc002f49792383e9bd917590954e70949b89f1eaea37462581c7a",
|
||||
"image": "sha256:ba4b133eb9586630024e71a617e66f37f29cc3534cdd46a6233e098ceded8dc9",
|
||||
"started_at": "2026-12-02T15:44:29.559090181Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "openbao",
|
||||
"volumes": [
|
||||
"mtusi-lab7_baodata"
|
||||
]
|
||||
},
|
||||
"otel-collector": {
|
||||
"id": "02e004fdf557d3671322ea1c22355c38e748758cfcee3339a00a620ce6c35764",
|
||||
"image": "sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea",
|
||||
"started_at": "2026-12-02T15:44:47.67769664Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001:10001",
|
||||
"volumes": []
|
||||
},
|
||||
"otel-collector-tls": {
|
||||
"id": "10ab06a075c8490e9db409381e57fb83444519308e375c8c1cd902edd33b7157",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:48.273502705Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"prometheus": {
|
||||
"id": "91d474d3250d8f3dab8dd99db3d2ee26c1d57005b189c11761a3e08081d19496",
|
||||
"image": "sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06",
|
||||
"started_at": "2026-12-02T15:44:46.822003752Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "nobody",
|
||||
"volumes": [
|
||||
"mtusi-lab7_prometheusdata"
|
||||
]
|
||||
},
|
||||
"prometheus-tls": {
|
||||
"id": "612d1f1509efb755145ff6ce6945316459cdc979defd03e9aa82944ad0c6e295",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:48.061973133Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"s3": {
|
||||
"id": "b2a89dd964d5b5fe45af06c27f322e6dd68b8e2a2d7a32003323746f3de3b7ce",
|
||||
"image": "sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15",
|
||||
"started_at": "2026-12-02T15:44:31.352056342Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"1432ccca7f9329bf205652067e548a1a9a523632f94d8bec600ed57a79bb09b3"
|
||||
]
|
||||
},
|
||||
"s3-storage": {
|
||||
"id": "a94fcd641d9e8ed28f946f940dcb06667c6b65be99413b9834aa519f437d7813",
|
||||
"image": "sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15",
|
||||
"started_at": "2026-12-02T15:44:28.674800296Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "",
|
||||
"volumes": [
|
||||
"mtusi-lab7_s3data"
|
||||
]
|
||||
},
|
||||
"s3-tls": {
|
||||
"id": "0e93e3cbf64898c9c1b43a3062670bfafc8350bdadc40b16b73740234eca1a1d",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:29.422474882Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"tempo": {
|
||||
"id": "2ffad20b6acb5ae2990839fa93c39686b688544397685e77118c53d6e80cde77",
|
||||
"image": "sha256:64e2fbd56d9c2b3412a4b430a58ea59e91a670b1e75f920a0c702213ad145044",
|
||||
"started_at": "2026-12-02T15:44:47.015637558Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "10001:10001",
|
||||
"volumes": [
|
||||
"mtusi-lab7_tempodata"
|
||||
]
|
||||
},
|
||||
"tempo-tls": {
|
||||
"id": "bbb513a12be6f0114a2845ac6f835fbf19b42ddfb914c9bdcfbf1e9dbebf129e",
|
||||
"image": "sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb",
|
||||
"started_at": "2026-12-02T15:44:48.170778392Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "101:101",
|
||||
"volumes": []
|
||||
},
|
||||
"worker": {
|
||||
"id": "6e0579589089c523aa597372e1460a8b2b2999fb86ea6b2e7cdaddad5b90986b",
|
||||
"image": "sha256:750b3a6e733077046e648583218b288129b18d0c65f49f09e3ce53fc6afb7827",
|
||||
"started_at": "2026-12-02T15:44:45.962419777Z",
|
||||
"running": true,
|
||||
"oom_killed": false,
|
||||
"restart_count": 0,
|
||||
"user": "messenger",
|
||||
"volumes": []
|
||||
}
|
||||
},
|
||||
"stop_seconds": 1.445
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,240 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"api": {
|
||||
"trace_id": "028e536339a97e81faf441b4e4a37f3d",
|
||||
"span_id": "c2efb65936889000",
|
||||
"event": "http.completed",
|
||||
"kind": "SERVER",
|
||||
"span_name": "GET /api/v1/users/me",
|
||||
"span_status": {},
|
||||
"span_duration_seconds": 0.003377103,
|
||||
"span_attributes": [
|
||||
{
|
||||
"key": "http.request.method",
|
||||
"value": {
|
||||
"stringValue": "GET"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "http.route",
|
||||
"value": {
|
||||
"stringValue": "/api/v1/users/me"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.request_id",
|
||||
"value": {
|
||||
"stringValue": "dbfea19e-0164-4d72-922d-b532b31b55ea"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "http.response.status_code",
|
||||
"value": {
|
||||
"intValue": "200"
|
||||
}
|
||||
}
|
||||
],
|
||||
"log": {
|
||||
"code_file_path": "/app/src/telemetry.py",
|
||||
"code_function_name": "event",
|
||||
"code_line_number": "119",
|
||||
"deployment_environment_name": "lab",
|
||||
"detected_level": "info",
|
||||
"duration_seconds": "0.003173",
|
||||
"event": "http.completed",
|
||||
"flags": "3",
|
||||
"method": "GET",
|
||||
"observed_timestamp": "1796226633633441055",
|
||||
"request_id": "dbfea19e-0164-4d72-922d-b532b31b55ea",
|
||||
"route": "/api/v1/users/me",
|
||||
"scope_name": "messenger",
|
||||
"service_instance_id": "4dc62abfe2354262861e7fce54a323b1",
|
||||
"service_name": "messenger-api",
|
||||
"service_version": "lab7",
|
||||
"severity_number": "9",
|
||||
"severity_text": "INFO",
|
||||
"span_id": "c2efb65936889000",
|
||||
"status_code": "200",
|
||||
"telemetry_sdk_language": "python",
|
||||
"telemetry_sdk_name": "opentelemetry",
|
||||
"telemetry_sdk_version": "1.45.2",
|
||||
"trace_id": "028e536339a97e81faf441b4e4a37f3d",
|
||||
"timestamp_ns": "1796226633633336576",
|
||||
"body": "http.completed"
|
||||
}
|
||||
},
|
||||
"worker": {
|
||||
"trace_id": "f12b32554aa13051376a36118998f50a",
|
||||
"span_id": "fefe8d06f1659c1d",
|
||||
"event": "job.completed",
|
||||
"kind": "CONSUMER",
|
||||
"span_name": "attachment.process",
|
||||
"span_status": {},
|
||||
"span_duration_seconds": 1.207597757,
|
||||
"span_attributes": [
|
||||
{
|
||||
"key": "messaging.system",
|
||||
"value": {
|
||||
"stringValue": "rabbitmq"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messaging.operation.type",
|
||||
"value": {
|
||||
"stringValue": "process"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.type",
|
||||
"value": {
|
||||
"stringValue": "attachment.process.v1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.id",
|
||||
"value": {
|
||||
"stringValue": "330498c8-7c41-42f4-b5ff-98a349a066c0"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.attempt",
|
||||
"value": {
|
||||
"intValue": "1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.outcome",
|
||||
"value": {
|
||||
"stringValue": "success"
|
||||
}
|
||||
}
|
||||
],
|
||||
"log": {
|
||||
"attempt": "1",
|
||||
"code_file_path": "/app/src/telemetry.py",
|
||||
"code_function_name": "event",
|
||||
"code_line_number": "119",
|
||||
"deployment_environment_name": "lab",
|
||||
"detected_level": "info",
|
||||
"duration_seconds": "1.207352",
|
||||
"event": "job.completed",
|
||||
"flags": "3",
|
||||
"job_id": "330498c8-7c41-42f4-b5ff-98a349a066c0",
|
||||
"observed_timestamp": "1796226639652378469",
|
||||
"outcome": "success",
|
||||
"scope_name": "messenger",
|
||||
"service_instance_id": "57062dd2b8044a1091ea5df1f384dcdb",
|
||||
"service_name": "messenger-worker",
|
||||
"service_version": "lab7",
|
||||
"severity_number": "9",
|
||||
"severity_text": "INFO",
|
||||
"span_id": "fefe8d06f1659c1d",
|
||||
"telemetry_sdk_language": "python",
|
||||
"telemetry_sdk_name": "opentelemetry",
|
||||
"telemetry_sdk_version": "1.45.2",
|
||||
"trace_id": "f12b32554aa13051376a36118998f50a",
|
||||
"timestamp_ns": "1796226639652215552",
|
||||
"body": "job.completed"
|
||||
}
|
||||
},
|
||||
"failed_worker": {
|
||||
"trace_id": "4222a8848c3ccea3715daf9913ba74ef",
|
||||
"span_id": "9158e364a7dcc6da",
|
||||
"event": "job.completed",
|
||||
"kind": "CONSUMER",
|
||||
"span_name": "attachment.process",
|
||||
"span_status": {
|
||||
"code": "STATUS_CODE_ERROR"
|
||||
},
|
||||
"span_duration_seconds": 1.206003588,
|
||||
"span_attributes": [
|
||||
{
|
||||
"key": "messaging.system",
|
||||
"value": {
|
||||
"stringValue": "rabbitmq"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messaging.operation.type",
|
||||
"value": {
|
||||
"stringValue": "process"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.type",
|
||||
"value": {
|
||||
"stringValue": "attachment.process.v1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.id",
|
||||
"value": {
|
||||
"stringValue": "028ab01c-97d3-49c2-aa3e-a75829913149"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.attempt",
|
||||
"value": {
|
||||
"intValue": "1"
|
||||
}
|
||||
},
|
||||
{
|
||||
"key": "messenger.job.outcome",
|
||||
"value": {
|
||||
"stringValue": "failed"
|
||||
}
|
||||
}
|
||||
],
|
||||
"log": {
|
||||
"attempt": "1",
|
||||
"code_file_path": "/app/src/telemetry.py",
|
||||
"code_function_name": "event",
|
||||
"code_line_number": "119",
|
||||
"deployment_environment_name": "lab",
|
||||
"detected_level": "info",
|
||||
"duration_seconds": "1.205467",
|
||||
"error_code": "invalid_image",
|
||||
"event": "job.completed",
|
||||
"flags": "3",
|
||||
"job_id": "028ab01c-97d3-49c2-aa3e-a75829913149",
|
||||
"observed_timestamp": "1796226647825671017",
|
||||
"outcome": "failed",
|
||||
"scope_name": "messenger",
|
||||
"service_instance_id": "9aaf50c415f04143abfa17d23b348eb7",
|
||||
"service_name": "messenger-worker",
|
||||
"service_version": "lab7",
|
||||
"severity_number": "9",
|
||||
"severity_text": "INFO",
|
||||
"span_id": "9158e364a7dcc6da",
|
||||
"telemetry_sdk_language": "python",
|
||||
"telemetry_sdk_name": "opentelemetry",
|
||||
"telemetry_sdk_version": "1.45.2",
|
||||
"trace_id": "4222a8848c3ccea3715daf9913ba74ef",
|
||||
"timestamp_ns": "1796226647825515776",
|
||||
"body": "job.completed"
|
||||
}
|
||||
},
|
||||
"failed_job_series": 1,
|
||||
"privacy": "PASS",
|
||||
"route_cardinality": "PASS",
|
||||
"no_duplicate_instrumentation": true,
|
||||
"http_series": 6,
|
||||
"job_series": 1,
|
||||
"http_histogram_buckets": 588,
|
||||
"job_histogram_buckets": 28,
|
||||
"grafana": {
|
||||
"log_trace_queries": [
|
||||
"loki",
|
||||
"tempo"
|
||||
],
|
||||
"dashboard_uid": "messenger-lab6",
|
||||
"data_sources": [
|
||||
"loki",
|
||||
"prometheus",
|
||||
"tempo"
|
||||
],
|
||||
"prometheus_queries_valid": 6,
|
||||
"source_health": "PASS"
|
||||
},
|
||||
"metric_time": 1796226676.822975
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
{
|
||||
"status": "PASS",
|
||||
"checks": {
|
||||
"api1:None": false,
|
||||
"api1:wrong-role": false,
|
||||
"api1:foreign": false,
|
||||
"api1:expired": false,
|
||||
"api1:lb": true,
|
||||
"api1:plaintext": false,
|
||||
"api2:None": false,
|
||||
"api2:wrong-role": false,
|
||||
"api2:foreign": false,
|
||||
"api2:expired": false,
|
||||
"api2:lb": true,
|
||||
"api2:plaintext": false,
|
||||
"reject_reasons": {
|
||||
"api1:None": "SSLError",
|
||||
"api1:wrong-role": "SSLError",
|
||||
"api1:foreign": "SSLError",
|
||||
"api1:expired": "SSLError",
|
||||
"api2:None": "SSLError",
|
||||
"api2:wrong-role": "SSLError",
|
||||
"api2:foreign": "SSLError",
|
||||
"api2:expired": "SSLError"
|
||||
},
|
||||
"untrusted-ca": "CERTIFICATE_VERIFY_FAILED",
|
||||
"wrong-hostname": "CERTIFICATE_VERIFY_FAILED"
|
||||
}
|
||||
}
|
||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,293 @@
|
||||
name: mtusi-lab6
|
||||
|
||||
x-app: &app
|
||||
image: mtusi-messenger:lab6
|
||||
build: .
|
||||
environment: &environment
|
||||
APP_HOST: 0.0.0.0
|
||||
APP_PORT: 8080
|
||||
APP_ENV: lab
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318
|
||||
OTEL_EXPORTER_OTLP_PROTOCOL: http/protobuf
|
||||
SERVICE_VERSION: ${SERVICE_VERSION:-lab6}
|
||||
DATABASE_URL_FILE: /run/secrets/database_url
|
||||
CURSOR_SECRET_FILE: /run/secrets/cursor_key
|
||||
SESSION_TTL_SECONDS: ${SESSION_TTL_SECONDS:-3600}
|
||||
IDEMPOTENCY_TTL_SECONDS: ${IDEMPOTENCY_TTL_SECONDS:-86400}
|
||||
S3_ENDPOINT: http://s3:9000
|
||||
S3_REGION: us-east-1
|
||||
S3_BUCKET: ${S3_BUCKET:-messenger-lab6-attachments}
|
||||
S3_ACCESS_KEY_ID_FILE: /run/secrets/s3_access_key_id
|
||||
S3_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_secret_access_key
|
||||
BROKER_URL_FILE: /run/secrets/broker_url
|
||||
JOB_MAX_ATTEMPTS: ${JOB_MAX_ATTEMPTS:-5}
|
||||
JOB_TIMEOUT_SECONDS: ${JOB_TIMEOUT_SECONDS:-60}
|
||||
STAGING_RETENTION_SECONDS: ${STAGING_RETENTION_SECONDS:-86400}
|
||||
CLEANUP_INTERVAL_SECONDS: ${CLEANUP_INTERVAL_SECONDS:-30}
|
||||
CLEANUP_GRACE_SECONDS: ${CLEANUP_GRACE_SECONDS:-600}
|
||||
secrets:
|
||||
- database_url
|
||||
- cursor_key
|
||||
- broker_url
|
||||
- s3_access_key_id
|
||||
- s3_secret_access_key
|
||||
stop_grace_period: 20s
|
||||
|
||||
services:
|
||||
db:
|
||||
image: postgres:17.11-bookworm@sha256:665dc7b37ac52a17e298511414c21d23ffa4e6a6ef6225b3e5d59c7afb35e994
|
||||
environment:
|
||||
POSTGRES_USER: messenger
|
||||
POSTGRES_DB: messenger
|
||||
POSTGRES_PASSWORD_FILE: /run/secrets/postgres_password
|
||||
secrets:
|
||||
- postgres_password
|
||||
volumes:
|
||||
- pgdata:/var/lib/postgresql/data
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "pg_isready -U messenger -d messenger"]
|
||||
interval: 2s
|
||||
timeout: 3s
|
||||
retries: 30
|
||||
stop_grace_period: 10s
|
||||
|
||||
s3-storage:
|
||||
image: chrislusf/seaweedfs:4.54@sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15
|
||||
command: ["server", "-filer", "-dir=/data", "-ip=s3-storage", "-ip.bind=0.0.0.0",
|
||||
"-master.volumeSizeLimitMB=128", "-volume.max=64", "-master.electionTimeout=1s",
|
||||
"-master.heartbeatInterval=100ms"]
|
||||
volumes:
|
||||
- s3data:/data
|
||||
networks:
|
||||
- storage
|
||||
healthcheck:
|
||||
test: ["CMD-SHELL", "wget -q -O - http://127.0.0.1:9333/cluster/status | grep -q '\"IsLeader\":true'"]
|
||||
interval: 2s
|
||||
timeout: 2s
|
||||
retries: 45
|
||||
stop_grace_period: 10s
|
||||
|
||||
s3:
|
||||
image: chrislusf/seaweedfs:4.54@sha256:4b42c212543a0acd4c0e675215ecdcaf62a186ef98def76c7e12701871222d15
|
||||
command: ["s3", "-filer=s3-storage:8888", "-port=9000", "-ip.bind=0.0.0.0",
|
||||
"-config=/run/secrets/s3_config", "-iam=false", "-port.iceberg=0", "-port.lance=0"]
|
||||
secrets:
|
||||
- s3_config
|
||||
networks:
|
||||
- default
|
||||
- storage
|
||||
depends_on:
|
||||
s3-storage:
|
||||
condition: service_healthy
|
||||
stop_grace_period: 3s
|
||||
|
||||
migrate:
|
||||
<<: *app
|
||||
command: ["python", "-m", "src.migrate"]
|
||||
secrets:
|
||||
- database_url
|
||||
healthcheck:
|
||||
disable: true
|
||||
depends_on:
|
||||
db:
|
||||
condition: service_healthy
|
||||
|
||||
bootstrap:
|
||||
<<: *app
|
||||
command: ["python", "-m", "src.bootstrap"]
|
||||
environment:
|
||||
<<: *environment
|
||||
S3_ADMIN_ACCESS_KEY_ID_FILE: /run/secrets/s3_admin_access_key_id
|
||||
S3_ADMIN_SECRET_ACCESS_KEY_FILE: /run/secrets/s3_admin_secret_access_key
|
||||
secrets:
|
||||
- s3_access_key_id
|
||||
- s3_secret_access_key
|
||||
- s3_admin_access_key_id
|
||||
- s3_admin_secret_access_key
|
||||
healthcheck:
|
||||
disable: true
|
||||
depends_on:
|
||||
s3:
|
||||
condition: service_started
|
||||
|
||||
broker:
|
||||
image: rabbitmq:4.4.1-management@sha256:61f90c401a5b5ed2486771973ea92ad66046471eacab9c9149f1a6e091c91677
|
||||
hostname: broker
|
||||
environment:
|
||||
RABBITMQ_CONFIG_FILE: /run/secrets/rabbitmq
|
||||
RABBITMQ_NODENAME: rabbit@broker
|
||||
secrets:
|
||||
- source: rabbitmq_config
|
||||
target: rabbitmq.conf
|
||||
volumes:
|
||||
- brokerdata:/var/lib/rabbitmq
|
||||
healthcheck:
|
||||
test: ["CMD", "rabbitmq-diagnostics", "-q", "ping"]
|
||||
interval: 3s
|
||||
timeout: 5s
|
||||
retries: 40
|
||||
stop_grace_period: 10s
|
||||
|
||||
worker:
|
||||
<<: *app
|
||||
command: ["python", "-m", "src.worker"]
|
||||
mem_limit: 768m
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
disable: true
|
||||
depends_on:
|
||||
broker:
|
||||
condition: service_healthy
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
bootstrap:
|
||||
condition: service_completed_successfully
|
||||
|
||||
api1: &api
|
||||
<<: *app
|
||||
mem_limit: 768m
|
||||
depends_on:
|
||||
broker:
|
||||
condition: service_healthy
|
||||
db:
|
||||
condition: service_healthy
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
bootstrap:
|
||||
condition: service_completed_successfully
|
||||
|
||||
api2:
|
||||
<<: *api
|
||||
|
||||
cleanup:
|
||||
<<: *app
|
||||
command: ["python", "-m", "src.cleanup"]
|
||||
restart: unless-stopped
|
||||
healthcheck:
|
||||
disable: true
|
||||
depends_on:
|
||||
migrate:
|
||||
condition: service_completed_successfully
|
||||
bootstrap:
|
||||
condition: service_completed_successfully
|
||||
|
||||
lb:
|
||||
image: haproxy:3.2.26@sha256:1242e4006ac3f1ed15871efadca3d8d089e76f720017a1c51747133ee40cc953
|
||||
ports:
|
||||
- "127.0.0.1:${HTTP_PORT:-8080}:8080"
|
||||
volumes:
|
||||
- ./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro
|
||||
depends_on:
|
||||
api1:
|
||||
condition: service_started
|
||||
api2:
|
||||
condition: service_started
|
||||
stop_grace_period: 3s
|
||||
|
||||
otel-collector:
|
||||
image: otel/opentelemetry-collector-contrib:0.165.0@sha256:e40d61f10c9a617cca1ffd1be4d7e2b3a4b0f0001798ff07e58cabe82e618cea
|
||||
command: ["--config=/etc/otel/collector.yaml"]
|
||||
volumes:
|
||||
- ./infra/otel/collector.yaml:/etc/otel/collector.yaml:ro
|
||||
mem_limit: 256m
|
||||
restart: unless-stopped
|
||||
depends_on:
|
||||
- loki
|
||||
- tempo
|
||||
stop_grace_period: 10s
|
||||
|
||||
prometheus:
|
||||
image: prom/prometheus:v3.16.0@sha256:e04987641b57704f408e31f6373ba4138ecf27cb4a165d24aabb6c38fddd0f06
|
||||
command: ["--config.file=/etc/prometheus/prometheus.yaml", "--storage.tsdb.path=/prometheus",
|
||||
"--storage.tsdb.retention.time=24h", "--storage.tsdb.retention.size=1GB"]
|
||||
volumes:
|
||||
- ./infra/otel/prometheus.yaml:/etc/prometheus/prometheus.yaml:ro
|
||||
- prometheusdata:/prometheus
|
||||
mem_limit: 512m
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 15s
|
||||
|
||||
loki:
|
||||
image: grafana/loki:3.7.10@sha256:b43c257ccfc925d4a50b8717cac61a3b51df8c48d01847936057e5c4075a24a7
|
||||
command: ["-config.file=/etc/loki/loki.yaml"]
|
||||
volumes:
|
||||
- ./infra/otel/loki.yaml:/etc/loki/loki.yaml:ro
|
||||
- lokidata:/loki
|
||||
mem_limit: 512m
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 15s
|
||||
|
||||
tempo:
|
||||
image: grafana/tempo:3.1.1@sha256:64e2fbd56d9c2b3412a4b430a58ea59e91a670b1e75f920a0c702213ad145044
|
||||
command: ["-config.file=/etc/tempo/tempo.yaml"]
|
||||
volumes:
|
||||
- ./infra/otel/tempo.yaml:/etc/tempo/tempo.yaml:ro
|
||||
- tempodata:/var/tempo
|
||||
mem_limit: 768m
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 15s
|
||||
|
||||
grafana:
|
||||
image: grafana/grafana:13.3.1@sha256:0615ec4fbd4072004b7d86b46ded63013a74b7d6eb1119273dd89e8fa25c13cf
|
||||
environment:
|
||||
GF_SECURITY_ADMIN_USER: admin
|
||||
GF_SECURITY_ADMIN_PASSWORD__FILE: /run/secrets/grafana_password
|
||||
GF_USERS_ALLOW_SIGN_UP: 'false'
|
||||
GF_AUTH_ANONYMOUS_ENABLED: 'false'
|
||||
GF_ANALYTICS_REPORTING_ENABLED: 'false'
|
||||
GF_ANALYTICS_CHECK_FOR_UPDATES: 'false'
|
||||
ports:
|
||||
- "127.0.0.1:${GRAFANA_PORT:-3306}:3000"
|
||||
volumes:
|
||||
- grafanadata:/var/lib/grafana
|
||||
- ./infra/grafana/provisioning:/etc/grafana/provisioning:ro
|
||||
- ./infra/grafana/dashboards:/var/lib/grafana/dashboards:ro
|
||||
secrets:
|
||||
- grafana_password
|
||||
mem_limit: 384m
|
||||
restart: unless-stopped
|
||||
stop_grace_period: 10s
|
||||
|
||||
volumes:
|
||||
pgdata:
|
||||
s3data:
|
||||
brokerdata:
|
||||
prometheusdata:
|
||||
lokidata:
|
||||
tempodata:
|
||||
grafanadata:
|
||||
|
||||
networks:
|
||||
default:
|
||||
ipam:
|
||||
config:
|
||||
- subnet: ${LAB6_APP_SUBNET:-10.240.60.0/24}
|
||||
storage:
|
||||
internal: true
|
||||
ipam:
|
||||
config:
|
||||
- subnet: ${LAB6_STORAGE_SUBNET:-10.240.61.0/24}
|
||||
|
||||
secrets:
|
||||
postgres_password:
|
||||
file: ./secrets/postgres_password
|
||||
database_url:
|
||||
file: ./secrets/database_url
|
||||
cursor_key:
|
||||
file: ./secrets/cursor_key
|
||||
s3_config:
|
||||
file: ./secrets/s3_config.json
|
||||
s3_access_key_id:
|
||||
file: ./secrets/s3_access_key_id
|
||||
s3_secret_access_key:
|
||||
file: ./secrets/s3_secret_access_key
|
||||
s3_admin_access_key_id:
|
||||
file: ./secrets/s3_admin_access_key_id
|
||||
s3_admin_secret_access_key:
|
||||
file: ./secrets/s3_admin_secret_access_key
|
||||
broker_url:
|
||||
file: ./secrets/broker_url
|
||||
rabbitmq_config:
|
||||
file: ./secrets/rabbitmq.conf
|
||||
grafana_password:
|
||||
file: ./secrets/grafana_password
|
||||
@@ -0,0 +1,270 @@
|
||||
{
|
||||
"uid": "messenger-lab6",
|
||||
"title": "Мессенджер — ЛР7",
|
||||
"schemaVersion": 39,
|
||||
"version": 1,
|
||||
"editable": false,
|
||||
"refresh": "5s",
|
||||
"timezone": "browser",
|
||||
"time": {
|
||||
"from": "now-15m",
|
||||
"to": "now"
|
||||
},
|
||||
"tags": [
|
||||
"lab7"
|
||||
],
|
||||
"templating": {
|
||||
"list": [
|
||||
{
|
||||
"name": "service",
|
||||
"label": "Сервис (логи/трассы)",
|
||||
"type": "custom",
|
||||
"query": "messenger-api,messenger-worker",
|
||||
"multi": true,
|
||||
"includeAll": true,
|
||||
"allValue": ".*",
|
||||
"current": {
|
||||
"text": "All",
|
||||
"value": "$__all"
|
||||
}
|
||||
},
|
||||
{
|
||||
"name": "instance",
|
||||
"label": "API-реплика",
|
||||
"type": "query",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"query": "label_values(messenger_http_requests_total,service_instance_id)",
|
||||
"refresh": 2,
|
||||
"multi": true,
|
||||
"includeAll": true,
|
||||
"allValue": ".*",
|
||||
"current": {
|
||||
"text": "All",
|
||||
"value": "$__all"
|
||||
}
|
||||
}
|
||||
]
|
||||
},
|
||||
"panels": [
|
||||
{
|
||||
"id": 1,
|
||||
"title": "RPS API",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "reqps"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (service_instance_id) (rate(messenger_http_requests_total{service_instance_id=~\"$instance\",route!~\"/health/.*\"}[1m]))",
|
||||
"legendFormat": "{{service_instance_id}} {{outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 2,
|
||||
"title": "Серверные ошибки, запросов/с",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 0,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "reqps"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum(rate(messenger_http_requests_total{status_class=\"5xx\",service_instance_id=~\"$instance\",route!~\"/health/.*\"}[1m])) or vector(0)",
|
||||
"legendFormat": "{{service_instance_id}} {{outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 3,
|
||||
"title": "Доля 5xx",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 8,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "percentunit"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "(sum(rate(messenger_http_requests_total{status_class=\"5xx\",service_instance_id=~\"$instance\",route!~\"/health/.*\"}[1m])) or vector(0)) / clamp_min(sum(rate(messenger_http_requests_total{service_instance_id=~\"$instance\",route!~\"/health/.*\"}[1m])), 0.000001)",
|
||||
"legendFormat": "{{service_instance_id}} {{outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 4,
|
||||
"title": "Время API, среднее",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 8,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum(rate(messenger_http_duration_seconds_sum{service_instance_id=~\"$instance\",route!~\"/health/.*\"}[1m])) / clamp_min(sum(rate(messenger_http_duration_seconds_count{service_instance_id=~\"$instance\",route!~\"/health/.*\"}[1m])), 0.000001)",
|
||||
"legendFormat": "{{service_instance_id}} {{outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 5,
|
||||
"title": "Попытки worker, всего",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 16,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "short"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (outcome) (messenger_jobs_total)",
|
||||
"legendFormat": "{{service_instance_id}} {{outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 6,
|
||||
"title": "Время попытки worker, среднее",
|
||||
"type": "timeseries",
|
||||
"datasource": {
|
||||
"type": "prometheus",
|
||||
"uid": "prometheus"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 12,
|
||||
"y": 16,
|
||||
"w": 12,
|
||||
"h": 8
|
||||
},
|
||||
"fieldConfig": {
|
||||
"defaults": {
|
||||
"unit": "s"
|
||||
},
|
||||
"overrides": []
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "sum by (outcome) (rate(messenger_job_duration_seconds_sum[1m])) / clamp_min(sum by (outcome) (rate(messenger_job_duration_seconds_count[1m])), 0.000001)",
|
||||
"legendFormat": "{{service_instance_id}} {{outcome}}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 7,
|
||||
"title": "События API и worker",
|
||||
"type": "logs",
|
||||
"datasource": {
|
||||
"type": "loki",
|
||||
"uid": "loki"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 24,
|
||||
"w": 24,
|
||||
"h": 10
|
||||
},
|
||||
"options": {
|
||||
"showTime": true,
|
||||
"showLabels": true,
|
||||
"sortOrder": "Descending"
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"expr": "{service_name=~\"$service\"}"
|
||||
}
|
||||
]
|
||||
},
|
||||
{
|
||||
"id": 8,
|
||||
"title": "Трассы API и worker",
|
||||
"type": "table",
|
||||
"datasource": {
|
||||
"type": "tempo",
|
||||
"uid": "tempo"
|
||||
},
|
||||
"gridPos": {
|
||||
"x": 0,
|
||||
"y": 34,
|
||||
"w": 24,
|
||||
"h": 10
|
||||
},
|
||||
"targets": [
|
||||
{
|
||||
"refId": "A",
|
||||
"queryType": "traceql",
|
||||
"query": "{ resource.service.name =~ \"$service\" }",
|
||||
"limit": 20
|
||||
}
|
||||
]
|
||||
}
|
||||
]
|
||||
}
|
||||
@@ -0,0 +1,10 @@
|
||||
apiVersion: 1
|
||||
providers:
|
||||
- name: messenger
|
||||
orgId: 1
|
||||
folder: ЛР7
|
||||
type: file
|
||||
disableDeletion: true
|
||||
editable: false
|
||||
options:
|
||||
path: /var/lib/grafana/dashboards
|
||||
@@ -0,0 +1,39 @@
|
||||
apiVersion: 1
|
||||
datasources:
|
||||
- name: Prometheus
|
||||
uid: prometheus
|
||||
type: prometheus
|
||||
access: proxy
|
||||
url: http://prometheus:9090
|
||||
isDefault: true
|
||||
editable: false
|
||||
jsonData:
|
||||
timeInterval: 5s
|
||||
- name: Loki
|
||||
uid: loki
|
||||
type: loki
|
||||
access: proxy
|
||||
url: http://loki:3100
|
||||
editable: false
|
||||
jsonData:
|
||||
derivedFields:
|
||||
- name: Trace
|
||||
matcherRegex: trace_id
|
||||
matcherType: label
|
||||
datasourceUid: tempo
|
||||
url: '$${__value.raw}'
|
||||
- name: Tempo
|
||||
uid: tempo
|
||||
type: tempo
|
||||
access: proxy
|
||||
url: http://tempo:3200
|
||||
editable: false
|
||||
jsonData:
|
||||
tracesToLogsV2:
|
||||
datasourceUid: loki
|
||||
spanStartTimeShift: '-1m'
|
||||
spanEndTimeShift: '1m'
|
||||
filterByTraceID: true
|
||||
tags:
|
||||
- key: service.name
|
||||
value: service_name
|
||||
@@ -0,0 +1,48 @@
|
||||
global
|
||||
log stdout format raw local0
|
||||
maxconn 256
|
||||
|
||||
defaults
|
||||
mode http
|
||||
log global
|
||||
timeout connect 1s
|
||||
timeout client 60s
|
||||
timeout server 60s
|
||||
timeout check 3s
|
||||
retries 0
|
||||
http-error status 503 content-type application/json lf-string '{"error":{"code":"unavailable","message":"API temporarily unavailable","request_id":"%[unique-id]"}}' hdr X-Request-Id %[unique-id] hdr X-Instance-Id lb
|
||||
|
||||
resolvers docker
|
||||
nameserver local 127.0.0.11:53
|
||||
resolve_retries 2
|
||||
timeout resolve 1s
|
||||
timeout retry 1s
|
||||
hold valid 1s
|
||||
hold nx 1s
|
||||
hold obsolete 1s
|
||||
|
||||
frontend public
|
||||
bind :8443 ssl crt /run/server/bundle.pem ssl-min-ver TLSv1.2
|
||||
unique-id-format %[uuid()]
|
||||
stick-table type ip size 100k expire 10s store http_req_rate(1s)
|
||||
http-request set-header X-Forwarded-For %[src]
|
||||
http-request track-sc0 src if { path /api/v1/auth/sessions } METH_POST
|
||||
http-request return status 429 content-type application/json lf-string '{"error":{"code":"rate_limited","message":"Too many logins","request_id":"%[unique-id]"}}' hdr Retry-After 1 hdr X-Request-Id %[unique-id] hdr X-Instance-Id lb if { path /api/v1/auth/sessions } METH_POST { sc_http_req_rate(0) gt 20 }
|
||||
use_backend api_live if { path /health/live }
|
||||
default_backend api_ready
|
||||
|
||||
backend api_ready
|
||||
balance roundrobin
|
||||
option httpchk GET /health/ready
|
||||
http-check expect status 200
|
||||
default-server inter 1s fall 2 rise 1 resolvers docker init-addr libc,none
|
||||
server first api1:8443 check ssl verify required ca-file /run/pki/ca.crt crt /run/identity/bundle.pem verifyhost api1 sni str(api1) check-sni api1
|
||||
server second api2:8443 check ssl verify required ca-file /run/pki/ca.crt crt /run/identity/bundle.pem verifyhost api2 sni str(api2) check-sni api2
|
||||
|
||||
backend api_live
|
||||
balance roundrobin
|
||||
option httpchk GET /health/live
|
||||
http-check expect status 200
|
||||
default-server inter 1s fall 2 rise 1 resolvers docker init-addr libc,none
|
||||
server first api1:8443 check ssl verify required ca-file /run/pki/ca.crt crt /run/identity/bundle.pem verifyhost api1 sni str(api1) check-sni api1
|
||||
server second api2:8443 check ssl verify required ca-file /run/pki/ca.crt crt /run/identity/bundle.pem verifyhost api2 sni str(api2) check-sni api2
|
||||
@@ -0,0 +1,63 @@
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
http:
|
||||
endpoint: 0.0.0.0:4318
|
||||
|
||||
processors:
|
||||
memory_limiter:
|
||||
check_interval: 1s
|
||||
limit_mib: 192
|
||||
spike_limit_mib: 32
|
||||
batch:
|
||||
timeout: 1s
|
||||
send_batch_size: 128
|
||||
send_batch_max_size: 256
|
||||
|
||||
exporters:
|
||||
prometheus:
|
||||
endpoint: 0.0.0.0:8889
|
||||
resource_to_telemetry_conversion:
|
||||
enabled: true
|
||||
otlphttp/loki:
|
||||
endpoint: http://loki:3100/otlp
|
||||
timeout: 2s
|
||||
sending_queue:
|
||||
queue_size: 128
|
||||
num_consumers: 2
|
||||
retry_on_failure:
|
||||
initial_interval: 1s
|
||||
max_interval: 5s
|
||||
max_elapsed_time: 30s
|
||||
otlp_grpc/tempo:
|
||||
endpoint: tempo:4317
|
||||
tls:
|
||||
insecure: true
|
||||
timeout: 2s
|
||||
sending_queue:
|
||||
queue_size: 128
|
||||
num_consumers: 2
|
||||
retry_on_failure:
|
||||
initial_interval: 1s
|
||||
max_interval: 5s
|
||||
max_elapsed_time: 30s
|
||||
|
||||
extensions:
|
||||
health_check:
|
||||
endpoint: 0.0.0.0:13133
|
||||
|
||||
service:
|
||||
extensions: [health_check]
|
||||
pipelines:
|
||||
metrics:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [prometheus]
|
||||
logs:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlphttp/loki]
|
||||
traces:
|
||||
receivers: [otlp]
|
||||
processors: [memory_limiter, batch]
|
||||
exporters: [otlp_grpc/tempo]
|
||||
@@ -0,0 +1,45 @@
|
||||
auth_enabled: false
|
||||
server:
|
||||
http_listen_port: 3100
|
||||
common:
|
||||
path_prefix: /loki
|
||||
replication_factor: 1
|
||||
ring:
|
||||
kvstore:
|
||||
store: inmemory
|
||||
storage:
|
||||
filesystem:
|
||||
chunks_directory: /loki/chunks
|
||||
rules_directory: /loki/rules
|
||||
schema_config:
|
||||
configs:
|
||||
- from: 2024-01-01
|
||||
store: tsdb
|
||||
object_store: filesystem
|
||||
schema: v13
|
||||
index:
|
||||
prefix: index_
|
||||
period: 24h
|
||||
ingester:
|
||||
wal:
|
||||
enabled: true
|
||||
dir: /loki/wal
|
||||
limits_config:
|
||||
allow_structured_metadata: true
|
||||
retention_period: 24h
|
||||
ingestion_rate_mb: 4
|
||||
ingestion_burst_size_mb: 8
|
||||
otlp_config:
|
||||
resource_attributes:
|
||||
ignore_defaults: true
|
||||
attributes_config:
|
||||
- action: index_label
|
||||
attributes: [service.name, deployment.environment.name]
|
||||
- action: structured_metadata
|
||||
attributes: [service.version, service.instance.id]
|
||||
compactor:
|
||||
working_directory: /loki/compactor
|
||||
retention_enabled: true
|
||||
delete_request_store: filesystem
|
||||
analytics:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,7 @@
|
||||
global:
|
||||
scrape_interval: 5s
|
||||
evaluation_interval: 5s
|
||||
scrape_configs:
|
||||
- job_name: messenger
|
||||
static_configs:
|
||||
- targets: [otel-collector:8889]
|
||||
@@ -0,0 +1,22 @@
|
||||
target: all
|
||||
server:
|
||||
http_listen_port: 3200
|
||||
distributor:
|
||||
receivers:
|
||||
otlp:
|
||||
protocols:
|
||||
grpc:
|
||||
endpoint: 0.0.0.0:4317
|
||||
storage:
|
||||
trace:
|
||||
backend: local
|
||||
wal:
|
||||
path: /var/tempo/wal
|
||||
local:
|
||||
path: /var/tempo/blocks
|
||||
overrides:
|
||||
defaults:
|
||||
compaction:
|
||||
block_retention: 24h
|
||||
usage_report:
|
||||
reporting_enabled: false
|
||||
@@ -0,0 +1,40 @@
|
||||
CREATE TABLE users (
|
||||
id uuid PRIMARY KEY,
|
||||
username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'),
|
||||
display_name varchar(100) NOT NULL CHECK (length(btrim(display_name)) > 0),
|
||||
password_hash text NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
|
||||
CREATE TABLE chats (
|
||||
id uuid PRIMARY KEY,
|
||||
title varchar(100) NOT NULL CHECK (length(btrim(title)) > 0),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
|
||||
CREATE TABLE chat_members (
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
PRIMARY KEY (chat_id, user_id)
|
||||
);
|
||||
CREATE INDEX chat_members_user_idx ON chat_members(user_id, chat_id);
|
||||
CREATE INDEX chats_history_idx ON chats(created_at, id);
|
||||
|
||||
CREATE TABLE messages (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
sender_id uuid NOT NULL REFERENCES users(id),
|
||||
text varchar(4000) NOT NULL CHECK (length(btrim(text)) > 0),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
FOREIGN KEY (chat_id, sender_id) REFERENCES chat_members(chat_id, user_id)
|
||||
);
|
||||
CREATE INDEX messages_history_idx ON messages(chat_id, created_at, id);
|
||||
|
||||
CREATE TABLE sessions (
|
||||
token_hash char(64) PRIMARY KEY,
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
CHECK (expires_at > created_at)
|
||||
);
|
||||
CREATE INDEX sessions_expiry_idx ON sessions(expires_at);
|
||||
@@ -0,0 +1,15 @@
|
||||
CREATE TABLE idempotency_keys (
|
||||
user_id uuid NOT NULL REFERENCES users(id),
|
||||
method varchar(8) NOT NULL CHECK (method = 'POST'),
|
||||
path varchar(128) NOT NULL,
|
||||
request_key varchar(128) NOT NULL CHECK (request_key ~ '^[A-Za-z0-9._:-]{1,128}$'),
|
||||
request_hash char(64) NOT NULL,
|
||||
message_id uuid NOT NULL REFERENCES messages(id),
|
||||
response_status smallint NOT NULL CHECK (response_status = 201),
|
||||
response_body jsonb NOT NULL,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
expires_at timestamptz NOT NULL,
|
||||
PRIMARY KEY (user_id, method, path, request_key),
|
||||
CHECK (expires_at > created_at)
|
||||
);
|
||||
CREATE INDEX idempotency_expiry_idx ON idempotency_keys(expires_at);
|
||||
@@ -0,0 +1,38 @@
|
||||
CREATE TABLE attachments (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
owner_id uuid NOT NULL REFERENCES users(id),
|
||||
filename varchar(255) NOT NULL,
|
||||
content_type text NOT NULL CHECK (content_type IN ('image/png', 'image/jpeg')),
|
||||
size_bytes integer NOT NULL CHECK (size_bytes BETWEEN 1 AND 10485760),
|
||||
sha256 char(64) NOT NULL CHECK (sha256 ~ '^[a-f0-9]{64}$'),
|
||||
object_key text NOT NULL UNIQUE,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
updated_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
UNIQUE (id, chat_id),
|
||||
FOREIGN KEY (chat_id, owner_id) REFERENCES chat_members(chat_id, user_id)
|
||||
);
|
||||
CREATE INDEX attachments_chat_idx ON attachments(chat_id, created_at, id);
|
||||
|
||||
ALTER TABLE messages DROP CONSTRAINT messages_text_check;
|
||||
ALTER TABLE messages ADD CONSTRAINT messages_id_chat_unique UNIQUE (id, chat_id);
|
||||
|
||||
CREATE TABLE message_attachments (
|
||||
message_id uuid NOT NULL,
|
||||
attachment_id uuid NOT NULL,
|
||||
chat_id uuid NOT NULL,
|
||||
position smallint NOT NULL CHECK (position BETWEEN 0 AND 9),
|
||||
PRIMARY KEY (message_id, attachment_id),
|
||||
UNIQUE (message_id, position),
|
||||
FOREIGN KEY (message_id, chat_id) REFERENCES messages(id, chat_id),
|
||||
FOREIGN KEY (attachment_id, chat_id) REFERENCES attachments(id, chat_id)
|
||||
);
|
||||
|
||||
CREATE TABLE upload_intents (
|
||||
id uuid PRIMARY KEY,
|
||||
chat_id uuid NOT NULL REFERENCES chats(id),
|
||||
owner_id uuid NOT NULL REFERENCES users(id),
|
||||
object_key text NOT NULL UNIQUE,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE INDEX upload_intents_age_idx ON upload_intents(created_at, id);
|
||||
@@ -0,0 +1,27 @@
|
||||
ALTER TABLE attachments ADD COLUMN status text NOT NULL DEFAULT 'ready'
|
||||
CHECK (status IN ('queued','processing','ready','failed'));
|
||||
ALTER TABLE attachments ADD COLUMN error_code text;
|
||||
ALTER TABLE attachments ADD COLUMN staging_deleted boolean NOT NULL DEFAULT false;
|
||||
|
||||
CREATE TABLE attachment_jobs (
|
||||
id uuid PRIMARY KEY,
|
||||
attachment_id uuid NOT NULL UNIQUE REFERENCES attachments(id),
|
||||
pipeline_version integer NOT NULL DEFAULT 1 CHECK (pipeline_version = 1),
|
||||
staging_key text NOT NULL UNIQUE,
|
||||
attempt integer NOT NULL DEFAULT 0,
|
||||
next_attempt_at timestamptz NOT NULL DEFAULT clock_timestamp(),
|
||||
published_at timestamptz,
|
||||
created_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
);
|
||||
CREATE TABLE attachment_variants (
|
||||
attachment_id uuid NOT NULL REFERENCES attachments(id),
|
||||
pipeline_version integer NOT NULL DEFAULT 1,
|
||||
name text NOT NULL CHECK (name = 'thumbnail'),
|
||||
content_type text NOT NULL,
|
||||
width integer NOT NULL,
|
||||
height integer NOT NULL,
|
||||
size_bytes integer NOT NULL,
|
||||
sha256 char(64) NOT NULL,
|
||||
object_key text NOT NULL UNIQUE,
|
||||
PRIMARY KEY (attachment_id,pipeline_version,name)
|
||||
);
|
||||
@@ -0,0 +1,20 @@
|
||||
attrs==26.1.0
|
||||
certifi==2026.10.23
|
||||
charset-normalizer==3.5.2
|
||||
idna==3.20
|
||||
jsonschema==4.26.0
|
||||
jsonschema-path==0.3.4
|
||||
jsonschema-specifications==2025.9.1
|
||||
lazy-object-proxy==1.13.0
|
||||
openapi-schema-validator==0.6.3
|
||||
openapi-spec-validator==0.7.2
|
||||
pathable==0.4.4
|
||||
pyyaml==6.0.3
|
||||
referencing==0.36.2
|
||||
requests==2.34.2
|
||||
rfc3339-validator==0.1.4
|
||||
rpds-py==2026.9.1
|
||||
six==1.17.0
|
||||
urllib3==2.8.0
|
||||
|
||||
cryptography==51.0.0
|
||||
@@ -0,0 +1,43 @@
|
||||
annotated-doc==0.0.5
|
||||
annotated-types==0.8.0
|
||||
anyio==4.16.0
|
||||
argon2-cffi-bindings==26.1.0
|
||||
argon2-cffi==25.1.0
|
||||
boto3==1.44.3
|
||||
botocore==1.44.3
|
||||
certifi==2026.10.23
|
||||
cffi==2.1.1
|
||||
charset-normalizer==3.5.2
|
||||
click==8.5.1
|
||||
fastapi==0.162.2
|
||||
googleapis-common-protos==1.76.0
|
||||
h11==0.16.0
|
||||
idna==3.20
|
||||
jmespath==1.1.0
|
||||
opentelemetry-api==1.45.2
|
||||
opentelemetry-exporter-http-transport==0.66b2
|
||||
opentelemetry-exporter-otlp-common==0.66b2
|
||||
opentelemetry-exporter-otlp-proto-common==1.45.2
|
||||
opentelemetry-exporter-otlp-proto-http==1.45.2
|
||||
opentelemetry-proto==1.45.2
|
||||
opentelemetry-sdk==1.45.2
|
||||
opentelemetry-semantic-conventions==0.66b2
|
||||
pika==1.4.4
|
||||
pillow==13.0.0
|
||||
protobuf==7.36.2
|
||||
psycopg-binary==3.3.8
|
||||
psycopg-pool==3.3.3
|
||||
psycopg==3.3.8
|
||||
pycparser==3.12
|
||||
pydantic==2.14.3
|
||||
pydantic_core==2.50.4
|
||||
python-dateutil==2.9.0.post0
|
||||
requests==2.34.2
|
||||
s3transfer==0.19.3
|
||||
six==1.17.0
|
||||
starlette==1.10.0
|
||||
typing-inspection==0.4.5
|
||||
typing_extensions==4.16.0
|
||||
tzdata==2026.6
|
||||
urllib3==2.8.0
|
||||
uvicorn==0.54.0
|
||||
@@ -0,0 +1,66 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
||||
from scripts import provision as p
|
||||
|
||||
|
||||
def compose(*args, input=None):
|
||||
result=subprocess.run(['docker','compose','--project-name',p.PROJECT,'--env-file','.env',*args],
|
||||
cwd=p.ROOT,input=input,text=True,capture_output=True,encoding='utf-8')
|
||||
if result.returncode:
|
||||
raise RuntimeError('Operator command failed: ' + ' '.join(args[:3]))
|
||||
return result.stdout
|
||||
|
||||
|
||||
def sql(statement):
|
||||
return compose('exec','-T','db','psql','-U','messenger','-d','messenger','-v','ON_ERROR_STOP=1','-At','-f','-',input=statement)
|
||||
|
||||
|
||||
def grants():
|
||||
v=p.values()
|
||||
statement=''
|
||||
for role in ('api','worker','cleanup'):
|
||||
statement+=f"DO $$ BEGIN CREATE ROLE {role} LOGIN; EXCEPTION WHEN duplicate_object THEN NULL; END $$; ALTER ROLE {role} PASSWORD '{v[role+'_db']}';\n"
|
||||
statement+='REVOKE ALL ON SCHEMA public FROM PUBLIC; GRANT USAGE ON SCHEMA public TO api,worker,cleanup;\n'
|
||||
statement+='GRANT SELECT ON ALL TABLES IN SCHEMA public TO api;\n'
|
||||
statement+='GRANT INSERT ON users,chats,chat_members,messages,message_attachments,sessions,idempotency_keys,attachments,attachment_jobs,upload_intents TO api;\n'
|
||||
statement+='GRANT DELETE ON sessions,idempotency_keys,upload_intents TO api; GRANT UPDATE ON upload_intents TO api; GRANT UPDATE(published_at) ON attachment_jobs TO api;\n'
|
||||
statement+='GRANT SELECT ON attachments,attachment_jobs,attachment_variants,schema_migrations TO worker; GRANT INSERT,UPDATE ON attachment_variants TO worker;\n'
|
||||
statement+='GRANT UPDATE(status,error_code,updated_at) ON attachments TO worker; GRANT UPDATE(attempt,next_attempt_at) ON attachment_jobs TO worker;\n'
|
||||
statement+='GRANT SELECT ON attachments,attachment_jobs,upload_intents,schema_migrations TO cleanup; GRANT UPDATE,DELETE ON upload_intents TO cleanup; GRANT UPDATE(status,error_code,updated_at,staging_deleted) ON attachments TO cleanup;\n'
|
||||
sql(statement)
|
||||
print('PASS: separate database roles configured')
|
||||
|
||||
|
||||
def main():
|
||||
action=sys.argv[1]
|
||||
if action=='setup':
|
||||
p.pki();p.configuration()
|
||||
print('Local PKI/configuration ready; operator profile encrypted outside repository')
|
||||
elif action=='bao-bootstrap':
|
||||
deadline=time.monotonic()+90
|
||||
while True:
|
||||
try:
|
||||
p.bao_request('sys/init');break
|
||||
except Exception:
|
||||
if time.monotonic()>deadline:raise RuntimeError('OpenBao TLS startup timeout') from None
|
||||
time.sleep(1)
|
||||
p.bootstrap_bao();print('PASS: OpenBao initialized/unsealed, cert auth and scoped policies configured')
|
||||
elif action=='pki-renew':
|
||||
p.pki(renew=True);p.configuration();state=p.operator_load();state['renew_roles']=True;p.operator_save(state)
|
||||
print('Leaf certificates reissued; CA and application data preserved')
|
||||
elif action=='grants':
|
||||
grants()
|
||||
elif action=='bao-unseal':
|
||||
p.unseal();print('OpenBao unsealed')
|
||||
elif action=='bao-status':
|
||||
status=p.bao_request('sys/seal-status');print(json.dumps({k:status[k] for k in ('sealed','initialized','type')}))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
+693
@@ -0,0 +1,693 @@
|
||||
import argparse
|
||||
from datetime import datetime, timezone
|
||||
import hashlib
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import platform
|
||||
import secrets
|
||||
import shutil
|
||||
import socket
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from urllib.error import URLError
|
||||
from urllib.request import ProxyHandler, build_opener
|
||||
import venv
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
LOG = []
|
||||
LOCAL_HTTP = build_opener(ProxyHandler({}))
|
||||
|
||||
|
||||
def settings():
|
||||
path = ROOT / ".env"
|
||||
result = {}
|
||||
if path.exists():
|
||||
for line in path.read_text(encoding="utf-8-sig").splitlines():
|
||||
key, separator, value = line.partition("=")
|
||||
if separator and not key.strip().startswith("#"):
|
||||
result[key.strip()] = value.strip()
|
||||
return result
|
||||
|
||||
|
||||
def environment(args):
|
||||
result = os.environ.copy()
|
||||
result.update(PYTHONUTF8="1", PYTHONIOENCODING="utf-8", PYTHONDONTWRITEBYTECODE="1",
|
||||
COMPOSE_PROJECT_NAME=args.project, HTTP_PORT=str(args.port),
|
||||
GRAFANA_PORT=str(getattr(args, "grafana_port", None) or (3311 if args.project.endswith("-ttl") else (3310 if "clean" in args.project else int(settings().get("GRAFANA_PORT", "3309"))))),
|
||||
SESSION_TTL_SECONDS=str(args.ttl), LAB7_PROJECT=args.project,
|
||||
LAB7_PORT=str(args.port), LAB7_TTL=str(args.ttl))
|
||||
result['CA_FILE'] = str(ROOT / 'runtime' / args.project / 'pki/ca.crt')
|
||||
result['BAO_TOKEN_TTL'] = '2' if args.project.endswith('-bao-ttl') else '900'
|
||||
result['BASE_URL'] = f'https://127.0.0.1:{args.port}'
|
||||
result['BAO_PORT'] = '18202' if args.project.endswith('-ttl') else ('18201' if 'clean' in args.project else '18200')
|
||||
result["LAB7_GRAFANA_PORT"] = result["GRAFANA_PORT"]
|
||||
subnet = 72 if args.project.endswith('-ttl') else (74 if 'clean' in args.project else 70)
|
||||
result['LAB7_APP_SUBNET'] = f'10.240.{subnet}.0/24'
|
||||
result['LAB7_STORAGE_SUBNET'] = f'10.240.{subnet+1}.0/24'
|
||||
for key in ("NO_PROXY", "no_proxy"):
|
||||
result[key] = ",".join(filter(None, [result.get(key), "localhost", "127.0.0.1"]))
|
||||
return result
|
||||
|
||||
|
||||
def say(value):
|
||||
line = str(value).replace(str(ROOT), ".")
|
||||
print(line, flush=True)
|
||||
LOG.append(line)
|
||||
|
||||
|
||||
def run(args, command, quiet=False):
|
||||
command = [str(item) for item in command]
|
||||
if not quiet:
|
||||
say("$ " + subprocess.list2cmdline(command))
|
||||
with subprocess.Popen(command, cwd=ROOT, env=environment(args), stdout=subprocess.PIPE,
|
||||
stderr=subprocess.STDOUT, text=True, encoding="utf-8", errors="replace") as process:
|
||||
lines = []
|
||||
for line in process.stdout:
|
||||
lines.append(line)
|
||||
if not quiet:
|
||||
say(line.rstrip())
|
||||
code = process.wait()
|
||||
if code:
|
||||
raise RuntimeError(f"{command[0]} exited with code {code}")
|
||||
return "".join(lines)
|
||||
|
||||
|
||||
def compose(args, *command, quiet=False):
|
||||
if args.project != "mtusi-lab7" and not args.project.startswith("mtusi-lab7-"):
|
||||
raise RuntimeError("Only lab7 projects are allowed")
|
||||
return run(args, ["docker", "compose", "--project-name", args.project, "--env-file", ".env", *command], quiet)
|
||||
|
||||
|
||||
def interpreter():
|
||||
return ROOT / ".venv" / ("Scripts/python.exe" if os.name == "nt" else "bin/python")
|
||||
|
||||
|
||||
def evidence(name, value):
|
||||
path = ROOT / "evidence" / name
|
||||
path.parent.mkdir(exist_ok=True)
|
||||
content = json.dumps(value, ensure_ascii=False, indent=2) if not isinstance(value, str) else value
|
||||
path.write_text(content.rstrip() + "\n", encoding="utf-8", newline="\n")
|
||||
|
||||
|
||||
def setup(args):
|
||||
if not (ROOT / '.env').exists():
|
||||
shutil.copyfile(ROOT / '.env.example', ROOT / '.env')
|
||||
if not interpreter().exists():
|
||||
venv.EnvBuilder(with_pip=True).create(ROOT / '.venv')
|
||||
locks = [ROOT / 'requirements.lock', ROOT / 'requirements-validation.lock']
|
||||
fingerprint = hashlib.sha256(b''.join(p.read_bytes() for p in locks)).hexdigest()
|
||||
marker = ROOT / '.venv/.lab-dependencies'
|
||||
if not marker.exists() or marker.read_text() != fingerprint:
|
||||
run(args, [interpreter(), '-m', 'pip', 'install', '--quiet', '--disable-pip-version-check', '-r', locks[0], '-r', locks[1]])
|
||||
marker.write_text(fingerprint)
|
||||
admin(args, 'setup')
|
||||
|
||||
|
||||
def admin(args, action):
|
||||
return run(args, [interpreter(), '-X', 'utf8', 'scripts/admin.py', action])
|
||||
|
||||
|
||||
def tls_opener(args):
|
||||
import ssl
|
||||
from urllib.request import HTTPSHandler
|
||||
return build_opener(ProxyHandler({}), HTTPSHandler(context=ssl.create_default_context(cafile=environment(args)['CA_FILE'])))
|
||||
|
||||
|
||||
def base_url(args):
|
||||
return f"https://127.0.0.1:{args.port}"
|
||||
|
||||
|
||||
def wait_storage(args, timeout=90):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
container = compose(args, "ps", "--all", "--quiet", "s3-storage", quiet=True).strip()
|
||||
if container:
|
||||
status = run(args, ["docker", "inspect", "--format", "{{.State.Health.Status}}", container], quiet=True).strip()
|
||||
if status == "healthy":
|
||||
return
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError("S3 storage readiness timeout")
|
||||
|
||||
|
||||
def wait_ready(args, timeout=90):
|
||||
wait_storage(args, timeout)
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
with tls_opener(args).open(base_url(args) + "/health/ready", timeout=4) as response:
|
||||
if response.status == 200 and json.load(response) == {"status": "ok"}:
|
||||
return
|
||||
except (URLError, OSError, ValueError):
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
raise RuntimeError("API readiness timeout")
|
||||
|
||||
|
||||
def build(args):
|
||||
compose(args, "config", "--quiet")
|
||||
compose(args, "build", "api1")
|
||||
compose(args, "run", "--rm", "--no-deps", "lb", "haproxy", "-c", "-f",
|
||||
"/usr/local/etc/haproxy/haproxy.cfg")
|
||||
|
||||
|
||||
def start(args):
|
||||
compose(args, 'up', '-d', '--no-build', 'db', 'openbao', 'broker', 's3-storage', 's3', 's3-tls')
|
||||
wait_storage(args)
|
||||
admin(args, 'bao-bootstrap')
|
||||
compose(args, 'run', '--rm', '--no-deps', 'migrate')
|
||||
admin(args, 'grants')
|
||||
compose(args, 'run', '--rm', '--no-deps', 'bootstrap')
|
||||
compose(args, 'up', '-d', '--no-build', 'loki', 'tempo', 'prometheus', 'loki-tls', 'tempo-tls', 'prometheus-tls',
|
||||
'otel-collector', 'otel-collector-tls', 'grafana', 'api1', 'api2', 'worker', 'cleanup', 'api1-tls', 'api2-tls', 'lb')
|
||||
wait_ready(args)
|
||||
wait_replicas(args)
|
||||
say('Two API replicas ready over verified HTTPS: ' + base_url(args))
|
||||
|
||||
|
||||
def states(args):
|
||||
services = ("api1", "api2", "db", "lb", "s3", "s3-storage", "cleanup", "broker", "worker", "otel-collector", "prometheus", "loki", "tempo", "grafana", "openbao", "api1-tls", "api2-tls", "s3-tls", "otel-collector-tls", "loki-tls", "tempo-tls", "prometheus-tls")
|
||||
containers = compose(args, "ps", "--all", "--quiet", *services, quiet=True).split()
|
||||
if len(set(containers)) != len(services):
|
||||
raise RuntimeError("Missing runtime container")
|
||||
result = {}
|
||||
for data in json.loads(run(args, ["docker", "inspect", *containers], quiet=True)):
|
||||
labels = data["Config"].get("Labels", {})
|
||||
service = labels.get("com.docker.compose.service")
|
||||
if labels.get("com.docker.compose.project") != args.project or service not in services or service in result:
|
||||
raise RuntimeError("Unexpected container ownership")
|
||||
result[service] = {
|
||||
"id": data["Id"], "image": data["Image"], "started_at": data["State"]["StartedAt"],
|
||||
"running": data["State"]["Running"], "oom_killed": data["State"]["OOMKilled"],
|
||||
"restart_count": data["RestartCount"], "user": data["Config"]["User"],
|
||||
"volumes": [mount["Name"] for mount in data["Mounts"] if mount["Type"] == "volume"],
|
||||
}
|
||||
return result
|
||||
|
||||
|
||||
def restart(args):
|
||||
before = states(args)
|
||||
compose(args, 'stop', '--timeout', '10')
|
||||
start(args)
|
||||
after = states(args)
|
||||
for name in before:
|
||||
if before[name]['started_at'] == after[name]['started_at'] or before[name]['volumes'] != after[name]['volumes']:
|
||||
raise RuntimeError('Restart/volume mismatch: ' + name)
|
||||
evidence('restart.json', {'before': before, 'after': after, 'operator_unseal': True})
|
||||
say('PASS: all runtime services restarted, OpenBao unsealed, volumes preserved')
|
||||
|
||||
|
||||
def contract_tests(args):
|
||||
run(args, [interpreter(), "-X", "utf8", "scripts/check_contract.py"])
|
||||
run(args, [interpreter(), "-X", "utf8", "scripts/validate_openapi.py"])
|
||||
compose(args, "config", "--quiet")
|
||||
|
||||
|
||||
def api_tests(args):
|
||||
wait_ready(args)
|
||||
run(args, [interpreter(), "-X", "utf8", "tests/smoke.py", "--base-url", base_url(args)])
|
||||
os.environ["BASE_URL"] = base_url(args)
|
||||
run(args, [interpreter(), "-X", "utf8", "-m", "unittest", "discover", "-s", "student-tests", "-v"])
|
||||
|
||||
|
||||
def client(args):
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client
|
||||
for key in ("NO_PROXY", "no_proxy"):
|
||||
os.environ[key] = environment(args)[key]
|
||||
return Client(base_url(args), ca_file=environment(args)["CA_FILE"])
|
||||
|
||||
|
||||
def database_stats(args):
|
||||
sql = """SELECT json_build_object(
|
||||
'users',(SELECT count(*) FROM users),'chats',(SELECT count(*) FROM chats),
|
||||
'members',(SELECT count(*) FROM chat_members),'messages',(SELECT count(*) FROM messages),
|
||||
'sessions',(SELECT count(*) FROM sessions),'migrations',(SELECT count(*) FROM schema_migrations),
|
||||
'idempotency_keys',(SELECT count(*) FROM idempotency_keys),
|
||||
'attachments',(SELECT count(*) FROM attachments),'message_attachments',(SELECT count(*) FROM message_attachments),
|
||||
'upload_intents',(SELECT count(*) FROM upload_intents),
|
||||
'expiry_fingerprint',(SELECT md5(COALESCE(string_agg(user_id::text || created_at::text || expires_at::text,
|
||||
',' ORDER BY token_hash),'')) FROM sessions),
|
||||
'passwords_are_argon2id',(SELECT bool_and(password_hash LIKE '$argon2id$%') FROM users),
|
||||
'session_hashes_only',(SELECT bool_and(token_hash ~ '^[0-9a-f]{64}$') FROM sessions))"""
|
||||
result = compose(args, "exec", "-T", "db", "psql", "-U", "messenger", "-d", "messenger",
|
||||
"-At", "-c", sql, quiet=True)
|
||||
return json.loads(result)
|
||||
|
||||
|
||||
def restart_check(args):
|
||||
from urllib.parse import urlencode
|
||||
c = client(args)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
replay_key = secrets.token_hex(16)
|
||||
original = c.message(alice, chat, "first", key=replay_key)["json"]
|
||||
last = c.message(bob, chat, "second")["json"]
|
||||
page = c.call("GET", path + "?limit=1", actor=alice, schema="MessagePage")["json"]
|
||||
revoked = c.user("revoked")
|
||||
c.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=revoked)
|
||||
hook = ROOT / "scripts" / ("restart.cmd" if os.name == "nt" else "restart.sh")
|
||||
run(args, [interpreter(), "-X", "utf8", "tests/resilience.py", "--mode", "persistence",
|
||||
"--action-script", hook, "--base-url", base_url(args)])
|
||||
continued = c.call("GET", path + "?" + urlencode({"cursor": page["next_cursor"]}),
|
||||
actor=alice, schema="MessagePage")["json"]
|
||||
if continued != {"items": [last], "next_cursor": None}:
|
||||
raise RuntimeError("Old cursor did not survive restart")
|
||||
c.call("GET", "/api/v1/users/me", 401, actor=revoked)
|
||||
c.call("GET", "/api/v1/chats/" + chat["id"], 404, actor=eve)
|
||||
before = database_stats(args)
|
||||
compose(args, "run", "--rm", "--no-deps", "migrate")
|
||||
compose(args, "run", "--rm", "--no-deps", "migrate")
|
||||
after = database_stats(args)
|
||||
stable_before = {key: value for key, value in before.items() if key != "upload_intents"}
|
||||
stable_after = {key: value for key, value in after.items() if key != "upload_intents"}
|
||||
if stable_before != stable_after or after["migrations"] != 4:
|
||||
raise RuntimeError("Migration replay changed existing data")
|
||||
if not after["passwords_are_argon2id"] or not after["session_hashes_only"]:
|
||||
raise RuntimeError("Unexpected credential representation in DB")
|
||||
repeated = c.message(alice, chat, "first", key=replay_key)["json"]
|
||||
if repeated != original:
|
||||
raise RuntimeError("Idempotency result was not preserved")
|
||||
result = {"idempotency_after_restart": "PASS", "public_persistence": "PASS", "cursor_after_restart": "PASS",
|
||||
"logout_after_restart": "PASS", "migration_replay": "PASS", "database": after}
|
||||
evidence("persistence.json", result)
|
||||
say("PASS: old session/cursor, durable logout and repeatable migrations")
|
||||
return result
|
||||
|
||||
|
||||
def ttl_check(args):
|
||||
test = argparse.Namespace(project=args.project + "-ttl", port=args.test_port, ttl=2,
|
||||
test_port=args.test_port, action="start")
|
||||
try:
|
||||
setup(test)
|
||||
start(test)
|
||||
c = client(test)
|
||||
actor = c.user("expiry")
|
||||
c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
before = database_stats(test)["expiry_fingerprint"]
|
||||
compose(test, "stop", "--timeout", "3", "api1-tls", "api2-tls")
|
||||
compose(test, "restart", "--timeout", "3", "api1", "api2")
|
||||
compose(test, "start", "api1-tls", "api2-tls")
|
||||
wait_ready(test)
|
||||
after = database_stats(test)["expiry_fingerprint"]
|
||||
if before != after:
|
||||
raise RuntimeError("Session expiry changed during restart")
|
||||
time.sleep(2.2)
|
||||
c.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
registration = actor["registration"]
|
||||
import base64
|
||||
basic = base64.b64encode((registration["username"] + ":" + registration["password"]).encode()).decode()
|
||||
c.call("POST", "/api/v1/auth/sessions", 201, headers={"Authorization": "Basic " + basic}, schema="Session")
|
||||
say("PASS: TTL=2, expired token rejected after API restart; fresh login works")
|
||||
result = {"ttl_seconds": 2, "expiry_unchanged_on_restart": True, "before_restart": 200,
|
||||
"after_expiry_and_restart": 401, "new_login": 201}
|
||||
evidence("expiry.json", result)
|
||||
return result
|
||||
finally:
|
||||
compose(test, "down", "--timeout", "10")
|
||||
|
||||
|
||||
def dependency_check(args):
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import Request
|
||||
c = client(args)
|
||||
actor = c.user('dependencies')
|
||||
result = {}
|
||||
for service in ('db', 's3', 'broker'):
|
||||
try:
|
||||
compose(args, 'stop', '--timeout', '10', service)
|
||||
c.call('GET', '/health/live', schema='Health')
|
||||
outage_response(args, '/health/ready')
|
||||
deadline = time.monotonic() + 20
|
||||
while True:
|
||||
try:
|
||||
with tls_opener(args).open(Request(base_url(args) + '/api/v1/users/me',
|
||||
headers={'Authorization': 'Bearer ' + actor['token']}), timeout=5) as response:
|
||||
if response.status != 200:
|
||||
raise RuntimeError('Unexpected dependency response')
|
||||
except HTTPError as error:
|
||||
if error.code != 503:
|
||||
raise RuntimeError('Unexpected dependency status') from None
|
||||
error.close()
|
||||
break
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError('LB did not withdraw unready replicas')
|
||||
time.sleep(0.3)
|
||||
outage_response(args, '/api/v1/users/me', actor['token'])
|
||||
finally:
|
||||
compose(args, 'start', service)
|
||||
wait_ready(args)
|
||||
c.call('GET', '/api/v1/users/me', actor=actor, schema='User')
|
||||
result[service] = {'live': 200, 'ready': 503, 'business': 503, 'recovered': 200}
|
||||
say('PASS: ' + service + ' outage and recovery')
|
||||
return result
|
||||
|
||||
|
||||
def observability_check(args, mode):
|
||||
run(args, [interpreter(), '-X', 'utf8', 'scripts/observability_checks.py', mode])
|
||||
return json.loads((ROOT / ('evidence/' + mode + '.json')).read_text(encoding='utf-8'))
|
||||
|
||||
|
||||
def verify(args):
|
||||
summary = {"date_utc": datetime.now(timezone.utc).isoformat(), "platform": platform.platform(),
|
||||
"source_commit": run(args, ["git", "rev-parse", "HEAD"], quiet=True).strip(),
|
||||
"worktree_dirty_at_start": bool(run(args, ["git", "status", "--porcelain"], quiet=True).strip()),
|
||||
"project": args.project, "status": "FAIL"}
|
||||
try:
|
||||
setup(args)
|
||||
contract_tests(args)
|
||||
build(args)
|
||||
start(args)
|
||||
api_tests(args)
|
||||
summary["queue"] = queue_check(args)
|
||||
summary["retry"] = retry_check(args)
|
||||
summary["persistence"] = restart_check(args)
|
||||
summary["failover"] = failover_check(args)
|
||||
summary["attachments_failover"] = attachment_failover_check(args)
|
||||
summary["expiry"] = ttl_check(args)
|
||||
summary["dependency"] = dependency_check(args)
|
||||
run(args, [interpreter(), "-X", "utf8", "tests/smoke.py", "--base-url", base_url(args)])
|
||||
summary["telemetry"] = observability_check(args, 'telemetry')
|
||||
summary["incidents"] = observability_check(args, 'incidents')
|
||||
summary["telemetry_outage"] = observability_check(args, 'outage')
|
||||
run(args, [interpreter(),'-X','utf8','tests/security.py','--base-url',base_url(args)])
|
||||
run(args, [interpreter(),'-X','utf8','scripts/security_checks.py','security-check'])
|
||||
run(args, [interpreter(),'-X','utf8','scripts/security_checks.py','bao-check'])
|
||||
summary['security'] = json.loads((ROOT/'evidence/policies.json').read_text())
|
||||
summary['bao_expiry'] = json.loads((ROOT/'evidence/bao-expiry.json').read_text())
|
||||
summary["containers"] = states(args)
|
||||
summary["docker"] = run(args, ["docker", "version", "--format", "{{.Server.Version}}"], quiet=True).strip()
|
||||
summary["resources"] = json.loads(run(
|
||||
args, ["docker", "info", "--format", '{"cpus":{{.NCPU}},"memory_bytes":{{.MemTotal}}}'], quiet=True))
|
||||
summary["status"] = "PASS"
|
||||
say("PASS: full lab7 verification")
|
||||
finally:
|
||||
evidence("verification.txt", "\n".join(LOG))
|
||||
evidence("summary.json", summary)
|
||||
|
||||
|
||||
def instance_map(args):
|
||||
current = states(args)
|
||||
result = {}
|
||||
for service in ("api1", "api2"):
|
||||
item = current[service]
|
||||
if not item["running"]:
|
||||
continue
|
||||
code = (
|
||||
"import urllib.request; "
|
||||
"o=urllib.request.build_opener(urllib.request.ProxyHandler({})); "
|
||||
"r=o.open('http://127.0.0.1:8080/health/live',timeout=1); "
|
||||
"print(r.headers['X-Instance-Id'])"
|
||||
)
|
||||
alias = run(args, ["docker", "exec", item["id"], "python", "-c", code], quiet=True).strip()
|
||||
import re
|
||||
if not re.fullmatch(r"[0-9a-f]{32}", alias):
|
||||
raise RuntimeError("Invalid API instance alias")
|
||||
result[service] = {"instance_id": alias, "container_id": item["id"]}
|
||||
return result
|
||||
|
||||
|
||||
def wait_replicas(args):
|
||||
deadline = time.monotonic() + 90
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
mapping = instance_map(args)
|
||||
if len(mapping) == 2:
|
||||
c = client(args)
|
||||
seen = {c.call("GET", "/health/ready", schema="Health")["headers"]["X-Instance-Id"]
|
||||
for _ in range(8)}
|
||||
if seen == {item["instance_id"] for item in mapping.values()}:
|
||||
return mapping
|
||||
except (RuntimeError, OSError, AssertionError):
|
||||
pass
|
||||
time.sleep(0.3)
|
||||
raise RuntimeError("Two healthy API replicas were not observed through LB")
|
||||
|
||||
|
||||
def restore(args):
|
||||
compose(args, "start", "api1", "api2")
|
||||
compose(args, "restart", "api1-tls", "api2-tls")
|
||||
wait_ready(args)
|
||||
return wait_replicas(args)
|
||||
|
||||
|
||||
def stop_one(args):
|
||||
target = os.environ.get("TARGET_INSTANCE_ID", "")
|
||||
before = instance_map(args)
|
||||
matches = [(name, item) for name, item in before.items() if item["instance_id"] == target]
|
||||
if len(before) != 2 or len(matches) != 1:
|
||||
raise RuntimeError("Target must match exactly one of two running API replicas")
|
||||
service, item = matches[0]
|
||||
started = time.monotonic()
|
||||
compose(args, "stop", "--timeout", "3", service + "-tls", service)
|
||||
after = states(args)
|
||||
if after[service]["running"] or not after["api1" if service == "api2" else "api2"]["running"]:
|
||||
raise RuntimeError("Unexpected API state after stop")
|
||||
elapsed = time.monotonic() - started
|
||||
if elapsed >= 10:
|
||||
raise RuntimeError("Stopping the selected API exceeded 10 seconds")
|
||||
evidence("stop-one.json", {"service": service, "target_instance": target, "before": before,
|
||||
"after": after, "stop_seconds": round(elapsed, 3)})
|
||||
say("Stopped only " + service)
|
||||
|
||||
|
||||
def failover_check(args):
|
||||
wait_replicas(args)
|
||||
hook = ROOT / "scripts" / ("stop-one.cmd" if os.name == "nt" else "stop-one.sh")
|
||||
try:
|
||||
output = run(args, [interpreter(), "-X", "utf8", "tests/resilience.py", "--mode", "failover",
|
||||
"--action-script", hook, "--base-url", base_url(args)])
|
||||
first = json.loads((ROOT / "evidence/stop-one.json").read_text(encoding="utf-8"))
|
||||
first["metrics"] = next(json.loads(line) for line in output.splitlines()
|
||||
if line.startswith("{") and "first_recovery_seconds" in line)
|
||||
if first["after"][first["service"]]["running"]:
|
||||
raise RuntimeError("Public hook did not leave the target stopped")
|
||||
finally:
|
||||
restore(args)
|
||||
other_service = "api2" if first["service"] == "api1" else "api1"
|
||||
mapping = instance_map(args)
|
||||
target = mapping[other_service]["instance_id"]
|
||||
c = client(args)
|
||||
c.timeout = 2
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
for _ in range(10):
|
||||
replay_key = secrets.token_hex(16)
|
||||
replay_text = "before-failure-" + replay_key
|
||||
response = c.message(alice, chat, replay_text, key=replay_key)
|
||||
if response["headers"]["X-Instance-Id"] == target:
|
||||
original = response["json"]
|
||||
break
|
||||
else:
|
||||
raise RuntimeError("Second API was not reached through LB")
|
||||
env = environment(args)
|
||||
env["TARGET_INSTANCE_ID"] = target
|
||||
started = time.monotonic()
|
||||
process = subprocess.Popen([str(hook)], cwd=ROOT, env=env, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
from client import Failure
|
||||
from resilience import history
|
||||
confirmations, after_instances = [], []
|
||||
failures = 0
|
||||
recovered = None
|
||||
key = secrets.token_hex(16)
|
||||
text = "during-failure-" + key
|
||||
try:
|
||||
while time.monotonic() - started < 15:
|
||||
code = process.poll()
|
||||
if code not in (None, 0):
|
||||
raise RuntimeError("Second stop hook failed")
|
||||
if code is None and time.monotonic() - started >= 10:
|
||||
raise RuntimeError("Second stop hook exceeded 10 seconds")
|
||||
try:
|
||||
response = c.message(alice, chat, text, key=key)
|
||||
confirmations.append(response["json"])
|
||||
if code == 0:
|
||||
if recovered is None:
|
||||
recovered = time.monotonic() - started
|
||||
after_instances.append(response["headers"]["X-Instance-Id"])
|
||||
key = secrets.token_hex(16)
|
||||
text = "during-failure-" + key
|
||||
except Failure:
|
||||
failures += 1
|
||||
time.sleep(0.1)
|
||||
if process.poll() != 0 or recovered is None or recovered > 10:
|
||||
raise RuntimeError("Second API failure did not recover within 10 seconds")
|
||||
if len(after_instances) < 5 or target in after_instances[-5:]:
|
||||
raise RuntimeError("Stopped API still serves requests")
|
||||
replayed = c.message(alice, chat, replay_text, key=replay_key)
|
||||
if replayed["json"] != original or replayed["headers"]["X-Instance-Id"] == target:
|
||||
raise RuntimeError("Message replay through the survivor changed the result")
|
||||
messages = history(c, bob, chat)
|
||||
ids = [item["id"] for item in messages]
|
||||
texts = [item["text"] for item in messages]
|
||||
if len(ids) != len(set(ids)) or len(texts) != len(set(texts)):
|
||||
raise RuntimeError("Duplicates appeared during failover")
|
||||
if any(item not in messages for item in [original, *confirmations]):
|
||||
raise RuntimeError("A confirmed message was lost")
|
||||
second = json.loads((ROOT / "evidence/stop-one.json").read_text(encoding="utf-8"))
|
||||
if second["service"] != other_service:
|
||||
raise RuntimeError("Wrong second API was stopped")
|
||||
second["metrics"] = {"successful_writes": len(confirmations), "failed_attempts": failures,
|
||||
"first_recovery_seconds": round(recovered, 3),
|
||||
"replay_on_survivor": "PASS"}
|
||||
result = {"public": first, "second_replica": second, "status": "PASS"}
|
||||
evidence("failover.json", result)
|
||||
say("PASS: both physical API replicas stopped separately; no lost messages or duplicates")
|
||||
return result
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.terminate()
|
||||
process.wait(timeout=5)
|
||||
restore(args)
|
||||
|
||||
|
||||
def outage_response(args, path, token=None):
|
||||
from urllib.error import HTTPError
|
||||
from urllib.request import Request
|
||||
from client import shape
|
||||
headers = {"Authorization": "Bearer " + token} if token else {}
|
||||
try:
|
||||
response = tls_opener(args).open(Request(base_url(args) + path, headers=headers), timeout=10)
|
||||
except HTTPError as error:
|
||||
response = error
|
||||
with response:
|
||||
payload = json.load(response)
|
||||
if response.status != 503 or not response.headers.get("X-Request-Id"):
|
||||
raise RuntimeError("Unexpected dependency failure response")
|
||||
shape(payload, "Error")
|
||||
if payload["error"]["request_id"] != response.headers["X-Request-Id"]:
|
||||
raise RuntimeError("LB error request ID mismatch")
|
||||
|
||||
|
||||
|
||||
def attachment_failover_check(args):
|
||||
import hashlib
|
||||
results = []
|
||||
raw = (ROOT / "tests/fixtures/sample.png").read_bytes()
|
||||
try:
|
||||
for service in ("api1", "api2"):
|
||||
mapping = wait_replicas(args)
|
||||
c = client(args)
|
||||
alice, bob, eve, chat = c.bootstrap()
|
||||
target = mapping[service]["instance_id"]
|
||||
for _ in range(8):
|
||||
uploaded = c.call(
|
||||
"POST", "/api/v1/chats/" + chat["id"] + "/attachments?filename=failover.png", 202,
|
||||
actor=alice, raw=raw, headers={"Content-Type": "image/png"}, schema="Attachment",
|
||||
)
|
||||
if uploaded["headers"]["X-Instance-Id"] == target:
|
||||
break
|
||||
else:
|
||||
raise RuntimeError("Selected upload replica was not observed")
|
||||
attachment = uploaded["json"]
|
||||
c.wait_ready(alice, attachment)
|
||||
linked = c.message(alice, chat, "", attachments=[attachment["id"]])["json"]
|
||||
hook = ROOT / "scripts" / ("stop-one.cmd" if os.name == "nt" else "stop-one.sh")
|
||||
previous = os.environ.get("TARGET_INSTANCE_ID")
|
||||
os.environ["TARGET_INSTANCE_ID"] = target
|
||||
started = time.monotonic()
|
||||
try:
|
||||
run(args, [str(hook)])
|
||||
finally:
|
||||
if previous is None:
|
||||
os.environ.pop("TARGET_INSTANCE_ID", None)
|
||||
else:
|
||||
os.environ["TARGET_INSTANCE_ID"] = previous
|
||||
from client import Client
|
||||
reads = Client(base_url(args), ca_file=environment(args)["CA_FILE"], timeout=2)
|
||||
errors = 0
|
||||
while True:
|
||||
try:
|
||||
downloaded = reads.call("GET", "/api/v1/attachments/" + attachment["id"] + "/content", actor=bob)
|
||||
history_response = reads.call(
|
||||
"GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=bob, schema="MessagePage",
|
||||
)
|
||||
break
|
||||
except (AssertionError, OSError) as error:
|
||||
if isinstance(error, AssertionError) and not any(
|
||||
text in str(error) for text in ("received 502", "received 503", "connection/TLS failure")
|
||||
):
|
||||
raise
|
||||
errors += 1
|
||||
if time.monotonic() - started >= 10:
|
||||
raise RuntimeError("File and history did not recover within 10 seconds") from None
|
||||
time.sleep(0.1)
|
||||
recovered = time.monotonic() - started
|
||||
if downloaded["bytes"] != raw or hashlib.sha256(raw).hexdigest() != attachment["sha256"]:
|
||||
raise RuntimeError("Original file changed after API failure")
|
||||
if downloaded["headers"]["X-Instance-Id"] == target or recovered > 10:
|
||||
raise RuntimeError("Upload replica was not replaced")
|
||||
history = history_response["json"]["items"]
|
||||
if history_response["headers"]["X-Instance-Id"] == target:
|
||||
raise RuntimeError("Stopped API returned history")
|
||||
if history != [linked]:
|
||||
raise RuntimeError("Attached message changed during failover")
|
||||
results.append({"stopped_service": service, "upload_instance": target,
|
||||
"download_instance": downloaded["headers"]["X-Instance-Id"],
|
||||
"recovery_seconds": round(recovered, 3), "transitional_errors": errors,
|
||||
"same_original": True, "message_preserved": True})
|
||||
restore(args)
|
||||
result = {"status": "PASS", "cases": results}
|
||||
evidence("attachment-failover.json", result)
|
||||
say("PASS: stopped each uploader; other API downloaded the same original")
|
||||
return result
|
||||
finally:
|
||||
restore(args)
|
||||
|
||||
|
||||
def queue_check(args):
|
||||
run(args, [interpreter(), '-X', 'utf8', 'scripts/pipeline_checks.py', 'queue'])
|
||||
return json.loads((ROOT / 'evidence/queue.json').read_text(encoding='utf-8'))
|
||||
|
||||
|
||||
def retry_check(args):
|
||||
run(args, [interpreter(), '-X', 'utf8', 'scripts/pipeline_checks.py', 'retry'])
|
||||
return json.loads((ROOT / 'evidence/retry.json').read_text(encoding='utf-8'))
|
||||
|
||||
|
||||
def jobs_failed(args):
|
||||
query = "SELECT a.id,a.error_code,j.attempt FROM attachments a JOIN attachment_jobs j ON a.id=j.attachment_id WHERE a.status='failed' ORDER BY a.updated_at DESC LIMIT 100"
|
||||
say(compose(args, 'exec', '-T', 'db', 'psql', '-U', 'messenger', '-d', 'messenger', '-c', query, quiet=True))
|
||||
|
||||
|
||||
def main():
|
||||
saved = settings()
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("action", choices=["setup", "build", "start", "test", "restart", "stop-one",
|
||||
"restart-check", "failover-check", "restore", "stop", "verify", "queue-check", "retry-check", "worker-stop", "worker-start", "jobs-failed", "telemetry-check", "incident-check", "telemetry-outage-check", "bao-check", "tls-check", "policy-check", "security-check", "bao-status", "bao-unseal", "pki-renew"])
|
||||
parser.add_argument("--project", default=os.environ.get("LAB7_PROJECT", saved.get("COMPOSE_PROJECT_NAME", "mtusi-lab7")))
|
||||
parser.add_argument("--port", type=int, default=int(os.environ.get("LAB7_PORT", saved.get("HTTP_PORT", "8443"))))
|
||||
parser.add_argument("--ttl", type=int, default=int(os.environ.get("LAB7_TTL", saved.get("SESSION_TTL_SECONDS", "3600"))))
|
||||
parser.add_argument("--grafana-port", type=int, default=int(os.environ["LAB7_GRAFANA_PORT"]) if "LAB7_GRAFANA_PORT" in os.environ else None)
|
||||
parser.add_argument("--test-port", type=int, default=18444)
|
||||
args = parser.parse_args()
|
||||
if not 1 <= args.port <= 65535 or not 1 <= args.test_port <= 65534 or not 1 <= args.ttl <= 86400:
|
||||
parser.error("Invalid port or session TTL")
|
||||
if args.action in ("setup", "build", "start", "test", "restart-check", "failover-check", "queue-check", "retry-check"):
|
||||
setup(args)
|
||||
actions = {"setup": lambda item: None, "build": build, "start": start,
|
||||
"test": lambda item: (contract_tests(item), api_tests(item)),
|
||||
"restart": restart, "restart-check": restart_check, "verify": verify,
|
||||
"queue-check": queue_check, "retry-check": retry_check, "jobs-failed": jobs_failed,
|
||||
"worker-stop": lambda item: compose(item, "stop", "--timeout", "3", "worker"),
|
||||
"worker-start": lambda item: compose(item, "start", "worker"),
|
||||
"stop-one": stop_one, "restore": restore, "failover-check": failover_check,
|
||||
|
||||
"stop": lambda item: compose(item, "stop", "--timeout", "10")}
|
||||
for action, mode in (("telemetry-check", "telemetry"), ("incident-check", "incidents"), ("telemetry-outage-check", "outage")):
|
||||
actions[action] = lambda item, mode=mode: observability_check(item, mode)
|
||||
for action in ('bao-status','bao-unseal'):
|
||||
actions[action] = lambda item, action=action: admin(item, action)
|
||||
for action in ('tls-check','policy-check','security-check','bao-check'):
|
||||
actions[action] = lambda item, action=action: run(item,[interpreter(),'-X','utf8','scripts/security_checks.py',action])
|
||||
actions['pki-renew'] = lambda item: (compose(item,'stop','--timeout','10'),admin(item,'pki-renew'),start(item))
|
||||
actions[args.action](args)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (RuntimeError, OSError, ValueError) as error:
|
||||
print("FAIL: " + str(error), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,322 @@
|
||||
import base64
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import time
|
||||
from types import SimpleNamespace
|
||||
from urllib.parse import urlencode
|
||||
from urllib.request import Request
|
||||
from uuid import uuid4
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from scripts import lab
|
||||
|
||||
|
||||
def arguments():
|
||||
saved = lab.settings()
|
||||
return SimpleNamespace(project=os.environ.get('LAB7_PROJECT', saved['COMPOSE_PROJECT_NAME']),
|
||||
port=int(os.environ.get('LAB7_PORT', saved['HTTP_PORT'])),
|
||||
ttl=int(os.environ.get('LAB7_TTL', saved['SESSION_TTL_SECONDS'])),
|
||||
test_port=18444, grafana_port=int(os.environ["LAB7_GRAFANA_PORT"]) if "LAB7_GRAFANA_PORT" in os.environ else None)
|
||||
|
||||
|
||||
def wait(predicate, seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
last = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
result = predicate()
|
||||
if result:
|
||||
return result
|
||||
except (RuntimeError, ValueError, OSError) as error:
|
||||
last = type(error).__name__
|
||||
time.sleep(1)
|
||||
raise RuntimeError('Telemetry condition timed out' + (': ' + last if last else ''))
|
||||
|
||||
|
||||
def probe(args, payload):
|
||||
import subprocess
|
||||
result=subprocess.run(['docker','compose','--project-name',args.project,'--env-file','.env','run','--rm','--no-deps','-T','probe','python','/app/probe.py'],
|
||||
cwd=lab.ROOT,env=lab.environment(args),input=json.dumps(payload),text=True,capture_output=True,encoding='utf-8')
|
||||
if result.returncode:
|
||||
raise RuntimeError('TLS probe failed: ' + result.stderr[-350:])
|
||||
return json.loads(result.stdout)
|
||||
|
||||
|
||||
def backend(args, url):
|
||||
return backend_many(args,[url])[0]
|
||||
|
||||
|
||||
def backend_many(args, urls):
|
||||
return probe(args, {'op':'fetch','urls':[url.replace('http://','https://') for url in urls]})
|
||||
|
||||
|
||||
def prom(args, query, at=None):
|
||||
params = {'query': query}
|
||||
if at:
|
||||
params['time'] = at
|
||||
result = backend(args, 'http://prometheus:9090/api/v1/query?' + urlencode(params))
|
||||
if result['status'] != 'success':
|
||||
raise RuntimeError('Prometheus query failed')
|
||||
return result['data']['result']
|
||||
|
||||
|
||||
def logs(args, query, start=None):
|
||||
params = {'query': query, 'limit': 2000, 'start': str(int((start or time.time() - 300) * 1e9)),
|
||||
'end': str(time.time_ns()), 'direction': 'backward'}
|
||||
result = backend(args, 'http://loki:3100/loki/api/v1/query_range?' + urlencode(params))
|
||||
entries = []
|
||||
for stream in result['data']['result']:
|
||||
for value in stream['values']:
|
||||
item = {**stream['stream'], 'timestamp_ns': value[0], 'body': value[1]}
|
||||
if len(value) > 2:
|
||||
item.update(value[2])
|
||||
entries.append(item)
|
||||
return entries
|
||||
|
||||
|
||||
def trace_data(args, trace_id):
|
||||
return backend(args, 'http://tempo:3200/api/traces/' + trace_id)
|
||||
|
||||
|
||||
def spans(data):
|
||||
found = []
|
||||
if isinstance(data, dict):
|
||||
if 'spanId' in data and 'name' in data:
|
||||
found.append(data)
|
||||
for value in data.values():
|
||||
found.extend(spans(value))
|
||||
elif isinstance(data, list):
|
||||
for value in data:
|
||||
found.extend(spans(value))
|
||||
return found
|
||||
|
||||
|
||||
def correlated(args, query, kind, start=None):
|
||||
entry = wait(lambda: next((item for item in logs(args, query, start) if item.get('trace_id')), None))
|
||||
data = wait(lambda: trace_data(args, entry['trace_id']))
|
||||
candidates = [span for span in spans(data) if span.get('kind') in (kind, 'SPAN_KIND_' + kind)]
|
||||
if not candidates or not any(int(span['endTimeUnixNano']) > int(span['startTimeUnixNano']) for span in candidates):
|
||||
raise RuntimeError('Real span with required kind/duration not found')
|
||||
matched = next((span for span in candidates if
|
||||
(span['spanId'] if len(span['spanId']) == 16 else base64.b64decode(span['spanId']).hex()) == entry['span_id']), None)
|
||||
if matched is None:
|
||||
raise RuntimeError('Log span ID does not match the trace')
|
||||
return {'trace_id': entry['trace_id'], 'span_id': entry['span_id'], 'event': entry['body'],
|
||||
'kind': kind, 'span_name': matched['name'], 'span_status': matched.get('status', {}),
|
||||
'span_duration_seconds': (int(matched['endTimeUnixNano']) - int(matched['startTimeUnixNano'])) / 1e9,
|
||||
'span_attributes': matched.get('attributes', []), 'log': entry}
|
||||
|
||||
|
||||
def sql(args, statement):
|
||||
return lab.compose(args, 'exec', '-T', 'db', 'psql', '-U', 'messenger', '-d', 'messenger',
|
||||
'-v', 'ON_ERROR_STOP=1', '-At', '-c', statement, quiet=True).strip()
|
||||
|
||||
|
||||
def job_id(args, attachment):
|
||||
return sql(args, "SELECT id FROM attachment_jobs WHERE attachment_id='" + attachment['id'] + "'")
|
||||
|
||||
|
||||
def grafana(args):
|
||||
port = int(lab.environment(args)['GRAFANA_PORT'])
|
||||
password = (lab.ROOT / 'runtime' / args.project / 'grafana/password').read_text().strip()
|
||||
authorization = 'Basic ' + base64.b64encode(('admin:' + password).encode()).decode()
|
||||
|
||||
def get(path):
|
||||
with lab.tls_opener(args).open(Request('https://127.0.0.1:' + str(port) + path,
|
||||
headers={'Authorization': authorization}), timeout=10) as response:
|
||||
return json.load(response)
|
||||
|
||||
sources = wait(lambda: get('/api/datasources'))
|
||||
if {source['uid'] for source in sources} != {'prometheus', 'loki', 'tempo'}:
|
||||
raise RuntimeError('Grafana data sources missing')
|
||||
dashboard = get('/api/dashboards/uid/messenger-lab6')['dashboard']
|
||||
queries = [target['expr'] for panel in dashboard['panels'] for target in panel.get('targets', [])
|
||||
if panel.get('datasource', {}).get('uid') == 'prometheus']
|
||||
for query in queries:
|
||||
prom(args, query.replace("$instance", ".*"))
|
||||
for source in sources:
|
||||
health = get('/api/datasources/uid/' + source['uid'] + '/health')
|
||||
if health['status'] != 'OK':
|
||||
raise RuntimeError('Grafana data source health failed')
|
||||
loki = next(source for source in sources if source['uid'] == 'loki')
|
||||
if loki['jsonData']['derivedFields'][0]['url'] != '${__value.raw}':
|
||||
raise RuntimeError('Loki trace link is not provisioned correctly')
|
||||
query_checks = []
|
||||
for uid, query in (('loki', {'expr': '{service_name="messenger-api"}', 'queryType': 'range', 'maxLines': 5}),
|
||||
('tempo', {'query': '{ resource.service.name = "messenger-api" }', 'queryType': 'traceql', 'limit': 5})):
|
||||
payload = json.dumps({'from': str(int((time.time() - 300) * 1000)), 'to': str(time.time_ns() // 1000000),
|
||||
'queries': [{'refId': 'A', 'datasource': {'type': uid, 'uid': uid}, **query}]}).encode()
|
||||
request = Request('https://127.0.0.1:' + str(port) + '/api/ds/query', data=payload,
|
||||
headers={'Authorization': authorization, 'Content-Type': 'application/json'})
|
||||
with lab.tls_opener(args).open(request, timeout=15) as response:
|
||||
result = json.load(response)['results']['A']
|
||||
if result.get('error') or result.get('status') != 200 or not result.get('frames'):
|
||||
raise RuntimeError('Grafana log/trace query failed')
|
||||
query_checks.append(uid)
|
||||
return {'log_trace_queries': query_checks, 'dashboard_uid': dashboard['uid'], 'data_sources': [s['uid'] for s in sources],
|
||||
'prometheus_queries_valid': len(queries), 'source_health': 'PASS'}
|
||||
|
||||
|
||||
def telemetry(args):
|
||||
c = lab.client(args)
|
||||
start = time.time()
|
||||
actor, bob, eve, chat = c.bootstrap()
|
||||
marker = 'private-content-' + uuid4().hex
|
||||
c.message(actor, chat, marker)
|
||||
response = c.call('GET', '/api/v1/users/me', actor=actor)
|
||||
request_id = response['headers']['X-Request-Id']
|
||||
api = correlated(args, '{service_name="messenger-api"} | request_id="' + request_id + '"', 'SERVER', start)
|
||||
filename = 'private-name-' + uuid4().hex + '.png'
|
||||
raw = (lab.ROOT / 'tests/fixtures/sample.png').read_bytes()
|
||||
attachment = c.call('POST', '/api/v1/chats/' + chat['id'] + '/attachments?filename=' + filename,
|
||||
202, actor=actor, raw=raw, headers={'Content-Type': 'image/png'}, schema='Attachment')['json']
|
||||
c.wait_ready(actor, attachment)
|
||||
job = job_id(args, attachment)
|
||||
worker = correlated(args, '{service_name="messenger-worker"} | job_id="' + job + '" | event="job.completed"', 'CONSUMER', start)
|
||||
try:
|
||||
lab.compose(args, 'stop', '--timeout', '10', 'worker')
|
||||
broken, _ = c.attachment(actor, chat)
|
||||
stage = sql(args, "SELECT staging_key FROM attachment_jobs WHERE attachment_id='" + broken['id'] + "'")
|
||||
code = ("from src.objects import Objects; from io import BytesIO; o=Objects(admin=True); "
|
||||
"o.put(" + repr(stage) + ",BytesIO(b'broken'),6,'image/png'); o.close()")
|
||||
lab.compose(args, 'run', '--rm', '--no-deps', '-T', 'bootstrap', 'python', '-c', code, quiet=True)
|
||||
finally:
|
||||
lab.compose(args, 'start', 'worker')
|
||||
wait(lambda: sql(args, "SELECT status FROM attachments WHERE id='" + broken['id'] + "'") == 'failed')
|
||||
failed_job = job_id(args, broken)
|
||||
failed = correlated(args, '{service_name="messenger-worker"} | job_id="' + failed_job + '" | event="job.completed"', 'CONSUMER', start)
|
||||
failed_counter = wait(lambda: prom(args, 'messenger_jobs_total{outcome="failed"}'))
|
||||
for _ in range(4):
|
||||
c.call('GET', '/api/v1/chats/' + str(uuid4()), 404, actor=actor)
|
||||
c.call('GET', '/not-a-route-' + uuid4().hex, 404)
|
||||
c.call('GET', '/api/v1/users/me', 401)
|
||||
http = wait(lambda: prom(args, 'messenger_http_requests_total{route="/api/v1/users/me"}'))
|
||||
jobs = wait(lambda: prom(args, 'messenger_jobs_total{outcome="success"}'))
|
||||
histograms = wait(lambda: prom(args, 'messenger_job_duration_seconds_bucket'))
|
||||
http_histograms = wait(lambda: prom(args, 'messenger_http_duration_seconds_bucket'))
|
||||
series = prom(args, 'messenger_http_requests_total')
|
||||
forbidden = {'request_id', 'user_id', 'chat_id', 'message_id', 'attachment_id', 'filename', 'url', 'url_full'}
|
||||
for sample in series:
|
||||
labels = sample['metric']
|
||||
if forbidden.intersection(labels) or any(value in labels.get('route', '') for value in (chat['id'], actor['id'])):
|
||||
raise RuntimeError('High cardinality metric attributes')
|
||||
current_instances = '|'.join(item['instance_id'] for item in lab.instance_map(args).values())
|
||||
if prom(args, '{__name__=~"http_server_request_duration.*",service_instance_id=~"' + current_instances + '"}'):
|
||||
raise RuntimeError('Duplicate native FastAPI metrics found')
|
||||
records = logs(args, '{service_name=~"messenger-api|messenger-worker"}', start)
|
||||
ids = sorted({item['trace_id'] for item in records if item.get('trace_id')})
|
||||
traces = wait(lambda: backend_many(args, ['http://tempo:3200/api/traces/' + value for value in ids]))
|
||||
exported = json.dumps(records, ensure_ascii=False) + json.dumps(traces, ensure_ascii=False)
|
||||
private = [marker, filename, actor['token'], actor['registration']['password'], actor['registration']['display_name']]
|
||||
if any(value in exported for value in private):
|
||||
raise RuntimeError('Private data exported')
|
||||
if not all(key in api['log'] for key in ('severity_text', 'service_name', 'event', 'trace_id', 'span_id')):
|
||||
raise RuntimeError('Required structured log fields missing')
|
||||
result = {'status': 'PASS', 'api': api, 'worker': worker, 'failed_worker': failed, 'failed_job_series': len(failed_counter), 'privacy': 'PASS',
|
||||
'route_cardinality': 'PASS', 'no_duplicate_instrumentation': True,
|
||||
'http_series': len(http), 'job_series': len(jobs),
|
||||
'http_histogram_buckets': len(http_histograms), 'job_histogram_buckets': len(histograms),
|
||||
'grafana': grafana(args), 'metric_time': time.time()}
|
||||
lab.evidence('telemetry.json', result)
|
||||
lab.say('PASS: real API/worker traces and related logs, metrics, privacy and Grafana provisioning')
|
||||
return result
|
||||
|
||||
|
||||
def incidents(args):
|
||||
c = lab.client(args)
|
||||
actor, bob, eve, chat = c.bootstrap()
|
||||
started = time.time()
|
||||
lab.run(args, [lab.interpreter(), '-X', 'utf8', 'tests/load.py', '--base-url', lab.base_url(args),
|
||||
'--duration', '30', '--concurrency', '4', '--output', 'evidence/load.json'])
|
||||
queue = []
|
||||
try:
|
||||
lab.compose(args, 'stop', '--timeout', '10', 'worker')
|
||||
stopped_at = time.time()
|
||||
for _ in range(3):
|
||||
item, _ = c.attachment(actor, chat)
|
||||
state = c.call('GET', '/api/v1/attachments/' + item['id'], actor=actor, schema='Attachment')['json']
|
||||
if state['status'] != 'queued':
|
||||
raise RuntimeError('Stopped worker processed a job')
|
||||
queue.append((item, job_id(args, item)))
|
||||
time.sleep(5)
|
||||
pending = logs(args, '{service_name="messenger-worker"} | event="job.started"', stopped_at)
|
||||
if any(record.get('job_id') in {job for _, job in queue} for record in pending):
|
||||
raise RuntimeError('Stopped worker emitted processing events')
|
||||
finally:
|
||||
lab.compose(args, 'start', 'worker')
|
||||
completed = []
|
||||
for item, job in queue:
|
||||
c.wait_ready(actor, item)
|
||||
completed.append(correlated(args, '{service_name="messenger-worker"} | job_id="' + job + '" | event="job.completed"', 'CONSUMER', stopped_at))
|
||||
worker_incident = {'started_at': stopped_at, 'queued_jobs': [job for _, job in queue],
|
||||
'accepted_logs': wait(lambda: logs(args, '{service_name="messenger-api"} | event="job.accepted"', stopped_at)),
|
||||
'recovered_jobs': completed, 'recovered_at': time.time()}
|
||||
try:
|
||||
lab.compose(args, 'stop', '--timeout', '10', 'db')
|
||||
db_at = time.time()
|
||||
response = c.call('GET', '/api/v1/users/me', 503, actor=actor)
|
||||
request_id = response['headers']['X-Request-Id']
|
||||
db_trace = correlated(args, '{service_name="messenger-api"} | request_id="' + request_id + '"', 'SERVER', db_at)
|
||||
db_logs = wait(lambda: logs(args, '{service_name="messenger-api"} | event="dependency.postgresql_unavailable"', db_at))
|
||||
errors = wait(lambda: prom(args, 'messenger_http_requests_total{status_class="5xx",route="/api/v1/users/me"}'))
|
||||
finally:
|
||||
lab.compose(args, 'start', 'db')
|
||||
lab.wait_ready(args)
|
||||
c.call('GET', '/api/v1/users/me', actor=actor)
|
||||
result = {'status': 'PASS', 'started_at': started, 'worker': worker_incident,
|
||||
'postgresql': {'started_at': db_at, 'request': db_trace, 'dependency_logs': db_logs[:4],
|
||||
'error_series': errors, 'recovered_at': time.time(), 'recovered_status': 200}}
|
||||
lab.evidence('incidents.json', result)
|
||||
lab.say('PASS: bounded worker and PostgreSQL incidents observed and recovered')
|
||||
return result
|
||||
|
||||
|
||||
def outage(args):
|
||||
c = lab.client(args)
|
||||
actor, bob, eve, chat = c.bootstrap()
|
||||
before = lab.states(args)
|
||||
cases = []
|
||||
for service in ('otel-collector', 'loki'):
|
||||
try:
|
||||
lab.compose(args, 'stop', '--timeout', '10', service+'-tls', service)
|
||||
start = time.monotonic()
|
||||
confirmations = []
|
||||
for index in range(6):
|
||||
confirmations.append(c.message(actor, chat, 'telemetry-outage-' + str(index))['json']['id'])
|
||||
item, _ = c.attachment(actor, chat)
|
||||
c.wait_ready(actor, item)
|
||||
time.sleep(5)
|
||||
c.call('GET', '/health/ready', schema='Health')
|
||||
elapsed = time.monotonic() - start
|
||||
finally:
|
||||
lab.compose(args, 'start', service)
|
||||
lab.compose(args, 'start', service+'-tls')
|
||||
response = c.call('GET', '/api/v1/users/me', actor=actor)
|
||||
observed = correlated(args, '{service_name="messenger-api"} | request_id="' + response['headers']['X-Request-Id'] + '"', 'SERVER')
|
||||
cases.append({'stopped': service, 'duration_seconds': round(elapsed, 2),
|
||||
'confirmed_messages': len(confirmations), 'ready_attachments': 6,
|
||||
'business_ready': 200, 'telemetry_recovered': observed})
|
||||
preserved = telemetry(args)
|
||||
lab.restart(args)
|
||||
lab.wait_ready(args)
|
||||
wait(lambda: trace_data(args, preserved['api']['trace_id']))
|
||||
wait(lambda: logs(args, '{service_name="messenger-api"} | trace_id="' + preserved['api']['trace_id'] + '"'))
|
||||
wait(lambda: prom(args, 'messenger_http_requests_total', preserved['metric_time']))
|
||||
after = lab.states(args)
|
||||
if any(after[name]['oom_killed'] for name in after):
|
||||
raise RuntimeError('Container OOM observed')
|
||||
result = {'status': 'PASS', 'cases': cases, 'history_after_restart': 'PASS', 'oom_killed': False,
|
||||
'preserved_trace_id': preserved['api']['trace_id'],
|
||||
'same_volumes': all(before[name]['volumes'] == after[name]['volumes'] for name in before),
|
||||
'loss_policy': 'Bounded in-memory SDK/Collector queues; telemetry during outage may be lost.'}
|
||||
lab.evidence('outage.json', result)
|
||||
lab.say('PASS: telemetry outages do not break messages/jobs; stored telemetry survives restart')
|
||||
return result
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
mode = sys.argv[1]
|
||||
{'telemetry': telemetry, 'incidents': incidents, 'outage': outage}[mode](arguments())
|
||||
@@ -0,0 +1,204 @@
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import time
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
from types import SimpleNamespace
|
||||
from uuid import uuid4
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
def check(args, lab, retry=False):
|
||||
c = lab.client(args)
|
||||
actor, bob, eve, chat = c.bootstrap()
|
||||
|
||||
def sql(statement):
|
||||
return lab.compose(args, 'exec', '-T', 'db', 'psql', '-U', 'messenger', '-d', 'messenger',
|
||||
'-v', 'ON_ERROR_STOP=1', '-At', '-c', statement, quiet=True).strip()
|
||||
|
||||
def wait(predicate, seconds=60):
|
||||
end = time.monotonic() + seconds
|
||||
while time.monotonic() < end:
|
||||
if predicate():
|
||||
return
|
||||
time.sleep(0.2)
|
||||
raise RuntimeError('Pipeline test condition timed out')
|
||||
|
||||
def ready(att):
|
||||
done = c.wait_ready(actor, att)
|
||||
path = '/api/v1/attachments/' + att['id'] + '/content'
|
||||
raw = c.call('GET', path, actor=bob)['bytes']
|
||||
if hashlib.sha256(raw).hexdigest() != att['sha256']:
|
||||
raise RuntimeError('Original checksum changed')
|
||||
thumb = c.call('GET', path + '?variant=thumbnail', actor=bob)['bytes']
|
||||
with Image.open(io.BytesIO(thumb)) as image:
|
||||
if image.format != 'JPEG' or image.size != (256, 160):
|
||||
raise RuntimeError('Thumbnail format or size mismatch')
|
||||
if hashlib.sha256(thumb).hexdigest() != done['variants'][0]['sha256']:
|
||||
raise RuntimeError('Thumbnail checksum mismatch')
|
||||
return done
|
||||
|
||||
def duplicate(att):
|
||||
code = ('from src.storage import PostgresStore; from src.broker import publish,envelope; '
|
||||
's=PostgresStore(); s.open()\n'
|
||||
'with s.connection() as c: j=c.execute("SELECT * FROM attachment_jobs WHERE attachment_id=%s",'
|
||||
'("' + att['id'] + '",)).fetchone()\n'
|
||||
'publish(envelope(j)); publish(envelope(j)); s.close()')
|
||||
lab.compose(args, 'exec', '-T', 'api1', 'python', '-c', code, quiet=True)
|
||||
def drained():
|
||||
lines = lab.compose(args, 'exec', '-T', 'broker', 'rabbitmqctl', '-q',
|
||||
'list_queues', '-p', 'messenger', 'name', 'messages', quiet=True)
|
||||
return any(line.split() == ['attachment.process.v1', '0'] for line in lines.splitlines())
|
||||
wait(drained, 30)
|
||||
now = c.call('GET', '/api/v1/attachments/' + att['id'], actor=actor, schema='Attachment')['json']
|
||||
if now != att:
|
||||
raise RuntimeError('Duplicate delivery changed ready metadata')
|
||||
|
||||
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
||||
try:
|
||||
attachment, original = c.attachment(actor, chat)
|
||||
path = '/api/v1/attachments/' + attachment['id']
|
||||
if not retry:
|
||||
from jsonschema import Draft202012Validator, FormatChecker
|
||||
job_row = json.loads(sql("SELECT row_to_json(j) FROM attachment_jobs j WHERE attachment_id='" + attachment['id'] + "'"))
|
||||
carrier = {'schema_version': 1, 'job_id': job_row['id'], 'attachment_id': attachment['id'],
|
||||
'type': 'attachment.process.v1', 'pipeline_version': 1, 'attempt': 1,
|
||||
'created_at': job_row['created_at']}
|
||||
schema = json.loads((lab.ROOT / 'contracts/jobs.schema.json').read_text())
|
||||
Draft202012Validator(schema, format_checker=FormatChecker()).validate(carrier)
|
||||
anonymous = (
|
||||
"import os,boto3; from botocore import UNSIGNED; from botocore.config import Config; "
|
||||
"from botocore.exceptions import ClientError\n"
|
||||
"c=boto3.client('s3',endpoint_url=os.environ['S3_ENDPOINT'],verify=os.environ['TLS_CA_FILE'],config=Config(signature_version=UNSIGNED,proxies={}))\n"
|
||||
"try:\n r=c.get_object(Bucket=os.environ['S3_BUCKET'],Key='system/readiness'); r['Body'].close(); status=200\n"
|
||||
"except ClientError as e:\n status=e.response['ResponseMetadata']['HTTPStatusCode']\n"
|
||||
"assert status==403; print(status)"
|
||||
)
|
||||
if lab.compose(args, 'exec', '-T', 'api1', 'python', '-c', anonymous, quiet=True).strip() != '403':
|
||||
raise RuntimeError('Anonymous S3 access allowed')
|
||||
linked = c.message(actor, chat, '', attachments=[attachment['id']])['json']
|
||||
for variant in ('original', 'thumbnail'):
|
||||
c.call('GET', path + '/content?variant=' + variant, 409, actor=bob)
|
||||
c.call('GET', path, 404, actor=eve)
|
||||
c.message(bob, chat, 'worker is stopped')
|
||||
before = lab.states(args)
|
||||
lab.compose(args, 'stop', '--timeout', '3', 'api1-tls', 'api2-tls')
|
||||
lab.compose(args, 'restart', '--timeout', '10', 'api1', 'api2', 'broker')
|
||||
lab.compose(args, 'start', 'api1-tls', 'api2-tls')
|
||||
lab.wait_ready(args)
|
||||
after = lab.states(args)
|
||||
for name in ('api1', 'api2', 'broker'):
|
||||
if before[name]['started_at'] == after[name]['started_at'] or before[name]['volumes'] != after[name]['volumes']:
|
||||
raise RuntimeError('Queue restart evidence mismatch')
|
||||
queued = c.call('GET', path, actor=actor, schema='Attachment')['json']
|
||||
if queued['status'] != 'queued':
|
||||
raise RuntimeError('Stopped worker unexpectedly processed the upload')
|
||||
lab.compose(args, 'start', 'worker')
|
||||
done = ready(attachment)
|
||||
duplicate(done)
|
||||
c.call('GET', path + '/content?variant=crop', 404, actor=bob)
|
||||
history = c.call('GET', '/api/v1/chats/' + chat['id'] + '/messages', actor=bob, schema='MessagePage')['json']['items']
|
||||
if linked not in history:
|
||||
raise RuntimeError('Queued attachment message was lost')
|
||||
result = {'status': 'PASS', 'upload_with_stopped_worker': 202, 'pending_content': 409,
|
||||
'same_attachment_after_api_broker_restart': True, 'original_and_thumbnail': 'PASS',
|
||||
'duplicate_noop': 'PASS', 'job_schema': 'PASS', 'anonymous_s3': 403, 'before': before, 'after': after}
|
||||
lab.evidence('queue.json', result)
|
||||
lab.say('PASS: accepted upload survived API/broker restart; thumbnail and duplicate delivery checked')
|
||||
return result
|
||||
|
||||
job = json.loads(sql("SELECT row_to_json(j) FROM attachment_jobs j WHERE attachment_id='" + attachment['id'] + "'"))
|
||||
sql("UPDATE attachment_jobs SET staging_key='missing-test/" + attachment['id'] + "' WHERE id='" + job['id'] + "'")
|
||||
lab.compose(args, 'start', 'worker')
|
||||
wait(lambda: int(sql("SELECT attempt FROM attachment_jobs WHERE id='" + job['id'] + "'")) >= 1)
|
||||
sql("UPDATE attachment_jobs SET staging_key='" + job['staging_key'] + "' WHERE id='" + job['id'] + "'")
|
||||
ready(attachment)
|
||||
attempts = int(sql("SELECT attempt FROM attachment_jobs WHERE id='" + job['id'] + "'"))
|
||||
if attempts < 2:
|
||||
raise RuntimeError('Transient error did not cause a retry')
|
||||
|
||||
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
||||
failed, _ = c.attachment(actor, chat)
|
||||
failed_job = json.loads(sql("SELECT row_to_json(j) FROM attachment_jobs j WHERE attachment_id='" + failed['id'] + "'"))
|
||||
sql("UPDATE attachment_jobs SET staging_key='missing-test/" + failed['id'] + "' WHERE id='" + failed_job['id'] + "'")
|
||||
lab.compose(args, 'start', 'worker')
|
||||
wait(lambda: sql("SELECT status FROM attachments WHERE id='" + failed['id'] + "'") == 'failed', 75)
|
||||
state = c.call('GET', '/api/v1/attachments/' + failed['id'], actor=actor, schema='Attachment')['json']
|
||||
count = int(sql("SELECT attempt FROM attachment_jobs WHERE id='" + failed_job['id'] + "'"))
|
||||
if count != 5 or state['error_code'] != 'retry_exhausted':
|
||||
raise RuntimeError('Retry budget was not enforced')
|
||||
c.call('GET', '/api/v1/attachments/' + failed['id'] + '/content', 409, actor=actor)
|
||||
c.call('POST', '/api/v1/chats/' + chat['id'] + '/messages', 409, actor=actor,
|
||||
body={'text': '', 'attachment_ids': [failed['id']]}, headers={'Idempotency-Key': uuid4().hex})
|
||||
sql("UPDATE attachment_jobs SET staging_key='" + failed_job['staging_key'] + "' WHERE id='" + failed_job['id'] + "'")
|
||||
|
||||
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
||||
corrupt, _ = c.attachment(actor, chat)
|
||||
stage = sql("SELECT staging_key FROM attachment_jobs WHERE attachment_id='" + corrupt['id'] + "'")
|
||||
code = ("from src.objects import Objects; from io import BytesIO; o=Objects(admin=True); "
|
||||
"o.put(" + repr(stage) + ",BytesIO(b'broken'),6,'image/png'); o.close()")
|
||||
lab.compose(args, 'run', '--rm', '--no-deps', '-T', 'bootstrap', 'python', '-c', code, quiet=True)
|
||||
lab.compose(args, 'start', 'worker')
|
||||
wait(lambda: sql("SELECT status FROM attachments WHERE id='" + corrupt['id'] + "'") == 'failed')
|
||||
if sql("SELECT error_code FROM attachments WHERE id='" + corrupt['id'] + "'") != 'invalid_image':
|
||||
raise RuntimeError('Permanent image error was not classified')
|
||||
if sql("SELECT attempt FROM attachment_jobs WHERE attachment_id='" + corrupt['id'] + "'") != '1':
|
||||
raise RuntimeError('Permanent error retried')
|
||||
|
||||
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
||||
crash, _ = c.attachment(actor, chat)
|
||||
function = 'test_pause_' + uuid4().hex
|
||||
sql("CREATE FUNCTION " + function + "() RETURNS trigger LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_sleep(30); RETURN NEW; END $$; "
|
||||
"CREATE TRIGGER " + function + " BEFORE INSERT ON attachment_variants FOR EACH ROW "
|
||||
"WHEN (NEW.attachment_id='" + crash['id'] + "'::uuid) EXECUTE FUNCTION " + function + "()")
|
||||
try:
|
||||
lab.compose(args, 'start', 'worker')
|
||||
wait(lambda: sql("SELECT count(*) FROM pg_stat_activity WHERE wait_event='PgSleep'") != '0')
|
||||
if sql("SELECT status FROM attachments WHERE id='" + crash['id'] + "'") != 'processing':
|
||||
raise RuntimeError('Processing state not observed')
|
||||
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
||||
finally:
|
||||
sql('DROP TRIGGER IF EXISTS ' + function + ' ON attachment_variants; DROP FUNCTION IF EXISTS ' + function + '()')
|
||||
lab.compose(args, 'start', 'worker')
|
||||
ready(crash)
|
||||
if sql("SELECT count(*) FROM attachment_variants WHERE attachment_id='" + crash['id'] + "'") != '1':
|
||||
raise RuntimeError('Worker restart duplicated variants')
|
||||
lab.compose(args, 'stop', '--timeout', '3', 'worker')
|
||||
pending, _ = c.attachment(actor, chat)
|
||||
sql("UPDATE attachment_jobs SET created_at=clock_timestamp()-INTERVAL '25 hours' "
|
||||
"WHERE attachment_id='" + pending['id'] + "'; UPDATE attachments SET "
|
||||
"updated_at=clock_timestamp()-INTERVAL '25 hours' WHERE id='" + failed['id'] + "'")
|
||||
cleanup = ('from src.storage import PostgresStore; from src.objects import Objects; '
|
||||
'from src.cleanup import clean_once; s=PostgresStore(); s.open(); o=Objects(); '
|
||||
'clean_once(s,o); o.close(); s.close()')
|
||||
lab.compose(args, 'exec', '-T', 'cleanup', 'python', '-c', cleanup, quiet=True)
|
||||
if sql("SELECT status || ':' || staging_deleted FROM attachments WHERE id='" + pending['id'] + "'") != 'queued:false':
|
||||
raise RuntimeError('Cleanup removed accepted waiting work')
|
||||
if sql("SELECT staging_deleted FROM attachments WHERE id='" + failed['id'] + "'") != 't':
|
||||
raise RuntimeError('Expired failed staging was not cleaned')
|
||||
if sql("SELECT staging_deleted FROM attachments WHERE id='" + corrupt['id'] + "'") != 'f':
|
||||
raise RuntimeError('Fresh failed staging was removed early')
|
||||
ready(attachment)
|
||||
lab.compose(args, 'start', 'worker')
|
||||
ready(pending)
|
||||
result = {'status': 'PASS', 'transient_attempts': attempts, 'max_attempts': count,
|
||||
'failed_content': 409, 'failed_link': 409, 'processing_observed': True,
|
||||
'permanent_error_attempts': 1, 'worker_stopped_before_result_commit': True,
|
||||
'staging_retention_and_pending_protection': True, 'redelivery_same_result': True}
|
||||
lab.evidence('retry.json', result)
|
||||
lab.say('PASS: retry recovery, final failed and real worker interruption')
|
||||
return result
|
||||
finally:
|
||||
lab.compose(args, 'start', 'worker')
|
||||
lab.wait_ready(args)
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1]))
|
||||
from scripts import lab
|
||||
args = SimpleNamespace(project=os.environ['LAB7_PROJECT'], port=int(os.environ['LAB7_PORT']),
|
||||
ttl=int(os.environ['LAB7_TTL']), test_port=18444)
|
||||
check(args, lab, retry=sys.argv[1] == 'retry')
|
||||
@@ -0,0 +1,379 @@
|
||||
import base64
|
||||
import ctypes
|
||||
from datetime import datetime, timedelta, timezone
|
||||
import hashlib
|
||||
import ipaddress
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import secrets
|
||||
import ssl
|
||||
import subprocess
|
||||
import time
|
||||
from urllib.request import build_opener, HTTPSHandler, ProxyHandler, Request
|
||||
|
||||
from cryptography import x509
|
||||
from cryptography.hazmat.primitives import hashes, serialization
|
||||
from cryptography.hazmat.primitives.asymmetric import ec
|
||||
from cryptography.x509.oid import NameOID, ExtendedKeyUsageOID
|
||||
import yaml
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PROJECT = os.environ.get('LAB7_PROJECT', 'mtusi-lab7')
|
||||
if not __import__('re').fullmatch(r'mtusi-lab7(?:-[a-z0-9]+)*', PROJECT):
|
||||
raise RuntimeError('Invalid lab7 project name')
|
||||
RUNTIME = ROOT / 'runtime' / PROJECT
|
||||
CA = RUNTIME / 'pki/ca.crt'
|
||||
|
||||
|
||||
def write(path, value):
|
||||
path = RUNTIME / path
|
||||
path.parent.mkdir(parents=True, exist_ok=True)
|
||||
value = yaml.safe_dump(value, sort_keys=False) if isinstance(value, dict) else value
|
||||
path.write_text(value, encoding='utf-8', newline='\n')
|
||||
path.chmod(0o644)
|
||||
|
||||
|
||||
def operator_path():
|
||||
folder = Path(os.environ.get('LOCALAPPDATA', str(Path.home() / '.local/share'))) / 'Codex/Lab7'
|
||||
folder.mkdir(parents=True, exist_ok=True)
|
||||
return folder / (PROJECT + ('.dpapi' if os.name=='nt' else '.enc'))
|
||||
|
||||
|
||||
def dpapi(data, decrypt=False):
|
||||
if os.name != 'nt':
|
||||
import getpass
|
||||
from cryptography.hazmat.primitives.kdf.scrypt import Scrypt
|
||||
from cryptography.hazmat.primitives.ciphers.aead import AESGCM
|
||||
global _operator_passphrase
|
||||
if '_operator_passphrase' not in globals():
|
||||
_operator_passphrase=getpass.getpass('Operator profile passphrase: ')
|
||||
if not decrypt and _operator_passphrase!=getpass.getpass('Repeat passphrase: '):
|
||||
raise RuntimeError('Passphrase mismatch')
|
||||
if not _operator_passphrase:raise RuntimeError('Empty operator passphrase')
|
||||
salt=data[:16] if decrypt else secrets.token_bytes(16)
|
||||
key=Scrypt(salt=salt,length=32,n=32768,r=8,p=1).derive(_operator_passphrase.encode())
|
||||
if decrypt:return AESGCM(key).decrypt(data[16:28],data[28:],b'lab7-operator')
|
||||
nonce=secrets.token_bytes(12)
|
||||
return salt+nonce+AESGCM(key).encrypt(nonce,data,b'lab7-operator')
|
||||
class Blob(ctypes.Structure):
|
||||
_fields_ = [('size', ctypes.c_ulong), ('data', ctypes.POINTER(ctypes.c_ubyte))]
|
||||
buffer = ctypes.create_string_buffer(data)
|
||||
source = Blob(len(data), ctypes.cast(buffer, ctypes.POINTER(ctypes.c_ubyte)))
|
||||
output = Blob()
|
||||
function = ctypes.windll.crypt32.CryptUnprotectData if decrypt else ctypes.windll.crypt32.CryptProtectData
|
||||
if not function(ctypes.byref(source), None, None, None, None, 1, ctypes.byref(output)):
|
||||
raise RuntimeError('DPAPI operation failed')
|
||||
try:
|
||||
return ctypes.string_at(output.data, output.size)
|
||||
finally:
|
||||
ctypes.windll.kernel32.LocalFree(output.data)
|
||||
|
||||
|
||||
def operator_load():
|
||||
return json.loads(dpapi(operator_path().read_bytes(), True)) if operator_path().exists() else {}
|
||||
|
||||
|
||||
def operator_save(data):
|
||||
operator_path().write_bytes(dpapi(json.dumps(data).encode()))
|
||||
|
||||
|
||||
def new_key():
|
||||
return ec.generate_private_key(ec.SECP256R1())
|
||||
|
||||
|
||||
def private(key):
|
||||
return key.private_bytes(serialization.Encoding.PEM, serialization.PrivateFormat.PKCS8,
|
||||
serialization.NoEncryption()).decode()
|
||||
|
||||
|
||||
def pki(renew=False):
|
||||
RUNTIME.parent.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||
RUNTIME.mkdir(mode=0o700,parents=True,exist_ok=True)
|
||||
if os.name!='nt':
|
||||
RUNTIME.parent.chmod(0o700)
|
||||
RUNTIME.chmod(0o700)
|
||||
state = operator_load()
|
||||
if not CA.exists():
|
||||
key = new_key()
|
||||
name = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, 'MTUSI Lab7 ' + PROJECT)])
|
||||
now = datetime.now(timezone.utc)
|
||||
cert = (x509.CertificateBuilder().subject_name(name).issuer_name(name).public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number()).not_valid_before(now - timedelta(minutes=5))
|
||||
.not_valid_after(now + timedelta(days=365)).add_extension(x509.BasicConstraints(ca=True, path_length=0), True)
|
||||
.add_extension(x509.KeyUsage(False, False, False, False, False, True, True, False, False), True)
|
||||
.sign(key, hashes.SHA256()))
|
||||
write('pki/ca.crt', cert.public_bytes(serialization.Encoding.PEM).decode())
|
||||
state['ca_key'] = private(key)
|
||||
operator_save(state)
|
||||
cert = x509.load_pem_x509_certificate(CA.read_bytes())
|
||||
try:
|
||||
cert.extensions.get_extension_for_class(x509.SubjectKeyIdentifier)
|
||||
except x509.ExtensionNotFound:
|
||||
key = serialization.load_pem_private_key(state['ca_key'].encode(), None)
|
||||
now = datetime.now(timezone.utc)
|
||||
cert = (x509.CertificateBuilder().subject_name(cert.subject).issuer_name(cert.subject).public_key(key.public_key())
|
||||
.serial_number(x509.random_serial_number()).not_valid_before(now-timedelta(minutes=5)).not_valid_after(now+timedelta(days=365))
|
||||
.add_extension(x509.BasicConstraints(ca=True,path_length=0),True)
|
||||
.add_extension(x509.KeyUsage(False,False,False,False,False,True,True,False,False),True)
|
||||
.add_extension(x509.SubjectKeyIdentifier.from_public_key(key.public_key()),False)
|
||||
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False).sign(key,hashes.SHA256()))
|
||||
write('pki/ca.crt',cert.public_bytes(serialization.Encoding.PEM).decode())
|
||||
key = serialization.load_pem_private_key(state['ca_key'].encode(), None)
|
||||
now = datetime.now(timezone.utc)
|
||||
for kind, identities in [('server', ['lb','api1','api2','db','s3','broker','otel-collector','prometheus','loki','tempo','grafana','openbao']),
|
||||
('client', ['lb','api1','api2','worker','cleanup','collector','grafana','scraper','operator','wrong-role'])]:
|
||||
for identity in identities:
|
||||
path = RUNTIME / f'pki/{kind}/{identity}'
|
||||
if (path / 'client.crt').exists() and not renew:
|
||||
leaf = x509.load_pem_x509_certificate((path / 'client.crt').read_bytes())
|
||||
if leaf.not_valid_after_utc <= now:
|
||||
raise RuntimeError('Expired certificate: ' + identity)
|
||||
try:
|
||||
leaf.extensions.get_extension_for_class(x509.AuthorityKeyIdentifier)
|
||||
continue
|
||||
except x509.ExtensionNotFound:
|
||||
pass
|
||||
leaf_key = new_key()
|
||||
sans = [x509.DNSName(identity)]
|
||||
if kind == 'server' and identity in ('lb','grafana','openbao'):
|
||||
sans += [x509.DNSName('localhost'), x509.IPAddress(ipaddress.ip_address('127.0.0.1'))]
|
||||
eku = ExtendedKeyUsageOID.SERVER_AUTH if kind == 'server' else ExtendedKeyUsageOID.CLIENT_AUTH
|
||||
leaf = (x509.CertificateBuilder().subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, identity)]))
|
||||
.issuer_name(cert.subject).public_key(leaf_key.public_key()).serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now - timedelta(minutes=5)).not_valid_after(now + timedelta(days=30))
|
||||
.add_extension(x509.BasicConstraints(ca=False, path_length=None), True)
|
||||
.add_extension(x509.SubjectAlternativeName(sans), False)
|
||||
.add_extension(x509.ExtendedKeyUsage([eku]), False)
|
||||
.add_extension(x509.SubjectKeyIdentifier.from_public_key(leaf_key.public_key()),False)
|
||||
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(key.public_key()),False)
|
||||
.add_extension(x509.KeyUsage(True,False,False,False,False,False,False,False,False),True)
|
||||
.sign(key, hashes.SHA256()))
|
||||
write(f'pki/{kind}/{identity}/client.crt', leaf.public_bytes(serialization.Encoding.PEM).decode())
|
||||
write(f'pki/{kind}/{identity}/client.key', private(leaf_key))
|
||||
write(f'pki/{kind}/{identity}/bundle.pem', private(leaf_key) + leaf.public_bytes(serialization.Encoding.PEM).decode())
|
||||
|
||||
|
||||
def values():
|
||||
state = operator_load()
|
||||
if 'credentials' not in state:
|
||||
state['credentials'] = {name: secrets.token_hex(24) for name in
|
||||
['dbadmin','api_db','worker_db','cleanup_db','api_s3_id','api_s3_key','worker_s3_id','worker_s3_key',
|
||||
'cleanup_s3_id','cleanup_s3_key','admin_s3_id','admin_s3_key','api_mq','worker_mq','mqadmin',
|
||||
'api_otel','worker_otel','grafana','cursor']}
|
||||
operator_save(state)
|
||||
return state['credentials']
|
||||
|
||||
|
||||
def bundle(role):
|
||||
v = values()
|
||||
data = {'database_url': f"postgresql://{role}:{v[role+'_db']}@db:5432/messenger?sslmode=verify-full&sslrootcert=/run/pki/ca.crt",
|
||||
's3_access_key_id': v[role+'_s3_id'], 's3_secret_access_key': v[role+'_s3_key']}
|
||||
if role in ('api','worker'):
|
||||
data['broker_url'] = f"amqps://{role}:{v[role+'_mq']}@broker:5671/messenger"
|
||||
data['otel_authorization'] = 'Basic ' + base64.b64encode((role + ':' + v[role+'_otel']).encode()).decode()
|
||||
if role == 'api':
|
||||
data['cursor_key'] = v['cursor']
|
||||
return data
|
||||
|
||||
|
||||
def tls_context(server, clients=None):
|
||||
common = {'tls_certificates': [{'certificate_chain': {'filename': '/run/server/client.crt'},
|
||||
'private_key': {'filename': '/run/server/client.key'}}],
|
||||
'tls_params': {'tls_minimum_protocol_version': 'TLSv1_2'}}
|
||||
if clients:
|
||||
common['validation_context'] = {'trusted_ca': {'filename': '/run/pki/ca.crt'},
|
||||
'match_typed_subject_alt_names': [{'san_type': 'DNS','matcher': {'exact': name}} for name in clients]}
|
||||
return {'name': 'envoy.transport_sockets.tls', 'typed_config': {
|
||||
'@type': 'type.googleapis.com/envoy.extensions.transport_sockets.tls.v3.DownstreamTlsContext',
|
||||
'require_client_certificate': bool(clients), 'common_tls_context': common}}
|
||||
|
||||
|
||||
def gateway(name, listeners):
|
||||
chains, clusters = [], []
|
||||
for external, internal, clients, access in listeners:
|
||||
cluster = 'local_' + str(internal)
|
||||
clusters.append({'name': cluster, 'type': 'STATIC', 'connect_timeout': '2s', 'load_assignment': {
|
||||
'cluster_name': cluster, 'endpoints': [{'lb_endpoints': [{'endpoint': {'address': {'socket_address': {
|
||||
'address': '127.0.0.1', 'port_value': internal}}}}]}]}})
|
||||
filters = [{'name':'envoy.filters.network.tcp_proxy','typed_config': {
|
||||
'@type':'type.googleapis.com/envoy.extensions.filters.network.tcp_proxy.v3.TcpProxy',
|
||||
'stat_prefix':cluster,'cluster':cluster,'idle_timeout':'65s'}}]
|
||||
if access:
|
||||
policies = {}
|
||||
for identity, pattern in access.items():
|
||||
policies[identity] = {'permissions':[{'and_rules':{'rules':[
|
||||
{'header':{'name':':path','string_match':{'safe_regex':{'regex':pattern}}}},
|
||||
{'header':{'name':':method','string_match':{'safe_regex':{'regex': '.*' if identity=='operator' else ('POST' if identity=='collector' else ('GET|POST' if name=='prometheus' else 'GET'))}}}}]}}],
|
||||
'principals':[{'authenticated':{'principal_name':{'exact':identity}}}]}
|
||||
filters = [{'name':'envoy.filters.network.http_connection_manager','typed_config': {
|
||||
'@type':'type.googleapis.com/envoy.extensions.filters.network.http_connection_manager.v3.HttpConnectionManager',
|
||||
'stat_prefix':cluster,'codec_type':'AUTO','stream_idle_timeout':'65s',
|
||||
'route_config':{'name':'routes','virtual_hosts':[{'name':'local','domains':['*'],
|
||||
'routes':[{'match':{'prefix':'/'},'route':{'cluster':cluster,'timeout':'60s'}}]}]},
|
||||
'http_filters':[{'name':'envoy.filters.http.rbac','typed_config': {
|
||||
'@type':'type.googleapis.com/envoy.extensions.filters.http.rbac.v3.RBAC',
|
||||
'rules':{'action':'ALLOW','policies':policies}}},
|
||||
{'name':'envoy.filters.http.router','typed_config':{
|
||||
'@type':'type.googleapis.com/envoy.extensions.filters.http.router.v3.Router'}}]}}]
|
||||
chains.append({'name':name+str(external),'address':{'socket_address':{'address':'0.0.0.0','port_value':external}},
|
||||
'filter_chains':[{'transport_socket':tls_context(name, clients),'filters':filters}]})
|
||||
write('envoy/'+name+'.yaml', {'static_resources':{'listeners':chains,'clusters':clusters}})
|
||||
|
||||
|
||||
def configuration():
|
||||
v = values()
|
||||
write('db/password', v['dbadmin'])
|
||||
write('operator/database_url', f"postgresql://messenger:{v['dbadmin']}@db:5432/messenger?sslmode=verify-full&sslrootcert=/run/pki/ca.crt")
|
||||
write('operator/s3_admin_access_key_id', v['admin_s3_id'])
|
||||
write('operator/s3_admin_secret_access_key', v['admin_s3_key'])
|
||||
write('operator/s3_access_key_id', v['api_s3_id'])
|
||||
write('operator/s3_secret_access_key', v['api_s3_key'])
|
||||
write('grafana/password', v['grafana'])
|
||||
write('db/pg_hba.conf', 'local all all trust\nhostnossl all all all reject\nhostssl messenger all all scram-sha-256\n')
|
||||
accounts = []
|
||||
rules = {'api':['Read:messenger-attachments/originals/*','Read:messenger-attachments/variants/*',
|
||||
'Read:messenger-attachments/system/*','Write:messenger-attachments/staging/*','List:messenger-attachments'],
|
||||
'worker':['Read:messenger-attachments/staging/*','Write:messenger-attachments/originals/*',
|
||||
'Write:messenger-attachments/variants/*'],
|
||||
'cleanup':['Write:messenger-attachments/staging/*','Write:messenger-attachments/originals/*',
|
||||
'Write:messenger-attachments/variants/*']}
|
||||
for role, actions in rules.items():
|
||||
accounts.append({'name':role,'credentials':[{'accessKey':v[role+'_s3_id'],'secretKey':v[role+'_s3_key']}], 'actions':actions})
|
||||
accounts.append({'name':'operator','credentials':[{'accessKey':v['admin_s3_id'],'secretKey':v['admin_s3_key']}],
|
||||
'actions':['Admin','Read','Write','List']})
|
||||
write('s3/config.json', json.dumps({'identities':accounts}))
|
||||
write('broker/rabbitmq.conf', 'listeners.tcp = none\nlisteners.ssl.default = 5671\nssl_options.cacertfile = /run/pki/ca.crt\nssl_options.certfile = /run/server/client.crt\nssl_options.keyfile = /run/server/client.key\nssl_options.verify = verify_none\nprometheus.tcp.ip = 127.0.0.1\nmanagement.tcp.ip = 127.0.0.1\nmanagement.tcp.port = 15672\ndefinitions.import_backend = local_filesystem\ndefinitions.local.path = /run/config/definitions.json\n')
|
||||
users = [{'name':role,'password_hash':base64.b64encode((salt:=secrets.token_bytes(4))+hashlib.sha256(salt+v[key].encode()).digest()).decode(),
|
||||
'hashing_algorithm':'rabbit_password_hashing_sha256','tags': 'administrator' if role=='operator' else ''}
|
||||
for role,key in [('operator','mqadmin'),('api','api_mq'),('worker','worker_mq')]]
|
||||
permissions=[{'user':'operator','vhost':'messenger','configure':'.*','write':'.*','read':'.*'},
|
||||
{'user':'api','vhost':'messenger','configure':'^$','write':'^(attachment.jobs|attachment.process.v1)$','read':'^$'},
|
||||
{'user':'worker','vhost':'messenger','configure':'^$','write':'^(attachment.jobs|attachment.process.v1)$','read':'^attachment.process.v1$'}]
|
||||
write('broker/definitions.json',json.dumps({'users':users,'vhosts':[{'name':'messenger'}],'permissions':permissions,
|
||||
'queues':[{'name':'attachment.process.v1','vhost':'messenger','durable':True,'auto_delete':False,'arguments':{}}],
|
||||
'exchanges':[{'name':'attachment.jobs','vhost':'messenger','type':'direct','durable':True,'auto_delete':False,'internal':False,'arguments':{}}],
|
||||
'bindings':[{'source':'attachment.jobs','vhost':'messenger','destination':'attachment.process.v1','destination_type':'queue','routing_key':'attachment.process.v1','arguments':{}}]}))
|
||||
gateway('api1',[(8443,8080,['lb'],None)])
|
||||
gateway('api2',[(8443,8080,['lb'],None)])
|
||||
gateway('s3',[(9000,9001,None,None)])
|
||||
gateway('otel-collector',[(4318,4319,None,None),(8889,8890,['scraper','operator'],None)])
|
||||
gateway('loki',[(3100,3101,['collector','grafana','operator'],{
|
||||
'collector':r'/otlp/v1/logs','grafana':r'/(loki/api/.*|ready)','operator':r'/.*'})])
|
||||
gateway('tempo',[(4318,4319,['collector','operator'],None),(3200,3201,['grafana','operator'],{
|
||||
'grafana':r'/api/.*','operator':r'/.*'})])
|
||||
gateway('prometheus',[(9090,9091,['grafana','operator'],{'grafana':r'/api/v1/(query.*|labels.*|label/.*|series.*|status/.*|metadata.*|exemplars.*)', 'operator':r'/.*'})])
|
||||
write('bao/config.json', json.dumps({'ui':False,'api_addr':'https://openbao:8200',
|
||||
'cluster_addr':'https://127.0.0.1:8201','storage':{'raft':{'path':'/bao/data','node_id':'lab7'}},
|
||||
'listener':{'tcp':{'address':'0.0.0.0:8200','cluster_address':'127.0.0.1:8201',
|
||||
'tls_cert_file':'/run/server/client.crt','tls_key_file':'/run/server/client.key',
|
||||
'tls_client_ca_file':'/run/pki/ca.crt','tls_min_version':'tls12'}}}))
|
||||
collector = yaml.safe_load((ROOT/'infra/otel/collector.yaml').read_text())
|
||||
collector['receivers']['otlp']['protocols']['http']={'endpoint':'127.0.0.1:4319','auth':{'authenticator':'basicauth/server'}}
|
||||
collector['exporters']['prometheus']['endpoint']='127.0.0.1:8890'
|
||||
collector['exporters'].pop('otlp_grpc/tempo',None)
|
||||
collector['exporters']['otlphttp/tempo']={'endpoint':'https://tempo:4318','tls':{'ca_file':'/run/pki/ca.crt','cert_file':'/run/identity/client.crt','key_file':'/run/identity/client.key'},'sending_queue':{'queue_size':128},'timeout':'2s'}
|
||||
collector['exporters']['otlphttp/loki']['endpoint']='https://loki:3100/otlp'
|
||||
collector['exporters']['otlphttp/loki']['tls']={'ca_file':'/run/pki/ca.crt','cert_file':'/run/identity/client.crt','key_file':'/run/identity/client.key'}
|
||||
collector['service']['pipelines']['traces']['exporters']=['otlphttp/tempo']
|
||||
collector['extensions']['health_check']['endpoint']='127.0.0.1:13133'
|
||||
collector['extensions']['basicauth/server']={'htpasswd':{'file':'/run/config/htpasswd'}}
|
||||
collector['service']['extensions'].append('basicauth/server')
|
||||
write('otel/collector.yaml',collector)
|
||||
write('otel/htpasswd',''.join(role+':{SHA}'+base64.b64encode(hashlib.sha1(v[role+'_otel'].encode()).digest()).decode()+'\n' for role in ('api','worker')))
|
||||
write('otel/prometheus.yaml',{'global':{'scrape_interval':'5s'},'scrape_configs':[{'job_name':'messenger','scheme':'https',
|
||||
'tls_config':{'ca_file':'/run/pki/ca.crt','cert_file':'/run/identity/client.crt','key_file':'/run/identity/client.key'},
|
||||
'static_configs':[{'targets':['otel-collector:8889']}]}]})
|
||||
loki=yaml.safe_load((ROOT/'infra/otel/loki.yaml').read_text());loki['server'].update(http_listen_address='127.0.0.1',http_listen_port=3101,grpc_listen_address='127.0.0.1')
|
||||
loki['common']['instance_addr']='127.0.0.1';write('otel/loki.yaml',loki)
|
||||
tempo=yaml.safe_load((ROOT/'infra/otel/tempo.yaml').read_text());tempo['server'].update(http_listen_address='127.0.0.1',http_listen_port=3201,grpc_listen_address='127.0.0.1')
|
||||
tempo['distributor']['receivers']['otlp']['protocols']={'http':{'endpoint':'127.0.0.1:4319'}};write('otel/tempo.yaml',tempo)
|
||||
write('grafana/provisioning/dashboards/dashboards.yaml',yaml.safe_load((ROOT/'infra/grafana/provisioning/dashboards/dashboards.yaml').read_text(encoding='utf-8')))
|
||||
sources=yaml.safe_load((ROOT/'infra/grafana/provisioning/datasources/sources.yaml').read_text())
|
||||
for source in sources['datasources']:
|
||||
source['url']=source['url'].replace('http://','https://')
|
||||
source.setdefault('jsonData',{}).update(tlsAuth=True,tlsAuthWithCACert=True)
|
||||
source['secureJsonData']={'tlsCACert':CA.read_text(),'tlsClientCert':(RUNTIME/'pki/client/grafana/client.crt').read_text(),
|
||||
'tlsClientKey':(RUNTIME/'pki/client/grafana/client.key').read_text()}
|
||||
write('grafana/provisioning/datasources/sources.yaml',sources)
|
||||
|
||||
|
||||
def negative_certificates():
|
||||
state=operator_load()
|
||||
root=x509.load_pem_x509_certificate(CA.read_bytes())
|
||||
for identity in ('foreign','expired'):
|
||||
path=RUNTIME/f'pki/client/{identity}/client.crt'
|
||||
if path.exists():continue
|
||||
signer=new_key() if identity=='foreign' else serialization.load_pem_private_key(state['ca_key'].encode(),None)
|
||||
key=new_key()
|
||||
now=datetime.now(timezone.utc)
|
||||
issuer=x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'Foreign CA')]) if identity=='foreign' else root.subject
|
||||
cert=(x509.CertificateBuilder().subject_name(x509.Name([x509.NameAttribute(NameOID.COMMON_NAME,'lb')]))
|
||||
.issuer_name(issuer).public_key(key.public_key()).serial_number(x509.random_serial_number())
|
||||
.not_valid_before(now-timedelta(days=2)).not_valid_after(now-timedelta(days=1) if identity=='expired' else now+timedelta(days=1))
|
||||
.add_extension(x509.SubjectAlternativeName([x509.DNSName('lb')]),False)
|
||||
.add_extension(x509.BasicConstraints(False,None),True)
|
||||
.add_extension(x509.ExtendedKeyUsage([ExtendedKeyUsageOID.CLIENT_AUTH]),False)
|
||||
.add_extension(x509.AuthorityKeyIdentifier.from_issuer_public_key(signer.public_key()),False).sign(signer,hashes.SHA256()))
|
||||
write(f'pki/client/{identity}/client.crt',cert.public_bytes(serialization.Encoding.PEM).decode())
|
||||
write(f'pki/client/{identity}/client.key',private(key))
|
||||
|
||||
|
||||
def bao_request(path, data=None, token=None, identity='operator', method=None):
|
||||
context=ssl.create_default_context(cafile=str(CA))
|
||||
context.load_cert_chain(str(RUNTIME/f'pki/client/{identity}/client.crt'),str(RUNTIME/f'pki/client/{identity}/client.key'))
|
||||
opener=build_opener(ProxyHandler({}),HTTPSHandler(context=context))
|
||||
headers={'Content-Type':'application/json'}
|
||||
if token:headers['X-Vault-Token']=token
|
||||
port=int(os.environ.get('BAO_PORT','18200'))
|
||||
raw=json.dumps(data).encode() if data is not None else None
|
||||
with opener.open(Request(f'https://127.0.0.1:{port}/v1/'+path,data=raw,headers=headers,method=method),timeout=10) as r:
|
||||
payload=r.read()
|
||||
return json.loads(payload) if payload else {}
|
||||
|
||||
|
||||
def unseal():
|
||||
state=operator_load()
|
||||
for share in state.get('unseal',[]):
|
||||
if not bao_request('sys/seal-status')['sealed']:break
|
||||
bao_request('sys/unseal',{'key':share})
|
||||
|
||||
|
||||
def bootstrap_bao():
|
||||
state=operator_load()
|
||||
if not bao_request('sys/init')['initialized']:
|
||||
result=bao_request('sys/init',{'secret_shares':5,'secret_threshold':3})
|
||||
state.update(unseal=result['keys_base64'],root_token=result['root_token'],configured=False)
|
||||
operator_save(state)
|
||||
unseal()
|
||||
if state.get('configured'):
|
||||
if state.pop('renew_roles',False):
|
||||
token=bao_request('auth/cert/login',{'name':'operator'})['auth']['client_token']
|
||||
register_roles(token)
|
||||
bao_request('auth/token/revoke-self',{},token)
|
||||
operator_save(state)
|
||||
return
|
||||
token=state['root_token']
|
||||
if 'secret/' not in bao_request('sys/mounts',token=token):
|
||||
bao_request('sys/mounts/secret',{'type':'kv','options':{'version':'2'}},token)
|
||||
if 'cert/' not in bao_request('sys/auth',token=token):
|
||||
bao_request('sys/auth/cert',{'type':'cert'},token)
|
||||
for role in ('api','worker','cleanup'):
|
||||
bao_request('secret/data/'+role,{'data':bundle(role)},token)
|
||||
policy='path "secret/data/'+role+'" { capabilities = ["read"] }\n'
|
||||
bao_request('sys/policies/acl/lab7-'+role,{'policy':policy},token,method='PUT')
|
||||
operator_policy='''path "secret/*" { capabilities = ["create", "read", "update", "delete", "list"] }
|
||||
path "auth/cert/*" { capabilities = ["create", "read", "update", "delete", "list", "sudo"] }
|
||||
path "sys/policies/acl/lab7-*" { capabilities = ["create", "read", "update", "delete", "list"] }
|
||||
path "sys/seal" { capabilities = ["update", "sudo"] }
|
||||
'''
|
||||
bao_request('sys/policies/acl/lab7-operator',{'policy':operator_policy},token,method='PUT')
|
||||
register_roles(token)
|
||||
bao_request('auth/token/revoke-self',{},token)
|
||||
state.pop('root_token',None);state['configured']=True;operator_save(state)
|
||||
|
||||
|
||||
def register_roles(token):
|
||||
for identity,role in [('api1','api'),('api2','api'),('worker','worker'),('cleanup','cleanup'),('operator','operator')]:
|
||||
bao_request('auth/cert/certs/'+identity,{'certificate':CA.read_text(),
|
||||
'allowed_dns_sans':[identity],'token_policies':['lab7-'+role],'token_ttl':int(os.environ.get('BAO_TOKEN_TTL','900')),'token_max_ttl':max(4,int(os.environ.get('BAO_TOKEN_TTL','900'))*4)},token)
|
||||
@@ -0,0 +1,145 @@
|
||||
import json
|
||||
import ssl
|
||||
import sys
|
||||
from urllib.request import build_opener, HTTPSHandler, ProxyHandler, Request
|
||||
|
||||
|
||||
def opener(identity='operator', trusted=True):
|
||||
context=ssl.create_default_context(cafile='/run/pki/ca.crt') if trusted else ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT)
|
||||
if identity:
|
||||
context.load_cert_chain('/run/all-pki/client/'+identity+'/client.crt','/run/all-pki/client/'+identity+'/client.key')
|
||||
return build_opener(ProxyHandler({}),HTTPSHandler(context=context))
|
||||
|
||||
|
||||
def fetch(url, identity='operator', data=None, headers=None, method=None):
|
||||
raw=json.dumps(data).encode() if data is not None else None
|
||||
with opener(identity).open(Request(url,data=raw,headers={'Accept':'application/json','Content-Type':'application/json',**(headers or {})},method=method),timeout=10) as r:
|
||||
raw=r.read()
|
||||
return json.loads(raw) if raw else {}
|
||||
|
||||
|
||||
def secret(role, identity):
|
||||
auth=fetch('https://openbao:8200/v1/auth/cert/login',identity,{'name':identity})['auth']
|
||||
return fetch('https://openbao:8200/v1/secret/data/'+role,identity,
|
||||
headers={'X-Vault-Token':auth['client_token']})['data']['data']
|
||||
|
||||
|
||||
def main():
|
||||
spec=json.load(sys.stdin)
|
||||
if spec['op']=='fetch':
|
||||
print(json.dumps([fetch(url) for url in spec['urls']]))
|
||||
elif spec['op']=='tls':
|
||||
import socket
|
||||
results={}
|
||||
reasons={}
|
||||
for server in ('api1','api2'):
|
||||
for identity in (None,'wrong-role','foreign','expired','lb'):
|
||||
context=ssl.create_default_context(cafile='/run/pki/ca.crt')
|
||||
if identity:
|
||||
context.load_cert_chain('/run/all-pki/client/'+identity+'/client.crt','/run/all-pki/client/'+identity+'/client.key')
|
||||
try:
|
||||
with socket.create_connection((server,8443),timeout=5) as raw:
|
||||
with context.wrap_socket(raw,server_hostname=server) as connection:
|
||||
connection.sendall(b'GET /health/live HTTP/1.1\r\nHost: api\r\nConnection: close\r\n\r\n')
|
||||
data=connection.recv(4096)
|
||||
success=b'200 OK' in data
|
||||
except (TimeoutError,ConnectionRefusedError):
|
||||
raise RuntimeError('TLS test endpoint unavailable') from None
|
||||
except (ssl.SSLError,ConnectionResetError) as error:
|
||||
reasons[server+':'+str(identity)]=type(error).__name__
|
||||
success=False
|
||||
results[server+':'+str(identity)]=success
|
||||
try:
|
||||
with socket.create_connection((server,8080),timeout=2):
|
||||
results[server+':plaintext']=True
|
||||
except OSError:
|
||||
results[server+':plaintext']=False
|
||||
results['reject_reasons']=reasons
|
||||
print(json.dumps(results))
|
||||
elif spec['op']=='audit':
|
||||
import socket
|
||||
results={}
|
||||
hidden={'api1':[8080],'api2':[8080],'s3':[7333,8080,8888,9333,19001],
|
||||
'broker':[4369,5672,15672,15692,25672],'otel-collector':[4319,8890,8888,13133],
|
||||
'loki':[3101,9095],'tempo':[3201,4319,9095],'prometheus':[9091],'openbao':[8201]}
|
||||
for host,ports in hidden.items():
|
||||
for port in ports:
|
||||
try:
|
||||
with socket.create_connection((host,port),timeout=1):results[host+':'+str(port)]=False
|
||||
except (ConnectionRefusedError,TimeoutError):results[host+':'+str(port)]=True
|
||||
print(json.dumps(results))
|
||||
elif spec['op']=='rights':
|
||||
import boto3,pika
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import ClientError
|
||||
from pika.exceptions import ChannelClosedByBroker
|
||||
results={}
|
||||
for role,identity in [('api','api1'),('worker','worker')]:
|
||||
v=secret(role,identity)
|
||||
c=boto3.client('s3',endpoint_url='https://s3:9000',verify='/run/pki/ca.crt',
|
||||
aws_access_key_id=v['s3_access_key_id'],aws_secret_access_key=v['s3_secret_access_key'],
|
||||
config=Config(signature_version='s3v4',proxies={},retries={'total_max_attempts':1}))
|
||||
operation=(lambda:c.get_object(Bucket='messenger-attachments',Key='staging/forbidden')) if role=='api' else (lambda:c.get_object(Bucket='messenger-attachments',Key='system/readiness'))
|
||||
try:
|
||||
operation();results[role+':s3_denied']=False
|
||||
except ClientError as error:
|
||||
results[role+':s3_denied']=error.response['ResponseMetadata']['HTTPStatusCode']==403
|
||||
try:
|
||||
c.create_bucket(Bucket='forbidden-security-probe');results[role+':bucket_admin_denied']=False
|
||||
except ClientError as error:
|
||||
results[role+':bucket_admin_denied']=error.response['ResponseMetadata']['HTTPStatusCode']==403
|
||||
params=pika.URLParameters(v['broker_url']);params.ssl_options=pika.SSLOptions(ssl.create_default_context(cafile='/run/pki/ca.crt'),'broker')
|
||||
conn=pika.BlockingConnection(params)
|
||||
try:
|
||||
ch=conn.channel();ch.queue_declare(queue='attachment.process.v1',passive=True)
|
||||
results[role+':amqps']=True
|
||||
try:
|
||||
ch.basic_get(queue='attachment.process.v1') if role=='api' else ch.queue_declare(queue='forbidden')
|
||||
results[role+':broker_denied']=False
|
||||
except ChannelClosedByBroker as error:
|
||||
results[role+':broker_denied']=error.reply_code==403
|
||||
finally:conn.close()
|
||||
from urllib.error import HTTPError
|
||||
for label,url,identity in [('grafana_ingest','https://loki:3100/otlp/v1/logs','grafana'),('collector_query','https://loki:3100/loki/api/v1/query_range','collector'),('anonymous_otlp','https://otel-collector:4318/v1/logs',None)]:
|
||||
try:
|
||||
fetch(url,identity,{} if label!='collector_query' else None);results[label]=False
|
||||
except HTTPError as error:
|
||||
results[label]=error.code in (401,403);error.close()
|
||||
print(json.dumps(results))
|
||||
elif spec['op']=='argon2':
|
||||
import time,statistics
|
||||
from argon2 import PasswordHasher
|
||||
h=PasswordHasher(memory_cost=19456,time_cost=2,parallelism=1)
|
||||
hashed=h.hash('synthetic-benchmark-password')
|
||||
h.verify(hashed,'synthetic-benchmark-password')
|
||||
timings={}
|
||||
for name,operation in [('hash',lambda:h.hash('synthetic-benchmark-password')),('verify',lambda:h.verify(hashed,'synthetic-benchmark-password'))]:
|
||||
values=[]
|
||||
for _ in range(30):
|
||||
started=time.perf_counter();operation();values.append((time.perf_counter()-started)*1000)
|
||||
timings[name]={'p50_ms':round(statistics.median(values),3),'p95_ms':round(sorted(values)[28],3),'samples':30}
|
||||
print(json.dumps({'timings':timings,'context':'Linux application image, one CPU'}))
|
||||
elif spec['op']=='database':
|
||||
import psycopg
|
||||
results={}
|
||||
for role,identity in [('api','api1'),('worker','worker'),('cleanup','cleanup')]:
|
||||
values=secret(role,identity)
|
||||
with psycopg.connect(values['database_url'],autocommit=True) as db:
|
||||
results[role+':tls']=db.execute('SELECT ssl FROM pg_stat_ssl WHERE pid=pg_backend_pid()').fetchone()[0]
|
||||
try:
|
||||
db.execute('CREATE TABLE forbidden_probe(id int)')
|
||||
results[role+':ddl_denied']=False
|
||||
db.execute('DROP TABLE forbidden_probe')
|
||||
except psycopg.errors.InsufficientPrivilege:
|
||||
results[role+':ddl_denied']=True
|
||||
if role!='api':
|
||||
try:
|
||||
db.execute('SELECT password_hash FROM users LIMIT 1')
|
||||
results[role+':users_denied']=False
|
||||
except psycopg.errors.InsufficientPrivilege:
|
||||
results[role+':users_denied']=True
|
||||
print(json.dumps(results))
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
main()
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
python "%~dp0lab.py" restart
|
||||
exit /b %errorlevel%
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
TASK_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
exec python3 "$TASK_DIR/lab.py" restart
|
||||
@@ -0,0 +1,147 @@
|
||||
import base64
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import socket
|
||||
import ssl
|
||||
import statistics
|
||||
import sys
|
||||
import time
|
||||
from urllib.error import HTTPError, URLError
|
||||
from urllib.request import Request
|
||||
|
||||
sys.path.insert(0,str(Path(__file__).resolve().parents[1]))
|
||||
from scripts import lab, provision as p
|
||||
from scripts.observability_checks import arguments, probe
|
||||
|
||||
|
||||
def denied(function, allowed=(400,403)):
|
||||
try:
|
||||
function()
|
||||
except HTTPError as error:
|
||||
status=error.code;error.close()
|
||||
if status not in allowed:raise RuntimeError('Unexpected deny status: '+str(status))
|
||||
return status
|
||||
raise RuntimeError('Forbidden operation was permitted')
|
||||
|
||||
|
||||
def tls(args):
|
||||
p.negative_certificates()
|
||||
c=lab.client(args)
|
||||
c.call('GET','/health/live',schema='Health')
|
||||
results=probe(args,{'op':'tls'})
|
||||
for server in ('api1','api2'):
|
||||
for identity in ('None','wrong-role','foreign','expired'):
|
||||
if results[server+':'+identity]:raise RuntimeError('Unauthorized TLS identity reached API')
|
||||
if not results[server+':lb'] or results[server+':plaintext']:
|
||||
raise RuntimeError('mTLS positive/plaintext boundary failed')
|
||||
for name in ('untrusted-ca','wrong-hostname'):
|
||||
context=ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) if name=='untrusted-ca' else ssl.create_default_context(cafile=lab.environment(args)['CA_FILE'])
|
||||
try:
|
||||
with socket.create_connection(('127.0.0.1',args.port),timeout=5) as raw:
|
||||
with context.wrap_socket(raw,server_hostname='localhost' if name=='untrusted-ca' else 'wrong.lab'):pass
|
||||
except ssl.SSLCertVerificationError:
|
||||
results[name]='CERTIFICATE_VERIFY_FAILED'
|
||||
else:raise RuntimeError('Bad external TLS trust accepted')
|
||||
lab.evidence('tls.json',{'status':'PASS','checks':results})
|
||||
lab.say('PASS: external CA/hostname, both mTLS identities, foreign CA, expiry and no plaintext bypass')
|
||||
return results
|
||||
|
||||
|
||||
def policies(args):
|
||||
result={}
|
||||
result['wrong_certificate_role']=denied(lambda:p.bao_request('auth/cert/login',{'name':'api1'},identity='wrong-role'))
|
||||
result['local_boundaries']=probe(args,{'op':'audit'})
|
||||
if not all(result['local_boundaries'].values()):raise RuntimeError('Unexpected plaintext/admin listener exposed')
|
||||
for identity,role in [('api1','api'),('api2','api'),('worker','worker'),('cleanup','cleanup')]:
|
||||
auth=p.bao_request('auth/cert/login',{'name':identity},identity=identity)['auth']
|
||||
token=auth['client_token']
|
||||
own=p.bao_request('secret/data/'+role,token=token,identity=identity)['data']['data']
|
||||
result[identity]={'own_secret':True,'ttl_seconds':auth['lease_duration']}
|
||||
other='api' if role!='api' else 'worker'
|
||||
result[identity]['other_secret']=denied(lambda:p.bao_request('secret/data/'+other,token=token,identity=identity))
|
||||
result[identity]['write_policy']=denied(lambda:p.bao_request('sys/policies/acl/forbidden',{'policy':''},token,identity,method='PUT'))
|
||||
p.bao_request('auth/token/revoke-self',{},token,identity)
|
||||
result[identity]['revoked_token']=denied(lambda:p.bao_request('secret/data/'+role,token=token,identity=identity))
|
||||
if role!='api' and ('cursor_key' in own or 'api' in own['database_url'].split('@')[0]):
|
||||
raise RuntimeError('Wrong secret bundle')
|
||||
result['database']=probe(args,{'op':'database'})
|
||||
if not all(result['database'].values()):raise RuntimeError('Database role check failed')
|
||||
result['dependencies']=probe(args,{'op':'rights'})
|
||||
if not all(result['dependencies'].values()):raise RuntimeError('Dependency ACL check failed')
|
||||
for name, state in lab.states(args).items():
|
||||
if name in ('api1','api2','worker') and state['user']!='messenger':
|
||||
raise RuntimeError('Application user is not non-root')
|
||||
if 'root_token' in p.operator_load():raise RuntimeError('Initial root token not revoked')
|
||||
lab.evidence('policies.json',{'status':'PASS','results':result})
|
||||
lab.say('PASS: scoped OpenBao policies, revoked tokens, DB/S3/broker/telemetry permissions')
|
||||
return result
|
||||
|
||||
|
||||
def limits(args):
|
||||
c=lab.client(args)
|
||||
c.call('POST','/api/v1/users',413,raw=b' '*65537,headers={'Content-Type':'application/json'})
|
||||
def chunks():
|
||||
for _ in range(17):yield b' '*4096
|
||||
c.call('POST','/api/v1/users',413,raw=chunks(),headers={'Content-Type':'application/json'})
|
||||
authorization='Basic '+base64.b64encode(b'unknown:wrong-password').decode()
|
||||
def login(_):
|
||||
return c.call('POST','/api/v1/auth/sessions',[401,429],headers={'Authorization':authorization})
|
||||
with ThreadPoolExecutor(max_workers=12) as pool:
|
||||
replies=list(pool.map(login,range(60)))
|
||||
rejected=[r for r in replies if r['status']==429]
|
||||
if not rejected or not all(r['headers'].get('Retry-After') for r in rejected):
|
||||
raise RuntimeError('No valid login rate limit observed')
|
||||
time.sleep(2)
|
||||
actor=c.user('after_rate_limit')
|
||||
c.call('GET','/api/v1/users/me',actor=actor)
|
||||
measured=probe(args,{'op':'argon2'})
|
||||
timings=measured['timings']
|
||||
result={'status':'PASS','json_limit_bytes':65536,'chunked_limit':'PASS','login_429':len(rejected),
|
||||
'retry_after':'PASS','recovered_login':201,'measurement_context':measured['context'],'argon2id':{'memory_kib':19456,'t':2,'p':1,'timings':timings}}
|
||||
lab.evidence('limits.json',result)
|
||||
lab.say('PASS: JSON/chunked limits, login 429/Retry-After, Argon2id measurements')
|
||||
return result
|
||||
|
||||
|
||||
def bao_expiry(args):
|
||||
import argparse
|
||||
test=argparse.Namespace(project=args.project+'-bao-ttl',port=args.test_port,ttl=3600,
|
||||
test_port=args.test_port,grafana_port=3311,action='start')
|
||||
try:
|
||||
lab.setup(test)
|
||||
lab.start(test)
|
||||
lab.run(test,[lab.interpreter(),'-X','utf8','scripts/security_checks.py','bao-expiry'])
|
||||
finally:
|
||||
lab.compose(test,'down','--timeout','10')
|
||||
|
||||
|
||||
def sealed_case(args):
|
||||
c=lab.client(args)
|
||||
actor=c.user('bao_expiry')
|
||||
c.call('GET','/api/v1/users/me',actor=actor)
|
||||
auth=p.bao_request('auth/cert/login',{'name':'operator'})['auth']
|
||||
try:
|
||||
p.bao_request('sys/seal',{},auth['client_token'])
|
||||
time.sleep(5)
|
||||
c.call('GET','/health/live',schema='Health')
|
||||
c.call('GET','/health/ready',503)
|
||||
c.call('GET','/api/v1/users/me',503,actor=actor)
|
||||
finally:
|
||||
p.unseal()
|
||||
lab.wait_ready(args)
|
||||
c.call('GET','/api/v1/users/me',actor=actor)
|
||||
result={'status':'PASS','service_token_ttl':2,'while_sealed':{'live':200,'ready':503,'business':503},
|
||||
'after_unseal':200,'old_session_preserved':True,'operator_unseal_outside_containers':True}
|
||||
lab.evidence('bao-expiry.json',result)
|
||||
lab.say('PASS: sealed OpenBao, bounded credential cache and recovery with old session')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
args=arguments()
|
||||
if sys.argv[1] in ('tls-check','security-check'):tls(args)
|
||||
if sys.argv[1] in ('policy-check','security-check'):policies(args)
|
||||
if sys.argv[1]=='security-check':limits(args)
|
||||
if sys.argv[1]=='bao-check':bao_expiry(args)
|
||||
if sys.argv[1]=='bao-expiry':sealed_case(args)
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
python "%~dp0lab.py" stop-one
|
||||
exit /b %errorlevel%
|
||||
Executable
+5
@@ -0,0 +1,5 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
: "${TARGET_INSTANCE_ID:?missing TARGET_INSTANCE_ID}"
|
||||
TASK_DIR=$(CDPATH= cd -- "$(dirname -- "$0")" && pwd)
|
||||
exec python3 "$TASK_DIR/lab.py" stop-one
|
||||
@@ -0,0 +1,118 @@
|
||||
from copy import deepcopy
|
||||
from pathlib import Path
|
||||
import yaml
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
ENVOY = 'envoyproxy/envoy:v1.40.2@sha256:8de97e654644827d62afdbf7e1d3dc9fee01a8690d410dd1c63a30dc6b6cecbb'
|
||||
BAO = 'openbao/openbao:2.7.3@sha256:ba4b133eb9586630024e71a617e66f37f29cc3534cdd46a6233e098ceded8dc9'
|
||||
|
||||
|
||||
def certs(server=None, client=None):
|
||||
mounts = ['./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro']
|
||||
if server:
|
||||
mounts.append(f'./runtime/${{COMPOSE_PROJECT_NAME}}/pki/server/{server}:/run/server:ro')
|
||||
if client:
|
||||
mounts.append(f'./runtime/${{COMPOSE_PROJECT_NAME}}/pki/client/{client}:/run/identity:ro')
|
||||
return mounts
|
||||
|
||||
|
||||
def render():
|
||||
base = yaml.safe_load((ROOT/'infra/base-compose.yaml').read_text(encoding='utf-8'))
|
||||
original = base['services']
|
||||
services = deepcopy(original)
|
||||
for service in services.values():
|
||||
service.pop('secrets', None)
|
||||
service.pop('networks', None)
|
||||
service.pop('depends_on', None)
|
||||
service['mem_limit'] = service.get('mem_limit','512m')
|
||||
service['cpus'] = 1.0
|
||||
app_environment = deepcopy(original['api1']['environment'])
|
||||
app_environment.update(APP_HOST='127.0.0.1', SERVICE_VERSION='lab7', TLS_CA_FILE='/run/pki/ca.crt',
|
||||
S3_ENDPOINT='https://s3:9000',S3_BUCKET='messenger-attachments',
|
||||
OTEL_EXPORTER_OTLP_ENDPOINT='https://otel-collector:4318')
|
||||
for key in ('DATABASE_URL_FILE','CURSOR_SECRET_FILE','S3_ACCESS_KEY_ID_FILE','S3_SECRET_ACCESS_KEY_FILE','BROKER_URL_FILE'):
|
||||
app_environment[key] = app_environment[key].replace('/run/secrets/','/run/runtime/')
|
||||
for name in ('api1','api2','worker','cleanup'):
|
||||
service = services[name]
|
||||
role = 'api' if name.startswith('api') else name
|
||||
service['image']='mtusi-messenger:lab7'
|
||||
service['environment']=dict(app_environment,SERVICE_IDENTITY=name,SECRET_ROLE=role)
|
||||
if role=='cleanup':
|
||||
for key in ('CURSOR_SECRET_FILE','BROKER_URL_FILE'):
|
||||
service['environment'].pop(key)
|
||||
service['volumes']=certs(client=name)
|
||||
service['tmpfs']=['/run/runtime:uid=10001,gid=10001,mode=0700','/tmp:uid=10001,gid=10001,mode=0700']
|
||||
service['cap_drop']=['ALL']
|
||||
service['security_opt']=['no-new-privileges:true']
|
||||
service['stop_grace_period']='20s'
|
||||
db=services['db']
|
||||
db['environment']['POSTGRES_PASSWORD_FILE']='/run/config/password'
|
||||
db['volumes'] += ['./runtime/${COMPOSE_PROJECT_NAME}/db:/run/config:ro'] + certs(server='db')
|
||||
db['entrypoint']=['/bin/sh','-c','install -o postgres -g postgres -m 600 /run/server/client.key /var/lib/postgresql/server.key; exec docker-entrypoint.sh postgres -c ssl=on -c ssl_cert_file=/run/server/client.crt -c ssl_key_file=/var/lib/postgresql/server.key -c hba_file=/run/config/pg_hba.conf']
|
||||
storage=services['s3-storage']
|
||||
storage['command']=[str(x).replace('-ip=s3-storage','-ip=127.0.0.1').replace('-ip.bind=0.0.0.0','-ip.bind=127.0.0.1') for x in storage['command']]
|
||||
storage['networks']={'default':{'aliases':['s3']}}
|
||||
s3=services['s3']
|
||||
s3['network_mode']='service:s3-storage'
|
||||
s3['command']=['s3','-filer=127.0.0.1:8888','-port=9001','-ip.bind=127.0.0.1',
|
||||
'-config=/run/config/config.json','-iam=false','-port.iceberg=0','-port.lance=0']
|
||||
s3['volumes']=['./runtime/${COMPOSE_PROJECT_NAME}/s3:/run/config:ro']
|
||||
s3['depends_on']={'s3-storage':{'condition':'service_healthy'}}
|
||||
broker=services['broker']
|
||||
broker['environment']['RABBITMQ_CONFIG_FILE']='/run/config/rabbitmq'
|
||||
broker['environment']['RABBITMQ_SERVER_ADDITIONAL_ERL_ARGS']='-kernel inet_dist_use_interface {127,0,0,1}'
|
||||
broker['environment']['ERL_EPMD_ADDRESS']='127.0.0.1'
|
||||
broker['extra_hosts']={'broker':'127.0.0.1'}
|
||||
broker['volumes'] += ['./runtime/${COMPOSE_PROJECT_NAME}/broker:/run/config:ro']+certs(server='broker')
|
||||
for name in ('migrate','bootstrap'):
|
||||
service=services[name]
|
||||
service['image']='mtusi-messenger:lab7'
|
||||
service['environment']=dict(app_environment)
|
||||
service['environment'].pop('CURSOR_SECRET_FILE')
|
||||
for key in ('DATABASE_URL_FILE','S3_ACCESS_KEY_ID_FILE','S3_SECRET_ACCESS_KEY_FILE'):
|
||||
service['environment'][key]=service['environment'][key].replace('/run/runtime/','/run/operator/')
|
||||
if name=='bootstrap':
|
||||
service['environment'].update(S3_ADMIN_ACCESS_KEY_ID_FILE='/run/operator/s3_admin_access_key_id',
|
||||
S3_ADMIN_SECRET_ACCESS_KEY_FILE='/run/operator/s3_admin_secret_access_key')
|
||||
service['volumes']=certs()+['./runtime/${COMPOSE_PROJECT_NAME}/operator:/run/operator:ro']
|
||||
services['lb']['volumes']=['./infra/haproxy.cfg:/usr/local/etc/haproxy/haproxy.cfg:ro']+certs(server='lb',client='lb')
|
||||
services['lb']['ports']=['127.0.0.1:${HTTP_PORT:-8443}:8443']
|
||||
services['lb']['user']='99:99'
|
||||
for name in ('otel-collector','prometheus','loki','tempo'):
|
||||
service=services[name]
|
||||
client={'otel-collector':'collector','prometheus':'scraper'}.get(name)
|
||||
service['volumes']=[mount.replace('./infra/otel/','./runtime/${COMPOSE_PROJECT_NAME}/otel/') for mount in service['volumes']]+certs(client=client)
|
||||
if name=='otel-collector':
|
||||
service['volumes'].append('./runtime/${COMPOSE_PROJECT_NAME}/otel/htpasswd:/run/config/htpasswd:ro')
|
||||
if name=='prometheus':
|
||||
service['command'].append('--web.listen-address=127.0.0.1:9091')
|
||||
grafana=services['grafana']
|
||||
grafana['volumes']=[mount.replace('./infra/grafana/provisioning:/etc/grafana/provisioning:ro','./runtime/${COMPOSE_PROJECT_NAME}/grafana/provisioning:/etc/grafana/provisioning:ro') for mount in grafana['volumes']]+certs(server='grafana')
|
||||
grafana['volumes'] += ['./runtime/${COMPOSE_PROJECT_NAME}/grafana/password:/run/config/password:ro']
|
||||
grafana['environment'].update(GF_SERVER_PROTOCOL='https',GF_SERVER_CERT_FILE='/run/server/client.crt',
|
||||
GF_SERVER_CERT_KEY='/run/server/client.key',GF_SECURITY_ADMIN_PASSWORD__FILE='/run/config/password')
|
||||
grafana['ports']=['127.0.0.1:${GRAFANA_PORT:-3309}:3000']
|
||||
for name in ('api1','api2','s3','otel-collector','prometheus','loki','tempo'):
|
||||
owner='s3-storage' if name=='s3' else name
|
||||
services[name+'-tls']={'image':ENVOY,'user':'101:101','network_mode':'service:'+owner,
|
||||
'command':['envoy','-c','/etc/envoy/envoy.yaml','--concurrency','2','--disable-hot-restart'],
|
||||
'volumes':certs(server=name)+[f'./runtime/${{COMPOSE_PROJECT_NAME}}/envoy/{name}.yaml:/etc/envoy/envoy.yaml:ro'],
|
||||
'cap_drop':['ALL'],'security_opt':['no-new-privileges:true'],'mem_limit':'128m','cpus':0.5,
|
||||
'depends_on':{owner:{'condition':'service_started'}},'stop_grace_period':'5s'}
|
||||
services['openbao']={'image':BAO,'command':['server','-config=/run/config/config.json'],
|
||||
'volumes':['baodata:/bao/data','./runtime/${COMPOSE_PROJECT_NAME}/bao:/run/config:ro']+certs(server='openbao'),
|
||||
'ports':['127.0.0.1:${BAO_PORT:-18200}:8200'],'mem_limit':'512m','cpus':1.0,
|
||||
'environment':{'SKIP_SETCAP':'true'},'cap_drop':['IPC_LOCK'],'stop_grace_period':'10s'}
|
||||
services['bao-volume-init']={'image':'mtusi-messenger:lab7','user':'0:0','network_mode':'none','volumes':['baodata:/bao/data'],'command':['python','-c',"import os; os.chown('/bao/data',100,1000)"],'mem_limit':'64m','cap_drop':['ALL'],'cap_add':['CHOWN'],'healthcheck':{'disable':True}}
|
||||
services['openbao']['depends_on']={'bao-volume-init':{'condition':'service_completed_successfully'}}
|
||||
services['probe']={'image':'mtusi-messenger:lab7','profiles':['tools'],'user':'0:0',
|
||||
'volumes':['./runtime/${COMPOSE_PROJECT_NAME}/pki:/run/all-pki:ro','./runtime/${COMPOSE_PROJECT_NAME}/pki/ca.crt:/run/pki/ca.crt:ro',
|
||||
'./runtime/${COMPOSE_PROJECT_NAME}/pki/client/operator:/run/identity:ro'], 'mem_limit':'256m','cpus':1.0,
|
||||
'healthcheck':{'disable':True}}
|
||||
base={'name':'mtusi-lab7','services':services,'volumes':{**base['volumes'],'baodata':{}},
|
||||
'networks':{'default':{'ipam':{'config':[{'subnet':'${LAB7_APP_SUBNET:-10.240.70.0/24}'}]}}}}
|
||||
(ROOT/'compose.yaml').write_text(yaml.safe_dump(base,sort_keys=False),encoding='utf-8',newline='\n')
|
||||
|
||||
|
||||
if __name__=='__main__':
|
||||
render()
|
||||
@@ -0,0 +1 @@
|
||||
|
||||
@@ -0,0 +1,23 @@
|
||||
import logging
|
||||
import os
|
||||
|
||||
import uvicorn
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
from . import bao
|
||||
bao.initialize()
|
||||
logging.basicConfig(level=logging.INFO, format="%(levelname)s %(message)s")
|
||||
logging.getLogger("messenger").info("environment=%s", os.environ.get("APP_ENV", "lab"))
|
||||
port = int(os.environ.get("APP_PORT", "8080"))
|
||||
if not 1 <= port <= 65535:
|
||||
raise SystemExit("APP_PORT должен быть от 1 до 65535")
|
||||
uvicorn.run(
|
||||
"src.app:create_app",
|
||||
factory=True,
|
||||
host=os.environ.get("APP_HOST", "0.0.0.0"),
|
||||
port=port,
|
||||
workers=1,
|
||||
access_log=False,
|
||||
timeout_graceful_shutdown=2,
|
||||
)
|
||||
+227
@@ -0,0 +1,227 @@
|
||||
from contextlib import asynccontextmanager
|
||||
import logging
|
||||
import re
|
||||
import time
|
||||
from opentelemetry import trace
|
||||
from uuid import UUID, uuid4
|
||||
from urllib.parse import quote
|
||||
from typing import Literal
|
||||
|
||||
from fastapi import FastAPI, Request, Response
|
||||
from fastapi.exceptions import RequestValidationError
|
||||
from fastapi.responses import JSONResponse, StreamingResponse
|
||||
from starlette.background import BackgroundTask
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.exceptions import HTTPException
|
||||
|
||||
from .attachments import Attachments
|
||||
from .objects import Objects
|
||||
from . import broker, telemetry, bao
|
||||
from .errors import ApiError, invalid
|
||||
from .models import CreateChat, CreateMessage, CreateUser
|
||||
from .security import basic_credentials, bearer_token
|
||||
from .storage import PostgresStore
|
||||
|
||||
|
||||
logger = logging.getLogger("messenger")
|
||||
SESSION_PATH = "/api/v1/auth/sessions"
|
||||
|
||||
|
||||
def uuid_value(value):
|
||||
try:
|
||||
return UUID(value)
|
||||
except ValueError:
|
||||
raise invalid("Неверный UUID") from None
|
||||
|
||||
|
||||
def page_args(request):
|
||||
raw = request.query_params.get("limit", "50")
|
||||
normalized = raw.lstrip("0") or "0"
|
||||
if re.fullmatch(r"[0-9]+", raw) is None or len(normalized) > 3 or not 1 <= int(normalized) <= 100:
|
||||
raise invalid("Limit должен быть от 1 до 100")
|
||||
return int(normalized), request.query_params.get("cursor")
|
||||
|
||||
|
||||
def create_app():
|
||||
store = PostgresStore()
|
||||
objects = Objects()
|
||||
attachments = Attachments(store, objects)
|
||||
instance_id = uuid4().hex
|
||||
runtime = telemetry.initialize("messenger-api", instance_id)
|
||||
|
||||
@asynccontextmanager
|
||||
async def lifespan(app):
|
||||
await run_in_threadpool(store.open)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
await run_in_threadpool(store.close)
|
||||
objects.close()
|
||||
await run_in_threadpool(runtime.shutdown)
|
||||
|
||||
app = FastAPI(telemetry={"tracing": False, "metrics": False, "logs": False, "operation_spans": False}, redirect_slashes=False, docs_url=None, redoc_url=None, openapi_url=None, lifespan=lifespan)
|
||||
app.state.store = store
|
||||
|
||||
def error_response(request, error):
|
||||
request_id = request.state.request_id
|
||||
headers = dict(error.headers)
|
||||
if error.status == 401:
|
||||
headers["WWW-Authenticate"] = (
|
||||
'Basic realm="messenger", charset="UTF-8"' if request.url.path == SESSION_PATH
|
||||
else 'Bearer realm="messenger"'
|
||||
)
|
||||
return JSONResponse(
|
||||
status_code=error.status, headers=headers,
|
||||
content={"error": {"code": error.code, "message": error.message, "request_id": request_id}},
|
||||
)
|
||||
|
||||
@app.middleware("http")
|
||||
async def request_context(request, call_next):
|
||||
request.state.request_id = str(uuid4())
|
||||
route = telemetry.route_template(app, request.scope)
|
||||
method = request.method if request.method in {"GET", "POST", "DELETE", "PUT", "PATCH", "HEAD", "OPTIONS"} else "OTHER"
|
||||
started = time.monotonic()
|
||||
with runtime.tracer.start_as_current_span(method + " " + route, kind=trace.SpanKind.SERVER,
|
||||
attributes={"http.request.method": method, "http.route": route,
|
||||
"messenger.request_id": request.state.request_id},
|
||||
record_exception=False, set_status_on_exception=False) as span:
|
||||
try:
|
||||
path = request.url.path
|
||||
if path.startswith("/api/v1/"):
|
||||
bao.ready()
|
||||
registration = path == "/api/v1/users" and request.method == "POST"
|
||||
login = path == SESSION_PATH and request.method == "POST"
|
||||
if login:
|
||||
request.state.credentials = basic_credentials(request.headers.get("Authorization"))
|
||||
async for chunk in request.stream():
|
||||
if chunk:
|
||||
raise invalid("Вход не принимает тело запроса")
|
||||
elif path.startswith("/api/v1/") and not registration:
|
||||
token = bearer_token(request.headers.get("Authorization"))
|
||||
request.state.user_id = await run_in_threadpool(store.authenticate, token)
|
||||
request.state.token = token
|
||||
upload = re.fullmatch(r"/api/v1/chats/[^/]+/attachments", path) is not None
|
||||
if request.method == "POST" and path.startswith("/api/v1/") and not login and not upload:
|
||||
media_type = request.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
|
||||
if media_type != "application/json":
|
||||
raise ApiError(415, "unsupported_media_type", "Нужен application/json")
|
||||
try:
|
||||
payload = bytearray()
|
||||
async for chunk in request.stream():
|
||||
payload.extend(chunk)
|
||||
if len(payload) > 65536:
|
||||
raise ApiError(413, "payload_too_large", "JSON больше 64 KiB")
|
||||
request._body = bytes(payload)
|
||||
request._body.decode("utf-8")
|
||||
except UnicodeDecodeError:
|
||||
raise invalid("JSON должен быть в UTF-8") from None
|
||||
response = await call_next(request)
|
||||
except ApiError as error:
|
||||
response = error_response(request, error)
|
||||
except Exception as error:
|
||||
telemetry.event("http.internal_error", logging.ERROR, error_type=type(error).__name__)
|
||||
response = error_response(request, ApiError(500, "internal_error", "Внутренняя ошибка"))
|
||||
response.headers["X-Instance-Id"] = instance_id
|
||||
response.headers["X-Request-Id"] = request.state.request_id
|
||||
duration = time.monotonic() - started
|
||||
attributes = {"method": method, "route": route, "status_class": str(response.status_code // 100) + "xx"}
|
||||
runtime.http_count.add(1, attributes)
|
||||
runtime.http_duration.record(duration, attributes)
|
||||
span.set_attribute("http.response.status_code", response.status_code)
|
||||
if response.status_code >= 500:
|
||||
span.set_status(trace.StatusCode.ERROR)
|
||||
telemetry.event("http.completed", request_id=request.state.request_id, method=method, route=route,
|
||||
status_code=response.status_code, duration_seconds=round(duration, 6))
|
||||
return response
|
||||
|
||||
@app.exception_handler(ApiError)
|
||||
async def api_error(request, error):
|
||||
return error_response(request, error)
|
||||
|
||||
@app.exception_handler(RequestValidationError)
|
||||
async def validation_error(request, error):
|
||||
return error_response(request, invalid("Неверные поля запроса"))
|
||||
|
||||
@app.exception_handler(HTTPException)
|
||||
async def http_error(request, error):
|
||||
code = "not_found" if error.status_code == 404 else "invalid_request"
|
||||
return error_response(request, ApiError(error.status_code, code, "Неверный запрос"))
|
||||
|
||||
@app.get("/health/live")
|
||||
def live():
|
||||
return {"status": "ok"}
|
||||
|
||||
@app.get("/health/ready")
|
||||
def ready():
|
||||
result = store.ready()
|
||||
objects.ready()
|
||||
broker.ready()
|
||||
return result
|
||||
|
||||
@app.post("/api/v1/users", status_code=201)
|
||||
def create_user(body: CreateUser):
|
||||
return store.create_user(body)
|
||||
|
||||
@app.post(SESSION_PATH, status_code=201)
|
||||
def login(request: Request):
|
||||
return store.create_session(*request.state.credentials)
|
||||
|
||||
@app.delete(SESSION_PATH + "/current", status_code=204)
|
||||
def logout(request: Request):
|
||||
store.logout(request.state.token)
|
||||
return Response(status_code=204)
|
||||
|
||||
@app.get("/api/v1/users/me")
|
||||
def me(request: Request):
|
||||
return store.user(request.state.user_id)
|
||||
|
||||
@app.post("/api/v1/chats", status_code=201)
|
||||
def create_chat(body: CreateChat, request: Request):
|
||||
return store.create_chat(request.state.user_id, body)
|
||||
|
||||
@app.get("/api/v1/chats")
|
||||
def list_chats(request: Request):
|
||||
return store.list_chats(request.state.user_id, *page_args(request))
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}")
|
||||
def chat(chat_id: str, request: Request):
|
||||
return store.chat(request.state.user_id, uuid_value(chat_id))
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/messages", status_code=201)
|
||||
def create_message(chat_id: str, body: CreateMessage, request: Request):
|
||||
key = request.headers.get("Idempotency-Key", "")
|
||||
if re.fullmatch(r"[A-Za-z0-9._:-]{1,128}", key) is None:
|
||||
raise invalid("Неверный Idempotency-Key")
|
||||
return store.create_message(request.state.user_id, uuid_value(chat_id), body, key)
|
||||
|
||||
@app.get("/api/v1/chats/{chat_id}/messages")
|
||||
def messages(chat_id: str, request: Request):
|
||||
return store.list_messages(request.state.user_id, uuid_value(chat_id), *page_args(request))
|
||||
|
||||
@app.post("/api/v1/chats/{chat_id}/attachments", status_code=202)
|
||||
async def upload(chat_id: str, filename: str, request: Request):
|
||||
return await attachments.receive(request, uuid_value(chat_id), filename)
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}")
|
||||
def attachment(attachment_id: str, request: Request):
|
||||
return attachments.get(request.state.user_id, uuid_value(attachment_id))
|
||||
|
||||
@app.get("/api/v1/attachments/{attachment_id}/content")
|
||||
def download(attachment_id: str, request: Request, variant: Literal["original", "thumbnail", "crop", "optimized"] = "original"):
|
||||
row = attachments.content(request.state.user_id, uuid_value(attachment_id), variant)
|
||||
body = objects.content(row["object_key"])
|
||||
|
||||
def chunks():
|
||||
try:
|
||||
while data := body.read(65536):
|
||||
yield data
|
||||
finally:
|
||||
body.close()
|
||||
|
||||
return StreamingResponse(
|
||||
chunks(), media_type=row["content_type"], background=BackgroundTask(body.close),
|
||||
headers={"Content-Length": str(row["size_bytes"]), "X-Content-Type-Options": "nosniff",
|
||||
"Content-Disposition": "attachment; filename*=UTF-8''" + quote(row["filename"], safe="")},
|
||||
)
|
||||
|
||||
return app
|
||||
@@ -0,0 +1,164 @@
|
||||
import asyncio
|
||||
import hashlib
|
||||
import tempfile
|
||||
import unicodedata
|
||||
import warnings
|
||||
from uuid import uuid4
|
||||
|
||||
import anyio
|
||||
from PIL import Image, UnidentifiedImageError
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
from starlette.requests import ClientDisconnect
|
||||
|
||||
from .errors import ApiError, invalid, not_found
|
||||
from .storage import serialize
|
||||
from .broker import envelope, publish
|
||||
from .telemetry import event
|
||||
|
||||
|
||||
MAX_BYTES = 10485760
|
||||
MAX_PIXELS = 40000000
|
||||
Image.MAX_IMAGE_PIXELS = MAX_PIXELS
|
||||
FIELDS = "id,chat_id,owner_id,filename,content_type,size_bytes,sha256,status,error_code,created_at,updated_at"
|
||||
|
||||
|
||||
def public(row):
|
||||
return {**serialize(row), "variants": []}
|
||||
|
||||
|
||||
def filename_value(value):
|
||||
if not 1 <= len(value) <= 255 or not value.strip():
|
||||
raise invalid("Неверное имя файла")
|
||||
if any(c in "/\\" or unicodedata.category(c) == "Cc" for c in value):
|
||||
raise invalid("Неверное имя файла")
|
||||
try:
|
||||
value.encode("utf-8")
|
||||
except UnicodeError:
|
||||
raise invalid("Неверное имя файла") from None
|
||||
return value
|
||||
|
||||
|
||||
def validate_image(source, media_type):
|
||||
try:
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("error", Image.DecompressionBombWarning)
|
||||
source.seek(0)
|
||||
with Image.open(source, formats=["PNG", "JPEG"]) as image:
|
||||
if image.width * image.height > MAX_PIXELS:
|
||||
raise ApiError(413, "payload_too_large", "Слишком много пикселей")
|
||||
actual = {"PNG": "image/png", "JPEG": "image/jpeg"}[image.format]
|
||||
if actual != media_type:
|
||||
raise ApiError(415, "unsupported_media_type", "Формат не совпадает с Content-Type")
|
||||
image.verify()
|
||||
source.seek(0)
|
||||
with Image.open(source, formats=["PNG", "JPEG"]) as image:
|
||||
image.load()
|
||||
except (Image.DecompressionBombWarning, Image.DecompressionBombError):
|
||||
raise ApiError(413, "payload_too_large", "Слишком много пикселей") from None
|
||||
except (UnidentifiedImageError, OSError, ValueError, SyntaxError):
|
||||
raise ApiError(415, "unsupported_media_type", "Повреждённое изображение") from None
|
||||
|
||||
|
||||
class Attachments:
|
||||
def __init__(self, store, objects):
|
||||
self.store = store
|
||||
self.objects = objects
|
||||
self.slots = asyncio.Semaphore(2)
|
||||
|
||||
async def receive(self, request, chat_id, filename):
|
||||
user_id = request.state.user_id
|
||||
await run_in_threadpool(self.store.chat, user_id, chat_id)
|
||||
filename = filename_value(filename)
|
||||
media_type = request.headers.get("Content-Type", "").split(";", 1)[0].strip().lower()
|
||||
if media_type not in ("image/png", "image/jpeg"):
|
||||
raise ApiError(415, "unsupported_media_type", "Нужен PNG или JPEG")
|
||||
declared = request.headers.get("Content-Length")
|
||||
if declared is not None:
|
||||
if not declared.isascii() or not declared.isdecimal() or len(declared) > 18:
|
||||
raise invalid("Неверный Content-Length")
|
||||
if int(declared) > MAX_BYTES:
|
||||
raise ApiError(413, "payload_too_large", "Файл больше 10 MiB")
|
||||
try:
|
||||
await asyncio.wait_for(self.slots.acquire(), timeout=15)
|
||||
except TimeoutError:
|
||||
raise ApiError(429, "rate_limited", "Загрузки заняты", {"Retry-After": "1"}) from None
|
||||
try:
|
||||
with tempfile.TemporaryFile(mode="w+b") as source:
|
||||
size, checksum = 0, hashlib.sha256()
|
||||
try:
|
||||
with anyio.fail_after(15):
|
||||
async for chunk in request.stream():
|
||||
size += len(chunk)
|
||||
if size > MAX_BYTES:
|
||||
raise ApiError(413, "payload_too_large", "Файл больше 10 MiB")
|
||||
checksum.update(chunk)
|
||||
await run_in_threadpool(source.write, chunk)
|
||||
except (TimeoutError, ClientDisconnect):
|
||||
raise invalid("Загрузка прервана или слишком медленная") from None
|
||||
await run_in_threadpool(validate_image, source, media_type)
|
||||
return await run_in_threadpool(
|
||||
self.publish, user_id, chat_id, filename, media_type, size, checksum.hexdigest(), source,
|
||||
)
|
||||
finally:
|
||||
self.slots.release()
|
||||
|
||||
def publish(self, user_id, chat_id, filename, media_type, size, checksum, source):
|
||||
attachment_id, job_id = uuid4(), uuid4()
|
||||
stage = "staging/" + attachment_id.hex
|
||||
key = "originals/" + str(attachment_id)
|
||||
with self.store.connection() as connection:
|
||||
self.store.require_chat(connection, user_id, chat_id)
|
||||
connection.execute(
|
||||
"INSERT INTO upload_intents(id,chat_id,owner_id,object_key) VALUES (%s,%s,%s,%s)",
|
||||
(attachment_id, chat_id, user_id, stage),
|
||||
)
|
||||
with self.store.connection() as connection:
|
||||
connection.execute("SELECT id FROM upload_intents WHERE id=%s FOR UPDATE", (attachment_id,))
|
||||
self.objects.put(stage, source, size, media_type)
|
||||
row = connection.execute(
|
||||
"INSERT INTO attachments(id,chat_id,owner_id,filename,content_type,size_bytes,sha256,object_key,status) "
|
||||
"VALUES (%s,%s,%s,%s,%s,%s,%s,%s,'queued') RETURNING " + FIELDS,
|
||||
(attachment_id, chat_id, user_id, filename, media_type, size, checksum, key),
|
||||
).fetchone()
|
||||
job = connection.execute(
|
||||
"INSERT INTO attachment_jobs(id,attachment_id,staging_key) VALUES (%s,%s,%s) RETURNING *",
|
||||
(job_id, attachment_id, stage),
|
||||
).fetchone()
|
||||
connection.execute("DELETE FROM upload_intents WHERE id=%s", (attachment_id,))
|
||||
publish(envelope(job))
|
||||
with self.store.connection() as connection:
|
||||
connection.execute("UPDATE attachment_jobs SET published_at=clock_timestamp() WHERE id=%s", (job_id,))
|
||||
event("job.accepted", job_id=str(job_id))
|
||||
return public(row)
|
||||
|
||||
def get(self, user_id, attachment_id, internal=False):
|
||||
with self.store.connection() as connection:
|
||||
row = connection.execute(
|
||||
"SELECT " + FIELDS + (",object_key" if internal else "") + " FROM attachments a "
|
||||
"WHERE a.id=%s AND EXISTS (SELECT 1 FROM chat_members m "
|
||||
"WHERE m.chat_id=a.chat_id AND m.user_id=%s)", (attachment_id, user_id),
|
||||
).fetchone()
|
||||
if not row:
|
||||
raise not_found()
|
||||
variants = connection.execute(
|
||||
"SELECT name,content_type,width,height,size_bytes,sha256 FROM attachment_variants "
|
||||
"WHERE attachment_id=%s ORDER BY name", (attachment_id,),
|
||||
).fetchall() if row['status'] == 'ready' else []
|
||||
if internal:
|
||||
return row
|
||||
return {**public(row), "variants": serialize(variants)}
|
||||
|
||||
def content(self, user_id, attachment_id, variant):
|
||||
row = self.get(user_id, attachment_id, internal=True)
|
||||
if row['status'] != 'ready':
|
||||
raise ApiError(409, 'conflict', 'Файл ещё не готов')
|
||||
if variant == 'original':
|
||||
return row
|
||||
with self.store.connection() as connection:
|
||||
found = connection.execute(
|
||||
"SELECT object_key,content_type,size_bytes FROM attachment_variants "
|
||||
"WHERE attachment_id=%s AND name=%s", (attachment_id, variant),
|
||||
).fetchone()
|
||||
if not found:
|
||||
raise not_found()
|
||||
return {**row, **found}
|
||||
+81
@@ -0,0 +1,81 @@
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import ssl
|
||||
import threading
|
||||
import time
|
||||
from urllib.request import build_opener, HTTPSHandler, ProxyHandler, Request
|
||||
|
||||
from .errors import ApiError
|
||||
|
||||
_deadline = 0
|
||||
_enabled = False
|
||||
_token = None
|
||||
_lock = threading.Lock()
|
||||
|
||||
|
||||
def request(path, data=None, token=None):
|
||||
context = ssl.create_default_context(cafile='/run/pki/ca.crt')
|
||||
context.load_cert_chain('/run/identity/client.crt', '/run/identity/client.key')
|
||||
opener = build_opener(ProxyHandler({}), HTTPSHandler(context=context))
|
||||
headers = {'Content-Type': 'application/json'}
|
||||
if token:
|
||||
headers['X-Vault-Token'] = token
|
||||
raw = json.dumps(data).encode() if data is not None else None
|
||||
with opener.open(Request('https://openbao:8200/v1/' + path, data=raw, headers=headers), timeout=3) as response:
|
||||
return json.load(response)
|
||||
|
||||
|
||||
def refresh():
|
||||
global _deadline, _token
|
||||
identity = os.environ['SERVICE_IDENTITY']
|
||||
issued = time.monotonic()
|
||||
result = request('auth/cert/login', {'name': identity})['auth']
|
||||
token = result['client_token']
|
||||
bundle = request('secret/data/' + os.environ['SECRET_ROLE'], token=token)['data']['data']
|
||||
deadline = issued + result['lease_duration']
|
||||
if time.monotonic() >= deadline:
|
||||
raise ApiError(503, 'unavailable', 'Secrets lease expired')
|
||||
for name, value in bundle.items():
|
||||
path = Path('/run/runtime') / name
|
||||
temporary = path.with_suffix('.tmp')
|
||||
temporary.write_text(value, encoding='utf-8', newline='\n')
|
||||
temporary.chmod(0o600)
|
||||
temporary.replace(path)
|
||||
with _lock:
|
||||
_token = token
|
||||
_deadline = deadline
|
||||
|
||||
|
||||
def renew():
|
||||
global _deadline
|
||||
while True:
|
||||
time.sleep(1)
|
||||
try:
|
||||
with _lock:
|
||||
remaining, token = _deadline - time.monotonic(), _token
|
||||
if remaining > 300:
|
||||
continue
|
||||
try:
|
||||
issued = time.monotonic()
|
||||
auth = request('auth/token/renew-self', {}, token)['auth']
|
||||
with _lock:
|
||||
_deadline = issued + auth['lease_duration']
|
||||
except Exception:
|
||||
refresh()
|
||||
except Exception:
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
def initialize():
|
||||
global _enabled
|
||||
if not os.environ.get('SERVICE_IDENTITY') or _enabled:
|
||||
return
|
||||
refresh()
|
||||
_enabled = True
|
||||
threading.Thread(target=renew, name='bao-renew', daemon=True).start()
|
||||
|
||||
|
||||
def ready():
|
||||
if _enabled and time.monotonic() >= _deadline:
|
||||
raise ApiError(503, 'unavailable', 'Secrets temporarily unavailable')
|
||||
@@ -0,0 +1,53 @@
|
||||
import logging
|
||||
import time
|
||||
from io import BytesIO
|
||||
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from .objects import Objects
|
||||
from .errors import ApiError
|
||||
|
||||
|
||||
def main():
|
||||
admin, app = Objects(admin=True), Objects()
|
||||
try:
|
||||
deadline = time.monotonic() + 90
|
||||
while True:
|
||||
try:
|
||||
admin.client.list_buckets()
|
||||
break
|
||||
except (ClientError, BotoCoreError):
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError("S3 startup timeout") from None
|
||||
time.sleep(1)
|
||||
try:
|
||||
admin.client.head_bucket(Bucket=admin.bucket)
|
||||
except ClientError as error:
|
||||
if error.response["ResponseMetadata"]["HTTPStatusCode"] != 404:
|
||||
raise RuntimeError("Bucket is not accessible") from None
|
||||
admin.client.create_bucket(Bucket=admin.bucket)
|
||||
acl = admin.client.get_bucket_acl(Bucket=admin.bucket)
|
||||
if any("URI" in grant["Grantee"] for grant in acl["Grants"]):
|
||||
raise RuntimeError("Bucket must be private")
|
||||
while True:
|
||||
try:
|
||||
probe = b"messenger-ready"
|
||||
admin.put("system/readiness", BytesIO(probe), len(probe), "application/octet-stream")
|
||||
app.ready()
|
||||
break
|
||||
except ApiError:
|
||||
if time.monotonic() >= deadline:
|
||||
raise RuntimeError("S3 object path is not ready") from None
|
||||
time.sleep(0.5)
|
||||
print("PASS: private bucket ready; application credentials work", flush=True)
|
||||
finally:
|
||||
admin.close()
|
||||
app.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Exception as error:
|
||||
logging.error("S3 bootstrap failed: %s", type(error).__name__)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,66 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import ssl
|
||||
|
||||
import pika
|
||||
|
||||
from .config import secret
|
||||
from .errors import ApiError
|
||||
|
||||
|
||||
QUEUE = 'attachment.process.v1'
|
||||
|
||||
|
||||
def connect():
|
||||
parameters = pika.URLParameters(secret('BROKER_URL_FILE'))
|
||||
parameters.ssl_options = pika.SSLOptions(ssl.create_default_context(cafile=os.environ['TLS_CA_FILE']), 'broker')
|
||||
parameters.heartbeat = 10
|
||||
parameters.socket_timeout = 2
|
||||
parameters.stack_timeout = 8
|
||||
parameters.blocked_connection_timeout = 5
|
||||
parameters.connection_attempts = 1
|
||||
logging.getLogger('pika').setLevel(logging.CRITICAL)
|
||||
return pika.BlockingConnection(parameters)
|
||||
|
||||
|
||||
def publish(job):
|
||||
connection = None
|
||||
try:
|
||||
connection = connect()
|
||||
channel = connection.channel()
|
||||
channel.queue_declare(queue=QUEUE, passive=True)
|
||||
channel.confirm_delivery()
|
||||
channel.basic_publish(exchange='attachment.jobs', routing_key=QUEUE, mandatory=True,
|
||||
body=json.dumps(job, separators=(',', ':')).encode(),
|
||||
properties=pika.BasicProperties(delivery_mode=2, content_type='application/json',
|
||||
message_id=job['job_id']))
|
||||
except (pika.exceptions.AMQPError, OSError):
|
||||
raise ApiError(503, 'unavailable', 'Очередь недоступна') from None
|
||||
finally:
|
||||
if connection and connection.is_open:
|
||||
try:
|
||||
connection.close()
|
||||
except (pika.exceptions.AMQPError, OSError):
|
||||
pass
|
||||
|
||||
|
||||
def ready():
|
||||
connection = None
|
||||
try:
|
||||
connection = connect()
|
||||
connection.channel().queue_declare(queue=QUEUE, passive=True)
|
||||
except (pika.exceptions.AMQPError, OSError):
|
||||
raise ApiError(503, 'unavailable', 'Очередь недоступна') from None
|
||||
finally:
|
||||
if connection and connection.is_open:
|
||||
try:
|
||||
connection.close()
|
||||
except (pika.exceptions.AMQPError, OSError):
|
||||
pass
|
||||
|
||||
|
||||
def envelope(row, attempt=1):
|
||||
return {'schema_version': 1, 'job_id': str(row['id']), 'type': QUEUE,
|
||||
'attachment_id': str(row['attachment_id']), 'pipeline_version': 1,
|
||||
'attempt': attempt, 'created_at': row['created_at'].isoformat().replace('+00:00', 'Z')}
|
||||
@@ -0,0 +1,92 @@
|
||||
import argparse
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
|
||||
from . import bao
|
||||
from .errors import ApiError
|
||||
from .objects import Objects
|
||||
from .storage import PostgresStore
|
||||
|
||||
|
||||
def clean_once(store, objects, grace=600):
|
||||
result = {"deleted": 0, "protected": 0}
|
||||
for _ in range(100):
|
||||
with store.connection() as connection:
|
||||
intent = connection.execute(
|
||||
"SELECT id,object_key FROM upload_intents "
|
||||
"WHERE created_at < clock_timestamp() - %s * INTERVAL '1 second' "
|
||||
"ORDER BY created_at,id LIMIT 1 FOR UPDATE SKIP LOCKED", (grace,),
|
||||
).fetchone()
|
||||
if not intent:
|
||||
break
|
||||
ready = connection.execute(
|
||||
"SELECT id FROM attachments WHERE object_key=%s", (intent["object_key"],),
|
||||
).fetchone()
|
||||
if ready:
|
||||
result["protected"] += 1
|
||||
else:
|
||||
objects.delete(intent["object_key"])
|
||||
result["deleted"] += 1
|
||||
connection.execute("DELETE FROM upload_intents WHERE id=%s", (intent["id"],))
|
||||
with store.connection() as connection:
|
||||
jobs = connection.execute(
|
||||
"SELECT j.id,j.attachment_id,j.staging_key,a.status,a.staging_deleted FROM attachment_jobs j "
|
||||
"JOIN attachments a ON a.id=j.attachment_id WHERE NOT a.staging_deleted AND "
|
||||
"(a.status='ready' OR (a.status='failed' AND a.updated_at < clock_timestamp() - "
|
||||
"%s * INTERVAL '1 second') OR (a.status='queued' AND j.published_at IS NULL AND "
|
||||
"j.created_at < clock_timestamp() - %s * INTERVAL '1 second')) LIMIT 100",
|
||||
(int(os.environ.get('STAGING_RETENTION_SECONDS', '86400')),)*2,
|
||||
).fetchall()
|
||||
for job in jobs:
|
||||
lock = int.from_bytes(job['id'].bytes[:8], 'big', signed=True)
|
||||
if not connection.execute('SELECT pg_try_advisory_xact_lock(%s) AS locked', (lock,)).fetchone()['locked']:
|
||||
continue
|
||||
current = connection.execute('SELECT status FROM attachments WHERE id=%s FOR UPDATE',
|
||||
(job['attachment_id'],)).fetchone()
|
||||
if current['status'] == 'processing':
|
||||
continue
|
||||
if current['status'] == 'queued':
|
||||
connection.execute("UPDATE attachments SET status='failed',error_code='dispatch_failed',"
|
||||
'updated_at=clock_timestamp() WHERE id=%s', (job['attachment_id'],))
|
||||
objects.delete(job['staging_key'])
|
||||
if current['status'] != 'ready':
|
||||
objects.delete('originals/' + str(job['attachment_id']))
|
||||
objects.delete('variants/' + str(job['attachment_id']) + '/v1/thumbnail.jpg')
|
||||
connection.execute('UPDATE attachments SET staging_deleted=true WHERE id=%s', (job['attachment_id'],))
|
||||
result['deleted'] += 1
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
bao.initialize()
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--once", action="store_true")
|
||||
args = parser.parse_args()
|
||||
store, objects = PostgresStore(), Objects()
|
||||
store.open()
|
||||
try:
|
||||
while True:
|
||||
try:
|
||||
bao.ready()
|
||||
result = clean_once(store, objects, int(os.environ.get("CLEANUP_GRACE_SECONDS", "600")))
|
||||
print(json.dumps(result), flush=True)
|
||||
except ApiError:
|
||||
if args.once:
|
||||
raise
|
||||
logging.warning("cleanup: storage unavailable, retry later")
|
||||
if args.once:
|
||||
return
|
||||
time.sleep(int(os.environ.get("CLEANUP_INTERVAL_SECONDS", "30")))
|
||||
finally:
|
||||
objects.close()
|
||||
store.close()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except Exception as error:
|
||||
logging.error("Cleanup failed: %s", type(error).__name__)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,23 @@
|
||||
import os
|
||||
from pathlib import Path
|
||||
|
||||
|
||||
def secret(name):
|
||||
value = Path(os.environ[name]).read_text(encoding="utf-8").strip()
|
||||
if not value:
|
||||
raise ValueError(f"Empty secret file: {name}")
|
||||
return value
|
||||
|
||||
|
||||
def session_ttl():
|
||||
value = int(os.environ.get("SESSION_TTL_SECONDS", "3600"))
|
||||
if not 1 <= value <= 86400:
|
||||
raise ValueError("SESSION_TTL_SECONDS must be between 1 and 86400")
|
||||
return value
|
||||
|
||||
|
||||
def idempotency_ttl():
|
||||
value = int(os.environ.get("IDEMPOTENCY_TTL_SECONDS", "86400"))
|
||||
if value < 86400:
|
||||
raise ValueError("IDEMPOTENCY_TTL_SECONDS must be at least 86400")
|
||||
return value
|
||||
@@ -0,0 +1,15 @@
|
||||
class ApiError(Exception):
|
||||
def __init__(self, status, code, message, headers=None):
|
||||
super().__init__(message)
|
||||
self.status = status
|
||||
self.code = code
|
||||
self.message = message
|
||||
self.headers = headers or {}
|
||||
|
||||
|
||||
def invalid(message="Неверный запрос"):
|
||||
return ApiError(400, "invalid_request", message)
|
||||
|
||||
|
||||
def not_found():
|
||||
return ApiError(404, "not_found", "Объект не найден")
|
||||
@@ -0,0 +1,50 @@
|
||||
import hashlib
|
||||
import logging
|
||||
from pathlib import Path
|
||||
|
||||
import psycopg
|
||||
|
||||
from .config import secret
|
||||
|
||||
|
||||
def migrate():
|
||||
files = sorted((Path(__file__).resolve().parents[1] / "migrations").glob("*.sql"))
|
||||
if not files:
|
||||
raise RuntimeError("No migrations found")
|
||||
with psycopg.connect(secret("DATABASE_URL_FILE"), connect_timeout=5) as connection:
|
||||
with connection.transaction():
|
||||
connection.execute("SELECT pg_advisory_xact_lock(230402)")
|
||||
connection.execute("""
|
||||
CREATE TABLE IF NOT EXISTS schema_migrations (
|
||||
version text PRIMARY KEY,
|
||||
checksum char(64) NOT NULL,
|
||||
applied_at timestamptz NOT NULL DEFAULT clock_timestamp()
|
||||
)
|
||||
""")
|
||||
for file in files:
|
||||
content = file.read_text(encoding="utf-8")
|
||||
checksum = hashlib.sha256(content.encode("utf-8")).hexdigest()
|
||||
with connection.transaction():
|
||||
connection.execute("SELECT pg_advisory_xact_lock(230402)")
|
||||
old = connection.execute(
|
||||
"SELECT checksum FROM schema_migrations WHERE version = %s", (file.name,)
|
||||
).fetchone()
|
||||
if old:
|
||||
if old[0] != checksum:
|
||||
raise RuntimeError("Applied migration was changed")
|
||||
print("Already applied: " + file.name, flush=True)
|
||||
continue
|
||||
connection.execute(content)
|
||||
connection.execute(
|
||||
"INSERT INTO schema_migrations(version, checksum) VALUES (%s, %s)",
|
||||
(file.name, checksum),
|
||||
)
|
||||
print("Applied: " + file.name, flush=True)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
migrate()
|
||||
except Exception as error:
|
||||
logging.error("Migration failed: %s", type(error).__name__)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,61 @@
|
||||
import re
|
||||
from typing import Annotated
|
||||
from uuid import UUID
|
||||
|
||||
from pydantic import AfterValidator, BaseModel, ConfigDict, Field, StringConstraints, field_validator, model_validator
|
||||
|
||||
|
||||
def nonblank(value: str) -> str:
|
||||
if not value.strip() or "\x00" in value:
|
||||
raise ValueError("Пустая строка или NUL")
|
||||
value.encode("utf-8")
|
||||
return value
|
||||
|
||||
|
||||
Name = Annotated[str, StringConstraints(min_length=1, max_length=100), AfterValidator(nonblank)]
|
||||
Text = Annotated[str, StringConstraints(min_length=1, max_length=4000), AfterValidator(nonblank)]
|
||||
Password = Annotated[str, StringConstraints(min_length=12, max_length=128), AfterValidator(nonblank)]
|
||||
UserId = Annotated[UUID, Field(strict=False)]
|
||||
|
||||
|
||||
class RequestBody(BaseModel):
|
||||
model_config = ConfigDict(extra="forbid", strict=True)
|
||||
|
||||
|
||||
class CreateUser(RequestBody):
|
||||
username: str
|
||||
display_name: Name
|
||||
password: Password = Field(repr=False)
|
||||
|
||||
@field_validator("username")
|
||||
@classmethod
|
||||
def check_username(cls, value):
|
||||
if re.fullmatch(r"[a-z0-9_]{3,32}", value) is None:
|
||||
raise ValueError("Неверный username")
|
||||
return value
|
||||
|
||||
|
||||
class CreateChat(RequestBody):
|
||||
title: Name
|
||||
member_ids: list[UserId] = Field(min_length=1, max_length=100)
|
||||
|
||||
@field_validator("member_ids")
|
||||
@classmethod
|
||||
def unique_members(cls, value):
|
||||
if len(set(value)) != len(value):
|
||||
raise ValueError("Повтор участника")
|
||||
return value
|
||||
|
||||
|
||||
class CreateMessage(RequestBody):
|
||||
text: str = Field(max_length=4000)
|
||||
attachment_ids: list[UserId] = Field(default_factory=list, max_length=10)
|
||||
|
||||
@model_validator(mode="after")
|
||||
def check_message(self):
|
||||
if "\x00" in self.text or (not self.text.strip() and not self.attachment_ids):
|
||||
raise ValueError("Нужен текст или вложение")
|
||||
self.text.encode("utf-8")
|
||||
if len(set(self.attachment_ids)) != len(self.attachment_ids):
|
||||
raise ValueError("Повтор вложения")
|
||||
return self
|
||||
@@ -0,0 +1,57 @@
|
||||
import os
|
||||
|
||||
import boto3
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from .config import secret
|
||||
from .errors import ApiError
|
||||
|
||||
|
||||
class Objects:
|
||||
def __init__(self, admin=False):
|
||||
prefix = "S3_ADMIN_" if admin else "S3_"
|
||||
self.bucket = os.environ.get("S3_BUCKET", "messenger-attachments")
|
||||
self.client = boto3.client(
|
||||
"s3", endpoint_url=os.environ.get("S3_ENDPOINT", "http://s3:9000"),
|
||||
verify=os.environ.get("TLS_CA_FILE"),
|
||||
region_name=os.environ.get("S3_REGION", "us-east-1"),
|
||||
aws_access_key_id=secret(prefix + "ACCESS_KEY_ID_FILE"),
|
||||
aws_secret_access_key=secret(prefix + "SECRET_ACCESS_KEY_FILE"),
|
||||
config=Config(
|
||||
signature_version="s3v4", connect_timeout=2, read_timeout=5,
|
||||
max_pool_connections=8, retries={"total_max_attempts": 1}, proxies={},
|
||||
s3={"addressing_style": "path"},
|
||||
request_checksum_calculation="when_required",
|
||||
response_checksum_validation="when_required",
|
||||
),
|
||||
)
|
||||
|
||||
def call(self, operation, **values):
|
||||
try:
|
||||
return getattr(self.client, operation)(Bucket=self.bucket, **values)
|
||||
except (BotoCoreError, ClientError):
|
||||
raise ApiError(503, "unavailable", "Файловое хранилище недоступно") from None
|
||||
|
||||
def ready(self):
|
||||
body = self.content("system/readiness")
|
||||
try:
|
||||
if body.read(32) != b"messenger-ready":
|
||||
raise ApiError(503, "unavailable", "Файловое хранилище не готово")
|
||||
except BotoCoreError:
|
||||
raise ApiError(503, "unavailable", "Файловое хранилище недоступно") from None
|
||||
finally:
|
||||
body.close()
|
||||
|
||||
def put(self, key, source, size, content_type):
|
||||
source.seek(0)
|
||||
self.call("put_object", Key=key, Body=source, ContentLength=size, ContentType=content_type)
|
||||
|
||||
def delete(self, key):
|
||||
self.call("delete_object", Key=key)
|
||||
|
||||
def content(self, key):
|
||||
return self.call("get_object", Key=key)["Body"]
|
||||
|
||||
def close(self):
|
||||
self.client.close()
|
||||
@@ -0,0 +1,44 @@
|
||||
import base64
|
||||
import hashlib
|
||||
import hmac
|
||||
import json
|
||||
from datetime import datetime, timezone
|
||||
from uuid import UUID
|
||||
|
||||
from .errors import invalid
|
||||
|
||||
|
||||
class Pagination:
|
||||
def __init__(self, secret):
|
||||
self.secret = secret
|
||||
|
||||
def encode(self, scope, item):
|
||||
data = json.dumps([1, scope, item["created_at"], item["id"]], separators=(",", ":"))
|
||||
payload = base64.urlsafe_b64encode(data.encode()).rstrip(b"=").decode()
|
||||
signature = hmac.new(self.secret, payload.encode(), hashlib.sha256).hexdigest()
|
||||
return payload + "." + signature
|
||||
|
||||
def decode(self, scope, cursor):
|
||||
try:
|
||||
if not isinstance(cursor, str) or not cursor or len(cursor) > 2048:
|
||||
raise ValueError()
|
||||
payload, signature = cursor.split(".")
|
||||
expected = hmac.new(self.secret, payload.encode("ascii"), hashlib.sha256).hexdigest()
|
||||
if not hmac.compare_digest(signature, expected):
|
||||
raise ValueError()
|
||||
data = json.loads(base64.b64decode(payload + "=" * (-len(payload) % 4), altchars=b"-_", validate=True))
|
||||
if not isinstance(data, list) or len(data) != 4 or data[:2] != [1, scope]:
|
||||
raise ValueError()
|
||||
if not isinstance(data[2], str) or not data[2].endswith("Z"):
|
||||
raise ValueError()
|
||||
created_at = datetime.fromisoformat(data[2].replace("Z", "+00:00"))
|
||||
if created_at.utcoffset() != timezone.utc.utcoffset(created_at):
|
||||
raise ValueError()
|
||||
return created_at, UUID(data[3])
|
||||
except (ValueError, TypeError, UnicodeError, KeyError, OverflowError):
|
||||
raise invalid("Неверный cursor") from None
|
||||
|
||||
def page(self, rows, scope, limit):
|
||||
items = rows[:limit]
|
||||
cursor = self.encode(scope, items[-1]) if len(rows) > limit else None
|
||||
return {"items": items, "next_cursor": cursor}
|
||||
@@ -0,0 +1,66 @@
|
||||
import hashlib
|
||||
import io
|
||||
import json
|
||||
import sys
|
||||
import tempfile
|
||||
|
||||
from PIL import Image, ImageOps
|
||||
|
||||
from .attachments import validate_image
|
||||
from .errors import ApiError
|
||||
from .objects import Objects
|
||||
|
||||
|
||||
def process(job):
|
||||
objects = Objects()
|
||||
try:
|
||||
with tempfile.TemporaryFile(mode='w+b') as original:
|
||||
body = objects.content(job['staging_key'])
|
||||
checksum, size = hashlib.sha256(), 0
|
||||
try:
|
||||
while chunk := body.read(65536):
|
||||
size += len(chunk)
|
||||
if size > 10485760:
|
||||
raise ValueError('size')
|
||||
checksum.update(chunk)
|
||||
original.write(chunk)
|
||||
finally:
|
||||
body.close()
|
||||
if size != job['size_bytes'] or checksum.hexdigest() != job['sha256']:
|
||||
raise ValueError('checksum')
|
||||
validate_image(original, job['content_type'])
|
||||
original.seek(0)
|
||||
with Image.open(original) as image:
|
||||
ImageOps.exif_transpose(image, in_place=True)
|
||||
scale = min(1, 256 / image.width, 256 / image.height)
|
||||
width, height = max(1, int(image.width * scale)), max(1, int(image.height * scale))
|
||||
with image.resize((width, height), Image.Resampling.LANCZOS) as small:
|
||||
rgba = small.convert('RGBA')
|
||||
rgb = Image.new('RGB', small.size, 'white')
|
||||
try:
|
||||
rgb.paste(rgba, mask=rgba.getchannel('A'))
|
||||
output = io.BytesIO()
|
||||
rgb.save(output, format='JPEG', quality=85)
|
||||
finally:
|
||||
rgba.close()
|
||||
rgb.close()
|
||||
thumb = output.getvalue()
|
||||
key = 'variants/' + job['attachment_id'] + '/v1/thumbnail.jpg'
|
||||
objects.put(job['object_key'], original, size, job['content_type'])
|
||||
objects.put(key, io.BytesIO(thumb), len(thumb), 'image/jpeg')
|
||||
return {'name': 'thumbnail', 'content_type': 'image/jpeg', 'width': width, 'height': height,
|
||||
'size_bytes': len(thumb), 'sha256': hashlib.sha256(thumb).hexdigest(), 'object_key': key}
|
||||
finally:
|
||||
objects.close()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
try:
|
||||
result = process(json.load(sys.stdin))
|
||||
print(json.dumps(result), flush=True)
|
||||
except (ValueError, OSError):
|
||||
sys.exit(43)
|
||||
except ApiError as error:
|
||||
sys.exit(43 if error.status in (400, 413, 415) else 1)
|
||||
except Exception:
|
||||
sys.exit(1)
|
||||
@@ -0,0 +1,74 @@
|
||||
from contextlib import contextmanager
|
||||
import base64
|
||||
import binascii
|
||||
import hashlib
|
||||
import re
|
||||
import secrets
|
||||
from threading import BoundedSemaphore
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
from argon2.exceptions import VerificationError
|
||||
from argon2.low_level import Type
|
||||
|
||||
from .errors import ApiError
|
||||
|
||||
HASHER = PasswordHasher(time_cost=2, memory_cost=19456, parallelism=1, type=Type.ID)
|
||||
HASH_SLOTS = BoundedSemaphore(2)
|
||||
DUMMY_HASH = HASHER.hash(secrets.token_urlsafe(32))
|
||||
|
||||
|
||||
def unauthorized():
|
||||
return ApiError(401, "unauthorized", "Неверные данные авторизации")
|
||||
|
||||
|
||||
@contextmanager
|
||||
def hash_slot():
|
||||
if not HASH_SLOTS.acquire(timeout=1):
|
||||
raise ApiError(429, 'rate_limited', 'Hashing busy', {'Retry-After': '1'})
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
HASH_SLOTS.release()
|
||||
|
||||
|
||||
def hash_password(password):
|
||||
with hash_slot():
|
||||
return HASHER.hash(password)
|
||||
|
||||
|
||||
def verify_password(password_hash, password):
|
||||
try:
|
||||
with hash_slot():
|
||||
return HASHER.verify(password_hash or DUMMY_HASH, password)
|
||||
except (VerificationError, ValueError):
|
||||
return False
|
||||
|
||||
|
||||
def basic_credentials(header):
|
||||
try:
|
||||
scheme, encoded = header.split(" ", 1)
|
||||
if scheme.lower() != "basic" or len(encoded) > 2048:
|
||||
raise ValueError()
|
||||
decoded = base64.b64decode(encoded, validate=True).decode("utf-8")
|
||||
username, separator, password = decoded.partition(":")
|
||||
if not separator or re.fullmatch(r"[a-z0-9_]{3,32}", username) is None:
|
||||
raise ValueError()
|
||||
if not 12 <= len(password) <= 128 or not password.strip() or "\x00" in password:
|
||||
raise ValueError()
|
||||
return username, password
|
||||
except (ValueError, UnicodeError, AttributeError, binascii.Error):
|
||||
raise unauthorized() from None
|
||||
|
||||
|
||||
def bearer_token(header):
|
||||
try:
|
||||
scheme, token = header.split(" ", 1)
|
||||
if scheme.lower() != "bearer" or not re.fullmatch(r"[A-Za-z0-9_-]{43}", token):
|
||||
raise ValueError()
|
||||
return token
|
||||
except (ValueError, TypeError, AttributeError):
|
||||
raise unauthorized() from None
|
||||
|
||||
|
||||
def token_hash(token):
|
||||
return hashlib.sha256(token.encode("ascii")).hexdigest()
|
||||
+246
@@ -0,0 +1,246 @@
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime
|
||||
import logging
|
||||
import hashlib
|
||||
import json
|
||||
import secrets
|
||||
from uuid import UUID, uuid4
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
from psycopg.types.json import Jsonb
|
||||
from psycopg_pool import ConnectionPool, PoolTimeout, TooManyRequests
|
||||
|
||||
from .config import idempotency_ttl, secret, session_ttl
|
||||
from .errors import ApiError, invalid, not_found
|
||||
from .telemetry import event
|
||||
from . import bao
|
||||
from .pagination import Pagination
|
||||
from .security import hash_password, token_hash, unauthorized, verify_password
|
||||
|
||||
|
||||
USER_FIELDS = "id, username, display_name, created_at"
|
||||
CHAT_FIELDS = """
|
||||
c.id, c.title, c.created_at,
|
||||
ARRAY(SELECT cm.user_id FROM chat_members cm WHERE cm.chat_id=c.id ORDER BY cm.user_id) AS member_ids
|
||||
"""
|
||||
|
||||
|
||||
def serialize(value):
|
||||
if isinstance(value, UUID):
|
||||
return str(value)
|
||||
if isinstance(value, datetime):
|
||||
return value.isoformat(timespec="microseconds").replace("+00:00", "Z")
|
||||
if isinstance(value, dict):
|
||||
return {key: serialize(item) for key, item in value.items()}
|
||||
if isinstance(value, list):
|
||||
return [serialize(item) for item in value]
|
||||
return value
|
||||
|
||||
|
||||
class PostgresStore:
|
||||
def __init__(self):
|
||||
logging.getLogger("psycopg.pool").setLevel(logging.CRITICAL)
|
||||
self.pool = ConnectionPool(
|
||||
secret("DATABASE_URL_FILE"), min_size=1, max_size=10, timeout=3, max_waiting=40,
|
||||
open=False, check=ConnectionPool.check_connection,
|
||||
kwargs={"row_factory": dict_row, "connect_timeout": 3,
|
||||
"options": "-c timezone=UTC -c statement_timeout=5000 -c lock_timeout=2000"},
|
||||
)
|
||||
self.pagination = Pagination(secret("CURSOR_SECRET_FILE").encode("ascii")) if "CURSOR_SECRET_FILE" in __import__("os").environ else None
|
||||
self.ttl = session_ttl()
|
||||
self.idempotency_ttl = idempotency_ttl()
|
||||
|
||||
def open(self):
|
||||
self.pool.open()
|
||||
|
||||
def close(self):
|
||||
self.pool.close()
|
||||
|
||||
@contextmanager
|
||||
def connection(self):
|
||||
bao.ready()
|
||||
try:
|
||||
with self.pool.connection() as connection:
|
||||
yield connection
|
||||
except (psycopg.OperationalError, psycopg.InterfaceError, PoolTimeout, TooManyRequests,
|
||||
psycopg.errors.QueryCanceled, psycopg.errors.LockNotAvailable):
|
||||
event("dependency.postgresql_unavailable", logging.ERROR)
|
||||
raise ApiError(503, "unavailable", "Хранилище временно недоступно") from None
|
||||
|
||||
def ready(self):
|
||||
try:
|
||||
with self.connection() as connection:
|
||||
row = connection.execute(
|
||||
"SELECT version FROM schema_migrations WHERE version=%s", ("004_jobs.sql",)
|
||||
).fetchone()
|
||||
if not row:
|
||||
raise ApiError(503, "unavailable", "Схема ещё не готова")
|
||||
except psycopg.errors.UndefinedTable:
|
||||
raise ApiError(503, "unavailable", "Схема ещё не готова") from None
|
||||
return {"status": "ok"}
|
||||
|
||||
def create_user(self, body):
|
||||
password_hash = hash_password(body.password)
|
||||
try:
|
||||
with self.connection() as connection:
|
||||
row = connection.execute(
|
||||
"INSERT INTO users(id,username,display_name,password_hash) VALUES (%s,%s,%s,%s) RETURNING "
|
||||
+ USER_FIELDS,
|
||||
(uuid4(), body.username, body.display_name, password_hash),
|
||||
).fetchone()
|
||||
return serialize(row)
|
||||
except psycopg.errors.UniqueViolation:
|
||||
raise ApiError(409, "conflict", "Username уже занят") from None
|
||||
|
||||
def create_session(self, username, password):
|
||||
with self.connection() as connection:
|
||||
row = connection.execute(
|
||||
"SELECT " + USER_FIELDS + ", password_hash FROM users WHERE username=%s", (username,)
|
||||
).fetchone()
|
||||
if not verify_password(row["password_hash"] if row else None, password) or row is None:
|
||||
raise unauthorized()
|
||||
token = secrets.token_urlsafe(32)
|
||||
with self.connection() as connection:
|
||||
session = connection.execute("""
|
||||
INSERT INTO sessions(token_hash,user_id,created_at,expires_at)
|
||||
VALUES (%s,%s,CURRENT_TIMESTAMP,CURRENT_TIMESTAMP + %s * INTERVAL '1 second')
|
||||
RETURNING expires_at
|
||||
""", (token_hash(token), row["id"], self.ttl)).fetchone()
|
||||
user = {key: value for key, value in row.items() if key != "password_hash"}
|
||||
return {"token": token, "token_type": "Bearer", "expires_at": serialize(session["expires_at"]),
|
||||
"user": serialize(user)}
|
||||
|
||||
def authenticate(self, token):
|
||||
with self.connection() as connection:
|
||||
row = connection.execute("""
|
||||
SELECT user_id FROM sessions
|
||||
WHERE token_hash=%s AND expires_at > CURRENT_TIMESTAMP
|
||||
""", (token_hash(token),)).fetchone()
|
||||
if row is None:
|
||||
raise unauthorized()
|
||||
return row["user_id"]
|
||||
|
||||
def logout(self, token):
|
||||
with self.connection() as connection:
|
||||
result = connection.execute("DELETE FROM sessions WHERE token_hash=%s", (token_hash(token),))
|
||||
if result.rowcount != 1:
|
||||
raise unauthorized()
|
||||
|
||||
def user(self, user_id):
|
||||
with self.connection() as connection:
|
||||
row = connection.execute("SELECT " + USER_FIELDS + " FROM users WHERE id=%s", (user_id,)).fetchone()
|
||||
if not row:
|
||||
raise unauthorized()
|
||||
return serialize(row)
|
||||
|
||||
def create_chat(self, user_id, body):
|
||||
members = body.member_ids
|
||||
if user_id not in members:
|
||||
raise invalid("Неверный список участников")
|
||||
with self.connection() as connection:
|
||||
found = connection.execute("SELECT id FROM users WHERE id=ANY(%s)", (members,)).fetchall()
|
||||
if len(found) != len(members):
|
||||
raise invalid("Неверный список участников")
|
||||
chat_id = uuid4()
|
||||
# чат и участники коммитятся вместе
|
||||
connection.execute("INSERT INTO chats(id,title) VALUES (%s,%s)", (chat_id, body.title))
|
||||
with connection.cursor() as cursor:
|
||||
cursor.executemany(
|
||||
"INSERT INTO chat_members(chat_id,user_id) VALUES (%s,%s)",
|
||||
[(chat_id, member) for member in members],
|
||||
)
|
||||
return serialize(self.require_chat(connection, user_id, chat_id))
|
||||
|
||||
def require_chat(self, connection, user_id, chat_id):
|
||||
row = connection.execute(
|
||||
"SELECT " + CHAT_FIELDS + """ FROM chats c WHERE c.id=%s
|
||||
AND EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id=c.id AND m.user_id=%s)
|
||||
""", (chat_id, user_id)
|
||||
).fetchone()
|
||||
if row is None:
|
||||
raise not_found()
|
||||
return row
|
||||
|
||||
def chat(self, user_id, chat_id):
|
||||
with self.connection() as connection:
|
||||
return serialize(self.require_chat(connection, user_id, chat_id))
|
||||
|
||||
def list_chats(self, user_id, limit, cursor):
|
||||
scope = "chats:" + str(user_id)
|
||||
after = self.pagination.decode(scope, cursor) if cursor is not None else None
|
||||
condition = " AND (c.created_at,c.id) > (%s,%s)" if after else ""
|
||||
with self.connection() as connection:
|
||||
rows = connection.execute(
|
||||
"SELECT " + CHAT_FIELDS + """ FROM chats c
|
||||
WHERE EXISTS (SELECT 1 FROM chat_members m WHERE m.chat_id=c.id AND m.user_id=%s)"""
|
||||
+ condition + " ORDER BY c.created_at,c.id LIMIT %s",
|
||||
[user_id, *(after or ()), limit + 1],
|
||||
).fetchall()
|
||||
return self.pagination.page(serialize(rows), scope, limit)
|
||||
|
||||
def create_message(self, user_id, chat_id, body, key):
|
||||
path = f"/api/v1/chats/{chat_id}/messages"
|
||||
scope = (user_id, "POST", path, key)
|
||||
canonical = json.dumps(body.model_dump(mode="json"), sort_keys=True, ensure_ascii=False, separators=(",", ":"))
|
||||
request_hash = hashlib.sha256(canonical.encode("utf-8")).hexdigest()
|
||||
lock_data = json.dumps([str(user_id), "POST", path, key], separators=(",", ":")).encode()
|
||||
lock_id = int.from_bytes(hashlib.sha256(lock_data).digest()[:8], "big", signed=True)
|
||||
with self.connection() as connection:
|
||||
self.require_chat(connection, user_id, chat_id)
|
||||
# один ключ блокируется сразу для обеих реплик
|
||||
connection.execute("SELECT pg_advisory_xact_lock(%s)", (lock_id,))
|
||||
saved = connection.execute("""
|
||||
SELECT request_hash,response_body,expires_at > clock_timestamp() AS active
|
||||
FROM idempotency_keys WHERE user_id=%s AND method=%s AND path=%s AND request_key=%s
|
||||
""", scope).fetchone()
|
||||
if saved and saved["active"]:
|
||||
if saved["request_hash"] != request_hash:
|
||||
raise ApiError(409, "conflict", "С этим ключом уже отправлен другой запрос")
|
||||
return saved["response_body"]
|
||||
if saved:
|
||||
connection.execute("""
|
||||
DELETE FROM idempotency_keys WHERE user_id=%s AND method=%s AND path=%s AND request_key=%s
|
||||
""", scope)
|
||||
if body.attachment_ids:
|
||||
found = connection.execute(
|
||||
"SELECT id,status FROM attachments WHERE chat_id=%s AND id=ANY(%s)",
|
||||
(chat_id, body.attachment_ids),
|
||||
).fetchall()
|
||||
if len(found) != len(body.attachment_ids):
|
||||
raise not_found()
|
||||
if any(item["status"] == "failed" for item in found):
|
||||
raise ApiError(409, "conflict", "Вложение не обработано")
|
||||
row = connection.execute("""
|
||||
INSERT INTO messages(id,chat_id,sender_id,text) VALUES (%s,%s,%s,%s)
|
||||
RETURNING id,chat_id,sender_id,text,created_at
|
||||
""", (uuid4(), chat_id, user_id, body.text)).fetchone()
|
||||
for position, attachment_id in enumerate(body.attachment_ids):
|
||||
connection.execute(
|
||||
"INSERT INTO message_attachments(message_id,attachment_id,chat_id,position) VALUES (%s,%s,%s,%s)",
|
||||
(row["id"], attachment_id, chat_id, position),
|
||||
)
|
||||
row["attachment_ids"] = body.attachment_ids
|
||||
message = serialize(row)
|
||||
connection.execute("""
|
||||
INSERT INTO idempotency_keys
|
||||
(user_id,method,path,request_key,request_hash,message_id,response_status,response_body,expires_at)
|
||||
VALUES (%s,%s,%s,%s,%s,%s,201,%s,clock_timestamp() + %s * INTERVAL '1 second')
|
||||
""", (*scope, request_hash, row["id"], Jsonb(message), self.idempotency_ttl))
|
||||
return message
|
||||
|
||||
def list_messages(self, user_id, chat_id, limit, cursor):
|
||||
scope = "messages:" + str(chat_id)
|
||||
after = self.pagination.decode(scope, cursor) if cursor is not None else None
|
||||
condition = " AND (created_at,id) > (%s,%s)" if after else ""
|
||||
with self.connection() as connection:
|
||||
self.require_chat(connection, user_id, chat_id)
|
||||
rows = connection.execute(
|
||||
"""SELECT m.id,m.chat_id,m.sender_id,m.text,m.created_at,
|
||||
ARRAY(SELECT ma.attachment_id FROM message_attachments ma
|
||||
WHERE ma.message_id=m.id ORDER BY ma.position) AS attachment_ids
|
||||
FROM messages m WHERE chat_id=%s"""
|
||||
+ condition + " ORDER BY created_at,id LIMIT %s",
|
||||
[chat_id, *(after or ()), limit + 1],
|
||||
).fetchall()
|
||||
return self.pagination.page(serialize(rows), scope, limit)
|
||||
@@ -0,0 +1,156 @@
|
||||
from contextlib import contextmanager
|
||||
from datetime import datetime, timezone
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import time
|
||||
from uuid import uuid4
|
||||
|
||||
from opentelemetry import metrics, trace
|
||||
from opentelemetry._logs import set_logger_provider
|
||||
from opentelemetry.exporter.otlp.proto.http._log_exporter import OTLPLogExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.metric_exporter import OTLPMetricExporter
|
||||
from opentelemetry.exporter.otlp.proto.http.trace_exporter import OTLPSpanExporter
|
||||
from opentelemetry.sdk._logs import LoggerProvider, LoggingHandler
|
||||
from opentelemetry.sdk._logs.export import BatchLogRecordProcessor
|
||||
from opentelemetry.sdk.metrics import MeterProvider
|
||||
from opentelemetry.sdk.metrics.export import PeriodicExportingMetricReader
|
||||
from opentelemetry.sdk.metrics.view import ExplicitBucketHistogramAggregation, View
|
||||
from opentelemetry.sdk.resources import Resource
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
from opentelemetry.sdk.trace.export import BatchSpanProcessor
|
||||
from starlette.routing import Match
|
||||
|
||||
|
||||
BUCKETS = (0.005, 0.01, 0.025, 0.05, 0.1, 0.25, 0.5, 1, 2.5, 5, 10, 30, 60)
|
||||
FIELDS = {'event', 'request_id', 'job_id', 'attempt', 'outcome', 'error_code',
|
||||
'error_type', 'method', 'route', 'status_code', 'duration_seconds'}
|
||||
logger = logging.getLogger('messenger')
|
||||
_runtime = None
|
||||
|
||||
|
||||
class SafeFields(logging.Filter):
|
||||
def filter(self, record):
|
||||
record.msg = getattr(record, 'event', 'application.event')
|
||||
record.args = ()
|
||||
record.exc_info = None
|
||||
record.exc_text = None
|
||||
record.stack_info = None
|
||||
for name in list(record.__dict__):
|
||||
if name not in STANDARD_FIELDS and name not in FIELDS:
|
||||
del record.__dict__[name]
|
||||
return True
|
||||
|
||||
|
||||
STANDARD_FIELDS = set(logging.makeLogRecord({}).__dict__)
|
||||
|
||||
|
||||
class JsonLog(logging.Formatter):
|
||||
def format(self, record):
|
||||
data = {'timestamp': datetime.fromtimestamp(record.created, timezone.utc).isoformat(),
|
||||
'severity': record.levelname, 'service.name': _runtime.service,
|
||||
'event': record.getMessage()}
|
||||
data.update({name: getattr(record, name) for name in FIELDS if hasattr(record, name)})
|
||||
context = trace.get_current_span().get_span_context()
|
||||
if context.is_valid:
|
||||
data.update(trace_id=f'{context.trace_id:032x}', span_id=f'{context.span_id:016x}')
|
||||
return json.dumps(data, ensure_ascii=False)
|
||||
|
||||
|
||||
class Runtime:
|
||||
def __init__(self, service, instance):
|
||||
self.service = service
|
||||
self.instance = instance
|
||||
resource = Resource.create({'service.name': service,
|
||||
'service.version': os.environ.get('SERVICE_VERSION', 'lab6'),
|
||||
'service.instance.id': instance,
|
||||
'deployment.environment.name': 'lab'})
|
||||
endpoint = os.environ.get('OTEL_EXPORTER_OTLP_ENDPOINT', 'http://otel-collector:4318').rstrip('/')
|
||||
self.traces = TracerProvider(resource=resource)
|
||||
self.traces.add_span_processor(BatchSpanProcessor(
|
||||
OTLPSpanExporter(endpoint=endpoint + '/v1/traces', timeout=2, certificate_file='/run/pki/ca.crt', headers=self.headers()),
|
||||
max_queue_size=1024, max_export_batch_size=128, schedule_delay_millis=1000))
|
||||
self.logs = LoggerProvider(resource=resource)
|
||||
self.logs.add_log_record_processor(BatchLogRecordProcessor(
|
||||
OTLPLogExporter(endpoint=endpoint + '/v1/logs', timeout=2, certificate_file='/run/pki/ca.crt', headers=self.headers()),
|
||||
max_queue_size=1024, max_export_batch_size=128, schedule_delay_millis=1000))
|
||||
self.metrics = MeterProvider(resource=resource, metric_readers=[PeriodicExportingMetricReader(
|
||||
OTLPMetricExporter(endpoint=endpoint + '/v1/metrics', timeout=2, certificate_file='/run/pki/ca.crt', headers=self.headers()),
|
||||
export_interval_millis=5000, export_timeout_millis=2500)], views=[
|
||||
View(instrument_name='messenger.http.duration', aggregation=ExplicitBucketHistogramAggregation(BUCKETS)),
|
||||
View(instrument_name='messenger.job.duration', aggregation=ExplicitBucketHistogramAggregation(BUCKETS))])
|
||||
trace.set_tracer_provider(self.traces)
|
||||
metrics.set_meter_provider(self.metrics)
|
||||
set_logger_provider(self.logs)
|
||||
self.tracer = self.traces.get_tracer('messenger')
|
||||
meter = self.metrics.get_meter('messenger')
|
||||
self.http_count = meter.create_counter('messenger.http.requests', unit='1')
|
||||
self.http_duration = meter.create_histogram('messenger.http.duration', unit='s')
|
||||
self.job_count = meter.create_counter('messenger.jobs', unit='1')
|
||||
self.job_duration = meter.create_histogram('messenger.job.duration', unit='s')
|
||||
logger.setLevel(logging.INFO)
|
||||
logger.propagate = False
|
||||
logger.addFilter(SafeFields())
|
||||
output = logging.StreamHandler()
|
||||
output.setFormatter(JsonLog())
|
||||
logger.addHandler(output)
|
||||
logger.addHandler(LoggingHandler(level=logging.INFO, logger_provider=self.logs))
|
||||
|
||||
def headers(self):
|
||||
from pathlib import Path
|
||||
return {"Authorization": Path("/run/runtime/otel_authorization").read_text().strip()}
|
||||
|
||||
def shutdown(self):
|
||||
self.traces.force_flush(timeout_millis=2500)
|
||||
self.logs.force_flush(timeout_millis=2500)
|
||||
self.metrics.shutdown(timeout_millis=2500)
|
||||
self.traces.shutdown()
|
||||
self.logs.shutdown()
|
||||
|
||||
|
||||
def initialize(service, instance=None):
|
||||
global _runtime
|
||||
if _runtime is None:
|
||||
_runtime = Runtime(service, instance or uuid4().hex)
|
||||
return _runtime
|
||||
|
||||
|
||||
def event(name, level=logging.INFO, **fields):
|
||||
logger.log(level, name, extra={'event': name, **{k: v for k, v in fields.items() if k in FIELDS}})
|
||||
|
||||
|
||||
def route_template(app, scope):
|
||||
for route in app.router.routes:
|
||||
match, _ = route.matches(scope)
|
||||
if match in (Match.FULL, Match.PARTIAL):
|
||||
return route.path
|
||||
return 'unmatched'
|
||||
|
||||
|
||||
@contextmanager
|
||||
def job_attempt(job_id, attempt):
|
||||
runtime = initialize('messenger-worker')
|
||||
started = time.monotonic()
|
||||
result = {'outcome': 'retry'}
|
||||
with runtime.tracer.start_as_current_span('attachment.process', kind=trace.SpanKind.CONSUMER,
|
||||
attributes={'messaging.system': 'rabbitmq', 'messaging.operation.type': 'process',
|
||||
'messenger.job.type': 'attachment.process.v1', 'messenger.job.id': str(job_id),
|
||||
'messenger.job.attempt': attempt}, record_exception=False, set_status_on_exception=False) as span:
|
||||
event('job.started', job_id=str(job_id), attempt=attempt)
|
||||
try:
|
||||
yield result
|
||||
except Exception as error:
|
||||
event('job.dependency_failed', logging.ERROR, job_id=str(job_id),
|
||||
error_type=type(error).__name__)
|
||||
raise
|
||||
finally:
|
||||
duration = time.monotonic() - started
|
||||
outcome = result['outcome']
|
||||
attributes = {'job_type': 'attachment.process.v1', 'outcome': outcome}
|
||||
span.set_attribute('messenger.job.outcome', outcome)
|
||||
if outcome != 'success':
|
||||
span.set_status(trace.StatusCode.ERROR)
|
||||
runtime.job_count.add(1, attributes)
|
||||
runtime.job_duration.record(duration, attributes)
|
||||
event('job.completed', job_id=str(job_id), attempt=attempt, outcome=outcome,
|
||||
duration_seconds=round(duration, 6), error_code=result.get('error_code', ''))
|
||||
+167
@@ -0,0 +1,167 @@
|
||||
import json
|
||||
import logging
|
||||
import os
|
||||
import signal
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
from uuid import UUID
|
||||
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
|
||||
from . import bao
|
||||
from .telemetry import initialize, event, job_attempt
|
||||
from .broker import QUEUE, connect, envelope, publish
|
||||
from .config import secret
|
||||
from .storage import serialize
|
||||
|
||||
|
||||
def pause(connection, seconds):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
connection.process_data_events(time_limit=min(0.2, deadline - time.monotonic()))
|
||||
|
||||
|
||||
def handle(connection, channel, tag, message):
|
||||
try:
|
||||
data = json.loads(message)
|
||||
if not isinstance(data, dict) or set(data) - {'schema_version','job_id','type','attachment_id',
|
||||
'pipeline_version','attempt','created_at','traceparent','tracestate'}:
|
||||
raise ValueError()
|
||||
job_id, attachment_id = UUID(data['job_id']), UUID(data['attachment_id'])
|
||||
if type(data['schema_version']) is not int or type(data['pipeline_version']) is not int:
|
||||
raise ValueError()
|
||||
if data['schema_version'] != 1 or data['pipeline_version'] != 1 or data['type'] != QUEUE:
|
||||
raise ValueError()
|
||||
if type(data['attempt']) is not int or data['attempt'] < 1:
|
||||
raise ValueError()
|
||||
if not isinstance(data['created_at'], str) or datetime.fromisoformat(data['created_at'].replace('Z', '+00:00')).tzinfo is None:
|
||||
raise ValueError()
|
||||
except (ValueError, KeyError, TypeError):
|
||||
channel.basic_reject(tag, requeue=False)
|
||||
event('job.rejected', logging.WARNING)
|
||||
return
|
||||
with psycopg.connect(secret('DATABASE_URL_FILE'), autocommit=True, row_factory=dict_row,
|
||||
connect_timeout=3, options='-c statement_timeout=5000') as db:
|
||||
lock = int.from_bytes(job_id.bytes[:8], 'big', signed=True)
|
||||
if not db.execute('SELECT pg_try_advisory_lock(%s) AS locked', (lock,)).fetchone()['locked']:
|
||||
pause(connection, 1)
|
||||
channel.basic_nack(tag, requeue=True)
|
||||
return
|
||||
row = db.execute('SELECT j.*,a.object_key,a.content_type,a.size_bytes,a.sha256,a.status '
|
||||
'FROM attachment_jobs j JOIN attachments a ON a.id=j.attachment_id '
|
||||
'WHERE j.id=%s AND j.attachment_id=%s', (job_id, attachment_id)).fetchone()
|
||||
if not row or row['status'] in ('ready', 'failed'):
|
||||
channel.basic_ack(tag)
|
||||
return
|
||||
maximum = int(os.environ.get('JOB_MAX_ATTEMPTS', '5'))
|
||||
if row['attempt'] >= maximum:
|
||||
db.execute("UPDATE attachments SET status='failed',error_code='retry_exhausted',"
|
||||
'updated_at=clock_timestamp() WHERE id=%s', (attachment_id,))
|
||||
channel.basic_ack(tag)
|
||||
return
|
||||
expected = row['attempt'] + 1
|
||||
if data['attempt'] < expected:
|
||||
publish(envelope(row, expected))
|
||||
channel.basic_ack(tag)
|
||||
return
|
||||
if data['attempt'] > expected:
|
||||
channel.basic_reject(tag, requeue=False)
|
||||
return
|
||||
delay = (row['next_attempt_at'] - datetime.now(timezone.utc)).total_seconds()
|
||||
if delay > 0:
|
||||
pause(connection, min(delay, 5))
|
||||
with db.transaction():
|
||||
db.execute("UPDATE attachments SET status='processing',error_code=NULL,updated_at=clock_timestamp() "
|
||||
'WHERE id=%s', (attachment_id,))
|
||||
db.execute('UPDATE attachment_jobs SET attempt=%s WHERE id=%s', (expected, job_id))
|
||||
with job_attempt(job_id, expected) as outcome:
|
||||
process = subprocess.Popen([sys.executable, '-m', 'src.process_image'], stdin=subprocess.PIPE,
|
||||
stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, text=True)
|
||||
started = time.monotonic()
|
||||
try:
|
||||
process.stdin.write(json.dumps(serialize(row)))
|
||||
process.stdin.close()
|
||||
while process.poll() is None:
|
||||
if time.monotonic() - started > int(os.environ.get('JOB_TIMEOUT_SECONDS', '60')):
|
||||
process.kill()
|
||||
process.wait()
|
||||
break
|
||||
connection.process_data_events(time_limit=0.2)
|
||||
result = json.loads(process.stdout.read()) if process.returncode == 0 else None
|
||||
finally:
|
||||
if process.poll() is None:
|
||||
process.kill()
|
||||
process.wait()
|
||||
process.stdout.close()
|
||||
if result:
|
||||
with db.transaction():
|
||||
db.execute('INSERT INTO attachment_variants '
|
||||
'(attachment_id,name,content_type,width,height,size_bytes,sha256,object_key) '
|
||||
'VALUES (%s,%s,%s,%s,%s,%s,%s,%s) ON CONFLICT (attachment_id,pipeline_version,name) '
|
||||
'DO UPDATE SET content_type=EXCLUDED.content_type,width=EXCLUDED.width,height=EXCLUDED.height,'
|
||||
'size_bytes=EXCLUDED.size_bytes,sha256=EXCLUDED.sha256,object_key=EXCLUDED.object_key',
|
||||
(attachment_id, *[result[k] for k in ('name','content_type','width','height','size_bytes','sha256','object_key')]))
|
||||
db.execute("UPDATE attachments SET status='ready',error_code=NULL,updated_at=clock_timestamp() "
|
||||
'WHERE id=%s', (attachment_id,))
|
||||
outcome['outcome'] = 'success'
|
||||
channel.basic_ack(tag)
|
||||
elif process.returncode == 43 or expected >= maximum:
|
||||
code = 'invalid_image' if process.returncode == 43 else 'retry_exhausted'
|
||||
db.execute("UPDATE attachments SET status='failed',error_code=%s,updated_at=clock_timestamp() "
|
||||
'WHERE id=%s', (code, attachment_id))
|
||||
outcome.update(outcome='failed', error_code=code)
|
||||
channel.basic_ack(tag)
|
||||
else:
|
||||
with db.transaction():
|
||||
db.execute("UPDATE attachments SET status='queued',error_code=NULL,updated_at=clock_timestamp() "
|
||||
'WHERE id=%s', (attachment_id,))
|
||||
db.execute("UPDATE attachment_jobs SET next_attempt_at=clock_timestamp()+INTERVAL '5 seconds' "
|
||||
'WHERE id=%s', (job_id,))
|
||||
publish(envelope(row, expected + 1))
|
||||
channel.basic_ack(tag)
|
||||
|
||||
|
||||
|
||||
def consume():
|
||||
signal.signal(signal.SIGTERM, lambda *_: sys.exit(0))
|
||||
while True:
|
||||
connection = None
|
||||
try:
|
||||
connection = connect()
|
||||
channel = connection.channel()
|
||||
channel.queue_declare(queue=QUEUE, passive=True)
|
||||
channel.basic_qos(prefetch_count=1)
|
||||
for method, properties, message in channel.consume(QUEUE, inactivity_timeout=1, auto_ack=False):
|
||||
if method:
|
||||
while True:
|
||||
try:
|
||||
bao.ready()
|
||||
break
|
||||
except Exception:
|
||||
pause(connection, 1)
|
||||
handle(connection, channel, method.delivery_tag, message)
|
||||
except Exception as error:
|
||||
event('worker.reconnect', logging.WARNING, error_type=type(error).__name__)
|
||||
finally:
|
||||
if connection and connection.is_open:
|
||||
try:
|
||||
connection.close()
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
def main():
|
||||
bao.initialize()
|
||||
runtime = initialize('messenger-worker')
|
||||
try:
|
||||
consume()
|
||||
finally:
|
||||
runtime.shutdown()
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
main()
|
||||
@@ -0,0 +1,90 @@
|
||||
import argparse
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import struct
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import zlib
|
||||
|
||||
from PIL import Image
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT))
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client
|
||||
from scripts import lab
|
||||
|
||||
|
||||
def arguments():
|
||||
return argparse.Namespace(
|
||||
project=os.environ.get("LAB7_PROJECT", "mtusi-lab7"),
|
||||
port=int(os.environ.get("LAB7_PORT", "8080")),
|
||||
ttl=int(os.environ.get("LAB7_TTL", "3600")), test_port=18082,
|
||||
)
|
||||
|
||||
|
||||
def sql(statement):
|
||||
args = arguments()
|
||||
return lab.compose(args, "exec", "-T", "db", "psql", "-U", "messenger", "-d", "messenger",
|
||||
"-v", "ON_ERROR_STOP=1", "-At", "-c", statement, quiet=True).strip()
|
||||
|
||||
|
||||
def s3(code, admin=True):
|
||||
args = arguments()
|
||||
prelude = "import json; from src.objects import Objects; o=Objects(admin=" + str(admin) + "); c=o.client; b=o.bucket; "
|
||||
if admin:
|
||||
output = lab.compose(args, "run", "--rm", "--no-deps", "-T", "bootstrap",
|
||||
"python", "-c", prelude + code, quiet=True)
|
||||
else:
|
||||
output = lab.compose(args, "exec", "-T", "api1", "python", "-c", prelude + code, quiet=True)
|
||||
return json.loads(output.strip().splitlines()[-1])
|
||||
|
||||
|
||||
def object_exists(key):
|
||||
return s3("print(json.dumps(any(x['Key']==" + repr(key)
|
||||
+ " for x in c.list_objects_v2(Bucket=b,Prefix=" + repr(key) + ").get('Contents',[]))))")
|
||||
|
||||
|
||||
def wait(predicate, seconds=30):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
if predicate():
|
||||
return
|
||||
time.sleep(0.1)
|
||||
raise AssertionError("Test condition timed out")
|
||||
|
||||
|
||||
def image_bytes(kind="PNG", size=(32, 24), mode="RGB"):
|
||||
with Image.new(mode, size, (35, 120, 200, 255) if mode == "RGBA" else (35, 120, 200)) as image:
|
||||
output = io.BytesIO()
|
||||
image.save(output, format=kind)
|
||||
return output.getvalue()
|
||||
|
||||
|
||||
def chunk(kind, data):
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xffffffff)
|
||||
|
||||
|
||||
def padded_png(size):
|
||||
base = image_bytes()
|
||||
padding = b"p" * (size - len(base) - 12)
|
||||
return base[:-12] + chunk(b"raNd", padding) + base[-12:]
|
||||
|
||||
|
||||
def oversized_pixels():
|
||||
header = struct.pack(">IIBBBBB", 8000, 5001, 8, 2, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", header) + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def cleanup_once(expected=True):
|
||||
args = arguments()
|
||||
command = ["docker", "compose", "--project-name", args.project, "--env-file", ".env",
|
||||
"run", "--rm", "--no-deps", "-T", "cleanup", "python", "-m", "src.cleanup", "--once"]
|
||||
result = subprocess.run(command, cwd=ROOT, env=lab.environment(args), capture_output=True, text=True, encoding="utf-8")
|
||||
if (result.returncode == 0) != expected:
|
||||
raise AssertionError("Unexpected cleanup exit status")
|
||||
return json.loads(result.stdout.strip().splitlines()[-1]) if expected else None
|
||||
@@ -0,0 +1,181 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import os
|
||||
from pathlib import Path
|
||||
import sys
|
||||
import unittest
|
||||
from urllib.parse import urlencode
|
||||
from uuid import uuid4
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, timestamp
|
||||
|
||||
|
||||
class ApiTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.client = Client(os.environ.get("BASE_URL", "http://127.0.0.1:8080"))
|
||||
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
|
||||
self.path = "/api/v1/chats/" + self.chat["id"]
|
||||
|
||||
def error(self, method, path, status=400, **kwargs):
|
||||
if method == "POST" and path.endswith("/messages"):
|
||||
kwargs.setdefault("headers", {}).setdefault("Idempotency-Key", uuid4().hex)
|
||||
response = self.client.call(method, path, status, **kwargs)
|
||||
code = {400: "invalid_request", 401: "unauthorized", 404: "not_found", 409: "conflict", 415: "unsupported_media_type"}[status]
|
||||
self.assertEqual(response["json"]["error"]["code"], code)
|
||||
|
||||
def get_page(self, path, actor=None, **query):
|
||||
schema = "MessagePage" if path.endswith("/messages") else "ChatPage"
|
||||
return self.client.call("GET", path + "?" + urlencode(query), actor=actor or self.alice, schema=schema)["json"]
|
||||
|
||||
def new_chat(self):
|
||||
return self.client.call("POST", "/api/v1/chats", 201, actor=self.alice,
|
||||
body={"title": "Ещё чат", "member_ids": [self.alice["id"], self.bob["id"]]}, schema="Chat")["json"]
|
||||
|
||||
def test_user_fields(self):
|
||||
name = "u_" + uuid4().hex[:20]
|
||||
bodies = [
|
||||
{"username": "ab", "display_name": "Имя"},
|
||||
{"username": "ABC", "display_name": "Имя"},
|
||||
{"username": "valid\n", "display_name": "Имя"},
|
||||
{"username": 123, "display_name": "Имя"},
|
||||
{"username": name, "display_name": " \t\n"},
|
||||
{"username": name, "display_name": 123},
|
||||
{"username": name, "display_name": None},
|
||||
{"username": name, "display_name": "я" * 101},
|
||||
{"username": name, "display_name": "Имя", "password": "extra"},
|
||||
{"username": name},
|
||||
]
|
||||
for body in bodies:
|
||||
body.setdefault("password", "T3st-password-123")
|
||||
with self.subTest(fields=sorted(body)):
|
||||
self.error("POST", "/api/v1/users", body=body)
|
||||
user = self.client.call("POST", "/api/v1/users", 201,
|
||||
body={"username": name, "display_name": "👋" * 100, "password": "T3st-password-123"}, schema="User")["json"]
|
||||
self.assertEqual(user["display_name"], "👋" * 100)
|
||||
self.error("POST", "/api/v1/users", 409, body={"username": name, "display_name": "Повтор", "password": "T3st-password-123"})
|
||||
|
||||
def test_invalid_json_and_content_type(self):
|
||||
for raw in (b'{"username":', b"null", b"[]", b"true", b"\xff", '{}'.encode('utf-16')):
|
||||
with self.subTest(raw=raw):
|
||||
self.error("POST", "/api/v1/users", raw=raw, headers={"Content-Type": "application/json"})
|
||||
self.error("POST", "/api/v1/users", 415, raw=b"text", headers={"Content-Type": "text/plain"})
|
||||
self.error("POST", "/api/v1/users", 415, raw=b"{}")
|
||||
|
||||
def test_auth_and_access(self):
|
||||
self.error("GET", "/api/v1/users/me", 401)
|
||||
for value in (str(uuid4()), "bad-id"):
|
||||
self.error("GET", "/api/v1/users/me", 401, headers={"X-User-Id": value})
|
||||
self.error("GET", "/api/v1/chats/bad-id", 401)
|
||||
self.error("GET", "/api/v1/chats/bad-id", actor=self.alice)
|
||||
self.error("GET", "/api/v1/chats/" + str(uuid4()), 404, actor=self.alice)
|
||||
self.error("GET", self.path, 404, actor=self.eve)
|
||||
self.error("GET", self.path + "/messages", 404, actor=self.eve)
|
||||
self.error("POST", self.path + "/messages", 404, actor=self.eve, body={"text": "Чужое"})
|
||||
self.assertEqual(self.get_page("/api/v1/chats", self.eve)["items"], [])
|
||||
|
||||
def test_chat_validation_is_atomic(self):
|
||||
before = self.get_page("/api/v1/chats")["items"]
|
||||
valid = [self.alice["id"], self.bob["id"]]
|
||||
for members in ([], [self.bob["id"]], [self.alice["id"], str(uuid4())],
|
||||
[self.alice["id"], self.alice["id"].upper()], ["bad-id"], valid * 51):
|
||||
self.error("POST", "/api/v1/chats", actor=self.alice, body={"title": "Чат", "member_ids": members})
|
||||
for title in ("", " \t", "я" * 101, 123):
|
||||
self.error("POST", "/api/v1/chats", actor=self.alice, body={"title": title, "member_ids": valid})
|
||||
self.error("POST", "/api/v1/chats", actor=self.alice, body={"title": "Чат", "member_ids": valid, "extra": 1})
|
||||
self.assertEqual(before, self.get_page("/api/v1/chats")["items"])
|
||||
|
||||
def test_message_fields_and_unicode(self):
|
||||
bodies = [{"text": value} for value in ("", " \t\n", "я" * 4001, None, 123, True, [])]
|
||||
bodies += [{}, {"text": "Hi", "sender_id": self.bob["id"]}, {"text": "Hi", "unexpected": []}]
|
||||
for body in bodies:
|
||||
self.error("POST", self.path + "/messages", actor=self.alice, body=body)
|
||||
for text in (" Привет, мир 👋\n", "👋" * 4000):
|
||||
message = self.client.message(self.alice, self.chat, text)["json"]
|
||||
self.assertEqual(message["text"], text)
|
||||
self.assertEqual(message["sender_id"], self.alice["id"])
|
||||
|
||||
def test_message_pagination(self):
|
||||
self.assertEqual(self.get_page(self.path + "/messages"), {"items": [], "next_cursor": None})
|
||||
self.assertEqual(self.get_page(self.path + "/messages", limit="0000000001")["items"], [])
|
||||
sent = [self.client.message(self.alice if i % 2 else self.bob, self.chat, str(i))["json"] for i in range(6)]
|
||||
received, cursor = [], None
|
||||
for limit in (2, 3, 1):
|
||||
query = {"limit": limit}
|
||||
if cursor:
|
||||
query["cursor"] = cursor
|
||||
page = self.get_page(self.path + "/messages", self.bob, **query)
|
||||
received.extend(page["items"])
|
||||
cursor = page["next_cursor"]
|
||||
self.assertIsNone(cursor)
|
||||
self.assertEqual(received, sorted(sent, key=lambda item: (timestamp(item["created_at"]), item["id"])))
|
||||
|
||||
def test_chat_pagination(self):
|
||||
chats = [self.chat] + [self.new_chat() for _ in range(4)]
|
||||
received, cursor = [], None
|
||||
while True:
|
||||
query = {"limit": 2}
|
||||
if cursor:
|
||||
query["cursor"] = cursor
|
||||
page = self.get_page("/api/v1/chats", **query)
|
||||
received += page["items"]
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
self.assertEqual(received, sorted(chats, key=lambda item: (timestamp(item["created_at"]), item["id"])))
|
||||
cursor = self.get_page("/api/v1/chats", limit=1)["next_cursor"]
|
||||
self.error("GET", "/api/v1/chats?" + urlencode({"cursor": cursor}), actor=self.bob)
|
||||
|
||||
def test_bad_cursors_and_limits(self):
|
||||
for i in range(2):
|
||||
self.client.message(self.alice, self.chat, str(i))
|
||||
cursor = self.get_page(self.path + "/messages", limit=1)["next_cursor"]
|
||||
for value in ("", "bad", cursor[:-1] + ("0" if cursor[-1] != "0" else "1")):
|
||||
self.error("GET", self.path + "/messages?" + urlencode({"cursor": value}), actor=self.alice)
|
||||
other = self.new_chat()
|
||||
self.error("GET", "/api/v1/chats/" + other["id"] + "/messages?" + urlencode({"cursor": cursor}), actor=self.alice)
|
||||
self.error("GET", "/api/v1/chats?" + urlencode({"cursor": cursor}), actor=self.alice)
|
||||
for path in ("/api/v1/chats", self.path + "/messages"):
|
||||
for value in ("", "0", "-1", "101", "1.5", "true", "9" * 500):
|
||||
self.error("GET", path + "?" + urlencode({"limit": value}), actor=self.alice)
|
||||
|
||||
def test_read_after_write(self):
|
||||
first = self.client.message(self.alice, self.chat, "Первое")["json"]
|
||||
second = self.client.message(self.bob, self.chat, "Второе")["json"]
|
||||
page = self.get_page(self.path + "/messages", limit=1)
|
||||
third = self.client.message(self.bob, self.chat, "Новое")["json"]
|
||||
rest = self.get_page(self.path + "/messages", self.bob, cursor=page["next_cursor"])
|
||||
self.assertEqual(page["items"] + rest["items"], [first, second, third])
|
||||
self.assertIsNone(rest["next_cursor"])
|
||||
|
||||
def test_parallel_messages(self):
|
||||
def send(worker):
|
||||
client = Client(self.client.base)
|
||||
return [client.message(self.alice, self.chat, f"{worker}:{i}")["json"]["id"] for i in range(10)]
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
sent = [item for group in pool.map(send, range(10)) for item in group]
|
||||
received, cursor = [], None
|
||||
while True:
|
||||
query = {"limit": 17}
|
||||
if cursor:
|
||||
query["cursor"] = cursor
|
||||
page = self.get_page(self.path + "/messages", self.bob, **query)
|
||||
received += page["items"]
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
self.assertEqual(len(received), 100)
|
||||
self.assertEqual(len({item["text"] for item in received}), 100)
|
||||
self.assertEqual({item["id"] for item in received}, set(sent))
|
||||
|
||||
def test_parallel_username(self):
|
||||
body = {"username": "u_" + uuid4().hex[:20], "display_name": "Один", "password": "T3st-password-123"}
|
||||
def create(_):
|
||||
return Client(self.client.base).call("POST", "/api/v1/users", [201, 409], body=body, schema="User")["status"]
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
statuses = list(pool.map(create, range(10)))
|
||||
self.assertEqual(statuses.count(201), 1)
|
||||
self.assertEqual(statuses.count(409), 9)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,148 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import hashlib
|
||||
import io
|
||||
from PIL import Image
|
||||
from urllib.parse import urlencode
|
||||
from uuid import uuid4
|
||||
import unittest
|
||||
|
||||
from helpers import Client, ROOT, image_bytes, oversized_pixels, padded_png
|
||||
|
||||
|
||||
class AttachmentTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.client = Client(timeout=60)
|
||||
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
|
||||
self.path = "/api/v1/chats/" + self.chat["id"]
|
||||
|
||||
def upload(self, content=None, media="image/png", name="photo.png", expected=201, actor=None):
|
||||
response = self.client.call(
|
||||
"POST", self.path + "/attachments?" + urlencode({"filename": name}), 202 if expected == 201 else expected,
|
||||
actor=actor or self.alice, raw=image_bytes() if content is None else content,
|
||||
headers={"Content-Type": media}, schema="Attachment" if expected == 201 else None,
|
||||
)
|
||||
if expected == 201:
|
||||
response["json"] = self.client.wait_ready(actor or self.alice, response["json"])
|
||||
return response
|
||||
|
||||
def test_original_png_jpeg_and_unicode_filename(self):
|
||||
for kind, media in (("PNG", "image/png"), ("JPEG", "image/jpeg")):
|
||||
raw = image_bytes(kind)
|
||||
att = self.upload(raw, media, "фото 👋." + kind.lower())["json"]
|
||||
self.assertEqual(att["owner_id"], self.alice["id"])
|
||||
self.assertEqual(att["sha256"], hashlib.sha256(raw).hexdigest())
|
||||
self.assertEqual(att["size_bytes"], len(raw))
|
||||
self.assertEqual((att["status"], att["error_code"]), ("ready", None))
|
||||
self.assertEqual([v["name"] for v in att["variants"]], ["thumbnail"])
|
||||
path = "/api/v1/attachments/" + att["id"]
|
||||
metadata = self.client.call("GET", path, actor=self.bob, schema="Attachment")["json"]
|
||||
self.assertEqual(metadata, att)
|
||||
downloaded = self.client.call("GET", path + "/content", actor=self.bob)
|
||||
self.assertEqual(downloaded["bytes"], raw)
|
||||
self.assertEqual(downloaded["headers"].get_content_type(), media)
|
||||
self.assertNotIn("object_key", metadata)
|
||||
self.assertNotIn("Location", downloaded["headers"])
|
||||
|
||||
def test_thumbnail_orientation_transparency_and_small_size(self):
|
||||
cases = []
|
||||
with Image.new('RGB', (80, 40), 'red') as image:
|
||||
output = io.BytesIO()
|
||||
exif = Image.Exif()
|
||||
exif[274] = 6
|
||||
image.save(output, format='JPEG', exif=exif)
|
||||
cases.append((output.getvalue(), 'image/jpeg', (40, 80), False))
|
||||
with Image.new('RGBA', (21, 11), (255, 0, 0, 0)) as image:
|
||||
output = io.BytesIO()
|
||||
image.save(output, format='PNG')
|
||||
cases.append((output.getvalue(), 'image/png', (21, 11), True))
|
||||
for raw, media, size, white in cases:
|
||||
att = self.upload(raw, media)['json']
|
||||
variant = att['variants'][0]
|
||||
self.assertEqual((variant['width'], variant['height']), size)
|
||||
response = self.client.call('GET', '/api/v1/attachments/' + att['id'] + '/content?variant=thumbnail', actor=self.bob)
|
||||
self.assertEqual(hashlib.sha256(response['bytes']).hexdigest(), variant['sha256'])
|
||||
with Image.open(io.BytesIO(response['bytes'])) as thumbnail:
|
||||
self.assertEqual(thumbnail.format, 'JPEG')
|
||||
self.assertEqual(thumbnail.size, size)
|
||||
self.assertNotIn(274, thumbnail.getexif())
|
||||
if white:
|
||||
self.assertTrue(all(channel >= 245 for channel in thumbnail.getpixel((0, 0))))
|
||||
|
||||
def test_filename_validation(self):
|
||||
for name in ("", " \t", "../a.png", "a/b.png", "a\\b.png", "a\x00.png", "a\n.png", "a\x7f.png", "я" * 256):
|
||||
self.upload(name=name, expected=400)
|
||||
self.assertEqual(self.upload(name="я" * 255)["json"]["filename"], "я" * 255)
|
||||
|
||||
def test_corrupt_images_mime_and_multipart(self):
|
||||
png, jpeg = image_bytes(), image_bytes("JPEG")
|
||||
for content, media in ((b"", "image/png"), (b"not an image", "image/png"),
|
||||
(png[:-8], "image/png"), (jpeg[:-8], "image/jpeg"),
|
||||
(png, "image/jpeg"), (jpeg, "image/png"),
|
||||
(image_bytes("GIF"), "image/png"), (png, "multipart/form-data")):
|
||||
self.upload(content, media, expected=415)
|
||||
|
||||
def test_byte_limit_and_original_at_exact_boundary(self):
|
||||
raw = padded_png(10485760)
|
||||
att = self.upload(raw)["json"]
|
||||
downloaded = self.client.call("GET", "/api/v1/attachments/" + att["id"] + "/content", actor=self.bob)
|
||||
self.assertEqual(downloaded["bytes"], raw)
|
||||
self.upload(raw + b"x", expected=413)
|
||||
|
||||
def test_chunked_body_cannot_bypass_size_limit(self):
|
||||
def blocks():
|
||||
for _ in range(161):
|
||||
yield b"x" * 65536
|
||||
self.upload(blocks(), expected=413)
|
||||
|
||||
def test_pixel_boundary_and_decompression_bomb(self):
|
||||
self.upload(oversized_pixels(), expected=413)
|
||||
self.assertEqual(self.upload(image_bytes(size=(8000, 5000)))["json"]["status"], "ready")
|
||||
|
||||
def test_attachment_access_and_unknown_ids(self):
|
||||
att = self.upload()["json"]
|
||||
for suffix in ("", "/content"):
|
||||
self.client.call("GET", "/api/v1/attachments/" + att["id"] + suffix, 404, actor=self.eve)
|
||||
self.client.call("GET", "/api/v1/attachments/" + str(uuid4()) + suffix, 404, actor=self.alice)
|
||||
self.client.call("GET", "/api/v1/attachments/" + att["id"] + suffix, 401)
|
||||
self.upload(actor=self.eve, expected=404)
|
||||
|
||||
def test_messages_keep_attachment_order_and_allow_empty_text(self):
|
||||
ids = [self.upload()["json"]["id"] for _ in range(2)]
|
||||
for text in ("", " \t\n", "с картинками"):
|
||||
message = self.client.message(self.bob, self.chat, text, attachments=ids[::-1])["json"]
|
||||
self.assertEqual(message["attachment_ids"], ids[::-1])
|
||||
self.assertEqual(message["text"], text)
|
||||
page = self.client.call("GET", self.path + "/messages", actor=self.alice, schema="MessagePage")["json"]
|
||||
self.assertEqual([m["attachment_ids"] for m in page["items"]], [ids[::-1]] * 3)
|
||||
|
||||
def test_bad_attachment_list_and_other_chat_do_not_create_messages(self):
|
||||
att = self.upload()["json"]["id"]
|
||||
other = self.client.call("POST", "/api/v1/chats", 201, actor=self.alice,
|
||||
body={"title": "other", "member_ids": [self.alice["id"]]}, schema="Chat")["json"]
|
||||
foreign = self.client.attachment(self.alice, other)[0]["id"]
|
||||
for ids, status in (([att, att], 400), ([str(uuid4()) for _ in range(11)], 400),
|
||||
(["bad"], 400), ([str(uuid4())], 404), ([foreign], 404)):
|
||||
self.client.call("POST", self.path + "/messages", status, actor=self.alice,
|
||||
body={"text": "test", "attachment_ids": ids}, headers={"Idempotency-Key": uuid4().hex})
|
||||
page = self.client.call("GET", self.path + "/messages", actor=self.alice, schema="MessagePage")["json"]
|
||||
self.assertEqual(page["items"], [])
|
||||
|
||||
def test_idempotency_defaults_and_attachment_replay(self):
|
||||
key = uuid4().hex
|
||||
original = self.client.message(self.alice, self.chat, "text", key=key)["json"]
|
||||
explicit = self.client.message(self.alice, self.chat, "text", key=key, attachments=[])["json"]
|
||||
self.assertEqual(original, explicit)
|
||||
att = self.upload()["json"]["id"]
|
||||
key = uuid4().hex
|
||||
def send(_):
|
||||
return Client(timeout=30).message(self.alice, self.chat, "", key=key, attachments=[att])
|
||||
with ThreadPoolExecutor(max_workers=10) as pool:
|
||||
responses = list(pool.map(send, range(10)))
|
||||
self.assertEqual(len({r["json"]["id"] for r in responses}), 1)
|
||||
self.assertEqual(len({r["headers"]["X-Instance-Id"] for r in responses}), 2)
|
||||
self.client.call("POST", self.path + "/messages", 409, actor=self.alice,
|
||||
body={"text": "different", "attachment_ids": [att]}, headers={"Idempotency-Key": key})
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,140 @@
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
from uuid import uuid4
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client
|
||||
|
||||
|
||||
class IdempotencyTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.client = Client(os.environ.get("BASE_URL", "http://127.0.0.1:8080"))
|
||||
self.alice, self.bob, self.eve, self.chat = self.client.bootstrap()
|
||||
self.path = "/api/v1/chats/" + self.chat["id"] + "/messages"
|
||||
|
||||
def history(self):
|
||||
return self.client.call("GET", self.path + "?limit=100", actor=self.alice, schema="MessagePage")["json"]["items"]
|
||||
|
||||
def sql(self, statement):
|
||||
project = os.environ.get("LAB7_PROJECT", "mtusi-lab7")
|
||||
command = ["docker", "compose", "--project-name", project, "--env-file", ".env",
|
||||
"exec", "-T", "db", "psql", "-U", "messenger", "-d", "messenger",
|
||||
"-v", "ON_ERROR_STOP=1", "-At", "-c", statement]
|
||||
result = subprocess.run(command, cwd=ROOT, capture_output=True, text=True, encoding="utf-8")
|
||||
if result.returncode:
|
||||
raise AssertionError("Database test command failed")
|
||||
return result.stdout.strip()
|
||||
|
||||
def test_key_required_and_format(self):
|
||||
for key in (None, "", "two words", "a/b", "é", "a" * 129):
|
||||
headers = {} if key is None else {"Idempotency-Key": key}
|
||||
self.client.call("POST", self.path, 400, actor=self.alice, body={"text": "test"}, headers=headers)
|
||||
for key in ("a", ".:_-", "a" * 128):
|
||||
self.client.message(self.alice, self.chat, key, key=key)
|
||||
self.assertEqual(len(self.history()), 3)
|
||||
|
||||
def test_replay_normalizes_json(self):
|
||||
key = uuid4().hex
|
||||
text = "Привет 👋"
|
||||
first = self.client.message(self.alice, self.chat, text, key=key)
|
||||
raw = json.dumps({"text": text}, ensure_ascii=True, indent=4).encode("ascii")
|
||||
second = self.client.call("POST", self.path, 201, actor=self.alice, raw=raw,
|
||||
headers={"Idempotency-Key": key, "Content-Type": "application/json"}, schema="Message")
|
||||
self.assertEqual(first["json"], second["json"])
|
||||
self.assertNotEqual(first["headers"]["X-Request-Id"], second["headers"]["X-Request-Id"])
|
||||
self.assertEqual(len(self.history()), 1)
|
||||
|
||||
def test_different_body_conflicts(self):
|
||||
key = uuid4().hex
|
||||
original = self.client.message(self.alice, self.chat, "first", key=key)["json"]
|
||||
self.client.call("POST", self.path, 409, actor=self.alice,
|
||||
body={"text": "second"}, headers={"Idempotency-Key": key})
|
||||
self.assertEqual(self.client.message(self.alice, self.chat, "first", key=key)["json"], original)
|
||||
self.assertEqual(self.history(), [original])
|
||||
|
||||
def test_twenty_concurrent_requests_use_both_replicas(self):
|
||||
key = uuid4().hex
|
||||
def send(_):
|
||||
return Client(self.client.base).message(self.alice, self.chat, "one message", key=key)
|
||||
with ThreadPoolExecutor(max_workers=20) as pool:
|
||||
responses = list(pool.map(send, range(20)))
|
||||
self.assertEqual(len({item["json"]["id"] for item in responses}), 1)
|
||||
self.assertEqual(len({item["headers"]["X-Instance-Id"] for item in responses}), 2)
|
||||
self.assertTrue(all(item["json"] == responses[0]["json"] for item in responses))
|
||||
self.assertEqual(self.history(), [responses[0]["json"]])
|
||||
|
||||
def test_scope_is_user_and_chat_not_session(self):
|
||||
key = uuid4().hex
|
||||
first = self.client.message(self.alice, self.chat, "shared", key=key)["json"]
|
||||
second = self.client.message(self.bob, self.chat, "shared", key=key)["json"]
|
||||
other = self.client.call("POST", "/api/v1/chats", 201, actor=self.alice,
|
||||
body={"title": "other", "member_ids": [self.alice["id"]]}, schema="Chat")["json"]
|
||||
third = self.client.message(self.alice, other, "shared", key=key)["json"]
|
||||
self.assertEqual(len({first["id"], second["id"], third["id"]}), 3)
|
||||
source = self.alice["registration"]
|
||||
value = base64.b64encode((source["username"] + ":" + source["password"]).encode()).decode()
|
||||
session = self.client.call("POST", "/api/v1/auth/sessions", 201,
|
||||
headers={"Authorization": "Basic " + value}, schema="Session")["json"]
|
||||
actor = {"id": self.alice["id"], "token": session["token"]}
|
||||
self.assertEqual(self.client.message(actor, self.chat, "shared", key=key)["json"], first)
|
||||
|
||||
def test_replay_still_checks_access_and_session(self):
|
||||
key = uuid4().hex
|
||||
self.client.message(self.alice, self.chat, "private", key=key)
|
||||
self.client.call("POST", self.path, 404, actor=self.eve,
|
||||
body={"text": "private"}, headers={"Idempotency-Key": key})
|
||||
self.client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.alice)
|
||||
self.client.call("POST", self.path, 401, actor=self.alice,
|
||||
body={"text": "private"}, headers={"Idempotency-Key": key})
|
||||
|
||||
def test_failure_rolls_back_message_and_key(self):
|
||||
key = "fault-" + uuid4().hex
|
||||
constraint = "test_reject_" + uuid4().hex[:12]
|
||||
self.sql("ALTER TABLE idempotency_keys ADD CONSTRAINT " + constraint
|
||||
+ " CHECK(request_key <> '" + key + "') NOT VALID")
|
||||
try:
|
||||
self.client.call("POST", self.path, 500, actor=self.alice,
|
||||
body={"text": "rollback"}, headers={"Idempotency-Key": key})
|
||||
self.assertEqual(self.history(), [])
|
||||
self.assertEqual(self.sql("SELECT count(*) FROM idempotency_keys WHERE request_key='" + key + "'"), "0")
|
||||
finally:
|
||||
self.sql("ALTER TABLE idempotency_keys DROP CONSTRAINT " + constraint)
|
||||
result = self.client.message(self.alice, self.chat, "rollback", key=key)["json"]
|
||||
self.assertEqual(self.client.message(self.alice, self.chat, "rollback", key=key)["json"], result)
|
||||
self.assertEqual(self.history(), [result])
|
||||
|
||||
def test_retention_and_expired_key_reuse(self):
|
||||
key = uuid4().hex
|
||||
first = self.client.message(self.alice, self.chat, "old", key=key)["json"]
|
||||
retained = self.sql("SELECT expires_at-created_at > INTERVAL '23 hours 59 minutes 59 seconds'"
|
||||
+ " FROM idempotency_keys WHERE request_key='" + key + "'")
|
||||
self.assertEqual(retained, "t")
|
||||
self.sql("UPDATE idempotency_keys SET expires_at=created_at + INTERVAL '1 microsecond'"
|
||||
+ " WHERE request_key='" + key + "'")
|
||||
second = self.client.message(self.alice, self.chat, "new", key=key)["json"]
|
||||
self.assertNotEqual(first["id"], second["id"])
|
||||
self.assertEqual(self.history(), [first, second])
|
||||
|
||||
def test_same_session_on_both_instances(self):
|
||||
responses = [self.client.call("GET", "/api/v1/users/me", actor=self.alice, schema="User")
|
||||
for _ in range(12)]
|
||||
self.assertEqual(len({item["headers"]["X-Instance-Id"] for item in responses}), 2)
|
||||
self.assertTrue(all(item["json"] == self.alice["user"] for item in responses))
|
||||
|
||||
def test_invalid_body_does_not_reserve_key(self):
|
||||
key = uuid4().hex
|
||||
self.client.call("POST", self.path, 400, actor=self.alice,
|
||||
body={"text": ""}, headers={"Idempotency-Key": key})
|
||||
result = self.client.message(self.alice, self.chat, "fixed", key=key)["json"]
|
||||
self.assertEqual(self.history(), [result])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,96 @@
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
from pathlib import Path
|
||||
import re
|
||||
import sys
|
||||
import unittest
|
||||
from uuid import uuid4
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
value = base64.b64encode((username + ":" + password).encode("utf-8")).decode("ascii")
|
||||
return {"Authorization": "Basic " + value}
|
||||
|
||||
|
||||
class SessionTests(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.client = Client(os.environ.get("BASE_URL", "http://127.0.0.1:8080"))
|
||||
self.actor = self.client.user("auth")
|
||||
|
||||
def register(self, password):
|
||||
body = {"username": "p_" + uuid4().hex[:20], "display_name": "Пароль", "password": password}
|
||||
user = self.client.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
|
||||
session = self.client.call("POST", "/api/v1/auth/sessions", 201,
|
||||
headers=basic(body["username"], password), schema="Session")["json"]
|
||||
self.assertEqual(session["user"], user)
|
||||
self.assertEqual(set(session), {"token", "token_type", "expires_at", "user"})
|
||||
self.assertTrue(re.fullmatch(r"[A-Za-z0-9_-]{43}", session["token"]), "Invalid token format")
|
||||
return body, session
|
||||
|
||||
def test_password_required_and_limits(self):
|
||||
source = self.actor["registration"]
|
||||
for password in ("x" * 11, "x" * 129, " " * 12, None, 123, True, "a" * 12 + "\x00"):
|
||||
body = {**source, "username": "p_" + uuid4().hex[:20], "password": password}
|
||||
self.client.call("POST", "/api/v1/users", 400, body=body)
|
||||
missing = {key: value for key, value in source.items() if key != "password"}
|
||||
self.client.call("POST", "/api/v1/users", 400, body=missing)
|
||||
raw = json.dumps({**source, "username": "p_" + uuid4().hex[:20], "password": "\ud800" * 12}).encode()
|
||||
self.client.call("POST", "/api/v1/users", 400, raw=raw, headers={"Content-Type": "application/json"})
|
||||
|
||||
def test_password_boundaries_unicode_colon_spaces(self):
|
||||
for password in ("x" * 12, "🙂" * 127 + ":", " Привет:пароль🙂 "):
|
||||
body, session = self.register(password)
|
||||
actor = {"id": session["user"]["id"], "token": session["token"]}
|
||||
self.client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
changed = password.strip() if password != password.strip() else password + "!"
|
||||
self.client.call("POST", "/api/v1/auth/sessions", 401,
|
||||
headers=basic(body["username"], changed))
|
||||
|
||||
def test_wrong_and_unknown_credentials(self):
|
||||
source = self.actor["registration"]
|
||||
wrong = self.client.call("POST", "/api/v1/auth/sessions", 401,
|
||||
headers=basic(source["username"], "wrong-password-123"))
|
||||
unknown = self.client.call("POST", "/api/v1/auth/sessions", 401,
|
||||
headers=basic("unknown_" + uuid4().hex[:12], source["password"]))
|
||||
self.assertEqual(wrong["json"]["error"]["message"], unknown["json"]["error"]["message"])
|
||||
self.assertEqual(wrong["headers"]["WWW-Authenticate"], 'Basic realm="messenger", charset="UTF-8"')
|
||||
|
||||
def test_malformed_basic_and_body(self):
|
||||
for value in ("", "Basic", "Basic !!!", "Bearer " + self.actor["token"],
|
||||
"Basic " + base64.b64encode(b"missing-colon").decode(),
|
||||
"Basic " + base64.b64encode(b"\xff:some-password").decode()):
|
||||
self.client.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": value})
|
||||
source = self.actor["registration"]
|
||||
self.client.call("POST", "/api/v1/auth/sessions", 400, body={},
|
||||
headers=basic(source["username"], source["password"]))
|
||||
|
||||
def test_only_bearer_identifies_user(self):
|
||||
source = self.actor["registration"]
|
||||
for value in ("", "Bearer", "Bearer bad", "Bearer " + "x" * 43,
|
||||
basic(source["username"], source["password"])["Authorization"]):
|
||||
self.client.call("GET", "/api/v1/users/me", 401, headers={"Authorization": value})
|
||||
self.client.call("GET", "/api/v1/users/me", 401, headers={"X-User-Id": self.actor["id"]})
|
||||
other = self.client.user("other")
|
||||
result = self.client.call("GET", "/api/v1/users/me", actor=self.actor,
|
||||
headers={"X-User-Id": other["id"]}, schema="User")
|
||||
self.assertEqual(result["json"]["id"], self.actor["id"])
|
||||
self.client.call("GET", "/api/v1/users/me", schema="User",
|
||||
headers={"Authorization": "bEaReR " + self.actor["token"]})
|
||||
|
||||
def test_logout_only_revokes_current_session(self):
|
||||
source = self.actor["registration"]
|
||||
second = self.client.call("POST", "/api/v1/auth/sessions", 201,
|
||||
headers=basic(source["username"], source["password"]), schema="Session")["json"]
|
||||
other_session = {"id": self.actor["id"], "token": second["token"]}
|
||||
self.client.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=self.actor)
|
||||
for method, path in (("GET", "/api/v1/users/me"), ("DELETE", "/api/v1/auth/sessions/current")):
|
||||
self.client.call(method, path, 401, actor=self.actor)
|
||||
self.client.call("GET", "/api/v1/users/me", actor=other_session, schema="User")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
Reference in New Issue
Block a user