Close the source image after converting to RGBA so PNGs at the pixel limit fit the render memory limit. Strengthen the fencing test so that it fails without the attempt check, and measure worker and relay stops under load. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
8425 lines
316 KiB
Python
8425 lines
316 KiB
Python
#!/usr/bin/env python3
|
||
"""Драйвер API мессенджера для агента: запуск, сценарий, запросы, остановка.
|
||
|
||
Только стандартная библиотека. Запускать из корня репозитория:
|
||
|
||
python3 .claude/skills/run-mtusi-messenger/driver.py [--port N] <cmd>
|
||
|
||
Команды:
|
||
start `make upgrade start_cache start_s3 start_broker` (Postgres из
|
||
compose и миграции, Valkey, S3 с bootstrap, RabbitMQ), затем
|
||
поднять `python -m src` (console, reload), `make run_worker` и
|
||
`make run_relay` в одной группе процессов и дождаться
|
||
/health/ready, соединения worker с брокером и старта relay; лог и
|
||
pid — /tmp/mtusi-api-<port>.{log,pid}, логи worker и relay —
|
||
/tmp/mtusi-worker-<port>.log, /tmp/mtusi-relay-<port>.log
|
||
status кто слушает порт и что отвечает /health/ready
|
||
flow сквозной сценарий по HTTP с проверками; код выхода 1 при провале
|
||
req один запрос: req METHOD PATH [--token T | --basic USER:PASS]
|
||
[--data JSON] [--key K | --no-key]; POST сообщения без --key
|
||
получает новый Idempotency-Key (печатается для повтора)
|
||
smoke публичный tests/smoke.py против этого порта
|
||
student собственные тесты student-tests/ (make student_test) против
|
||
этого порта; против своего процесса — с EXPECT_REPLICAS=1
|
||
instances [--count N] распределение одной сессии по репликам: вход
|
||
одним синтетическим пользователем, N × GET /users/me с одним
|
||
токеном, X-Instance-Id каждого ответа и итог по репликам
|
||
kill-inflight [--threads N] [--seconds S] [--after A] только стенд
|
||
с LB: N потоков S секунд входят по Basic (Argon2id — запросы
|
||
в полёте есть всегда), через A секунд scripts/stop-one.sh в
|
||
режиме kill убивает реплику пробного запроса; статусы по
|
||
репликам и ответы LB. Реплика остаётся остановленной
|
||
(make replicas)
|
||
idle-conns [--threads N] [--requests M] [--keep-alive S] [--lb C]
|
||
только стенд с LB: всплеск запросов через LB, клиенты
|
||
остаются подключены; раз в секунду — соединения на порт API
|
||
внутри каждой реплики и пул LB (контейнер C, по умолчанию
|
||
сервис haproxy стенда); код 1, если реплики держат
|
||
соединения дольше S секунд — срока keep-alive реплики
|
||
hang-key только стенд с LB: сценарий «Повтор ключа после зависшей
|
||
реплики» — временный триггер задерживает вставку пробного
|
||
сообщения, реплика с этой транзакцией замораживается
|
||
(docker pause), повторы того же ключа через LB до 201,
|
||
разморозка, одно сообщение в чате, строка журнала PostgreSQL;
|
||
триггер удаляется при любом исходе, в том числе по Ctrl+C,
|
||
SIGTERM и SIGHUP; не удалось — печатается SQL удаления
|
||
cache-check [--require-test-keys] только стенд с LB: сценарии
|
||
chat-cache «Чтение из кэша», «Срок записи», «Временная
|
||
база» — ключ карточки после создания чата, TTL и настроенный
|
||
срок, 50 чтений через LB между снимками чтений таблицы chats
|
||
и keyspace_hits Valkey, TTL не продлевается чтениями, ключи
|
||
рабочей и тестовой базы (перед командой — make
|
||
test_isolated); код 1 и нарушенный факт. Без ключей тестовой
|
||
базы — PASS с «temporary database: not checked», с
|
||
--require-test-keys — код 1
|
||
auth-storage только стенд с LB: сценарии sessions «Токена нет в
|
||
хранилище» и users «Хэш в БД» — префиксы Argon2id и разные
|
||
хэши одного пароля, token_hash = SHA-256 токена, ни токена,
|
||
ни пароля в pg_dump; секреты не печатаются
|
||
s3-check стенд compose (make s3_check), без приложения: спек
|
||
object-storage «Проверка приватности вне API» — bootstrap S3
|
||
в режиме check (права ключа API, чужой bucket,
|
||
административные запросы, аноним изнутри сервера), анонимные
|
||
запросы с хоста и из сети стенда, порты контейнера S3 из
|
||
сети, затем режим cleanup и проверка, что проверочных
|
||
объектов и bucket не осталось; таблица «где → проверка →
|
||
ожидаемо → получено», среди строк bootstrap обязательны список
|
||
уборщика по префиксам staging и базы; код 1 при расхождении
|
||
stop-at-start [--image ТЕГ] [--delays 0.2,0.3,0.4,1.5,5]
|
||
[--server-start 3] docker stop контейнеров образа (лимиты
|
||
реплики, без сети) во время старта: через паузу после
|
||
docker run и по строке «Started server process»; время
|
||
сигнала и выхода, код выхода, этап старта, кто остановил
|
||
(ранний обработчик или uvicorn); код 1, если стартующий
|
||
контейнер останавливается дольше 1 с или не с кодом 0
|
||
upload --token T --chat C --file F [--type …] [--filename …]
|
||
загрузка вложения: статус (202), X-Instance-Id, тело, SHA-256
|
||
файла, затем опрос метаданных до ready; код 2 при статусе ≥ 400,
|
||
failed или сроке ожидания
|
||
download --token T --attachment A [--out F] [--variant …] [--wait]
|
||
скачивание оригинала или варианта: статус, X-Instance-Id,
|
||
Content-Type, размер и SHA-256 полученного, у JPEG — размеры по
|
||
SOF; не ready — 409 и код 2, с --wait — сначала опрос до ready
|
||
attachment-failover [--mode stop|kill] только стенд с LB: спек
|
||
attachments «Принявшая реплика остановлена» — загрузка
|
||
tests/fixtures/sample.png через LB (202, ожидание ready),
|
||
сообщение со ссылкой, scripts/stop-one.sh реплики, принявшей
|
||
файл, скачивание Бобом через другую реплику (SHA-256 совпадает),
|
||
404 Еве; в finally — make replicas; docker compose ps до и
|
||
после, таблица без токенов; код 1 при расхождении, без LB — код 2
|
||
attachment-storage только стенд с LB: спек attachments «Байты не в
|
||
БД и не на диске API» — колонки таблиц вложений (байты — только
|
||
32-байтные SHA-256), object_key вида <база>/attachments/<id>/
|
||
original без filename, staging_key вида <база>/staging/<id>/
|
||
original или уже пуст (убрал уборщик), объект и три варианта в
|
||
bucket (weed shell), анонимный GET ключа с хоста — 403, docker
|
||
diff реплик и worker без файлов оригиналов; спек data-storage
|
||
«Ограничения обработки в схеме» — вставки в откатываемой
|
||
транзакции отклонены, в том числе аудит replay с неизвестным
|
||
заданием; код 1 при расхождении, без LB — код 2
|
||
upload-consistency только стенд с LB: спеки attachments «Порядок
|
||
записи» и storage-consistency — загрузка при docker compose
|
||
pause s3 (503, строка pending), загрузка со сбоем перевода в
|
||
queued (триггер на уникальный filename, 503, объект staging
|
||
удалён компенсацией), обе строки не видны через API (404), после
|
||
grace 30 с — docker compose run --rm --no-deps cleaner --once,
|
||
ни строк, ни объектов, объектов без строки под префиксом базы
|
||
нет, staging готового вложения убран тем же проходом, готовое
|
||
вложение скачивается с тем же SHA-256; триггер снимается в
|
||
finally и в начале следующего прогона; код 1 при расхождении, без
|
||
LB — код 2
|
||
defense-scenario только стенд с LB: спек student-tests «Сценарий защиты
|
||
автоматизирован» — docker compose stop worker, загрузка
|
||
sample.png 202, сообщение с вложением 201, скачивание 409,
|
||
текстовое сообщение 201, опрос: сообщение в очереди (его публикует
|
||
relay, он не останавливается), scripts/restart.sh, docker compose
|
||
start worker, ожидание ready, оригинал (SHA-256) и три варианта
|
||
(настоящие JPEG и WebP); шаги, коды, id, StartedAt api и rabbitmq
|
||
до и после, без токенов. Worker и relay запускаются при любом
|
||
исходе, в том числе по SIGINT, SIGTERM, SIGHUP; код 1 при
|
||
расхождении, 130 по сигналу, 2 — нет стенда
|
||
defense-faults только стенд с LB: шаг 4 защиты, окна отказа (design
|
||
change pipeline-reliability, решения 14 и 17) — crash после записи
|
||
объектов до фиксации, после фиксации до подтверждения, relay убит
|
||
до публикации и после подтверждения до отметки, реестр failed и
|
||
replay, отказ replay готового. Триггеры — на уникальный filename,
|
||
снимаются в finally и в начале следующего прогона; worker и relay
|
||
запускаются при любом исходе, в том числе по сигналу; по каждому
|
||
окну — действие, id задания, число попыток, итог. Код 1 при
|
||
расхождении, 130 по сигналу, 2 — нет стенда
|
||
relay-process только стенд с LB: спеки container-run, graceful-shutdown,
|
||
service-configuration — PID 1 relay, нет healthcheck, лимиты,
|
||
окружение без S3 и Valkey, декодера в процессе нет, «Started relay»,
|
||
значения по умолчанию, неверные RELAY__* (код 2), подмена
|
||
окружением, остановка простаивающего и на старте, рестарт хранилищ;
|
||
relay и worker запущены при любом исходе; код 1 при расхождении,
|
||
130 по сигналу, 2 — нет стенда
|
||
pipeline-state только чтение, стенд compose: JSON — задания по состояниям,
|
||
due, ждущие срока, опубликованные и не взятые, истёкшие аренды,
|
||
возраст старейшего queued, состояние очереди; брокер недоступен —
|
||
queue.available false и код 0; PostgreSQL недоступен — код 1
|
||
broker-check [--require-test-queue] стенд compose: спек message-broker
|
||
— образ тегом и digest, volume, docker port только AMQP на
|
||
127.0.0.1, предел памяти меньше лимита контейнера, рабочая
|
||
очередь durable, пароль брокера только у rabbitmq, relay и worker,
|
||
с флагом — очередь test_<db> есть, docker compose stop rabbitmq с
|
||
кодом 0 раньше срока и возврат; таблица, код 1 при расхождении,
|
||
130 по сигналу
|
||
worker-process только стенд с LB: спеки container-run и
|
||
graceful-shutdown — PID 1 worker, нет healthcheck, лимиты, Pillow
|
||
нет ни в процессе API, ни в процессе 1 worker, версия Pillow,
|
||
«Started worker», неверные WORKER__* (код 2), подмена окружением,
|
||
значения по умолчанию, остановка простаивающего и на старте,
|
||
«Worker переживает рестарт хранилищ»; worker и relay запущены при
|
||
любом исходе; код 1 при расхождении, 130 по сигналу, 2 — нет стенда
|
||
reconcile-cycle только стенд с LB: спек storage-consistency, сверка
|
||
bucket и БД — исходный dry-run без расхождений (иначе код 2),
|
||
расхождения с обеих сторон (объект мимо API и чужой ключ —
|
||
docker exec реплики своими ключами, удалённые объекты — weed
|
||
shell fs.rm, удалённая строка и другой размер — psql, обрыв
|
||
между объектом и фиксацией — триггер COMMIT на уникальный
|
||
filename), объекты staging без строки и с чужим ключом, после
|
||
grace 30 с dry-run без изменений, 500 до сверки, --apply, 404 и
|
||
200 после, повтор, удаление чужих объектов, свежий объект после
|
||
grace, возврат оригинала; код 1 при расхождении, без LB — код 2
|
||
reconcile-stress [--seconds S] [--clients N] только стенд с LB:
|
||
«Сверка под нагрузкой» — внесённые расхождения, N клиентов S
|
||
секунд загружают PNG ~100 KiB и отправляют сообщения, поток
|
||
сверки — --apply с grace 20 с раз в ~3 с; каждое 202 доходит до
|
||
ready и скачивается с тем же SHA-256, сообщения отдают вложения,
|
||
повтор — 0; код 1 при расхождении
|
||
reconcile-signal только не рабочий проект compose (окружение
|
||
COMPOSE_PROJECT_NAME / COMPOSE_FILE; mtusi-lab5 — код 2): спек
|
||
graceful-shutdown, разовый проход сверки, прерванный сигналом,
|
||
— код 1: docker compose pause s3, run -d cleaner reconcile
|
||
--apply, через секунду после «Started cleaner» docker stop;
|
||
interrupted_by stop, «Stopped cleaner» с exit_code 1, остановка
|
||
быстрее stop_grace_period 10 с; S3 размораживается в finally;
|
||
код 1 при расхождении. --pace (change track2-reconcile-cost):
|
||
вместо pause s3 — объекты пробы мимо API (botocore в одноразовом
|
||
контейнере api его ключами), reconcile --max-objects-per-second
|
||
1, docker stop через 2 с после «Started cleaner» во время паузы
|
||
предела скорости — остановка не дольше секунды, listed_objects
|
||
итога — ключи страницы; объекты удаляются в finally.
|
||
--pace --apply (verify W1): объекты пробы без строки
|
||
(<id>/original), через grace 18 с + 1 — reconcile --apply с тем
|
||
же пределом, docker stop во время паузы после DELETE: удалённых
|
||
объектов столько же, сколько записей «Fixed» и fixed итога
|
||
s3-idle [--rounds 3] [--downloads 10] [--puts 12] [--size-mib 4]
|
||
[--pause-ms 0.5] только стенд с LB: спеки object-storage
|
||
«Вызов после простоя» и attachments «Загрузка после простоя
|
||
S3» — проба клиента S3 в реплике (docker exec -i … python -,
|
||
код и ключи образа), варианты «image» и «reference» (прежний
|
||
read_timeout aiohttp = [s3] timeout_seconds); раунд —
|
||
одновременные медленные скачивания объекта, простой срока
|
||
вызова + 0,5 с, PUT по одному; взведённые и испорченные
|
||
соединения пула, PUT прошло и упало (цепочка ошибки, мс),
|
||
чтение записанного обратно; объекты под
|
||
<база>/.s3-idle-probe/ удаляются в finally; код 0 — у образа
|
||
ни порчи, ни упавших PUT, 1 — иначе, 2 — нет стенда
|
||
lb-upload-timeouts [--config F] [--image ТЕГ] без стенда: спек
|
||
load-balancing «Загрузки через балансировщик» — временная
|
||
сеть, HAProxy закреплённого образа с конфигурацией F (по
|
||
умолчанию infra/haproxy/haproxy.cfg) и заглушка реплики под
|
||
именем api; молчание заглушки 12 с до и после тела загрузки —
|
||
202, 12 с на другом пути — 504 через ~10 с, 32 с на пути
|
||
загрузки — 504 через ~30 с, клиент молчит посреди тела — 400
|
||
в формате контракта; сеть и контейнеры удаляются при любом
|
||
исходе; код 1 при расхождении
|
||
stop остановить свой экземпляр на порту
|
||
all start → flow → smoke → student (если есть student-tests/) → stop
|
||
|
||
Работает на python3 3.9+ (системный python3 macOS): `make instances`
|
||
вызывает его без uv. Отсюда `from __future__ import annotations` и
|
||
`timezone.utc` вместо `datetime.UTC` (3.11+, `noqa: UP017`: ruff
|
||
проекта целится в py312 и иначе вернул бы `datetime.UTC`).
|
||
|
||
Порт по умолчанию 18080, а не 8080: на 8080 обычно работает стенд
|
||
`make run_docker` (HAProxy перед репликами API) или `make run_dev`
|
||
пользователя, и их процессы трогать не надо. Экземпляр драйвера пишет в
|
||
ту же рабочую базу Postgres. flow, req, smoke, student и instances
|
||
работают с любым сервером на порту, в том числе со стендом через
|
||
балансировщик (`--port 8080`).
|
||
"""
|
||
|
||
from __future__ import annotations
|
||
|
||
import argparse
|
||
import base64
|
||
import contextlib
|
||
import csv
|
||
import hashlib
|
||
import http.client
|
||
import io
|
||
import ipaddress
|
||
import json
|
||
import os
|
||
import re
|
||
import secrets
|
||
import signal
|
||
import socket
|
||
import struct
|
||
import subprocess
|
||
import sys
|
||
import threading
|
||
import time
|
||
import urllib.error
|
||
import urllib.parse
|
||
import urllib.request
|
||
import uuid
|
||
import zlib
|
||
from collections import Counter
|
||
from collections.abc import Callable
|
||
from datetime import datetime, timezone
|
||
from pathlib import Path
|
||
from typing import NamedTuple
|
||
|
||
# datetime.UTC появился в 3.11, а драйвер работает и на python3 3.9
|
||
UTC = timezone.utc # noqa: UP017
|
||
ROOT = Path(__file__).resolve().parents[3]
|
||
DEFAULT_PORT = 18080
|
||
USERS = "/api/v1/users"
|
||
CHATS = "/api/v1/chats"
|
||
SESSIONS = "/api/v1/auth/sessions"
|
||
BASIC_CHALLENGE = 'Basic realm="messenger", charset="UTF-8"'
|
||
BEARER_CHALLENGE = 'Bearer realm="messenger"'
|
||
# с лабы 3 обязателен у POST сообщения: одна отправка — один ключ
|
||
IDEMPOTENCY_KEY = "Idempotency-Key"
|
||
# запись журнала worker: соединение с брокером есть, очередь объявлена
|
||
WORKER_CONNECTED = "Connected to broker"
|
||
RELAY_STARTED = "Started relay"
|
||
|
||
|
||
def key_header(key: str | None = None) -> dict[str, str]:
|
||
"""Заголовок ключа идемпотентности; без `key` — новый ключ."""
|
||
return {IDEMPOTENCY_KEY: key or uuid.uuid4().hex}
|
||
|
||
|
||
def paths(port: int) -> tuple[Path, Path]:
|
||
return (
|
||
Path(f"/tmp/mtusi-api-{port}.log"),
|
||
Path(f"/tmp/mtusi-api-{port}.pid"),
|
||
)
|
||
|
||
|
||
def worker_log(port: int) -> Path:
|
||
return Path(f"/tmp/mtusi-worker-{port}.log")
|
||
|
||
|
||
def relay_log(port: int) -> Path:
|
||
return Path(f"/tmp/mtusi-relay-{port}.log")
|
||
|
||
|
||
def group_alive(group: int) -> bool:
|
||
"""Есть ли ещё процессы в группе."""
|
||
try:
|
||
os.killpg(group, 0)
|
||
except ProcessLookupError:
|
||
return False
|
||
return True
|
||
|
||
|
||
def base_url(port: int) -> str:
|
||
return f"http://127.0.0.1:{port}"
|
||
|
||
|
||
def basic(username: str, password: str) -> str:
|
||
"""Значение `Authorization: Basic` из username и пароля в UTF-8."""
|
||
raw = f"{username}:{password}".encode()
|
||
return "Basic " + base64.b64encode(raw).decode("ascii")
|
||
|
||
|
||
def call(
|
||
port: int,
|
||
method: str,
|
||
path: str,
|
||
*,
|
||
token: str | None = None,
|
||
authorization: str | None = None,
|
||
extra: dict[str, str] | None = None,
|
||
body: object = None,
|
||
raw: bytes | None = None,
|
||
timeout: float = 5,
|
||
) -> tuple[int, dict[str, str], object]:
|
||
data = raw
|
||
headers = {"Accept": "application/json"}
|
||
if body is not None:
|
||
data = json.dumps(body).encode()
|
||
if data is not None:
|
||
headers["Content-Type"] = "application/json"
|
||
if token is not None:
|
||
headers["Authorization"] = f"Bearer {token}"
|
||
if authorization is not None:
|
||
headers["Authorization"] = authorization
|
||
headers.update(extra or {})
|
||
request = urllib.request.Request(
|
||
base_url(port) + path,
|
||
data=data,
|
||
method=method,
|
||
headers=headers,
|
||
)
|
||
try:
|
||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||
status = response.status
|
||
hdrs = dict(response.headers)
|
||
payload = response.read()
|
||
except urllib.error.HTTPError as error:
|
||
status, hdrs, payload = error.code, dict(error.headers), error.read()
|
||
hdrs = {key.lower(): value for key, value in hdrs.items()}
|
||
try:
|
||
parsed = json.loads(payload) if payload else None
|
||
except json.JSONDecodeError:
|
||
parsed = payload.decode(errors="replace")
|
||
return status, hdrs, parsed
|
||
|
||
|
||
def listener_pids(port: int) -> list[int]:
|
||
out = subprocess.run(
|
||
["lsof", "-nP", f"-iTCP:{port}", "-sTCP:LISTEN", "-t"],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
).stdout
|
||
return [int(pid) for pid in out.split()]
|
||
|
||
|
||
def is_ready(port: int) -> bool:
|
||
try:
|
||
status, _, _ = call(port, "GET", "/health/ready")
|
||
except OSError:
|
||
return False
|
||
return status == 200
|
||
|
||
|
||
def cmd_start(port: int) -> int:
|
||
log_path, pid_path = paths(port)
|
||
if listener_pids(port):
|
||
if is_ready(port):
|
||
print(f"already up on {base_url(port)}")
|
||
return 0
|
||
print(f"port {port} is busy:", listener_pids(port))
|
||
return 1
|
||
# без Postgres сервис стартует, но /health/ready отвечает 503; без
|
||
# Valkey работает, но мимо кэша; без S3 — 503 на путях вложений; без
|
||
# брокера загрузка — 202, задание ждёт в PostgreSQL
|
||
targets = ["upgrade", "start_cache", "start_s3", "start_broker"]
|
||
upgrade = subprocess.run(
|
||
["make", *targets],
|
||
cwd=ROOT,
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
if upgrade.returncode != 0:
|
||
print(f"make {' '.join(targets)} failed:")
|
||
print((upgrade.stdout + upgrade.stderr)[-2000:])
|
||
return 1
|
||
worker_log_path = worker_log(port)
|
||
worker_log_path.write_bytes(b"")
|
||
relay_log_path = relay_log(port)
|
||
relay_log_path.write_bytes(b"")
|
||
env = os.environ | {
|
||
"APP__RUN_MODE": "console",
|
||
"APP__PORT": str(port),
|
||
"MTUSI_WORKER_LOG": str(worker_log_path),
|
||
"MTUSI_RELAY_LOG": str(relay_log_path),
|
||
}
|
||
with log_path.open("wb") as log:
|
||
# своя группа процессов: stop гасит uv, reloader, worker и relay разом.
|
||
# Их запускает сам sh: в группу другой сессии снаружи не войти, а
|
||
# sh без job control оставляет фоновую команду в своей группе, и exec
|
||
# сохраняет её номер. make run_worker подставляет ключи пользователя
|
||
# S3 worker и в вывод их не печатает
|
||
proc = subprocess.Popen(
|
||
[
|
||
"sh",
|
||
"-c",
|
||
'make run_worker >"$MTUSI_WORKER_LOG" 2>&1 </dev/null & '
|
||
'make run_relay >"$MTUSI_RELAY_LOG" 2>&1 </dev/null & '
|
||
"exec uv run python -m src",
|
||
],
|
||
cwd=ROOT,
|
||
env=env,
|
||
stdout=log,
|
||
stderr=subprocess.STDOUT,
|
||
start_new_session=True,
|
||
)
|
||
pid_path.write_text(str(proc.pid))
|
||
deadline = time.monotonic() + 30
|
||
while time.monotonic() < deadline:
|
||
if proc.poll() is not None:
|
||
print(f"server exited with {proc.returncode}; log: {log_path}")
|
||
print(log_path.read_text()[-2000:])
|
||
return 1
|
||
if (
|
||
is_ready(port)
|
||
and WORKER_CONNECTED in worker_log_path.read_text()
|
||
and RELAY_STARTED in relay_log_path.read_text()
|
||
):
|
||
print(
|
||
f"up on {base_url(port)} pgid={proc.pid} log={log_path} "
|
||
f"worker log={worker_log_path} relay log={relay_log_path}",
|
||
)
|
||
return 0
|
||
time.sleep(0.25)
|
||
print(
|
||
f"not ready after 30s; logs: {log_path} {worker_log_path} "
|
||
f"{relay_log_path}",
|
||
)
|
||
return 1
|
||
|
||
|
||
def cmd_stop(port: int) -> int:
|
||
_, pid_path = paths(port)
|
||
if not pid_path.exists():
|
||
# экземпляр не наш (например, make run_dev): не трогаем
|
||
if listener_pids(port):
|
||
print(f"port {port} is not ours (no pid file); left running")
|
||
return 1
|
||
print(f"nothing on {port}")
|
||
return 0
|
||
group = int(pid_path.read_text())
|
||
with contextlib.suppress(ProcessLookupError):
|
||
os.killpg(group, signal.SIGTERM)
|
||
pid_path.unlink()
|
||
deadline = time.monotonic() + 12
|
||
while listener_pids(port) and time.monotonic() < deadline:
|
||
time.sleep(0.2)
|
||
if listener_pids(port):
|
||
print(f"still listening on {port}:", listener_pids(port))
|
||
return 1
|
||
# worker и relay выходят сами, но не дольше срока остановки (≤ 9,5 с)
|
||
while group_alive(group) and time.monotonic() < deadline:
|
||
time.sleep(0.2)
|
||
if group_alive(group):
|
||
print(f"process group {group} is still running")
|
||
return 1
|
||
print(f"stopped {port}")
|
||
return 0
|
||
|
||
|
||
def cmd_status(port: int) -> int:
|
||
pids = listener_pids(port)
|
||
print("listeners:", pids or "none")
|
||
if pids:
|
||
print("ready:", is_ready(port))
|
||
return 0 if pids else 1
|
||
|
||
|
||
def cmd_req(port: int, args: argparse.Namespace) -> int:
|
||
body = json.loads(args.data) if args.data is not None else None
|
||
authorization = None
|
||
if args.basic is not None:
|
||
username, _, password = args.basic.partition(":")
|
||
authorization = basic(username, password)
|
||
method = args.method.upper()
|
||
extra = {}
|
||
sends_message = method == "POST" and args.path.rstrip("/").endswith(
|
||
"/messages",
|
||
)
|
||
if args.key is not None or (sends_message and not args.no_key):
|
||
extra = key_header(args.key)
|
||
# синтетический ключ: для повтора той же отправки через --key
|
||
print("idempotency-key:", extra[IDEMPOTENCY_KEY])
|
||
status, hdrs, payload = call(
|
||
port,
|
||
method,
|
||
args.path,
|
||
token=args.token,
|
||
authorization=authorization,
|
||
extra=extra,
|
||
body=body,
|
||
)
|
||
print(
|
||
status,
|
||
"x-request-id:",
|
||
hdrs.get("x-request-id"),
|
||
"x-instance-id:",
|
||
hdrs.get("x-instance-id"),
|
||
)
|
||
if "www-authenticate" in hdrs:
|
||
print("www-authenticate:", hdrs["www-authenticate"])
|
||
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
||
return 0 if status < 400 else 2
|
||
|
||
|
||
class Flow:
|
||
def __init__(self, port: int) -> None:
|
||
self.port = port
|
||
self.failures = 0
|
||
|
||
def check(self, label: str, ok: bool, detail: object = "") -> None:
|
||
mark = "ok " if ok else "FAIL"
|
||
print(f"[{mark}] {label}" + (f" {detail}" if detail else ""))
|
||
if not ok:
|
||
self.failures += 1
|
||
|
||
def expect(
|
||
self,
|
||
label: str,
|
||
method: str,
|
||
path: str,
|
||
status: int,
|
||
challenge: str | None = None,
|
||
**kwargs: object,
|
||
) -> object:
|
||
"""Запрос + проверка статуса, X-Request-Id, X-Instance-Id (с лабы
|
||
3), формата ошибки и, если задан, `WWW-Authenticate`."""
|
||
got, hdrs, payload = call(self.port, method, path, **kwargs)
|
||
request_id = hdrs.get("x-request-id")
|
||
ok = got == status and bool(request_id)
|
||
ok = ok and bool(hdrs.get("x-instance-id"))
|
||
detail = str(got)
|
||
if got >= 400:
|
||
error = {}
|
||
if isinstance(payload, dict):
|
||
error = payload.get("error", {})
|
||
ok = ok and error.get("request_id") == request_id
|
||
detail = f"{got} {error.get('code')}"
|
||
if challenge is not None:
|
||
ok = ok and hdrs.get("www-authenticate") == challenge
|
||
detail += f" {hdrs.get('www-authenticate')}"
|
||
shown = path if len(path) <= 60 else path[:57] + "..."
|
||
self.check(f"{method} {shown} -> {status} ({label})", ok, detail)
|
||
return payload
|
||
|
||
|
||
def cmd_flow(port: int) -> int:
|
||
flow = Flow(port)
|
||
tag = uuid.uuid4().hex[:8]
|
||
flow.expect("live", "GET", "/health/live", 200)
|
||
flow.expect("ready", "GET", "/health/ready", 200)
|
||
|
||
me_path = f"{USERS}/me"
|
||
ids, tokens, logins = {}, {}, {}
|
||
for name in ("alice", "bob", "eve"):
|
||
username, password = f"{name}_{tag}", f"Pw-{name}-{uuid.uuid4().hex}"
|
||
body = {
|
||
"username": username,
|
||
"display_name": f"{name} ✨",
|
||
"password": password,
|
||
}
|
||
user = flow.expect("register", "POST", USERS, 201, body=body)
|
||
flow.check("no password in User", "password" not in user)
|
||
session = flow.expect(
|
||
"login",
|
||
"POST",
|
||
SESSIONS,
|
||
201,
|
||
authorization=basic(username, password),
|
||
)
|
||
ids[name], tokens[name] = user["id"], session["token"]
|
||
logins[name] = (username, password)
|
||
alice, bob, eve = tokens["alice"], tokens["bob"], tokens["eve"]
|
||
dup = {
|
||
"username": f"alice_{tag}",
|
||
"display_name": "again",
|
||
"password": "Another-password-1",
|
||
}
|
||
flow.expect("duplicate username", "POST", USERS, 409, body=dup)
|
||
no_password = {"username": f"nopw_{tag}", "display_name": "x"}
|
||
flow.expect("no password", "POST", USERS, 400, body=no_password)
|
||
|
||
username, password = logins["alice"]
|
||
wrong = basic(username, "Wrong-password-1")
|
||
flow.expect(
|
||
"wrong password",
|
||
"POST",
|
||
SESSIONS,
|
||
401,
|
||
challenge=BASIC_CHALLENGE,
|
||
authorization=wrong,
|
||
)
|
||
me = flow.expect("me", "GET", me_path, 200, token=alice)
|
||
flow.check("me.id == alice", me.get("id") == ids["alice"])
|
||
flow.expect("no token", "GET", me_path, 401, challenge=BEARER_CHALLENGE)
|
||
flow.expect(
|
||
"Basic on business endpoint",
|
||
"GET",
|
||
me_path,
|
||
401,
|
||
challenge=BEARER_CHALLENGE,
|
||
authorization=basic(username, password),
|
||
)
|
||
flow.expect(
|
||
"only X-User-Id",
|
||
"GET",
|
||
me_path,
|
||
401,
|
||
challenge=BEARER_CHALLENGE,
|
||
extra={"X-User-Id": ids["alice"]},
|
||
)
|
||
spoofed = flow.expect(
|
||
"X-User-Id ignored",
|
||
"GET",
|
||
me_path,
|
||
200,
|
||
token=alice,
|
||
extra={"X-User-Id": ids["eve"]},
|
||
)
|
||
flow.check("still alice", spoofed.get("id") == ids["alice"])
|
||
flow.expect(
|
||
"unknown token",
|
||
"GET",
|
||
me_path,
|
||
401,
|
||
challenge=BEARER_CHALLENGE,
|
||
token=uuid.uuid4().hex * 2,
|
||
)
|
||
|
||
body = {"title": "Проект 🚀", "member_ids": [ids["alice"], ids["bob"]]}
|
||
chat = flow.expect("new chat", "POST", CHATS, 201, token=alice, body=body)
|
||
chat_path = f"{CHATS}/{chat['id']}"
|
||
msgs = f"{chat_path}/messages"
|
||
body = {"title": "x", "member_ids": [ids["alice"]]}
|
||
flow.expect("not a member", "POST", CHATS, 400, token=eve, body=body)
|
||
|
||
texts = ["привет", "hi 👋", "третье", "четвёртое", "пятое"]
|
||
for index, text in enumerate(texts):
|
||
sender = alice if index % 2 == 0 else bob
|
||
body = {"text": text}
|
||
flow.expect(
|
||
"send",
|
||
"POST",
|
||
msgs,
|
||
201,
|
||
token=sender,
|
||
body=body,
|
||
extra=key_header(),
|
||
)
|
||
# с ключом: 400 из-за тела, а не из-за отсутствия ключа
|
||
blank = {"text": " "}
|
||
flow.expect(
|
||
"blank text",
|
||
"POST",
|
||
msgs,
|
||
400,
|
||
token=alice,
|
||
body=blank,
|
||
extra=key_header(),
|
||
)
|
||
spoof = {"text": "x", "sender_id": ids["alice"]}
|
||
flow.expect(
|
||
"sender_id",
|
||
"POST",
|
||
msgs,
|
||
400,
|
||
token=alice,
|
||
body=spoof,
|
||
extra=key_header(),
|
||
)
|
||
|
||
seen, cursor, pages = [], None, 0
|
||
while pages < 10:
|
||
query = "?limit=2" + (f"&cursor={cursor}" if cursor else "")
|
||
page = flow.expect("page", "GET", msgs + query, 200, token=bob)
|
||
seen += [item["text"] for item in page["items"]]
|
||
cursor, pages = page["next_cursor"], pages + 1
|
||
if cursor is None:
|
||
break
|
||
flow.check("history order via cursor", seen == texts, f"{pages} pages")
|
||
flow.check("created_at ends with Z", chat["created_at"].endswith("Z"))
|
||
|
||
flow.expect("outsider reads chat", "GET", chat_path, 404, token=eve)
|
||
flow.expect("outsider reads history", "GET", msgs, 404, token=eve)
|
||
hi = {"text": "hi"}
|
||
flow.expect(
|
||
"outsider posts",
|
||
"POST",
|
||
msgs,
|
||
404,
|
||
token=eve,
|
||
body=hi,
|
||
extra=key_header(),
|
||
)
|
||
|
||
# идемпотентность (лаба 3): повтор, другое тело, нет и неверный ключ
|
||
key = key_header()
|
||
once = {"text": "один раз"}
|
||
sent = flow.expect(
|
||
"keyed send",
|
||
"POST",
|
||
msgs,
|
||
201,
|
||
token=alice,
|
||
body=once,
|
||
extra=key,
|
||
)
|
||
again = flow.expect(
|
||
"replay",
|
||
"POST",
|
||
msgs,
|
||
201,
|
||
token=alice,
|
||
body=once,
|
||
extra=key,
|
||
)
|
||
flow.check("replay returns the same message", again == sent)
|
||
other = {"text": "другое"}
|
||
flow.expect(
|
||
"same key, other body",
|
||
"POST",
|
||
msgs,
|
||
409,
|
||
token=alice,
|
||
body=other,
|
||
extra=key,
|
||
)
|
||
flow.expect("no key", "POST", msgs, 400, token=alice, body=other)
|
||
flow.expect(
|
||
"bad key",
|
||
"POST",
|
||
msgs,
|
||
400,
|
||
token=alice,
|
||
body=other,
|
||
extra=key_header("bad key"),
|
||
)
|
||
history = flow.expect(
|
||
"history",
|
||
"GET",
|
||
msgs + "?limit=100",
|
||
200,
|
||
token=bob,
|
||
)
|
||
keyed = [item for item in history["items"] if item["text"] == once["text"]]
|
||
flow.check("one message per key", len(keyed) == 1, f"{len(keyed)} found")
|
||
flow.expect("no token beats 404", "GET", chat_path, 401)
|
||
flow.expect("limit=0", "GET", msgs + "?limit=0", 400, token=alice)
|
||
flow.expect("bad cursor", "GET", msgs + "?cursor=zzz", 400, token=alice)
|
||
flow.expect("chat_id not uuid", "GET", f"{CHATS}/nope", 400, token=alice)
|
||
flow.expect("malformed json", "POST", USERS, 400, raw=b"{not json")
|
||
flow.expect("unknown path", "GET", "/nope", 404)
|
||
chats = flow.expect("list chats", "GET", CHATS, 200, token=bob)
|
||
listed = [item["id"] for item in chats["items"]]
|
||
flow.check("bob sees the chat", chat["id"] in listed)
|
||
|
||
# вложения (лабы 4 и 5): загрузка fixture 202, сообщение со ссылкой,
|
||
# ожидание ready, оригинал Бобу побайтно, thumbnail, 404 Еве
|
||
data = FIXTURE_PNG.read_bytes()
|
||
status, hdrs, attachment = upload_bytes(
|
||
port,
|
||
alice,
|
||
chat["id"],
|
||
data,
|
||
content_type="image/png",
|
||
filename=FIXTURE_PNG.name,
|
||
)
|
||
uploaded = status == ATTACHMENT_ACCEPTED and isinstance(attachment, dict)
|
||
flow.check(
|
||
f"POST {CHATS}/…/attachments -> 202 (upload fixture)",
|
||
uploaded
|
||
and attachment.get("sha256") == sha256_hex(data)
|
||
and attachment.get("status") == "queued",
|
||
f"{status} {hdrs.get('x-instance-id')}",
|
||
)
|
||
if uploaded:
|
||
attachment_path = f"{ATTACHMENTS}/{attachment['id']}"
|
||
with_file = flow.expect(
|
||
"message with attachment",
|
||
"POST",
|
||
msgs,
|
||
201,
|
||
token=alice,
|
||
body={"text": "", "attachment_ids": [attachment["id"]]},
|
||
extra=key_header(),
|
||
)
|
||
flow.check(
|
||
"attachment_ids in message",
|
||
isinstance(with_file, dict)
|
||
and with_file.get("attachment_ids") == [attachment["id"]],
|
||
)
|
||
ready = wait_attachment(port, bob, str(attachment["id"]))
|
||
flow.check(
|
||
f"GET {ATTACHMENTS}/… -> ready (poll)",
|
||
ready.get("status") == "ready",
|
||
f"{ready.get('status')} {ready.get('error_code')}",
|
||
)
|
||
status, hdrs, payload = call_bytes(
|
||
port,
|
||
"GET",
|
||
f"{attachment_path}/content",
|
||
token=bob,
|
||
)
|
||
flow.check(
|
||
f"GET {ATTACHMENTS}/…/content -> 200 (bob, same sha256)",
|
||
status == 200 and sha256_hex(payload) == sha256_hex(data),
|
||
f"{status} {hdrs.get('content-type')} {len(payload)} bytes",
|
||
)
|
||
status, hdrs, payload = call_bytes(
|
||
port,
|
||
"GET",
|
||
f"{attachment_path}/content?variant=thumbnail",
|
||
token=bob,
|
||
)
|
||
flow.check(
|
||
f"GET {ATTACHMENTS}/…/content?variant=thumbnail -> 200 (JPEG)",
|
||
status == 200 and jpeg_dimensions(payload) == THUMBNAIL_SIZE,
|
||
f"{status} {hdrs.get('content-type')} {jpeg_dimensions(payload)}",
|
||
)
|
||
flow.expect(
|
||
"outsider metadata",
|
||
"GET",
|
||
attachment_path,
|
||
404,
|
||
token=eve,
|
||
)
|
||
flow.expect(
|
||
"outsider content",
|
||
"GET",
|
||
f"{attachment_path}/content",
|
||
404,
|
||
token=eve,
|
||
)
|
||
|
||
flow.expect("logout", "DELETE", f"{SESSIONS}/current", 204, token=eve)
|
||
flow.expect(
|
||
"token after logout",
|
||
"GET",
|
||
me_path,
|
||
401,
|
||
challenge=BEARER_CHALLENGE,
|
||
token=eve,
|
||
)
|
||
|
||
print(
|
||
f"\nalice={ids['alice']}\nbob={ids['bob']}\neve={ids['eve']}"
|
||
f"\nchat={chat['id']}"
|
||
# синтетический токен локального стенда: для `req --token`
|
||
f"\nalice_token={alice}",
|
||
)
|
||
print("FAILED:", flow.failures or "none")
|
||
return 1 if flow.failures else 0
|
||
|
||
|
||
def cmd_smoke(port: int) -> int:
|
||
return subprocess.call(
|
||
[
|
||
sys.executable,
|
||
"tests/smoke.py",
|
||
"--base-url",
|
||
f"http://localhost:{port}",
|
||
],
|
||
cwd=ROOT,
|
||
)
|
||
|
||
|
||
def cmd_student(port: int) -> int:
|
||
if not (ROOT / "student-tests").is_dir():
|
||
print("no student-tests/ in this checkout")
|
||
return 1
|
||
command = ["make", "student_test", f"BASE_URL=http://localhost:{port}"]
|
||
_, pid_path = paths(port)
|
||
if pid_path.exists():
|
||
# на порту свой процесс драйвера: один API без балансировщика,
|
||
# тесты реплик пропускаются с причиной
|
||
command.append("EXPECT_REPLICAS=1")
|
||
return subprocess.call(command, cwd=ROOT)
|
||
|
||
|
||
def cmd_instances(port: int, count: int) -> int:
|
||
"""Распределение одной сессии по репликам: один вход, `count`
|
||
запросов `GET /users/me` с одним токеном. Токен не печатается."""
|
||
tag = uuid.uuid4().hex[:8]
|
||
username, password = f"lb_{tag}", f"Pw-lb-{uuid.uuid4().hex}"
|
||
body = {
|
||
"username": username,
|
||
"display_name": "LB demo",
|
||
"password": password,
|
||
}
|
||
status, _, _ = call(port, "POST", USERS, body=body)
|
||
if status != 201:
|
||
print(f"register: {status}")
|
||
return 1
|
||
status, _, session = call(
|
||
port,
|
||
"POST",
|
||
SESSIONS,
|
||
authorization=basic(username, password),
|
||
)
|
||
if status != 201 or not isinstance(session, dict):
|
||
print(f"login: {status}")
|
||
return 1
|
||
token = session["token"]
|
||
counts: Counter[str] = Counter()
|
||
failures = 0
|
||
for number in range(1, count + 1):
|
||
status, hdrs, payload = call(port, "GET", f"{USERS}/me", token=token)
|
||
instance = hdrs.get("x-instance-id", "-")
|
||
ok = status == 200 and isinstance(payload, dict)
|
||
ok = ok and payload.get("username") == username
|
||
failures += not ok
|
||
print(
|
||
f"{number:>3} GET /api/v1/users/me {status} "
|
||
f"x-instance-id: {instance}" + ("" if ok else " UNEXPECTED"),
|
||
)
|
||
counts[instance] += 1
|
||
print(f"user {username}: one login, {count} requests with one token")
|
||
for instance, served in counts.most_common():
|
||
print(f" {instance}: {served}")
|
||
print(f"instances: {len(counts)}")
|
||
return 1 if failures else 0
|
||
|
||
|
||
def cmd_kill_inflight(
|
||
port: int,
|
||
*,
|
||
threads: int,
|
||
seconds: float,
|
||
after: float,
|
||
) -> int:
|
||
"""Сценарий «Оборванный ответ не повторяется» (спек `load-balancing`).
|
||
|
||
`threads` потоков `seconds` секунд подряд входят по Basic одним
|
||
синтетическим пользователем: Argon2id на реплике с лимитом 1 CPU
|
||
занимает сотни миллисекунд, поэтому в момент kill запросы в полёте
|
||
есть. Через `after` секунд `scripts/stop-one.sh` в режиме kill
|
||
убивает реплику, ответившую на пробный запрос. Пароль и токены не
|
||
печатаются, тела успешных ответов не сохраняются.
|
||
"""
|
||
_, pid_path = paths(port)
|
||
if pid_path.exists():
|
||
print(f"port {port}: console process of the driver, no LB to test")
|
||
return 1
|
||
tag = uuid.uuid4().hex[:8]
|
||
username, password = f"kill_{tag}", f"Pw-kill-{uuid.uuid4().hex}"
|
||
body = {
|
||
"username": username,
|
||
"display_name": "Kill demo",
|
||
"password": password,
|
||
}
|
||
status, _, _ = call(port, "POST", USERS, body=body)
|
||
if status != 201:
|
||
print(f"register: {status}")
|
||
return 1
|
||
authorization = basic(username, password)
|
||
_, probe, _ = call(port, "GET", "/health/live")
|
||
target = probe.get("x-instance-id", "")
|
||
print(f"target replica (X-Instance-Id of a probe): {target}")
|
||
|
||
# (статус, реплика, тело ошибки LB, совпал ли request_id с заголовком)
|
||
results: list[tuple[int, str, object, bool]] = []
|
||
lock = threading.Lock()
|
||
deadline = time.monotonic() + seconds
|
||
|
||
def login() -> None:
|
||
while time.monotonic() < deadline:
|
||
try:
|
||
status, hdrs, payload = call(
|
||
port,
|
||
"POST",
|
||
SESSIONS,
|
||
authorization=authorization,
|
||
)
|
||
except OSError as error:
|
||
status, hdrs, payload = 0, {}, type(error).__name__
|
||
error = None
|
||
same_id = False
|
||
if status >= 500 or status == 0:
|
||
error = payload
|
||
if isinstance(payload, dict) and "error" in payload:
|
||
error = payload["error"]
|
||
same_id = error.get("request_id") == hdrs.get(
|
||
"x-request-id",
|
||
)
|
||
with lock:
|
||
results.append(
|
||
(status, hdrs.get("x-instance-id", "LB"), error, same_id),
|
||
)
|
||
|
||
workers = [threading.Thread(target=login) for _ in range(threads)]
|
||
for worker in workers:
|
||
worker.start()
|
||
time.sleep(after)
|
||
hook = subprocess.run(
|
||
[str(ROOT / "scripts" / "stop-one.sh")],
|
||
cwd=ROOT,
|
||
env=os.environ | {"TARGET_INSTANCE_ID": target, "STOP_MODE": "kill"},
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
print(f"stop-one.sh (kill): exit {hook.returncode}; {hook.stderr.strip()}")
|
||
for worker in workers:
|
||
worker.join()
|
||
|
||
print(f"{len(results)} logins in {seconds:g} s by {threads} threads")
|
||
counts = Counter((status, instance) for status, instance, _, _ in results)
|
||
for (status, instance), served in sorted(counts.items()):
|
||
print(f" {status} via {instance}: {served}")
|
||
cut = [(s, e, same) for s, _, e, same in results if e is not None]
|
||
for status, error, same_id in cut:
|
||
print(
|
||
f" LB error {status}: {json.dumps(error, ensure_ascii=False)}"
|
||
f" request_id == X-Request-Id: {same_id}",
|
||
)
|
||
print(f"replica {target} is left stopped; restore: make replicas")
|
||
if hook.returncode != 0:
|
||
return 1
|
||
if not cut:
|
||
print("no request was in flight on the killed replica: repeat")
|
||
return 1
|
||
unexpected = {status for status, _, _, _ in results} - {201, 502}
|
||
return 1 if unexpected else 0
|
||
|
||
|
||
# статистика HAProxy изнутри контейнера LB, как make lb_stats
|
||
LB_STATS = (
|
||
"exec 3<>/dev/tcp/127.0.0.1/8404 && "
|
||
'printf "GET /stats;csv HTTP/1.0\\r\\n\\r\\n" >&3 && cat <&3'
|
||
)
|
||
# psql в контейнере PostgreSQL рабочего стенда от пользователя образа
|
||
PSQL = (
|
||
'exec psql -U "$POSTGRES_USER" -d "$POSTGRES_DB" -XAtq -v ON_ERROR_STOP=1'
|
||
)
|
||
|
||
|
||
def compose(
|
||
*args: str,
|
||
stdin: str | None = None,
|
||
timeout: float | None = None,
|
||
) -> str:
|
||
"""docker compose рабочего стенда (проект из docker-compose.yml)."""
|
||
proc = subprocess.run(
|
||
["docker", "compose", *args],
|
||
cwd=ROOT,
|
||
input=stdin,
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
timeout=timeout,
|
||
)
|
||
if proc.returncode != 0:
|
||
raise RuntimeError(f"docker compose {args[0]}: {proc.stderr[-500:]}")
|
||
return proc.stdout
|
||
|
||
|
||
def lb_slots(lb: str | None = None) -> list[dict[str, str]]:
|
||
"""Занятые слоты backend `api`: адрес, состояние, соединения.
|
||
|
||
`lb` — имя контейнера LB; по умолчанию сервис `haproxy` стенда.
|
||
"""
|
||
if lb is None:
|
||
text = compose("exec", "-T", "haproxy", "bash", "-c", LB_STATS)
|
||
else:
|
||
proc = subprocess.run(
|
||
["docker", "exec", lb, "bash", "-c", LB_STATS],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
if proc.returncode != 0:
|
||
raise RuntimeError(f"docker exec {lb}: {proc.stderr[-500:]}")
|
||
text = proc.stdout
|
||
lines = [ln for ln in text.splitlines() if ln.startswith(("# ", "api,"))]
|
||
if not lines:
|
||
return []
|
||
rows = csv.DictReader(io.StringIO("\n".join(lines).removeprefix("# ")))
|
||
return [
|
||
row
|
||
for row in rows
|
||
if row["svname"] not in ("BACKEND", "FRONTEND") and row.get("addr")
|
||
]
|
||
|
||
|
||
def no_lb(port: int) -> bool:
|
||
_, pid_path = paths(port)
|
||
if pid_path.exists():
|
||
print(f"port {port}: console process of the driver, no LB to test")
|
||
return True
|
||
return False
|
||
|
||
|
||
def replica_connections(container: str, port: int) -> int:
|
||
"""Установленные TCP-соединения на порт API внутри контейнера
|
||
реплики (`/proc/net/tcp`): то, что реплика держит открытым."""
|
||
out = subprocess.run(
|
||
[
|
||
"docker",
|
||
"exec",
|
||
container,
|
||
"cat",
|
||
"/proc/net/tcp",
|
||
"/proc/net/tcp6",
|
||
],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
).stdout
|
||
suffix = f":{port:04X}"
|
||
return sum(
|
||
1
|
||
for parts in (line.split() for line in out.splitlines())
|
||
if len(parts) > 3
|
||
and parts[0] != "sl"
|
||
and parts[1].endswith(suffix)
|
||
and parts[3] == "01"
|
||
)
|
||
|
||
|
||
def cmd_idle_conns(
|
||
port: int,
|
||
*,
|
||
threads: int,
|
||
requests: int,
|
||
keep_alive: float,
|
||
lb: str | None = None,
|
||
) -> int:
|
||
"""Простаивающие соединения LB → реплика (решение 3 design change
|
||
`graceful-failover`): их должен закрыть LB раньше, чем реплика по
|
||
своему сроку keep-alive.
|
||
|
||
Клиенты после всплеска остаются подключены и молчат, как браузер
|
||
между запросами. Каждую секунду — соединения на порт API внутри
|
||
каждой реплики и пул LB. Реплика закрыла бы их через `keep_alive`
|
||
секунд, LB — через свой `timeout http-keep-alive` (10 с): по тому,
|
||
когда они исчезли, видно, кто закрыл.
|
||
|
||
`lb` — контейнер LB, если `--port` ведёт не на LB стенда: так
|
||
проверяется другой вариант конфигурации LB перед теми же репликами
|
||
(verify change `graceful-failover`, `evidence/failover/keep-alive.md`).
|
||
"""
|
||
if no_lb(port):
|
||
return 1
|
||
statuses: Counter[int] = Counter()
|
||
lock = threading.Lock()
|
||
clients: list[http.client.HTTPConnection] = []
|
||
|
||
def burst() -> None:
|
||
# одно keep-alive соединение клиента на поток, после всплеска
|
||
# остаётся открытым
|
||
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=5)
|
||
with lock:
|
||
clients.append(conn)
|
||
for _ in range(requests):
|
||
conn.request("GET", "/health/live")
|
||
response = conn.getresponse()
|
||
response.read()
|
||
with lock:
|
||
statuses[response.status] += 1
|
||
|
||
replicas = {}
|
||
for container in compose("ps", "-q", "api").split():
|
||
address = subprocess.run(
|
||
[
|
||
"docker",
|
||
"inspect",
|
||
"-f",
|
||
"{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}",
|
||
container,
|
||
],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
).stdout.strip()
|
||
replicas[container] = address
|
||
slots = {row["addr"].rsplit(":", 1)[0]: row for row in lb_slots(lb)}
|
||
api_port = int(next(iter(slots.values()))["addr"].rsplit(":", 1)[1])
|
||
workers = [threading.Thread(target=burst) for _ in range(threads)]
|
||
for worker in workers:
|
||
worker.start()
|
||
for worker in workers:
|
||
worker.join()
|
||
last = time.monotonic()
|
||
print(
|
||
f"burst: {threads} keep-alive clients × {requests} GET /health/live "
|
||
f"through LB: {dict(statuses)}; clients stay connected and idle",
|
||
)
|
||
print("t, s replica: connections on its API port | LB pool idle+safe")
|
||
zero_since: float | None = None
|
||
try:
|
||
while True:
|
||
elapsed = time.monotonic() - last
|
||
held = {
|
||
container: replica_connections(container, api_port)
|
||
for container in replicas
|
||
}
|
||
pools = {
|
||
container: sum(
|
||
int(slots_now.get(field) or 0)
|
||
for field in ("idle_conn_cur", "safe_conn_cur")
|
||
)
|
||
for container, address in replicas.items()
|
||
for slots_now in [
|
||
{
|
||
row["addr"].rsplit(":", 1)[0]: row
|
||
for row in lb_slots(lb)
|
||
}.get(address, {}),
|
||
]
|
||
}
|
||
print(
|
||
f"{elapsed:5.1f} "
|
||
+ " ".join(
|
||
f"{container[:12]}: {held[container]} | {pools[container]}"
|
||
for container in replicas
|
||
),
|
||
flush=True,
|
||
)
|
||
# проверка LB открывает соединение на миг: ноль — дважды подряд
|
||
if any(held.values()):
|
||
zero_since = None
|
||
elif zero_since is None:
|
||
zero_since = elapsed
|
||
else:
|
||
# раньше срока реплики закрыть мог только LB
|
||
by_lb = zero_since < keep_alive
|
||
print(
|
||
f"replicas hold no connections {zero_since:.1f} s after "
|
||
f"the last request (replica keep-alive {keep_alive:g} "
|
||
f"s): closed by {'LB' if by_lb else 'the replica'}",
|
||
)
|
||
return 0 if by_lb else 1
|
||
if elapsed > keep_alive + 10:
|
||
print(f"replicas still hold connections after {elapsed:.0f} s")
|
||
return 1
|
||
time.sleep(max(0.0, last + elapsed + 1 - time.monotonic()))
|
||
finally:
|
||
for conn in clients:
|
||
conn.close()
|
||
|
||
|
||
def cmd_hang_key(port: int) -> int:
|
||
"""Сценарий «Повтор ключа после зависшей реплики» (спек
|
||
`load-balancing`, решение 4 design change `graceful-failover`).
|
||
|
||
Пробный текст уникален: триггер задерживает вставку только этого
|
||
сообщения (`pg_sleep`), другие запросы стенда он не трогает. Имена
|
||
функции и триггера — с меткой запуска. Триггер удаляется в `finally`
|
||
при любом исходе: SIGTERM и SIGHUP превращаются в `KeyboardInterrupt`,
|
||
как Ctrl+C. Если удалить не удалось (PostgreSQL недоступен, второе
|
||
прерывание), команда печатает SQL удаления и завершается с кодом 1.
|
||
От SIGKILL уборки нет. Пароль, токен и ключ не печатаются.
|
||
"""
|
||
if no_lb(port):
|
||
return 1
|
||
|
||
def interrupted(signum: int, _frame: object) -> None:
|
||
raise KeyboardInterrupt(signal.Signals(signum).name)
|
||
|
||
previous = {
|
||
signum: signal.signal(signum, interrupted)
|
||
for signum in (signal.SIGTERM, signal.SIGHUP)
|
||
}
|
||
try:
|
||
return hang_key(port)
|
||
finally:
|
||
for signum, handler in previous.items():
|
||
signal.signal(signum, handler)
|
||
|
||
|
||
def hang_key(port: int) -> int:
|
||
"""Тело `cmd_hang_key`: сценарий и уборка триггера."""
|
||
tag = uuid.uuid4().hex[:8]
|
||
username, password = f"hang_{tag}", f"Pw-hang-{uuid.uuid4().hex}"
|
||
status, _, user = call(
|
||
port,
|
||
"POST",
|
||
USERS,
|
||
body={
|
||
"username": username,
|
||
"display_name": "Hang demo",
|
||
"password": password,
|
||
},
|
||
)
|
||
if status != 201 or not isinstance(user, dict):
|
||
print(f"register: {status}")
|
||
return 1
|
||
status, _, session = call(
|
||
port,
|
||
"POST",
|
||
SESSIONS,
|
||
authorization=basic(username, password),
|
||
)
|
||
if status != 201 or not isinstance(session, dict):
|
||
print(f"login: {status}")
|
||
return 1
|
||
token = session["token"]
|
||
status, _, chat = call(
|
||
port,
|
||
"POST",
|
||
CHATS,
|
||
token=token,
|
||
body={"title": "Hang demo", "member_ids": [user["id"]]},
|
||
)
|
||
if status != 201 or not isinstance(chat, dict):
|
||
print(f"create chat: {status}")
|
||
return 1
|
||
text = f"hang-probe-{tag}"
|
||
path = f"{CHATS}/{chat['id']}/messages"
|
||
key = key_header()
|
||
# метка — hex: в SQL безопасна и отделяет одновременные запуски
|
||
probe = f"hang_probe_{tag}"
|
||
trigger = (
|
||
f"CREATE OR REPLACE FUNCTION {probe}() RETURNS trigger "
|
||
"LANGUAGE plpgsql AS $$ BEGIN PERFORM pg_sleep(2); RETURN NEW; "
|
||
"END $$;\n"
|
||
f"CREATE TRIGGER {probe} BEFORE INSERT ON messages FOR EACH ROW "
|
||
f"WHEN (NEW.text = '{text}') EXECUTE FUNCTION {probe}();\n"
|
||
)
|
||
cleanup = (
|
||
f"DROP TRIGGER IF EXISTS {probe} ON messages;\n"
|
||
f"DROP FUNCTION IF EXISTS {probe}();\n"
|
||
)
|
||
started = time.time()
|
||
t0 = time.monotonic()
|
||
paused: str | None = None
|
||
first: list[tuple[int, str, float]] = []
|
||
|
||
def send(timeout: float) -> tuple[int, str]:
|
||
try:
|
||
status, hdrs, _ = call(
|
||
port,
|
||
"POST",
|
||
path,
|
||
token=token,
|
||
extra=key,
|
||
body={"text": text},
|
||
timeout=timeout,
|
||
)
|
||
except OSError as error:
|
||
return 0, type(error).__name__
|
||
return status, hdrs.get("x-instance-id", "LB")
|
||
|
||
def original() -> None:
|
||
status, instance = send(30)
|
||
first.append((status, instance, time.monotonic() - t0))
|
||
|
||
try:
|
||
compose("exec", "-T", "postgres", "sh", "-c", PSQL, stdin=trigger)
|
||
print(f"trigger {probe}: INSERT of the probe message sleeps 2 s")
|
||
# daemon: прерывание не ждёт исходного запроса (до 30 с)
|
||
sender = threading.Thread(target=original, daemon=True)
|
||
sender.start()
|
||
address = ""
|
||
deadline = time.monotonic() + 3
|
||
while not address and time.monotonic() < deadline:
|
||
address = compose(
|
||
"exec",
|
||
"-T",
|
||
"postgres",
|
||
"sh",
|
||
"-c",
|
||
PSQL,
|
||
stdin="SELECT host(client_addr) FROM pg_stat_activity "
|
||
"WHERE wait_event = 'PgSleep' "
|
||
"AND application_name = 'mtusi-messenger';\n",
|
||
).strip()
|
||
ids = compose("ps", "-q", "api").split()
|
||
for container in ids:
|
||
ip = subprocess.run(
|
||
[
|
||
"docker",
|
||
"inspect",
|
||
"-f",
|
||
"{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}",
|
||
container,
|
||
],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
).stdout.strip()
|
||
if address and ip == address.splitlines()[0]:
|
||
paused = container
|
||
if paused is None:
|
||
print(f"replica of the probe INSERT not found ({address!r})")
|
||
return 1
|
||
timeout_setting = subprocess.run(
|
||
[
|
||
"docker",
|
||
"exec",
|
||
paused,
|
||
"python",
|
||
"-c",
|
||
"import asyncio\n"
|
||
"from sqlalchemy import text\n"
|
||
"from src.infra.db.session import engine\n"
|
||
"async def main():\n"
|
||
" async with engine.connect() as c:\n"
|
||
" r = await c.execute(text("
|
||
"'SHOW idle_in_transaction_session_timeout'))\n"
|
||
" print(r.scalar())\n"
|
||
" await engine.dispose()\n"
|
||
"asyncio.run(main())\n",
|
||
],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
).stdout.strip()
|
||
subprocess.run(
|
||
["docker", "pause", paused],
|
||
check=True,
|
||
capture_output=True,
|
||
)
|
||
mark = time.monotonic() - t0
|
||
print(
|
||
f"{mark:5.2f} s paused replica {paused[:12]} inside the "
|
||
"transaction with the key (INSERT of the probe message); its "
|
||
f"connections: idle_in_transaction_session_timeout = "
|
||
f"{timeout_setting or '?'}",
|
||
)
|
||
done = False
|
||
while not done and time.monotonic() - t0 < 60:
|
||
start = time.monotonic() - t0
|
||
status, instance = send(15)
|
||
spent = time.monotonic() - t0 - start
|
||
print(
|
||
f"{start:5.2f} s retry with the same key: {status} via "
|
||
f"{instance} in {spent:.2f} s",
|
||
flush=True,
|
||
)
|
||
done = status == 201
|
||
if not done:
|
||
time.sleep(0.5)
|
||
sender.join()
|
||
for status, instance, at in first:
|
||
print(
|
||
f"{at:5.2f} s original request answered: {status} via {instance}",
|
||
)
|
||
logs = compose(
|
||
"logs",
|
||
"--no-log-prefix",
|
||
"--since",
|
||
f"{started:.0f}",
|
||
"postgres",
|
||
)
|
||
terminated = [
|
||
ln for ln in logs.splitlines() if "idle-in-transaction" in ln
|
||
]
|
||
for line in terminated:
|
||
# отметка журнала PostgreSQL — часы ВМ, близкие к часам хоста
|
||
stamp = datetime.strptime(line[:23], "%Y-%m-%d %H:%M:%S.%f")
|
||
at = stamp.replace(tzinfo=UTC).timestamp() - started
|
||
print(f"{at:5.2f} s postgres: {line.strip()}")
|
||
subprocess.run(
|
||
["docker", "unpause", paused],
|
||
check=True,
|
||
capture_output=True,
|
||
)
|
||
print(f"{time.monotonic() - t0:5.2f} s unpaused {paused[:12]}")
|
||
paused = None
|
||
deadline = time.monotonic() + 15
|
||
up = False
|
||
while not up and time.monotonic() < deadline:
|
||
up = all(row["status"] == "UP" for row in lb_slots())
|
||
if not up:
|
||
time.sleep(0.5)
|
||
status, _, page = call(port, "GET", f"{path}?limit=100", token=token)
|
||
items = page.get("items", []) if isinstance(page, dict) else []
|
||
count = sum(1 for item in items if item.get("text") == text)
|
||
print(
|
||
f"chat history: {status}, {count} message(s) with the probe text; "
|
||
f"all replicas UP in LB: {up}",
|
||
)
|
||
return 0 if done and count == 1 and terminated and up else 1
|
||
finally:
|
||
if paused is not None:
|
||
subprocess.run(
|
||
["docker", "unpause", paused],
|
||
check=False,
|
||
capture_output=True,
|
||
)
|
||
try:
|
||
compose("exec", "-T", "postgres", "sh", "-c", PSQL, stdin=cleanup)
|
||
except (RuntimeError, OSError, KeyboardInterrupt) as error:
|
||
print(
|
||
f"trigger {probe} NOT removed ({error!r}); remove it from "
|
||
f"the repository root:\n docker compose exec -T postgres "
|
||
f"sh -c '{PSQL}' <<'SQL'\n{cleanup}SQL",
|
||
flush=True,
|
||
)
|
||
raise SystemExit(1) from error
|
||
print(f"trigger {probe} removed", flush=True)
|
||
|
||
|
||
# cache-check: начало ключа карточки — копия CACHE_KEY_PREFIX из
|
||
# src/utils/constants.py, как в student-tests/fault_hook.py
|
||
CACHE_KEY_PREFIX = "messenger:v1"
|
||
# простаивающий backend PostgreSQL сбрасывает счётчики таблиц не сразу, а
|
||
# до 10 с спустя (PGSTAT_IDLE_INTERVAL): снимок — через 11 с после запросов
|
||
PGSTAT_WAIT_S = 11
|
||
CACHE_READS = 50
|
||
CACHE_TTL_READS = 10
|
||
CHAT_CARD_KEYS = {"id", "title", "member_ids", "created_at"}
|
||
# префикс строки Argon2id без соли: алгоритм, версия и параметры
|
||
ARGON2_PREFIX_LEN = 31
|
||
|
||
|
||
def short_name(username: str) -> str:
|
||
return username.split("_", 1)[0] + "_…"
|
||
|
||
|
||
def stand_psql(sql: str) -> str:
|
||
"""psql в контейнере PostgreSQL рабочего стенда, SQL через stdin."""
|
||
return compose("exec", "-T", "postgres", "sh", "-c", PSQL, stdin=sql)
|
||
|
||
|
||
def stand_valkey(*args: str) -> str:
|
||
"""valkey-cli рабочего стенда: пароль — VALKEYCLI_AUTH контейнера,
|
||
аргументы — позиционные параметры sh, без подстановки в строку."""
|
||
return compose(
|
||
"exec",
|
||
"-T",
|
||
"valkey",
|
||
"sh",
|
||
"-c",
|
||
'exec valkey-cli -p "$VALKEY_PORT" "$@"',
|
||
"sh",
|
||
*args,
|
||
).strip()
|
||
|
||
|
||
def valkey_stats() -> tuple[int, int]:
|
||
"""`keyspace_hits` и `keyspace_misses` из `INFO stats`."""
|
||
values = {}
|
||
for line in stand_valkey("INFO", "stats").splitlines():
|
||
name, _, value = line.strip().partition(":")
|
||
if name in ("keyspace_hits", "keyspace_misses"):
|
||
values[name] = int(value)
|
||
return values["keyspace_hits"], values["keyspace_misses"]
|
||
|
||
|
||
def chats_reads() -> int:
|
||
"""Чтения таблицы chats: `seq_scan + idx_scan` (`pg_stat_user_tables`)."""
|
||
return int(
|
||
stand_psql(
|
||
"SELECT coalesce(seq_scan, 0) + coalesce(idx_scan, 0) "
|
||
"FROM pg_stat_user_tables WHERE relname = 'chats';\n",
|
||
).strip(),
|
||
)
|
||
|
||
|
||
def register_user(
|
||
port: int,
|
||
prefix: str,
|
||
password: str,
|
||
) -> dict[str, object] | None:
|
||
"""Регистрация синтетического пользователя; тело `User` или None."""
|
||
status, _, user = call(
|
||
port,
|
||
"POST",
|
||
USERS,
|
||
body={
|
||
"username": f"{prefix}_{uuid.uuid4().hex[:8]}",
|
||
"display_name": prefix.capitalize(),
|
||
"password": password,
|
||
},
|
||
)
|
||
if status != 201 or not isinstance(user, dict):
|
||
print(f"register {prefix}: {status}")
|
||
return None
|
||
return user
|
||
|
||
|
||
def synthetic_user(
|
||
port: int,
|
||
prefix: str,
|
||
password: str,
|
||
) -> tuple[dict[str, object], str] | None:
|
||
"""Регистрация и вход по Basic; (пользователь, токен) или None."""
|
||
user = register_user(port, prefix, password)
|
||
if user is None:
|
||
return None
|
||
status, _, session = call(
|
||
port,
|
||
"POST",
|
||
SESSIONS,
|
||
authorization=basic(str(user["username"]), password),
|
||
)
|
||
if status != 201 or not isinstance(session, dict):
|
||
print(f"login {prefix}: {status}")
|
||
return None
|
||
return user, session["token"]
|
||
|
||
|
||
def cmd_cache_check(port: int, *, require_test_keys: bool) -> int:
|
||
"""Сценарии `chat-cache` «Чтение из кэша», «Срок записи» и «Временная
|
||
база» на стенде с LB (решение 1 design change `fix-known-issues`).
|
||
|
||
«Временная база» проверяется только при ключах `test_<db>` (перед
|
||
командой — `make test_isolated`). С `require_test_keys` их отсутствие
|
||
— FAIL, без него — PASS с пометкой «not checked»: доказательство
|
||
сценария снимается с флагом.
|
||
|
||
Между двумя снимками счётчиков — только `CACHE_READS` чтений карточки
|
||
через LB: к ключу драйвер в это время не обращается (`EXISTS`, `TTL`
|
||
и `GET` Valkey тоже считает в `keyspace_hits`). Ключ перед окном
|
||
удаляется: первое чтение — промах и одно чтение `chats`. Во время
|
||
команды на стенде не должно идти ничего другого: счётчики — всей
|
||
таблицы и всего Valkey. Токены и пароли не печатаются, название чата
|
||
тоже; пользователи и чат остаются в рабочей базе."""
|
||
if no_lb(port):
|
||
return 1
|
||
password = f"Pw-cache-{uuid.uuid4().hex}"
|
||
alice = synthetic_user(port, "alice", password)
|
||
bob = synthetic_user(port, "bob", password)
|
||
if alice is None or bob is None:
|
||
return 1
|
||
(alice_user, alice_token), (bob_user, bob_token) = alice, bob
|
||
status, _, chat = call(
|
||
port,
|
||
"POST",
|
||
CHATS,
|
||
token=alice_token,
|
||
body={
|
||
"title": "Cache check",
|
||
"member_ids": [bob_user["id"], alice_user["id"]],
|
||
},
|
||
)
|
||
if status != 201 or not isinstance(chat, dict):
|
||
print(f"create chat: {status}")
|
||
return 1
|
||
database = compose("exec", "-T", "postgres", "printenv", "POSTGRES_DB")
|
||
database = database.strip()
|
||
key = f"{CACHE_KEY_PREFIX}:{database}:chat:{chat['id']}"
|
||
exists = stand_valkey("EXISTS", key)
|
||
ttl0 = int(stand_valkey("TTL", key))
|
||
replica = compose("ps", "-q", "api").split()[0]
|
||
configured = int(
|
||
subprocess.run(
|
||
[
|
||
"docker",
|
||
"exec",
|
||
replica,
|
||
"python",
|
||
"-c",
|
||
"from src.config import settings; "
|
||
"print(settings.cache.chat_ttl_seconds)",
|
||
],
|
||
capture_output=True,
|
||
text=True,
|
||
check=True,
|
||
).stdout.strip(),
|
||
)
|
||
try:
|
||
card = json.loads(stand_valkey("GET", key))
|
||
except json.JSONDecodeError:
|
||
card = None
|
||
card_ok = (
|
||
isinstance(card, dict)
|
||
and set(card) == CHAT_CARD_KEYS
|
||
and card["member_ids"] == chat["member_ids"]
|
||
and card["id"] == chat["id"]
|
||
)
|
||
print(
|
||
f"users {short_name(alice_user['username'])} (creator) and "
|
||
f"{short_name(bob_user['username'])} (reader), chat {chat['id']}",
|
||
)
|
||
print(f"key {key}")
|
||
print(
|
||
f"right after 201: EXISTS {exists}, TTL {ttl0} s (configured "
|
||
f"[cache] chat_ttl_seconds {configured} s in the replica); value "
|
||
f"keys {sorted(card) if isinstance(card, dict) else '-'}, member_ids "
|
||
f"in creation order: {'yes' if card_ok else 'no'}",
|
||
)
|
||
stand_valkey("DEL", key)
|
||
print(f"DEL key: the first read is a miss; waiting {PGSTAT_WAIT_S} s")
|
||
time.sleep(PGSTAT_WAIT_S)
|
||
reads_before = chats_reads()
|
||
hits_before, misses_before = valkey_stats()
|
||
instances: Counter[str] = Counter()
|
||
bad = 0
|
||
path = f"{CHATS}/{chat['id']}"
|
||
|
||
def read() -> None:
|
||
nonlocal bad
|
||
status, hdrs, payload = call(port, "GET", path, token=bob_token)
|
||
instances[hdrs.get("x-instance-id", "LB")] += 1
|
||
bad += status != 200 or payload != chat
|
||
|
||
for _ in range(CACHE_READS):
|
||
read()
|
||
time.sleep(PGSTAT_WAIT_S)
|
||
reads = chats_reads() - reads_before
|
||
hits_after, misses_after = valkey_stats()
|
||
hits, misses = hits_after - hits_before, misses_after - misses_before
|
||
print(
|
||
f"{CACHE_READS} × GET {CHATS}/{{id}} by the reader through LB: "
|
||
f"{CACHE_READS - bad} equal to the creation response; by replica "
|
||
+ ", ".join(f"{i} {n}" for i, n in sorted(instances.items())),
|
||
)
|
||
print(
|
||
f"after {PGSTAT_WAIT_S} s: reads of table chats (seq_scan + "
|
||
f"idx_scan) +{reads}, keyspace_hits +{hits}, keyspace_misses "
|
||
f"+{misses}",
|
||
)
|
||
ttl_a = int(stand_valkey("TTL", key))
|
||
for _ in range(CACHE_TTL_READS):
|
||
read()
|
||
ttl_b = int(stand_valkey("TTL", key))
|
||
print(
|
||
f"TTL {ttl_a} s, then {CACHE_TTL_READS} more reads, TTL {ttl_b} s: "
|
||
f"reads {'do not extend' if ttl_b <= ttl_a else 'EXTEND'} the key",
|
||
)
|
||
counts = {}
|
||
for name in (database, f"test_{database}"):
|
||
pattern = f"{CACHE_KEY_PREFIX}:{name}:chat:*"
|
||
keys = stand_valkey("--scan", "--pattern", pattern)
|
||
counts[name] = len(keys.split())
|
||
print(f"keys {pattern}: {counts[name]}")
|
||
test_keys = counts[f"test_{database}"]
|
||
if not test_keys:
|
||
print(
|
||
"no keys of the test database: run make test_isolated before "
|
||
"this command for the scenario «Временная база»",
|
||
)
|
||
problems = []
|
||
if require_test_keys and not test_keys:
|
||
problems.append("no keys of the test database (--require-test-keys)")
|
||
if reads > 1:
|
||
problems.append(f"table chats read {reads} times")
|
||
if hits < CACHE_READS - 1 or misses > 1:
|
||
problems.append(f"cache hits +{hits}, misses +{misses}")
|
||
if bad:
|
||
problems.append(f"{bad} reads differ from the creation response")
|
||
if exists != "1" or not card_ok:
|
||
problems.append("card is not written after commit as expected")
|
||
if not 0 < ttl0 <= configured or not ttl_b <= ttl_a < ttl0:
|
||
problems.append(f"TTL {ttl0} / {ttl_a} / {ttl_b} s")
|
||
if len(instances) < 2:
|
||
problems.append(f"{len(instances)} X-Instance-Id seen")
|
||
if problems:
|
||
print("FAIL: " + "; ".join(problems))
|
||
return 1
|
||
temporary = (
|
||
f"temporary database: {test_keys} keys under its own prefix"
|
||
if test_keys
|
||
else "temporary database: not checked, run make test_isolated first"
|
||
)
|
||
print(
|
||
"PASS: one read of chats, the rest from Valkey; TTL is bounded; "
|
||
+ temporary,
|
||
)
|
||
return 0
|
||
|
||
|
||
def cmd_auth_storage(port: int) -> int:
|
||
"""Сценарии `sessions` «Токена нет в хранилище» и `users` «Хэш в БД»
|
||
(решение 1 design change `fix-known-issues`).
|
||
|
||
Пароль P (синтетический, с `:` и кириллицей) и токен T живут только в
|
||
памяти процесса. Печатаются факты, счётчики и префикс строки Argon2id
|
||
до соли; дамп базы читается в память и никуда не пишется."""
|
||
if no_lb(port):
|
||
return 1
|
||
password = f"Пароль:{secrets.token_urlsafe(18)}:ключ"
|
||
# вход только первого: второй нужен лишь для второго хэша того же P
|
||
first = synthetic_user(port, "auth", password)
|
||
user2 = register_user(port, "auth", password)
|
||
if first is None or user2 is None:
|
||
return 1
|
||
user1, token = first
|
||
names = (user1["username"], user2["username"])
|
||
# username — синтетические [a-z0-9_], hex — безопасны в тексте SQL
|
||
rows = stand_psql(
|
||
"SELECT left(password_hash, "
|
||
f"{ARGON2_PREFIX_LEN}), length(password_hash) FROM users "
|
||
f"WHERE username IN ('{names[0]}', '{names[1]}') ORDER BY username;\n"
|
||
"SELECT a.password_hash <> b.password_hash FROM users a, users b "
|
||
f"WHERE a.username = '{names[0]}' AND b.username = '{names[1]}';\n",
|
||
).splitlines()
|
||
hashes = [row.split("|") for row in rows[:2]]
|
||
differ = rows[2].strip() if len(rows) > 2 else "?"
|
||
digest = hashlib.sha256(token.encode()).hexdigest()
|
||
session = stand_psql(
|
||
"SELECT count(*), coalesce(max(octet_length(token_hash)), 0) "
|
||
f"FROM sessions WHERE token_hash = decode('{digest}', 'hex');\n",
|
||
).strip()
|
||
count, length = (int(x) for x in session.split("|"))
|
||
dump = compose(
|
||
"exec",
|
||
"-T",
|
||
"postgres",
|
||
"sh",
|
||
"-c",
|
||
'exec pg_dump -U "$POSTGRES_USER" -d "$POSTGRES_DB" --data-only',
|
||
)
|
||
blocks = sum(1 for line in dump.splitlines() if line.startswith("COPY "))
|
||
token_text = token in dump
|
||
token_hex = token.encode().hex() in dump
|
||
password_text = password in dump
|
||
print(
|
||
f"users {short_name(names[0])} and {short_name(names[1])}: same "
|
||
f"password P ({len(password)} characters with ':' and Cyrillic)",
|
||
)
|
||
# zip(strict=) — 3.10+, драйвер работает и на 3.9
|
||
for prefix, size in hashes:
|
||
print(f" password_hash {prefix}… ({size} chars)")
|
||
print(f" hashes differ: {differ}")
|
||
print(
|
||
f"session of the first user: token T ({len(token)} characters); rows "
|
||
f"of sessions with token_hash = SHA-256(T): {count}, "
|
||
f"octet_length {length}",
|
||
)
|
||
print(
|
||
f"pg_dump --data-only: {blocks} COPY blocks; T as text: "
|
||
f"{'yes' if token_text else 'no'}, T in hex: "
|
||
f"{'yes' if token_hex else 'no'}, P as text: "
|
||
f"{'yes' if password_text else 'no'}",
|
||
)
|
||
problems = []
|
||
if len(hashes) != 2 or any(
|
||
not p.startswith("$argon2id$") for p, _ in hashes
|
||
):
|
||
problems.append("password_hash is not Argon2id")
|
||
if differ != "t":
|
||
problems.append("hashes of the same password are equal")
|
||
if count != 1 or length != hashlib.sha256().digest_size:
|
||
problems.append(f"sessions rows {count}, token_hash {length} bytes")
|
||
if token_text or token_hex or password_text:
|
||
problems.append("T or P found in the dump")
|
||
if problems:
|
||
print("FAIL: " + "; ".join(problems))
|
||
return 1
|
||
print("PASS: only Argon2id strings and SHA-256 of the token are stored")
|
||
return 0
|
||
|
||
|
||
# s3-check: проверочный объект режима check bootstrap S3
|
||
S3_CHECK_KEY = ".s3-check/probe"
|
||
# строки проверок bootstrap: «s3-bootstrap: check<TAB>имя<TAB>ожидаемо…»
|
||
S3_CHECK_ROW = "s3-bootstrap: check\t"
|
||
# список уборщика: префиксы вложений и staging своей базы (design change
|
||
# pipeline-reliability, решение 9)
|
||
S3_REQUIRED_ROWS = (
|
||
"cleaner key list attachments prefix",
|
||
"cleaner key list staging prefix",
|
||
"cleaner key list database prefix",
|
||
)
|
||
# слушающие сокеты контейнера S3 (busybox netstat образа): вне loopback
|
||
# должны быть только API S3 и gRPC шлюза, остальные — только на loopback.
|
||
# Список берётся с сервера, а не задаётся заранее: новый выпуск SeaweedFS
|
||
# с новым портом список не обойдёт
|
||
S3_LISTEN_COMMAND = "exec netstat -tuln"
|
||
# анонимные запросы из сети стенда и порты контейнера S3: одноразовый
|
||
# контейнер на образе сервера (curl и nc в нём есть). Строки — как у
|
||
# bootstrap: имя, ожидаемо, получено
|
||
S3_NETWORK_SCRIPT = r"""
|
||
set -u
|
||
code() { curl -s -o /dev/null -w '%{http_code}' --max-time 5 "$@" || echo 000; }
|
||
row() { printf 'row\t%s\t%s\t%s\n' "$1" "$2" "$3"; }
|
||
base="http://$S3_HOST:$S3_PORT"
|
||
row "anonymous get object" 403 "$(code "$base/$S3_BUCKET/$S3_KEY")"
|
||
row "anonymous head object" 403 "$(code -I "$base/$S3_BUCKET/$S3_KEY")"
|
||
row "anonymous get missing object" 403 "$(code "$base/$S3_BUCKET/.s3-check/missing")"
|
||
row "anonymous list objects" 403 "$(code "$base/$S3_BUCKET?list-type=2")"
|
||
row "anonymous list buckets" 403 "$(code "$base/")"
|
||
row "anonymous put object" 403 "$(code -X PUT --data-binary x "$base/$S3_BUCKET/.s3-check/anonymous")"
|
||
for p in $S3_PORT $S3_GRPC_PORT; do
|
||
if nc -z -w 2 "$S3_HOST" "$p"; then got=open; else got=closed; fi
|
||
row "port $p (S3 API / gRPC of gateway)" open "$got"
|
||
done
|
||
for p in $S3_CLOSED; do
|
||
if nc -z -w 2 "$S3_HOST" "$p"; then got=open; else got=closed; fi
|
||
row "port $p (loopback only)" closed "$got"
|
||
done
|
||
"""
|
||
|
||
|
||
def s3_listening() -> tuple[list[str], list[int]]:
|
||
"""Слушающие сокеты контейнера `s3`: вне loopback (TCP — номер порта,
|
||
UDP — `udp/<порт>`) и TCP-порты только на loopback."""
|
||
outside_tcp: set[int] = set()
|
||
outside_udp: set[int] = set()
|
||
loopback_tcp: set[int] = set()
|
||
netstat = compose("exec", "-T", "s3", "sh", "-c", S3_LISTEN_COMMAND)
|
||
for line in netstat.splitlines():
|
||
parts = line.split()
|
||
if len(parts) < 4 or not parts[0].startswith(("tcp", "udp")):
|
||
continue
|
||
host, port = parts[3].rsplit(":", 1)
|
||
try:
|
||
on_loopback = ipaddress.ip_address(host).is_loopback
|
||
except ValueError:
|
||
on_loopback = False
|
||
tcp = parts[0].startswith("tcp")
|
||
if on_loopback:
|
||
if tcp:
|
||
loopback_tcp.add(int(port))
|
||
elif tcp:
|
||
outside_tcp.add(int(port))
|
||
else:
|
||
outside_udp.add(int(port))
|
||
outside = [str(p) for p in sorted(outside_tcp)]
|
||
outside += [f"udp/{p}" for p in sorted(outside_udp)]
|
||
return outside, sorted(loopback_tcp - outside_tcp)
|
||
|
||
|
||
def s3_stand() -> dict[str, str]:
|
||
"""Параметры S3 стенда из `docker compose config` без секретов:
|
||
проект, образ, адрес и порт в сети, порт на хосте, bucket."""
|
||
config = json.loads(compose("config", "--format", "json"))
|
||
services = config["services"]
|
||
s3 = services["s3"]
|
||
published = next(
|
||
p for p in s3.get("ports", []) if p.get("host_ip") == "127.0.0.1"
|
||
)
|
||
api_env = services["api"]["environment"]
|
||
return {
|
||
"project": config["name"],
|
||
"image": s3["image"],
|
||
"host": str(api_env["S3__HOST"]),
|
||
"port": str(published["target"]),
|
||
"out_port": str(published["published"]),
|
||
"bucket": str(services["s3-bootstrap"]["environment"]["S3_BUCKET"]),
|
||
}
|
||
|
||
|
||
def anonymous_code(
|
||
url: str,
|
||
method: str = "GET",
|
||
data: bytes | None = None,
|
||
) -> str:
|
||
request = urllib.request.Request(url, method=method, data=data)
|
||
try:
|
||
with urllib.request.urlopen(request, timeout=5) as response:
|
||
return str(response.status)
|
||
except urllib.error.HTTPError as error:
|
||
return str(error.code)
|
||
except OSError:
|
||
return "000"
|
||
|
||
|
||
def weed_shell(command: str) -> str:
|
||
"""Одна команда `weed shell` в контейнере `s3` стенда: master и filer
|
||
на его loopback, ключ подписи — в его окружении."""
|
||
return compose(
|
||
"exec",
|
||
"-T",
|
||
"s3",
|
||
"sh",
|
||
"-c",
|
||
"exec weed shell -master=127.0.0.1:9333 2>&1",
|
||
stdin=f"{command}\n",
|
||
)
|
||
|
||
|
||
def s3_bootstrap(mode: str) -> tuple[int, str]:
|
||
"""Bootstrap S3 стенда в режиме `check` или `cleanup`: код и вывод."""
|
||
proc = subprocess.run(
|
||
[
|
||
"docker",
|
||
"compose",
|
||
"run",
|
||
"--rm",
|
||
"--no-deps",
|
||
"s3-bootstrap",
|
||
mode,
|
||
],
|
||
cwd=ROOT,
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
return proc.returncode, proc.stdout + proc.stderr
|
||
|
||
|
||
def cmd_s3_check() -> int:
|
||
"""Спек `object-storage`, «Проверка приватности вне API»: права ключа
|
||
API и приватность bucket без приложения (design change `s3-storage`,
|
||
решение 8).
|
||
|
||
1. Bootstrap в режиме `check`: ключ API пишет проверочный объект и
|
||
проверяет свои права, чужой bucket (временный) и административные
|
||
запросы; аноним изнутри сервера.
|
||
2. Анонимные запросы к объекту с хоста (`127.0.0.1:S3_OUT_PORT`) и из
|
||
сети стенда (одноразовый контейнер того же образа). Порты:
|
||
слушающие сокеты контейнера S3 (`netstat`) — вне loopback ровно
|
||
API S3 и gRPC шлюза, а остальные слушающие порты из сети закрыты
|
||
(`nc -z`).
|
||
3. Bootstrap в режиме `cleanup`: объект и временные bucket-ы удалены,
|
||
остатков нет (`weed shell` в контейнере `s3`).
|
||
|
||
Печатает таблицу «где → проверка → ожидаемо → получено» без
|
||
секретов; код 1 при любом расхождении."""
|
||
try:
|
||
stand = s3_stand()
|
||
except (RuntimeError, KeyError, StopIteration, ValueError) as e:
|
||
print(f"FAIL: compose config of the S3 stand: {e}")
|
||
return 1
|
||
if not compose("ps", "-q", "--status", "running", "s3").strip():
|
||
print("FAIL: service s3 is not running, make run_docker first")
|
||
return 1
|
||
rows: list[tuple[str, str, str, str]] = []
|
||
problems: list[str] = []
|
||
try:
|
||
rc, out = s3_bootstrap("check")
|
||
for line in out.splitlines():
|
||
if line.startswith(S3_CHECK_ROW):
|
||
name, expected, got, _ = line[len(S3_CHECK_ROW) :].split("\t")
|
||
rows.append(("server", name, expected, got))
|
||
elif "FAILED" in line and "check(s) failed" not in line:
|
||
problems.append(line.strip())
|
||
if rc != 0 and not problems and not any(r[2] != r[3] for r in rows):
|
||
problems.append(f"s3-bootstrap check exited with {rc}")
|
||
# bootstrap печатает строки сам; прежний bootstrap.sh их не напечатает
|
||
seen_rows = {row[1] for row in rows}
|
||
for name in S3_REQUIRED_ROWS:
|
||
if name not in seen_rows:
|
||
problems.append(f"no row from s3-bootstrap check: {name}")
|
||
host = f"http://127.0.0.1:{stand['out_port']}"
|
||
obj = f"{host}/{stand['bucket']}/{S3_CHECK_KEY}"
|
||
for name, url, method, data in (
|
||
("anonymous get object", obj, "GET", None),
|
||
("anonymous head object", obj, "HEAD", None),
|
||
(
|
||
"anonymous get missing object",
|
||
f"{host}/{stand['bucket']}/.s3-check/missing",
|
||
"GET",
|
||
None,
|
||
),
|
||
(
|
||
"anonymous list objects",
|
||
f"{host}/{stand['bucket']}?list-type=2",
|
||
"GET",
|
||
None,
|
||
),
|
||
("anonymous list buckets", f"{host}/", "GET", None),
|
||
(
|
||
"anonymous put object",
|
||
f"{host}/{stand['bucket']}/.s3-check/anonymous",
|
||
"PUT",
|
||
b"x",
|
||
),
|
||
):
|
||
rows.append(
|
||
("host", name, "403", anonymous_code(url, method, data)),
|
||
)
|
||
# вне loopback — ровно API S3 и gRPC шлюза; остальные слушающие
|
||
# порты сервера из сети стенда закрыты (nc -z ниже)
|
||
outside, loopback_only = s3_listening()
|
||
grpc_port = int(stand["port"]) + 10000
|
||
rows.append(
|
||
(
|
||
"server",
|
||
"listening outside loopback",
|
||
f"{stand['port']} {grpc_port}",
|
||
" ".join(outside) or "-",
|
||
),
|
||
)
|
||
network = subprocess.run(
|
||
[
|
||
"docker",
|
||
"run",
|
||
"--rm",
|
||
"--network",
|
||
f"{stand['project']}_default",
|
||
"-e",
|
||
f"S3_HOST={stand['host']}",
|
||
"-e",
|
||
f"S3_PORT={stand['port']}",
|
||
"-e",
|
||
f"S3_GRPC_PORT={grpc_port}",
|
||
"-e",
|
||
f"S3_BUCKET={stand['bucket']}",
|
||
"-e",
|
||
f"S3_KEY={S3_CHECK_KEY}",
|
||
"-e",
|
||
"S3_CLOSED=" + " ".join(str(p) for p in loopback_only),
|
||
"--entrypoint",
|
||
"sh",
|
||
stand["image"],
|
||
"-c",
|
||
S3_NETWORK_SCRIPT,
|
||
],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
for line in network.stdout.splitlines():
|
||
if line.startswith("row\t"):
|
||
_, name, expected, got = line.split("\t")
|
||
rows.append(("network", name, expected, got))
|
||
if network.returncode != 0:
|
||
problems.append(f"network probe exited with {network.returncode}")
|
||
finally:
|
||
rc, out = s3_bootstrap("cleanup")
|
||
if rc != 0:
|
||
problems.append("cleanup: " + out.strip().splitlines()[-1])
|
||
buckets = weed_shell("s3.bucket.list")
|
||
left_buckets = sum(
|
||
1
|
||
for line in buckets.splitlines()
|
||
if line.split()
|
||
and line.split()[0].startswith(f"{stand['bucket']}-check-")
|
||
)
|
||
check_dir = S3_CHECK_KEY.split("/")[0]
|
||
objects = weed_shell(f"fs.ls /buckets/{stand['bucket']}/{check_dir}")
|
||
# пустой каталог или его нет («no entry is found») — остатков нет
|
||
left_objects = sum(
|
||
1
|
||
for line in objects.splitlines()
|
||
if line.strip() and "no entry" not in line
|
||
)
|
||
rows.append(("server", "temporary buckets left", "0", str(left_buckets)))
|
||
rows.append(("server", "probe objects left", "0", str(left_objects)))
|
||
|
||
width = max(len(name) for _, name, _, _ in rows)
|
||
e_width = max(len("expected"), *(len(e) for _, _, e, _ in rows))
|
||
g_width = max(len("got"), *(len(g) for _, _, _, g in rows))
|
||
print(
|
||
f"S3 {stand['host']}:{stand['port']} (host 127.0.0.1:"
|
||
f"{stand['out_port']}), bucket {stand['bucket']}, image "
|
||
f"{stand['image'].split('@')[0]}",
|
||
)
|
||
print(
|
||
f"{'where':<8} {'check':<{width}} {'expected':<{e_width}} "
|
||
f"{'got':<{g_width}} verdict",
|
||
)
|
||
failed = 0
|
||
for where, name, expected, got in rows:
|
||
ok = expected == got
|
||
failed += not ok
|
||
print(
|
||
f"{where:<8} {name:<{width}} {expected:<{e_width}} "
|
||
f"{got:<{g_width}} {'ok' if ok else 'FAIL'}",
|
||
)
|
||
for problem in problems:
|
||
print(f"FAIL: {problem}")
|
||
if failed or problems:
|
||
names = [f"{w}: {n}" for w, n, e, g in rows if e != g]
|
||
print(
|
||
f"FAIL: {failed} check(s) failed"
|
||
+ (f": {'; '.join(names)}" if names else ""),
|
||
)
|
||
return 1
|
||
print(f"PASS: {len(rows)} checks, bucket {stand['bucket']} is private")
|
||
return 0
|
||
|
||
|
||
# вложения (лаба 4): публичный fixture и пути API
|
||
FIXTURE_PNG = ROOT / "tests" / "fixtures" / "sample.png"
|
||
ATTACHMENTS = "/api/v1/attachments"
|
||
PNG_SIGNATURE = b"\x89PNG\r\n\x1a\n"
|
||
JPEG_SIGNATURE = b"\xff\xd8\xff"
|
||
# сколько раз скачивать через LB после остановки реплики: первые запросы
|
||
# может принять слот остановленной, пока LB её не исключил
|
||
FAILOVER_ATTEMPTS = 30
|
||
FAILOVER_PAUSE_S = 0.5
|
||
# сколько ждать, пока LB снова пометит вернувшуюся реплику UP
|
||
LB_UP_WAIT_S = 20
|
||
# ключ объекта: <база>/attachments/<id>/original (design change
|
||
# attachments, решение 4), до обработки — <база>/staging/<id>/original
|
||
# (design change async-attachments, решение 1)
|
||
ATTACHMENT_KEY_PREFIX = "attachments"
|
||
STAGING_KEY_PREFIX = "staging"
|
||
ATTACHMENT_ORIGINAL = "original"
|
||
# загрузка с лабы 5: 202 и снимок queued, ready — опросом метаданных
|
||
ATTACHMENT_ACCEPTED = 202
|
||
READY_POLL_S = 0.2
|
||
READY_WAIT_S = 60
|
||
# thumbnail tests/fixtures/sample.png (320 × 200): ширина и высота по SOF
|
||
THUMBNAIL_SIZE = (256, 160)
|
||
# варианты того же fixture (design change pipeline-reliability, решение 6):
|
||
# имя → тип и размеры, снятые с самих байтов
|
||
FIXTURE_VARIANTS = {
|
||
"thumbnail": ("image/jpeg", THUMBNAIL_SIZE),
|
||
"crop": ("image/jpeg", (128, 128)),
|
||
"optimized": ("image/webp", (320, 200)),
|
||
}
|
||
# маркеры начала кадра JPEG, у которых есть размеры (tests/image_probe.py)
|
||
JPEG_SOF = frozenset(range(0xC0, 0xD0)) - {0xC4, 0xC8, 0xCC}
|
||
|
||
|
||
def call_bytes(
|
||
port: int,
|
||
method: str,
|
||
path: str,
|
||
*,
|
||
token: str | None = None,
|
||
data: bytes | None = None,
|
||
content_type: str | None = None,
|
||
timeout: float = 30,
|
||
) -> tuple[int, dict[str, str], bytes]:
|
||
"""Запрос с сырыми байтами в теле или ответе (загрузка, скачивание).
|
||
|
||
`urllib` напрямую к одной реплике ранний 413 на большом теле теряет
|
||
(обрыв при отправке): через LB ответ доходит (SKILL.md, Gotchas).
|
||
"""
|
||
headers = {}
|
||
if token is not None:
|
||
headers["Authorization"] = f"Bearer {token}"
|
||
if content_type is not None:
|
||
headers["Content-Type"] = content_type
|
||
request = urllib.request.Request(
|
||
base_url(port) + path,
|
||
data=data,
|
||
method=method,
|
||
headers=headers,
|
||
)
|
||
try:
|
||
with urllib.request.urlopen(request, timeout=timeout) as response:
|
||
status, hdrs = response.status, dict(response.headers)
|
||
payload = response.read()
|
||
except urllib.error.HTTPError as error:
|
||
status, hdrs, payload = error.code, dict(error.headers), error.read()
|
||
return status, {k.lower(): v for k, v in hdrs.items()}, payload
|
||
|
||
|
||
def image_type(data: bytes) -> str:
|
||
if data.startswith(PNG_SIGNATURE):
|
||
return "image/png"
|
||
if data.startswith(JPEG_SIGNATURE):
|
||
return "image/jpeg"
|
||
return "application/octet-stream"
|
||
|
||
|
||
def upload_bytes(
|
||
port: int,
|
||
token: str,
|
||
chat_id: str,
|
||
data: bytes,
|
||
*,
|
||
content_type: str,
|
||
filename: str,
|
||
) -> tuple[int, dict[str, str], object]:
|
||
query = urllib.parse.urlencode({"filename": filename})
|
||
status, hdrs, payload = call_bytes(
|
||
port,
|
||
"POST",
|
||
f"{CHATS}/{chat_id}/attachments?{query}",
|
||
token=token,
|
||
data=data,
|
||
content_type=content_type,
|
||
)
|
||
try:
|
||
parsed: object = json.loads(payload) if payload else None
|
||
except json.JSONDecodeError:
|
||
parsed = payload.decode(errors="replace")
|
||
return status, hdrs, parsed
|
||
|
||
|
||
def wait_attachment(
|
||
port: int,
|
||
token: str,
|
||
attachment_id: str,
|
||
*,
|
||
timeout: float = READY_WAIT_S,
|
||
) -> dict[str, object]:
|
||
"""Опрос метаданных раз в 0,2 с до `ready` или `failed`; срок вышел —
|
||
последний полученный ответ. Сбой запроса опрос не прерывает: стенд может
|
||
ещё подниматься."""
|
||
deadline = time.monotonic() + timeout
|
||
last: dict[str, object] = {}
|
||
while True:
|
||
with contextlib.suppress(OSError, http.client.HTTPException):
|
||
status, _, payload = call(
|
||
port,
|
||
"GET",
|
||
f"{ATTACHMENTS}/{attachment_id}",
|
||
token=token,
|
||
)
|
||
if status == 200 and isinstance(payload, dict):
|
||
last = payload
|
||
if payload.get("status") in ("ready", "failed"):
|
||
return payload
|
||
if time.monotonic() >= deadline:
|
||
return last
|
||
time.sleep(READY_POLL_S)
|
||
|
||
|
||
def upload_ready(
|
||
port: int,
|
||
token: str,
|
||
chat_id: str,
|
||
data: bytes,
|
||
*,
|
||
content_type: str,
|
||
filename: str,
|
||
) -> tuple[int, dict[str, str], object]:
|
||
"""Загрузка и ожидание `ready`: статус ответа загрузки и метаданные
|
||
готового вложения. Не дошло до `ready` — вместо метаданных `None`, причина
|
||
напечатана."""
|
||
status, hdrs, payload = upload_bytes(
|
||
port,
|
||
token,
|
||
chat_id,
|
||
data,
|
||
content_type=content_type,
|
||
filename=filename,
|
||
)
|
||
if status != ATTACHMENT_ACCEPTED or not isinstance(payload, dict):
|
||
return status, hdrs, payload
|
||
ready = wait_attachment(port, token, str(payload["id"]))
|
||
if ready.get("status") != "ready":
|
||
print(
|
||
f"attachment {payload['id']}: status {ready.get('status')}, "
|
||
f"error_code {ready.get('error_code')} (waited {READY_WAIT_S} s)",
|
||
)
|
||
return status, hdrs, None
|
||
return status, hdrs, ready
|
||
|
||
|
||
def sha256_hex(data: bytes) -> str:
|
||
return hashlib.sha256(data).hexdigest()
|
||
|
||
|
||
def jpeg_dimensions(data: bytes) -> tuple[int, int] | None:
|
||
"""Ширина и высота JPEG по SOF без внешних библиотек, как
|
||
`tests/image_probe.py`; ещё начало скана и EOI: это не декодер, но обрезок
|
||
и подделку заголовка видно. Иначе — `None`."""
|
||
if data[:2] != b"\xff\xd8" or not data.endswith(b"\xff\xd9"):
|
||
return None
|
||
size: tuple[int, int] | None = None
|
||
at = 2
|
||
while at + 4 <= len(data):
|
||
if data[at] != 0xFF:
|
||
return None
|
||
while at < len(data) and data[at] == 0xFF:
|
||
at += 1
|
||
if at >= len(data):
|
||
return None
|
||
marker = data[at]
|
||
at += 1
|
||
if marker == 0xDA:
|
||
return size
|
||
if marker in (0x01, 0xD8) or 0xD0 <= marker <= 0xD7:
|
||
continue
|
||
length = int.from_bytes(data[at : at + 2], "big")
|
||
if length < 2 or at + length > len(data):
|
||
return None
|
||
if marker in JPEG_SOF and length >= 8:
|
||
size = (
|
||
int.from_bytes(data[at + 5 : at + 7], "big"),
|
||
int.from_bytes(data[at + 3 : at + 5], "big"),
|
||
)
|
||
at += length
|
||
return None
|
||
|
||
|
||
def webp_dimensions(data: bytes) -> tuple[int, int] | None:
|
||
"""Ширина и высота WebP по заголовку чанка без внешних библиотек; ещё длина
|
||
RIFF: обрезок видно. Иначе — `None`."""
|
||
if data[:4] != b"RIFF" or data[8:12] != b"WEBP":
|
||
return None
|
||
if len(data) != 8 + int.from_bytes(data[4:8], "little"):
|
||
return None
|
||
kind = data[12:16]
|
||
if kind == b"VP8X" and len(data) >= 30:
|
||
return (
|
||
1 + int.from_bytes(data[24:27], "little"),
|
||
1 + int.from_bytes(data[27:30], "little"),
|
||
)
|
||
if kind == b"VP8 " and len(data) >= 30 and data[23:26] == b"\x9d\x01\x2a":
|
||
return (
|
||
int.from_bytes(data[26:28], "little") & 0x3FFF,
|
||
int.from_bytes(data[28:30], "little") & 0x3FFF,
|
||
)
|
||
if kind == b"VP8L" and len(data) >= 25 and data[20] == 0x2F:
|
||
bits = int.from_bytes(data[21:25], "little")
|
||
return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1
|
||
return None
|
||
|
||
|
||
def image_dimensions(data: bytes) -> tuple[int, int] | None:
|
||
"""Размеры JPEG или WebP по самим байтам."""
|
||
if data.startswith(b"RIFF"):
|
||
return webp_dimensions(data)
|
||
return jpeg_dimensions(data)
|
||
|
||
|
||
def variant_checks(
|
||
port: int,
|
||
token: str,
|
||
meta: dict[str, object],
|
||
) -> list[tuple[str, str, str]]:
|
||
"""Три варианта готового fixture: в метаданных, по байтам и по SHA-256:
|
||
строки «проверка → ожидаемо → получено»."""
|
||
listed = meta.get("variants")
|
||
variants = {
|
||
str(item.get("name")): item
|
||
for item in (listed if isinstance(listed, list) else [])
|
||
}
|
||
rows = [
|
||
(
|
||
"variants in metadata",
|
||
",".join(sorted(FIXTURE_VARIANTS)),
|
||
",".join(sorted(variants)) or "-",
|
||
),
|
||
]
|
||
for name, (content_type, size) in FIXTURE_VARIANTS.items():
|
||
status, hdrs, body = call_bytes(
|
||
port,
|
||
"GET",
|
||
f"{ATTACHMENTS}/{meta['id']}/content?variant={name}",
|
||
token=token,
|
||
)
|
||
rows.extend(
|
||
[
|
||
(f"download {name}", "200", str(status)),
|
||
(
|
||
f"{name} content type",
|
||
content_type,
|
||
hdrs.get("content-type", "-"),
|
||
),
|
||
(
|
||
f"{name} size by bytes",
|
||
str(size),
|
||
str(image_dimensions(body)),
|
||
),
|
||
(
|
||
f"{name} sha256 = metadata",
|
||
"yes",
|
||
yes(
|
||
sha256_hex(body)
|
||
== variants.get(name, {}).get("sha256"),
|
||
),
|
||
),
|
||
],
|
||
)
|
||
return rows
|
||
|
||
|
||
def cmd_upload(port: int, args: argparse.Namespace) -> int:
|
||
"""Загрузка файла: статус, `X-Instance-Id`, тело, SHA-256 файла, затем
|
||
опрос до `ready`."""
|
||
data = Path(args.file).read_bytes()
|
||
content_type = args.type or image_type(data)
|
||
status, hdrs, payload = upload_bytes(
|
||
port,
|
||
args.token,
|
||
args.chat,
|
||
data,
|
||
content_type=content_type,
|
||
filename=args.filename or Path(args.file).name,
|
||
)
|
||
print(status, "x-instance-id:", hdrs.get("x-instance-id"))
|
||
print(json.dumps(payload, ensure_ascii=False, indent=2))
|
||
print(f"file: {len(data)} bytes, sha256 {sha256_hex(data)}")
|
||
if status >= 400:
|
||
return 2
|
||
if status != ATTACHMENT_ACCEPTED or not isinstance(payload, dict):
|
||
return 0
|
||
print("sha256 matches:", payload.get("sha256") == sha256_hex(data))
|
||
ready = wait_attachment(port, args.token, str(payload["id"]))
|
||
print(json.dumps(ready, ensure_ascii=False, indent=2))
|
||
return 0 if ready.get("status") == "ready" else 2
|
||
|
||
|
||
def cmd_download(port: int, args: argparse.Namespace) -> int:
|
||
"""Скачивание оригинала или варианта: статус, тип, размер, SHA-256
|
||
полученного. Не `ready` — 409 и код 2: так его и показывают; `--wait` —
|
||
сначала опрос до `ready`."""
|
||
path = f"{ATTACHMENTS}/{args.attachment}/content"
|
||
if args.variant is not None:
|
||
path += "?" + urllib.parse.urlencode({"variant": args.variant})
|
||
if args.wait:
|
||
ready = wait_attachment(port, args.token, args.attachment)
|
||
print(f"status {ready.get('status')}")
|
||
status, hdrs, payload = call_bytes(port, "GET", path, token=args.token)
|
||
print(
|
||
status,
|
||
"x-instance-id:",
|
||
hdrs.get("x-instance-id"),
|
||
"content-type:",
|
||
hdrs.get("content-type"),
|
||
"content-length:",
|
||
hdrs.get("content-length"),
|
||
)
|
||
if status != 200:
|
||
print(payload.decode(errors="replace"))
|
||
return 2
|
||
print(f"received: {len(payload)} bytes, sha256 {sha256_hex(payload)}")
|
||
if hdrs.get("content-type") == "image/jpeg":
|
||
print(f"JPEG size by SOF: {jpeg_dimensions(payload)}")
|
||
if hdrs.get("content-type") == "image/webp":
|
||
print(f"WebP size by header: {webp_dimensions(payload)}")
|
||
if args.out:
|
||
Path(args.out).write_bytes(payload)
|
||
print(f"saved to {args.out}")
|
||
return 0
|
||
|
||
|
||
def attachment_people(
|
||
port: int,
|
||
tag: str,
|
||
) -> tuple[dict[str, str], dict[str, str], str] | None:
|
||
"""Синтетические Алиса, Боб, Ева и чат Алисы и Боба: (id, токены,
|
||
id чата). Пароли и токены не печатаются."""
|
||
ids: dict[str, str] = {}
|
||
tokens: dict[str, str] = {}
|
||
for name in ("alice", "bob", "eve"):
|
||
made = synthetic_user(port, f"{tag}{name}", f"Pw-{uuid.uuid4().hex}")
|
||
if made is None:
|
||
return None
|
||
ids[name], tokens[name] = str(made[0]["id"]), made[1]
|
||
status, _, chat = call(
|
||
port,
|
||
"POST",
|
||
CHATS,
|
||
token=tokens["alice"],
|
||
body={
|
||
"title": "attachments",
|
||
"member_ids": [ids["alice"], ids["bob"]],
|
||
},
|
||
)
|
||
if status != 201 or not isinstance(chat, dict):
|
||
print(f"create chat: {status}")
|
||
return None
|
||
return ids, tokens, str(chat["id"])
|
||
|
||
|
||
def compose_ps() -> str:
|
||
return compose(
|
||
"ps",
|
||
"--format",
|
||
"table {{.Name}}\t{{.Status}}",
|
||
).strip()
|
||
|
||
|
||
def cmd_attachment_failover(port: int, mode: str) -> int:
|
||
"""Спек `attachments`, «Принявшая реплика остановлена» (design change
|
||
`attachments`, решение 13): загрузка через LB, `scripts/stop-one.sh`
|
||
реплики, принявшей файл, скачивание через другую с тем же SHA-256,
|
||
404 постороннему; в `finally` — `make replicas`."""
|
||
if no_lb(port):
|
||
print("attachment-failover needs the stand with the load balancer")
|
||
return 2
|
||
data = FIXTURE_PNG.read_bytes()
|
||
print(f"mode: {mode}; fixture {FIXTURE_PNG.name}: {len(data)} bytes")
|
||
print("docker compose ps (before):")
|
||
print(compose_ps())
|
||
people = attachment_people(port, "af")
|
||
if people is None:
|
||
return 1
|
||
_, tokens, chat_id = people
|
||
rows: list[tuple[str, str, str, str]] = []
|
||
problems: list[str] = []
|
||
status, hdrs, attachment = upload_ready(
|
||
port,
|
||
tokens["alice"],
|
||
chat_id,
|
||
data,
|
||
content_type="image/png",
|
||
filename=FIXTURE_PNG.name,
|
||
)
|
||
accepted_by = hdrs.get("x-instance-id", "")
|
||
rows.append(("alice uploads", "202", str(status), accepted_by))
|
||
if status != ATTACHMENT_ACCEPTED or not isinstance(attachment, dict):
|
||
print(f"FAIL: upload {status}, not ready")
|
||
return 1
|
||
rows.append(("attachment is ready", "ready", attachment["status"], ""))
|
||
attachment_id = str(attachment["id"])
|
||
uploaded_sha = str(attachment["sha256"])
|
||
status, hdrs, message = call(
|
||
port,
|
||
"POST",
|
||
f"{CHATS}/{chat_id}/messages",
|
||
token=tokens["alice"],
|
||
body={"text": "", "attachment_ids": [attachment_id]},
|
||
extra=key_header(),
|
||
)
|
||
rows.append(
|
||
(
|
||
"alice sends message",
|
||
"201",
|
||
str(status),
|
||
hdrs.get("x-instance-id", ""),
|
||
),
|
||
)
|
||
try:
|
||
hook = subprocess.run(
|
||
[str(ROOT / "scripts" / "stop-one.sh")],
|
||
cwd=ROOT,
|
||
env=os.environ
|
||
| {"TARGET_INSTANCE_ID": accepted_by, "STOP_MODE": mode},
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
rows.append(
|
||
("stop-one.sh " + mode, "0", str(hook.returncode), accepted_by),
|
||
)
|
||
downloaded = b""
|
||
served_by = ""
|
||
meta_status = 0
|
||
for _ in range(FAILOVER_ATTEMPTS):
|
||
status, hdrs, payload = call_bytes(
|
||
port,
|
||
"GET",
|
||
f"{ATTACHMENTS}/{attachment_id}/content",
|
||
token=tokens["bob"],
|
||
)
|
||
if status == 200:
|
||
downloaded, served_by = payload, hdrs.get("x-instance-id", "")
|
||
break
|
||
time.sleep(FAILOVER_PAUSE_S)
|
||
rows.append(("bob downloads", "200", str(status), served_by))
|
||
meta_status, hdrs, meta = call(
|
||
port,
|
||
"GET",
|
||
f"{ATTACHMENTS}/{attachment_id}",
|
||
token=tokens["bob"],
|
||
)
|
||
rows.append(
|
||
(
|
||
"bob reads metadata",
|
||
"200",
|
||
str(meta_status),
|
||
hdrs.get("x-instance-id", ""),
|
||
),
|
||
)
|
||
for label, path in (
|
||
("eve reads metadata", f"{ATTACHMENTS}/{attachment_id}"),
|
||
("eve downloads", f"{ATTACHMENTS}/{attachment_id}/content"),
|
||
):
|
||
status, hdrs, _ = call_bytes(
|
||
port,
|
||
"GET",
|
||
path,
|
||
token=tokens["eve"],
|
||
)
|
||
rows.append(
|
||
(label, "404", str(status), hdrs.get("x-instance-id", "")),
|
||
)
|
||
if hook.returncode != 0:
|
||
problems.append(f"stop-one.sh: {hook.stderr.strip()}")
|
||
if served_by in ("", accepted_by):
|
||
problems.append("download was not served by another replica")
|
||
print(f"sha256 uploaded: {uploaded_sha}")
|
||
print(f"sha256 downloaded: {sha256_hex(downloaded)}")
|
||
if sha256_hex(downloaded) != uploaded_sha:
|
||
problems.append("sha256 of the downloaded original differs")
|
||
if isinstance(meta, dict) and meta != attachment:
|
||
problems.append("metadata differs from the upload response")
|
||
finally:
|
||
restore = subprocess.run(
|
||
["make", "replicas"],
|
||
cwd=ROOT,
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
rows.append(("make replicas", "0", str(restore.returncode), ""))
|
||
print("docker compose ps (after):")
|
||
print(compose_ps())
|
||
# make replicas ждёт healthy контейнера, а LB видит его по своим
|
||
# проверкам на секунды позже
|
||
replicas = len(compose("ps", "-q", "--status", "running", "api").split())
|
||
deadline = time.monotonic() + LB_UP_WAIT_S
|
||
up = 0
|
||
while time.monotonic() < deadline:
|
||
up = sum(1 for slot in lb_slots() if slot.get("status") == "UP")
|
||
if up >= replicas:
|
||
break
|
||
time.sleep(FAILOVER_PAUSE_S)
|
||
rows.append(("LB slots UP", str(replicas), str(up), ""))
|
||
width = max(len(step) for step, _, _, _ in rows)
|
||
print(f"{'step':<{width}} expected got x-instance-id")
|
||
failed = 0
|
||
for step, expected, got, instance in rows:
|
||
ok = expected == got
|
||
failed += not ok
|
||
print(
|
||
f"{step:<{width}} {expected:<8} {got:<5} {instance}"
|
||
+ ("" if ok else " FAIL"),
|
||
)
|
||
for problem in problems:
|
||
print(f"FAIL: {problem}")
|
||
if failed or problems:
|
||
return 1
|
||
print(
|
||
f"PASS: accepted by {accepted_by}, served by {served_by} after "
|
||
f"{mode}, sha256 matches, outsider gets 404",
|
||
)
|
||
return 0
|
||
|
||
|
||
def cmd_attachment_storage(port: int) -> int:
|
||
"""Спек `attachments`, «Байты не в БД и не на диске API» (design change
|
||
`attachments`, решение 13): колонки таблиц вложений, вид
|
||
`object_key` и `staging_key`, объекты в bucket, анонимный GET — 403,
|
||
`docker diff` реплик и worker без файлов оригиналов. Спек `data-storage`,
|
||
«Ограничения обработки в схеме»: вставки в откатываемой транзакции."""
|
||
if no_lb(port):
|
||
print("attachment-storage needs the stand with the load balancer")
|
||
return 2
|
||
try:
|
||
stand = s3_stand()
|
||
config = json.loads(compose("config", "--format", "json"))
|
||
database = str(
|
||
config["services"]["api"]["environment"]["DATABASE__NAME"],
|
||
)
|
||
except (RuntimeError, KeyError, StopIteration, ValueError) as e:
|
||
print(f"FAIL: compose config of the stand: {e}")
|
||
return 1
|
||
people = attachment_people(port, "as")
|
||
if people is None:
|
||
return 1
|
||
_, tokens, chat_id = people
|
||
data = FIXTURE_PNG.read_bytes()
|
||
uploads = []
|
||
for number in range(2):
|
||
filename = f"storage-check-{uuid.uuid4().hex[:8]}-{number}.png"
|
||
status, hdrs, attachment = upload_ready(
|
||
port,
|
||
tokens["alice"],
|
||
chat_id,
|
||
data,
|
||
content_type="image/png",
|
||
filename=filename,
|
||
)
|
||
if status != ATTACHMENT_ACCEPTED or not isinstance(attachment, dict):
|
||
print(f"FAIL: upload {status}, not ready")
|
||
return 1
|
||
uploads.append((attachment, filename, hdrs.get("x-instance-id", "")))
|
||
rows: list[tuple[str, str, str]] = []
|
||
columns = stand_psql(
|
||
"SELECT table_name, column_name, data_type "
|
||
"FROM information_schema.columns WHERE table_schema = 'public' "
|
||
"AND table_name IN ('attachments', 'message_attachments', "
|
||
"'attachment_jobs', 'attachment_variants', 'attachment_job_replays') "
|
||
"ORDER BY table_name, ordinal_position;\n",
|
||
).splitlines()
|
||
print("columns of attachment tables:")
|
||
for line in columns:
|
||
print(" " + line.replace("|", " "))
|
||
binary = [
|
||
line.split("|")[0] + "." + line.split("|")[1]
|
||
for line in columns
|
||
if line.endswith("|bytea")
|
||
]
|
||
rows.append(
|
||
(
|
||
"bytea columns",
|
||
"attachment_variants.sha256,attachments.sha256",
|
||
",".join(binary) or "-",
|
||
),
|
||
)
|
||
# id — UUID ответа API: безопасны в тексте SQL
|
||
ids = ", ".join(f"'{a['id']}'" for a, _, _ in uploads)
|
||
sha_length = stand_psql(
|
||
"SELECT coalesce(max(octet_length(sha256)), 0) FROM attachments "
|
||
f"WHERE id IN ({ids});\n",
|
||
).strip()
|
||
rows.append(("octet_length(sha256)", "32", sha_length))
|
||
keys = {
|
||
line.split("|")[0]: line.split("|")[1:]
|
||
for line in stand_psql(
|
||
"SELECT id, object_key, staging_key FROM attachments "
|
||
f"WHERE id IN ({ids});\n",
|
||
).splitlines()
|
||
}
|
||
variant_keys: dict[str, dict[str, str]] = {}
|
||
for line in stand_psql(
|
||
"SELECT attachment_id, variant, object_key FROM attachment_variants "
|
||
f"WHERE attachment_id IN ({ids});\n",
|
||
).splitlines():
|
||
owner, variant_name, variant_key = line.split("|")
|
||
variant_keys.setdefault(owner, {})[variant_name] = variant_key
|
||
for attachment, filename, instance in uploads:
|
||
attachment_id = str(attachment["id"])
|
||
key, staging = keys.get(attachment_id, ["", ""])
|
||
expected = "/".join(
|
||
(
|
||
database,
|
||
ATTACHMENT_KEY_PREFIX,
|
||
attachment_id,
|
||
ATTACHMENT_ORIGINAL,
|
||
),
|
||
)
|
||
print(
|
||
f"upload via {instance}: object_key {key}, staging_key "
|
||
f"{staging or 'NULL (already removed by the cleaner)'}",
|
||
)
|
||
rows.append(("object_key form", expected, key))
|
||
# staging готового вложения убирает проход уборщика (раз в 60 с)
|
||
rows.append(
|
||
(
|
||
"staging_key: its form or already empty",
|
||
"yes",
|
||
yes(
|
||
staging
|
||
in (
|
||
"",
|
||
"/".join(
|
||
(
|
||
database,
|
||
STAGING_KEY_PREFIX,
|
||
attachment_id,
|
||
ATTACHMENT_ORIGINAL,
|
||
),
|
||
),
|
||
),
|
||
),
|
||
),
|
||
)
|
||
rows.append(
|
||
("filename not in key", "no", "yes" if filename in key else "no"),
|
||
)
|
||
listing = weed_shell(
|
||
f"fs.ls -l /buckets/{stand['bucket']}/{database}/"
|
||
f"{ATTACHMENT_KEY_PREFIX}/{attachment_id}",
|
||
)
|
||
stored_variants = variant_keys.get(attachment_id, {})
|
||
rows.append(
|
||
(
|
||
"variant rows",
|
||
",".join(sorted(FIXTURE_VARIANTS)),
|
||
",".join(sorted(stored_variants)) or "-",
|
||
),
|
||
)
|
||
for variant_name, variant in sorted(stored_variants.items()):
|
||
rows.append(
|
||
(
|
||
f"{variant_name} in bucket",
|
||
"yes",
|
||
yes(variant.split("/")[-1] in listing),
|
||
),
|
||
)
|
||
rows.append(
|
||
(
|
||
f"anonymous GET of {variant_name}",
|
||
"403",
|
||
anonymous_code(
|
||
f"http://127.0.0.1:{stand['out_port']}/"
|
||
f"{stand['bucket']}/{variant}",
|
||
),
|
||
),
|
||
)
|
||
# «-rw-rw---- 1 seaweed seaweed <размер> <полный путь>»
|
||
sizes = [
|
||
parts[-2]
|
||
for parts in (line.split() for line in listing.splitlines())
|
||
if len(parts) > 2
|
||
and parts[-1] == f"/buckets/{stand['bucket']}/{key}"
|
||
]
|
||
rows.append(
|
||
(
|
||
"object in bucket, bytes",
|
||
str(attachment["size_bytes"]),
|
||
sizes[0] if sizes else "missing",
|
||
),
|
||
)
|
||
url = f"http://127.0.0.1:{stand['out_port']}/{stand['bucket']}/{key}"
|
||
rows.append(("anonymous GET of the key", "403", anonymous_code(url)))
|
||
status, _, payload = call_bytes(
|
||
port,
|
||
"GET",
|
||
f"{ATTACHMENTS}/{attachment_id}/content",
|
||
token=tokens["bob"],
|
||
)
|
||
print(
|
||
f" sha256 uploaded {attachment['sha256']}, downloaded by a "
|
||
f"member ({status}) {sha256_hex(payload)}",
|
||
)
|
||
rows.append(
|
||
(
|
||
"downloaded sha256 = uploaded",
|
||
"yes",
|
||
"yes" if sha256_hex(payload) == attachment["sha256"] else "no",
|
||
),
|
||
)
|
||
# ограничения обработки: вставка копии строки готового вложения
|
||
probe_id = str(uploads[0][0]["id"])
|
||
probes = dict(
|
||
line.split("|", 1)
|
||
for line in stand_psql(
|
||
PROCESSING_LIMITS_SQL.format(attachment_id=probe_id),
|
||
).splitlines()
|
||
if "|" in line
|
||
)
|
||
print("constraint probes (rolled back):")
|
||
for name, expected in PROCESSING_LIMITS:
|
||
print(f" {name}: {probes.get(name, 'no result')}")
|
||
rows.append((f"probe: {name}", expected, probes.get(name, "-")))
|
||
left = stand_psql(
|
||
"SELECT (SELECT count(*) FROM attachment_jobs WHERE attachment_id = "
|
||
f"'{probe_id}') || '|' || (SELECT count(*) FROM attachment_variants "
|
||
f"WHERE attachment_id = '{probe_id}');\n",
|
||
).strip()
|
||
rows.append(("jobs | variants after the probes", "1|3", left))
|
||
replicas = compose("ps", "-q", "api", "worker").split()
|
||
for container in replicas:
|
||
diff = subprocess.run(
|
||
["docker", "diff", container],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
).stdout.splitlines()
|
||
suspicious = [
|
||
line
|
||
for line in diff
|
||
if any(
|
||
str(a["id"]) in line or name in line for a, name, _ in uploads
|
||
)
|
||
or line.lower().endswith((".png", ".jpg", ".jpeg", "/original"))
|
||
]
|
||
print(f"docker diff {container[:12]}: {len(diff)} changes")
|
||
for line in diff:
|
||
print(" " + line)
|
||
rows.append(
|
||
(f"original files in {container[:12]}", "0", str(len(suspicious))),
|
||
)
|
||
width = max(len(check) for check, _, _ in rows)
|
||
failed = 0
|
||
for check, expected, got in rows:
|
||
ok = expected == got
|
||
failed += not ok
|
||
print(
|
||
f"{check:<{width}} expected {expected} got {got}"
|
||
+ ("" if ok else " FAIL"),
|
||
)
|
||
print(f"sha256 of the fixture: {sha256_hex(data)}")
|
||
if failed:
|
||
print(f"FAIL: {failed} check(s) failed")
|
||
return 1
|
||
print(
|
||
"PASS: metadata in PostgreSQL, bytes only in the private bucket "
|
||
f"{stand['bucket']}, none in the API containers",
|
||
)
|
||
return 0
|
||
|
||
|
||
# attachment-storage: спек data-storage, «Ограничения обработки в схеме».
|
||
# Каждая вставка — в своём блоке, итог — SQLSTATE и имя ограничения; ROLLBACK
|
||
# в конце: на рабочей базе не остаётся ничего. Копии — той же строки, поэтому
|
||
# отказ даёт только проверяемое ограничение
|
||
PROCESSING_LIMITS = (
|
||
(
|
||
"second job of the version",
|
||
"23505 uq_attachment_jobs_attachment_id_pipeline_version",
|
||
),
|
||
("second variant of the name", "23505 pk_attachment_variants"),
|
||
(
|
||
"error_code on not failed",
|
||
"23514 ck_attachments_error_code_failed",
|
||
),
|
||
(
|
||
"replay audit of an unknown job",
|
||
"23503 fk_attachment_job_replays_job_id_attachment_jobs",
|
||
),
|
||
)
|
||
PROCESSING_LIMITS_SQL = """\
|
||
BEGIN;
|
||
CREATE TEMP TABLE driver_probe (name text, outcome text) ON COMMIT DROP;
|
||
CREATE FUNCTION pg_temp.driver_try(name text, statement text)
|
||
RETURNS void LANGUAGE plpgsql AS $$
|
||
DECLARE
|
||
state text;
|
||
limit_name text;
|
||
BEGIN
|
||
EXECUTE statement;
|
||
INSERT INTO driver_probe VALUES (name, 'accepted');
|
||
EXCEPTION WHEN others THEN
|
||
GET STACKED DIAGNOSTICS state = RETURNED_SQLSTATE,
|
||
limit_name = CONSTRAINT_NAME;
|
||
INSERT INTO driver_probe VALUES (name, state || ' ' || limit_name);
|
||
END
|
||
$$;
|
||
SELECT pg_temp.driver_try('second job of the version', $q$
|
||
INSERT INTO attachment_jobs (id, attachment_id, pipeline_version, state,
|
||
attempt, updated_at, created_at)
|
||
SELECT gen_random_uuid(), attachment_id, pipeline_version, 'queued', 0,
|
||
now(), now()
|
||
FROM attachment_jobs WHERE attachment_id = '{attachment_id}'
|
||
$q$) \\g /dev/null
|
||
SELECT pg_temp.driver_try('second variant of the name', $q$
|
||
INSERT INTO attachment_variants (attachment_id, pipeline_version, variant,
|
||
object_key, content_type, size_bytes, width, height, sha256,
|
||
created_at)
|
||
SELECT attachment_id, pipeline_version, variant,
|
||
object_key || '-probe', content_type, size_bytes, width, height,
|
||
sha256, now()
|
||
FROM attachment_variants WHERE attachment_id = '{attachment_id}'
|
||
$q$) \\g /dev/null
|
||
SELECT pg_temp.driver_try('error_code on not failed', $q$
|
||
INSERT INTO attachments (id, chat_id, owner_id, filename, content_type,
|
||
size_bytes, sha256, object_key, staging_key, status, error_code,
|
||
updated_at, created_at)
|
||
SELECT gen_random_uuid(), chat_id, owner_id, filename, content_type,
|
||
size_bytes, sha256, object_key || '-probe', staging_key, status,
|
||
'probe', now(), now()
|
||
FROM attachments WHERE id = '{attachment_id}'
|
||
$q$) \\g /dev/null
|
||
SELECT pg_temp.driver_try('replay audit of an unknown job', $q$
|
||
INSERT INTO attachment_job_replays (id, job_id, operator, error_code,
|
||
reason, attempt, created_at)
|
||
VALUES (gen_random_uuid(), gen_random_uuid(), 'driver-probe', NULL, NULL,
|
||
0, now())
|
||
$q$) \\g /dev/null
|
||
SELECT name || '|' || outcome FROM driver_probe;
|
||
ROLLBACK;
|
||
"""
|
||
# upload-consistency: имена триггера и функции постоянные — остаток
|
||
# прерванного прогона убирается в начале следующего. Отказ — SQLSTATE 08006:
|
||
# для API это отказ БД (503), а не дефект (500)
|
||
UC_TRIGGER = "driver_uc_fail_queued"
|
||
UC_FAIL_QUEUED_SQL = """\
|
||
CREATE OR REPLACE FUNCTION {name}() RETURNS trigger
|
||
LANGUAGE plpgsql AS $$
|
||
BEGIN
|
||
IF NEW.filename = TG_ARGV[0] AND OLD.status = 'pending'
|
||
AND NEW.status = 'queued' THEN
|
||
RAISE EXCEPTION 'driver: attachment queued failure'
|
||
USING ERRCODE = '08006';
|
||
END IF;
|
||
RETURN NEW;
|
||
END
|
||
$$;
|
||
DROP TRIGGER IF EXISTS {name} ON attachments;
|
||
CREATE TRIGGER {name} BEFORE UPDATE ON attachments
|
||
FOR EACH ROW EXECUTE FUNCTION {name}('{filename}');
|
||
"""
|
||
UC_CLEAR_SQL = f"""\
|
||
DROP TRIGGER IF EXISTS {UC_TRIGGER} ON attachments;
|
||
DROP FUNCTION IF EXISTS {UC_TRIGGER}();
|
||
DROP TRIGGER IF EXISTS driver_uc_fail_ready ON attachments;
|
||
DROP FUNCTION IF EXISTS driver_uc_fail_ready();
|
||
"""
|
||
# grace разового прохода: больше границы живой загрузки (17 с)
|
||
UC_GRACE_S = 30
|
||
# срок клиента загрузки при замороженном S3: ответ API — через 5 с
|
||
UC_UPLOAD_TIMEOUT_S = 30
|
||
UC_TREE_LINE = re.compile(r"^((?:[│ ] {3})*)[├└]──\s*(.*?)\s*$")
|
||
UC_UUID = re.compile(
|
||
r"^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$",
|
||
)
|
||
|
||
|
||
def stored_attachment_ids(
|
||
bucket: str,
|
||
database: str,
|
||
prefix: str = ATTACHMENT_KEY_PREFIX,
|
||
) -> set[str]:
|
||
"""`id` вложений с файлом `original` под `<база>/attachments/` (или
|
||
`<база>/staging/`) bucket стенда — по файлам `fs.tree`, а не по каталогам:
|
||
пустой каталог `<id>/` SeaweedFS убирает лишь через ~2 мин после DELETE."""
|
||
tree = weed_shell(f"fs.tree /buckets/{bucket}/{database}/{prefix}")
|
||
found: set[str] = set()
|
||
current = ""
|
||
for line in tree.splitlines():
|
||
match = UC_TREE_LINE.match(line)
|
||
if match is None:
|
||
continue
|
||
depth = len(match.group(1)) // 4 + 1
|
||
if depth == 1:
|
||
current = match.group(2) if UC_UUID.match(match.group(2)) else ""
|
||
elif depth == 2 and match.group(2) == ATTACHMENT_ORIGINAL and current:
|
||
found.add(current)
|
||
return found
|
||
|
||
|
||
def attachment_statuses() -> dict[str, str]:
|
||
"""Все вложения рабочей базы: `id` → статус."""
|
||
rows = stand_psql("SELECT id, status FROM attachments;\n").splitlines()
|
||
return dict(line.split("|") for line in rows if "|" in line)
|
||
|
||
|
||
def pending_row(attachment_id: str) -> str:
|
||
"""Строка вложения для вывода: статус, возраст, ключ объекта."""
|
||
# id — UUID из ответа psql: безопасен в тексте SQL
|
||
return stand_psql(
|
||
"SELECT status || ' age ' || round(extract(epoch FROM now() - "
|
||
"created_at)) || ' s key ' || object_key FROM attachments "
|
||
f"WHERE id = '{attachment_id}';\n",
|
||
).strip()
|
||
|
||
|
||
def cmd_upload_consistency(port: int) -> int:
|
||
"""Спеки `attachments` («Порядок записи») и `storage-consistency` на
|
||
рабочем стенде через LB (design change `upload-consistency`, решение
|
||
11; `async-attachments`, решения 3 и 11): загрузка при замороженном S3 и
|
||
при сбое перевода в `queued`, их строки `pending` не видны через API,
|
||
компенсация удаляет объект staging, разовый проход уборщика убирает обе
|
||
загрузки, готовое вложение цело.
|
||
Триггер — только на уникальный `filename` прогона, снимается в
|
||
`finally` и в начале следующего прогона; S3 размораживается в
|
||
`finally`. Токенов и секретов в выводе нет."""
|
||
if no_lb(port):
|
||
print("upload-consistency needs the stand with the load balancer")
|
||
return 2
|
||
|
||
def interrupted(signum: int, _frame: object) -> None:
|
||
raise KeyboardInterrupt(signal.Signals(signum).name)
|
||
|
||
previous = {
|
||
signum: signal.signal(signum, interrupted)
|
||
for signum in (signal.SIGTERM, signal.SIGHUP)
|
||
}
|
||
try:
|
||
return upload_consistency(port)
|
||
finally:
|
||
for signum, handler in previous.items():
|
||
signal.signal(signum, handler)
|
||
|
||
|
||
def upload_consistency(port: int) -> int:
|
||
"""Тело `cmd_upload_consistency`."""
|
||
try:
|
||
stand = s3_stand()
|
||
config = json.loads(compose("config", "--format", "json"))
|
||
database = str(
|
||
config["services"]["api"]["environment"]["DATABASE__NAME"],
|
||
)
|
||
except (RuntimeError, KeyError, StopIteration, ValueError) as e:
|
||
print(f"FAIL: compose config of the stand: {e}")
|
||
return 1
|
||
bucket = stand["bucket"]
|
||
# остаток прерванного прогона
|
||
stand_psql(UC_CLEAR_SQL)
|
||
people = attachment_people(port, "uc")
|
||
if people is None:
|
||
return 1
|
||
_, tokens, chat_id = people
|
||
data = FIXTURE_PNG.read_bytes()
|
||
tag = uuid.uuid4().hex[:8]
|
||
rows: list[tuple[str, str, str]] = []
|
||
|
||
def upload(filename: str, timeout: float = 30) -> tuple[int, object]:
|
||
query = urllib.parse.urlencode({"filename": filename})
|
||
status, _, payload = call_bytes(
|
||
port,
|
||
"POST",
|
||
f"{CHATS}/{chat_id}/attachments?{query}",
|
||
token=tokens["alice"],
|
||
data=data,
|
||
content_type="image/png",
|
||
timeout=timeout,
|
||
)
|
||
try:
|
||
return status, json.loads(payload) if payload else None
|
||
except json.JSONDecodeError:
|
||
return status, None
|
||
|
||
status, payload = upload(f"uc-{tag}-ready.png")
|
||
if status != ATTACHMENT_ACCEPTED or not isinstance(payload, dict):
|
||
print(f"FAIL: ready upload {status}")
|
||
return 1
|
||
ready = wait_attachment(port, tokens["alice"], str(payload["id"]))
|
||
rows.append(("attachment R uploaded", "202", str(status)))
|
||
rows.append(("attachment R processed", "ready", str(ready.get("status"))))
|
||
if ready.get("status") != "ready":
|
||
return report_rows(rows)
|
||
|
||
# 1. S3 заморожен на время PUT
|
||
before = attachment_statuses()
|
||
started = time.monotonic()
|
||
compose("pause", "s3")
|
||
try:
|
||
status, _ = upload(f"uc-{tag}-paused.png", UC_UPLOAD_TIMEOUT_S)
|
||
took = time.monotonic() - started
|
||
finally:
|
||
compose("unpause", "s3")
|
||
print(f"upload with paused S3: {status} after {took:.1f} s")
|
||
rows.append(("upload with paused S3", "503", str(status)))
|
||
paused = sorted(set(attachment_statuses()) - set(before))
|
||
rows.append(("new pending rows (paused)", "1", str(len(paused))))
|
||
if len(paused) != 1:
|
||
print("FAIL: no single pending row of the paused upload")
|
||
return report_rows(rows)
|
||
paused_id = paused[0]
|
||
print(f"pending {paused_id}: {pending_row(paused_id)}")
|
||
|
||
# 2. перевод в queued падает: компенсация удаляет объект staging
|
||
fail_name = f"uc-{tag}-queued-failure.png"
|
||
before = attachment_statuses()
|
||
try:
|
||
stand_psql(
|
||
UC_FAIL_QUEUED_SQL.format(name=UC_TRIGGER, filename=fail_name),
|
||
)
|
||
status, _ = upload(fail_name)
|
||
finally:
|
||
stand_psql(UC_CLEAR_SQL)
|
||
rows.append(("upload with queued failure", "503", str(status)))
|
||
failed = sorted(set(attachment_statuses()) - set(before))
|
||
rows.append(("new pending rows (queued failure)", "1", str(len(failed))))
|
||
if len(failed) != 1:
|
||
print("FAIL: no single pending row of the queued failure")
|
||
return report_rows(rows)
|
||
failed_id = failed[0]
|
||
print(f"pending {failed_id}: {pending_row(failed_id)}")
|
||
staged = stored_attachment_ids(bucket, database, STAGING_KEY_PREFIX)
|
||
rows.append(
|
||
(
|
||
"staging object after compensation",
|
||
"absent",
|
||
"present" if failed_id in staged else "absent",
|
||
),
|
||
)
|
||
rows.append(
|
||
(
|
||
"staging object of the paused upload",
|
||
"absent",
|
||
"present" if paused_id in staged else "absent",
|
||
),
|
||
)
|
||
triggers = stand_psql(
|
||
f"SELECT count(*) FROM pg_trigger WHERE tgname = '{UC_TRIGGER}';\n",
|
||
).strip()
|
||
rows.append(("driver trigger left", "0", triggers))
|
||
|
||
# pending не видны через API
|
||
for pending_id in (paused_id, failed_id):
|
||
for label, path in (
|
||
("metadata", f"{ATTACHMENTS}/{pending_id}"),
|
||
("content", f"{ATTACHMENTS}/{pending_id}/content"),
|
||
):
|
||
status, _, _ = call_bytes(
|
||
port,
|
||
"GET",
|
||
path,
|
||
token=tokens["alice"],
|
||
)
|
||
rows.append(
|
||
(f"{label} of pending {pending_id[:8]}", "404", str(status)),
|
||
)
|
||
status, _, _ = call(
|
||
port,
|
||
"POST",
|
||
f"{CHATS}/{chat_id}/messages",
|
||
token=tokens["alice"],
|
||
body={"text": "link", "attachment_ids": [pending_id]},
|
||
extra=key_header(),
|
||
)
|
||
rows.append((f"message with {pending_id[:8]}", "404", str(status)))
|
||
|
||
# 3. разовый проход уборщика после grace прогона
|
||
# строка сбоя queued — младшая из двух: ждём, пока и она старше grace
|
||
wait = max(0.0, UC_GRACE_S + 1 - float(age_of(failed_id)))
|
||
print(f"waiting {wait:.0f} s for grace {UC_GRACE_S} s")
|
||
time.sleep(wait)
|
||
proc = subprocess.run(
|
||
[
|
||
"docker",
|
||
"compose",
|
||
"run",
|
||
"--rm",
|
||
"--no-deps",
|
||
"-e",
|
||
f"CLEANER__PENDING_GRACE_SECONDS={UC_GRACE_S}",
|
||
"cleaner",
|
||
"--once",
|
||
],
|
||
cwd=ROOT,
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
print(f"cleaner --once (grace {UC_GRACE_S} s): exit {proc.returncode}")
|
||
for line in (proc.stdout + proc.stderr).splitlines():
|
||
if line.startswith("{"):
|
||
print(" " + line)
|
||
rows.append(("cleaner --once exit code", "0", str(proc.returncode)))
|
||
# тем же проходом убран staging готового вложения; метаданные прежние
|
||
# (design change pipeline-reliability, решение 9)
|
||
ready_id = str(ready["id"])
|
||
rows.append(
|
||
(
|
||
"R staging_key after the pass",
|
||
"NULL",
|
||
stand_psql(
|
||
"SELECT coalesce(staging_key, 'NULL') FROM attachments "
|
||
f"WHERE id = '{ready_id}';\n",
|
||
).strip(),
|
||
),
|
||
)
|
||
status, _, meta = call(
|
||
port,
|
||
"GET",
|
||
f"{ATTACHMENTS}/{ready_id}",
|
||
token=tokens["bob"],
|
||
)
|
||
rows.append(("R metadata unchanged", "yes", yes(meta == ready)))
|
||
|
||
# 4. ни строк, ни объектов; объектов без строки нет
|
||
statuses = attachment_statuses()
|
||
stored = stored_attachment_ids(bucket, database)
|
||
staged = stored_attachment_ids(bucket, database, STAGING_KEY_PREFIX)
|
||
for pending_id in (paused_id, failed_id):
|
||
rows.append(
|
||
(
|
||
f"row of {pending_id[:8]}",
|
||
"absent",
|
||
"present" if pending_id in statuses else "absent",
|
||
),
|
||
)
|
||
rows.append(
|
||
(
|
||
f"object of {pending_id[:8]}",
|
||
"absent",
|
||
"present"
|
||
if pending_id in stored or pending_id in staged
|
||
else "absent",
|
||
),
|
||
)
|
||
orphans = stored - set(statuses)
|
||
print(
|
||
f"bucket {bucket}, prefix {database}/: {len(stored)} objects, "
|
||
f"{len(statuses)} rows, {len(orphans)} objects without a row",
|
||
)
|
||
rows.append(("objects without a row", "0", str(len(orphans))))
|
||
rows.append(
|
||
(
|
||
"R staging object after the pass",
|
||
"absent",
|
||
"present" if ready_id in staged else "absent",
|
||
),
|
||
)
|
||
status, _, got = call_bytes(
|
||
port,
|
||
"GET",
|
||
f"{ATTACHMENTS}/{ready['id']}/content",
|
||
token=tokens["bob"],
|
||
)
|
||
rows.append(("R downloaded", "200", str(status)))
|
||
rows.append(
|
||
(
|
||
"R sha256 = uploaded",
|
||
"yes",
|
||
"yes" if sha256_hex(got) == ready["sha256"] else "no",
|
||
),
|
||
)
|
||
return report_rows(rows)
|
||
|
||
|
||
def age_of(attachment_id: str) -> str:
|
||
"""Возраст строки в секундах; нет строки — 0."""
|
||
value = stand_psql(
|
||
"SELECT coalesce(max(extract(epoch FROM now() - created_at)), 0) "
|
||
f"FROM attachments WHERE id = '{attachment_id}';\n",
|
||
).strip()
|
||
return value or "0"
|
||
|
||
|
||
def report_rows(rows: list[tuple[str, str, str]]) -> int:
|
||
"""Таблица «проверка → ожидаемо → получено»; код 1 при расхождении."""
|
||
width = max(len(check) for check, _, _ in rows)
|
||
failed = 0
|
||
for check, expected, got in rows:
|
||
ok = expected == got
|
||
failed += not ok
|
||
print(
|
||
f"{check:<{width}} expected {expected:<7} got {got}"
|
||
+ ("" if ok else " FAIL"),
|
||
)
|
||
if failed:
|
||
print(f"FAIL: {failed} check(s) failed")
|
||
return 1
|
||
print(
|
||
"PASS: pending rows are invisible, the queued failure is compensated, "
|
||
"the cleaner removed both uploads, no object without a row, R intact",
|
||
)
|
||
return 0
|
||
|
||
|
||
# reconcile-cycle и reconcile-stress (design change track2-reconciler,
|
||
# решение 12): разовая сверка — в одноразовом контейнере уборщика стенда с
|
||
# grace прогона. Триггер обрыва между объектом и фиксацией — отложенный
|
||
# триггер ограничения на уникальный filename: COMMIT перевода в queued
|
||
# падает (08006), объект staging остаётся, строка pending. Имя постоянное:
|
||
# остаток прерванного прогона убирается в начале следующего
|
||
RC_TRIGGER = "driver_rc_fail_commit"
|
||
RC_FAIL_COMMIT_SQL = """\
|
||
CREATE OR REPLACE FUNCTION {name}() RETURNS trigger
|
||
LANGUAGE plpgsql AS $$
|
||
BEGIN
|
||
IF NEW.filename = TG_ARGV[0] AND OLD.status = 'pending'
|
||
AND NEW.status = 'queued' THEN
|
||
RAISE EXCEPTION 'driver: attachment queued commit failure'
|
||
USING ERRCODE = '08006';
|
||
END IF;
|
||
RETURN NULL;
|
||
END
|
||
$$;
|
||
DROP TRIGGER IF EXISTS {name} ON attachments;
|
||
CREATE CONSTRAINT TRIGGER {name} AFTER UPDATE ON attachments
|
||
DEFERRABLE INITIALLY DEFERRED FOR EACH ROW
|
||
EXECUTE FUNCTION {name}('{filename}');
|
||
"""
|
||
RC_CLEAR_SQL = f"""\
|
||
DROP TRIGGER IF EXISTS {RC_TRIGGER} ON attachments;
|
||
DROP FUNCTION IF EXISTS {RC_TRIGGER}();
|
||
"""
|
||
# grace прогона цикла и стресса: больше границы живой загрузки (17 с)
|
||
RC_GRACE_S = 30
|
||
RC_STRESS_GRACE_S = 20
|
||
RC_STRESS_PERIOD_S = 3
|
||
RC_STRESS_PAUSE_S = 0.2
|
||
# объект мимо API: botocore образа с настройками процесса реплики (адрес,
|
||
# регион, ключи API — из окружения контейнера, в драйвер не попадают)
|
||
RC_PUT_OBJECT_PY = """\
|
||
import sys
|
||
import botocore.session
|
||
from botocore.config import Config
|
||
from src.config import settings
|
||
s3 = settings.s3
|
||
client = botocore.session.get_session().create_client(
|
||
"s3",
|
||
endpoint_url=s3.endpoint_url,
|
||
region_name=s3.region,
|
||
aws_access_key_id=s3.access_key_id.get_secret_value(),
|
||
aws_secret_access_key=s3.secret_access_key.get_secret_value(),
|
||
config=Config(s3={"addressing_style": "path"},
|
||
retries={"total_max_attempts": 1}),
|
||
)
|
||
body = sys.stdin.buffer.read()
|
||
client.put_object(Bucket=s3.bucket, Key=sys.argv[1], Body=body)
|
||
"""
|
||
RC_FOUND = "Found storage discrepancy"
|
||
RC_FIXED = "Fixed storage discrepancy"
|
||
RC_FINISHED = "Finished reconcile pass"
|
||
|
||
|
||
def rc_reconcile(
|
||
*,
|
||
apply: bool,
|
||
grace: int | None = None,
|
||
staging_retention: int | None = None,
|
||
) -> tuple[int, list[dict[str, object]]]:
|
||
"""Разовая сверка в контейнере уборщика: код выхода и записи журнала."""
|
||
env = (
|
||
[]
|
||
if grace is None
|
||
else ["-e", f"CLEANER__PENDING_GRACE_SECONDS={grace}"]
|
||
)
|
||
if staging_retention is not None:
|
||
env += [
|
||
"-e",
|
||
f"CLEANER__STAGING_RETENTION_SECONDS={staging_retention}",
|
||
]
|
||
proc = subprocess.run(
|
||
[
|
||
"docker",
|
||
"compose",
|
||
"run",
|
||
"--rm",
|
||
"--no-deps",
|
||
"-T",
|
||
*env,
|
||
"cleaner",
|
||
"reconcile",
|
||
*(["--apply"] if apply else []),
|
||
],
|
||
cwd=ROOT,
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
records = []
|
||
for line in proc.stdout.splitlines():
|
||
if line.startswith("{"):
|
||
with contextlib.suppress(json.JSONDecodeError):
|
||
records.append(json.loads(line))
|
||
return proc.returncode, records
|
||
|
||
|
||
def rc_events(
|
||
records: list[dict[str, object]],
|
||
event: str,
|
||
) -> list[dict[str, object]]:
|
||
return [item for item in records if item.get("event") == event]
|
||
|
||
|
||
def rc_finished(records: list[dict[str, object]]) -> dict[str, object]:
|
||
found = rc_events(records, RC_FINISHED)
|
||
return found[-1] if found else {}
|
||
|
||
|
||
def rc_print_pass(
|
||
title: str,
|
||
code: int,
|
||
records: list[dict[str, object]],
|
||
) -> None:
|
||
"""Таблица «класс → ключ → id → возраст» прохода и его итог."""
|
||
finished = rc_finished(records)
|
||
print(f"{title}: exit {code}")
|
||
for record in (
|
||
*rc_events(records, RC_FOUND),
|
||
*rc_events(records, RC_FIXED),
|
||
):
|
||
action = record.get("action") or "-"
|
||
sizes = ""
|
||
if record.get("stored_size") is not None:
|
||
sizes = (
|
||
f" size {record.get('size_bytes')} stored "
|
||
f"{record.get('stored_size')}"
|
||
)
|
||
print(
|
||
f" {record.get('level', ''):<7} {record.get('kind', ''):<16} "
|
||
f"{action:<15} {record.get('object_key')} id "
|
||
f"{record.get('attachment_id') or '-'} age "
|
||
f"{record.get('age_seconds')} s{sizes}",
|
||
)
|
||
keys = (
|
||
"listed_objects",
|
||
"listed_staging",
|
||
"checked_rows",
|
||
"found",
|
||
"fixed",
|
||
"remaining",
|
||
"fresh_objects",
|
||
"fresh_rows",
|
||
"lost_known",
|
||
"refused",
|
||
"interrupted_by",
|
||
"duration_ms",
|
||
)
|
||
print(
|
||
" total: " + ", ".join(f"{key}={finished.get(key)}" for key in keys),
|
||
)
|
||
|
||
|
||
def rc_kinds(
|
||
records: list[dict[str, object]],
|
||
event: str,
|
||
names: dict[str, str],
|
||
) -> dict[str, str]:
|
||
"""Свои находки: имя в прогоне → класс (по ключу объекта)."""
|
||
by_key = {value: name for name, value in names.items()}
|
||
return {
|
||
by_key[str(record.get("object_key"))]: str(record.get("kind"))
|
||
for record in rc_events(records, event)
|
||
if str(record.get("object_key")) in by_key
|
||
}
|
||
|
||
|
||
def rc_put_object(key: str, data: bytes) -> int:
|
||
"""Объект мимо API процессом в контейнере реплики; код выхода."""
|
||
replicas = compose("ps", "-q", "--status", "running", "api").split()
|
||
if not replicas:
|
||
return 1
|
||
proc = subprocess.run(
|
||
["docker", "exec", "-i", replicas[0], "python", "-c", RC_PUT_OBJECT_PY]
|
||
+ [key],
|
||
input=data,
|
||
capture_output=True,
|
||
check=False,
|
||
)
|
||
return proc.returncode
|
||
|
||
|
||
def rc_lost_ids() -> set[str]:
|
||
return set(
|
||
stand_psql(
|
||
"SELECT id FROM attachments WHERE lost_at IS NOT NULL;\n",
|
||
).split(),
|
||
)
|
||
|
||
|
||
def rc_rows() -> dict[str, str]:
|
||
"""Строки вложений рабочей базы: `id` → `статус размер`."""
|
||
rows = stand_psql(
|
||
"SELECT id || '|' || status || ' ' || size_bytes FROM attachments;\n",
|
||
).splitlines()
|
||
return dict(line.split("|") for line in rows if "|" in line)
|
||
|
||
|
||
def rc_png(seed: int, *, width: int = 200, height: int = 170) -> bytes:
|
||
"""Настоящий RGB PNG из шума (~100 KiB при 200 × 170) на stdlib."""
|
||
noise = random_bytes(seed, height * (width * 3))
|
||
rows = b"".join(
|
||
b"\x00" + noise[row * width * 3 : (row + 1) * width * 3]
|
||
for row in range(height)
|
||
)
|
||
|
||
def chunk(kind: bytes, body: bytes) -> bytes:
|
||
crc = zlib.crc32(kind + body)
|
||
return (
|
||
struct.pack(">I", len(body)) + kind + body + struct.pack(">I", crc)
|
||
)
|
||
|
||
header = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||
return (
|
||
b"\x89PNG\r\n\x1a\n"
|
||
+ chunk(b"IHDR", header)
|
||
+ chunk(b"IDAT", zlib.compress(rows, 1))
|
||
+ chunk(b"IEND", b"")
|
||
)
|
||
|
||
|
||
def random_bytes(seed: int, size: int) -> bytes:
|
||
"""Детерминированные «шумовые» байты по зерну: PNG из них почти не
|
||
сжимается, и размер файла — около `size`."""
|
||
out = bytearray()
|
||
counter = 0
|
||
while len(out) < size:
|
||
out += hashlib.sha256(f"{seed}:{counter}".encode()).digest()
|
||
counter += 1
|
||
return bytes(out[:size])
|
||
|
||
|
||
def rc_stand() -> tuple[str, str] | None:
|
||
"""Bucket и имя базы рабочего стенда из `docker compose config`."""
|
||
try:
|
||
stand = s3_stand()
|
||
config = json.loads(compose("config", "--format", "json"))
|
||
database = str(
|
||
config["services"]["api"]["environment"]["DATABASE__NAME"],
|
||
)
|
||
except (RuntimeError, KeyError, StopIteration, ValueError) as e:
|
||
print(f"FAIL: compose config of the stand: {e}")
|
||
return None
|
||
return stand["bucket"], database
|
||
|
||
|
||
def rc_signals(body: Callable[[], int]) -> int:
|
||
"""SIGTERM и SIGHUP — как Ctrl+C: `finally` тела снимает триггер."""
|
||
|
||
def interrupted(signum: int, _frame: object) -> None:
|
||
raise KeyboardInterrupt(signal.Signals(signum).name)
|
||
|
||
previous = {
|
||
signum: signal.signal(signum, interrupted)
|
||
for signum in (signal.SIGTERM, signal.SIGHUP)
|
||
}
|
||
try:
|
||
return body()
|
||
finally:
|
||
for signum, handler in previous.items():
|
||
signal.signal(signum, handler)
|
||
|
||
|
||
def cmd_reconcile_cycle(port: int) -> int:
|
||
"""Спек `storage-consistency`, сверка bucket и БД на рабочем стенде
|
||
через LB (design change `track2-reconciler`, решение 12): исходный
|
||
dry-run без расхождений, расхождения с обеих сторон, dry-run без
|
||
изменений, 500 до сверки, `--apply`, 404 и 200 после, повтор, удаление
|
||
чужого объекта оператором, свежий объект после grace, возврат
|
||
оригинала. Триггер — на уникальный `filename`, снимается в `finally` и
|
||
в начале следующего прогона. Токенов и секретов в выводе нет."""
|
||
if no_lb(port):
|
||
print("reconcile-cycle needs the stand with the load balancer")
|
||
return 2
|
||
return rc_signals(lambda: reconcile_cycle(port))
|
||
|
||
|
||
def reconcile_cycle(port: int) -> int:
|
||
"""Тело `cmd_reconcile_cycle`."""
|
||
names = rc_stand()
|
||
if names is None:
|
||
return 1
|
||
bucket, database = names
|
||
prefix = f"{database}/{ATTACHMENT_KEY_PREFIX}"
|
||
stand_psql(RC_CLEAR_SQL)
|
||
rows: list[tuple[str, str, str]] = []
|
||
|
||
# 1. исходный dry-run с grace по умолчанию: стенд сведён
|
||
code, records = rc_reconcile(apply=False)
|
||
rc_print_pass("initial dry-run (default grace)", code, records)
|
||
if code != 0 or rc_events(records, RC_FOUND):
|
||
print("FAIL: the stand is not reconciled, run make reconcile first")
|
||
return 2
|
||
|
||
# 2. участники и вложения через LB
|
||
people = attachment_people(port, "rc")
|
||
if people is None:
|
||
return 1
|
||
_, tokens, chat_id = people
|
||
data = FIXTURE_PNG.read_bytes()
|
||
tag = uuid.uuid4().hex[:8]
|
||
uploaded: dict[str, dict[str, object]] = {}
|
||
for name in ("A", "B", "C"):
|
||
status, _, attachment = upload_ready(
|
||
port,
|
||
tokens["alice"],
|
||
chat_id,
|
||
data,
|
||
content_type="image/png",
|
||
filename=f"rc-{tag}-{name}.png",
|
||
)
|
||
rows.append((f"upload {name}", "202", str(status)))
|
||
if status != ATTACHMENT_ACCEPTED or not isinstance(attachment, dict):
|
||
return report_reconcile(rows)
|
||
uploaded[name] = attachment
|
||
status, _, message = call(
|
||
port,
|
||
"POST",
|
||
f"{CHATS}/{chat_id}/messages",
|
||
token=tokens["alice"],
|
||
body={"text": "", "attachment_ids": [uploaded["A"]["id"]]},
|
||
extra=key_header(),
|
||
)
|
||
rows.append(("message with A", "201", str(status)))
|
||
message_id = message.get("id") if isinstance(message, dict) else None
|
||
keys = {
|
||
name: f"{prefix}/{attachment['id']}/{ATTACHMENT_ORIGINAL}"
|
||
for name, attachment in uploaded.items()
|
||
}
|
||
keys["O"] = f"{prefix}/{uuid.uuid4()}/{ATTACHMENT_ORIGINAL}"
|
||
keys["X"] = f"{prefix}/x-{uuid.uuid4()}"
|
||
ids = {
|
||
name: str(attachment["id"]) for name, attachment in uploaded.items()
|
||
}
|
||
# объекты вариантов B: строки B не станет, они тоже объекты без метаданных
|
||
b_variants = []
|
||
for line in stand_psql(
|
||
"SELECT variant, object_key FROM attachment_variants "
|
||
f"WHERE attachment_id = '{ids['B']}';\n",
|
||
).splitlines():
|
||
variant_name, variant_key = line.split("|")
|
||
keys[f"B-{variant_name}"] = variant_key
|
||
b_variants.append(f"B-{variant_name}")
|
||
rows.append(("variants of B", "3", str(len(b_variants))))
|
||
# staging: S — без строки, Y — ключ другого вида (design change
|
||
# pipeline-reliability, решение 9)
|
||
staging_prefix = f"{database}/{STAGING_KEY_PREFIX}"
|
||
keys["S"] = f"{staging_prefix}/{uuid.uuid4()}/{ATTACHMENT_ORIGINAL}"
|
||
keys["Y"] = f"{staging_prefix}/y-{uuid.uuid4()}"
|
||
try:
|
||
# 3. расхождения с обеих сторон
|
||
rows.append(
|
||
("put O without a row", "0", str(rc_put_object(keys["O"], data))),
|
||
)
|
||
rows.append(
|
||
("put X (unknown key)", "0", str(rc_put_object(keys["X"], data))),
|
||
)
|
||
rows.append(
|
||
("put S without a row", "0", str(rc_put_object(keys["S"], data))),
|
||
)
|
||
rows.append(
|
||
("put Y (unknown key)", "0", str(rc_put_object(keys["Y"], data))),
|
||
)
|
||
weed_shell(f"fs.rm /buckets/{bucket}/{keys['A']}")
|
||
# id — UUID из ответа API: безопасны в тексте SQL
|
||
stand_psql(
|
||
"BEGIN;\n"
|
||
f"DELETE FROM attachment_variants WHERE attachment_id = '{ids['B']}';\n"
|
||
f"DELETE FROM attachment_jobs WHERE attachment_id = '{ids['B']}';\n"
|
||
f"DELETE FROM attachments WHERE id = '{ids['B']}';\n"
|
||
"COMMIT;\n",
|
||
)
|
||
stand_psql(
|
||
"UPDATE attachments SET size_bytes = size_bytes + 1 "
|
||
f"WHERE id = '{ids['C']}';\n",
|
||
)
|
||
fail_name = f"rc-{tag}-P.png"
|
||
before = attachment_statuses()
|
||
stand_psql(
|
||
RC_FAIL_COMMIT_SQL.format(name=RC_TRIGGER, filename=fail_name),
|
||
)
|
||
status, _, _ = upload_bytes(
|
||
port,
|
||
tokens["alice"],
|
||
chat_id,
|
||
data,
|
||
content_type="image/png",
|
||
filename=fail_name,
|
||
)
|
||
stand_psql(RC_CLEAR_SQL)
|
||
rows.append(("upload P with COMMIT failure", "503", str(status)))
|
||
pending = sorted(set(attachment_statuses()) - set(before))
|
||
rows.append(("pending rows of P", "1", str(len(pending))))
|
||
if len(pending) != 1:
|
||
return report_reconcile(rows)
|
||
ids["P"] = pending[0]
|
||
# зависшая загрузка называет ключ staging (design change
|
||
# async-attachments, решение 11)
|
||
keys["P"] = (
|
||
f"{database}/{STAGING_KEY_PREFIX}/{ids['P']}/{ATTACHMENT_ORIGINAL}"
|
||
)
|
||
print("keys of the run:")
|
||
for name, key in sorted(keys.items()):
|
||
print(f" {name}: {key}")
|
||
|
||
# 4. после grace прогона — dry-run без изменений. Срок хранения staging
|
||
# прогона — тот же grace: иначе S — свежий ещё сутки
|
||
print(f"waiting {RC_GRACE_S + 1} s for grace {RC_GRACE_S} s")
|
||
time.sleep(RC_GRACE_S + 1)
|
||
snapshot = (
|
||
rc_rows(),
|
||
stored_attachment_ids(bucket, database),
|
||
rc_lost_ids(),
|
||
)
|
||
code, records = rc_reconcile(apply=False, grace=RC_GRACE_S)
|
||
rc_print_pass(
|
||
"dry-run (grace 30 s, default staging retention)",
|
||
code,
|
||
records,
|
||
)
|
||
found = rc_kinds(records, RC_FOUND, keys)
|
||
rows.append(("S fresh by retention", "-", found.get("S", "-")))
|
||
rows.append(("Y fresh by retention", "-", found.get("Y", "-")))
|
||
code, records = rc_reconcile(
|
||
apply=False,
|
||
grace=RC_GRACE_S,
|
||
staging_retention=RC_GRACE_S,
|
||
)
|
||
rc_print_pass(
|
||
f"dry-run (grace and staging retention {RC_GRACE_S} s)",
|
||
code,
|
||
records,
|
||
)
|
||
after = (
|
||
rc_rows(),
|
||
stored_attachment_ids(bucket, database),
|
||
rc_lost_ids(),
|
||
)
|
||
rows.append(("dry-run exit code", "3", str(code)))
|
||
found = rc_kinds(records, RC_FOUND, keys)
|
||
for name, kind in (
|
||
("O", "orphan_object"),
|
||
("B", "orphan_object"),
|
||
*((name, "orphan_object") for name in b_variants),
|
||
("S", "orphan_staging"),
|
||
("A", "missing_object"),
|
||
("C", "size_mismatch"),
|
||
("P", "stale_pending"),
|
||
("X", "unknown_object"),
|
||
("Y", "unknown_object"),
|
||
):
|
||
rows.append((f"dry-run finds {name}", kind, found.get(name, "-")))
|
||
rows.append(
|
||
(
|
||
"dry-run changes rows, objects, marks",
|
||
"no",
|
||
"no" if after == snapshot else "yes",
|
||
),
|
||
)
|
||
|
||
# 5. байты потерянного до сверки
|
||
status, _, _ = call_bytes(
|
||
port,
|
||
"GET",
|
||
f"{ATTACHMENTS}/{ids['A']}/content",
|
||
token=tokens["bob"],
|
||
)
|
||
rows.append(("A content before apply", "500", str(status)))
|
||
|
||
# 6. --apply; свежий объект F записан прямо перед ним
|
||
keys["F"] = f"{prefix}/{uuid.uuid4()}/{ATTACHMENT_ORIGINAL}"
|
||
rows.append(("put fresh F", "0", str(rc_put_object(keys["F"], data))))
|
||
fresh_written = time.monotonic()
|
||
code, records = rc_reconcile(
|
||
apply=True,
|
||
grace=RC_GRACE_S,
|
||
staging_retention=RC_GRACE_S,
|
||
)
|
||
rc_print_pass(f"apply (grace {RC_GRACE_S} s)", code, records)
|
||
rows.append(("apply exit code (X and Y left)", "3", str(code)))
|
||
fixed = {
|
||
name: str(record.get("action"))
|
||
for record in rc_events(records, RC_FIXED)
|
||
for name, key in keys.items()
|
||
if record.get("object_key") == key
|
||
}
|
||
for name, action in (
|
||
("O", "deleted_object"),
|
||
("B", "deleted_object"),
|
||
*((name, "deleted_object") for name in b_variants),
|
||
("S", "deleted_object"),
|
||
("A", "marked_lost"),
|
||
("C", "marked_lost"),
|
||
("P", "removed_pending"),
|
||
):
|
||
rows.append((f"apply fixes {name}", action, fixed.get(name, "-")))
|
||
rows.append(("apply touches F (fresh)", "-", fixed.get("F", "-")))
|
||
stored = stored_attachment_ids(bucket, database)
|
||
staged = stored_attachment_ids(bucket, database, STAGING_KEY_PREFIX)
|
||
statuses = attachment_statuses()
|
||
lost = rc_lost_ids()
|
||
rows.append(
|
||
("A and C marked lost", "yes", yes({ids["A"], ids["C"]} <= lost)),
|
||
)
|
||
rows.append(
|
||
(
|
||
"P row and staging object",
|
||
"absent",
|
||
"present"
|
||
if ids["P"] in statuses or ids["P"] in staged
|
||
else "absent",
|
||
),
|
||
)
|
||
rows.append(
|
||
(
|
||
"staging object S",
|
||
"absent",
|
||
"present" if keys["S"].split("/")[-2] in staged else "absent",
|
||
),
|
||
)
|
||
for name in ("O", "B"):
|
||
object_id = keys[name].split("/")[-2]
|
||
rows.append(
|
||
(
|
||
f"object {name}",
|
||
"absent",
|
||
"present" if object_id in stored else "absent",
|
||
),
|
||
)
|
||
rows.append(
|
||
(
|
||
"fresh F kept",
|
||
"present",
|
||
"present" if keys["F"].split("/")[-2] in stored else "absent",
|
||
),
|
||
)
|
||
status, _, _ = call_bytes(
|
||
port,
|
||
"GET",
|
||
f"{ATTACHMENTS}/{ids['A']}/content",
|
||
token=tokens["bob"],
|
||
)
|
||
rows.append(("A content after apply", "404", str(status)))
|
||
status, _, meta = call(
|
||
port,
|
||
"GET",
|
||
f"{ATTACHMENTS}/{ids['A']}",
|
||
token=tokens["bob"],
|
||
)
|
||
rows.append(("A metadata after apply", "200", str(status)))
|
||
rows.append(
|
||
(
|
||
"A metadata = upload response",
|
||
"yes",
|
||
yes(meta == uploaded["A"]),
|
||
),
|
||
)
|
||
status, _, page = call(
|
||
port,
|
||
"GET",
|
||
f"{CHATS}/{chat_id}/messages",
|
||
token=tokens["bob"],
|
||
)
|
||
linked = [
|
||
item.get("attachment_ids")
|
||
for item in (
|
||
page.get("items", []) if isinstance(page, dict) else []
|
||
)
|
||
if item.get("id") == message_id
|
||
]
|
||
rows.append(
|
||
(
|
||
"history keeps A in the message",
|
||
"yes",
|
||
yes(linked == [[ids["A"]]]),
|
||
),
|
||
)
|
||
|
||
# 7. повтор: остались только чужие X и Y; оператор удаляет их. Срок
|
||
# хранения прогона: со сроком по умолчанию Y (моложе суток) — свежий
|
||
code, records = rc_reconcile(
|
||
apply=False,
|
||
grace=RC_GRACE_S,
|
||
staging_retention=RC_GRACE_S,
|
||
)
|
||
rc_print_pass("repeat dry-run", code, records)
|
||
found = rc_kinds(records, RC_FOUND, keys)
|
||
rows.append(
|
||
(
|
||
"repeat finds only X and Y",
|
||
"X,Y",
|
||
",".join(sorted(found)) or "-",
|
||
),
|
||
)
|
||
rows.append(("repeat exit code", "3", str(code)))
|
||
weed_shell(f"fs.rm /buckets/{bucket}/{keys['X']}")
|
||
weed_shell(f"fs.rm /buckets/{bucket}/{keys['Y']}")
|
||
print("operator removed X and Y (weed shell fs.rm)")
|
||
code, records = rc_reconcile(
|
||
apply=False,
|
||
grace=RC_GRACE_S,
|
||
staging_retention=RC_GRACE_S,
|
||
)
|
||
rc_print_pass("dry-run after X and Y are removed", code, records)
|
||
rows.append(("exit code after X and Y are removed", "0", str(code)))
|
||
wait = max(0.0, fresh_written + RC_GRACE_S + 1 - time.monotonic())
|
||
print(f"waiting {wait:.0f} s until F is older than grace")
|
||
time.sleep(wait)
|
||
code, records = rc_reconcile(apply=True, grace=RC_GRACE_S)
|
||
rc_print_pass("apply after F aged", code, records)
|
||
fixed = rc_kinds(records, RC_FIXED, keys)
|
||
rows.append(
|
||
("F removed after grace", "orphan_object", fixed.get("F", "-")),
|
||
)
|
||
rows.append(("apply exit code (F)", "0", str(code)))
|
||
|
||
# 8. возврат оригинала
|
||
rows.append(
|
||
("put A original back", "0", str(rc_put_object(keys["A"], data))),
|
||
)
|
||
code, records = rc_reconcile(apply=True, grace=RC_GRACE_S)
|
||
rc_print_pass("apply after A is back", code, records)
|
||
fixed = rc_kinds(records, RC_FIXED, keys)
|
||
rows.append(("A restored", "restored_object", fixed.get("A", "-")))
|
||
status, _, payload = call_bytes(
|
||
port,
|
||
"GET",
|
||
f"{ATTACHMENTS}/{ids['A']}/content",
|
||
token=tokens["bob"],
|
||
)
|
||
rows.append(("A content after restore", "200", str(status)))
|
||
rows.append(
|
||
(
|
||
"A sha256 = uploaded",
|
||
"yes",
|
||
yes(sha256_hex(payload) == uploaded["A"]["sha256"]),
|
||
),
|
||
)
|
||
code, records = rc_reconcile(apply=False, grace=RC_GRACE_S)
|
||
rc_print_pass("final dry-run", code, records)
|
||
rows.append(("final dry-run exit code", "0", str(code)))
|
||
finally:
|
||
stand_psql(RC_CLEAR_SQL)
|
||
# чужие и свежий объект не остаются при любом исходе
|
||
for name in ("X", "F", "O", "S", "Y"):
|
||
if name in keys:
|
||
weed_shell(f"fs.rm /buckets/{bucket}/{keys[name]}")
|
||
# staging B: строки нет, а срок хранения ещё не вышел: сверка считает его
|
||
# свежим сутки
|
||
weed_shell(
|
||
f"fs.rm /buckets/{bucket}/{database}/{STAGING_KEY_PREFIX}/"
|
||
f"{ids['B']}/{ATTACHMENT_ORIGINAL}",
|
||
)
|
||
triggers = stand_psql(
|
||
f"SELECT count(*) FROM pg_trigger WHERE tgname = '{RC_TRIGGER}';\n",
|
||
).strip()
|
||
rows.append(("driver trigger left", "0", triggers))
|
||
return report_reconcile(rows)
|
||
|
||
|
||
def yes(value: bool) -> str:
|
||
return "yes" if value else "no"
|
||
|
||
|
||
def report_reconcile(
|
||
rows: list[tuple[str, str, str]],
|
||
*,
|
||
passed: str = "reconcile found and fixed the discrepancies, repeat found 0",
|
||
) -> int:
|
||
"""Таблица «проверка → ожидаемо → получено»; код 1 при расхождении."""
|
||
width = max(len(check) for check, _, _ in rows)
|
||
failed = 0
|
||
for check, expected, got in rows:
|
||
ok = expected == got
|
||
failed += not ok
|
||
print(
|
||
f"{check:<{width}} expected {expected:<15} got {got}"
|
||
+ ("" if ok else " FAIL"),
|
||
)
|
||
if failed:
|
||
print(f"FAIL: {failed} check(s) failed")
|
||
return 1
|
||
print(f"PASS: {passed}")
|
||
return 0
|
||
|
||
|
||
def cmd_reconcile_stress(port: int, *, seconds: float, clients: int) -> int:
|
||
"""Спек `storage-consistency`, «Сверка под нагрузкой», на рабочем
|
||
стенде через LB (design change `track2-reconciler`, решение 12):
|
||
внесённые расхождения, `clients` клиентов `seconds` секунд загружают
|
||
PNG ~100 KiB и отправляют сообщения, поток сверки — `--apply` с grace
|
||
20 с раз в ~3 с. В конце — каждое 202 дошло до `ready` и скачивается с
|
||
тем же SHA-256, каждое сообщение отдаёт своё вложение, повтор — 0. Проверка
|
||
корректности, не замер: тихий хост не нужен."""
|
||
if no_lb(port):
|
||
print("reconcile-stress needs the stand with the load balancer")
|
||
return 2
|
||
if seconds <= RC_STRESS_GRACE_S:
|
||
print(f"--seconds must be longer than grace {RC_STRESS_GRACE_S} s")
|
||
return 2
|
||
return rc_signals(lambda: reconcile_stress(port, seconds, clients))
|
||
|
||
|
||
def reconcile_stress(port: int, seconds: float, clients: int) -> int:
|
||
"""Тело `cmd_reconcile_stress`."""
|
||
names = rc_stand()
|
||
if names is None:
|
||
return 1
|
||
bucket, database = names
|
||
prefix = f"{database}/{ATTACHMENT_KEY_PREFIX}"
|
||
code, records = rc_reconcile(apply=False, grace=RC_STRESS_GRACE_S)
|
||
rc_print_pass(
|
||
f"precondition dry-run (grace {RC_STRESS_GRACE_S} s)",
|
||
code,
|
||
records,
|
||
)
|
||
if code != 0 or rc_events(records, RC_FOUND):
|
||
print("FAIL: the stand is not reconciled, run make reconcile first")
|
||
return 2
|
||
people = attachment_people(port, "rs")
|
||
if people is None:
|
||
return 1
|
||
_, tokens, chat_id = people
|
||
data = FIXTURE_PNG.read_bytes()
|
||
rows: list[tuple[str, str, str]] = []
|
||
orphans = [
|
||
f"{prefix}/{uuid.uuid4()}/{ATTACHMENT_ORIGINAL}" for _ in range(2)
|
||
]
|
||
for key in orphans:
|
||
rows.append(
|
||
("put object without a row", "0", str(rc_put_object(key, data))),
|
||
)
|
||
injected: list[str] = []
|
||
for _ in range(2):
|
||
status, _, attachment = upload_ready(
|
||
port,
|
||
tokens["alice"],
|
||
chat_id,
|
||
data,
|
||
content_type="image/png",
|
||
filename="rs-lost.png",
|
||
)
|
||
if status != ATTACHMENT_ACCEPTED or not isinstance(attachment, dict):
|
||
print(f"FAIL: upload {status}, not ready")
|
||
return 1
|
||
injected.append(str(attachment["id"]))
|
||
weed_shell(
|
||
f"fs.rm /buckets/{bucket}/{prefix}/{attachment['id']}/"
|
||
f"{ATTACHMENT_ORIGINAL}",
|
||
)
|
||
lost_before = rc_lost_ids()
|
||
deadline = time.monotonic() + seconds
|
||
lock = threading.Lock()
|
||
uploads: dict[str, str] = {}
|
||
messages: dict[str, str] = {}
|
||
codes: Counter[int] = Counter()
|
||
passes: list[tuple[int, list[dict[str, object]]]] = []
|
||
errors: list[str] = []
|
||
|
||
def load(worker: int) -> None:
|
||
token = tokens["alice"] if worker % 2 == 0 else tokens["bob"]
|
||
number = 0
|
||
while time.monotonic() < deadline:
|
||
number += 1
|
||
body = rc_png(worker * 1_000_000 + number)
|
||
status, _, attachment = upload_ready(
|
||
port,
|
||
token,
|
||
chat_id,
|
||
body,
|
||
content_type="image/png",
|
||
filename="rs.png",
|
||
)
|
||
with lock:
|
||
codes[status] += 1
|
||
if status != ATTACHMENT_ACCEPTED:
|
||
continue
|
||
if not isinstance(attachment, dict):
|
||
with lock:
|
||
errors.append("attachment did not become ready")
|
||
continue
|
||
attachment_id = str(attachment["id"])
|
||
with lock:
|
||
uploads[attachment_id] = sha256_hex(body)
|
||
status, _, message = call(
|
||
port,
|
||
"POST",
|
||
f"{CHATS}/{chat_id}/messages",
|
||
token=token,
|
||
body={"text": "", "attachment_ids": [attachment_id]},
|
||
extra=key_header(),
|
||
timeout=30,
|
||
)
|
||
if status == 201 and isinstance(message, dict):
|
||
with lock:
|
||
messages[str(message["id"])] = attachment_id
|
||
else:
|
||
with lock:
|
||
errors.append(f"message {status}")
|
||
# пауза клиента: синтетические объекты остаются в рабочем
|
||
# bucket, без неё 4 клиента за 40 с пишут ~5 800 по 100 KiB
|
||
time.sleep(RC_STRESS_PAUSE_S)
|
||
|
||
def reconcile() -> None:
|
||
while time.monotonic() < deadline:
|
||
started = time.monotonic()
|
||
passes.append(rc_reconcile(apply=True, grace=RC_STRESS_GRACE_S))
|
||
time.sleep(
|
||
max(0.0, started + RC_STRESS_PERIOD_S - time.monotonic()),
|
||
)
|
||
|
||
def guarded(target: Callable[..., None], *args: object) -> None:
|
||
try:
|
||
target(*args)
|
||
except Exception as e: # noqa: BLE001 — в отчёт, а не в stderr
|
||
with lock:
|
||
errors.append(repr(e))
|
||
|
||
print(
|
||
f"load: {clients} clients for {seconds:.0f} s, apply every {RC_STRESS_PERIOD_S} s",
|
||
)
|
||
threads = [
|
||
threading.Thread(target=guarded, args=(load, worker))
|
||
for worker in range(clients)
|
||
]
|
||
threads.append(threading.Thread(target=guarded, args=(reconcile,)))
|
||
for thread in threads:
|
||
thread.start()
|
||
for thread in threads:
|
||
thread.join()
|
||
# проход после нагрузки: всё внесённое уже старше grace
|
||
final_code, final_records = rc_reconcile(
|
||
apply=True,
|
||
grace=RC_STRESS_GRACE_S,
|
||
)
|
||
passes.append((final_code, final_records))
|
||
fixed: Counter[str] = Counter()
|
||
for _, pass_records in passes:
|
||
for record in rc_events(pass_records, RC_FIXED):
|
||
fixed[str(record.get("kind"))] += 1
|
||
stored = stored_attachment_ids(bucket, database)
|
||
lost_new = rc_lost_ids() - lost_before
|
||
mismatched = 0
|
||
for attachment_id, digest in uploads.items():
|
||
status, _, payload = call_bytes(
|
||
port,
|
||
"GET",
|
||
f"{ATTACHMENTS}/{attachment_id}/content",
|
||
token=tokens["bob"],
|
||
)
|
||
if status != 200 or sha256_hex(payload) != digest:
|
||
mismatched += 1
|
||
history: dict[str, list[object]] = {}
|
||
cursor = None
|
||
while True:
|
||
path = f"{CHATS}/{chat_id}/messages?limit=100"
|
||
if cursor:
|
||
path += "&" + urllib.parse.urlencode({"cursor": cursor})
|
||
status, _, page = call(port, "GET", path, token=tokens["alice"])
|
||
if status != 200 or not isinstance(page, dict):
|
||
errors.append(f"history {status}")
|
||
break
|
||
for item in page["items"]:
|
||
history[str(item["id"])] = item["attachment_ids"]
|
||
cursor = page.get("next_cursor")
|
||
if not cursor:
|
||
break
|
||
broken = sum(
|
||
history.get(message_id) != [attachment_id]
|
||
for message_id, attachment_id in messages.items()
|
||
)
|
||
code, records = rc_reconcile(apply=False, grace=RC_STRESS_GRACE_S)
|
||
rc_print_pass("repeat dry-run", code, records)
|
||
print(
|
||
"uploads by status: "
|
||
+ ", ".join(f"{k}={v}" for k, v in sorted(codes.items())),
|
||
)
|
||
print(f"messages sent: {len(messages)}")
|
||
print("reconcile passes: " + ", ".join(str(item[0]) for item in passes))
|
||
print(
|
||
"fixed by class: "
|
||
+ (", ".join(f"{k}={v}" for k, v in sorted(fixed.items())) or "-"),
|
||
)
|
||
rows.append(("uploads 202 and ready", ">0", ">0" if uploads else "0"))
|
||
rows.append(
|
||
(
|
||
"uploads not 202",
|
||
"0",
|
||
str(sum(v for k, v in codes.items() if k != ATTACHMENT_ACCEPTED)),
|
||
),
|
||
)
|
||
rows.append(
|
||
(
|
||
"passes interrupted (exit 1)",
|
||
"0",
|
||
str(sum(item[0] == 1 for item in passes)),
|
||
),
|
||
)
|
||
rows.append(
|
||
(
|
||
"objects without a row removed",
|
||
"yes",
|
||
yes(not {key.split("/")[-2] for key in orphans} & stored),
|
||
),
|
||
)
|
||
rows.append(
|
||
("new lost marks = injected", "yes", yes(lost_new == set(injected))),
|
||
)
|
||
rows.append(("downloads with other sha256", "0", str(mismatched)))
|
||
rows.append(("messages with unavailable attachment", "0", str(broken)))
|
||
rows.append(("thread errors", "0", str(len(errors))))
|
||
rows.append(("repeat dry-run exit code", "0", str(code)))
|
||
for error in errors[:5]:
|
||
print(f" error: {error}")
|
||
return report_reconcile(rows)
|
||
|
||
|
||
# reconcile-signal (design change track2-reconciler, «Уточнения apply», п.
|
||
# 23): код разового прохода, прерванного сигналом. S3 заморожен, поэтому
|
||
# только не рабочий проект compose
|
||
RS_WORKING_PROJECT = "mtusi-lab5"
|
||
RS_START_TIMEOUT_S = 30
|
||
# SIGTERM — через столько после «Started cleaner»: первая страница списка
|
||
# уже ждёт замороженный S3
|
||
RS_AFTER_START_S = 1.0
|
||
# stop_grace_period уборщика в docker-compose.yml: дольше — был бы SIGKILL
|
||
RS_STOP_LIMIT_S = 10
|
||
# режим --pace (design change track2-reconcile-cost, решение 14): пауза
|
||
# предела скорости вместо замороженного S3. Объекты под префиксом вложений
|
||
# с ключом, которого API не пишет (чужие для сверки): при пределе 1 объект/с
|
||
# проход после страницы списка ждёт столько секунд, сколько ключей
|
||
RS_PACE_OBJECTS = 8
|
||
RS_PACE_RATE = "1"
|
||
RS_PACE_AFTER_START_S = 2.0
|
||
# остановка во время паузы — не позже секунды после сигнала
|
||
RS_PACE_STOP_LIMIT_S = 1.0
|
||
# режим --pace --apply (verify W1 change track2-reconcile-cost): объекты
|
||
# пробы — без строки (<id>/original), и сверка с --apply их удаляет. Grace
|
||
# прохода — наименьший, который примет уборщик (граница живой загрузки
|
||
# 17 с), объекты старше него через секунду. При пределе 1 объект/с: список
|
||
# — 8 с, перепроверка — HEAD на объект (ещё 8 с), затем DELETE раз в
|
||
# секунду, и после каждого — пауза ~1 с. docker stop — посреди удалений
|
||
RS_PACE_APPLY_GRACE_S = 18
|
||
RS_PACE_APPLY_AFTER_START_S = 19.5
|
||
# объекты пробы — botocore в одноразовом контейнере сервиса api его
|
||
# ключами из окружения (как put-object hook стенда отказов); в argv и
|
||
# вывод ключи доступа не попадают. argv: действие (put, delete, count) и
|
||
# хвосты ключей под <база>/attachments/
|
||
RS_PACE_OBJECTS_PY = r"""
|
||
import os, sys
|
||
import botocore.session
|
||
from botocore.config import Config
|
||
from botocore.exceptions import ClientError
|
||
|
||
s3 = botocore.session.get_session().create_client(
|
||
"s3",
|
||
endpoint_url=f"http://{os.environ['S3__HOST']}:{os.environ['S3__PORT']}",
|
||
region_name="us-east-1",
|
||
aws_access_key_id=os.environ["S3__ACCESS_KEY_ID"],
|
||
aws_secret_access_key=os.environ["S3__SECRET_ACCESS_KEY"],
|
||
config=Config(s3={"addressing_style": "path"}),
|
||
)
|
||
bucket = os.environ["S3__BUCKET"]
|
||
prefix = os.environ["DATABASE__NAME"] + "/attachments/"
|
||
action, tails = sys.argv[1], sys.argv[2:]
|
||
present = 0
|
||
for tail in tails:
|
||
key = prefix + tail
|
||
if action == "put":
|
||
s3.put_object(Bucket=bucket, Key=key, Body=b"pace", ContentType="image/png")
|
||
elif action == "delete":
|
||
s3.delete_object(Bucket=bucket, Key=key)
|
||
else:
|
||
try:
|
||
s3.head_object(Bucket=bucket, Key=key)
|
||
present += 1
|
||
except ClientError:
|
||
pass
|
||
print(f"present {present}" if action == "count" else f"{action} {len(tails)} objects")
|
||
"""
|
||
|
||
|
||
def rfc3339_ns(text: str) -> int:
|
||
"""`2026-10-23T01:33:32.338748123Z` (Docker) → наносекунды эпохи;
|
||
без `fromisoformat`: Python 3.9 не принимает `Z` и наносекунды."""
|
||
base, _, rest = text.strip().partition(".")
|
||
digits = "".join(ch for ch in rest if ch.isdigit())
|
||
moment = datetime.strptime(base.rstrip("Z"), "%Y-%m-%dT%H:%M:%S")
|
||
seconds = int(moment.replace(tzinfo=UTC).timestamp())
|
||
return seconds * 10**9 + int((digits + "0" * 9)[:9])
|
||
|
||
|
||
def rs_pace_objects(action: str, tails: list[str]) -> str:
|
||
"""`put`, `delete` или `count` объектов пробы режима `--pace`; вывод
|
||
скрипта (у `count` — `present N`)."""
|
||
return compose(
|
||
"run",
|
||
"--rm",
|
||
"--no-deps",
|
||
"-T",
|
||
"--entrypoint",
|
||
"python",
|
||
"api",
|
||
"-",
|
||
action,
|
||
*tails,
|
||
stdin=RS_PACE_OBJECTS_PY,
|
||
)
|
||
|
||
|
||
def cmd_reconcile_signal(*, pace: bool = False, apply: bool = False) -> int:
|
||
"""Спек `graceful-shutdown`, разовый проход сверки, прерванный сигналом,
|
||
— код 1: на стенде проекта compose из окружения (`COMPOSE_PROJECT_NAME`
|
||
и др., рабочий `mtusi-lab5` — отказ, код 2) `docker compose pause s3`,
|
||
`run -d --no-deps cleaner reconcile --apply`, через секунду после
|
||
«Started cleaner» — `docker stop`; S3 размораживается в `finally`.
|
||
`pace` — вместо замороженного S3 пауза предела скорости: объекты пробы,
|
||
`reconcile --max-objects-per-second 1` (dry-run), `docker stop` через
|
||
2 с после «Started cleaner», остановка не дольше секунды, итог называет
|
||
ключи страницы (`listed_objects`); объекты удаляются в `finally`.
|
||
`pace` и `apply` (verify W1) — объекты пробы без строки, через grace
|
||
`reconcile --apply` с тем же пределом и `docker stop` посреди удалений:
|
||
каждое удалённое — запись «Fixed» и счёт `fixed`. Таблица и записи
|
||
процесса без секретов; код 1 при расхождении."""
|
||
if apply and not pace:
|
||
print("reconcile-signal: --apply is a variant of --pace")
|
||
return 2
|
||
try:
|
||
config = json.loads(compose("config", "--format", "json"))
|
||
except (RuntimeError, ValueError) as e:
|
||
print(f"FAIL: compose config of the stand: {e}")
|
||
return 2
|
||
project = str(config.get("name", ""))
|
||
if project == RS_WORKING_PROJECT:
|
||
print(
|
||
"reconcile-signal pauses S3 or adds probe objects: run it on a "
|
||
f"temporary stand (COMPOSE_PROJECT_NAME), not {RS_WORKING_PROJECT}",
|
||
)
|
||
return 2
|
||
services = config.get("services", {})
|
||
if "cleaner" not in services or "s3" not in services:
|
||
print(f"FAIL: no cleaner or s3 service in project {project}")
|
||
return 2
|
||
if not compose("ps", "-q", "--status", "running", "s3").strip():
|
||
print(f"FAIL: s3 of project {project} is not running")
|
||
return 2
|
||
name = f"{project}-reconcile-signal"
|
||
subprocess.run(["docker", "rm", "-f", name], capture_output=True)
|
||
started = False
|
||
took = -1.0
|
||
after_signal = -1.0
|
||
exit_code = ""
|
||
logs = ""
|
||
left = -1
|
||
tails: list[str] = []
|
||
run_env: list[str] = []
|
||
if pace:
|
||
if apply:
|
||
tails = [
|
||
f"{uuid.uuid4()}/original" for _ in range(RS_PACE_OBJECTS)
|
||
]
|
||
else:
|
||
tails = [f"pace-signal-{i}" for i in range(RS_PACE_OBJECTS)]
|
||
rs_pace_objects("put", tails)
|
||
print(f"{project}: {RS_PACE_OBJECTS} probe objects put")
|
||
args = ["reconcile", "--max-objects-per-second", RS_PACE_RATE]
|
||
after_start, limit = RS_PACE_AFTER_START_S, RS_PACE_STOP_LIMIT_S
|
||
waiting = "the rate limit pause"
|
||
if apply:
|
||
args.append("--apply")
|
||
grace = RS_PACE_APPLY_GRACE_S
|
||
run_env = ["-e", f"CLEANER__PENDING_GRACE_SECONDS={grace}"]
|
||
after_start = RS_PACE_APPLY_AFTER_START_S
|
||
waiting = "the rate limit pause after a DELETE"
|
||
print(f"waiting {grace + 1} s: probe objects older than grace")
|
||
time.sleep(grace + 1)
|
||
else:
|
||
compose("pause", "s3")
|
||
print(f"{project}: s3 paused")
|
||
args = ["reconcile", "--apply"]
|
||
after_start, limit = RS_AFTER_START_S, float(RS_STOP_LIMIT_S)
|
||
waiting = "paused S3"
|
||
try:
|
||
compose(
|
||
"run",
|
||
"-d",
|
||
"--no-deps",
|
||
"--name",
|
||
name,
|
||
*run_env,
|
||
"cleaner",
|
||
*args,
|
||
)
|
||
deadline = time.monotonic() + RS_START_TIMEOUT_S
|
||
while time.monotonic() < deadline:
|
||
logs = docker_logs(name)
|
||
if '"Started cleaner"' in logs:
|
||
started = True
|
||
break
|
||
time.sleep(0.2)
|
||
if started:
|
||
time.sleep(after_start)
|
||
print(f"docker stop while reconcile waits for {waiting}")
|
||
# момент сигнала — событие kill Docker (часы ВМ, как FinishedAt):
|
||
# время docker stop включает ещё разбор контейнера демоном
|
||
events = subprocess.Popen(
|
||
[
|
||
"docker",
|
||
"events",
|
||
"--filter",
|
||
f"container={name}",
|
||
"--filter",
|
||
"event=kill",
|
||
"--format",
|
||
"{{.TimeNano}}",
|
||
],
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.DEVNULL,
|
||
text=True,
|
||
)
|
||
time.sleep(0.3)
|
||
began = time.monotonic()
|
||
subprocess.run(["docker", "stop", name], capture_output=True)
|
||
took = time.monotonic() - began
|
||
time.sleep(0.3)
|
||
events.terminate()
|
||
kill_lines = (events.communicate()[0] or "").split()
|
||
exit_code, finished_at = (
|
||
subprocess.run(
|
||
[
|
||
"docker",
|
||
"inspect",
|
||
"-f",
|
||
"{{.State.ExitCode}}|{{.State.FinishedAt}}",
|
||
name,
|
||
],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
).stdout.strip()
|
||
+ "|"
|
||
).split("|")[:2]
|
||
if kill_lines and finished_at:
|
||
after_signal = (
|
||
rfc3339_ns(finished_at) - int(kill_lines[0])
|
||
) / 1e9
|
||
logs = docker_logs(name)
|
||
finally:
|
||
subprocess.run(["docker", "rm", "-f", name], capture_output=True)
|
||
if pace:
|
||
if apply:
|
||
lines = rs_pace_objects("count", tails).strip().splitlines()
|
||
counted = lines[-1].split() if lines else []
|
||
if counted[:1] == ["present"]:
|
||
left = int(counted[1])
|
||
print(f"{project}: probe objects left after the pass: {left}")
|
||
rs_pace_objects("delete", tails)
|
||
print(f"{project}: probe objects deleted")
|
||
else:
|
||
compose("unpause", "s3")
|
||
print(f"{project}: s3 unpaused")
|
||
records = []
|
||
for line in logs.splitlines():
|
||
if line.startswith("{"):
|
||
with contextlib.suppress(json.JSONDecodeError):
|
||
records.append(json.loads(line))
|
||
shown = ("event", "level", "mode", "operation", "error_type")
|
||
shown += ("reconcile_max_objects_per_second", "reconcile_apply")
|
||
shown += ("kind", "action", "object_key", "listed_objects", "found")
|
||
shown += ("fixed", "storage_objects", "s3_requests")
|
||
shown += ("max_objects_per_second", "duration_ms", "interrupted_by")
|
||
shown += ("exit_code", "timestamp")
|
||
print("== records of the one-off reconcile")
|
||
for record in records:
|
||
print(
|
||
json.dumps(
|
||
{key: record[key] for key in shown if key in record},
|
||
ensure_ascii=False,
|
||
),
|
||
)
|
||
finished = rc_finished(records)
|
||
stopped = [
|
||
item for item in records if item.get("event") == "Stopped cleaner"
|
||
]
|
||
# удалённые до сигнала объекты пробы: каждый — запись «Fixed» и fixed
|
||
deleted = RS_PACE_OBJECTS - left if left >= 0 else -1
|
||
print(
|
||
f"docker stop took {took:.1f} s, container exited "
|
||
f"{after_signal:.2f} s after the kill event, exit code "
|
||
f"{exit_code or '-'}",
|
||
)
|
||
rows = [
|
||
("Started cleaner (mode reconcile)", "yes", yes(started)),
|
||
("exit code", "1", exit_code),
|
||
(
|
||
"Finished reconcile pass interrupted_by",
|
||
"stop",
|
||
str(finished.get("interrupted_by")),
|
||
),
|
||
(
|
||
"Stopped cleaner exit_code",
|
||
"1",
|
||
str(stopped[-1].get("exit_code")) if stopped else "-",
|
||
),
|
||
(
|
||
"Fixed storage discrepancy records",
|
||
str(deleted) if apply else "0",
|
||
str(len(rc_events(records, RC_FIXED))),
|
||
),
|
||
(
|
||
f"exited within {limit:g} s after the signal"
|
||
if pace
|
||
else f"docker stop faster than {limit:g} s",
|
||
"yes",
|
||
yes(0 <= after_signal <= limit if pace else 0 <= took < limit),
|
||
),
|
||
]
|
||
if pace:
|
||
rate = next(
|
||
(
|
||
item.get("reconcile_max_objects_per_second")
|
||
for item in records
|
||
if item.get("event") == "Started cleaner"
|
||
),
|
||
None,
|
||
)
|
||
rows.insert(
|
||
1,
|
||
(
|
||
"Started cleaner reconcile_max_objects_per_second",
|
||
RS_PACE_RATE,
|
||
"-" if rate is None else f"{float(rate):g}",
|
||
),
|
||
)
|
||
# ключи страницы, после которой пришёл сигнал, — в итоге (verify W1)
|
||
rows.append(
|
||
(
|
||
"Finished reconcile pass listed_objects",
|
||
str(RS_PACE_OBJECTS),
|
||
str(finished.get("listed_objects")),
|
||
),
|
||
)
|
||
if apply:
|
||
fixed = finished.get("fixed")
|
||
rows += [
|
||
(
|
||
"probe objects deleted before the signal",
|
||
">0",
|
||
">0" if deleted > 0 else str(deleted),
|
||
),
|
||
(
|
||
"Finished reconcile pass fixed orphan_object",
|
||
str(deleted),
|
||
str(
|
||
fixed.get("orphan_object", 0)
|
||
if isinstance(fixed, dict)
|
||
else "-",
|
||
),
|
||
),
|
||
]
|
||
if apply:
|
||
passed = (
|
||
"one-off reconcile --apply stopped by SIGTERM during the rate "
|
||
"limit pause: exit 1 within a second, every deleted object fixed"
|
||
)
|
||
elif pace:
|
||
passed = (
|
||
"one-off reconcile stopped by SIGTERM during the rate limit "
|
||
"pause: exit 1 within a second"
|
||
)
|
||
else:
|
||
passed = (
|
||
"one-off reconcile stopped by SIGTERM: exit 1, nothing changed"
|
||
)
|
||
return report_reconcile(rows, passed=passed)
|
||
|
||
|
||
def docker_logs(name: str) -> str:
|
||
proc = subprocess.run(
|
||
["docker", "logs", name],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
return proc.stdout + proc.stderr
|
||
|
||
|
||
# lb-upload-timeouts: сроки LB пути загрузки на заглушке (design change
|
||
# upload-memory, решение 7). Молчание заглушки: дольше timeout server
|
||
# прочих путей (10 с), но меньше срока пути загрузки (30 с) — и дольше его
|
||
LBTO_LABEL = "mtusi.lb-upload-timeouts"
|
||
LBTO_SILENT_S = 12
|
||
LBTO_LONG_S = 32
|
||
# сколько клиент молчит посреди тела, если LB не ответил раньше: дольше
|
||
# timeout client (30 с)
|
||
LBTO_CLIENT_SILENT_S = 35
|
||
LBTO_BODY_BYTES = 10 * 1024 * 1024
|
||
LBTO_UPLOAD_PATH = f"{CHATS}/{uuid.UUID(int=1)}/attachments"
|
||
LBTO_READY_TIMEOUT_S = 30
|
||
# заглушка реплики на asyncio (stdlib образа API): /health/ready — 200,
|
||
# остальное — по параметру case; тело читает только там, где сказано
|
||
LBTO_STUB = r"""
|
||
import asyncio, json, os
|
||
|
||
SILENT = float(os.environ["STUB_SILENT_S"])
|
||
LONG = float(os.environ["STUB_LONG_S"])
|
||
|
||
|
||
async def handle(reader, writer):
|
||
try:
|
||
head = await reader.readuntil(b"\r\n\r\n")
|
||
lines = head.decode("latin-1").split("\r\n")
|
||
target = lines[0].split(" ")[1]
|
||
headers = {}
|
||
for line in lines[1:]:
|
||
name, sep, value = line.partition(":")
|
||
if sep:
|
||
headers[name.strip().lower()] = value.strip()
|
||
path, _, query = target.partition("?")
|
||
params = dict(p.split("=", 1) for p in query.split("&") if "=" in p)
|
||
case = params.get("case", "")
|
||
length = int(headers.get("content-length") or 0)
|
||
status = 200
|
||
if path != "/health/ready":
|
||
if case == "before-body":
|
||
await asyncio.sleep(SILENT)
|
||
await reader.readexactly(length)
|
||
status = 202
|
||
elif case in ("after-body", "too-long"):
|
||
await reader.readexactly(length)
|
||
await asyncio.sleep(SILENT if case == "after-body" else LONG)
|
||
status = 202
|
||
elif case == "other-path":
|
||
await asyncio.sleep(SILENT)
|
||
else:
|
||
await reader.readexactly(length)
|
||
status = 202
|
||
body = json.dumps({"status": "ok", "case": case}).encode()
|
||
writer.write(
|
||
f"HTTP/1.1 {status} Stub\r\nContent-Type: application/json\r\n"
|
||
f"Content-Length: {len(body)}\r\nX-Request-Id: stub-{case}\r\n"
|
||
"X-Instance-Id: stub\r\nConnection: close\r\n\r\n".encode() + body
|
||
)
|
||
await writer.drain()
|
||
except Exception:
|
||
pass
|
||
finally:
|
||
writer.close()
|
||
|
||
|
||
async def main():
|
||
server = await asyncio.start_server(handle, "0.0.0.0", 8080)
|
||
async with server:
|
||
await server.serve_forever()
|
||
|
||
|
||
asyncio.run(main())
|
||
"""
|
||
|
||
|
||
def lbto_docker(*args: str, check: bool = True) -> str:
|
||
"""docker CLI без shell; вывод — строкой."""
|
||
result = subprocess.run(
|
||
["docker", *args],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
if check and result.returncode != 0:
|
||
raise RuntimeError(
|
||
f"docker {args[0]} {args[1] if len(args) > 1 else ''}: "
|
||
f"{result.stderr.strip()[-300:]}",
|
||
)
|
||
return result.stdout.strip()
|
||
|
||
|
||
def lbto_haproxy_image() -> str:
|
||
"""Образ LB рабочего стенда — тег и digest из docker-compose.yml."""
|
||
text = (ROOT / "docker-compose.yml").read_text(encoding="utf-8")
|
||
match = re.search(r"^\s*image:\s*(haproxy:\S+)\s*$", text, re.MULTILINE)
|
||
if match is None:
|
||
raise RuntimeError("no haproxy image in docker-compose.yml")
|
||
return match.group(1)
|
||
|
||
|
||
def lbto_error_ok(
|
||
headers: dict[str, str],
|
||
body: bytes,
|
||
code: str,
|
||
) -> str:
|
||
"""Пусто — ответ LB в формате ошибки контракта; иначе — что не так."""
|
||
media = headers.get("content-type", "").split(";")[0].strip()
|
||
if media != "application/json":
|
||
return f"Content-Type {media or '-'}"
|
||
try:
|
||
data = json.loads(body.decode("utf-8"))
|
||
except (UnicodeDecodeError, ValueError):
|
||
return "body is not JSON"
|
||
error = data.get("error") if isinstance(data, dict) else None
|
||
if not isinstance(error, dict) or set(data) != {"error"}:
|
||
return "not {error: …}"
|
||
if set(error) != {"code", "message", "request_id"}:
|
||
return f"error fields {sorted(error)}"
|
||
if error["code"] != code:
|
||
return f"code {error['code']}"
|
||
request_id = headers.get("x-request-id", "")
|
||
if not request_id or error["request_id"] != request_id:
|
||
return "request_id differs from X-Request-Id"
|
||
return ""
|
||
|
||
|
||
def lbto_request(
|
||
port: int,
|
||
method: str,
|
||
path: str,
|
||
body: bytes | None,
|
||
) -> tuple[int, dict[str, str], bytes, float]:
|
||
"""Запрос через LB: статус, заголовки, тело, секунды до ответа."""
|
||
conn = http.client.HTTPConnection("127.0.0.1", port, timeout=60)
|
||
started = time.monotonic()
|
||
try:
|
||
headers = {"Content-Type": "image/png"} if body is not None else {}
|
||
conn.request(method, path, body=body, headers=headers)
|
||
resp = conn.getresponse()
|
||
data = resp.read()
|
||
elapsed = time.monotonic() - started
|
||
return (
|
||
resp.status,
|
||
{k.lower(): v for k, v in resp.getheaders()},
|
||
data,
|
||
elapsed,
|
||
)
|
||
finally:
|
||
conn.close()
|
||
|
||
|
||
def lbto_silent_client(
|
||
port: int,
|
||
) -> tuple[int, dict[str, str], bytes, float]:
|
||
"""Клиент отправил половину тела и молчит: ответ LB и секунды от
|
||
последнего отправленного байта."""
|
||
sock = socket.create_connection(("127.0.0.1", port), timeout=10)
|
||
try:
|
||
head = (
|
||
f"POST {LBTO_UPLOAD_PATH}?case=client-silent HTTP/1.1\r\n"
|
||
f"Host: 127.0.0.1:{port}\r\nContent-Type: image/png\r\n"
|
||
f"Content-Length: {LBTO_BODY_BYTES}\r\n\r\n"
|
||
).encode("ascii")
|
||
sock.sendall(head + bytes(LBTO_BODY_BYTES // 2))
|
||
started = time.monotonic()
|
||
sock.settimeout(LBTO_CLIENT_SILENT_S + 10)
|
||
resp = http.client.HTTPResponse(sock, method="POST")
|
||
resp.begin()
|
||
data = resp.read()
|
||
return (
|
||
resp.status,
|
||
{k.lower(): v for k, v in resp.getheaders()},
|
||
data,
|
||
time.monotonic() - started,
|
||
)
|
||
finally:
|
||
sock.close()
|
||
|
||
|
||
def cmd_lb_upload_timeouts(config: str, image: str) -> int:
|
||
"""Сроки LB пути загрузки (спек `load-balancing`, «Загрузки через
|
||
балансировщик», «Ошибки балансировщика в формате контракта»; design
|
||
change `upload-memory`, решение 7).
|
||
|
||
Временная сеть, заглушка реплики под именем `api` (образ API, stdlib)
|
||
и HAProxy закреплённого образа с `config`, порт LB — на свободном
|
||
`127.0.0.1`. Случаи идут параллельно, каждый — своё соединение и свой
|
||
`case` в строке запроса. Хранилищ и стендов compose не трогает; сеть и
|
||
контейнеры по метке удаляются при любом исходе."""
|
||
|
||
def interrupted(signum: int, _frame: object) -> None:
|
||
raise KeyboardInterrupt(signal.Signals(signum).name)
|
||
|
||
config_path = Path(config).resolve()
|
||
if not config_path.is_file():
|
||
print(f"config {config_path} not found")
|
||
return 2
|
||
tag = uuid.uuid4().hex[:8]
|
||
label = f"{LBTO_LABEL}={tag}"
|
||
network = f"mtusi-lbto-{tag}"
|
||
haproxy = lbto_haproxy_image()
|
||
port = lbto_free_port()
|
||
print(f"config {config_path}")
|
||
print(f"haproxy {haproxy}, stub image {image}, LB 127.0.0.1:{port}")
|
||
previous = {
|
||
signum: signal.signal(signum, interrupted)
|
||
for signum in (signal.SIGTERM, signal.SIGHUP)
|
||
}
|
||
mount = (
|
||
f"type=bind,src={config_path},"
|
||
"dst=/usr/local/etc/haproxy/haproxy.cfg,readonly"
|
||
)
|
||
try:
|
||
checked = subprocess.run(
|
||
[
|
||
"docker",
|
||
"run",
|
||
"--rm",
|
||
"--label",
|
||
label,
|
||
"-e",
|
||
"API_PORT=8080",
|
||
"--mount",
|
||
mount,
|
||
haproxy,
|
||
"haproxy",
|
||
"-c",
|
||
"-f",
|
||
"/usr/local/etc/haproxy/haproxy.cfg",
|
||
],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
print(f"haproxy -c: exit {checked.returncode}")
|
||
if checked.returncode != 0:
|
||
print((checked.stdout + checked.stderr).strip()[-600:])
|
||
return 1
|
||
lbto_docker("network", "create", "--label", label, network)
|
||
lbto_docker(
|
||
"run",
|
||
"-d",
|
||
"--name",
|
||
f"{network}-api",
|
||
"--label",
|
||
label,
|
||
"--network",
|
||
network,
|
||
"--network-alias",
|
||
"api",
|
||
"--no-healthcheck",
|
||
"-e",
|
||
f"STUB_SILENT_S={LBTO_SILENT_S}",
|
||
"-e",
|
||
f"STUB_LONG_S={LBTO_LONG_S}",
|
||
"--entrypoint",
|
||
"python",
|
||
image,
|
||
"-c",
|
||
LBTO_STUB,
|
||
)
|
||
lbto_docker(
|
||
"run",
|
||
"-d",
|
||
"--name",
|
||
f"{network}-lb",
|
||
"--label",
|
||
label,
|
||
"--network",
|
||
network,
|
||
"-e",
|
||
"API_PORT=8080",
|
||
"-p",
|
||
f"127.0.0.1:{port}:8080",
|
||
"--mount",
|
||
mount,
|
||
haproxy,
|
||
)
|
||
deadline = time.monotonic() + LBTO_READY_TIMEOUT_S
|
||
while True:
|
||
try:
|
||
status = lbto_request(port, "GET", "/health/ready", None)[0]
|
||
except OSError:
|
||
status = 0
|
||
if status == 200:
|
||
break
|
||
if time.monotonic() > deadline:
|
||
print(f"stub is not UP in LB after {LBTO_READY_TIMEOUT_S}s")
|
||
return 1
|
||
time.sleep(0.5)
|
||
return lbto_cases(port)
|
||
finally:
|
||
left = lbto_docker(
|
||
"ps",
|
||
"-aq",
|
||
"--filter",
|
||
f"label={label}",
|
||
check=False,
|
||
).split()
|
||
if left:
|
||
lbto_docker("rm", "-f", *left, check=False)
|
||
lbto_docker("network", "rm", network, check=False)
|
||
for signum, handler in previous.items():
|
||
signal.signal(signum, handler)
|
||
|
||
|
||
def lbto_free_port() -> int:
|
||
"""Свободный порт 127.0.0.1; сокет закрывается до публикации LB."""
|
||
with socket.socket() as sock:
|
||
sock.bind(("127.0.0.1", 0))
|
||
return sock.getsockname()[1]
|
||
|
||
|
||
def lbto_cases(port: int) -> int:
|
||
"""Случаи параллельно; таблица и код 1 при расхождении."""
|
||
body = b"\x89PNG\r\n\x1a\n" + bytes(LBTO_BODY_BYTES - 8)
|
||
upload = f"{LBTO_UPLOAD_PATH}?case="
|
||
# случай, вызов, статус, code ошибки LB (пусто — ответ заглушки) и
|
||
# границы времени ответа, с
|
||
cases = [
|
||
(
|
||
"upload: replica silent 12 s before body",
|
||
lambda: lbto_request(port, "POST", f"{upload}before-body", body),
|
||
202,
|
||
"",
|
||
(LBTO_SILENT_S - 0.5, LBTO_SILENT_S + 5),
|
||
),
|
||
(
|
||
"upload: replica silent 12 s after body",
|
||
lambda: lbto_request(port, "POST", f"{upload}after-body", body),
|
||
202,
|
||
"",
|
||
(LBTO_SILENT_S - 0.5, LBTO_SILENT_S + 5),
|
||
),
|
||
(
|
||
"other path: replica silent 12 s",
|
||
lambda: lbto_request(
|
||
port,
|
||
"GET",
|
||
"/api/v1/users/me?case=other-path",
|
||
None,
|
||
),
|
||
504,
|
||
"unavailable",
|
||
(9.5, 12),
|
||
),
|
||
(
|
||
"upload: replica silent 32 s",
|
||
lambda: lbto_request(port, "POST", f"{upload}too-long", body),
|
||
504,
|
||
"unavailable",
|
||
(29.5, 32),
|
||
),
|
||
(
|
||
"upload: client silent mid-body",
|
||
lambda: lbto_silent_client(port),
|
||
400,
|
||
"invalid_request",
|
||
(29, 33),
|
||
),
|
||
]
|
||
results: dict[int, object] = {}
|
||
|
||
def run_case(number: int, call: object) -> None:
|
||
try:
|
||
results[number] = call() # type: ignore[operator]
|
||
except Exception as e: # noqa: BLE001 — исход случая в таблицу
|
||
results[number] = e
|
||
|
||
threads = [
|
||
threading.Thread(target=run_case, args=(number, case[1]))
|
||
for number, case in enumerate(cases)
|
||
]
|
||
for thread in threads:
|
||
thread.start()
|
||
for thread in threads:
|
||
thread.join()
|
||
width = max(len(case[0]) for case in cases)
|
||
print(
|
||
f"{'case':<{width}} {'expected':<29} {'got':<24} {'time':>7}",
|
||
)
|
||
failed = 0
|
||
for number, (name, _, status, code, (low, high)) in enumerate(cases):
|
||
expected = f"{status} {code or 'replica'} {low:g}–{high:g} s"
|
||
outcome = results.get(number)
|
||
if isinstance(outcome, Exception):
|
||
got, elapsed, problem = type(outcome).__name__, None, "error"
|
||
else:
|
||
got_status, headers, data, elapsed = outcome # type: ignore[misc]
|
||
problem = ""
|
||
if got_status != status:
|
||
problem = f"status {got_status}"
|
||
elif code:
|
||
problem = lbto_error_ok(headers, data, code)
|
||
elif headers.get("x-instance-id") != "stub":
|
||
problem = "not the replica answer"
|
||
if not problem and not low <= elapsed <= high:
|
||
problem = f"time {elapsed:.2f} s"
|
||
source = (
|
||
"replica" if headers.get("x-instance-id") == "stub" else "LB"
|
||
)
|
||
got = f"{got_status} {source}"
|
||
if got_status >= 400 and source == "LB":
|
||
media = headers.get("content-type", "").split(";")[0]
|
||
got += f" {media or '-'}"
|
||
time_cell = "-" if elapsed is None else f"{elapsed:.2f} s"
|
||
verdict = "" if not problem else f" FAIL: {problem}"
|
||
failed += bool(problem)
|
||
print(
|
||
f"{name:<{width}} {expected:<29} {got:<24} {time_cell:>7}"
|
||
f"{verdict}",
|
||
)
|
||
if failed:
|
||
print(f"FAIL: {failed} case(s) differ")
|
||
return 1
|
||
print(
|
||
"PASS: the upload path waits 30 s for the replica, other paths 10 s, "
|
||
"LB errors are in the contract format",
|
||
)
|
||
return 0
|
||
|
||
|
||
# stop-at-start: записи журнала, по которым видны этапы старта и остановки
|
||
STARTED_SERVER = "Started server process"
|
||
SERVER_RUNNING = "Uvicorn running on"
|
||
EARLY_STOP = "Stopped API before startup"
|
||
UVICORN_STOP = ("Shutting down", "Stopped API", "Finished server process")
|
||
# имена событий без переменной части («... [1]», «... on http://...»)
|
||
EVENT_PREFIXES = (STARTED_SERVER, SERVER_RUNNING, "Finished server process")
|
||
STOP_LABEL = "mtusi.stop-at-start"
|
||
# docker stop стартующего контейнера — не дольше (спек graceful-shutdown)
|
||
STOP_LIMIT_S = 1.0
|
||
# срок docker stop — stop_grace_period сервиса api в compose; явно: без
|
||
# --timeout у контейнера docker run Docker Desktop 29 ждёт ~3 с, а не 10
|
||
STOP_GRACE_S = 10
|
||
# ожидание события die и строки старта сервера
|
||
ATTEMPT_TIMEOUT_S = 30
|
||
|
||
|
||
def event_name(event: str) -> str:
|
||
for prefix in EVENT_PREFIXES:
|
||
if event.startswith(prefix):
|
||
return prefix
|
||
return event
|
||
|
||
|
||
def log_time(value: str) -> float | None:
|
||
"""`timestamp` записи журнала (ISO 8601 UTC с `Z`) — секунды эпохи."""
|
||
try:
|
||
moment = datetime.strptime(value, "%Y-%m-%dT%H:%M:%S.%fZ")
|
||
except (TypeError, ValueError):
|
||
return None
|
||
return moment.replace(tzinfo=UTC).timestamp()
|
||
|
||
|
||
def docker_events(path: Path) -> list[tuple[float, str, str, str, str]]:
|
||
"""Строки потока событий: (время ВМ, действие, ID, сигнал, код)."""
|
||
rows = []
|
||
for line in path.read_text(encoding="utf-8").splitlines():
|
||
parts = line.split("|")
|
||
if len(parts) == 5 and parts[0].isdigit():
|
||
rows.append((int(parts[0]) / 1e9, *parts[1:]))
|
||
return rows
|
||
|
||
|
||
def cmd_stop_at_start(image: str, delays: list[float], server: int) -> int:
|
||
"""Сценарии спека `graceful-shutdown` «Остановка во время старта»
|
||
(решение 8 design change `fix-known-issues`).
|
||
|
||
Каждая попытка — свой контейнер образа с лимитами реплики `api`
|
||
(1 CPU / 512 МиБ без swap), без сети и без `config.toml`: приложение
|
||
стартует на дефолтах, соединения с хранилищами ленивые. `docker stop`
|
||
(срок 10 с, как `stop_grace_period`) — через паузу после `docker run`
|
||
или, у попыток `--server-start`, сразу по строке «Started server
|
||
process» (`docker logs -f`). Время — часы ВМ Docker: поток `docker
|
||
events` по метке (`start`, `kill` с сигналом 15, `die` с кодом) и
|
||
`timestamp` записей журнала. Проекты compose не трогаются, свои
|
||
контейнеры удаляются по метке при любом исходе."""
|
||
|
||
def interrupted(signum: int, _frame: object) -> None:
|
||
raise KeyboardInterrupt(signal.Signals(signum).name)
|
||
|
||
tag = uuid.uuid4().hex[:8]
|
||
label = f"{STOP_LABEL}={tag}"
|
||
events_path = Path(f"/tmp/mtusi-stop-at-start-{tag}.events")
|
||
image_id = subprocess.run(
|
||
["docker", "image", "inspect", "-f", "{{.Id}}", image],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
).stdout.strip()
|
||
if not image_id:
|
||
print(f"image {image} not found")
|
||
return 1
|
||
print(f"image {image} ({image_id[:19]}), label {label}")
|
||
with events_path.open("w") as out:
|
||
stream = subprocess.Popen(
|
||
[
|
||
"docker",
|
||
"events",
|
||
"--filter",
|
||
f"label={label}",
|
||
"--filter",
|
||
"type=container",
|
||
"--filter",
|
||
"event=start",
|
||
"--filter",
|
||
"event=kill",
|
||
"--filter",
|
||
"event=die",
|
||
"--format",
|
||
"{{.TimeNano}}|{{.Action}}|{{.Actor.ID}}|"
|
||
'{{index .Actor.Attributes "signal"}}|'
|
||
'{{index .Actor.Attributes "exitCode"}}',
|
||
],
|
||
stdout=out,
|
||
stderr=subprocess.DEVNULL,
|
||
)
|
||
# обработчики ставятся прямо перед try: вернуть их может только finally
|
||
previous = {
|
||
signum: signal.signal(signum, interrupted)
|
||
for signum in (signal.SIGTERM, signal.SIGHUP)
|
||
}
|
||
try:
|
||
# CLI подключается к демону до первого контейнера
|
||
time.sleep(1)
|
||
plan = [("delay", d) for d in delays] + [("server", 0.0)] * server
|
||
attempts = []
|
||
for number, (how, delay) in enumerate(plan, start=1):
|
||
attempts.append(
|
||
stop_attempt(
|
||
number,
|
||
image,
|
||
label,
|
||
f"mtusi-stop-at-start-{tag}-{number}",
|
||
events_path,
|
||
delay=delay if how == "delay" else None,
|
||
),
|
||
)
|
||
return stop_verdict(attempts)
|
||
finally:
|
||
stream.terminate()
|
||
stream.wait()
|
||
events_path.unlink(missing_ok=True)
|
||
left = subprocess.run(
|
||
["docker", "ps", "-aq", "--filter", f"label={label}"],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
).stdout.split()
|
||
if left:
|
||
subprocess.run(
|
||
["docker", "rm", "-f", *left],
|
||
capture_output=True,
|
||
check=False,
|
||
)
|
||
for signum, handler in previous.items():
|
||
signal.signal(signum, handler)
|
||
|
||
|
||
def stop_attempt(
|
||
number: int,
|
||
image: str,
|
||
label: str,
|
||
name: str,
|
||
events_path: Path,
|
||
*,
|
||
delay: float | None,
|
||
) -> dict[str, object]:
|
||
"""Одна попытка: контейнер, `docker stop`, события и журнал."""
|
||
run = subprocess.run(
|
||
[
|
||
"docker",
|
||
"run",
|
||
"-d",
|
||
"--network",
|
||
"none",
|
||
"--cpus",
|
||
"1",
|
||
"--memory",
|
||
"512m",
|
||
"--memory-swap",
|
||
"512m",
|
||
"--label",
|
||
label,
|
||
"--name",
|
||
name,
|
||
image,
|
||
],
|
||
capture_output=True,
|
||
text=True,
|
||
check=True,
|
||
)
|
||
container = run.stdout.strip()
|
||
if delay is not None:
|
||
time.sleep(delay)
|
||
else:
|
||
follow = subprocess.Popen(
|
||
["docker", "logs", "-f", container],
|
||
stdout=subprocess.PIPE,
|
||
stderr=subprocess.STDOUT,
|
||
text=True,
|
||
)
|
||
timer = threading.Timer(ATTEMPT_TIMEOUT_S, follow.kill)
|
||
timer.start()
|
||
try:
|
||
for line in follow.stdout or []:
|
||
if STARTED_SERVER in line:
|
||
break
|
||
except BaseException:
|
||
# Ctrl+C или SIGTERM посреди чтения: docker logs -f не ждёт
|
||
# уборки контейнера по метке
|
||
follow.kill()
|
||
follow.wait()
|
||
raise
|
||
finally:
|
||
timer.cancel()
|
||
began = time.monotonic()
|
||
subprocess.run(
|
||
["docker", "stop", "--timeout", str(STOP_GRACE_S), container],
|
||
capture_output=True,
|
||
)
|
||
stop_s = time.monotonic() - began
|
||
if delay is None:
|
||
follow.kill()
|
||
follow.wait()
|
||
deadline = time.monotonic() + ATTEMPT_TIMEOUT_S
|
||
mine: list[tuple[float, str, str, str, str]] = []
|
||
while time.monotonic() < deadline:
|
||
mine = [e for e in docker_events(events_path) if e[2] == container]
|
||
if any(e[1] == "die" for e in mine):
|
||
break
|
||
time.sleep(0.2)
|
||
start = next((e[0] for e in mine if e[1] == "start"), None)
|
||
kill = next(
|
||
(e[0] for e in mine if e[1] == "kill" and e[3] == "15"),
|
||
None,
|
||
)
|
||
die = next((e for e in mine if e[1] == "die"), None)
|
||
logs = subprocess.run(
|
||
["docker", "logs", container],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
records = []
|
||
for line in (logs.stdout + logs.stderr).splitlines():
|
||
try:
|
||
record = json.loads(line)
|
||
except json.JSONDecodeError:
|
||
continue
|
||
if isinstance(record, dict) and isinstance(record.get("event"), str):
|
||
records.append(record)
|
||
names = [event_name(r["event"]) for r in records]
|
||
started_at = next(
|
||
(
|
||
log_time(r.get("timestamp"))
|
||
for r in records
|
||
if event_name(r["event"]) == STARTED_SERVER
|
||
),
|
||
None,
|
||
)
|
||
running_at = next(
|
||
(
|
||
log_time(r.get("timestamp"))
|
||
for r in records
|
||
if event_name(r["event"]) == SERVER_RUNNING
|
||
),
|
||
None,
|
||
)
|
||
if kill is None or started_at is None or kill < started_at:
|
||
kind = "import"
|
||
elif running_at is None or kill < running_at:
|
||
kind = "server-start"
|
||
else:
|
||
kind = "running"
|
||
early = [r for r in records if r["event"] == EARLY_STOP]
|
||
if early:
|
||
by = "early"
|
||
elif all(stage in names for stage in UVICORN_STOP):
|
||
by = "uvicorn"
|
||
else:
|
||
by = "none"
|
||
# запись ранней остановки — JSON с полями записей structlog
|
||
early_ok = all(
|
||
r.get("level") == "info"
|
||
and r.get("signal") == "SIGTERM"
|
||
and log_time(r.get("timestamp")) is not None
|
||
and r.get("instance_id")
|
||
for r in early
|
||
)
|
||
code = int(die[4]) if die is not None and die[4].isdigit() else None
|
||
result = {
|
||
"number": number,
|
||
"how": f"pause {delay:g} s" if delay is not None else "server-start",
|
||
"signal_after": None
|
||
if kill is None or start is None
|
||
else kill - start,
|
||
"stop_s": stop_s,
|
||
"exit_after": None if kill is None or die is None else die[0] - kill,
|
||
"code": code,
|
||
"kind": kind,
|
||
"by": by,
|
||
"early_ok": early_ok,
|
||
"events": names,
|
||
"instance": records[0].get("instance_id") if records else None,
|
||
}
|
||
|
||
def seconds(value: object) -> str:
|
||
return "-" if value is None else f"{value:.3f} s"
|
||
|
||
print(
|
||
f"#{number} {result['how']}: signal after "
|
||
f"{seconds(result['signal_after'])}, docker stop {stop_s:.3f} s, "
|
||
f"exit after signal {seconds(result['exit_after'])}, exit code "
|
||
f"{code}, {kind}, stopped by {by}",
|
||
flush=True,
|
||
)
|
||
print(f" log: {' → '.join(names) or '(empty)'}", flush=True)
|
||
return result
|
||
|
||
|
||
def stop_verdict(attempts: list[dict[str, object]]) -> int:
|
||
"""PASS (код 0) по решению 8 design change `fix-known-issues`."""
|
||
problems = []
|
||
for a in attempts:
|
||
n = a["number"]
|
||
if a["code"] != 0:
|
||
problems.append(f"#{n}: exit code {a['code']}")
|
||
if float(a["stop_s"]) > STOP_LIMIT_S:
|
||
problems.append(f"#{n}: docker stop took {a['stop_s']:.1f} s")
|
||
if a["kind"] == "import":
|
||
# окно config.load(): сигнал до первой строки uvicorn, но уже
|
||
# под его обработчиками — штатная остановка тоже верна
|
||
if a["by"] == "early":
|
||
if STARTED_SERVER in a["events"]:
|
||
problems.append(f"#{n}: server start after early stop")
|
||
if not a["early_ok"]:
|
||
problems.append(f"#{n}: malformed early stop record")
|
||
elif a["by"] != "uvicorn":
|
||
problems.append(f"#{n}: import, nobody stopped the process")
|
||
elif a["by"] != "uvicorn":
|
||
problems.append(f"#{n}: {a['kind']}, stopped by {a['by']}")
|
||
kinds = Counter(str(a["kind"]) for a in attempts)
|
||
if not any(a["kind"] == "import" and a["by"] == "early" for a in attempts):
|
||
problems.append("no import attempt stopped early")
|
||
if not kinds["running"]:
|
||
problems.append("no running attempt")
|
||
print(
|
||
f"attempts: import {kinds['import']}, server-start "
|
||
f"{kinds['server-start']}, running {kinds['running']}",
|
||
)
|
||
if problems:
|
||
print("FAIL: " + "; ".join(problems))
|
||
return 1
|
||
print("PASS: SIGTERM during start stops the replica at once, exit 0")
|
||
return 0
|
||
|
||
|
||
# s3-idle (change fix-upload-put-flake, design, решение 4): проба клиента
|
||
# S3 в реплике стенда. Объекты — под этим префиксом базы: сверка читает
|
||
# только `<база>/attachments/`, проба его не трогает
|
||
S3_IDLE_PREFIX = ".s3-idle-probe"
|
||
S3_IDLE_FILE = re.compile(r"^(source|r\d+-p\d+)$")
|
||
S3_IDLE_TIMEOUT_S = 900
|
||
# проба: код и ключи образа, процесс отдельный — пул API она не трогает.
|
||
# Счётчики пула — закрытые поля aiohttp (`_conns`, `_read_timeout_handle`,
|
||
# `_exception`): диагностика, а не код приложения; нет полей — «n/a».
|
||
# Строки без поля `type` — журнал клиента S3 (structlog в stdout)
|
||
S3_IDLE_PROBE_PY = r"""
|
||
import asyncio
|
||
import hashlib
|
||
import io
|
||
import json
|
||
import os
|
||
import sys
|
||
import time
|
||
import uuid
|
||
|
||
import aiohttp
|
||
|
||
import src.infra.s3.client as client_module
|
||
from src.config import settings
|
||
from src.core.exceptions import ObjectStorageUnavailable
|
||
from src.infra.s3.client import ObjectStorage
|
||
|
||
try:
|
||
import uvloop
|
||
except ImportError:
|
||
uvloop = None
|
||
|
||
ROUNDS, DOWNLOADS, PUTS, SIZE, PUT_SIZE = (int(v) for v in sys.argv[1:6])
|
||
PAUSE_S = float(sys.argv[6])
|
||
VARIANTS = sys.argv[7].split(",")
|
||
S3 = settings.s3
|
||
NAMESPACE = settings.database.name
|
||
BASE = f"{NAMESPACE}/.s3-idle-probe/{uuid.uuid4().hex}"
|
||
IDLE_S = S3.timeout_seconds + 0.5
|
||
TYPE = "application/octet-stream"
|
||
NA = "n/a"
|
||
|
||
|
||
def emit(**fields):
|
||
print(json.dumps(fields), flush=True)
|
||
|
||
|
||
def pool_state(storage):
|
||
# соединения в пуле aiohttp: всего, со взведённым сроком чтения и с
|
||
# сохранённым исключением (испорченные)
|
||
try:
|
||
sessions = storage._client._endpoint.http_session._sessions
|
||
protos = [
|
||
proto
|
||
for session in sessions.values()
|
||
for conns in session.connector._conns.values()
|
||
for proto, _ in conns
|
||
]
|
||
except AttributeError:
|
||
return {"pooled": NA, "armed": NA, "broken": NA}
|
||
if not all(
|
||
hasattr(p, "_read_timeout_handle") and hasattr(p, "_exception")
|
||
for p in protos
|
||
):
|
||
return {"pooled": len(protos), "armed": NA, "broken": NA}
|
||
return {
|
||
"pooled": len(protos),
|
||
"armed": sum(p._read_timeout_handle is not None for p in protos),
|
||
"broken": sum(p._exception is not None for p in protos),
|
||
}
|
||
|
||
|
||
def chain(error):
|
||
names, last, seen = [], error, set()
|
||
while error is not None and id(error) not in seen:
|
||
seen.add(id(error))
|
||
names.append(type(error).__name__)
|
||
last = error
|
||
error = error.__cause__ or error.__context__
|
||
return names, str(last)[:80]
|
||
|
||
|
||
async def make(variant):
|
||
# эталон — прежний срок чтения aiohttp: read_timeout = [s3] timeout
|
||
storage = ObjectStorage(S3, namespace=NAMESPACE)
|
||
original = client_module.AioConfig
|
||
if variant == "reference":
|
||
|
||
def config(**kwargs):
|
||
kwargs["read_timeout"] = S3.timeout_seconds
|
||
return original(**kwargs)
|
||
|
||
client_module.AioConfig = config
|
||
try:
|
||
await storage.start()
|
||
finally:
|
||
client_module.AioConfig = original
|
||
return storage
|
||
|
||
|
||
async def download(storage, key):
|
||
digest, size = hashlib.sha256(), 0
|
||
async with storage.open(key) as stored:
|
||
async for chunk in stored.iter_chunks():
|
||
digest.update(chunk)
|
||
size += len(chunk)
|
||
await asyncio.sleep(PAUSE_S)
|
||
return size, digest.hexdigest()
|
||
|
||
|
||
async def run_variant(variant, written):
|
||
storage = await make(variant)
|
||
emit(
|
||
type="variant",
|
||
variant=variant,
|
||
read_timeout=storage._client.meta.config.read_timeout,
|
||
)
|
||
try:
|
||
data = os.urandom(SIZE)
|
||
source = f"{BASE}/{variant}/source"
|
||
written.append(source)
|
||
await storage.put(
|
||
source,
|
||
io.BytesIO(data),
|
||
size=SIZE,
|
||
content_type=TYPE,
|
||
)
|
||
expected = (SIZE, hashlib.sha256(data).hexdigest())
|
||
stored = []
|
||
for number in range(1, ROUNDS + 1):
|
||
results = await asyncio.gather(
|
||
*(download(storage, source) for _ in range(DOWNLOADS)),
|
||
return_exceptions=True,
|
||
)
|
||
after_downloads = pool_state(storage)
|
||
await asyncio.sleep(IDLE_S)
|
||
after_idle = pool_state(storage)
|
||
ok, failures = 0, []
|
||
for index in range(1, PUTS + 1):
|
||
body = os.urandom(PUT_SIZE)
|
||
key = f"{BASE}/{variant}/r{number}-p{index}"
|
||
written.append(key)
|
||
started = time.monotonic()
|
||
try:
|
||
await storage.put(
|
||
key,
|
||
io.BytesIO(body),
|
||
size=PUT_SIZE,
|
||
content_type=TYPE,
|
||
)
|
||
except ObjectStorageUnavailable as error:
|
||
names, message = chain(error)
|
||
failures.append({
|
||
"put": index,
|
||
"ms": round((time.monotonic() - started) * 1000, 1),
|
||
"chain": names,
|
||
"message": message,
|
||
})
|
||
else:
|
||
ok += 1
|
||
stored.append((key, hashlib.sha256(body).hexdigest()))
|
||
emit(
|
||
type="round",
|
||
variant=variant,
|
||
round=number,
|
||
downloads_ok=sum(r == expected for r in results),
|
||
armed=after_downloads["armed"],
|
||
pooled=after_downloads["pooled"],
|
||
broken=after_idle["broken"],
|
||
pooled_idle=after_idle["pooled"],
|
||
puts_ok=ok,
|
||
failures=failures,
|
||
)
|
||
intact = 0
|
||
for key, digest in stored:
|
||
try:
|
||
async with storage.open(key) as obj:
|
||
body = await obj.read()
|
||
except ObjectStorageUnavailable:
|
||
continue
|
||
intact += len(body) == PUT_SIZE and (
|
||
hashlib.sha256(body).hexdigest() == digest
|
||
)
|
||
emit(
|
||
type="readback",
|
||
variant=variant,
|
||
written=len(stored),
|
||
intact=intact,
|
||
)
|
||
finally:
|
||
await storage.aclose()
|
||
|
||
|
||
async def main():
|
||
written = []
|
||
try:
|
||
for variant in VARIANTS:
|
||
await run_variant(variant, written)
|
||
finally:
|
||
# свой клиент без скачиваний: в его пуле нечему испортиться
|
||
cleaner = await make("image")
|
||
removed = 0
|
||
for key in written:
|
||
try:
|
||
await cleaner.delete(key)
|
||
removed += 1
|
||
except ObjectStorageUnavailable:
|
||
pass
|
||
await cleaner.aclose()
|
||
emit(type="cleanup", written=len(written), removed=removed)
|
||
|
||
|
||
emit(
|
||
type="start",
|
||
loop="uvloop" if uvloop else "asyncio",
|
||
aiohttp=aiohttp.__version__,
|
||
timeout=S3.timeout_seconds,
|
||
idle=IDLE_S,
|
||
database=NAMESPACE,
|
||
)
|
||
if uvloop:
|
||
uvloop.run(main())
|
||
else:
|
||
asyncio.run(main())
|
||
"""
|
||
|
||
|
||
def s3_idle_leftovers(bucket: str, database: str) -> int | None:
|
||
"""Файлы пробы под `<база>/.s3-idle-probe/` по `fs.tree` (каталоги
|
||
SeaweedFS убирает позже файлов); `None` — дерево не прочитано."""
|
||
try:
|
||
tree = weed_shell(
|
||
f"fs.tree /buckets/{bucket}/{database}/{S3_IDLE_PREFIX}",
|
||
)
|
||
except RuntimeError:
|
||
return None
|
||
return sum(
|
||
1
|
||
for line in tree.splitlines()
|
||
if (match := UC_TREE_LINE.match(line))
|
||
and S3_IDLE_FILE.match(match.group(2))
|
||
)
|
||
|
||
|
||
def cmd_s3_idle(
|
||
port: int,
|
||
*,
|
||
rounds: int,
|
||
downloads: int,
|
||
puts: int,
|
||
size_mib: int,
|
||
pause_ms: float,
|
||
) -> int:
|
||
"""Спек `object-storage`, «Вызов после простоя», и `attachments`,
|
||
«Загрузка после простоя S3» (design change `fix-upload-put-flake`,
|
||
решение 4): проба клиента S3 в работающей реплике стенда — вариант
|
||
образа и эталон с прежним сроком чтения aiohttp. Раунд — одновременные
|
||
медленные скачивания объекта, простой `[s3] timeout_seconds + 0,5` с,
|
||
PUT по одному; каждый записанный объект читается обратно. Код 0 — у
|
||
варианта образа ни одного испорченного соединения и упавшего PUT, 1 —
|
||
иначе (эталон может падать: так видно механизм), 2 — нет стенда."""
|
||
if no_lb(port):
|
||
return 2
|
||
stand = rc_stand()
|
||
try:
|
||
replicas = compose("ps", "-q", "--status", "running", "api").split()
|
||
except RuntimeError as e:
|
||
print(f"FAIL: docker compose ps: {e}")
|
||
return 2
|
||
if stand is None or not replicas:
|
||
print("FAIL: no running api replica of the stand")
|
||
return 2
|
||
bucket, database = stand
|
||
replica = replicas[0]
|
||
name = (
|
||
subprocess.run(
|
||
["docker", "inspect", "-f", "{{.Name}}", replica],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
.stdout.strip()
|
||
.lstrip("/")
|
||
)
|
||
args = [
|
||
str(rounds),
|
||
str(downloads),
|
||
str(puts),
|
||
str(size_mib * 1024 * 1024),
|
||
str(128 * 1024),
|
||
str(pause_ms / 1000),
|
||
"image,reference",
|
||
]
|
||
proc = subprocess.run(
|
||
["docker", "exec", "-i", replica, "python", "-", *args],
|
||
input=S3_IDLE_PROBE_PY,
|
||
capture_output=True,
|
||
text=True,
|
||
timeout=S3_IDLE_TIMEOUT_S,
|
||
check=False,
|
||
)
|
||
records: list[dict[str, object]] = []
|
||
storage_warnings = 0
|
||
for line in proc.stdout.splitlines():
|
||
try:
|
||
record = json.loads(line)
|
||
except json.JSONDecodeError:
|
||
continue
|
||
if "type" in record:
|
||
records.append(record)
|
||
elif record.get("event") == "Object storage is unavailable":
|
||
storage_warnings += 1
|
||
by_type: dict[str, list[dict[str, object]]] = {}
|
||
for record in records:
|
||
by_type.setdefault(str(record["type"]), []).append(record)
|
||
if proc.returncode != 0 or "start" not in by_type:
|
||
print(f"FAIL: probe exited {proc.returncode}")
|
||
print(proc.stderr[-2000:])
|
||
return 1
|
||
start = by_type["start"][0]
|
||
print(
|
||
f"s3-idle: replica {name}, loop {start['loop']}, aiohttp "
|
||
f"{start['aiohttp']}, [s3] timeout_seconds {start['timeout']} s, "
|
||
f"database {start['database']}",
|
||
)
|
||
print(
|
||
f"round: {downloads} concurrent downloads of {size_mib} MiB "
|
||
f"({pause_ms} ms pause per 64 KiB block) -> idle {start['idle']} s "
|
||
f"-> {puts} PUT of 128 KiB one by one; {rounds} rounds per variant",
|
||
)
|
||
timeouts = {
|
||
str(r["variant"]): r["read_timeout"]
|
||
for r in by_type.get("variant", [])
|
||
}
|
||
header = (
|
||
f"{'variant':<10} {'read_timeout':>12} {'round':>5} "
|
||
f"{'downloads':>9} {'armed/pool':>10} {'broken/pool':>11} "
|
||
f"{'PUT ok':>6} {'PUT fail':>8}"
|
||
)
|
||
print(header)
|
||
totals: dict[str, Counter[str]] = {}
|
||
failures: list[str] = []
|
||
for r in by_type.get("round", []):
|
||
variant = str(r["variant"])
|
||
total = totals.setdefault(variant, Counter())
|
||
failed: list[dict[str, object]] = list(r["failures"])
|
||
for key in ("armed", "broken"):
|
||
value = r[key]
|
||
if isinstance(value, int):
|
||
total[key] += value
|
||
else:
|
||
total[f"{key}_na"] += 1
|
||
total["downloads_bad"] += downloads - int(str(r["downloads_ok"]))
|
||
total["puts_failed"] += len(failed)
|
||
print(
|
||
f"{variant:<10} {timeouts.get(variant)!s:>12} {r['round']!s:>5} "
|
||
f"{r['downloads_ok']!s:>6}/{downloads:<2} "
|
||
f"{r['armed']!s:>5}/{r['pooled']!s:<4} "
|
||
f"{r['broken']!s:>6}/{r['pooled_idle']!s:<4} "
|
||
f"{r['puts_ok']!s:>6} {len(failed):>8}",
|
||
)
|
||
for item in failed:
|
||
causes = " <- ".join(str(name) for name in list(item["chain"]))
|
||
failures.append(
|
||
f" {variant} round {r['round']} PUT {item['put']}: "
|
||
f"{item['ms']} ms, {causes}: {item['message']}",
|
||
)
|
||
if failures:
|
||
print("failed PUT (error and its causes):")
|
||
print("\n".join(failures))
|
||
print(
|
||
f"'Object storage is unavailable' records of the probe: {storage_warnings}",
|
||
)
|
||
readback = {str(r["variant"]): r for r in by_type.get("readback", [])}
|
||
for variant, total in totals.items():
|
||
back = readback.get(variant, {})
|
||
na = " (pool counters n/a)" if total["broken_na"] else ""
|
||
print(
|
||
f"{variant}: armed {total['armed']}, broken {total['broken']}"
|
||
f"{na}, PUT failed {total['puts_failed']}, bad downloads "
|
||
f"{total['downloads_bad']}, read back {back.get('intact')}/"
|
||
f"{back.get('written')} with the same size and SHA-256",
|
||
)
|
||
cleanup = (by_type.get("cleanup") or [{}])[0]
|
||
leftovers = s3_idle_leftovers(bucket, database)
|
||
print(
|
||
f"cleanup: deleted {cleanup.get('removed')}/{cleanup.get('written')} "
|
||
f"objects; files left under {database}/{S3_IDLE_PREFIX}/: "
|
||
f"{'unknown' if leftovers is None else leftovers}",
|
||
)
|
||
image = totals.get("image", Counter())
|
||
image_back = readback.get("image", {})
|
||
problems = []
|
||
if image["broken"]:
|
||
problems.append(f"image variant: {image['broken']} broken connections")
|
||
if image["puts_failed"]:
|
||
problems.append(f"image variant: {image['puts_failed']} PUT failed")
|
||
if image["downloads_bad"]:
|
||
problems.append(
|
||
f"image variant: {image['downloads_bad']} bad downloads",
|
||
)
|
||
if image_back.get("intact") != image_back.get("written"):
|
||
problems.append("image variant: objects read back differ")
|
||
if len(by_type.get("round", [])) != 2 * rounds:
|
||
problems.append("probe did not finish every round")
|
||
if leftovers != 0:
|
||
problems.append("probe objects left in the bucket")
|
||
if problems:
|
||
print("FAIL: " + "; ".join(problems))
|
||
return 1
|
||
print(
|
||
"PASS: image client keeps no read timer in the pool; every PUT after "
|
||
"the idle passed",
|
||
)
|
||
return 0
|
||
|
||
|
||
# defense-scenario, broker-check, worker-process (design change
|
||
# async-attachments, решение 17), defense-faults, relay-process, pipeline-state
|
||
# (pipeline-reliability, решения 8, 14, 17). Сервисы worker и relay и брокер
|
||
# останавливаются на рабочем стенде, поэтому возврат — при любом исходе
|
||
INTERRUPTED_EXIT = 130
|
||
RESTORE_SIGNALS = (signal.SIGINT, signal.SIGTERM, signal.SIGHUP)
|
||
# scripts/restart.sh: ~35 с, на шумном хосте дольше
|
||
RESTART_WAIT_S = 180
|
||
LB_READY_WAIT_S = 60
|
||
# сервис считается запущенным, если столько проверок подряд видят его живым:
|
||
# прерванный docker compose stop ещё может его погасить
|
||
SERVICE_STABLE_CHECKS = 3
|
||
SERVICE_RESTORE_WAIT_S = 60
|
||
# опрос очереди и записей: relay публикует за проход (0,25 с)
|
||
QUEUE_WAIT_S = 20
|
||
QUEUE_POLL_S = 0.3
|
||
# очередь заданий: имя базы + суффикс (src/infra/broker)
|
||
QUEUE_SUFFIX = ".attachment.process.v1"
|
||
BROKER_IMAGE = re.compile(r"^rabbitmq:\d+\.\d+\.\d+@sha256:[0-9a-f]{64}$")
|
||
BROKER_MEMORY_LIMIT = 512 * 1024 * 1024
|
||
# срок остановки брокера: stop_grace_period в docker-compose.yml
|
||
BROKER_STOP_GRACE_S = 20
|
||
BROKER_CONSUMER_WAIT_S = 30
|
||
BROKER_START_WAIT_S = 120
|
||
# где есть пароль брокера: сервер и его клиенты (design change
|
||
# pipeline-reliability, решение 1)
|
||
BROKER_PASSWORD_ENV = ("RABBITMQ_DEFAULT_PASS", "BROKER__PASSWORD")
|
||
BROKER_HOLDERS = "rabbitmq,relay,worker"
|
||
# спек container-run и service-configuration: лимиты и значения по умолчанию
|
||
PROCESS_STOP_LIMIT_S = 10
|
||
PROCESS_LOG_WAIT_S = 30
|
||
# docker stop на старте: паузы после docker run, пока процесс импортирует
|
||
# приложение. Остановленный позже уже не «before startup» — следующая пауза
|
||
PROCESS_EARLY_DELAYS = (0.3, 0.2, 0.4)
|
||
PROCESS_EARLY_STOP_LIMIT_S = 1.0
|
||
PROCESS_EARLY_LABEL = "mtusi.process-check"
|
||
# остановка под нагрузкой (design change pipeline-reliability, решение 19): 8 +
|
||
# 0,5 × 3. Два файла — конкуренция worker
|
||
PROCESS_STOP_BOUND_S = 9.5
|
||
LOAD_FILES = 2
|
||
LOAD_FROZEN = ("postgres", "rabbitmq")
|
||
LOAD_TAKEN_WAIT_S = 30
|
||
LOAD_RENDER_SETTLE_S = 1
|
||
# аренда 70 с, затем по паре файлов: 15 с CPU на файл при конкуренции 2 — 30 с
|
||
LOAD_FINISH_WAIT_S = 200
|
||
EXPENSIVE_JPEG_PY = """\
|
||
import sys
|
||
sys.path.insert(0, "/tmp")
|
||
import images
|
||
sys.stdout.buffer.write(images.jpeg_scan_bomb())
|
||
"""
|
||
|
||
|
||
class ProcessSpec(NamedTuple):
|
||
"""Что проверяют `worker-process` и `relay-process` (спеки `container-run`,
|
||
`graceful-shutdown`, `service-configuration`)."""
|
||
|
||
# сервис compose, он же модуль `src.<service>` и имя в записях журнала
|
||
service: str
|
||
limits: dict[str, int]
|
||
defaults: dict[str, float]
|
||
# значения записи о старте, которые просто печатаются
|
||
other_fields: tuple[str, ...]
|
||
# (переменная, значение, поле в ошибке)
|
||
bad_settings: tuple[tuple[str, str, str], ...]
|
||
# (переменная, значение, поле записи о старте, значение в записи)
|
||
overrides: tuple[tuple[str, str, str, str], ...]
|
||
# начала имён переменных, которых нет в окружении контейнера
|
||
absent_env: tuple[str, ...] = ()
|
||
|
||
|
||
WORKER_SPEC = ProcessSpec(
|
||
service="worker",
|
||
limits={"NanoCpus": 1_000_000_000, "Memory": 1024 * 1024 * 1024},
|
||
defaults={
|
||
"concurrency": 2,
|
||
"prefetch": 2,
|
||
"max_attempts": 5,
|
||
"job_timeout_seconds": 60,
|
||
"lease_margin_seconds": 10,
|
||
"retry_base_delay_seconds": 5,
|
||
"retry_max_delay_seconds": 300,
|
||
"render_timeout_seconds": 40,
|
||
"render_cpu_limit_seconds": 15,
|
||
"render_memory_limit_mib": 450,
|
||
"graceful_shutdown_seconds": 8,
|
||
"reconnect_seconds": 2,
|
||
},
|
||
other_fields=(
|
||
"broker_host",
|
||
"broker_port",
|
||
"broker_queue",
|
||
"s3_host",
|
||
"s3_port",
|
||
"s3_bucket",
|
||
"database_host",
|
||
"database_port",
|
||
"database_name",
|
||
"database_pool_size",
|
||
),
|
||
bad_settings=(
|
||
("WORKER__CONCURRENCY", "0", "worker.concurrency"),
|
||
("WORKER__PREFETCH", "0", "worker.prefetch"),
|
||
("WORKER__MAX_ATTEMPTS", "abc", "worker.max_attempts"),
|
||
(
|
||
"WORKER__GRACEFUL_SHUTDOWN_SECONDS",
|
||
"9",
|
||
"worker.graceful_shutdown_seconds",
|
||
),
|
||
(
|
||
"WORKER__RENDER_MEMORY_LIMIT_MIB",
|
||
"0",
|
||
"worker.render_memory_limit_mib",
|
||
),
|
||
(
|
||
"WORKER__RENDER_TIMEOUT_SECONDS",
|
||
"120",
|
||
"worker.render_timeout_seconds",
|
||
),
|
||
),
|
||
overrides=(
|
||
("WORKER__CONCURRENCY", "3", "concurrency", "3"),
|
||
("WORKER__RECONNECT_SECONDS", "1", "reconnect_seconds", "1.0"),
|
||
),
|
||
)
|
||
RELAY_SPEC = ProcessSpec(
|
||
service="relay",
|
||
limits={"NanoCpus": 250_000_000, "Memory": 256 * 1024 * 1024},
|
||
defaults={
|
||
"poll_interval_seconds": 0.25,
|
||
"batch_size": 100,
|
||
"max_published_backlog": 1000,
|
||
"republish_after_seconds": 300,
|
||
"failure_pause_seconds": 2,
|
||
},
|
||
other_fields=(
|
||
"broker_host",
|
||
"broker_port",
|
||
"broker_queue",
|
||
"broker_publish_timeout_seconds",
|
||
"database_host",
|
||
"database_port",
|
||
"database_name",
|
||
"database_pool_size",
|
||
),
|
||
bad_settings=(
|
||
("RELAY__BATCH_SIZE", "0", "relay.batch_size"),
|
||
("RELAY__MAX_PUBLISHED_BACKLOG", "-1", "relay.max_published_backlog"),
|
||
("RELAY__POLL_INTERVAL_SECONDS", "abc", "relay.poll_interval_seconds"),
|
||
),
|
||
overrides=(
|
||
("RELAY__BATCH_SIZE", "7", "batch_size", "7"),
|
||
("RELAY__POLL_INTERVAL_SECONDS", "1", "poll_interval_seconds", "1.0"),
|
||
),
|
||
absent_env=("S3__", "S3_", "CACHE__", "VALKEY"),
|
||
)
|
||
|
||
|
||
@contextlib.contextmanager
|
||
def signals_ignored():
|
||
"""Возврат стенда не прерывается вторым сигналом."""
|
||
saved = {
|
||
sig: signal.signal(sig, signal.SIG_IGN) for sig in RESTORE_SIGNALS
|
||
}
|
||
try:
|
||
yield
|
||
finally:
|
||
for sig, handler in saved.items():
|
||
signal.signal(sig, handler)
|
||
|
||
|
||
def detached(*args: str, timeout: float | None = None) -> tuple[int, str]:
|
||
"""Команда в своей сессии: Ctrl+C терминала её не прерывает. Код и
|
||
вывод; в выводе секретов нет у команд compose без `config`."""
|
||
proc = subprocess.run(
|
||
list(args),
|
||
cwd=ROOT,
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
start_new_session=True,
|
||
timeout=timeout,
|
||
)
|
||
return proc.returncode, proc.stdout + proc.stderr
|
||
|
||
|
||
def service_containers(service: str) -> list[dict[str, object]]:
|
||
"""`docker inspect` работающих контейнеров сервиса. Там есть окружение
|
||
с секретами: печатать только отдельные поля."""
|
||
ids = compose("ps", "-q", "--status", "running", service).split()
|
||
if not ids:
|
||
return []
|
||
return json.loads(
|
||
subprocess.run(
|
||
["docker", "inspect", *ids],
|
||
capture_output=True,
|
||
text=True,
|
||
check=True,
|
||
).stdout,
|
||
)
|
||
|
||
|
||
def container_starts(*services: str) -> dict[str, str]:
|
||
"""Имя контейнера → `StartedAt` работающих контейнеров сервисов."""
|
||
return {
|
||
str(item["Name"]).lstrip("/"): str(item["State"]["StartedAt"])
|
||
for service in services
|
||
for item in service_containers(service)
|
||
}
|
||
|
||
|
||
def json_records(text: str) -> list[dict[str, object]]:
|
||
"""Записи журнала: строки JSON среди прочего вывода."""
|
||
records = []
|
||
for line in text.splitlines():
|
||
if line.startswith("{"):
|
||
with contextlib.suppress(json.JSONDecodeError):
|
||
records.append(json.loads(line))
|
||
return records
|
||
|
||
|
||
def broker_queues(
|
||
timeout: float | None = None,
|
||
) -> dict[str, dict[str, object]]:
|
||
"""Очереди брокера: имя → durable, messages, готовые, неподтверждённые,
|
||
consumers."""
|
||
out = compose(
|
||
"exec",
|
||
"-T",
|
||
"rabbitmq",
|
||
"rabbitmqctl",
|
||
"-q",
|
||
"list_queues",
|
||
"name",
|
||
"durable",
|
||
"messages",
|
||
"messages_ready",
|
||
"messages_unacknowledged",
|
||
"consumers",
|
||
"--formatter",
|
||
"json",
|
||
timeout=timeout,
|
||
)
|
||
return {str(item["name"]): item for item in json.loads(out or "[]")}
|
||
|
||
|
||
def queue_messages(queue: str) -> int:
|
||
"""Сообщений в очереди, в том числе неподтверждённых; очереди нет — 0."""
|
||
return int(str(broker_queues().get(queue, {}).get("messages", 0)))
|
||
|
||
|
||
def wait_queue_messages(
|
||
queue: str,
|
||
*,
|
||
at_least: int = 0,
|
||
exactly: int | None = None,
|
||
timeout: float = QUEUE_WAIT_S,
|
||
) -> int:
|
||
"""Опрос очереди: сообщения публикует relay. Столько сообщений есть —
|
||
вернуть их число; срок вышел — последнее увиденное."""
|
||
deadline = time.monotonic() + timeout
|
||
while True:
|
||
count = queue_messages(queue)
|
||
if count == exactly if exactly is not None else count >= at_least:
|
||
return count
|
||
if time.monotonic() >= deadline:
|
||
return count
|
||
time.sleep(QUEUE_POLL_S)
|
||
|
||
|
||
def wait_lb_ready(port: int) -> bool:
|
||
deadline = time.monotonic() + LB_READY_WAIT_S
|
||
while time.monotonic() < deadline:
|
||
if is_ready(port):
|
||
return True
|
||
time.sleep(0.5)
|
||
return False
|
||
|
||
|
||
def stand_answers(port: int, command: str) -> bool:
|
||
"""Стенд отвечает на порту: иначе команде нечего проверять."""
|
||
if no_lb(port):
|
||
print(f"{command} needs the stand with the load balancer")
|
||
return False
|
||
if not is_ready(port):
|
||
print(f"{command}: no stand on port {port}, use --port <LB>")
|
||
return False
|
||
return True
|
||
|
||
|
||
def service_ids(service: str, *, running: bool = True) -> list[str]:
|
||
"""`id` контейнеров сервиса: работающих или всех. Предупреждения compose в
|
||
выводе — не `id`."""
|
||
flags = ("--status", "running") if running else ("-a",)
|
||
code, out = detached("docker", "compose", "ps", "-q", *flags, service)
|
||
if code != 0:
|
||
return []
|
||
return [
|
||
word for word in out.split() if re.fullmatch("[0-9a-f]{12,64}", word)
|
||
]
|
||
|
||
|
||
def start_service(service: str) -> int:
|
||
"""Тот же контейнер, `docker start`: убитый `docker kill` сам не вернётся.
|
||
Контейнера нет — `up` без зависимостей. Код команды."""
|
||
ids = service_ids(service, running=False)
|
||
if ids:
|
||
return detached("docker", "start", *ids)[0]
|
||
return detached(
|
||
"docker",
|
||
"compose",
|
||
"up",
|
||
"-d",
|
||
"--no-deps",
|
||
"--no-recreate",
|
||
service,
|
||
)[0]
|
||
|
||
|
||
def ensure_running(*services: str) -> bool:
|
||
"""Запускать сервисы, пока все не живут стабильно."""
|
||
deadline = time.monotonic() + SERVICE_RESTORE_WAIT_S
|
||
stable = dict.fromkeys(services, 0)
|
||
while time.monotonic() < deadline:
|
||
for service in services:
|
||
if service_ids(service):
|
||
stable[service] += 1
|
||
else:
|
||
stable[service] = 0
|
||
start_service(service)
|
||
if all(count >= SERVICE_STABLE_CHECKS for count in stable.values()):
|
||
return True
|
||
time.sleep(1)
|
||
return False
|
||
|
||
|
||
class StandGuard:
|
||
"""Рестарт стенда, который доводится до конца, снятые внедрённые сбои и
|
||
worker и relay, запущенные при любом исходе. `restart.sh` — в своей сессии:
|
||
сигнал его не обрывает на полпути с остановленными репликами."""
|
||
|
||
def __init__(self) -> None:
|
||
self.restart: subprocess.Popen[bytes] | None = None
|
||
# снятие внедрённых сбоев: раньше запуска worker и relay
|
||
self.cleanups: list[Callable[[], None]] = []
|
||
# замороженный контейнер для `docker compose ps` работает: его придётся
|
||
# добить и запустить
|
||
self.frozen: set[str] = set()
|
||
|
||
def freeze(self, service: str) -> int:
|
||
"""`docker kill -s STOP`: статус `running`, не `paused`, поэтому KILL
|
||
проходит (design change pipeline-reliability, решение 14)."""
|
||
self.frozen.add(service)
|
||
ids = service_ids(service)
|
||
if not ids:
|
||
return 1
|
||
return detached("docker", "kill", "-s", "STOP", *ids)[0]
|
||
|
||
def kill(self, service: str) -> int:
|
||
"""SIGKILL контейнера сервиса."""
|
||
ids = service_ids(service)
|
||
if not ids:
|
||
return 1
|
||
code = detached("docker", "kill", *ids)[0]
|
||
self.frozen.discard(service)
|
||
return code
|
||
|
||
def run_restart(self) -> int:
|
||
self.restart = subprocess.Popen(
|
||
[str(ROOT / "scripts" / "restart.sh")],
|
||
cwd=ROOT,
|
||
stdout=subprocess.DEVNULL,
|
||
stderr=subprocess.DEVNULL,
|
||
start_new_session=True,
|
||
)
|
||
return self.restart.wait(timeout=RESTART_WAIT_S)
|
||
|
||
def restore(self) -> bool:
|
||
"""Дождаться начатого рестарта, снять сбои, запустить worker и relay."""
|
||
with signals_ignored():
|
||
finished = True
|
||
if self.restart is not None and self.restart.poll() is None:
|
||
print("waiting for scripts/restart.sh to finish", flush=True)
|
||
try:
|
||
self.restart.wait(timeout=RESTART_WAIT_S)
|
||
except subprocess.TimeoutExpired:
|
||
print("FAIL: scripts/restart.sh did not finish")
|
||
finished = False
|
||
for cleanup in self.cleanups:
|
||
try:
|
||
cleanup()
|
||
except (
|
||
RuntimeError,
|
||
OSError,
|
||
subprocess.TimeoutExpired,
|
||
) as e:
|
||
print(f"FAIL: cleanup: {e}", flush=True)
|
||
finished = False
|
||
for service in sorted(self.frozen):
|
||
self.kill(service)
|
||
running = ensure_running("worker", "relay")
|
||
print(
|
||
f"worker and relay running at the end: {yes(running)}",
|
||
flush=True,
|
||
)
|
||
if not running:
|
||
print(
|
||
"FAIL: start them by hand: docker compose start worker relay",
|
||
)
|
||
return running and finished
|
||
|
||
|
||
def run_guarded(body: Callable[[StandGuard], int]) -> int:
|
||
"""Тело с `StandGuard`: сигнал — код 130, worker и relay запущены всегда."""
|
||
|
||
def guarded() -> int:
|
||
guard = StandGuard()
|
||
code = 1
|
||
try:
|
||
code = body(guard)
|
||
except KeyboardInterrupt as e:
|
||
print(f"FAIL: interrupted by {str(e) or 'SIGINT'}", flush=True)
|
||
code = INTERRUPTED_EXIT
|
||
except (
|
||
RuntimeError,
|
||
ValueError,
|
||
KeyError,
|
||
OSError,
|
||
http.client.HTTPException,
|
||
subprocess.TimeoutExpired,
|
||
) as e:
|
||
print(f"FAIL: {type(e).__name__}: {e}", flush=True)
|
||
code = 1
|
||
finally:
|
||
if not guard.restore():
|
||
code = code or 1
|
||
return code
|
||
|
||
return rc_signals(guarded)
|
||
|
||
|
||
def cmd_defense_scenario(port: int) -> int:
|
||
"""Спек `student-tests`, «Сценарий защиты автоматизирован», на рабочем
|
||
стенде через LB (design change `async-attachments`, решение 17). Токенов
|
||
и секретов в выводе нет."""
|
||
if not stand_answers(port, "defense-scenario"):
|
||
return 2
|
||
return run_guarded(lambda guard: defense_scenario(port, guard))
|
||
|
||
|
||
def defense_scenario(port: int, guard: StandGuard) -> int:
|
||
"""Тело `cmd_defense_scenario`. Relay не трогает: сообщение появляется в
|
||
очереди после 202, поэтому его ждут опросом."""
|
||
names = rc_stand()
|
||
if names is None:
|
||
return 1
|
||
_, database = names
|
||
queue = database + QUEUE_SUFFIX
|
||
data = FIXTURE_PNG.read_bytes()
|
||
people = attachment_people(port, "ds")
|
||
if people is None:
|
||
return 1
|
||
_, tokens, chat_id = people
|
||
messages = f"{CHATS}/{chat_id}/messages"
|
||
rows: list[tuple[str, str, str]] = []
|
||
before = container_starts("api", "rabbitmq")
|
||
relay_before = container_starts("relay")
|
||
print(
|
||
f"fixture {FIXTURE_PNG.name}: {len(data)} bytes, sha256 "
|
||
f"{sha256_hex(data)}",
|
||
)
|
||
|
||
def step(name: str, expected: object, got: object) -> None:
|
||
rows.append((name, str(expected), str(got)))
|
||
print(f"{name}: {got}", flush=True)
|
||
|
||
compose("stop", "worker")
|
||
step("docker compose stop worker", "0", "0")
|
||
status, hdrs, attachment = upload_bytes(
|
||
port,
|
||
tokens["alice"],
|
||
chat_id,
|
||
data,
|
||
content_type="image/png",
|
||
filename=FIXTURE_PNG.name,
|
||
)
|
||
step("upload sample.png", ATTACHMENT_ACCEPTED, status)
|
||
if status != ATTACHMENT_ACCEPTED or not isinstance(attachment, dict):
|
||
return report_defense(rows, before)
|
||
attachment_id = str(attachment["id"])
|
||
content = f"{ATTACHMENTS}/{attachment_id}/content"
|
||
print(f"attachment id {attachment_id}, via {hdrs.get('x-instance-id')}")
|
||
step("snapshot status", "queued", attachment.get("status"))
|
||
status, _, message = call(
|
||
port,
|
||
"POST",
|
||
messages,
|
||
token=tokens["alice"],
|
||
body={"text": "", "attachment_ids": [attachment_id]},
|
||
extra=key_header(),
|
||
)
|
||
step("message with the attachment", 201, status)
|
||
message_id = message.get("id") if isinstance(message, dict) else None
|
||
print(f"message id {message_id}")
|
||
status, _, _ = call_bytes(port, "GET", content, token=tokens["bob"])
|
||
step("download before processing", 409, status)
|
||
status, _, text = call(
|
||
port,
|
||
"POST",
|
||
messages,
|
||
token=tokens["alice"],
|
||
body={"text": "text while the worker is stopped"},
|
||
extra=key_header(),
|
||
)
|
||
step("text message", 201, status)
|
||
text_id = text.get("id") if isinstance(text, dict) else None
|
||
print(f"text message id {text_id}")
|
||
step(
|
||
"job in the queue before restart",
|
||
"yes",
|
||
yes(wait_queue_messages(queue, at_least=1) >= 1),
|
||
)
|
||
depth = broker_queues().get(queue, {})
|
||
step("queue consumers before restart", "0", depth.get("consumers"))
|
||
|
||
step("scripts/restart.sh", "0", guard.run_restart())
|
||
step("LB ready after restart", "yes", yes(wait_lb_ready(port)))
|
||
step(
|
||
"job in the queue after restart",
|
||
"yes",
|
||
yes(wait_queue_messages(queue, at_least=1) >= 1),
|
||
)
|
||
status, _, meta = call(
|
||
port,
|
||
"GET",
|
||
f"{ATTACHMENTS}/{attachment_id}",
|
||
token=tokens["bob"],
|
||
)
|
||
step("metadata after restart (same session)", 200, status)
|
||
step(
|
||
"status after restart",
|
||
"queued",
|
||
meta.get("status") if isinstance(meta, dict) else meta,
|
||
)
|
||
|
||
code, _ = detached("docker", "compose", "start", "worker")
|
||
step("docker compose start worker", "0", code)
|
||
ready = wait_attachment(port, tokens["bob"], attachment_id)
|
||
step("attachment status", "ready", ready.get("status"))
|
||
status, _, original = call_bytes(port, "GET", content, token=tokens["bob"])
|
||
step("download original", 200, status)
|
||
step(
|
||
"original sha256 = uploaded",
|
||
"yes",
|
||
yes(sha256_hex(original) == sha256_hex(data)),
|
||
)
|
||
for name, expected, got in variant_checks(port, tokens["bob"], ready):
|
||
step(name, expected, got)
|
||
step(
|
||
"relay StartedAt unchanged",
|
||
"yes",
|
||
yes(bool(relay_before) and container_starts("relay") == relay_before),
|
||
)
|
||
status, _, page = call(port, "GET", messages, token=tokens["bob"])
|
||
items = page.get("items", []) if isinstance(page, dict) else []
|
||
step("history after restart", 200, status)
|
||
step(
|
||
"history keeps both messages",
|
||
"yes",
|
||
yes({item.get("id") for item in items} >= {message_id, text_id}),
|
||
)
|
||
return report_defense(rows, before)
|
||
|
||
|
||
def report_defense(
|
||
rows: list[tuple[str, str, str]],
|
||
before: dict[str, str],
|
||
) -> int:
|
||
"""Время старта до и после и таблица шагов."""
|
||
after = container_starts("api", "rabbitmq")
|
||
print("containers: StartedAt before -> after")
|
||
for name in sorted(set(before) | set(after)):
|
||
print(f" {name}: {before.get(name)} -> {after.get(name)}")
|
||
if rows[-1][0] != "upload sample.png":
|
||
same = sorted(
|
||
name
|
||
for name, started in before.items()
|
||
if after.get(name) == started
|
||
)
|
||
rows.append(
|
||
(
|
||
"api and rabbitmq restarted",
|
||
"yes",
|
||
yes(not same and bool(after)),
|
||
),
|
||
)
|
||
return report_reconcile(
|
||
rows,
|
||
passed="the file is accepted while the worker is stopped and becomes "
|
||
"ready after the restart",
|
||
)
|
||
|
||
|
||
def cmd_broker_check(*, require_test_queue: bool) -> int:
|
||
"""Спек `message-broker`: «Сервис брокера запущен», «Предел памяти
|
||
брокера», «Очереди разных баз разделены», «Остановка брокера». Брокер
|
||
возвращается при любом исходе; секретов в выводе нет."""
|
||
|
||
def guarded() -> int:
|
||
try:
|
||
return broker_check(require_test_queue=require_test_queue)
|
||
except KeyboardInterrupt as e:
|
||
print(f"FAIL: interrupted by {str(e) or 'SIGINT'}", flush=True)
|
||
return INTERRUPTED_EXIT
|
||
except RuntimeError as e:
|
||
print(f"FAIL: {e}", flush=True)
|
||
return 1
|
||
|
||
return rc_signals(guarded)
|
||
|
||
|
||
def broker_check(*, require_test_queue: bool) -> int:
|
||
"""Тело `cmd_broker_check`."""
|
||
names = rc_stand()
|
||
if names is None:
|
||
return 1
|
||
_, database = names
|
||
config = json.loads(compose("config", "--format", "json"))
|
||
project = str(config["name"])
|
||
service = config["services"]["rabbitmq"]
|
||
containers = service_containers("rabbitmq")
|
||
if not containers:
|
||
print("FAIL: service rabbitmq is not running, make run_docker first")
|
||
return 1
|
||
container = containers[0]
|
||
name = str(container["Name"]).lstrip("/")
|
||
rows: list[tuple[str, str, str]] = []
|
||
|
||
image = str(service["image"])
|
||
print(f"image {image}")
|
||
rows.append(
|
||
(
|
||
"image is tag and digest",
|
||
"yes",
|
||
yes(bool(BROKER_IMAGE.match(image))),
|
||
),
|
||
)
|
||
rows.append(
|
||
(
|
||
"container health",
|
||
"healthy",
|
||
str(container["State"].get("Health", {}).get("Status")),
|
||
),
|
||
)
|
||
mounts = [
|
||
str(item.get("Name"))
|
||
for item in container["Mounts"]
|
||
if item.get("Type") == "volume"
|
||
and item.get("Destination") == "/var/lib/rabbitmq"
|
||
]
|
||
rows.append(
|
||
(
|
||
"data volume",
|
||
f"{project}_rabbitmq_data",
|
||
",".join(mounts) or "-",
|
||
),
|
||
)
|
||
published = subprocess.run(
|
||
["docker", "port", name],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
).stdout.split("\n")
|
||
published = [line for line in published if line.strip()]
|
||
amqp = next(
|
||
item["published"]
|
||
for item in service["ports"]
|
||
if int(item["target"]) == 5672
|
||
)
|
||
rows.append(
|
||
(
|
||
"docker port",
|
||
f"5672/tcp -> 127.0.0.1:{amqp}",
|
||
";".join(published) or "-",
|
||
),
|
||
)
|
||
|
||
limit = int(container["HostConfig"]["Memory"])
|
||
rows.append(
|
||
("container memory limit", str(BROKER_MEMORY_LIMIT), str(limit)),
|
||
)
|
||
status = json.loads(
|
||
compose(
|
||
"exec",
|
||
"-T",
|
||
"rabbitmq",
|
||
"rabbitmqctl",
|
||
"-q",
|
||
"status",
|
||
"--formatter",
|
||
"json",
|
||
),
|
||
)
|
||
watermark = int(status["vm_memory_high_watermark_limit"])
|
||
print(f"memory high watermark {watermark}, container limit {limit}")
|
||
rows.append(
|
||
("watermark below container limit", "yes", yes(0 < watermark < limit)),
|
||
)
|
||
|
||
queues = broker_queues()
|
||
print("queues (name durable messages consumers):")
|
||
for item in queues.values():
|
||
print(
|
||
f" {item['name']} {item['durable']} {item['messages']} "
|
||
f"{item['consumers']}",
|
||
)
|
||
work = database + QUEUE_SUFFIX
|
||
# пароль брокера: только имена переменных, значения не печатаются. У реплик
|
||
# API брокера нет (design change pipeline-reliability, решение 1)
|
||
holders = sorted(
|
||
name
|
||
for name, item in config["services"].items()
|
||
if any(
|
||
key in BROKER_PASSWORD_ENV for key in item.get("environment") or {}
|
||
)
|
||
)
|
||
rows.append(("broker password holders", BROKER_HOLDERS, ",".join(holders)))
|
||
rows.append(
|
||
(
|
||
"BROKER__* in the api service",
|
||
"no",
|
||
yes(
|
||
any(
|
||
key.startswith("BROKER__")
|
||
for key in config["services"]["api"]["environment"]
|
||
),
|
||
),
|
||
),
|
||
)
|
||
relay_before = container_starts("relay")
|
||
rows.append(("work queue exists", "yes", yes(work in queues)))
|
||
rows.append(
|
||
(
|
||
"work queue durable",
|
||
"yes",
|
||
yes(queues.get(work, {}).get("durable") is True),
|
||
),
|
||
)
|
||
test_queue = f"test_{database}{QUEUE_SUFFIX}"
|
||
if require_test_queue:
|
||
rows.append(
|
||
(f"queue {test_queue}", "yes", yes(test_queue in queues)),
|
||
)
|
||
else:
|
||
print(f"temporary database queue {test_queue}: not checked")
|
||
|
||
had_consumer = int(str(queues.get(work, {}).get("consumers", 0))) > 0
|
||
try:
|
||
started = time.monotonic()
|
||
code, _ = detached("docker", "compose", "stop", "rabbitmq")
|
||
took = time.monotonic() - started
|
||
exit_code = subprocess.run(
|
||
["docker", "inspect", "-f", "{{.State.ExitCode}}", name],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
).stdout.strip()
|
||
print(f"docker compose stop rabbitmq: {took:.1f} s")
|
||
rows.append(("docker compose stop exit code", "0", str(code)))
|
||
rows.append(("container exit code", "0", exit_code))
|
||
rows.append(
|
||
(
|
||
f"stopped before the {BROKER_STOP_GRACE_S} s grace",
|
||
"yes",
|
||
yes(took < BROKER_STOP_GRACE_S),
|
||
),
|
||
)
|
||
finally:
|
||
with signals_ignored():
|
||
code, _ = detached(
|
||
"docker",
|
||
"compose",
|
||
"up",
|
||
"-d",
|
||
"--wait",
|
||
"--no-recreate",
|
||
"rabbitmq",
|
||
)
|
||
rows.append(("broker back (up --wait)", "0", str(code)))
|
||
queues = broker_queues()
|
||
rows.append(
|
||
(
|
||
"work queue after restart",
|
||
"yes",
|
||
yes(queues.get(work, {}).get("durable") is True),
|
||
),
|
||
)
|
||
if had_consumer:
|
||
deadline = time.monotonic() + BROKER_CONSUMER_WAIT_S
|
||
while time.monotonic() < deadline:
|
||
current = int(
|
||
str(broker_queues().get(work, {}).get("consumers", 0)),
|
||
)
|
||
if current > 0:
|
||
break
|
||
time.sleep(1)
|
||
rows.append(("worker consumes again", "yes", yes(current > 0)))
|
||
rows.append(
|
||
(
|
||
"relay survived the outage (StartedAt)",
|
||
"yes",
|
||
yes(
|
||
bool(relay_before)
|
||
and container_starts("relay") == relay_before,
|
||
),
|
||
),
|
||
)
|
||
return report_reconcile(rows, passed="the broker stand matches the spec")
|
||
|
||
|
||
def cmd_worker_process(port: int) -> int:
|
||
"""Спеки `container-run`, `graceful-shutdown`, `service-configuration`
|
||
о процессе worker на рабочем стенде (design change `async-attachments`,
|
||
решение 17). Секретов в выводе нет: печатаются только нужные поля."""
|
||
if not stand_answers(port, "worker-process"):
|
||
return 2
|
||
return run_guarded(lambda guard: service_process(port, guard, WORKER_SPEC))
|
||
|
||
|
||
def cmd_relay_process(port: int) -> int:
|
||
"""То же о процессе relay (design change `pipeline-reliability`, решение
|
||
17): PID 1, нет healthcheck, лимиты, окружение без S3 и Valkey, запись о
|
||
старте, неверные `RELAY__*`, остановка, рестарт хранилищ."""
|
||
if not stand_answers(port, "relay-process"):
|
||
return 2
|
||
return run_guarded(lambda guard: service_process(port, guard, RELAY_SPEC))
|
||
|
||
|
||
def imaging_row(container: str, title: str) -> tuple[str, str, str]:
|
||
"""Декодер в памяти PID 1 контейнера: строка таблицы."""
|
||
maps = subprocess.run(
|
||
["docker", "exec", container, "cat", "/proc/1/maps"],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
).stdout
|
||
return f"_imaging in {title}", "no", yes("_imaging" in maps)
|
||
|
||
|
||
def service_process(port: int, guard: StandGuard, spec: ProcessSpec) -> int:
|
||
"""Тело `cmd_worker_process` и `cmd_relay_process`."""
|
||
service = spec.service
|
||
config = json.loads(compose("config", "--format", "json"))
|
||
project = str(config["name"])
|
||
image = str(config["services"][service]["image"])
|
||
containers = service_containers(service)
|
||
if not containers:
|
||
print(f"FAIL: service {service} is not running, make run_docker first")
|
||
return 2
|
||
container = containers[0]
|
||
service_id = str(container["Id"])
|
||
name = str(container["Name"]).lstrip("/")
|
||
rows: list[tuple[str, str, str]] = []
|
||
|
||
# процесс
|
||
cmdline = subprocess.run(
|
||
["docker", "exec", name, "cat", "/proc/1/cmdline"],
|
||
capture_output=True,
|
||
check=False,
|
||
).stdout
|
||
rows.append(
|
||
(
|
||
f"PID 1 of the {service}",
|
||
f"python -m src.{service}",
|
||
cmdline.replace(b"\0", b" ").decode().strip(),
|
||
),
|
||
)
|
||
rows.append(
|
||
(
|
||
"healthcheck",
|
||
"NONE",
|
||
" ".join(
|
||
(container["Config"].get("Healthcheck") or {}).get("Test")
|
||
or [],
|
||
),
|
||
),
|
||
)
|
||
for field, expected in spec.limits.items():
|
||
rows.append(
|
||
(
|
||
f"limit {field}",
|
||
str(expected),
|
||
str(container["HostConfig"][field]),
|
||
),
|
||
)
|
||
# только имена переменных: значения — секреты
|
||
names = [str(item).split("=", 1)[0] for item in container["Config"]["Env"]]
|
||
for prefix in spec.absent_env:
|
||
rows.append(
|
||
(
|
||
f"{prefix}* in the environment",
|
||
"no",
|
||
yes(any(item.startswith(prefix) for item in names)),
|
||
),
|
||
)
|
||
replicas = service_containers("api")
|
||
for replica in replicas:
|
||
rows.append(
|
||
imaging_row(
|
||
str(replica["Id"]),
|
||
str(replica["Name"]).lstrip("/"),
|
||
),
|
||
)
|
||
rows.append(("API replicas checked", "yes", yes(bool(replicas))))
|
||
rows.append(imaging_row(name, f"PID 1 of the {service}"))
|
||
if service == "worker":
|
||
pillow = subprocess.run(
|
||
[
|
||
"docker",
|
||
"exec",
|
||
name,
|
||
"python",
|
||
"-c",
|
||
"import PIL; print(PIL.__version__)",
|
||
],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
).stdout.strip()
|
||
locked = re.search(
|
||
r'name = "pillow"\nversion = "([^"]+)"',
|
||
(ROOT / "uv.lock").read_text(),
|
||
)
|
||
rows.append(
|
||
(
|
||
"Pillow in the image = uv.lock",
|
||
locked.group(1) if locked else "-",
|
||
pillow or "-",
|
||
),
|
||
)
|
||
|
||
# запись о старте и значения по умолчанию
|
||
started_event = f"Started {service}"
|
||
logs = compose("logs", "--no-log-prefix", service)
|
||
started = [
|
||
r for r in json_records(logs) if r.get("event") == started_event
|
||
]
|
||
rows.append((f"'{started_event}' record", "yes", yes(bool(started))))
|
||
record = started[-1] if started else {}
|
||
print(f"{started_event}:")
|
||
for key in (*spec.defaults, *spec.other_fields):
|
||
print(f" {key}: {record.get(key)}")
|
||
for key in spec.other_fields:
|
||
rows.append((f"record names {key}", "yes", yes(key in record)))
|
||
for key, value in spec.defaults.items():
|
||
rows.append(
|
||
(
|
||
f"default {key}",
|
||
str(float(value)),
|
||
str(float(str(record.get(key, "nan")))),
|
||
),
|
||
)
|
||
|
||
# неверные настройки: код 2, поле называется, значения нет
|
||
for variable, value, field in spec.bad_settings:
|
||
code, out = detached(
|
||
"docker",
|
||
"compose",
|
||
"run",
|
||
"--rm",
|
||
"--no-deps",
|
||
"-T",
|
||
"-e",
|
||
f"{variable}={value}",
|
||
service,
|
||
)
|
||
invalid = next(
|
||
(
|
||
item
|
||
for item in json_records(out)
|
||
if item.get("event") == f"Invalid {service} settings"
|
||
),
|
||
{},
|
||
)
|
||
errors = invalid.get("errors") or []
|
||
print(f"{variable}={value}: exit {code}, errors {errors}")
|
||
rows.append((f"{variable}={value} exit code", "2", str(code)))
|
||
rows.append(
|
||
(
|
||
f"{variable} names the field",
|
||
"yes",
|
||
yes(any(item.get("loc") == field for item in errors)),
|
||
),
|
||
)
|
||
rows.append(
|
||
(
|
||
f"{variable} hides the value",
|
||
"yes",
|
||
yes(value not in json.dumps(errors)),
|
||
),
|
||
)
|
||
|
||
# подмена окружением: одноразовый контейнер рядом с сервисом
|
||
probe = f"{project}-{service}-process-{uuid.uuid4().hex[:8]}"
|
||
try:
|
||
env_flags = [
|
||
flag
|
||
for variable, value, _, _ in spec.overrides
|
||
for flag in ("-e", f"{variable}={value}")
|
||
]
|
||
code, _ = detached(
|
||
"docker",
|
||
"compose",
|
||
"run",
|
||
"-d",
|
||
"--no-deps",
|
||
"--name",
|
||
probe,
|
||
*env_flags,
|
||
service,
|
||
)
|
||
rows.append(("env override container started", "0", str(code)))
|
||
overridden: dict[str, object] = {}
|
||
deadline = time.monotonic() + PROCESS_LOG_WAIT_S
|
||
while time.monotonic() < deadline and not overridden:
|
||
_, out = detached("docker", "logs", probe)
|
||
overridden = next(
|
||
(
|
||
item
|
||
for item in json_records(out)
|
||
if item.get("event") == started_event
|
||
),
|
||
{},
|
||
)
|
||
time.sleep(0.2)
|
||
for _, _, field, expected in spec.overrides:
|
||
rows.append(
|
||
(
|
||
f"env override {field}",
|
||
expected,
|
||
str(overridden.get(field)),
|
||
),
|
||
)
|
||
finally:
|
||
with signals_ignored():
|
||
detached("docker", "rm", "-f", probe)
|
||
|
||
# остановка простаивающего сервиса
|
||
stopped_event = f"Stopped {service}"
|
||
started_at = time.monotonic()
|
||
code, _ = detached("docker", "compose", "stop", service)
|
||
took = time.monotonic() - started_at
|
||
print(f"docker compose stop {service}: {took:.1f} s")
|
||
state = subprocess.run(
|
||
["docker", "inspect", "-f", "{{.State.ExitCode}}", service_id],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
).stdout.strip()
|
||
_, out = detached("docker", "logs", service_id)
|
||
last = [
|
||
item
|
||
for item in json_records(out)
|
||
if item.get("event") in (started_event, stopped_event)
|
||
]
|
||
rows.append(("stop idle: command exit code", "0", str(code)))
|
||
rows.append(("stop idle: container exit code", "0", state))
|
||
rows.append(
|
||
(
|
||
f"stop idle: under {PROCESS_STOP_LIMIT_S} s",
|
||
"yes",
|
||
yes(took < PROCESS_STOP_LIMIT_S),
|
||
),
|
||
)
|
||
rows.append(
|
||
(
|
||
"stop idle: last record",
|
||
stopped_event,
|
||
str(last[-1].get("event")) if last else "-",
|
||
),
|
||
)
|
||
rows.append(
|
||
(
|
||
"stop idle: record exit_code",
|
||
"0",
|
||
str(last[-1].get("exit_code")) if last else "-",
|
||
),
|
||
)
|
||
code, _ = detached("docker", "compose", "start", service)
|
||
rows.append((f"docker compose start {service}", "0", str(code)))
|
||
|
||
# остановка на старте
|
||
rows.extend(process_early_stop(spec, image))
|
||
|
||
# рестарт хранилищ
|
||
before = service_containers(service)
|
||
rows.append(
|
||
(f"{service} running before restart", "yes", yes(bool(before))),
|
||
)
|
||
started_before = before[0]["State"]["StartedAt"] if before else None
|
||
rows.append(("scripts/restart.sh", "0", str(guard.run_restart())))
|
||
rows.append(("LB ready after restart", "yes", yes(wait_lb_ready(port))))
|
||
after = service_containers(service)
|
||
rows.append(
|
||
(
|
||
f"{service} StartedAt unchanged",
|
||
"yes",
|
||
yes(
|
||
bool(after)
|
||
and after[0]["State"]["StartedAt"] == started_before,
|
||
),
|
||
),
|
||
)
|
||
rows.append(
|
||
(
|
||
f"{service} RestartCount",
|
||
"0",
|
||
str(after[0]["RestartCount"]) if after else "-",
|
||
),
|
||
)
|
||
people = attachment_people(port, service[0] + "p")
|
||
if people is None:
|
||
rows.append(("new upload after restart", "ready", "no users"))
|
||
return report_reconcile(rows)
|
||
_, tokens, chat_id = people
|
||
status, _, attachment = upload_ready(
|
||
port,
|
||
tokens["alice"],
|
||
chat_id,
|
||
FIXTURE_PNG.read_bytes(),
|
||
content_type="image/png",
|
||
filename=FIXTURE_PNG.name,
|
||
)
|
||
rows.append(("new upload after restart", "202", str(status)))
|
||
rows.append(
|
||
(
|
||
"new upload becomes ready",
|
||
"yes",
|
||
yes(isinstance(attachment, dict)),
|
||
),
|
||
)
|
||
if service == "worker":
|
||
rows.extend(
|
||
worker_stop_under_load(port, guard, image, tokens, chat_id),
|
||
)
|
||
else:
|
||
rows.extend(relay_stop_broker_frozen(port, guard, tokens, chat_id))
|
||
return report_reconcile(
|
||
rows,
|
||
passed=f"the {service} process matches the spec",
|
||
)
|
||
|
||
|
||
def expensive_jpeg(image: str) -> bytes | None:
|
||
"""Дорогой JPEG тем же генератором, что у тестов: Pillow есть в образе, а
|
||
драйвер — только stdlib."""
|
||
source = ROOT / "student-tests" / "images.py"
|
||
proc = subprocess.run(
|
||
[
|
||
"docker",
|
||
"run",
|
||
"--rm",
|
||
"--network",
|
||
"none",
|
||
"-v",
|
||
f"{source}:/tmp/images.py:ro",
|
||
"--entrypoint",
|
||
"python",
|
||
image,
|
||
"-I",
|
||
"-c",
|
||
EXPENSIVE_JPEG_PY,
|
||
],
|
||
capture_output=True,
|
||
check=False,
|
||
)
|
||
return proc.stdout if proc.returncode == 0 and proc.stdout else None
|
||
|
||
|
||
def stopped_record_rows(
|
||
title: str,
|
||
service: str,
|
||
container: str,
|
||
) -> list[tuple[str, str, str]]:
|
||
"""Код контейнера и последняя запись журнала после `docker stop`."""
|
||
state = subprocess.run(
|
||
[
|
||
"docker",
|
||
"inspect",
|
||
"-f",
|
||
"{{.State.ExitCode}} {{.State.OOMKilled}}",
|
||
container,
|
||
],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
).stdout.split()
|
||
_, out = detached("docker", "logs", container)
|
||
last = [
|
||
item
|
||
for item in json_records(out)
|
||
if item.get("event") in (f"Started {service}", f"Stopped {service}")
|
||
]
|
||
return [
|
||
(f"{title}: container exit code", "0", state[0] if state else "-"),
|
||
(f"{title}: OOM killed", "false", state[1] if state[1:] else "-"),
|
||
(
|
||
f"{title}: last record",
|
||
f"Stopped {service}",
|
||
str(last[-1].get("event")) if last else "-",
|
||
),
|
||
]
|
||
|
||
|
||
def worker_stop_during_render(
|
||
port: int,
|
||
guard: StandGuard,
|
||
token: str,
|
||
chat_id: str,
|
||
data: bytes,
|
||
*,
|
||
frozen: bool,
|
||
) -> tuple[list[tuple[str, str, str]], list[str]]:
|
||
"""Два дорогих файла в обработке, `docker stop`: обработка не успевает за
|
||
срок остановки, поэтому идёт весь путь решения 19. Замороженные PostgreSQL и
|
||
брокер отвечать на закрытие клиентов не будут."""
|
||
title = "stop frozen storage" if frozen else "stop under load"
|
||
rows: list[tuple[str, str, str]] = []
|
||
ids: list[str] = []
|
||
stopped, _ = detached("docker", "compose", "stop", "worker")
|
||
rows.append((f"{title}: worker stopped before uploads", "0", str(stopped)))
|
||
for index in range(LOAD_FILES):
|
||
status, _, payload = upload_bytes(
|
||
port,
|
||
token,
|
||
chat_id,
|
||
data,
|
||
content_type="image/jpeg",
|
||
filename=f"process-load-{index}.jpg",
|
||
)
|
||
rows.append((f"{title}: upload {index}", "202", str(status)))
|
||
if isinstance(payload, dict) and "id" in payload:
|
||
ids.append(str(payload["id"]))
|
||
started_code = start_service("worker")
|
||
rows.append((f"{title}: worker started", "0", str(started_code)))
|
||
deadline = time.monotonic() + LOAD_TAKEN_WAIT_S
|
||
states: list[object] = []
|
||
while time.monotonic() < deadline:
|
||
states = [df_job(item).get("state") for item in ids]
|
||
if states and all(state == "processing" for state in states):
|
||
break
|
||
time.sleep(READY_POLL_S)
|
||
rows.append(
|
||
(
|
||
f"{title}: both files in processing",
|
||
"processing",
|
||
",".join(sorted({str(state) for state in states})),
|
||
),
|
||
)
|
||
# обработка идёт, а не только взята
|
||
time.sleep(LOAD_RENDER_SETTLE_S)
|
||
containers = service_ids("worker")
|
||
if not containers:
|
||
rows.append((f"{title}: worker running", "yes", "no"))
|
||
return rows, ids
|
||
if frozen:
|
||
guard.cleanups.append(
|
||
lambda: (
|
||
detached("docker", "compose", "unpause", *LOAD_FROZEN) and None
|
||
),
|
||
)
|
||
try:
|
||
if frozen:
|
||
code, _ = detached("docker", "compose", "pause", *LOAD_FROZEN)
|
||
rows.append((f"{title}: storage paused", "0", str(code)))
|
||
started = time.monotonic()
|
||
code, _ = detached(
|
||
"docker",
|
||
"stop",
|
||
"--timeout",
|
||
str(PROCESS_STOP_LIMIT_S),
|
||
containers[0],
|
||
)
|
||
took = time.monotonic() - started
|
||
finally:
|
||
if frozen:
|
||
detached("docker", "compose", "unpause", *LOAD_FROZEN)
|
||
print(f"{title}: docker stop worker took {took:.2f} s", flush=True)
|
||
rows.append((f"{title}: command exit code", "0", str(code)))
|
||
rows.append(
|
||
(
|
||
f"{title}: under {PROCESS_STOP_BOUND_S} s",
|
||
"yes",
|
||
yes(took < PROCESS_STOP_BOUND_S),
|
||
),
|
||
)
|
||
rows.extend(stopped_record_rows(title, "worker", containers[0]))
|
||
rows.append(
|
||
(f"{title}: worker back", "0", str(start_service("worker"))),
|
||
)
|
||
if frozen:
|
||
rows.append(
|
||
("LB ready after unpause", "yes", yes(wait_lb_ready(port))),
|
||
)
|
||
return rows, ids
|
||
|
||
|
||
def worker_stop_under_load(
|
||
port: int,
|
||
guard: StandGuard,
|
||
image: str,
|
||
tokens: dict[str, str],
|
||
chat_id: str,
|
||
) -> list[tuple[str, str, str]]:
|
||
"""Остановка на двух дорогих JPEG, затем то же при замороженных хранилищах
|
||
(спек `graceful-shutdown`, решение 19). Принятая работа не теряется: аренда
|
||
вернёт задания, и они упрутся в лимит CPU."""
|
||
data = expensive_jpeg(image)
|
||
rows: list[tuple[str, str, str]] = [
|
||
("expensive JPEG generated", "yes", yes(data is not None)),
|
||
]
|
||
if data is None:
|
||
return rows
|
||
token = tokens["alice"]
|
||
attachments: list[str] = []
|
||
for frozen in (False, True):
|
||
part, ids = worker_stop_during_render(
|
||
port,
|
||
guard,
|
||
token,
|
||
chat_id,
|
||
data,
|
||
frozen=frozen,
|
||
)
|
||
rows.extend(part)
|
||
attachments.extend(ids)
|
||
deadline = time.monotonic() + LOAD_FINISH_WAIT_S
|
||
for attachment_id in attachments:
|
||
final = wait_attachment(
|
||
port,
|
||
token,
|
||
attachment_id,
|
||
timeout=max(0.0, deadline - time.monotonic()),
|
||
)
|
||
job = df_job(attachment_id)
|
||
rows.append(
|
||
(
|
||
f"stopped work finished: {attachment_id}",
|
||
"failed limit_cpu",
|
||
f"{final.get('status')} {job.get('last_error_code')}",
|
||
),
|
||
)
|
||
return rows
|
||
|
||
|
||
def relay_stop_broker_frozen(
|
||
port: int,
|
||
guard: StandGuard,
|
||
tokens: dict[str, str],
|
||
chat_id: str,
|
||
) -> list[tuple[str, str, str]]:
|
||
"""`docker stop relay`, пока намерение есть, а брокер заморожен: публикация
|
||
висит до своего срока, остановка дожидается только текущего шага."""
|
||
title = "stop frozen broker"
|
||
token = tokens["alice"]
|
||
rows: list[tuple[str, str, str]] = []
|
||
containers = service_ids("relay")
|
||
if not containers:
|
||
return [(f"{title}: relay running", "yes", "no")]
|
||
guard.cleanups.append(
|
||
lambda: detached("docker", "compose", "unpause", "rabbitmq") and None,
|
||
)
|
||
try:
|
||
code, _ = detached("docker", "compose", "pause", "rabbitmq")
|
||
rows.append((f"{title}: broker paused", "0", str(code)))
|
||
status, _, payload = upload_bytes(
|
||
port,
|
||
token,
|
||
chat_id,
|
||
FIXTURE_PNG.read_bytes(),
|
||
content_type="image/png",
|
||
filename=FIXTURE_PNG.name,
|
||
)
|
||
rows.append((f"{title}: upload", "202", str(status)))
|
||
# relay уже в публикации: срок 2 с
|
||
time.sleep(LOAD_RENDER_SETTLE_S)
|
||
started = time.monotonic()
|
||
code, _ = detached(
|
||
"docker",
|
||
"stop",
|
||
"--timeout",
|
||
str(PROCESS_STOP_LIMIT_S),
|
||
containers[0],
|
||
)
|
||
took = time.monotonic() - started
|
||
finally:
|
||
detached("docker", "compose", "unpause", "rabbitmq")
|
||
print(f"{title}: docker stop relay took {took:.2f} s", flush=True)
|
||
rows.append((f"{title}: command exit code", "0", str(code)))
|
||
rows.append(
|
||
(
|
||
f"{title}: under {PROCESS_STOP_LIMIT_S} s",
|
||
"yes",
|
||
yes(took < PROCESS_STOP_LIMIT_S),
|
||
),
|
||
)
|
||
rows.extend(stopped_record_rows(title, "relay", containers[0]))
|
||
rows.append((f"{title}: relay back", "0", str(start_service("relay"))))
|
||
if isinstance(payload, dict) and "id" in payload:
|
||
final = wait_attachment(port, token, str(payload["id"]))
|
||
rows.append(
|
||
(
|
||
f"{title}: upload after start",
|
||
"ready",
|
||
str(final.get("status")),
|
||
),
|
||
)
|
||
return rows
|
||
|
||
|
||
def process_early_stop(
|
||
spec: ProcessSpec,
|
||
image: str,
|
||
) -> list[tuple[str, str, str]]:
|
||
"""`docker stop` во время импорта приложения: контейнер образа без сети
|
||
и `config.toml`, с лимитами сервиса, как `stop-at-start`. Каждая попытка —
|
||
код 0 и не дольше секунды; записи «before startup» нужно увидеть хотя бы
|
||
раз."""
|
||
rows: list[tuple[str, str, str]] = []
|
||
label = f"{PROCESS_EARLY_LABEL}={uuid.uuid4().hex[:8]}"
|
||
early_event = f"Stopped {spec.service} before startup"
|
||
seen = False
|
||
try:
|
||
for delay in PROCESS_EARLY_DELAYS:
|
||
code, out = detached(
|
||
"docker",
|
||
"run",
|
||
"-d",
|
||
"--network",
|
||
"none",
|
||
"--cpus",
|
||
str(spec.limits["NanoCpus"] / 1e9),
|
||
"--memory",
|
||
str(spec.limits["Memory"]),
|
||
"--label",
|
||
label,
|
||
"--entrypoint",
|
||
"python",
|
||
image,
|
||
"-m",
|
||
f"src.{spec.service}",
|
||
)
|
||
if code != 0:
|
||
rows.append(("early stop: docker run", "0", str(code)))
|
||
break
|
||
# в выводе есть и предупреждения Docker о лимитах
|
||
found = re.search(r"\b[0-9a-f]{64}\b", out)
|
||
if found is None:
|
||
rows.append(("early stop: container id", "yes", "no"))
|
||
break
|
||
container = found.group(0)
|
||
time.sleep(delay)
|
||
started = time.monotonic()
|
||
stop_code, _ = detached(
|
||
"docker",
|
||
"stop",
|
||
"--timeout",
|
||
str(PROCESS_STOP_LIMIT_S),
|
||
container,
|
||
)
|
||
took = time.monotonic() - started
|
||
state = subprocess.run(
|
||
["docker", "inspect", "-f", "{{.State.ExitCode}}", container],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
).stdout.strip()
|
||
_, logs = detached("docker", "logs", container)
|
||
events = [str(r.get("event")) for r in json_records(logs)]
|
||
early = early_event in events
|
||
seen = seen or early
|
||
print(
|
||
f"docker stop after {delay} s: {took:.2f} s, exit {state}, "
|
||
f"records {events}",
|
||
)
|
||
rows.append(
|
||
(f"early stop {delay} s: docker stop", "0", str(stop_code)),
|
||
)
|
||
rows.append((f"early stop {delay} s: exit code", "0", state))
|
||
rows.append(
|
||
(
|
||
f"early stop {delay} s: within "
|
||
f"{PROCESS_EARLY_STOP_LIMIT_S:.0f} s",
|
||
"yes",
|
||
yes(took <= PROCESS_EARLY_STOP_LIMIT_S),
|
||
),
|
||
)
|
||
finally:
|
||
with signals_ignored():
|
||
_, out = detached(
|
||
"docker",
|
||
"ps",
|
||
"-aq",
|
||
"--filter",
|
||
f"label={label}",
|
||
)
|
||
if out.split():
|
||
detached("docker", "rm", "-f", *out.split())
|
||
rows.append((f"'{early_event}' seen", "yes", yes(seen)))
|
||
return rows
|
||
|
||
|
||
# pipeline-state (design change pipeline-reliability, решение 8): только чтение.
|
||
# Время — часы PostgreSQL, одним запросом
|
||
PIPELINE_STATE_SQL = """\
|
||
SELECT row_to_json(s) FROM (
|
||
SELECT
|
||
(SELECT coalesce(json_object_agg(state, n), '{}'::json) FROM (
|
||
SELECT state, count(*) AS n FROM attachment_jobs GROUP BY state
|
||
) c) AS jobs_by_state,
|
||
count(*) FILTER (
|
||
WHERE state = 'queued' AND published_at IS NULL
|
||
AND COALESCE(next_attempt_at, created_at) <= now()
|
||
) AS due,
|
||
count(*) FILTER (
|
||
WHERE state = 'queued' AND published_at IS NULL
|
||
AND next_attempt_at > now()
|
||
) AS waiting_for_time,
|
||
count(*) FILTER (
|
||
WHERE state = 'queued' AND published_at IS NOT NULL
|
||
) AS published_not_taken,
|
||
count(*) FILTER (
|
||
WHERE state = 'processing' AND lease_expires_at < now()
|
||
) AS expired_leases,
|
||
extract(epoch FROM now() - min(created_at) FILTER (
|
||
WHERE state = 'queued'
|
||
)) AS oldest_queued_age_seconds
|
||
FROM attachment_jobs
|
||
) s;
|
||
"""
|
||
PIPELINE_QUEUE_TIMEOUT_S = 15
|
||
|
||
|
||
def cmd_pipeline_state() -> int:
|
||
"""Состояние конвейера JSON-ом: задания, очередь. Ничего не меняет.
|
||
Брокер недоступен — это тоже состояние, код 0; PostgreSQL — код 1."""
|
||
names = rc_stand()
|
||
if names is None:
|
||
return 1
|
||
_, database = names
|
||
queue_name = database + QUEUE_SUFFIX
|
||
try:
|
||
state = json.loads(stand_psql(PIPELINE_STATE_SQL))
|
||
except (RuntimeError, ValueError) as e:
|
||
print(f"FAIL: PostgreSQL of the stand: {e}", file=sys.stderr)
|
||
return 1
|
||
queue: dict[str, object] = {"name": queue_name, "available": False}
|
||
with contextlib.suppress(
|
||
RuntimeError,
|
||
ValueError,
|
||
subprocess.TimeoutExpired,
|
||
):
|
||
found = broker_queues(timeout=PIPELINE_QUEUE_TIMEOUT_S).get(queue_name)
|
||
queue = {
|
||
"name": queue_name,
|
||
"available": True,
|
||
"exists": found is not None,
|
||
}
|
||
for field in (
|
||
"durable",
|
||
"messages_ready",
|
||
"messages_unacknowledged",
|
||
"consumers",
|
||
):
|
||
queue[field] = None if found is None else found.get(field)
|
||
state["queue"] = queue
|
||
print(json.dumps(state, ensure_ascii=False, indent=2))
|
||
return 0
|
||
|
||
|
||
# defense-faults (design change pipeline-reliability, решения 14 и 17): окна
|
||
# отказа снаружи приложения, триггеры на уникальный filename прогона. Имена
|
||
# постоянные: остаток прерванного прогона убирается в начале следующего. Сроки
|
||
# ожидания в триггерах меньше statement_timeout (5 с): завершаются сами
|
||
DF_STALL_S = 4
|
||
DF_COMMIT_STALL_S = 3
|
||
DF_RELAY_STALL_S = 3
|
||
DF_READY_STALL_SQL = """\
|
||
CREATE OR REPLACE FUNCTION driver_df_ready_stall() RETURNS trigger
|
||
LANGUAGE plpgsql AS $$
|
||
BEGIN
|
||
IF NEW.filename = TG_ARGV[0] AND OLD.status <> 'ready'
|
||
AND NEW.status = 'ready' THEN
|
||
PERFORM pg_sleep({seconds});
|
||
END IF;
|
||
RETURN NEW;
|
||
END
|
||
$$;
|
||
DROP TRIGGER IF EXISTS driver_df_ready_stall ON attachments;
|
||
CREATE TRIGGER driver_df_ready_stall BEFORE UPDATE ON attachments
|
||
FOR EACH ROW EXECUTE FUNCTION driver_df_ready_stall('{filename}');
|
||
"""
|
||
DF_COMMIT_STALL_SQL = """\
|
||
CREATE OR REPLACE FUNCTION driver_df_commit_stall() RETURNS trigger
|
||
LANGUAGE plpgsql AS $$
|
||
BEGIN
|
||
IF NEW.filename = TG_ARGV[0] AND OLD.status <> 'ready'
|
||
AND NEW.status = 'ready' THEN
|
||
PERFORM pg_sleep({seconds});
|
||
END IF;
|
||
RETURN NULL;
|
||
END
|
||
$$;
|
||
DROP TRIGGER IF EXISTS driver_df_commit_stall ON attachments;
|
||
CREATE CONSTRAINT TRIGGER driver_df_commit_stall AFTER UPDATE ON attachments
|
||
DEFERRABLE INITIALLY DEFERRED FOR EACH ROW
|
||
EXECUTE FUNCTION driver_df_commit_stall('{filename}');
|
||
"""
|
||
DF_RELAY_STALL_SQL = """\
|
||
CREATE OR REPLACE FUNCTION driver_df_relay_stall() RETURNS trigger
|
||
LANGUAGE plpgsql AS $$
|
||
BEGIN
|
||
IF NEW.published_at IS NOT NULL
|
||
AND (SELECT filename FROM attachments
|
||
WHERE id = NEW.attachment_id) = TG_ARGV[0] THEN
|
||
PERFORM pg_sleep({seconds});
|
||
END IF;
|
||
RETURN NEW;
|
||
END
|
||
$$;
|
||
DROP TRIGGER IF EXISTS driver_df_relay_stall ON attachment_jobs;
|
||
CREATE TRIGGER driver_df_relay_stall
|
||
BEFORE UPDATE OF published_at ON attachment_jobs
|
||
FOR EACH ROW EXECUTE FUNCTION driver_df_relay_stall('{filename}');
|
||
"""
|
||
DF_CLEAR_SQL = """\
|
||
DROP TRIGGER IF EXISTS driver_df_ready_stall ON attachments;
|
||
DROP TRIGGER IF EXISTS driver_df_commit_stall ON attachments;
|
||
DROP TRIGGER IF EXISTS driver_df_relay_stall ON attachment_jobs;
|
||
DROP FUNCTION IF EXISTS driver_df_ready_stall();
|
||
DROP FUNCTION IF EXISTS driver_df_commit_stall();
|
||
DROP FUNCTION IF EXISTS driver_df_relay_stall();
|
||
"""
|
||
DF_TRIGGERS_LEFT_SQL = """\
|
||
SELECT count(*) FROM pg_trigger WHERE tgname LIKE 'driver\\_df\\_%';
|
||
"""
|
||
# сессия ждёт в pg_sleep на этом запросе: окно открыто
|
||
DF_SLEEPING_SQL = """\
|
||
SELECT count(*) FROM pg_stat_activity
|
||
WHERE wait_event = 'PgSleep' AND state = 'active' AND query ILIKE '{pattern}';
|
||
"""
|
||
DF_WINDOW_WAIT_S = 30
|
||
# job_timeout_seconds + lease_margin_seconds = 70 с и запас на проход relay
|
||
DF_LEASE_WAIT_S = 110
|
||
DF_OPERATOR = "driver-defense-faults"
|
||
DF_RECORD_WAIT_S = 30
|
||
# реестр показывается весь: на рабочем стенде строки прежних прогонов остаются
|
||
DF_REGISTRY_LIMIT = 100000
|
||
# значения — id из ответов API и psql: безопасны в тексте SQL
|
||
DF_JOB_SQL = """\
|
||
SELECT row_to_json(j) FROM (
|
||
SELECT id, state, attempt, attempt_base, last_error_code, published_at,
|
||
updated_at, lease_expires_at,
|
||
extract(epoch FROM lease_expires_at - now()) AS lease_left_seconds
|
||
FROM attachment_jobs WHERE attachment_id = '{attachment_id}'
|
||
) j;
|
||
"""
|
||
DF_REPLAYS_SQL = """\
|
||
SELECT coalesce(json_agg(r), '[]'::json) FROM (
|
||
SELECT r.operator, r.error_code, r.reason, r.attempt
|
||
FROM attachment_job_replays r
|
||
JOIN attachment_jobs j ON j.id = r.job_id
|
||
WHERE j.attachment_id = '{attachment_id}'
|
||
) r;
|
||
"""
|
||
# SHA-256 объектов bucket: процессом в контейнере реплики, ключи API не
|
||
# покидают контейнер. Нет объекта — пустая строка
|
||
DF_OBJECTS_SHA256_PY = """\
|
||
import hashlib
|
||
import json
|
||
import sys
|
||
import botocore.session
|
||
from botocore.config import Config
|
||
from botocore.exceptions import ClientError
|
||
from src.config import settings
|
||
s3 = settings.s3
|
||
client = botocore.session.get_session().create_client(
|
||
"s3",
|
||
endpoint_url=s3.endpoint_url,
|
||
region_name=s3.region,
|
||
aws_access_key_id=s3.access_key_id.get_secret_value(),
|
||
aws_secret_access_key=s3.secret_access_key.get_secret_value(),
|
||
config=Config(s3={"addressing_style": "path"},
|
||
retries={"total_max_attempts": 1}),
|
||
)
|
||
found = {}
|
||
for key in sys.argv[1:]:
|
||
try:
|
||
body = client.get_object(Bucket=s3.bucket, Key=key)["Body"].read()
|
||
except ClientError:
|
||
found[key] = ""
|
||
else:
|
||
found[key] = hashlib.sha256(body).hexdigest()
|
||
print(json.dumps(found))
|
||
"""
|
||
|
||
|
||
def df_job(attachment_id: str) -> dict[str, object]:
|
||
"""Строка задания вложения; нет строки — пустой словарь."""
|
||
out = stand_psql(DF_JOB_SQL.format(attachment_id=attachment_id)).strip()
|
||
return json.loads(out) if out else {}
|
||
|
||
|
||
def df_objects_sha256(keys: list[str]) -> dict[str, str]:
|
||
replicas = compose("ps", "-q", "--status", "running", "api").split()
|
||
if not replicas:
|
||
raise RuntimeError("no running API replica")
|
||
proc = subprocess.run(
|
||
[
|
||
"docker",
|
||
"exec",
|
||
replicas[0],
|
||
"python",
|
||
"-c",
|
||
DF_OBJECTS_SHA256_PY,
|
||
*keys,
|
||
],
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
lines = proc.stdout.strip().splitlines()
|
||
if proc.returncode != 0 or not lines:
|
||
raise RuntimeError("object sha256 probe failed")
|
||
return json.loads(lines[-1])
|
||
|
||
|
||
def df_wait_sleeping(pattern: str) -> bool:
|
||
"""Сессия PostgreSQL ждёт в триггере на этом запросе: окно открыто."""
|
||
deadline = time.monotonic() + DF_WINDOW_WAIT_S
|
||
sql = DF_SLEEPING_SQL.format(pattern=pattern)
|
||
while time.monotonic() < deadline:
|
||
if stand_psql(sql).strip() not in ("", "0"):
|
||
return True
|
||
return False
|
||
|
||
|
||
def df_wait_job(attachment_id: str, state: str) -> dict[str, object]:
|
||
"""Опрос строки задания до этого состояния; срок вышел — последняя."""
|
||
deadline = time.monotonic() + DF_WINDOW_WAIT_S
|
||
job = df_job(attachment_id)
|
||
while job.get("state") != state and time.monotonic() < deadline:
|
||
time.sleep(READY_POLL_S)
|
||
job = df_job(attachment_id)
|
||
return job
|
||
|
||
|
||
def df_wait_empty(queue: str) -> int:
|
||
return wait_queue_messages(queue, exactly=0, timeout=90)
|
||
|
||
|
||
def df_worker_records() -> list[dict[str, object]]:
|
||
return json_records(compose("logs", "--no-log-prefix", "worker"))
|
||
|
||
|
||
def df_replay(*args: str) -> tuple[int, list[dict[str, object]]]:
|
||
"""Команда реестра в одноразовом контейнере relay: код и записи."""
|
||
code, out = detached(
|
||
"docker",
|
||
"compose",
|
||
"run",
|
||
"--rm",
|
||
"--no-deps",
|
||
"-T",
|
||
"relay",
|
||
"replay",
|
||
*args,
|
||
)
|
||
return code, json_records(out)
|
||
|
||
|
||
def df_about(
|
||
records: list[dict[str, object]],
|
||
event: str,
|
||
attachment_id: str,
|
||
) -> list[dict[str, object]]:
|
||
return [
|
||
item
|
||
for item in records
|
||
if item.get("event") == event
|
||
and item.get("attachment_id") == attachment_id
|
||
]
|
||
|
||
|
||
class FaultRun:
|
||
"""Прогон окон: участники, таблица проверок и итог по каждому окну."""
|
||
|
||
def __init__(
|
||
self,
|
||
port: int,
|
||
guard: StandGuard,
|
||
tokens: dict[str, str],
|
||
chat_id: str,
|
||
queue: str,
|
||
database: str,
|
||
) -> None:
|
||
self.port = port
|
||
self.guard = guard
|
||
self.tokens = tokens
|
||
self.chat_id = chat_id
|
||
self.queue = queue
|
||
self.database = database
|
||
self.tag = uuid.uuid4().hex[:8]
|
||
self.data = FIXTURE_PNG.read_bytes()
|
||
self.rows: list[tuple[str, str, str]] = []
|
||
self.windows: list[tuple[str, str, str, str, str]] = []
|
||
self.current = ""
|
||
|
||
def window(self, title: str) -> None:
|
||
self.current = title
|
||
print(f"\nwindow: {title}", flush=True)
|
||
|
||
def action(self, text: str) -> None:
|
||
print(f" action: {text}", flush=True)
|
||
|
||
def check(self, name: str, expected: object, got: object) -> None:
|
||
self.rows.append((f"{self.current}: {name}", str(expected), str(got)))
|
||
mark = (
|
||
"" if str(expected) == str(got) else f" FAIL expected {expected}"
|
||
)
|
||
print(f" {name}: {got}{mark}", flush=True)
|
||
|
||
def result(
|
||
self,
|
||
action: str,
|
||
job: dict[str, object],
|
||
outcome: str,
|
||
) -> None:
|
||
self.windows.append(
|
||
(
|
||
self.current,
|
||
action,
|
||
str(job.get("id")),
|
||
str(job.get("attempt")),
|
||
outcome,
|
||
),
|
||
)
|
||
|
||
def upload(self, suffix: str) -> tuple[str, str]:
|
||
"""Загрузка fixture с уникальным именем: `id` вложения и имя."""
|
||
filename = f"df-{self.tag}-{suffix}.png"
|
||
status, _, payload = upload_bytes(
|
||
self.port,
|
||
self.tokens["alice"],
|
||
self.chat_id,
|
||
self.data,
|
||
content_type="image/png",
|
||
filename=filename,
|
||
)
|
||
self.check("upload", ATTACHMENT_ACCEPTED, status)
|
||
if status != ATTACHMENT_ACCEPTED or not isinstance(payload, dict):
|
||
raise RuntimeError(f"upload {status}")
|
||
print(f" attachment id {payload['id']}", flush=True)
|
||
return str(payload["id"]), filename
|
||
|
||
def meta(self, attachment_id: str) -> object:
|
||
return call(
|
||
self.port,
|
||
"GET",
|
||
f"{ATTACHMENTS}/{attachment_id}",
|
||
token=self.tokens["bob"],
|
||
)[2]
|
||
|
||
def wait_ready(
|
||
self,
|
||
attachment_id: str,
|
||
*,
|
||
timeout: float = READY_WAIT_S,
|
||
) -> dict[str, object]:
|
||
ready = wait_attachment(
|
||
self.port,
|
||
self.tokens["bob"],
|
||
attachment_id,
|
||
timeout=timeout,
|
||
)
|
||
self.check("attachment status", "ready", ready.get("status"))
|
||
return ready
|
||
|
||
def check_variants(self, ready: dict[str, object]) -> None:
|
||
for name, expected, got in variant_checks(
|
||
self.port,
|
||
self.tokens["bob"],
|
||
ready,
|
||
):
|
||
self.check(name, expected, got)
|
||
|
||
def variant_keys(self, attachment_id: str) -> dict[str, str]:
|
||
return {
|
||
name: (
|
||
f"{self.database}/{ATTACHMENT_KEY_PREFIX}/{attachment_id}/"
|
||
f"v1-{name}"
|
||
)
|
||
for name in FIXTURE_VARIANTS
|
||
}
|
||
|
||
def clear_triggers(self) -> None:
|
||
stand_psql(DF_CLEAR_SQL)
|
||
|
||
|
||
def cmd_defense_faults(port: int) -> int:
|
||
"""Спек `student-tests`, «Сценарий защиты автоматизирован», шаг 4, на
|
||
рабочем стенде через LB (design change `pipeline-reliability`, решения 14 и
|
||
17): окна отказа по порядку `test_defense_faults`. Токенов и секретов в выводе
|
||
нет."""
|
||
if not stand_answers(port, "defense-faults"):
|
||
return 2
|
||
return run_guarded(lambda guard: defense_faults(port, guard))
|
||
|
||
|
||
def defense_faults(port: int, guard: StandGuard) -> int:
|
||
"""Тело `cmd_defense_faults`."""
|
||
names = rc_stand()
|
||
if names is None:
|
||
return 1
|
||
_, database = names
|
||
queue = database + QUEUE_SUFFIX
|
||
# остаток прерванного прогона; снимается и при любом исходе
|
||
stand_psql(DF_CLEAR_SQL)
|
||
guard.cleanups.append(lambda: stand_psql(DF_CLEAR_SQL) and None)
|
||
if not ensure_running("worker", "relay"):
|
||
print("FAIL: worker and relay are not running")
|
||
return 1
|
||
people = attachment_people(port, "df")
|
||
if people is None:
|
||
return 1
|
||
_, tokens, chat_id = people
|
||
run = FaultRun(port, guard, tokens, chat_id, queue, database)
|
||
df_after_objects(run)
|
||
df_after_commit(run)
|
||
df_before_publish(run)
|
||
df_after_confirm(run)
|
||
df_replay_failed(run)
|
||
df_replay_ready(run)
|
||
stand_psql(DF_CLEAR_SQL)
|
||
run.current = "end"
|
||
run.check(
|
||
"driver triggers left",
|
||
"0",
|
||
stand_psql(DF_TRIGGERS_LEFT_SQL).strip(),
|
||
)
|
||
print("\nwindow -> action -> job id -> attempts started -> result")
|
||
for row in run.windows:
|
||
print(" " + " -> ".join(row))
|
||
print()
|
||
return report_reconcile(
|
||
run.rows,
|
||
passed="every window finished with the same result, no duplicate effect",
|
||
)
|
||
|
||
|
||
def df_after_objects(run: FaultRun) -> None:
|
||
"""(а) Объекты записаны, фиксация ждёт в триггере: KILL. Новая попытка — по
|
||
аренде — пишет те же ключи теми же байтами."""
|
||
run.window("after writing objects, before COMMIT")
|
||
run.check("queue empty before the window", 0, df_wait_empty(run.queue))
|
||
filename = f"df-{run.tag}-objects.png"
|
||
stand_psql(
|
||
DF_READY_STALL_SQL.format(seconds=DF_STALL_S, filename=filename),
|
||
)
|
||
try:
|
||
status, _, payload = upload_bytes(
|
||
run.port,
|
||
run.tokens["alice"],
|
||
run.chat_id,
|
||
run.data,
|
||
content_type="image/png",
|
||
filename=filename,
|
||
)
|
||
run.check("upload", ATTACHMENT_ACCEPTED, status)
|
||
if status != ATTACHMENT_ACCEPTED or not isinstance(payload, dict):
|
||
raise RuntimeError(f"upload {status}")
|
||
attachment_id = str(payload["id"])
|
||
print(f" attachment id {attachment_id}", flush=True)
|
||
run.check(
|
||
"COMMIT of ready waits in the trigger",
|
||
"yes",
|
||
yes(df_wait_sleeping("UPDATE attachments%")),
|
||
)
|
||
run.action("docker kill worker")
|
||
killed_at = time.monotonic()
|
||
run.check("docker kill worker", 0, run.guard.kill("worker"))
|
||
job = df_job(attachment_id)
|
||
run.check("job state after kill", "processing", job.get("state"))
|
||
run.check("attempt after kill", 1, job.get("attempt"))
|
||
print(f" job id {job.get('id')}", flush=True)
|
||
keys = run.variant_keys(attachment_id)
|
||
before = df_objects_sha256(list(keys.values()))
|
||
for name, key in keys.items():
|
||
print(
|
||
f" {name} sha256 before the crash {before[key]}",
|
||
flush=True,
|
||
)
|
||
run.check(f"{name} object written", "yes", yes(bool(before[key])))
|
||
finally:
|
||
run.clear_triggers()
|
||
lease_left = float(str(job.get("lease_left_seconds") or 0))
|
||
run.action(f"start worker, lease expires in {lease_left:.0f} s")
|
||
run.check("docker start worker", 0, start_service("worker"))
|
||
ready = run.wait_ready(attachment_id, timeout=DF_LEASE_WAIT_S)
|
||
waited = time.monotonic() - killed_at
|
||
print(f" ready {waited:.0f} s after the kill", flush=True)
|
||
run.check(
|
||
"next attempt not before the lease expired",
|
||
"yes",
|
||
yes(waited >= lease_left - 2),
|
||
)
|
||
run.check_variants(ready)
|
||
listed = ready.get("variants")
|
||
by_name = {
|
||
str(item.get("name")): item
|
||
for item in (listed if isinstance(listed, list) else [])
|
||
}
|
||
after = df_objects_sha256(list(keys.values()))
|
||
for name, key in keys.items():
|
||
run.check(f"{name} same sha256 in S3", before[key], after[key])
|
||
run.check(
|
||
f"{name} same sha256 in metadata",
|
||
before[key],
|
||
by_name.get(name, {}).get("sha256"),
|
||
)
|
||
job = df_job(attachment_id)
|
||
run.check("attempt", 2, job.get("attempt"))
|
||
run.check("job state", "succeeded", job.get("state"))
|
||
run.check("queue empty", 0, df_wait_empty(run.queue))
|
||
run.result(
|
||
"kill worker, wait for the lease",
|
||
job,
|
||
str(ready.get("status")),
|
||
)
|
||
|
||
|
||
def df_after_commit(run: FaultRun) -> None:
|
||
"""(б) COMMIT ждёт в отложенном триггере, worker заморожен: строка
|
||
`succeeded` при замороженном клиенте, KILL, ack не ушёл. Следующий запуск
|
||
получает сообщение снова и подтверждает его без эффекта."""
|
||
run.window("after COMMIT, before ack")
|
||
run.check("queue empty before the window", 0, df_wait_empty(run.queue))
|
||
filename = f"df-{run.tag}-commit.png"
|
||
stand_psql(
|
||
DF_COMMIT_STALL_SQL.format(
|
||
seconds=DF_COMMIT_STALL_S,
|
||
filename=filename,
|
||
),
|
||
)
|
||
try:
|
||
status, _, payload = upload_bytes(
|
||
run.port,
|
||
run.tokens["alice"],
|
||
run.chat_id,
|
||
run.data,
|
||
content_type="image/png",
|
||
filename=filename,
|
||
)
|
||
run.check("upload", ATTACHMENT_ACCEPTED, status)
|
||
if status != ATTACHMENT_ACCEPTED or not isinstance(payload, dict):
|
||
raise RuntimeError(f"upload {status}")
|
||
attachment_id = str(payload["id"])
|
||
print(f" attachment id {attachment_id}", flush=True)
|
||
run.check(
|
||
"COMMIT waits in the deferred trigger",
|
||
"yes",
|
||
yes(df_wait_sleeping("COMMIT%")),
|
||
)
|
||
run.action("docker kill -s STOP worker")
|
||
run.check("freeze worker", 0, run.guard.freeze("worker"))
|
||
job = df_wait_job(attachment_id, "succeeded")
|
||
run.check("job state while frozen", "succeeded", job.get("state"))
|
||
print(f" job id {job.get('id')}", flush=True)
|
||
ready = run.meta(attachment_id)
|
||
run.action("docker kill worker")
|
||
run.check("docker kill worker", 0, run.guard.kill("worker"))
|
||
run.check(
|
||
"message returned to the queue (no ack)",
|
||
1,
|
||
wait_queue_messages(run.queue, exactly=1),
|
||
)
|
||
seen = len(df_worker_records())
|
||
finally:
|
||
run.clear_triggers()
|
||
run.action("start worker")
|
||
run.check("docker start worker", 0, start_service("worker"))
|
||
deadline = time.monotonic() + DF_RECORD_WAIT_S
|
||
skipped: list[dict[str, object]] = []
|
||
started: list[dict[str, object]] = []
|
||
while not skipped and time.monotonic() < deadline:
|
||
records = df_worker_records()[seen:]
|
||
skipped = [
|
||
item
|
||
for item in records
|
||
if item.get("event") == "Skipped job message"
|
||
and item.get("job_id") == job.get("id")
|
||
and item.get("reason") == "finished"
|
||
]
|
||
started = [
|
||
item
|
||
for item in records
|
||
if item.get("event") == "Started job attempt"
|
||
and item.get("job_id") == job.get("id")
|
||
]
|
||
time.sleep(READY_POLL_S)
|
||
run.check(
|
||
"redelivered: 'Skipped job message', finished",
|
||
"yes",
|
||
yes(bool(skipped)),
|
||
)
|
||
run.check("new attempts", 0, len(started))
|
||
run.check("queue empty", 0, df_wait_empty(run.queue))
|
||
after = df_job(attachment_id)
|
||
run.check(
|
||
"same updated_at",
|
||
job.get("updated_at"),
|
||
after.get("updated_at"),
|
||
)
|
||
run.check("attempt", 1, after.get("attempt"))
|
||
run.check(
|
||
"metadata unchanged",
|
||
"yes",
|
||
yes(run.meta(attachment_id) == ready),
|
||
)
|
||
if isinstance(ready, dict):
|
||
run.check_variants(ready)
|
||
run.result("freeze and kill worker after COMMIT", after, "ready, no-op")
|
||
|
||
|
||
def df_before_publish(run: FaultRun) -> None:
|
||
"""(в) Relay убит до публикации: 202, сообщения нет, намерение в PostgreSQL;
|
||
relay запущен — `ready`."""
|
||
run.window("after COMMIT queued, before publish")
|
||
run.check("queue empty before the window", 0, df_wait_empty(run.queue))
|
||
run.action("docker kill relay")
|
||
run.check("docker kill relay", 0, run.guard.kill("relay"))
|
||
run.check("relay stays down", "no", yes(bool(service_ids("relay"))))
|
||
attachment_id, _ = run.upload("before-publish")
|
||
job = df_job(attachment_id)
|
||
print(f" job id {job.get('id')}", flush=True)
|
||
run.check("job state", "queued", job.get("state"))
|
||
run.check("published_at", None, job.get("published_at"))
|
||
run.check("messages in the queue", 0, queue_messages(run.queue))
|
||
run.action("start relay")
|
||
run.check("docker start relay", 0, start_service("relay"))
|
||
ready = run.wait_ready(attachment_id)
|
||
run.check_variants(ready)
|
||
job = df_job(attachment_id)
|
||
run.check("attempt", 1, job.get("attempt"))
|
||
run.result(
|
||
"kill relay, upload, start relay",
|
||
job,
|
||
str(ready.get("status")),
|
||
)
|
||
|
||
|
||
def df_after_confirm(run: FaultRun) -> None:
|
||
"""Relay убит после подтверждения брокера до отметки: транзакция отметки
|
||
откатилась. После запуска relay публикует ещё раз; дубль — no-op."""
|
||
run.window("after broker confirm, before the mark")
|
||
run.check("queue empty before the window", 0, df_wait_empty(run.queue))
|
||
run.action("docker compose stop worker")
|
||
compose("stop", "worker")
|
||
filename = f"df-{run.tag}-confirm.png"
|
||
stand_psql(
|
||
DF_RELAY_STALL_SQL.format(seconds=DF_RELAY_STALL_S, filename=filename),
|
||
)
|
||
try:
|
||
status, _, payload = upload_bytes(
|
||
run.port,
|
||
run.tokens["alice"],
|
||
run.chat_id,
|
||
run.data,
|
||
content_type="image/png",
|
||
filename=filename,
|
||
)
|
||
run.check("upload", ATTACHMENT_ACCEPTED, status)
|
||
if status != ATTACHMENT_ACCEPTED or not isinstance(payload, dict):
|
||
raise RuntimeError(f"upload {status}")
|
||
attachment_id = str(payload["id"])
|
||
print(f" attachment id {attachment_id}", flush=True)
|
||
run.check(
|
||
"the mark waits in the trigger",
|
||
"yes",
|
||
yes(df_wait_sleeping("UPDATE attachment_jobs%")),
|
||
)
|
||
run.action("docker kill relay")
|
||
run.check("docker kill relay", 0, run.guard.kill("relay"))
|
||
run.check("message in the queue", 1, queue_messages(run.queue))
|
||
job = df_job(attachment_id)
|
||
print(f" job id {job.get('id')}", flush=True)
|
||
run.check("published_at", None, job.get("published_at"))
|
||
finally:
|
||
run.clear_triggers()
|
||
run.action("start relay")
|
||
run.check("docker start relay", 0, start_service("relay"))
|
||
run.check(
|
||
"two messages with the worker stopped",
|
||
2,
|
||
wait_queue_messages(run.queue, exactly=2),
|
||
)
|
||
run.action("start worker")
|
||
run.check("docker start worker", 0, start_service("worker"))
|
||
ready = run.wait_ready(attachment_id)
|
||
run.check_variants(ready)
|
||
run.check("queue empty", 0, df_wait_empty(run.queue))
|
||
job = df_job(attachment_id)
|
||
run.check("attempt", 1, job.get("attempt"))
|
||
run.result(
|
||
"kill relay after confirm, duplicate",
|
||
job,
|
||
str(ready.get("status")),
|
||
)
|
||
|
||
|
||
def df_replay_failed(run: FaultRun) -> None:
|
||
"""(г) Объект staging заменён — `failed` `processing_failed` — реестр — объект
|
||
возвращён — replay — `ready` с тем же заданием и аудитом."""
|
||
run.window("replay of a failed job")
|
||
run.check("queue empty before the window", 0, df_wait_empty(run.queue))
|
||
run.action("docker compose stop worker")
|
||
compose("stop", "worker")
|
||
attachment_id, _ = run.upload("replay")
|
||
key = (
|
||
f"{run.database}/{STAGING_KEY_PREFIX}/{attachment_id}/"
|
||
f"{ATTACHMENT_ORIGINAL}"
|
||
)
|
||
run.action("staging object replaced with other bytes of the same size")
|
||
run.check(
|
||
"put other bytes",
|
||
0,
|
||
rc_put_object(key, random_bytes(37, len(run.data))),
|
||
)
|
||
run.action("start worker")
|
||
run.check("docker start worker", 0, start_service("worker"))
|
||
failed = wait_attachment(run.port, run.tokens["bob"], attachment_id)
|
||
run.check("attachment status", "failed", failed.get("status"))
|
||
run.check("error_code", "processing_failed", failed.get("error_code"))
|
||
job = df_job(attachment_id)
|
||
print(f" job id {job.get('id')}", flush=True)
|
||
run.check("reason", "source_corrupted", job.get("last_error_code"))
|
||
run.action("replay --error-code processing_failed (registry, dry-run)")
|
||
code, records = df_replay(
|
||
"--error-code",
|
||
"processing_failed",
|
||
"--limit",
|
||
str(DF_REGISTRY_LIMIT),
|
||
)
|
||
print(f" registry: exit {code}", flush=True)
|
||
run.check(
|
||
"registry names the job",
|
||
"yes",
|
||
yes(bool(df_about(records, "Found failed job", attachment_id))),
|
||
)
|
||
run.check("registry changes nothing", job, df_job(attachment_id))
|
||
run.action("original bytes returned to staging")
|
||
run.check("put original bytes", 0, rc_put_object(key, run.data))
|
||
run.action(f"replay --attachment-id {attachment_id} --apply")
|
||
code, records = df_replay(
|
||
"--attachment-id",
|
||
attachment_id,
|
||
"--apply",
|
||
"--operator",
|
||
DF_OPERATOR,
|
||
)
|
||
run.check("replay exit code", 0, code)
|
||
replayed = df_about(records, "Replayed job", attachment_id)
|
||
run.check("'Replayed job' record", "yes", yes(bool(replayed)))
|
||
ready = run.wait_ready(attachment_id)
|
||
run.check_variants(ready)
|
||
status, _, original = call_bytes(
|
||
run.port,
|
||
"GET",
|
||
f"{ATTACHMENTS}/{attachment_id}/content",
|
||
token=run.tokens["bob"],
|
||
)
|
||
run.check("download original", 200, status)
|
||
run.check(
|
||
"original sha256 = uploaded",
|
||
sha256_hex(run.data),
|
||
sha256_hex(original),
|
||
)
|
||
done = df_job(attachment_id)
|
||
run.check("same job", job.get("id"), done.get("id"))
|
||
run.check("attempt", 2, done.get("attempt"))
|
||
run.check("attempt_base", 1, done.get("attempt_base"))
|
||
audit = json.loads(
|
||
stand_psql(DF_REPLAYS_SQL.format(attachment_id=attachment_id)),
|
||
)
|
||
run.check(
|
||
"audit",
|
||
[
|
||
{
|
||
"operator": DF_OPERATOR,
|
||
"error_code": "processing_failed",
|
||
"reason": "source_corrupted",
|
||
"attempt": 1,
|
||
},
|
||
],
|
||
audit,
|
||
)
|
||
run.result("failed, registry, replay", done, str(ready.get("status")))
|
||
|
||
|
||
def df_replay_ready(run: FaultRun) -> None:
|
||
"""Replay готовой работы — отказ, код 3, ничего не изменилось."""
|
||
run.window("replay of a ready job")
|
||
attachment_id, _ = run.upload("replay-ready")
|
||
ready = run.wait_ready(attachment_id)
|
||
job = df_job(attachment_id)
|
||
print(f" job id {job.get('id')}", flush=True)
|
||
run.action(f"replay --attachment-id {attachment_id} --apply")
|
||
code, records = df_replay(
|
||
"--attachment-id",
|
||
attachment_id,
|
||
"--apply",
|
||
"--operator",
|
||
DF_OPERATOR,
|
||
)
|
||
run.check("replay exit code", 3, code)
|
||
refused = df_about(records, "Refused job replay", attachment_id)
|
||
run.check(
|
||
"refusal",
|
||
"already_ready",
|
||
refused[0].get("refusal") if refused else "-",
|
||
)
|
||
run.check(
|
||
"metadata unchanged",
|
||
"yes",
|
||
yes(run.meta(attachment_id) == ready),
|
||
)
|
||
after = df_job(attachment_id)
|
||
run.check("job unchanged", job.get("updated_at"), after.get("updated_at"))
|
||
run.check(
|
||
"audit records",
|
||
0,
|
||
len(
|
||
json.loads(
|
||
stand_psql(DF_REPLAYS_SQL.format(attachment_id=attachment_id)),
|
||
),
|
||
),
|
||
)
|
||
run.result("replay ready", after, "refused, exit 3")
|
||
|
||
|
||
def main() -> int:
|
||
parser = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||
parser.add_argument("--port", type=int, default=DEFAULT_PORT)
|
||
sub = parser.add_subparsers(dest="cmd", required=True)
|
||
for name in ("start", "stop", "status", "flow", "smoke", "student", "all"):
|
||
sub.add_parser(name)
|
||
instances = sub.add_parser("instances")
|
||
instances.add_argument("--count", type=int, default=12)
|
||
inflight = sub.add_parser("kill-inflight")
|
||
inflight.add_argument("--threads", type=int, default=8)
|
||
inflight.add_argument("--seconds", type=float, default=4)
|
||
inflight.add_argument("--after", type=float, default=1.5)
|
||
idle = sub.add_parser("idle-conns")
|
||
idle.add_argument("--threads", type=int, default=20)
|
||
idle.add_argument("--requests", type=int, default=50)
|
||
# [app] keep_alive_seconds реплики
|
||
idle.add_argument("--keep-alive", type=float, default=60)
|
||
# контейнер LB, если --port ведёт не на LB стенда (вариант конфигурации)
|
||
idle.add_argument("--lb")
|
||
sub.add_parser("hang-key")
|
||
cache = sub.add_parser("cache-check")
|
||
cache.add_argument(
|
||
"--require-test-keys",
|
||
action="store_true",
|
||
help="код 1 без ключей тестовой базы (сценарий «Временная база»)",
|
||
)
|
||
sub.add_parser("auth-storage")
|
||
sub.add_parser("s3-check")
|
||
upload = sub.add_parser("upload")
|
||
upload.add_argument("--token", required=True)
|
||
upload.add_argument("--chat", required=True)
|
||
upload.add_argument("--file", required=True)
|
||
upload.add_argument(
|
||
"--type",
|
||
help="Content-Type; по умолчанию — по сигнатуре",
|
||
)
|
||
upload.add_argument("--filename", help="по умолчанию — имя файла")
|
||
download = sub.add_parser("download")
|
||
download.add_argument("--token", required=True)
|
||
download.add_argument("--attachment", required=True)
|
||
download.add_argument("--out", help="сохранить полученные байты")
|
||
download.add_argument("--variant")
|
||
download.add_argument(
|
||
"--wait",
|
||
action="store_true",
|
||
help="сначала опрос метаданных до ready или failed",
|
||
)
|
||
sub.add_parser("defense-scenario")
|
||
broker = sub.add_parser("broker-check")
|
||
broker.add_argument(
|
||
"--require-test-queue",
|
||
action="store_true",
|
||
help="код 1 без очереди временной базы (идёт make test_isolated)",
|
||
)
|
||
sub.add_parser("worker-process")
|
||
sub.add_parser("defense-faults")
|
||
sub.add_parser("relay-process")
|
||
sub.add_parser("pipeline-state")
|
||
failover = sub.add_parser("attachment-failover")
|
||
failover.add_argument("--mode", choices=("stop", "kill"), default="stop")
|
||
sub.add_parser("attachment-storage")
|
||
sub.add_parser("upload-consistency")
|
||
sub.add_parser("reconcile-cycle")
|
||
stress = sub.add_parser("reconcile-stress")
|
||
stress.add_argument("--seconds", type=float, default=40)
|
||
stress.add_argument("--clients", type=int, default=4)
|
||
signal_cmd = sub.add_parser("reconcile-signal")
|
||
signal_cmd.add_argument("--pace", action="store_true")
|
||
signal_cmd.add_argument("--apply", action="store_true")
|
||
idle_s3 = sub.add_parser("s3-idle")
|
||
idle_s3.add_argument("--rounds", type=int, default=3)
|
||
idle_s3.add_argument("--downloads", type=int, default=10)
|
||
idle_s3.add_argument("--puts", type=int, default=12)
|
||
idle_s3.add_argument("--size-mib", type=int, default=4)
|
||
idle_s3.add_argument(
|
||
"--pause-ms",
|
||
type=float,
|
||
default=0.5,
|
||
help="пауза потребителя после блока 64 KiB, мс",
|
||
)
|
||
lbto = sub.add_parser("lb-upload-timeouts")
|
||
lbto.add_argument(
|
||
"--config",
|
||
default=str(ROOT / "infra" / "haproxy" / "haproxy.cfg"),
|
||
help="конфигурация HAProxy (по умолчанию — проекта)",
|
||
)
|
||
lbto.add_argument(
|
||
"--image",
|
||
default="mtusi-messenger:lab5",
|
||
help="образ заглушки реплики (нужен только python)",
|
||
)
|
||
stop = sub.add_parser("stop-at-start")
|
||
stop.add_argument("--image", default="mtusi-messenger:lab5")
|
||
stop.add_argument(
|
||
"--delays",
|
||
default="0.2,0.3,0.4,1.5,5",
|
||
help="паузы после docker run до docker stop, с",
|
||
)
|
||
stop.add_argument(
|
||
"--server-start",
|
||
type=int,
|
||
default=3,
|
||
help="попыток со stop по строке «Started server process»",
|
||
)
|
||
req = sub.add_parser("req")
|
||
req.add_argument("method")
|
||
req.add_argument("path")
|
||
auth = req.add_mutually_exclusive_group()
|
||
auth.add_argument("--token", help="Bearer-токен сессии")
|
||
auth.add_argument("--basic", help="USER:PASS для POST /auth/sessions")
|
||
req.add_argument("--data")
|
||
key = req.add_mutually_exclusive_group()
|
||
key.add_argument("--key", help="Idempotency-Key (повтор отправки)")
|
||
key.add_argument(
|
||
"--no-key",
|
||
action="store_true",
|
||
help="POST сообщения без Idempotency-Key (ожидается 400)",
|
||
)
|
||
args = parser.parse_args()
|
||
port = args.port
|
||
|
||
if args.cmd == "all":
|
||
if cmd_start(port) != 0:
|
||
return 1
|
||
try:
|
||
flow_rc = cmd_flow(port)
|
||
smoke_rc = cmd_smoke(port)
|
||
student_rc = 0
|
||
if (ROOT / "student-tests").is_dir():
|
||
student_rc = cmd_student(port)
|
||
finally:
|
||
cmd_stop(port)
|
||
return flow_rc or smoke_rc or student_rc
|
||
if args.cmd == "req":
|
||
return cmd_req(port, args)
|
||
if args.cmd == "instances":
|
||
return cmd_instances(port, args.count)
|
||
if args.cmd == "kill-inflight":
|
||
return cmd_kill_inflight(
|
||
port,
|
||
threads=args.threads,
|
||
seconds=args.seconds,
|
||
after=args.after,
|
||
)
|
||
if args.cmd == "idle-conns":
|
||
return cmd_idle_conns(
|
||
port,
|
||
threads=args.threads,
|
||
requests=args.requests,
|
||
keep_alive=args.keep_alive,
|
||
lb=args.lb,
|
||
)
|
||
if args.cmd == "hang-key":
|
||
return cmd_hang_key(port)
|
||
if args.cmd == "cache-check":
|
||
return cmd_cache_check(
|
||
port,
|
||
require_test_keys=args.require_test_keys,
|
||
)
|
||
if args.cmd == "auth-storage":
|
||
return cmd_auth_storage(port)
|
||
if args.cmd == "s3-check":
|
||
return cmd_s3_check()
|
||
if args.cmd == "upload":
|
||
return cmd_upload(port, args)
|
||
if args.cmd == "download":
|
||
return cmd_download(port, args)
|
||
if args.cmd == "defense-scenario":
|
||
return cmd_defense_scenario(port)
|
||
if args.cmd == "broker-check":
|
||
return cmd_broker_check(require_test_queue=args.require_test_queue)
|
||
if args.cmd == "worker-process":
|
||
return cmd_worker_process(port)
|
||
if args.cmd == "defense-faults":
|
||
return cmd_defense_faults(port)
|
||
if args.cmd == "relay-process":
|
||
return cmd_relay_process(port)
|
||
if args.cmd == "pipeline-state":
|
||
return cmd_pipeline_state()
|
||
if args.cmd == "attachment-failover":
|
||
return cmd_attachment_failover(port, args.mode)
|
||
if args.cmd == "attachment-storage":
|
||
return cmd_attachment_storage(port)
|
||
if args.cmd == "upload-consistency":
|
||
return cmd_upload_consistency(port)
|
||
if args.cmd == "reconcile-cycle":
|
||
return cmd_reconcile_cycle(port)
|
||
if args.cmd == "reconcile-stress":
|
||
return cmd_reconcile_stress(
|
||
port,
|
||
seconds=args.seconds,
|
||
clients=args.clients,
|
||
)
|
||
if args.cmd == "reconcile-signal":
|
||
return cmd_reconcile_signal(pace=args.pace, apply=args.apply)
|
||
if args.cmd == "s3-idle":
|
||
return cmd_s3_idle(
|
||
port,
|
||
rounds=args.rounds,
|
||
downloads=args.downloads,
|
||
puts=args.puts,
|
||
size_mib=args.size_mib,
|
||
pause_ms=args.pause_ms,
|
||
)
|
||
if args.cmd == "lb-upload-timeouts":
|
||
return cmd_lb_upload_timeouts(args.config, args.image)
|
||
if args.cmd == "stop-at-start":
|
||
return cmd_stop_at_start(
|
||
args.image,
|
||
[float(d) for d in args.delays.split(",") if d],
|
||
args.server_start,
|
||
)
|
||
handlers = {
|
||
"start": cmd_start,
|
||
"stop": cmd_stop,
|
||
"status": cmd_status,
|
||
"flow": cmd_flow,
|
||
"smoke": cmd_smoke,
|
||
"student": cmd_student,
|
||
}
|
||
return handlers[args.cmd](port)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
sys.exit(main())
|