Files
mtusi2026lab3/.claude/skills/run-mtusi-messenger/driver.py
T
ricoromaandClaude Opus 5.5 12783aaff1 fix: harden graceful-failover checks found in verify
hang-key names its trigger per run, turns SIGTERM and SIGHUP into an
interrupt so the trigger is always dropped and the replica unpaused, and
prints the cleanup SQL if dropping fails. idle-conns reports who closed
the idle connections and can read the pool of another LB container, so a
variant LB config can be checked against the same replicas. bench_compare
refuses a label measured without the load balancer. Stale numbers removed
from the haproxy.cfg comment.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-11 00:00:54 +03:00

1271 lines
46 KiB
Python
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Драйвер API мессенджера для агента: запуск, сценарий, запросы, остановка.
Только стандартная библиотека. Запускать из корня репозитория:
python3 .claude/skills/run-mtusi-messenger/driver.py [--port N] <cmd>
Команды:
start `make upgrade start_cache` (Postgres из compose и миграции,
Valkey), затем поднять `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 удаления
stop остановить свой экземпляр на порту
all start → flow → smoke → student (если есть student-tests/) → stop
Порт по умолчанию 18080, а не 8080: на 8080 обычно работает стенд
`make run_docker` (HAProxy перед репликами API) или `make run_dev`
пользователя, и их процессы трогать не надо. Экземпляр драйвера пишет в
ту же рабочую базу Postgres. flow, req, smoke, student и instances
работают с любым сервером на порту, в том числе со стендом через
балансировщик (`--port 8080`).
"""
import argparse
import base64
import contextlib
import csv
import http.client
import io
import json
import os
import signal
import subprocess
import sys
import threading
import time
import urllib.error
import urllib.request
import uuid
from collections import Counter
from datetime import UTC, datetime
from pathlib import Path
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 работает, но мимо кэша
upgrade = subprocess.run(
["make", "upgrade", "start_cache"],
cwd=ROOT,
capture_output=True,
text=True,
check=False,
)
if upgrade.returncode != 0:
print("make upgrade start_cache 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)
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)
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")
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)
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())