- upload: delete the stored object when ready fails before COMMIT or the pending row is gone (503 instead of 500); unknown COMMIT outcome keeps it - cleaner service (python -m src.cleaner): stale pending rows older than grace (900 s, must exceed 17 s live-upload bound) under FOR UPDATE SKIP LOCKED, object before row, own S3 user with read/delete only - shared session_scope for API and cleaner; early_stop process name - partial index on pending attachments, CREATE INDEX CONCURRENTLY - s3-bootstrap: cleaner user, policy and checks; make env_setup appends missing template variables to an existing .env - failure checks: cleaner on the failure stand, id-list hook actions, five new and three updated tests; driver upload-consistency - sync upload-consistency deltas into main specs (storage-consistency) Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
3248 lines
123 KiB
Python
3248 lines
123 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` (Postgres из compose и
|
||
миграции, Valkey, S3 с bootstrap), затем поднять
|
||
`python -m src` в фоне (console, reload) и дождаться
|
||
/health/ready; лог и pid — /tmp/mtusi-api-<port>.{log,pid}
|
||
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 не осталось; таблица «где → проверка →
|
||
ожидаемо → получено», код 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 …]
|
||
загрузка вложения: статус, X-Instance-Id, тело, SHA-256 файла
|
||
download --token T --attachment A [--out F] [--variant …]
|
||
скачивание оригинала: статус, X-Instance-Id, Content-Type,
|
||
размер и SHA-256 полученного
|
||
attachment-failover [--mode stop|kill] только стенд с LB: спек
|
||
attachments «Принявшая реплика остановлена» — загрузка
|
||
tests/fixtures/sample.png через LB, сообщение со ссылкой,
|
||
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, объект в bucket (weed shell), анонимный
|
||
GET ключа с хоста — 403, docker diff реплик без файлов
|
||
оригиналов; код 1 при расхождении, без LB — код 2
|
||
upload-consistency только стенд с LB: спеки attachments «Порядок
|
||
записи» и storage-consistency — загрузка при docker compose
|
||
pause s3 (503, строка pending), загрузка со сбоем фиксации
|
||
ready (триггер на уникальный filename, 503, объект удалён
|
||
компенсацией), обе строки не видны через API (404), после
|
||
grace 30 с — docker compose run --rm --no-deps cleaner --once,
|
||
ни строк, ни объектов, объектов без строки под префиксом базы
|
||
нет, готовое вложение скачивается с тем же SHA-256; триггер
|
||
снимается в finally и в начале следующего прогона; код 1 при
|
||
расхождении, без LB — код 2
|
||
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 subprocess
|
||
import sys
|
||
import threading
|
||
import time
|
||
import urllib.error
|
||
import urllib.parse
|
||
import urllib.request
|
||
import uuid
|
||
from collections import Counter
|
||
from datetime import datetime, timezone
|
||
from pathlib import Path
|
||
|
||
# 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"
|
||
|
||
|
||
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 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 на путях вложений
|
||
upgrade = subprocess.run(
|
||
["make", "upgrade", "start_cache", "start_s3"],
|
||
cwd=ROOT,
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
if upgrade.returncode != 0:
|
||
print("make upgrade start_cache start_s3 failed:")
|
||
print((upgrade.stdout + upgrade.stderr)[-2000:])
|
||
return 1
|
||
env = os.environ | {"APP__RUN_MODE": "console", "APP__PORT": str(port)}
|
||
with log_path.open("wb") as log:
|
||
proc = subprocess.Popen(
|
||
["uv", "run", "python", "-m", "src"],
|
||
cwd=ROOT,
|
||
env=env,
|
||
stdout=log,
|
||
stderr=subprocess.STDOUT,
|
||
# своя группа процессов: stop гасит uv, reloader и worker разом
|
||
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):
|
||
print(f"up on {base_url(port)} pgid={proc.pid} log={log_path}")
|
||
return 0
|
||
time.sleep(0.25)
|
||
print(f"not ready after 30s; log: {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
|
||
with contextlib.suppress(ProcessLookupError):
|
||
os.killpg(int(pid_path.read_text()), 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
|
||
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): загрузка fixture, сообщение со ссылкой, оригинал
|
||
# Бобу побайтно, 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 == 201 and isinstance(attachment, dict)
|
||
flow.check(
|
||
f"POST {CHATS}/…/attachments -> 201 (upload fixture)",
|
||
uploaded and attachment.get("sha256") == sha256_hex(data),
|
||
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"]],
|
||
)
|
||
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",
|
||
)
|
||
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) -> str:
|
||
"""docker compose рабочего стенда (проект из docker-compose.yml)."""
|
||
proc = subprocess.run(
|
||
["docker", "compose", *args],
|
||
cwd=ROOT,
|
||
input=stdin,
|
||
capture_output=True,
|
||
text=True,
|
||
check=False,
|
||
)
|
||
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"
|
||
# слушающие сокеты контейнера 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}")
|
||
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)
|
||
ATTACHMENT_KEY_PREFIX = "attachments"
|
||
ATTACHMENT_ORIGINAL = "original"
|
||
|
||
|
||
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 sha256_hex(data: bytes) -> str:
|
||
return hashlib.sha256(data).hexdigest()
|
||
|
||
|
||
def cmd_upload(port: int, args: argparse.Namespace) -> int:
|
||
"""Загрузка файла: статус, `X-Instance-Id`, тело, SHA-256 файла."""
|
||
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 == 201 and isinstance(payload, dict):
|
||
print("sha256 matches:", payload.get("sha256") == sha256_hex(data))
|
||
return 0 if status < 400 else 2
|
||
|
||
|
||
def cmd_download(port: int, args: argparse.Namespace) -> int:
|
||
"""Скачивание оригинала: статус, тип, размер, SHA-256 полученного."""
|
||
path = f"{ATTACHMENTS}/{args.attachment}/content"
|
||
if args.variant is not None:
|
||
path += "?" + urllib.parse.urlencode({"variant": args.variant})
|
||
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 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_bytes(
|
||
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", "201", str(status), accepted_by))
|
||
if status != 201 or not isinstance(attachment, dict):
|
||
print(f"FAIL: upload {status}")
|
||
return 1
|
||
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:<4} {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`, объект в bucket, анонимный GET — 403, `docker diff`
|
||
реплик без файлов оригиналов."""
|
||
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_bytes(
|
||
port,
|
||
tokens["alice"],
|
||
chat_id,
|
||
data,
|
||
content_type="image/png",
|
||
filename=filename,
|
||
)
|
||
if status != 201 or not isinstance(attachment, dict):
|
||
print(f"FAIL: upload {status}")
|
||
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') "
|
||
"ORDER BY table_name, ordinal_position;\n",
|
||
).splitlines()
|
||
print("columns of attachment tables:")
|
||
for line in columns:
|
||
print(" " + line.replace("|", " "))
|
||
binary = [
|
||
line.split("|")[1] for line in columns if line.endswith("|bytea")
|
||
]
|
||
rows.append(("bytea columns", "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 = dict(
|
||
line.split("|")
|
||
for line in stand_psql(
|
||
f"SELECT id, object_key FROM attachments WHERE id IN ({ids});\n",
|
||
).splitlines()
|
||
)
|
||
for attachment, filename, instance in uploads:
|
||
attachment_id = str(attachment["id"])
|
||
key = keys.get(attachment_id, "")
|
||
expected = "/".join(
|
||
(
|
||
database,
|
||
ATTACHMENT_KEY_PREFIX,
|
||
attachment_id,
|
||
ATTACHMENT_ORIGINAL,
|
||
),
|
||
)
|
||
print(f"upload via {instance}: object_key {key}")
|
||
rows.append(("object_key form", expected, key))
|
||
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}",
|
||
)
|
||
# «-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",
|
||
),
|
||
)
|
||
replicas = compose("ps", "-q", "api").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
|
||
|
||
|
||
# upload-consistency: имена триггера и функции постоянные — остаток
|
||
# прерванного прогона убирается в начале следующего. Отказ — SQLSTATE 08006:
|
||
# для API это отказ БД (503), а не дефект (500)
|
||
UC_TRIGGER = "driver_uc_fail_ready"
|
||
UC_FAIL_READY_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 = 'ready' THEN
|
||
RAISE EXCEPTION 'driver: attachment ready 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}();
|
||
"""
|
||
# 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) -> set[str]:
|
||
"""`id` вложений с файлом `original` под `<база>/attachments/` bucket
|
||
стенда — по файлам `fs.tree`, а не по каталогам: пустой каталог
|
||
`<id>/` SeaweedFS убирает лишь через ~2 мин после DELETE."""
|
||
tree = weed_shell(
|
||
f"fs.tree /buckets/{bucket}/{database}/{ATTACHMENT_KEY_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): загрузка при замороженном S3 и при сбое фиксации `ready`, их
|
||
строки `pending` не видны через API, компенсация удаляет объект,
|
||
разовый проход уборщика убирает обе загрузки, готовое вложение цело.
|
||
Триггер — только на уникальный `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 != 201 or not isinstance(payload, dict):
|
||
print(f"FAIL: ready upload {status}")
|
||
return 1
|
||
ready = payload
|
||
rows.append(("ready attachment R uploaded", "201", str(status)))
|
||
|
||
# 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. фиксация ready падает: компенсация удаляет объект
|
||
fail_name = f"uc-{tag}-ready-failure.png"
|
||
before = attachment_statuses()
|
||
try:
|
||
stand_psql(
|
||
UC_FAIL_READY_SQL.format(name=UC_TRIGGER, filename=fail_name),
|
||
)
|
||
status, _ = upload(fail_name)
|
||
finally:
|
||
stand_psql(UC_CLEAR_SQL)
|
||
rows.append(("upload with ready failure", "503", str(status)))
|
||
failed = sorted(set(attachment_statuses()) - set(before))
|
||
rows.append(("new pending rows (ready failure)", "1", str(len(failed))))
|
||
if len(failed) != 1:
|
||
print("FAIL: no single pending row of the ready failure")
|
||
return report_rows(rows)
|
||
failed_id = failed[0]
|
||
print(f"pending {failed_id}: {pending_row(failed_id)}")
|
||
stored = stored_attachment_ids(bucket, database)
|
||
rows.append(
|
||
(
|
||
"object after compensation",
|
||
"absent",
|
||
"present" if failed_id in stored 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 прогона
|
||
# строка сбоя ready — младшая из двух: ждём, пока и она старше 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)))
|
||
|
||
# 4. ни строк, ни объектов; объектов без строки нет
|
||
statuses = attachment_statuses()
|
||
stored = stored_attachment_ids(bucket, database)
|
||
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 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))))
|
||
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 ready failure is compensated, "
|
||
"the cleaner removed both uploads, no object without a row, R intact",
|
||
)
|
||
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
|
||
|
||
|
||
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")
|
||
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")
|
||
stop = sub.add_parser("stop-at-start")
|
||
stop.add_argument("--image", default="mtusi-messenger:lab4")
|
||
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 == "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 == "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())
|