forked from mtusi2026/mtusi2026lab6
Проверить сквозной контекст, отказы, SLO и требования уровня 4
This commit is contained in:
+35
@@ -0,0 +1,35 @@
|
|||||||
|
# Диагностика мессенджера №6
|
||||||
|
|
||||||
|
Стенд с синтетическими данными: API `http://127.0.0.1:8086`, Grafana `http://127.0.0.1:3006/d/messenger-lab6`. В Grafana доступен анонимный Viewer, административный пароль находится только в `secrets/grafana_password`. Внутренние порты хранилищ не публикуются. Время в сохранённых сигналах — UTC, в графиках эксперимента — секунды от начала.
|
||||||
|
|
||||||
|
Начните с dashboard, выберите интервал инцидента. В Explore доступны Prometheus, Loki, Tempo. Не начинайте с Docker logs: сначала запишите гипотезу по сохранённым сигналам, затем проверьте её состоянием контейнеров в `evidence/`.
|
||||||
|
|
||||||
|
## API
|
||||||
|
|
||||||
|
1. Проверьте долю отказов: `sum(rate(messenger_http_requests_total{status_class="5xx"}[30s])) / clamp_min(sum(rate(messenger_http_requests_total[30s])),0.001)`. Это бизнес-запросы, health исключён. 4xx не расходуют бюджет доступности.
|
||||||
|
2. Разложите duration по `route`, а также `messenger_db_pool_used` и `messenger_db_pool_waiting`. Счётчики показывают запросы, duration histogram — секунды. Высокая занятость pool и медленные/ошибочные SQL spans указывают на БД; медленный server span без медленного DB/S3 child требует проверки самого handler.
|
||||||
|
3. Найдите ошибки в Loki: `{service_name="messenger-api"} |= "http.completed" | json | status >= 500`. Из JSON возьмите `trace_id`, откройте его в Tempo. HTTP-клиент также получает `X-Trace-Id`; `X-Request-Id` связывает ошибку и лог.
|
||||||
|
4. Для исследованной блокировки таблицы messages ожидаются ошибочные SQL spans около двух секунд, server 503 и насыщение pool. Сравните с `evidence/incidents.json`: диагноз не должен опираться только на сам факт HTTP 503.
|
||||||
|
5. После устранения причины проверьте новые успешные сообщения, падение error ratio, отсутствие соответствующего alert в `/api/v1/alerts`. Resolved здесь означает исчезновение активного экземпляра alert; наружная доставка не настроена.
|
||||||
|
|
||||||
|
## Ready
|
||||||
|
|
||||||
|
1. Сравните `messenger_queue_depth` и `messenger_queue_oldest_seconds`. Это все незавершённые durable jobs из PostgreSQL, включая outbox/processing, а не только ready-сообщения RabbitMQ. Старейший возраст — секунды, глубина — jobs.
|
||||||
|
2. Проверьте `messenger_worker_busy` / `messenger_worker_capacity` и свежесть рядов. При остановке worker последний gauge может некоторое время оставаться в scrape: отсутствие свежих `job.processed` и рост backlog существеннее старого нуля busy.
|
||||||
|
3. В Loki: `{service_name="messenger-worker"} |= "job.processed" | json`. `outcome=retry` при живых worker требует просмотра S3/DB child spans. Отсутствие consumer spans и логов при продолжающихся `job.published` указывает на неработающих consumers.
|
||||||
|
4. Возьмите trace ID upload и найдите `attachment.publish` → `attachment.consume` → `attachment.transform_and_publish`, S3 и SQL. Повторы — новые producer/consumer spans в том же trace, с номером управляемой попытки в логе. Дубликат может дать `job.duplicate`, не новый результат.
|
||||||
|
5. Восстановите только соответствующие контейнеры №6. В тестах используется `docker start` по ID, найденным через `docker compose -p lyakhonov-lab6 ps -aq worker`: Compose 2.40 может при `start worker` также запустить зависимости и преждевременно снять отдельный отказ S3.
|
||||||
|
6. Проверьте уменьшение backlog до нуля, ready для каждого принятого ID и доступность всех вариантов, затем resolved QueueLag/ReadyBurn. Один HTTP 202 этого не доказывает.
|
||||||
|
|
||||||
|
## Telemetry backend
|
||||||
|
|
||||||
|
Если бизнес-ошибок нет, а trace отсутствует, проверьте `otelcol_exporter_queue_size`, `otelcol_exporter_send_failed_spans_total` и доступность Tempo. Не диагностируйте отсутствие trace как отсутствие обработки задания. Collector ограничен 256 MiB, memory limiter 160 MiB, очередь каждого OTLP exporter — 128 batch-запросов; после 15 s исчерпываются повторы и часть telemetry теряется. Источник бизнес-истины — PostgreSQL/S3. Grafana и Collector не заменяют эти хранилища.
|
||||||
|
|
||||||
|
## Учебные SLO и burn rate
|
||||||
|
|
||||||
|
- API: ≥99% бизнес HTTP-запросов без 5xx в скользящем окне 2 min. Сетевые ошибки до API этим SLI не покрываются и отдельно считаются генератором.
|
||||||
|
- Pipeline: ≥95% принятых вложений публикуют ready за ≤5 s, по когорте acceptance за 2 min. Когорта становится оцениваемой через 5 s; failed и ещё не ready считаются bad. Это исключает сокрытие зависших jobs в histogram только завершённых операций.
|
||||||
|
- API burn = error ratio / 0.01. Fast: >14.4 одновременно за 15 s и 1 min, `for: 15s`; Slow: >6 за 30 s и 2 min, `for: 30s`.
|
||||||
|
- Ready burn = bad/total / 0.05. Fast: >6 за 15 s и 1 min, `for: 15s`; Slow: >3 за 30 s и 2 min, `for: 30s`.
|
||||||
|
|
||||||
|
Это ускоренная учебная модель, а не перенесённые без обоснования production пороги 30-дневного SLO. 5 s выбраны как проверяемый локальный бюджет для fixture 320×200 при свободных worker; 60 s публичного smoke — отдельный timeout проверки. В малой когорте один файл существенно меняет ratio. При отсутствии новых запросов burn-alert не заменяет uptime probe, при отсутствии новых upload — QueueLag. Нулевой знаменатель не создаёт искусственного нарушения. Два окна и `for` должны подавлять четырёхсекундный всплеск, а длительное нарушение — обнаруживаться; результаты и ограничения см. REPORT.md.
|
||||||
+3
-3
@@ -1,7 +1,7 @@
|
|||||||
name: lyakhonov-lab6
|
name: lyakhonov-lab6
|
||||||
|
|
||||||
x-app: &app
|
x-app: &app
|
||||||
image: lyakhonov-messenger:lab6
|
image: ${APP_IMAGE:-lyakhonov-messenger:lab6}
|
||||||
environment:
|
environment:
|
||||||
OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318
|
OTEL_EXPORTER_OTLP_ENDPOINT: http://otel-collector:4318
|
||||||
TELEMETRY_ENABLED: ${TELEMETRY_ENABLED:-1}
|
TELEMETRY_ENABLED: ${TELEMETRY_ENABLED:-1}
|
||||||
@@ -116,7 +116,7 @@ services:
|
|||||||
cpus: 0.25
|
cpus: 0.25
|
||||||
mem_limit: 128m
|
mem_limit: 128m
|
||||||
s3:
|
s3:
|
||||||
image: lyakhonov-storage:lab6
|
image: ${S3_IMAGE:-lyakhonov-storage:lab6}
|
||||||
build:
|
build:
|
||||||
context: .
|
context: .
|
||||||
dockerfile: Dockerfile.s3
|
dockerfile: Dockerfile.s3
|
||||||
@@ -129,7 +129,7 @@ services:
|
|||||||
cpus: 1.0
|
cpus: 1.0
|
||||||
mem_limit: 768m
|
mem_limit: 768m
|
||||||
bucket-init:
|
bucket-init:
|
||||||
image: lyakhonov-storage:lab6
|
image: ${S3_IMAGE:-lyakhonov-storage:lab6}
|
||||||
pull_policy: never
|
pull_policy: never
|
||||||
entrypoint: [/bin/sh, /bootstrap/bucket.sh]
|
entrypoint: [/bin/sh, /bootstrap/bucket.sh]
|
||||||
secrets: [s3_root_user, s3_root_password, s3_access_key, s3_secret_key]
|
secrets: [s3_root_user, s3_root_password, s3_access_key, s3_secret_key]
|
||||||
|
|||||||
@@ -0,0 +1,414 @@
|
|||||||
|
{
|
||||||
|
"commit": "71254d3389dc55d59405189016ecc8d63339c101",
|
||||||
|
"whoami": "win-24dt7t3o465\\lyakhonov",
|
||||||
|
"docker_context": "desktop-linux",
|
||||||
|
"docker_version": {
|
||||||
|
"Client": {
|
||||||
|
"Version": "28.5.1",
|
||||||
|
"ApiVersion": "1.51",
|
||||||
|
"DefaultAPIVersion": "1.51",
|
||||||
|
"GitCommit": "e180ab8",
|
||||||
|
"GoVersion": "go1.24.8",
|
||||||
|
"Os": "windows",
|
||||||
|
"Arch": "amd64",
|
||||||
|
"BuildTime": "Wed Oct 8 12:19:16 2025",
|
||||||
|
"Context": "desktop-linux"
|
||||||
|
},
|
||||||
|
"Server": {
|
||||||
|
"Platform": {
|
||||||
|
"Name": "Docker Desktop 4.49.0 (208700)"
|
||||||
|
},
|
||||||
|
"Components": [
|
||||||
|
{
|
||||||
|
"Name": "Engine",
|
||||||
|
"Version": "28.5.1",
|
||||||
|
"Details": {
|
||||||
|
"ApiVersion": "1.51",
|
||||||
|
"Arch": "amd64",
|
||||||
|
"BuildTime": "Wed Oct 8 12:17:24 2025",
|
||||||
|
"Experimental": "false",
|
||||||
|
"GitCommit": "f8215cc",
|
||||||
|
"GoVersion": "go1.24.8",
|
||||||
|
"KernelVersion": "6.6.87.2-microsoft-standard-WSL2",
|
||||||
|
"MinAPIVersion": "1.24",
|
||||||
|
"Os": "linux"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "containerd",
|
||||||
|
"Version": "1.7.27",
|
||||||
|
"Details": {
|
||||||
|
"GitCommit": "05044ec0a9a75232cad458027ca83437aae3f4da"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "runc",
|
||||||
|
"Version": "1.2.5",
|
||||||
|
"Details": {
|
||||||
|
"GitCommit": "v1.2.5-0-g59923ef"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"Name": "docker-init",
|
||||||
|
"Version": "0.19.0",
|
||||||
|
"Details": {
|
||||||
|
"GitCommit": "de40ad0"
|
||||||
|
}
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"Version": "28.5.1",
|
||||||
|
"ApiVersion": "1.51",
|
||||||
|
"MinAPIVersion": "1.24",
|
||||||
|
"GitCommit": "f8215cc",
|
||||||
|
"GoVersion": "go1.24.8",
|
||||||
|
"Os": "linux",
|
||||||
|
"Arch": "amd64",
|
||||||
|
"KernelVersion": "6.6.87.2-microsoft-standard-WSL2",
|
||||||
|
"BuildTime": "2025-10-08T12:17:24.000000000+00:00"
|
||||||
|
}
|
||||||
|
},
|
||||||
|
"docker_resources": "16 CPUs 8126656512 bytes",
|
||||||
|
"compose_version": "Docker Compose version v2.40.3-desktop.1",
|
||||||
|
"containers": [
|
||||||
|
{
|
||||||
|
"id": "c321063cfe0dc6319e0cb3704f3902e5387e8e19f4c7c21b8c89ec54af2e99cb",
|
||||||
|
"service": "api",
|
||||||
|
"started_at": "2026-11-27T13:46:28.716162825Z",
|
||||||
|
"status": "running",
|
||||||
|
"memory_limit": 671088640,
|
||||||
|
"nano_cpus": 500000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "c200522d3266343ce6069346b58a6f645a4ed9129fc6be4503e7443b475033b9",
|
||||||
|
"service": "api",
|
||||||
|
"started_at": "2026-11-27T13:46:36.77308908Z",
|
||||||
|
"status": "running",
|
||||||
|
"memory_limit": 671088640,
|
||||||
|
"nano_cpus": 500000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "67250f581ff773c0f5daec64696792f6ef7fbbafed2fcc937bcd45edd96d28ad",
|
||||||
|
"service": "broker",
|
||||||
|
"started_at": "2026-11-27T13:45:10.97424342Z",
|
||||||
|
"status": "running",
|
||||||
|
"memory_limit": 536870912,
|
||||||
|
"nano_cpus": 750000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "a132f04f36935cdb0d11035f589a5cb4e5838538f184e7a32f0dcf6f99e18ef5",
|
||||||
|
"service": "bucket-init",
|
||||||
|
"started_at": "2026-11-27T13:47:27.333872276Z",
|
||||||
|
"status": "running",
|
||||||
|
"memory_limit": 134217728,
|
||||||
|
"nano_cpus": 250000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "8b2ac7682adccd6538de7c20f623ae01dd138898cc3ff0d3fffa6bd04c5870ae",
|
||||||
|
"service": "db",
|
||||||
|
"started_at": "2026-11-27T13:45:10.139067021Z",
|
||||||
|
"status": "running",
|
||||||
|
"memory_limit": 536870912,
|
||||||
|
"nano_cpus": 1000000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "c37c4520dde0281588280092f7b3eb0f666cfdc0c907c18071f4c257c608907d",
|
||||||
|
"service": "diagnostics",
|
||||||
|
"started_at": "2026-11-27T13:44:04.371189151Z",
|
||||||
|
"status": "running",
|
||||||
|
"memory_limit": 134217728,
|
||||||
|
"nano_cpus": 250000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "b01cf07496d8f1d7436aa7d6a13278bb1c6543bc1ed4c1e879aed3675a524f91",
|
||||||
|
"service": "dispatcher",
|
||||||
|
"started_at": "2026-11-27T13:45:10.274744107Z",
|
||||||
|
"status": "running",
|
||||||
|
"memory_limit": 268435456,
|
||||||
|
"nano_cpus": 500000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "fe879ab1e1e5a4d7761a03ab03e08aa614cf3194555d3362ba5a54a8e1ec8eba",
|
||||||
|
"service": "grafana",
|
||||||
|
"started_at": "2026-11-27T13:41:04.086803753Z",
|
||||||
|
"status": "running",
|
||||||
|
"memory_limit": 402653184,
|
||||||
|
"nano_cpus": 500000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "7eead7f9124d5e42bad9d977aeeaf851f52075586b23462e94b81e64c4a13525",
|
||||||
|
"service": "lb",
|
||||||
|
"started_at": "2026-11-27T13:45:09.878536759Z",
|
||||||
|
"status": "running",
|
||||||
|
"memory_limit": 134217728,
|
||||||
|
"nano_cpus": 500000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "d7eaf54f7dfa6ce43ca84e7630c357ba834d13826a07f1656d532bbd1aa8133d",
|
||||||
|
"service": "loki",
|
||||||
|
"started_at": "2026-11-27T13:41:03.943038494Z",
|
||||||
|
"status": "running",
|
||||||
|
"memory_limit": 402653184,
|
||||||
|
"nano_cpus": 500000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "3460fb4f99e34f2afc8cebf95563f121bd458fb983bacc35a2fb694d5580770b",
|
||||||
|
"service": "migrate",
|
||||||
|
"started_at": "2026-11-27T13:47:27.835587689Z",
|
||||||
|
"status": "exited",
|
||||||
|
"memory_limit": 671088640,
|
||||||
|
"nano_cpus": 500000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "eb8394f106efd30c4ef99094c79301d866a8533050b8eacf28e0e08099331302",
|
||||||
|
"service": "otel-collector",
|
||||||
|
"started_at": "2026-11-27T13:41:03.918588049Z",
|
||||||
|
"status": "running",
|
||||||
|
"memory_limit": 268435456,
|
||||||
|
"nano_cpus": 500000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "888ff5ffe6db73757cc652ce5376c3c9a78df120683edf2be120c17e7967e058",
|
||||||
|
"service": "prometheus",
|
||||||
|
"started_at": "2026-11-27T13:44:07.268964594Z",
|
||||||
|
"status": "running",
|
||||||
|
"memory_limit": 402653184,
|
||||||
|
"nano_cpus": 500000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "db034935279f969cd150b4fbe32817cf1ae334820e5e5e9d1cd7e7939bcf8dbb",
|
||||||
|
"service": "redis",
|
||||||
|
"started_at": "2026-11-27T13:45:09.601677028Z",
|
||||||
|
"status": "running",
|
||||||
|
"memory_limit": 134217728,
|
||||||
|
"nano_cpus": 250000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "c24794f0b24a27553c978dfd55459a02784da6f637ef8c69b12b4b9cb8cac555",
|
||||||
|
"service": "s3",
|
||||||
|
"started_at": "2026-11-27T13:45:09.53213622Z",
|
||||||
|
"status": "running",
|
||||||
|
"memory_limit": 805306368,
|
||||||
|
"nano_cpus": 1000000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "121813ef2b200ce213610c1d4d3d3c35af5203e8fe586bc070a231e51e01be81",
|
||||||
|
"service": "staging-cleaner",
|
||||||
|
"started_at": "2026-11-27T13:45:10.571681425Z",
|
||||||
|
"status": "running",
|
||||||
|
"memory_limit": 268435456,
|
||||||
|
"nano_cpus": 250000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "d89bc7eca7813a5b8eff9c5c37497bf7feb0c1ad7251797d0f99af5f9eee2337",
|
||||||
|
"service": "tempo",
|
||||||
|
"started_at": "2026-11-27T13:41:04.011042724Z",
|
||||||
|
"status": "running",
|
||||||
|
"memory_limit": 402653184,
|
||||||
|
"nano_cpus": 500000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "8f4bf0c0b97760df71ab60ecddb180a9a3aedca3a445c14c8925a1e0e613d818",
|
||||||
|
"service": "worker",
|
||||||
|
"started_at": "2026-11-27T13:45:10.016773257Z",
|
||||||
|
"status": "exited",
|
||||||
|
"memory_limit": 805306368,
|
||||||
|
"nano_cpus": 750000000
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "ca6de9150e29d58d0d60768e3ebaec6e6ed7fe56a0f1650dff31d8681870d266",
|
||||||
|
"service": "worker",
|
||||||
|
"started_at": "2026-11-27T13:45:10.503836556Z",
|
||||||
|
"status": "exited",
|
||||||
|
"memory_limit": 805306368,
|
||||||
|
"nano_cpus": 750000000
|
||||||
|
}
|
||||||
|
],
|
||||||
|
"other_containers": [
|
||||||
|
{
|
||||||
|
"id": "e36e30c0bc23ffdc3c2c4fe39b57ea98597764dfa313c509bd1734d74b801b44",
|
||||||
|
"project": "lyakhonov-lab5",
|
||||||
|
"started_at": "2026-11-27T13:46:55.696081044Z",
|
||||||
|
"state": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "b3f8a331a59832dde80002af9f29c5893381e780803283476c687168ede15842",
|
||||||
|
"project": "lyakhonov-lab5",
|
||||||
|
"started_at": "2026-11-20T04:00:04.137137202Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "1f724278797561aea476251a8902eac6377039c3e30cbc336d501409af118ae2",
|
||||||
|
"project": "lyakhonov-lab5",
|
||||||
|
"started_at": "2026-11-27T13:47:08.572881915Z",
|
||||||
|
"state": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "bdedd08309bb0db9dc94235a148fc0938180449b1431059178488d0c6f985049",
|
||||||
|
"project": "lyakhonov-lab5",
|
||||||
|
"started_at": "2026-11-27T13:46:52.646440477Z",
|
||||||
|
"state": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "23b814fb71a813bedb09712be57c736e19460c2c25d2b2b4b0e66facb0bfdab9",
|
||||||
|
"project": "lyakhonov-lab5",
|
||||||
|
"started_at": "2026-11-27T13:47:17.724596809Z",
|
||||||
|
"state": "running"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "a0acb99b68a1f803792742460827528137ac3ab96ec76a68de550f930a4a9368",
|
||||||
|
"project": "lyakhonov-lab5",
|
||||||
|
"started_at": "2026-11-20T04:00:23.843924506Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "39b8b11f3c7c9e1c3fb778e780dc8d123e4b955669ddee8c85420eefcb3abaca",
|
||||||
|
"project": "lyakhonov-lab5",
|
||||||
|
"started_at": "2026-11-20T03:59:01.96581278Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "934fcb61b954722ec6f9d3ce84d3399f5a35a30e8368e0ed44a939319ea9ff4f",
|
||||||
|
"project": "lyakhonov-lab5",
|
||||||
|
"started_at": "2026-11-20T03:58:30.862509137Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "fdca00783fcb86e75d3ec4c84494d1571548333d585459191b78992f707729ad",
|
||||||
|
"project": "lyakhonov-lab5",
|
||||||
|
"started_at": "2026-11-20T03:59:01.428198308Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "10408d41f3b50b0a5e8ad4e21b849fa97548c03f4a535b27c8c919163b9c30b2",
|
||||||
|
"project": "lyakhonov-lab5",
|
||||||
|
"started_at": "2026-11-20T03:58:30.504381937Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "b94a25ac1bb3df998e3d0c27beae4b97d655bbc0a7ae520bd60c736cd40462c9",
|
||||||
|
"project": "lyakhonov-lab5",
|
||||||
|
"started_at": "2026-11-20T03:58:31.88055044Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "c3962c31749b802835f909ce1b4efbe34149e88d9bc678ca3b82f9fdbcc97af1",
|
||||||
|
"project": "lyakhonov-lab5",
|
||||||
|
"started_at": "2026-11-20T03:58:30.614258194Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "0b09dce985685e130ed8774a277a3ff254e8a633ff1dfeed7fd2daf80b78c4e8",
|
||||||
|
"project": "lyakhonov-lab5",
|
||||||
|
"started_at": "2026-11-20T03:58:31.091098179Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "99f4403277a732ba8c6512634bdecbce168705cdfdf9edf83420133109647544",
|
||||||
|
"project": "lyakhonov-lab4",
|
||||||
|
"started_at": "2026-10-30T14:46:59.269605492Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "7523f15dc398abffadfc62383a4976e33e0f25220ecb983d059002bd1ac9563b",
|
||||||
|
"project": "lyakhonov-lab4",
|
||||||
|
"started_at": "2026-10-30T14:49:08.477185174Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "af9f952b1304310adb0cfd0620293050d2b1eb3a4e4b7395bd41d41df7730016",
|
||||||
|
"project": "lyakhonov-lab4",
|
||||||
|
"started_at": "2026-10-30T14:46:59.471200143Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "07a9b492d60425b059661cfa7075640b85bd6f5c18831e2b3eb448166b29a7ee",
|
||||||
|
"project": "lyakhonov-lab4",
|
||||||
|
"started_at": "2026-10-30T14:49:07.055892766Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "5d273b8dcb0cc6f4acfe44b78f189e2168eeb212103db0f18dcd5f6fbd3b3134",
|
||||||
|
"project": "lyakhonov-lab4",
|
||||||
|
"started_at": "2026-10-30T14:49:07.517707083Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "a6482b44d70a2031a2563b1b72d955435125453a48e95087464775c918801941",
|
||||||
|
"project": "lyakhonov-lab4",
|
||||||
|
"started_at": "2026-10-30T14:45:43.938532131Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "e9682a892ad30d5becf1fda8abbc16770aed81f261b0843f9cb047b5085baf76",
|
||||||
|
"project": "lyakhonov-lab4",
|
||||||
|
"started_at": "2026-10-30T14:45:44.017393725Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "10138b5c0beefe8a15a6679fdad81ddac663eea21e8f63bf3ca03545c2558f20",
|
||||||
|
"project": "lyakhonov-lab4",
|
||||||
|
"started_at": "2026-10-30T14:45:44.07685361Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "68997bbba33bdd4bed3093f2f7c127856cba5237c46511aad9a35945bdcf535f",
|
||||||
|
"project": "lyakhonov-lab4",
|
||||||
|
"started_at": "2026-10-30T14:45:43.846575438Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "83b50e889353134bf5f1d215a2bc66e8f921a2de8957f3cb176cea255035f17f",
|
||||||
|
"project": "lyakhonov-lab3",
|
||||||
|
"started_at": "2026-10-23T16:13:46.65851457Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "1ff12291d9d61efbb3795aab208fdadff718cb7f6470b4c1094ee76f9acf2924",
|
||||||
|
"project": "lyakhonov-lab3",
|
||||||
|
"started_at": "2026-10-23T16:13:47.058554979Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "1031c94e3574d1843bb615df3426f8769100f54cd862018bb597d54d2401387b",
|
||||||
|
"project": "lyakhonov-lab3",
|
||||||
|
"started_at": "2026-10-23T16:07:54.077571177Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "4577101bc498d9f217ad682ab8af2a4688f7772287a1755eab603ecc946ce2b7",
|
||||||
|
"project": "lyakhonov-lab3",
|
||||||
|
"started_at": "2026-10-23T16:08:02.041383013Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "f2cdcc232751e2c2400763e935897851aca1399824ed751ec96a51180282a207",
|
||||||
|
"project": "lyakhonov-lab3",
|
||||||
|
"started_at": "2026-10-23T16:08:02.306518292Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "889db8e55eb20c99fbe462f3d407763760cc40f0a053b144dcb9f6d13f6255c8",
|
||||||
|
"project": "lyakhonov-lab3",
|
||||||
|
"started_at": "2026-10-23T16:08:02.163804371Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "1d0681eaf75f9c0ed9e48f2529ab671d72b528c4a621e44b68199b1437387d7c",
|
||||||
|
"project": "lyakhonov-lab2",
|
||||||
|
"started_at": "2026-10-09T11:26:57.052800221Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "8bf3b717f757d92d742f440ee37fa2f7a304ca0b21912dcb5e02b9a7d9505a93",
|
||||||
|
"project": "lyakhonov-lab2",
|
||||||
|
"started_at": "2026-10-09T11:25:00.307001994Z",
|
||||||
|
"state": "exited"
|
||||||
|
},
|
||||||
|
{
|
||||||
|
"id": "92075e2bbf03ab04a43dccc4b171554af2781687127bd343453182cdcf3fb0ec",
|
||||||
|
"project": "lyakhonov-lab2",
|
||||||
|
"started_at": "2026-10-09T11:25:00.409548723Z",
|
||||||
|
"state": "exited"
|
||||||
|
}
|
||||||
|
]
|
||||||
|
}
|
||||||
@@ -0,0 +1,5 @@
|
|||||||
|
..
|
||||||
|
----------------------------------------------------------------------
|
||||||
|
Ran 2 tests in 0.223s
|
||||||
|
|
||||||
|
OK
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
Traceback (most recent call last):
|
||||||
|
File "C:\Users\User\Desktop\vysoko-nagr 6\student-tests\incidents.py", line 100, in <module>
|
||||||
|
if __name__=='__main__':main()
|
||||||
|
~~~~^^
|
||||||
|
File "C:\Users\User\Desktop\vysoko-nagr 6\student-tests\incidents.py", line 44, in main
|
||||||
|
check(retried,'no managed retry observed while S3 stopped')
|
||||||
|
~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
File "C:\Users\User\Desktop\vysoko-nagr 6\tests\client.py", line 24, in check
|
||||||
|
raise Failure(message)
|
||||||
|
client.Failure: no managed retry observed while S3 stopped
|
||||||
@@ -0,0 +1,10 @@
|
|||||||
|
Traceback (most recent call last):
|
||||||
|
File "C:\Users\User\Desktop\vysoko-nagr 6\student-tests\incidents.py", line 90, in <module>
|
||||||
|
if __name__=='__main__':main()
|
||||||
|
~~~~^^
|
||||||
|
File "C:\Users\User\Desktop\vysoko-nagr 6\student-tests\incidents.py", line 39, in main
|
||||||
|
check(sum(s['kind']=='SPAN_KIND_CONSUMER' for s in spans)>=2,'retry trace missing')
|
||||||
|
~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
File "C:\Users\User\Desktop\vysoko-nagr 6\tests\client.py", line 24, in check
|
||||||
|
raise Failure(message)
|
||||||
|
client.Failure: retry trace missing
|
||||||
@@ -0,0 +1,15 @@
|
|||||||
|
Traceback (most recent call last):
|
||||||
|
File "C:\Users\User\Desktop\vysoko-nagr 6\student-tests\incidents.py", line 116, in <module>
|
||||||
|
if __name__=='__main__':main()
|
||||||
|
~~~~^^
|
||||||
|
File "C:\Users\User\Desktop\vysoko-nagr 6\student-tests\incidents.py", line 60, in main
|
||||||
|
wait_result(response['json'])
|
||||||
|
~~~~~~~~~~~^^^^^^^^^^^^^^^^^^
|
||||||
|
File "C:\Users\User\Desktop\vysoko-nagr 6\student-tests\incidents.py", line 18, in wait_result
|
||||||
|
response=c.call('GET','/api/v1/attachments/'+att['id'],[200,503],actor=alice,schema='Attachment')
|
||||||
|
File "C:\Users\User\Desktop\vysoko-nagr 6\tests\client.py", line 133, in call
|
||||||
|
check(bool(rh.get('X-Request-Id')), 'missing X-Request-Id')
|
||||||
|
~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
File "C:\Users\User\Desktop\vysoko-nagr 6\tests\client.py", line 24, in check
|
||||||
|
raise Failure(message)
|
||||||
|
client.Failure: missing X-Request-Id
|
||||||
@@ -0,0 +1,2 @@
|
|||||||
|
PASS: two ready API instances, healthy DB/broker, required background containers running
|
||||||
|
PASS: worker lag, S3 retry context, DB outage, telemetry backend outage and recovery
|
||||||
@@ -0,0 +1,14 @@
|
|||||||
|
Traceback (most recent call last):
|
||||||
|
File "C:\Users\User\Desktop\vysoko-nagr 6\student-tests\incidents.py", line 100, in <module>
|
||||||
|
File "C:\Users\User\Desktop\vysoko-nagr 6\student-tests\incidents.py", line 46, in main
|
||||||
|
c.wait_ready(alice,response['json'])
|
||||||
|
~~~~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
File "C:\Users\User\Desktop\vysoko-nagr 6\tests\client.py", line 196, in wait_ready
|
||||||
|
att = self.call('GET','/api/v1/attachments/'+att['id'],actor=actor,schema='Attachment')['json']
|
||||||
|
~~~~~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
File "C:\Users\User\Desktop\vysoko-nagr 6\tests\client.py", line 132, in call
|
||||||
|
check(status in allowed, method + ' ' + path.split('?')[0] + ': expected ' + str(allowed) + ', received ' + str(status))
|
||||||
|
~~~~~^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
||||||
|
File "C:\Users\User\Desktop\vysoko-nagr 6\tests\client.py", line 24, in check
|
||||||
|
raise Failure(message)
|
||||||
|
client.Failure: GET /api/v1/attachments/d706a90b-8a94-4d37-87a7-08bb11b54739: expected [200], received 503
|
||||||
File diff suppressed because it is too large
Load Diff
@@ -0,0 +1,4 @@
|
|||||||
|
PASS: two ready API instances, healthy DB/broker, required background containers running
|
||||||
|
PASS: two ready API instances, healthy DB/broker, required background containers running
|
||||||
|
PASS: two ready API instances, healthy DB/broker, required background containers running
|
||||||
|
PASS: persistence, public failover twice, each API stopped separately
|
||||||
File diff suppressed because it is too large
Load Diff
+518
-16791
File diff suppressed because it is too large
Load Diff
+14
-14
@@ -20,42 +20,42 @@ groups:
|
|||||||
summary: Unfinished job age >10s; inspect worker busy/capacity and consume logs
|
summary: Unfinished job age >10s; inspect worker busy/capacity and consume logs
|
||||||
runbook: RUNBOOK.md
|
runbook: RUNBOOK.md
|
||||||
- alert: APIBurnFast
|
- alert: APIBurnFast
|
||||||
expr: (sum(rate(messenger_http_requests_total{status_class="5xx"}[30s])) / clamp_min(sum(rate(messenger_http_requests_total[30s])),0.001)
|
expr: (sum(rate(messenger_http_requests_total{status_class="5xx"}[15s])) / clamp_min(sum(rate(messenger_http_requests_total[15s])),0.001)
|
||||||
/ 0.01 > 14.4) and (sum(rate(messenger_http_requests_total{status_class="5xx"}[2m]))
|
/ 0.01 > 14.4) and (sum(rate(messenger_http_requests_total{status_class="5xx"}[1m]))
|
||||||
/ clamp_min(sum(rate(messenger_http_requests_total[2m])),0.001) / 0.01 > 14.4)
|
/ clamp_min(sum(rate(messenger_http_requests_total[1m])),0.001) / 0.01 > 14.4)
|
||||||
for: 15s
|
for: 15s
|
||||||
labels:
|
labels:
|
||||||
severity: critical
|
severity: critical
|
||||||
annotations:
|
annotations:
|
||||||
summary: API budget burn >14.4 in 30s AND 2m
|
summary: API budget burn >14.4 in 15s AND 1m
|
||||||
runbook: RUNBOOK.md#api
|
runbook: RUNBOOK.md#api
|
||||||
- alert: ReadyBurnFast
|
- alert: ReadyBurnFast
|
||||||
expr: (sum(messenger_ready_window_bad{window="30s"}) / clamp_min(sum(messenger_ready_window_total{window="30s"}),1)
|
expr: (sum(messenger_ready_window_bad{window="15s"}) / clamp_min(sum(messenger_ready_window_total{window="15s"}),1)
|
||||||
/ 0.05 > 6) and (sum(messenger_ready_window_bad{window="2m"}) / clamp_min(sum(messenger_ready_window_total{window="2m"}),1)
|
/ 0.05 > 6) and (sum(messenger_ready_window_bad{window="1m"}) / clamp_min(sum(messenger_ready_window_total{window="1m"}),1)
|
||||||
/ 0.05 > 6)
|
/ 0.05 > 6)
|
||||||
for: 15s
|
for: 15s
|
||||||
labels:
|
labels:
|
||||||
severity: critical
|
severity: critical
|
||||||
annotations:
|
annotations:
|
||||||
summary: Time-to-ready budget burn in 30s AND 2m, unfinished/failed included
|
summary: Time-to-ready budget burn in 15s AND 1m, unfinished/failed included
|
||||||
runbook: RUNBOOK.md#ready
|
runbook: RUNBOOK.md#ready
|
||||||
- alert: APIBurnSlow
|
- alert: APIBurnSlow
|
||||||
expr: (sum(rate(messenger_http_requests_total{status_class="5xx"}[1m])) / clamp_min(sum(rate(messenger_http_requests_total[1m])),0.001)
|
expr: (sum(rate(messenger_http_requests_total{status_class="5xx"}[30s])) / clamp_min(sum(rate(messenger_http_requests_total[30s])),0.001)
|
||||||
/ 0.01 > 6) and (sum(rate(messenger_http_requests_total{status_class="5xx"}[5m]))
|
/ 0.01 > 6) and (sum(rate(messenger_http_requests_total{status_class="5xx"}[2m]))
|
||||||
/ clamp_min(sum(rate(messenger_http_requests_total[5m])),0.001) / 0.01 > 6)
|
/ clamp_min(sum(rate(messenger_http_requests_total[2m])),0.001) / 0.01 > 6)
|
||||||
for: 30s
|
for: 30s
|
||||||
labels:
|
labels:
|
||||||
severity: critical
|
severity: critical
|
||||||
annotations:
|
annotations:
|
||||||
summary: API budget burn >6 in 1m AND 5m
|
summary: API budget burn >6 in 30s AND 2m
|
||||||
runbook: RUNBOOK.md#api
|
runbook: RUNBOOK.md#api
|
||||||
- alert: ReadyBurnSlow
|
- alert: ReadyBurnSlow
|
||||||
expr: (sum(messenger_ready_window_bad{window="1m"}) / clamp_min(sum(messenger_ready_window_total{window="1m"}),1)
|
expr: (sum(messenger_ready_window_bad{window="30s"}) / clamp_min(sum(messenger_ready_window_total{window="30s"}),1)
|
||||||
/ 0.05 > 3) and (sum(messenger_ready_window_bad{window="5m"}) / clamp_min(sum(messenger_ready_window_total{window="5m"}),1)
|
/ 0.05 > 3) and (sum(messenger_ready_window_bad{window="2m"}) / clamp_min(sum(messenger_ready_window_total{window="2m"}),1)
|
||||||
/ 0.05 > 3)
|
/ 0.05 > 3)
|
||||||
for: 30s
|
for: 30s
|
||||||
labels:
|
labels:
|
||||||
severity: critical
|
severity: critical
|
||||||
annotations:
|
annotations:
|
||||||
summary: Time-to-ready budget burn in 1m AND 5m, unfinished/failed included
|
summary: Time-to-ready budget burn in 30s AND 2m, unfinished/failed included
|
||||||
runbook: RUNBOOK.md#ready
|
runbook: RUNBOOK.md#ready
|
||||||
|
|||||||
@@ -0,0 +1,50 @@
|
|||||||
|
"""Preserved course materials, local author identities and absence of local secrets."""
|
||||||
|
import hashlib
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import re
|
||||||
|
import subprocess
|
||||||
|
|
||||||
|
ROOT=Path(__file__).resolve().parents[1]
|
||||||
|
BASE='470d9d6'
|
||||||
|
|
||||||
|
|
||||||
|
def git(*args,cwd=ROOT):return subprocess.check_output(['git',*args],cwd=cwd)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
original=git('ls-tree','-r','--name-only',BASE).decode().splitlines()
|
||||||
|
protected=[p for p in original if p!='REPORT.md']
|
||||||
|
changed=[]
|
||||||
|
for name in protected:
|
||||||
|
expected=git('show',BASE+':'+name).replace(b'\r\n',b'\n')
|
||||||
|
actual=(ROOT/name).read_bytes().replace(b'\r\n',b'\n')
|
||||||
|
if expected!=actual:changed.append(name)
|
||||||
|
tracked=git('ls-files','-z').decode().split('\0')
|
||||||
|
forbidden=[p for p in tracked if p.startswith(('secrets/','.env','data/','volumes/')) and p!='.env.example']
|
||||||
|
local_secrets=[p.read_bytes().strip() for p in (ROOT/'secrets').glob('*') if p.is_file() and p.stat().st_size>8]
|
||||||
|
leaks=[]
|
||||||
|
for name in tracked:
|
||||||
|
if not name or not (ROOT/name).is_file():continue
|
||||||
|
content=(ROOT/name).read_bytes()
|
||||||
|
if any(secret in content for secret in local_secrets):leaks.append(name)
|
||||||
|
if b'-----BEGIN PRIVATE KEY-----' in content:leaks.append(name)
|
||||||
|
identities=git('log',BASE+'..HEAD','--format=%H|%an|%ae|%cn|%ce').decode().splitlines()
|
||||||
|
invalid=[line for line in identities if line.split('|')[1:]!=['Sergey Lyakhonov','lyserg119@gmail.com','Sergey Lyakhonov','lyserg119@gmail.com']]
|
||||||
|
previous={}
|
||||||
|
for lab in (4,5):
|
||||||
|
folder=ROOT.parent/f'vysoko-nagr {lab}'
|
||||||
|
previous[str(lab)]={'head':git('rev-parse','HEAD',cwd=folder).decode().strip(),
|
||||||
|
'status':git('status','--porcelain',cwd=folder).decode(),'branch':git('branch','--show-current',cwd=folder).decode().strip()}
|
||||||
|
result={'protected_count':len(protected),'changed_originals':changed,'forbidden_paths':forbidden,
|
||||||
|
'secret_leaks':sorted(set(leaks)),'commits':identities,'invalid_identities':invalid,'previous':previous,
|
||||||
|
'status':git('status','--short').decode()}
|
||||||
|
(ROOT/'evidence/audit.json').write_text(json.dumps(result,ensure_ascii=False,indent=2),encoding='utf-8')
|
||||||
|
assert not (changed or forbidden or leaks or invalid),result
|
||||||
|
assert all(not value['status'] for value in previous.values()),'previous lab modified'
|
||||||
|
assert previous['4']['head']=='8f112e092a10d72a98c3d9d4554c52b81ebff2b3'
|
||||||
|
assert previous['5']['head'].startswith('9dd2a03')
|
||||||
|
print('PASS: original materials, author/committer, tracked secrets, previous labs')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':main()
|
||||||
@@ -0,0 +1,33 @@
|
|||||||
|
"""Only sanitized environment fields; never serialize Docker Config.Env or secrets."""
|
||||||
|
import json
|
||||||
|
from pathlib import Path
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
|
||||||
|
ROOT=Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0,str(ROOT/'student-tests'))
|
||||||
|
from common import snapshot,save,PROJECT
|
||||||
|
|
||||||
|
|
||||||
|
def command(*args):return subprocess.check_output(args,text=True,cwd=ROOT).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
other=[]
|
||||||
|
for cid in command('docker','ps','-aq').split():
|
||||||
|
row=json.loads(command('docker','inspect',cid))[0]
|
||||||
|
project=row['Config'].get('Labels',{}).get('com.docker.compose.project','')
|
||||||
|
if project != PROJECT:
|
||||||
|
other.append({'id':row['Id'],'project':project,'started_at':row['State']['StartedAt'],
|
||||||
|
'state':row['State']['Status']})
|
||||||
|
data={'commit':command('git','rev-parse','HEAD'),'whoami':command('whoami'),
|
||||||
|
'docker_context':command('docker','context','show'),
|
||||||
|
'docker_version':json.loads(command('docker','version','--format','{{json .}}')),
|
||||||
|
'docker_resources':command('docker','info','--format','{{.NCPU}} CPUs {{.MemTotal}} bytes'),
|
||||||
|
'compose_version':command('docker','compose','version'),'containers':snapshot(),'other_containers':other}
|
||||||
|
# Docker version output contains no application environment.
|
||||||
|
save('environment.json',data)
|
||||||
|
print('Sanitized environment captured')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':main()
|
||||||
+4
-1
@@ -51,7 +51,10 @@ def create_app() -> FastAPI:
|
|||||||
@app.middleware("http")
|
@app.middleware("http")
|
||||||
async def add_request_id(request: Request, call_next):
|
async def add_request_id(request: Request, call_next):
|
||||||
"""Добавляет идентификаторы запроса и процесса, ограничивает очередь."""
|
"""Добавляет идентификаторы запроса и процесса, ограничивает очередь."""
|
||||||
request_id = request.headers.get("X-Request-Id", "") or str(uuid.uuid4())
|
try:
|
||||||
|
request_id = str(uuid.UUID(request.headers.get("X-Request-Id", "")))
|
||||||
|
except ValueError:
|
||||||
|
request_id = str(uuid.uuid4())
|
||||||
request.state.request_id = request_id
|
request.state.request_id = request_id
|
||||||
|
|
||||||
# Ограничение числа обслуживаемых запросов в процессе.
|
# Ограничение числа обслуживаемых запросов в процессе.
|
||||||
|
|||||||
+1
-1
@@ -14,7 +14,7 @@ class Handler(BaseHTTPRequestHandler):
|
|||||||
"clock_timestamp()-min(created_at)),0) AS age FROM attachment_jobs "
|
"clock_timestamp()-min(created_at)),0) AS age FROM attachment_jobs "
|
||||||
"WHERE state IN ('queued','processing')").fetchone()
|
"WHERE state IN ('queued','processing')").fetchone()
|
||||||
windows = {}
|
windows = {}
|
||||||
for window, seconds in [('30s',30),('1m',60),('2m',120),('5m',300)]:
|
for window, seconds in [('15s',15),('30s',30),('1m',60),('2m',120),('5m',300)]:
|
||||||
result = conn.execute("SELECT count(*) AS total, count(*) FILTER (WHERE "
|
result = conn.execute("SELECT count(*) AS total, count(*) FILTER (WHERE "
|
||||||
"state <> 'ready' OR updated_at-created_at > interval '5 seconds') AS bad "
|
"state <> 'ready' OR updated_at-created_at > interval '5 seconds') AS bad "
|
||||||
"FROM attachments WHERE created_at <= clock_timestamp()-interval '5 seconds' "
|
"FROM attachments WHERE created_at <= clock_timestamp()-interval '5 seconds' "
|
||||||
|
|||||||
+22
-1
@@ -10,13 +10,17 @@ import urllib.request
|
|||||||
|
|
||||||
ROOT = Path(__file__).resolve().parents[1]
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
sys.path.insert(0,str(ROOT/'tests'))
|
sys.path.insert(0,str(ROOT/'tests'))
|
||||||
from client import Client, check
|
from client import Client, check, shape
|
||||||
BASE = os.getenv('BASE_URL','http://127.0.0.1:8086')
|
BASE = os.getenv('BASE_URL','http://127.0.0.1:8086')
|
||||||
GRAFANA = os.getenv('GRAFANA_URL','http://127.0.0.1:3006')
|
GRAFANA = os.getenv('GRAFANA_URL','http://127.0.0.1:3006')
|
||||||
PROJECT = os.getenv('COMPOSE_PROJECT_NAME','lyakhonov-lab6')
|
PROJECT = os.getenv('COMPOSE_PROJECT_NAME','lyakhonov-lab6')
|
||||||
|
|
||||||
|
|
||||||
def dc(*args):
|
def dc(*args):
|
||||||
|
if args and args[0]=='start':
|
||||||
|
# Compose v2.40 also starts dependencies, which would undo an injected S3 outage.
|
||||||
|
ids=subprocess.check_output(['docker','compose','-p',PROJECT,'ps','-aq',*args[1:]],cwd=ROOT,text=True).split()
|
||||||
|
return subprocess.check_output(['docker','start',*ids],text=True)
|
||||||
return subprocess.check_output(['docker','compose','-p',PROJECT,*args],cwd=ROOT,text=True,stderr=subprocess.STDOUT)
|
return subprocess.check_output(['docker','compose','-p',PROJECT,*args],cwd=ROOT,text=True,stderr=subprocess.STDOUT)
|
||||||
|
|
||||||
|
|
||||||
@@ -32,12 +36,29 @@ def prom(expr):
|
|||||||
return query('prometheus','/api/v1/query',query=expr)['data']['result']
|
return query('prometheus','/api/v1/query',query=expr)['data']['result']
|
||||||
|
|
||||||
|
|
||||||
|
class DBLock:
|
||||||
|
"""Bounded SQL lock in this project's DB; health reads remain usable."""
|
||||||
|
def start(self):
|
||||||
|
self.process=subprocess.Popen(['docker','compose','-p',PROJECT,'exec','-T','db',
|
||||||
|
'env','PGAPPNAME=lab6-fault-lock','psql','-U','messenger','-d','messenger','-c',
|
||||||
|
'BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(180); COMMIT;'],
|
||||||
|
cwd=ROOT,stdout=subprocess.DEVNULL,stderr=subprocess.DEVNULL)
|
||||||
|
time.sleep(.5)
|
||||||
|
check(self.process.poll() is None,'SQL fault process failed')
|
||||||
|
|
||||||
|
def stop(self):
|
||||||
|
dc('exec','-T','db','psql','-U','messenger','-d','messenger','-Atc',
|
||||||
|
"SELECT pg_terminate_backend(pid) FROM pg_stat_activity WHERE application_name='lab6-fault-lock' AND pid<>pg_backend_pid()")
|
||||||
|
self.process.wait(timeout=10)
|
||||||
|
|
||||||
|
|
||||||
def snapshot():
|
def snapshot():
|
||||||
ids=dc('ps','-aq').split()
|
ids=dc('ps','-aq').split()
|
||||||
result=[]
|
result=[]
|
||||||
for row in json.loads(subprocess.check_output(['docker','inspect',*ids],text=True)):
|
for row in json.loads(subprocess.check_output(['docker','inspect',*ids],text=True)):
|
||||||
result.append({'id':row['Id'],'service':row['Config']['Labels']['com.docker.compose.service'],
|
result.append({'id':row['Id'],'service':row['Config']['Labels']['com.docker.compose.service'],
|
||||||
'started_at':row['State']['StartedAt'],'status':row['State']['Status'],
|
'started_at':row['State']['StartedAt'],'status':row['State']['Status'],
|
||||||
|
'oom_killed':row['State']['OOMKilled'],
|
||||||
'memory_limit':row['HostConfig']['Memory'],'nano_cpus':row['HostConfig']['NanoCpus']})
|
'memory_limit':row['HostConfig']['Memory'],'nano_cpus':row['HostConfig']['NanoCpus']})
|
||||||
return result
|
return result
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,126 @@
|
|||||||
|
"""Bounded grade-4 failures, recovery and stored telemetry observations."""
|
||||||
|
from concurrent.futures import ThreadPoolExecutor
|
||||||
|
import time
|
||||||
|
from common import *
|
||||||
|
|
||||||
|
|
||||||
|
def alerts():
|
||||||
|
return query('prometheus','/api/v1/alerts')['data']['alerts']
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
c=Client(BASE);alice,bob,eve,chat=c.bootstrap()
|
||||||
|
result={'before':snapshot(),'incidents':[]}
|
||||||
|
def wait_result(att):
|
||||||
|
transitional=[]
|
||||||
|
deadline=time.monotonic()+90
|
||||||
|
while time.monotonic()<deadline:
|
||||||
|
request=urllib.request.Request(BASE+'/api/v1/attachments/'+att['id'],headers={'Authorization':'Bearer '+alice['token']})
|
||||||
|
try:response=urllib.request.urlopen(request,timeout=10)
|
||||||
|
except urllib.error.HTTPError as error:response=error
|
||||||
|
with response:
|
||||||
|
status=response.code
|
||||||
|
payload=response.read()
|
||||||
|
source='API' if response.headers.get('X-Instance-Id') else 'LB'
|
||||||
|
check(status in (200,503),'unexpected attachment response')
|
||||||
|
if status==503:
|
||||||
|
transitional.append({'time':time.time(),'status':503,'source':source})
|
||||||
|
time.sleep(.5)
|
||||||
|
continue
|
||||||
|
metadata=shape(json.loads(payload),'Attachment')
|
||||||
|
if metadata['status']=='ready':
|
||||||
|
result.setdefault('transition_errors',[]).extend(transitional)
|
||||||
|
return metadata
|
||||||
|
elif metadata['status']=='failed':
|
||||||
|
raise AssertionError('accepted attachment failed')
|
||||||
|
time.sleep(.5)
|
||||||
|
raise AssertionError('accepted attachment did not reach ready')
|
||||||
|
dc('stop','-t','2','worker')
|
||||||
|
try:
|
||||||
|
att,_=c.attachment(alice,chat)
|
||||||
|
observations=[]
|
||||||
|
for _ in range(8):
|
||||||
|
observations.append({'time':time.time(),'depth':prom('messenger_queue_depth'),
|
||||||
|
'age':prom('messenger_queue_oldest_seconds'),'alerts':alerts()})
|
||||||
|
time.sleep(5)
|
||||||
|
check(any(a['labels']['alertname']=='QueueLag' and a['state']=='firing'
|
||||||
|
for row in observations for a in row['alerts']),'queue alert did not fire')
|
||||||
|
finally:dc('start','worker')
|
||||||
|
wait_result(att)
|
||||||
|
result['incidents'].append({'name':'worker stopped','observations':observations,'ready':True})
|
||||||
|
save('incidents.json',result)
|
||||||
|
# Force at least one managed retry, keeping the original HTTP trace context.
|
||||||
|
dc('stop','-t','2','worker')
|
||||||
|
response=c.call('POST','/api/v1/chats/'+chat['id']+'/attachments?filename=retry.png',202,
|
||||||
|
actor=alice,raw=(ROOT/'tests/fixtures/sample.png').read_bytes(),headers={'Content-Type':'image/png'},schema='Attachment')
|
||||||
|
tid=response['headers']['X-Trace-Id']
|
||||||
|
dc('stop','-t','2','s3')
|
||||||
|
dc('start','worker')
|
||||||
|
try:
|
||||||
|
deadline=time.monotonic()+35
|
||||||
|
retried=False
|
||||||
|
while time.monotonic()<deadline:
|
||||||
|
records=query('loki','/loki/api/v1/query_range',query='{service_name="messenger-worker"} |= "'+tid+'" |= "retry"',limit=10)
|
||||||
|
if records['data']['result']:
|
||||||
|
retried=True
|
||||||
|
break
|
||||||
|
time.sleep(1)
|
||||||
|
check(retried,'no managed retry observed while S3 stopped')
|
||||||
|
finally:dc('start','s3')
|
||||||
|
wait_result(response['json'])
|
||||||
|
time.sleep(4)
|
||||||
|
doc,spans=trace_wait(tid)
|
||||||
|
check(sum(s['kind']=='SPAN_KIND_CONSUMER' for s in spans)>=2,'retry trace missing')
|
||||||
|
result['retry']={'trace_id':tid,'spans':spans,'ready':True}
|
||||||
|
save('incidents.json',result)
|
||||||
|
# DB unavailable to active business traffic, not just /health.
|
||||||
|
fault=DBLock();fault.start()
|
||||||
|
observations=[];responses=[]
|
||||||
|
try:
|
||||||
|
with ThreadPoolExecutor(max_workers=6) as pool:
|
||||||
|
deadline=time.monotonic()+45
|
||||||
|
while time.monotonic()<deadline:
|
||||||
|
futures=[pool.submit(c.call,'POST','/api/v1/chats/'+chat['id']+'/messages',[201,503],actor=alice,
|
||||||
|
body={'text':'DB lock experiment'},headers={'Idempotency-Key':str(time.time_ns())+str(i)},schema='Message') for i in range(6)]
|
||||||
|
for future in futures:
|
||||||
|
response=future.result()
|
||||||
|
responses.append({'status':response['status'],'elapsed':response['elapsed'],
|
||||||
|
'trace_id':response['headers']['X-Trace-Id']})
|
||||||
|
observations.append({'time':time.time(),'alerts':alerts(),'pool':prom('messenger_db_pool_waiting')})
|
||||||
|
check(any(a['labels']['alertname']=='HighAPIErrorRate' and a['state']=='firing' for row in observations for a in row['alerts']), 'API error alert did not fire')
|
||||||
|
finally:fault.stop()
|
||||||
|
subprocess.check_call([sys.executable,'scripts/wait_ready.py','--project',PROJECT,'--base-url',BASE],cwd=ROOT)
|
||||||
|
c.message(alice,chat,'after DB recovery')
|
||||||
|
_,dbspans=trace_wait(next(x['trace_id'] for x in responses if x['status']==503),services=('messenger-api',))
|
||||||
|
result['incidents'].append({'name':'DB messages table locked','responses':responses,'observations':observations,'trace_spans':dbspans,'recovered':True})
|
||||||
|
save('incidents.json',result)
|
||||||
|
# Backend outage: drive signals until Collector retry expires, then prove business durability.
|
||||||
|
before=prom('otelcol_exporter_send_failed_spans_total')
|
||||||
|
dc('stop','-t','2','tempo')
|
||||||
|
snapshots=[]
|
||||||
|
try:
|
||||||
|
for i in range(10):
|
||||||
|
c.message(alice,chat,'telemetry outage '+str(i))
|
||||||
|
att,_=c.attachment(alice,chat);c.wait_ready(alice,att)
|
||||||
|
snapshots.append({'time':time.time(),'stats':dc('stats','--no-stream','--format','json'),
|
||||||
|
'queue':prom('otelcol_exporter_queue_size'),'failed':prom('otelcol_exporter_send_failed_spans_total')})
|
||||||
|
time.sleep(2)
|
||||||
|
finally:dc('start','tempo')
|
||||||
|
result['backend_outage']={'before_failed':before,'samples':snapshots,'business_messages':10,'completed_uploads':10,'after':snapshot()}
|
||||||
|
save('incidents.json',result)
|
||||||
|
check(any(float(r['value'][1])>0 for sample in snapshots for r in sample['failed']), 'export failure counter did not increase')
|
||||||
|
check(all(float(r['value'][1])<=128 for sample in snapshots for r in sample['queue']), 'Collector queue exceeded configured bound')
|
||||||
|
# Observe recovery, allowing the independent error-rate lookback to age out.
|
||||||
|
deadline=time.monotonic()+160
|
||||||
|
while time.monotonic()<deadline:
|
||||||
|
c.message(alice,chat,'recovery control')
|
||||||
|
active=alerts()
|
||||||
|
if not any(a['labels']['alertname'] in ('HighAPIErrorRate','QueueLag') for a in active):break
|
||||||
|
time.sleep(5)
|
||||||
|
result['resolved_alerts']=active
|
||||||
|
save('incidents.json',result)
|
||||||
|
check(not any(a['labels']['alertname'] in ('HighAPIErrorRate','QueueLag') for a in active),'base alerts not resolved')
|
||||||
|
print('PASS: worker lag, S3 retry context, DB outage, telemetry backend outage and recovery')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':main()
|
||||||
@@ -0,0 +1,38 @@
|
|||||||
|
"""Public persistence and separately stop each real API replica; preserve volumes."""
|
||||||
|
import os
|
||||||
|
import subprocess
|
||||||
|
import time
|
||||||
|
from common import *
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
result={'before':snapshot()}
|
||||||
|
env=dict(os.environ,PYTHONUTF8='1')
|
||||||
|
for mode in ['persistence','failover','failover']:
|
||||||
|
script=ROOT/'scripts'/('restart.cmd' if mode=='persistence' else 'stop-one.cmd')
|
||||||
|
before=snapshot()
|
||||||
|
run=subprocess.run([sys.executable,'-X','utf8','tests/resilience.py','--base-url',BASE,
|
||||||
|
'--mode',mode,'--action-script',str(script)],cwd=ROOT,env=env,capture_output=True,text=True)
|
||||||
|
after=snapshot()
|
||||||
|
result.setdefault('runs',[]).append({'mode':mode,'before':before,'after':after,
|
||||||
|
'exit_code':run.returncode,'output':run.stdout+run.stderr})
|
||||||
|
# Bring back only our replicas after the public hook; next run targets the other alias below.
|
||||||
|
dc('start','api')
|
||||||
|
subprocess.check_call([sys.executable,'scripts/wait_ready.py','--project',PROJECT,'--base-url',BASE],cwd=ROOT)
|
||||||
|
save('resilience.json',result)
|
||||||
|
check(run.returncode==0,'public '+mode+' failed')
|
||||||
|
# Deterministic separate stops, independent of LB choice in the public hook.
|
||||||
|
c=Client(BASE);alice,bob,eve,chat=c.bootstrap()
|
||||||
|
for container in dc('ps','-q','api').split():
|
||||||
|
before=snapshot()
|
||||||
|
subprocess.check_call(['docker','stop','-t','2',container],stdout=subprocess.DEVNULL)
|
||||||
|
try:
|
||||||
|
for i in range(20):c.message(alice,chat,'targeted '+str(i))
|
||||||
|
finally:subprocess.check_call(['docker','start',container],stdout=subprocess.DEVNULL)
|
||||||
|
result.setdefault('each_api',[]).append({'stopped_id':container,'before':before,'after':snapshot(),'confirmed':20})
|
||||||
|
time.sleep(5)
|
||||||
|
save('resilience.json',result)
|
||||||
|
print('PASS: persistence, public failover twice, each API stopped separately')
|
||||||
|
|
||||||
|
|
||||||
|
if __name__=='__main__':main()
|
||||||
@@ -46,7 +46,8 @@ def main():
|
|||||||
telemetry=json.dumps([doc,logs,signals])
|
telemetry=json.dumps([doc,logs,signals])
|
||||||
for secret in [alice['token'],bob['token'],alice['registration']['password'],'synthetic concurrent']:
|
for secret in [alice['token'],bob['token'],alice['registration']['password'],'synthetic concurrent']:
|
||||||
check(secret not in telemetry,'sensitive data in telemetry')
|
check(secret not in telemetry,'sensitive data in telemetry')
|
||||||
save('signals.json',{'trace_id':tid,'spans':spans,'logs':logs,'metrics':signals,
|
compact={name:{'series_count':len(rows),'label_names':sorted(set().union(*(set(row['metric']) for row in rows))),'sample':rows[:2]} for name,rows in signals.items()}
|
||||||
|
save('signals.json',{'trace_id':tid,'spans':spans,'logs':logs,'metrics':compact,
|
||||||
'concurrent_requests':24,'unique_messages':1,'checks':'PASS'})
|
'concurrent_requests':24,'unique_messages':1,'checks':'PASS'})
|
||||||
print('PASS: real OTLP signals, connected producer/consumer/S3/DB graph, logs, metric labels, 24 concurrent replays and negative checks')
|
print('PASS: real OTLP signals, connected producer/consumer/S3/DB graph, logs, metric labels, 24 concurrent replays and negative checks')
|
||||||
|
|
||||||
|
|||||||
@@ -0,0 +1,53 @@
|
|||||||
|
import hashlib
|
||||||
|
import tempfile
|
||||||
|
import unittest
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
from PIL import Image
|
||||||
|
|
||||||
|
from src.image_pipeline import render
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
|
||||||
|
|
||||||
|
class Images(unittest.TestCase):
|
||||||
|
def test_public_fixture_and_repeat(self):
|
||||||
|
fixture = ROOT / 'tests' / 'fixtures' / 'sample.png'
|
||||||
|
original = hashlib.sha256(fixture.read_bytes()).hexdigest()
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
target = Path(directory)
|
||||||
|
expected = {
|
||||||
|
'thumbnail': ('JPEG', (256, 160)),
|
||||||
|
'crop': ('JPEG', (128, 128)),
|
||||||
|
'optimized': ('WEBP', (320, 200)),
|
||||||
|
}
|
||||||
|
first = render(fixture, target)
|
||||||
|
self.assertEqual(len(first), len(expected))
|
||||||
|
digests = {name: hashlib.sha256((target / name).read_bytes()).hexdigest() for name in expected}
|
||||||
|
self.assertEqual(first, render(fixture, target))
|
||||||
|
for name, properties in expected.items():
|
||||||
|
with Image.open(target / name) as image:
|
||||||
|
self.assertEqual((image.format, image.size), properties)
|
||||||
|
self.assertEqual(hashlib.sha256((target / name).read_bytes()).hexdigest(), digests[name])
|
||||||
|
self.assertEqual(hashlib.sha256(fixture.read_bytes()).hexdigest(), original)
|
||||||
|
|
||||||
|
def test_orientation_alpha_and_small_image(self):
|
||||||
|
with tempfile.TemporaryDirectory() as directory:
|
||||||
|
target = Path(directory)
|
||||||
|
source = target / 'source.png'
|
||||||
|
image = Image.new('RGBA', (35, 15), (255, 0, 0, 0))
|
||||||
|
image.save(source, exif=self.orientation())
|
||||||
|
render(source, target)
|
||||||
|
with Image.open(target / 'thumbnail') as thumbnail:
|
||||||
|
self.assertEqual(thumbnail.size, (15, 35))
|
||||||
|
self.assertEqual(thumbnail.getpixel((4, 4)), (255, 255, 255))
|
||||||
|
self.assertFalse(thumbnail.getexif())
|
||||||
|
with Image.open(target / 'optimized') as optimized:
|
||||||
|
self.assertEqual(optimized.size, (15, 35))
|
||||||
|
self.assertFalse(optimized.getexif())
|
||||||
|
|
||||||
|
@staticmethod
|
||||||
|
def orientation():
|
||||||
|
exif = Image.Exif()
|
||||||
|
exif[274] = 6
|
||||||
|
return exif
|
||||||
Reference in New Issue
Block a user