forked from mtusi2026/mtusi2026lab4
ЛР4
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
"""lab4, уровень 3: upload -> остановка ОБСЛУЖИВШЕЙ загрузку реплики -> download через другую.
|
||||
|
||||
make attachment-failover (= python student-tests/attachment_failover.py)
|
||||
|
||||
Доказывает, что оригинал не лежит на диске реплики: реплика, принявшая файл, остановлена
|
||||
(`docker stop`), а другая реплика отдаёт тот же файл байт в байт (сравнение SHA-256).
|
||||
В конце остановленная реплика запускается обратно (`docker start`).
|
||||
"""
|
||||
import hashlib
|
||||
|
||||
from filegen import upload_when_ready, wait_until
|
||||
from helpers import Client, check, run
|
||||
from stand import api_containers, docker, lb_summary, lb_up_count, ps_table, wait_balanced
|
||||
|
||||
|
||||
def main():
|
||||
api = Client()
|
||||
replicas = wait_balanced(2)
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
reply = upload_when_ready(api, alice, chat, name="failover.png")
|
||||
attachment, served = reply["json"], reply["headers"]["X-Instance-Id"]
|
||||
target = [c for c in replicas if c.startswith(served)]
|
||||
check(len(target) == 1, f"X-Instance-Id {served} does not match a running api container")
|
||||
print(f"uploaded {attachment['size_bytes']} bytes, sha256 {attachment['sha256'][:16]}..., "
|
||||
f"served by api replica {served}")
|
||||
print(ps_table())
|
||||
docker("stop", target[0])
|
||||
try:
|
||||
wait_until(lambda: lb_up_count() == len(replicas) - 1, 30, "HAProxy did not remove the stopped replica")
|
||||
print(f"stopped {served} (docker stop); HAProxy: {lb_summary()}")
|
||||
seen = set()
|
||||
for _ in range(4):
|
||||
got = api.call("GET", f"/api/v1/attachments/{attachment['id']}/content", actor=bob)
|
||||
check(hashlib.sha256(got["bytes"]).hexdigest() == attachment["sha256"], "downloaded file differs")
|
||||
seen.add(got["headers"]["X-Instance-Id"])
|
||||
check(served not in seen, "the stopped replica still answered")
|
||||
print(f"downloaded 4 times through {sorted(seen)}: same SHA-256 as uploaded")
|
||||
finally:
|
||||
docker("start", target[0])
|
||||
wait_balanced(len(replicas))
|
||||
print(f"restored {served}; HAProxy: {lb_summary()}")
|
||||
print(ps_table())
|
||||
print("PASS: the replica that accepted the upload was stopped; another replica returned the same bytes "
|
||||
"(the original lives in S3, not on the replica)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Отозванный токен не «воскресает» из кэша после возвращения Valkey (замечание к MR).
|
||||
|
||||
Запуск: make failure-valkey-pause
|
||||
|
||||
Сценарий преподавателя: Valkey ставится на паузу (docker compose pause) — процесс жив,
|
||||
данные в его памяти сохраняются, но он не отвечает. В это время делается logout: PostgreSQL
|
||||
отзывает сессию, а убрать запись из кэша нельзя. После unpause в кэше всё ещё лежит старая
|
||||
запись «токен -> пользователь». Она не должна снова пропускать этот токен.
|
||||
"""
|
||||
import time
|
||||
|
||||
from helpers import Client, compose, run, wait_ready
|
||||
|
||||
|
||||
def main():
|
||||
api = Client()
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
dave = api.user("dave")
|
||||
for _ in range(2): # запись о сессии dave точно лежит в кэше
|
||||
api.call("GET", "/api/v1/users/me", actor=dave, schema="User")
|
||||
|
||||
print("pausing valkey (docker compose pause valkey): данные в кэше сохраняются")
|
||||
compose("pause", "valkey")
|
||||
try:
|
||||
api.call("GET", "/api/v1/users/me", actor=dave, schema="User") # этот запрос обнаруживает сбой кэша
|
||||
api.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=dave)
|
||||
api.call("GET", "/api/v1/users/me", 401, actor=dave)
|
||||
print("во время паузы: logout -> 204, тот же токен -> 401")
|
||||
finally:
|
||||
print("unpausing valkey")
|
||||
compose("unpause", "valkey")
|
||||
|
||||
wait_ready(api)
|
||||
# Фоновая проверка возвращает кэш в работу в течение 5 с. Смотрим 12 с — дольше, чем она.
|
||||
deadline = time.monotonic() + 12
|
||||
checks = 0
|
||||
while time.monotonic() < deadline:
|
||||
api.call("GET", "/api/v1/users/me", 401, actor=dave)
|
||||
api.call("POST", "/api/v1/chats", 401, actor=dave, body={"title": "x", "member_ids": [dave["id"]]})
|
||||
checks += 1
|
||||
time.sleep(0.5)
|
||||
print(f"после unpause: {checks} проверок за 12 с, отозванный токен всегда 401 (и GET, и POST)")
|
||||
|
||||
api.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
api.message(bob, chat, "после возвращения Valkey")
|
||||
print("действующие токены других пользователей работают")
|
||||
print("PASS: revoked session stays revoked after Valkey comes back with stale data")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,111 @@
|
||||
"""lab3–lab4, уровень 4: проверка устройства стенда по реальным контейнерам и docker compose config.
|
||||
|
||||
make check-stack (= python student-tests/check_stack.py)
|
||||
|
||||
- не меньше 2 работающих реплик api, у них нет опубликованных портов (обойти балансировщик нельзя);
|
||||
- в балансировщике каждая реплика под проверкой готовности, резервных серверов без проверки нет
|
||||
(неготовая реплика не получает запросы ни при каких условиях);
|
||||
- ни у одного сервиса нет container_name (иначе нельзя запустить несколько реплик одного сервиса);
|
||||
- наружу опубликован только балансировщик и только на 127.0.0.1;
|
||||
- у каждого работающего контейнера есть лимиты CPU и RAM;
|
||||
- сети: postgres и valkey только во внутренней сети backend, lb только в edge, api в обеих;
|
||||
- секреты получает только тот, кому они нужны;
|
||||
- версии Docker, Compose и образов (для отчёта).
|
||||
"""
|
||||
import json
|
||||
|
||||
from helpers import check, run
|
||||
from stand import api_containers, compose_config, compose_output, docker, inspect, lb_rows
|
||||
|
||||
|
||||
def main():
|
||||
config = compose_config()
|
||||
services = config["services"]
|
||||
networks = config.get("networks", {})
|
||||
|
||||
print("docker: " + docker("version", "--format", "{{.Server.Version}}"))
|
||||
print("compose: " + compose_output("version", "--short").strip())
|
||||
|
||||
check(not [name for name, svc in services.items() if "container_name" in svc], "container_name is set")
|
||||
print("container_name: not set for any service (replicas of one service are possible)")
|
||||
|
||||
replicas = api_containers()
|
||||
check(len(replicas) >= 2, f"need >= 2 running api replicas, got {len(replicas)}")
|
||||
print(f"api replicas running: {len(replicas)} -> {[c[:12] for c in replicas]} "
|
||||
f"(deploy.replicas = {services['api'].get('deploy', {}).get('replicas')})")
|
||||
|
||||
print()
|
||||
print(f"{'service':<14} {'container':<13} {'cpus':>5} {'memory':>8} {'published ports':<34} networks")
|
||||
published = {}
|
||||
for container in sorted(compose_output("ps", "-q").split()):
|
||||
service = inspect(container, '{{index .Config.Labels "com.docker.compose.service"}}')
|
||||
nano_cpus = int(inspect(container, "{{.HostConfig.NanoCpus}}") or 0)
|
||||
memory = int(inspect(container, "{{.HostConfig.Memory}}") or 0)
|
||||
ports = json.loads(inspect(container, "{{json .NetworkSettings.Ports}}") or "{}") or {}
|
||||
bindings = [f"{b['HostIp']}:{b['HostPort']}->{port}" for port, items in ports.items() for b in (items or [])]
|
||||
nets = sorted(json.loads(inspect(container, "{{json .NetworkSettings.Networks}}") or "{}"))
|
||||
nets = [name.split("_", 1)[-1] for name in nets]
|
||||
published[service] = published.get(service, []) + bindings
|
||||
print(f"{service:<14} {container[:12]:<13} {nano_cpus / 1e9:>5.2f} {memory // 2**20:>6}Mi "
|
||||
f"{', '.join(bindings) or '-':<34} {', '.join(nets)}")
|
||||
check(nano_cpus > 0 and memory > 0, f"{service} {container[:12]} has no CPU/RAM limit")
|
||||
print()
|
||||
|
||||
check(not published.get("api"), "api publishes ports and can be reached bypassing the balancer")
|
||||
others = {service: ports for service, ports in published.items() if ports and service != "lb"}
|
||||
check(not others, f"only the balancer may publish ports, got {others}")
|
||||
check(published.get("lb") and all(b.startswith("127.0.0.1:") for b in published["lb"]),
|
||||
"the balancer must be published on 127.0.0.1 only")
|
||||
print("published: only lb, only on 127.0.0.1 (api replicas have no ports)")
|
||||
|
||||
servers = lb_rows("api")
|
||||
backups = [row["svname"] for row in servers if row.get("bck") == "1"]
|
||||
unchecked = [row["svname"] for row in servers
|
||||
if not row.get("status", "").startswith("MAINT") and not row.get("check_status")]
|
||||
check(not backups, f"backup servers in the balancer: {backups}")
|
||||
check(not unchecked, f"servers without a readiness check in the balancer: {unchecked}")
|
||||
in_use = [f"{row['svname']} {row['status']} ({row['check_status']})" for row in servers
|
||||
if not row.get("status", "").startswith("MAINT")]
|
||||
print(f"balancer: every api server is under the /health/ready check, no backup servers -> {', '.join(in_use)}")
|
||||
print("limits: every running container has CPU and RAM limits")
|
||||
|
||||
def nets_of(name):
|
||||
return sorted(services[name].get("networks", {}))
|
||||
|
||||
check(all(nets_of(name) == ["backend"] for name in ("postgres", "valkey", "s3", "s3-init")),
|
||||
"stores must be on backend only")
|
||||
check(nets_of("lb") == ["edge"], "lb must be on edge only")
|
||||
check(nets_of("api") == ["backend", "edge"], "api must be on edge and backend")
|
||||
check(networks.get("backend", {}).get("internal") is True, "backend network must be internal")
|
||||
print("networks: lb -> edge; api -> edge + backend; postgres, valkey, s3 -> backend (internal: no way out)")
|
||||
|
||||
# lab4: S3 без портов наружу и без веб-консоли; версии образов закреплены.
|
||||
s3 = services["s3"]
|
||||
check(not s3.get("ports"), "s3 must not publish ports")
|
||||
command = s3.get("command", [])
|
||||
check("-ip.bind=127.0.0.1" in command and "-s3.iam=false" in command,
|
||||
"SeaweedFS master/filer UIs must listen on 127.0.0.1 only and IAM API must be off")
|
||||
check(not s3["image"].endswith(":latest") and ":" in s3["image"], "s3 image must be pinned")
|
||||
check(any(v.get("source") == "s3data" for v in s3.get("volumes", [])), "s3 must use the persistent volume s3data")
|
||||
print("s3: no published ports; master/filer web UIs only on 127.0.0.1 inside the container; IAM API off; "
|
||||
"pinned image; volume s3data")
|
||||
|
||||
def secrets_of(name):
|
||||
return sorted(item["source"] for item in services[name].get("secrets", []))
|
||||
|
||||
expected = {"api": ["cache_url", "database_url", "s3_access_key_id", "s3_secret_access_key"],
|
||||
"migrate": ["database_url"], "lb": [],
|
||||
"postgres": ["postgres_password"], "valkey": ["valkey_acl"],
|
||||
"s3": ["s3_config"],
|
||||
"s3-init": ["s3_root_password", "s3_root_user"]}
|
||||
for name, wanted in expected.items():
|
||||
check(secrets_of(name) == wanted, f"{name} secrets {secrets_of(name)} != {wanted}")
|
||||
print("secrets: " + "; ".join(f"{name} -> {', '.join(wanted) or 'none'}" for name, wanted in expected.items()))
|
||||
print("images: " + "; ".join(f"{name} {services[name]['image']}" for name in ("lb", "api", "postgres", "valkey", "s3")))
|
||||
print("PASS: one entry point (lb on 127.0.0.1), >= 2 api replicas without ports and container_name, "
|
||||
"only ready replicas get traffic, CPU/RAM limits everywhere, stores (incl. S3) only on the internal network, "
|
||||
"S3 admin credentials only in s3-init")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,150 @@
|
||||
"""Интеграционные тесты хранилища на настоящей PostgreSQL (уровень 4).
|
||||
|
||||
Выполняются ВНУТРИ контейнера приложения (там есть psycopg и доступ к БД по сети стенда):
|
||||
make db-test == docker compose --profile tools run --rm db-test
|
||||
|
||||
Что проверяется:
|
||||
- повторный запуск миграций ничего не меняет;
|
||||
- составная операция «создать чат» откатывается целиком, если упала на середине;
|
||||
- одновременная регистрация одного username даёт ровно одного пользователя;
|
||||
- сама база не даёт записать сообщение от не-участника (внешний ключ);
|
||||
- (lab3) 20 одновременных add_message с одним Idempotency-Key создают одну строку;
|
||||
- (lab3) тот же ключ с другим телом — Conflict (409), строка одна;
|
||||
- (lab3) миграция 004 совместима со старой версией: INSERT сообщения без ключа, как делает
|
||||
код lab2, по-прежнему работает (поэтому миграцию можно применить до замены реплик).
|
||||
"""
|
||||
import hashlib
|
||||
import threading
|
||||
import unittest
|
||||
import uuid
|
||||
from unittest import mock
|
||||
|
||||
import psycopg
|
||||
from psycopg import errors as pg_errors
|
||||
|
||||
from messenger import config, db
|
||||
from messenger.errors import Conflict, InvalidRequest
|
||||
from messenger.store import PostgresStore
|
||||
|
||||
|
||||
class StoreIntegrationTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
config.validate()
|
||||
db.migrate()
|
||||
cls.pool = db.create_pool()
|
||||
cls.pool.open(wait=True)
|
||||
cls.store = PostgresStore(cls.pool)
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.pool.close()
|
||||
|
||||
def scalar(self, sql, *params):
|
||||
with self.pool.connection() as conn:
|
||||
return conn.execute(sql, params).fetchone()[0]
|
||||
|
||||
def new_user(self):
|
||||
return self.store.create_user("db_" + uuid.uuid4().hex[:12], "DB test", "not-a-real-hash")
|
||||
|
||||
def test_migrations_rerun_is_noop(self):
|
||||
versions = self.scalar("SELECT array_agg(version ORDER BY version) FROM schema_migrations")
|
||||
users = self.scalar("SELECT count(*) FROM users")
|
||||
self.assertEqual(db.migrate(), []) # второй прогон: применять нечего
|
||||
self.assertEqual(self.scalar("SELECT array_agg(version ORDER BY version) FROM schema_migrations"), versions)
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM users"), users)
|
||||
print(f"\n schema_migrations: {versions}; повторный migrate() ничего не применил")
|
||||
|
||||
def test_create_chat_rolls_back_when_failing_midway(self):
|
||||
alice = self.new_user()
|
||||
ghost = str(uuid.uuid4()) # такого пользователя нет
|
||||
title = "rollback-" + uuid.uuid4().hex[:8]
|
||||
# Отключаем предварительную проверку участников, чтобы ошибка случилась ВНУТРИ транзакции:
|
||||
# строка чата уже вставлена, а вставка участника-призрака нарушает внешний ключ.
|
||||
with mock.patch.object(PostgresStore, "_check_members_exist", staticmethod(lambda conn, members: None)):
|
||||
with self.assertRaises(InvalidRequest):
|
||||
self.store.create_chat(alice.id, title, [alice.id, ghost])
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM chats WHERE title = %s", title), 0)
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM chat_members WHERE user_id = %s", uuid.UUID(alice.id)), 0)
|
||||
print("\n чат с несуществующим участником: транзакция откатилась, строк chats/chat_members не осталось")
|
||||
|
||||
def test_concurrent_registration_has_one_winner(self):
|
||||
username = "dbrace_" + uuid.uuid4().hex[:10]
|
||||
threads, barrier, results = 20, threading.Barrier(20), []
|
||||
|
||||
def register():
|
||||
barrier.wait()
|
||||
try:
|
||||
self.store.create_user(username, "Race", "not-a-real-hash")
|
||||
results.append("created")
|
||||
except Conflict:
|
||||
results.append("conflict")
|
||||
|
||||
workers = [threading.Thread(target=register) for _ in range(threads)]
|
||||
for w in workers:
|
||||
w.start()
|
||||
for w in workers:
|
||||
w.join()
|
||||
self.assertEqual(results.count("created"), 1)
|
||||
self.assertEqual(results.count("conflict"), threads - 1)
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM users WHERE username = %s", username), 1)
|
||||
print(f"\n {threads} параллельных create_user: 1 создан, {threads - 1} получили Conflict (409)")
|
||||
|
||||
def test_concurrent_same_idempotency_key_creates_one_row(self):
|
||||
alice = self.new_user()
|
||||
chat = self.store.create_chat(alice.id, "idem", [alice.id])
|
||||
key, digest = "db-" + uuid.uuid4().hex, hashlib.sha256(b"same body").digest()
|
||||
threads, barrier, results, errors = 20, threading.Barrier(20), [], []
|
||||
|
||||
def send():
|
||||
barrier.wait()
|
||||
try:
|
||||
results.append(self.store.add_message(alice.id, chat.id, "один раз", key, digest))
|
||||
except Exception as exc: # noqa: BLE001 — любая ошибка = провал теста
|
||||
errors.append(exc)
|
||||
|
||||
workers = [threading.Thread(target=send) for _ in range(threads)]
|
||||
for w in workers:
|
||||
w.start()
|
||||
for w in workers:
|
||||
w.join()
|
||||
self.assertEqual(errors, [])
|
||||
self.assertEqual(len({message.id for message, _ in results}), 1)
|
||||
self.assertEqual(sum(1 for _, replayed in results if not replayed), 1)
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM messages WHERE chat_id = %s", uuid.UUID(chat.id)), 1)
|
||||
print(f"\n {threads} одновременных add_message с одним ключом: 1 строка, 1 новое + "
|
||||
f"{threads - 1} повторов с тем же сообщением")
|
||||
|
||||
def test_same_key_other_body_is_conflict(self):
|
||||
alice = self.new_user()
|
||||
chat = self.store.create_chat(alice.id, "idem409", [alice.id])
|
||||
key = "db-" + uuid.uuid4().hex
|
||||
self.store.add_message(alice.id, chat.id, "первый", key, hashlib.sha256(b"first").digest())
|
||||
with self.assertRaises(Conflict):
|
||||
self.store.add_message(alice.id, chat.id, "другой", key, hashlib.sha256(b"other").digest())
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM messages WHERE chat_id = %s", uuid.UUID(chat.id)), 1)
|
||||
print("\n тот же ключ с другим телом: Conflict (409), в базе по-прежнему одна строка")
|
||||
|
||||
def test_old_version_insert_without_key_still_works(self):
|
||||
alice = self.new_user()
|
||||
chat = self.store.create_chat(alice.id, "compat", [alice.id])
|
||||
with psycopg.connect(config.DATABASE_URL) as conn:
|
||||
for _ in range(2): # две строки без ключа: NULL не нарушает уникальность
|
||||
conn.execute("INSERT INTO messages (id, chat_id, sender_id, text) VALUES (%s, %s, %s, %s)",
|
||||
(uuid.uuid4(), uuid.UUID(chat.id), uuid.UUID(alice.id), b"lab2 style"))
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM messages WHERE chat_id = %s AND idempotency_key IS NULL",
|
||||
uuid.UUID(chat.id)), 2)
|
||||
print("\n INSERT как в lab2 (без ключа) после миграции 004 работает: старая версия совместима со схемой")
|
||||
|
||||
def test_database_rejects_message_from_non_member(self):
|
||||
alice, mallory = self.new_user(), self.new_user()
|
||||
chat = self.store.create_chat(alice.id, "fk", [alice.id])
|
||||
with self.assertRaises(pg_errors.ForeignKeyViolation):
|
||||
with psycopg.connect(config.DATABASE_URL) as conn:
|
||||
conn.execute("INSERT INTO messages (id, chat_id, sender_id, text) VALUES (%s, %s, %s, 'x')",
|
||||
(uuid.uuid4(), uuid.UUID(chat.id), uuid.UUID(mallory.id)))
|
||||
print("\n INSERT сообщения от не-участника напрямую в БД: ForeignKeyViolation")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,44 @@
|
||||
"""Демонстрация для защиты: пользователи, вход, чат, сообщения, logout — через балансировщик.
|
||||
|
||||
Запуск: make demo (печатает шаги; пароли и токены не выводятся)
|
||||
У каждого шага в скобках — какая реплика API ответила (X-Instance-Id = ID контейнера в `make ps`).
|
||||
"""
|
||||
import uuid
|
||||
|
||||
from helpers import Client, read_history, run
|
||||
|
||||
|
||||
def main():
|
||||
api = Client()
|
||||
|
||||
def who(reply):
|
||||
return reply["headers"]["X-Instance-Id"]
|
||||
|
||||
ready = api.call("GET", "/health/ready", schema="Health")
|
||||
print(f"1. /health/ready -> 200 ({who(ready)}): API запущен, PostgreSQL доступна, схема актуальна")
|
||||
alice, bob, eve, chat = api.bootstrap() # регистрация с паролем + вход через Basic у каждого
|
||||
for name, actor in (("alice", alice), ("bob", bob), ("eve", eve)):
|
||||
print(f"2. зарегистрирован {name}: {actor['user']['username']}, вход через Basic -> Bearer-токен")
|
||||
print(f"3. alice создала чат {chat['id']} с bob (eve не участник)")
|
||||
served = [who(api.call("GET", "/api/v1/users/me", actor=alice, schema="User")) for _ in range(4)]
|
||||
print(f"4. один и тот же токен alice, 4 запроса -> реплики {served}: повторный вход не нужен")
|
||||
key = uuid.uuid4().hex
|
||||
first = api.message(alice, chat, "Привет, Боб! Это сообщение лежит в PostgreSQL", key=key)
|
||||
again = api.message(alice, chat, "Привет, Боб! Это сообщение лежит в PostgreSQL", key=key)
|
||||
print(f"5. alice отправила сообщение ({who(first)}) и повторила его с тем же Idempotency-Key "
|
||||
f"({who(again)}): тот же id {again['json']['id'] == first['json']['id']}")
|
||||
api.message(bob, chat, "Привет, Алиса! Переживёт перезапуск и отказ реплики")
|
||||
history, pages = read_history(api, bob, chat["id"], limit=1)
|
||||
print(f"6. история чата (по 1 сообщению на страницу, страниц: {pages}) — дубля нет:")
|
||||
names = {alice["id"]: "alice", bob["id"]: "bob"}
|
||||
for m in history:
|
||||
print(f" {m['created_at']} {names[m['sender_id']]}: {m['text']}")
|
||||
api.call("GET", f"/api/v1/chats/{chat['id']}/messages", 404, actor=eve)
|
||||
print("7. eve читает чужой чат -> 404 (существование чата не раскрывается)")
|
||||
api.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=alice)
|
||||
after = [who(api.call("GET", "/api/v1/users/me", 401, actor=alice)) for _ in range(2)]
|
||||
print(f"8. alice logout -> 204, тот же токен -> 401 на репликах {after}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,137 @@
|
||||
"""Отказ зависимости (уровень 4). Запуск: make failure-valkey или make failure-postgres
|
||||
|
||||
Тест сам останавливает указанный контейнер (docker compose stop), проверяет поведение API
|
||||
и запускает контейнер обратно (docker compose start). Volumes не трогаются.
|
||||
|
||||
valkey — кэш недоступен: API обходит его и работает через PostgreSQL; logout действует сразу.
|
||||
postgres — источник истины недоступен: обе реплики не готовы (/health/ready = 503), и балансировщик
|
||||
исключает их из маршрутизации. Даже запрос с действующим токеном, который реплика могла бы
|
||||
подтвердить из кэша Valkey, через балансировщик получает 503 и до реплики не доходит
|
||||
(замечание к MR: раньше резервные слоты без проверки пропускали его, и он получал 200).
|
||||
Сами реплики при этом живы (/health/live = 200 изнутри контейнера).
|
||||
Запись во время отказа не сохраняется. После запуска БД прежний токен и данные доступны.
|
||||
"""
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from helpers import Client, check, compose, idempotency, read_history, run, wait_ready
|
||||
from stand import api_containers, lb_summary, lb_up_count, replica_status, try_call
|
||||
|
||||
LB_EXCLUDE_TIMEOUT_SECONDS = 15
|
||||
LOST_TEXT = "во время отказа PostgreSQL, не должно сохраниться " + uuid.uuid4().hex
|
||||
|
||||
|
||||
def timed(fn):
|
||||
started = time.monotonic()
|
||||
result = fn()
|
||||
return result, (time.monotonic() - started) * 1000
|
||||
|
||||
|
||||
def valkey_down(api, alice, bob, chat):
|
||||
ready, ms = timed(lambda: api.call("GET", "/health/ready", schema="Health"))
|
||||
print(f"/health/ready -> 200 ({ms:.0f} ms): Valkey не критичен, API готов")
|
||||
_, ms = timed(lambda: api.call("GET", "/api/v1/users/me", actor=alice, schema="User"))
|
||||
print(f"existing token: GET /users/me -> 200 ({ms:.0f} ms), сессия проверена по PostgreSQL (этот запрос и обнаружил сбой кэша)")
|
||||
sent = api.message(bob, chat, "во время отказа Valkey")["json"]
|
||||
history, _ = read_history(api, alice, chat["id"])
|
||||
check(sent["id"] in [m["id"] for m in history], "message written during Valkey outage is missing")
|
||||
print("POST message -> 201, история читается")
|
||||
carol = api.user("carol") # регистрация и вход тоже работают без кэша
|
||||
print("register + login new user -> 201")
|
||||
api.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=carol)
|
||||
api.call("GET", "/api/v1/users/me", 401, actor=carol)
|
||||
print("logout -> 204, затем тот же токен -> 401 (отзыв записан в PostgreSQL)")
|
||||
latencies = [timed(lambda: api.call("GET", "/api/v1/users/me", actor=alice))[1] for _ in range(10)]
|
||||
print(f"10 x GET /users/me без кэша: max {max(latencies):.0f} ms (кэш не ждём на каждом запросе)")
|
||||
check(max(latencies) < 1000, "requests must not wait for the dead cache on every call")
|
||||
# Фоновая проверка Valkey идёт раз в 5 с. Ждём дольше и убеждаемся, что запросы её не ждут.
|
||||
time.sleep(6)
|
||||
latencies = [timed(lambda: api.call("GET", "/api/v1/users/me", actor=alice))[1] for _ in range(10)]
|
||||
print(f"через 6 с, ещё 10 x GET /users/me: max {max(latencies):.0f} ms (повторные попытки — в фоне)")
|
||||
check(max(latencies) < 1000, "periodic reconnect attempts must not block user requests")
|
||||
return carol
|
||||
|
||||
|
||||
def refused_by_lb(method, path, token=None, body=None, headers=None):
|
||||
"""Запрос через балансировщик: ждём 503 от САМОГО балансировщика в формате ошибки контракта.
|
||||
|
||||
Признак того, что запрос не дошёл до реплики API: в ответе нет X-Instance-Id
|
||||
(его ставит каждая реплика), а X-Request-Id и request_id в теле — от балансировщика.
|
||||
"""
|
||||
reply = try_call(method, path, token=token, body=body, headers=headers, timeout=5)
|
||||
check(reply is not None, f"{method} {path}: no response from the balancer")
|
||||
check(reply.status == 503, f"{method} {path}: expected 503 from the balancer, got {reply.status}")
|
||||
check(not reply.instance, f"{method} {path}: answered by a NOT READY API replica {reply.instance}")
|
||||
error = (reply.json or {}).get("error") or {}
|
||||
check(error.get("code") == "unavailable", f"{method} {path}: wrong error format {reply.json}")
|
||||
check(error.get("request_id") and error["request_id"] == reply.headers.get("x-request-id"),
|
||||
f"{method} {path}: request_id differs from X-Request-Id")
|
||||
|
||||
|
||||
def postgres_down(api, alice, chat):
|
||||
started = time.monotonic()
|
||||
while lb_up_count() > 0:
|
||||
check(time.monotonic() - started < LB_EXCLUDE_TIMEOUT_SECONDS,
|
||||
f"HAProxy still routes to a replica {LB_EXCLUDE_TIMEOUT_SECONDS} s after the failure")
|
||||
time.sleep(0.2)
|
||||
print(f"HAProxy вывел все реплики из балансировки через {time.monotonic() - started:.1f} с "
|
||||
f"после остановки PostgreSQL ({lb_summary()})")
|
||||
for container in api_containers():
|
||||
live, ready = replica_status(container, "/health/live"), replica_status(container, "/health/ready")
|
||||
check(live == 200 and ready == 503, f"replica {container[:12]}: live {live}, ready {ready}")
|
||||
print(f"реплика {container[:12]} изнутри контейнера: /health/live -> {live}, /health/ready -> {ready} "
|
||||
f"(жива, но не готова)")
|
||||
# Главное (замечание к MR): токен alice лежит в кэше Valkey, и реплика могла бы ответить 200 без базы.
|
||||
refused_by_lb("GET", "/api/v1/users/me", token=alice["token"])
|
||||
print("GET /users/me с действующим токеном (он есть в кэше) -> 503 от балансировщика, без X-Instance-Id: "
|
||||
"до неготовой реплики запрос не дошёл")
|
||||
refused_by_lb("GET", "/api/v1/chats", token=alice["token"])
|
||||
refused_by_lb("GET", f"/api/v1/chats/{chat['id']}/messages", token=alice["token"])
|
||||
refused_by_lb("POST", f"/api/v1/chats/{chat['id']}/messages", token=alice["token"],
|
||||
body={"text": LOST_TEXT}, headers=idempotency())
|
||||
print("бизнес-запросы (список чатов, история, отправка сообщения) -> 503 от балансировщика")
|
||||
refused_by_lb("GET", "/api/v1/users/me")
|
||||
refused_by_lb("POST", "/api/v1/users", body={"username": "pg_" + uuid.uuid4().hex[:10],
|
||||
"display_name": "x", "password": "Pg-down-password"})
|
||||
refused_by_lb("GET", "/health/ready")
|
||||
print("без токена, регистрация и /health/ready через балансировщик -> 503: успешного ответа нет ни у кого")
|
||||
|
||||
|
||||
def main():
|
||||
target = sys.argv[1] if len(sys.argv) > 1 else ""
|
||||
check(target in ("valkey", "postgres"), "usage: dependency_failure.py valkey|postgres")
|
||||
api = Client()
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
before = api.message(alice, chat, "до отказа " + target)["json"]
|
||||
for _ in range(4): # запись о сессии alice точно лежит в общем кэше Valkey
|
||||
api.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
|
||||
print(f"stopping {target} (docker compose stop {target})")
|
||||
compose("stop", target)
|
||||
try:
|
||||
if target == "valkey":
|
||||
carol = valkey_down(api, alice, bob, chat)
|
||||
else:
|
||||
postgres_down(api, alice, chat)
|
||||
finally:
|
||||
print(f"starting {target} again")
|
||||
compose("start", target)
|
||||
|
||||
wait_ready(api)
|
||||
history, _ = read_history(api, alice, chat["id"])
|
||||
check(before in history, "message confirmed before the outage is lost or changed")
|
||||
check(all(m["text"] != LOST_TEXT for m in history), "a write refused during the outage was stored")
|
||||
api.call("GET", "/api/v1/users/me", actor=alice, schema="User")
|
||||
if target == "valkey":
|
||||
api.call("GET", "/api/v1/users/me", 401, actor=carol) # отозванный токен не «воскрес» из кэша
|
||||
print("after recovery: прежний токен работает, подтверждённые сообщения на месте")
|
||||
if target == "postgres":
|
||||
print("PASS: postgres outage: not ready replicas were excluded by the balancer, no request reached them, "
|
||||
"nothing was stored; data and the existing token survived")
|
||||
else:
|
||||
print("PASS: valkey outage handled without the cache; revoked tokens stay revoked")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,46 @@
|
||||
"""Проверка истечения сессии при коротком TTL (уровень 4). Запуск: make expiry
|
||||
|
||||
Нужен второй экземпляр API с SESSION_TTL_SECONDS=2 (сервис api-short-ttl, make expiry
|
||||
поднимает его сам). С lab3 он, как и основные реплики, доступен только через балансировщик:
|
||||
127.0.0.1:8081. База и кэш общие с основным API.
|
||||
|
||||
Сценарий: вход -> токен работает (и попадает в кэш Valkey) -> ждём истечения ->
|
||||
токен отклоняется с 401 и на коротком, и на основном API. Значит, срок жизни — свойство
|
||||
сессии в PostgreSQL, а кэш не продлевает её.
|
||||
"""
|
||||
import datetime as dt
|
||||
import os
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from helpers import Client, check, login, run, wait_ready
|
||||
|
||||
|
||||
def main():
|
||||
short = Client(os.environ.get("BASE_URL_TTL", "http://127.0.0.1:8081"))
|
||||
main_api = Client()
|
||||
# Контейнер уже healthy, но балансировщику нужно ещё пару секунд: найти его по DNS
|
||||
# и пройти 2 проверки готовности. Ждём готовности именно через балансировщик (:8081).
|
||||
wait_ready(short, seconds=60)
|
||||
body = {"username": "ttl_" + uuid.uuid4().hex[:12], "display_name": "TTL", "password": "Ttl-password-123"}
|
||||
short.call("POST", "/api/v1/users", 201, body=body, schema="User")
|
||||
session = login(short, body["username"], body["password"])
|
||||
auth = {"Authorization": "Bearer " + session["token"]}
|
||||
expires_at = dt.datetime.fromisoformat(session["expires_at"].replace("Z", "+00:00"))
|
||||
ttl = (expires_at - dt.datetime.now(dt.timezone.utc)).total_seconds()
|
||||
print(f"session issued by short-TTL API, expires in {ttl:.2f}s")
|
||||
check(0 < ttl <= 3, "short-TTL instance must issue ~2 second sessions")
|
||||
|
||||
for api in (short, short, main_api): # два раза подряд: второй ответ уже из кэша
|
||||
api.call("GET", "/api/v1/users/me", 200, headers=auth, schema="User")
|
||||
print("before expiry: GET /users/me -> 200 (short API twice, main API once)")
|
||||
|
||||
time.sleep(max(0.0, (expires_at - dt.datetime.now(dt.timezone.utc)).total_seconds()) + 1.0)
|
||||
for api in (short, main_api):
|
||||
api.call("GET", "/api/v1/users/me", 401, headers=auth) # клиент проверяет WWW-Authenticate: Bearer
|
||||
print("after expiry: GET /users/me -> 401 on both instances")
|
||||
print("PASS: session expired after SESSION_TTL_SECONDS; cache did not extend it")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,148 @@
|
||||
"""lab3, уровень 4: по очереди останавливаем КАЖДУЮ реплику API под нагрузкой и меряем.
|
||||
|
||||
make failover-metrics (= python student-tests/failover_metrics.py: stop и kill)
|
||||
python student-tests/failover_metrics.py stop (только плановая остановка)
|
||||
|
||||
Режимы:
|
||||
stop — docker stop (SIGTERM): плановая остановка. Реплика сначала отвечает 503 на /health/ready,
|
||||
HAProxy выводит её из балансировки, и только потом она закрывает приём (__main__.py).
|
||||
kill — docker kill (SIGKILL): авария. Процесс умирает сразу, начатые на нём запросы обрываются,
|
||||
клиент повторяет их с тем же Idempotency-Key.
|
||||
Нагрузка (loadgen.py): 4 потока пишут сообщения без пауз, 1 поток читает историю, timeout клиента 2 с.
|
||||
Меряем: успешные записи в секунду до и после отказа, ошибки и их коды, через сколько HAProxy вывел
|
||||
реплику (по его статистике, опрос раз в 0,1 с), через сколько прекратились ошибки, отвечала ли
|
||||
остановленная реплика после остановки, нет ли потерь и дублей. Затем реплика запускается снова
|
||||
(docker start) и ждём, пока HAProxy вернёт её, — только потом следующий прогон.
|
||||
Итог: таблица в консоли и evidence/failover-metrics.json (без токенов).
|
||||
"""
|
||||
import json
|
||||
import platform
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
from helpers import ROOT, check, run
|
||||
from loadgen import CLIENT_TIMEOUT_SECONDS, WRITERS, Load, summary
|
||||
from stand import api_containers, docker, lb_up_count, wait_balanced
|
||||
|
||||
WARMUP_SECONDS = 3
|
||||
AFTER_SECONDS = 10
|
||||
OUTPUT = ROOT / "evidence" / "failover-metrics.json"
|
||||
|
||||
|
||||
class LbWatch:
|
||||
"""Раз в 0,1 с спрашивает у HAProxy, сколько реплик в балансировке (UP)."""
|
||||
|
||||
def __init__(self):
|
||||
self.points, self.stopping = [], threading.Event()
|
||||
self.thread = threading.Thread(target=self._run, daemon=True)
|
||||
|
||||
def _run(self):
|
||||
while not self.stopping.is_set():
|
||||
try:
|
||||
self.points.append((time.monotonic(), lb_up_count()))
|
||||
except OSError:
|
||||
pass
|
||||
time.sleep(0.1)
|
||||
|
||||
def start(self):
|
||||
self.thread.start()
|
||||
|
||||
def stop(self):
|
||||
self.stopping.set()
|
||||
self.thread.join(timeout=3)
|
||||
|
||||
def first_drop(self, after, replicas):
|
||||
return next((t for t, up in self.points if t >= after and up < replicas), None)
|
||||
|
||||
|
||||
def measure(container, mode, replicas):
|
||||
wait_balanced(replicas)
|
||||
load, watch = Load(), LbWatch()
|
||||
watch.start()
|
||||
load.start()
|
||||
time.sleep(WARMUP_SECONDS)
|
||||
t0 = time.monotonic()
|
||||
if mode == "stop":
|
||||
docker("stop", "--time", "8", container)
|
||||
else:
|
||||
docker("kill", container)
|
||||
command_seconds = time.monotonic() - t0
|
||||
time.sleep(max(0.0, AFTER_SECONDS - command_seconds))
|
||||
end = t0 + AFTER_SECONDS
|
||||
load.stop()
|
||||
watch.stop()
|
||||
|
||||
errors = [e for e in load.window(t0 - WARMUP_SECONDS, end) if not e[2]]
|
||||
errors_end = max((e[0] + e[5] for e in errors), default=None)
|
||||
drop = watch.first_drop(t0, replicas)
|
||||
served_after = [e[4] for e in load.window(t0 + command_seconds, end) if e[2]]
|
||||
target_hits = sum(1 for instance in served_after if instance and container.startswith(instance))
|
||||
integrity = load.verify()
|
||||
|
||||
started = time.monotonic()
|
||||
docker("start", container)
|
||||
wait_balanced(replicas)
|
||||
rejoin_seconds = time.monotonic() - started
|
||||
|
||||
return {
|
||||
"replica": container[:12],
|
||||
"mode": mode,
|
||||
"command_seconds": round(command_seconds, 2),
|
||||
"lb_excluded_after_seconds": round(drop - t0, 2) if drop else None,
|
||||
"errors": len(errors),
|
||||
"error_codes": summary(load, t0 - WARMUP_SECONDS, end)["error_codes"],
|
||||
"errors_stopped_after_seconds": round(errors_end - t0, 2) if errors_end else 0.0,
|
||||
"before": summary(load, t0 - WARMUP_SECONDS, t0),
|
||||
"after": summary(load, t0, end),
|
||||
"stopped_replica_answers_after_stop": target_hits,
|
||||
"integrity": integrity,
|
||||
"rejoin_seconds": round(rejoin_seconds, 2),
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
modes = sys.argv[1:] or ["stop", "kill"]
|
||||
check(set(modes) <= {"stop", "kill"}, "usage: python student-tests/failover_metrics.py [stop] [kill]")
|
||||
containers = api_containers()
|
||||
replicas = len(containers)
|
||||
check(replicas >= 2, "need at least 2 running api replicas")
|
||||
print(f"api replicas: {[c[:12] for c in containers]}; load: {WRITERS} writers without pauses + 1 reader, "
|
||||
f"client timeout {CLIENT_TIMEOUT_SECONDS} s, retry with the same Idempotency-Key; "
|
||||
f"{WARMUP_SECONDS} s before and {AFTER_SECONDS} s after the failure")
|
||||
runs = []
|
||||
for container in containers:
|
||||
for mode in modes:
|
||||
print(f"--- {mode} {container[:12]} ...")
|
||||
run = measure(container, mode, replicas)
|
||||
runs.append(run)
|
||||
print(f" docker {mode}: {run['command_seconds']} s; HAProxy excluded it after "
|
||||
f"{run['lb_excluded_after_seconds']} s; errors: {run['errors']} {run['error_codes']}, "
|
||||
f"last error ended {run['errors_stopped_after_seconds']} s after the failure")
|
||||
print(f" write RPS before {run['before']['write_rps']} -> after {run['after']['write_rps']}; "
|
||||
f"p95 after {run['after']['write_p95_ms']} ms, max {run['after']['write_max_ms']} ms; "
|
||||
f"answers from the stopped replica after stop: {run['stopped_replica_answers_after_stop']}")
|
||||
print(f" confirmed {run['integrity']['confirmed_writes']}, in history "
|
||||
f"{run['integrity']['messages_in_history']}, lost 0, duplicates 0; "
|
||||
f"back in the balancer {run['rejoin_seconds']} s after docker start")
|
||||
check(run["stopped_replica_answers_after_stop"] == 0, "the stopped replica still answered")
|
||||
check(run["after"]["write_rps"] > 0, "no successful writes after the failure")
|
||||
print()
|
||||
print("replica mode cmd,s lb_out,s errors errors_end,s rps_before rps_after p95_after,ms rejoin,s")
|
||||
for r in runs:
|
||||
print(f"{r['replica']} {r['mode']:<4} {r['command_seconds']:>5} {str(r['lb_excluded_after_seconds']):>8} "
|
||||
f"{r['errors']:>6} {r['errors_stopped_after_seconds']:>12} {r['before']['write_rps']:>10} "
|
||||
f"{r['after']['write_rps']:>9} {str(r['after']['write_p95_ms']):>12} {r['rejoin_seconds']:>8}")
|
||||
OUTPUT.parent.mkdir(exist_ok=True)
|
||||
OUTPUT.write_text(json.dumps({
|
||||
"profile": {"writers": WRITERS, "readers": 1, "client_timeout_seconds": CLIENT_TIMEOUT_SECONDS,
|
||||
"warmup_seconds": WARMUP_SECONDS, "after_seconds": AFTER_SECONDS, "replicas": replicas,
|
||||
"client_python": platform.python_version()},
|
||||
"runs": runs,
|
||||
}, indent=2) + "\n", encoding="utf-8")
|
||||
print(f"PASS: every replica was stopped ({', '.join(modes)}) and restored; no lost or duplicated messages; "
|
||||
f"saved {OUTPUT.relative_to(ROOT).as_posix()}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,65 @@
|
||||
"""lab4, уровень 3: недоступность S3.
|
||||
|
||||
make failure-s3 (= python student-tests/failure_s3.py)
|
||||
|
||||
Останавливает контейнер s3 (SeaweedFS) и проверяет:
|
||||
- загрузка -> 503 unavailable за несколько секунд (таймауты S3), не 500 и не зависание;
|
||||
- метаданные готового вложения читаются (они в PostgreSQL), а байты -> 503;
|
||||
- текстовые сообщения и история работают, /health/ready = 200: S3 не критичен для обязательного
|
||||
текстового пути, поэтому реплики не выводятся из балансировки;
|
||||
после запуска S3 тот же файл скачивается без изменений, новая загрузка снова 201.
|
||||
"""
|
||||
import hashlib
|
||||
import time
|
||||
|
||||
from filegen import SAMPLE_PNG, upload_when_ready, wait_until
|
||||
from helpers import Client, Failure, check, idempotency, run
|
||||
from stand import compose_quiet, ps_table
|
||||
|
||||
|
||||
def main():
|
||||
api = Client()
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
upload_path = f"/api/v1/chats/{chat['id']}/attachments?filename=before.png"
|
||||
att = upload_when_ready(api, alice, chat, name="before.png")["json"]
|
||||
content = f"/api/v1/attachments/{att['id']}/content"
|
||||
compose_quiet("stop", "s3")
|
||||
try:
|
||||
print("=== s3 stopped")
|
||||
print(ps_table())
|
||||
started = time.monotonic()
|
||||
failed = api.call("POST", upload_path, 503, actor=alice, raw=SAMPLE_PNG, headers={"Content-Type": "image/png"})
|
||||
print(f"upload while S3 is down: {failed['status']} {failed['json']['error']['code']} "
|
||||
f"in {time.monotonic() - started:.2f} s")
|
||||
meta = api.call("GET", f"/api/v1/attachments/{att['id']}", actor=bob, schema="Attachment")
|
||||
print(f"metadata of the ready attachment (PostgreSQL): {meta['status']}")
|
||||
got = api.call("GET", content, 503, actor=bob)
|
||||
print(f"download while S3 is down: {got['status']} {got['json']['error']['code']}")
|
||||
sent = api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, actor=alice,
|
||||
body={"text": "S3 недоступен, текст работает"}, headers=idempotency(), schema="Message")
|
||||
history = api.call("GET", f"/api/v1/chats/{chat['id']}/messages", actor=bob, schema="MessagePage")
|
||||
ready = api.call("GET", "/health/ready", schema="Health")
|
||||
print(f"text message: {sent['status']}; history: {history['status']}; /health/ready: {ready['status']}")
|
||||
finally:
|
||||
compose_quiet("start", "s3")
|
||||
print("=== s3 started")
|
||||
|
||||
def downloaded():
|
||||
try:
|
||||
return api.call("GET", content, actor=bob)["bytes"] == SAMPLE_PNG
|
||||
except Failure:
|
||||
return False
|
||||
|
||||
started = time.monotonic()
|
||||
wait_until(downloaded, 60, "the old file is not downloadable after S3 restart")
|
||||
print(f"the file uploaded before the outage is back after {time.monotonic() - started:.1f} s, same bytes "
|
||||
f"(sha256 {hashlib.sha256(SAMPLE_PNG).hexdigest()[:16]}...)")
|
||||
api.call("POST", upload_path, 201, actor=alice, raw=SAMPLE_PNG, headers={"Content-Type": "image/png"},
|
||||
schema="Attachment")
|
||||
print(ps_table())
|
||||
print("PASS: S3 down -> upload/download 503 (no 500), metadata, text messages and readiness keep working; "
|
||||
"after S3 is back the original is intact and uploads work again")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,199 @@
|
||||
"""lab4: тестовые картинки и низкоуровневая загрузка — только стандартная библиотека Python.
|
||||
|
||||
- png(): настоящий PNG любого размера (шум не сжимается — так получаются файлы на 9 МБ);
|
||||
- bomb_png(): «бомба» — файл ~150 КБ, внутри 42 млн пикселей (больше лимита 40 млн);
|
||||
- SAMPLE_JPEG: синтетический JPEG 48×32 (781 байт), создан для курса программно;
|
||||
- raw_upload(): POST через сокет. Нужен там, где urllib не справится: сервер отвечает 413
|
||||
и закрывает соединение, пока клиент ещё отправляет тело, или клиент сам обрывает передачу;
|
||||
- in_api() / psql(): выполнить код внутри контейнера API или SQL в PostgreSQL (для проверок
|
||||
S3 и уборщика). Секреты не печатаются: код внутри контейнера сам читает их из /run/secrets.
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import select
|
||||
import socket
|
||||
import struct
|
||||
import subprocess
|
||||
import time
|
||||
import zlib
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from helpers import ROOT, check
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
|
||||
|
||||
SAMPLE_PNG = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
SAMPLE_JPEG = base64.b64decode(
|
||||
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAAYEBQYFBAYGBQYHBwYIChAKCgkJChQODwwQFxQYGBcUFhYaHSUfGhsjHBYWICwgIyYn"
|
||||
"KSopGR8tMC0oMCUoKSj/2wBDAQcHBwoIChMKChMoGhYaKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgoKCgo"
|
||||
"KCgoKCgoKCj/wAARCAAgADADASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUF"
|
||||
"BAQAAAF9AQIDAAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVW"
|
||||
"V1hZWmNkZWZnaGlqc3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi"
|
||||
"4+Tl5ufo6erx8vP09fb3+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAEC"
|
||||
"AxEEBSExBhJBUQdhcRMiMoEIFEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVm"
|
||||
"Z2hpanN0dXZ3eHl6goOEhYaHiImKkpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq"
|
||||
"8vP09fb3+Pn6/9oADAMBAAIRAxEAPwDwGCw9q0ILD2rcgsPatCCw9q+pqYw4MFj9tTDgsPatCCw9q24LD2rQgsPauCpjD67BY/bU"
|
||||
"xILD2q/BYe1bkFh7VoQWHtXBUxh9dgsftqc3BYe1aEFh7VuQWHtWhBYe1cdTGH824LH7amHBYe1aEFh7VuQWHtWhBYe1cFTGH12C"
|
||||
"x+2phwWHtWhBYe1bkFh7VoQWHtXn1MYfXYLH7an/2Q==")
|
||||
|
||||
|
||||
def _chunk(kind: bytes, data: bytes) -> bytes:
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def png(width: int, height: int, noise: bool = False) -> bytes:
|
||||
"""RGB PNG. noise=True — случайные пиксели (файл почти не сжимается), иначе однотонный."""
|
||||
compressor = zlib.compressobj(1)
|
||||
parts = []
|
||||
row = b"\x00" + b"\x40\x80\xc0" * width
|
||||
for _ in range(height):
|
||||
parts.append(compressor.compress(b"\x00" + os.urandom(width * 3) if noise else row))
|
||||
parts.append(compressor.flush())
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", ihdr) + _chunk(b"IDAT", b"".join(parts)) + _chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def bomb_png() -> bytes:
|
||||
"""7000×6000 = 42 млн пикселей нулей: файл маленький, распакованный — 126 МБ."""
|
||||
return png(7000, 6000)
|
||||
|
||||
|
||||
def corrupt_crc(data: bytes) -> bytes:
|
||||
"""Испортить один байт внутри данных IDAT: контрольная сумма блока перестаёт сходиться."""
|
||||
position = data.index(b"IDAT") + 8
|
||||
return data[:position] + bytes([data[position] ^ 0xFF]) + data[position + 1:]
|
||||
|
||||
|
||||
def truncated(data: bytes) -> bytes:
|
||||
return data[: len(data) // 2]
|
||||
|
||||
|
||||
# ---------- загрузка через сокет ----------
|
||||
|
||||
def raw_upload(path: str, token: str, body: bytes = b"", content_type: str = "image/png",
|
||||
content_length: int | None = None, abort_after: int | None = None, timeout: float = 30):
|
||||
"""POST path через балансировщик. Возвращает (status, headers, json) или None, если ответа нет.
|
||||
|
||||
content_length — что заявить в заголовке (по умолчанию len(body));
|
||||
abort_after — отправить столько байт тела и оборвать соединение (имитация обрыва загрузки).
|
||||
Тело шлётся кусками; если сервер уже ответил (413) и закрыл соединение — перестаём слать
|
||||
и читаем ответ.
|
||||
"""
|
||||
url = urlsplit(BASE_URL)
|
||||
sock = socket.create_connection((url.hostname, url.port or 80), timeout=timeout)
|
||||
length = len(body) if content_length is None else content_length
|
||||
# content_length=-1: Transfer-Encoding: chunked, размер заранее неизвестен серверу.
|
||||
framing = "Transfer-Encoding: chunked" if length == -1 else f"Content-Length: {length}"
|
||||
head = (f"POST {path} HTTP/1.1\r\nHost: {url.hostname}\r\nAuthorization: Bearer {token}\r\n"
|
||||
f"Content-Type: {content_type}\r\n{framing}\r\nConnection: close\r\n\r\n")
|
||||
to_send = body if abort_after is None else body[:abort_after]
|
||||
if length == -1:
|
||||
step = 64 * 1024
|
||||
to_send = b"".join(b"%x\r\n%s\r\n" % (len(to_send[i:i + step]), to_send[i:i + step])
|
||||
for i in range(0, len(to_send), step)) + b"0\r\n\r\n"
|
||||
try:
|
||||
sock.sendall(head.encode("ascii"))
|
||||
for start in range(0, len(to_send), 64 * 1024):
|
||||
# Сервер уже ответил (например, 413 до конца тела)? Тогда перестаём слать и читаем ответ:
|
||||
# продолжение отправки в закрытое соединение может стереть ответ (RST).
|
||||
if select.select([sock], [], [], 0)[0]:
|
||||
break
|
||||
sock.sendall(to_send[start:start + 64 * 1024])
|
||||
except OSError:
|
||||
pass # сервер закрыл соединение раньше — читаем то, что он успел ответить
|
||||
if abort_after is not None:
|
||||
sock.close()
|
||||
return None
|
||||
data = b""
|
||||
try:
|
||||
while True:
|
||||
part = sock.recv(65536)
|
||||
if not part:
|
||||
break
|
||||
data += part
|
||||
if _complete(data): # ответ получен целиком: не ждём, пока балансировщик закроет соединение
|
||||
break
|
||||
except OSError:
|
||||
pass
|
||||
finally:
|
||||
sock.close()
|
||||
if not data.startswith(b"HTTP/1."):
|
||||
return None
|
||||
header_blob, _, payload = data.partition(b"\r\n\r\n")
|
||||
lines = header_blob.decode("latin-1").split("\r\n")
|
||||
status = int(lines[0].split()[1])
|
||||
headers = {k.strip().lower(): v.strip() for k, v in (line.split(":", 1) for line in lines[1:] if ":" in line)}
|
||||
try:
|
||||
payload_json = json.loads(payload.decode("utf-8")) if payload else None
|
||||
except ValueError:
|
||||
payload_json = None
|
||||
return status, headers, payload_json
|
||||
|
||||
|
||||
def _complete(data: bytes) -> bool:
|
||||
head, sep, body = data.partition(b"\r\n\r\n")
|
||||
if not sep:
|
||||
return False
|
||||
for line in head.decode("latin-1").split("\r\n")[1:]:
|
||||
name, _, value = line.partition(":")
|
||||
if name.strip().lower() == "content-length":
|
||||
return len(body) >= int(value.strip())
|
||||
return False
|
||||
|
||||
|
||||
def upload_when_ready(api, actor, chat, data=None, name="ready.png", seconds=60):
|
||||
"""Загрузить файл; пока S3 только запускается (503) — повторять до seconds. Возвращает ответ 201."""
|
||||
path = f"/api/v1/chats/{chat['id']}/attachments?filename={name}"
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
reply = api.call("POST", path, [201, 503], actor=actor, raw=data or SAMPLE_PNG,
|
||||
headers={"Content-Type": "image/png"}, schema="Attachment")
|
||||
if reply["status"] == 201:
|
||||
return reply
|
||||
check(time.monotonic() < deadline, f"S3 is not ready for uploads after {seconds} s")
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
# ---------- внутри стенда ----------
|
||||
|
||||
def in_api(code: str) -> str:
|
||||
"""Выполнить Python-код в контейнере API (сеть backend, модули messenger). Возвращает stdout."""
|
||||
result = subprocess.run(["docker", "compose", "exec", "-T", "api", "python", "-"], cwd=ROOT,
|
||||
input=code.encode("utf-8"), capture_output=True)
|
||||
last_error = (result.stderr.decode("utf-8", "replace").strip().splitlines() or [""])[-1]
|
||||
check(result.returncode == 0, "code inside the api container failed: " + last_error)
|
||||
return result.stdout.decode("utf-8", "replace").strip()
|
||||
|
||||
|
||||
def exec_python(container: str, code: str) -> str:
|
||||
"""Python-код в конкретном контейнере через stdin (переводы строк одинаково работают и на Windows)."""
|
||||
result = subprocess.run(["docker", "exec", "-i", container, "python", "-"], cwd=ROOT,
|
||||
input=code.encode("utf-8"), capture_output=True)
|
||||
check(result.returncode == 0, f"code inside {container[:12]} failed")
|
||||
return result.stdout.decode("utf-8", "replace").strip()
|
||||
|
||||
|
||||
def psql(sql: str) -> str:
|
||||
"""SQL в PostgreSQL стенда (только для проверок; значения в SQL — проверенные UUID и числа)."""
|
||||
result = subprocess.run(["docker", "compose", "exec", "-T", "postgres", "psql", "-X", "-q", "-t", "-A",
|
||||
"-U", "messenger", "-d", "messenger", "-v", "ON_ERROR_STOP=1", "-c", sql],
|
||||
cwd=ROOT, capture_output=True)
|
||||
check(result.returncode == 0, "psql failed: " + result.stderr.decode("utf-8", "replace").strip())
|
||||
return result.stdout.decode("utf-8", "replace").strip()
|
||||
|
||||
|
||||
def cleanup_cli(*args: str) -> dict:
|
||||
"""python -m messenger.cleanup внутри контейнера API -> словарь счётчиков."""
|
||||
result = subprocess.run(["docker", "compose", "exec", "-T", "api", "python", "-m", "messenger.cleanup", *args],
|
||||
cwd=ROOT, capture_output=True)
|
||||
output = result.stdout.decode("utf-8", "replace").strip().splitlines()
|
||||
check(result.returncode == 0 and output, "cleanup failed: " + result.stderr.decode("utf-8", "replace")[-300:])
|
||||
return json.loads(output[-1])
|
||||
|
||||
|
||||
def wait_until(condition, seconds: float, message: str, step: float = 0.5):
|
||||
deadline = time.monotonic() + seconds
|
||||
while not condition():
|
||||
check(time.monotonic() < deadline, message)
|
||||
time.sleep(step)
|
||||
@@ -0,0 +1,71 @@
|
||||
"""Общие помощники для собственных тестов.
|
||||
|
||||
Переиспользуем публичный HTTP-клиент курса (tests/client.py), а не пишем свой:
|
||||
он уже проверяет X-Request-Id, X-Instance-Id (с lab3), формат ошибок, WWW-Authenticate
|
||||
и схемы ответов из контракта.
|
||||
С lab2 клиент сам регистрирует пользователя с паролем, входит через Basic
|
||||
и подставляет Bearer-токен (токен живёт только в памяти теста и не печатается).
|
||||
"""
|
||||
import base64
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
|
||||
from client import Client, Failure, check, run # noqa: E402 (импорт после правки sys.path)
|
||||
|
||||
__all__ = ["Client", "Failure", "check", "run", "read_history", "basic", "login", "compose", "wait_ready",
|
||||
"idempotency", "ROOT"]
|
||||
|
||||
|
||||
def idempotency(key=None):
|
||||
"""Заголовок Idempotency-Key (обязателен для POST сообщения с lab3). Без аргумента — новый ключ."""
|
||||
return {"Idempotency-Key": key or uuid.uuid4().hex}
|
||||
|
||||
|
||||
def read_history(api, actor, chat_id, limit=100):
|
||||
"""Читает всю историю чата по страницам. Возвращает (сообщения, число_страниц)."""
|
||||
items, pages, cursor = [], 0, None
|
||||
while True:
|
||||
query = f"?limit={limit}" + (f"&cursor={quote(cursor, safe='')}" if cursor else "")
|
||||
page = api.call("GET", f"/api/v1/chats/{chat_id}/messages{query}",
|
||||
actor=actor, schema="MessagePage")["json"]
|
||||
items += page["items"]
|
||||
pages += 1
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
return items, pages
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
"""Значение заголовка Authorization: Basic base64(username:password), пароль в UTF-8."""
|
||||
return "Basic " + base64.b64encode(f"{username}:{password}".encode("utf-8")).decode("ascii")
|
||||
|
||||
|
||||
def login(api, username, password, expected=201):
|
||||
"""POST /auth/sessions; при успехе возвращает тело Session (токен — только в памяти)."""
|
||||
schema = "Session" if expected == 201 else None
|
||||
return api.call("POST", "/api/v1/auth/sessions", expected,
|
||||
headers={"Authorization": basic(username, password)}, schema=schema)["json"]
|
||||
|
||||
|
||||
def compose(*args):
|
||||
"""docker compose <args> из корня репозитория; вывод скрыт (там могут быть имена/секреты)."""
|
||||
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def wait_ready(api, seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
try:
|
||||
api.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
check(time.monotonic() < deadline, f"API не стал готов за {seconds} с")
|
||||
time.sleep(0.5)
|
||||
@@ -0,0 +1,78 @@
|
||||
"""Профиль нагрузки для отчёта: публичный tests/load.py + CPU/RAM контейнеров во время нагрузки.
|
||||
|
||||
python student-tests/load_profile.py (30 с, 4 потока — как в tests/README.md)
|
||||
|
||||
Запускает tests/load.py (closed loop: каждый поток шлёт следующий POST сразу после ответа)
|
||||
и параллельно раз в ~2 с снимает `docker stats --no-stream` по контейнерам стенда.
|
||||
Сохраняет evidence/load.json (вывод load.py: успешные RPS, ошибки, p50/p95/p99)
|
||||
и evidence/load-stats.json (максимум CPU % и RAM по каждому сервису за время нагрузки).
|
||||
Числа зависят от машины и Docker Desktop; это замер этого стенда, а не предел пропускной способности.
|
||||
"""
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
|
||||
from helpers import ROOT, check, run
|
||||
from stand import BASE_URL, compose_output, inspect
|
||||
|
||||
DURATION, CONCURRENCY = 30, 4
|
||||
LOAD_JSON = ROOT / "evidence" / "load.json"
|
||||
STATS_JSON = ROOT / "evidence" / "load-stats.json"
|
||||
|
||||
|
||||
def mib(text):
|
||||
"""'123.4MiB' / '1.2GiB' / '512kB' -> MiB."""
|
||||
text = text.strip()
|
||||
units = {"KiB": 1 / 1024, "kB": 1 / 1024, "MiB": 1, "MB": 1, "GiB": 1024, "GB": 1024, "B": 1 / 2**20}
|
||||
for unit in sorted(units, key=len, reverse=True):
|
||||
if text.endswith(unit):
|
||||
return float(text[: -len(unit)]) * units[unit]
|
||||
return 0.0
|
||||
|
||||
|
||||
def main():
|
||||
# Только основной путь запроса: балансировщик, реплики API, PostgreSQL, Valkey.
|
||||
names = {c[:12]: inspect(c, '{{index .Config.Labels "com.docker.compose.service"}}')
|
||||
for c in compose_output("ps", "-q").split()}
|
||||
names = {cid: service for cid, service in names.items() if service in ("lb", "api", "postgres", "valkey")}
|
||||
containers = list(names)
|
||||
peaks, stopping = {}, threading.Event()
|
||||
|
||||
def sample():
|
||||
while not stopping.is_set():
|
||||
result = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{json .}}", *containers],
|
||||
capture_output=True, text=True)
|
||||
for line in result.stdout.splitlines():
|
||||
item = json.loads(line)
|
||||
key = item["ID"][:12]
|
||||
cpu = float(item["CPUPerc"].rstrip("%") or 0)
|
||||
used, _, limit = item["MemUsage"].partition("/")
|
||||
peak = peaks.setdefault(key, {"service": names.get(key, "?"), "cpu_percent_max": 0.0,
|
||||
"mem_mib_max": 0.0, "mem_limit_mib": round(mib(limit))})
|
||||
peak["cpu_percent_max"] = max(peak["cpu_percent_max"], cpu)
|
||||
peak["mem_mib_max"] = round(max(peak["mem_mib_max"], mib(used)), 1)
|
||||
time.sleep(1)
|
||||
|
||||
sampler = threading.Thread(target=sample, daemon=True)
|
||||
sampler.start()
|
||||
result = subprocess.run([sys.executable, "tests/load.py", "--base-url", BASE_URL, "--duration", str(DURATION),
|
||||
"--concurrency", str(CONCURRENCY), "--output", str(LOAD_JSON)],
|
||||
cwd=ROOT, capture_output=True)
|
||||
stopping.set()
|
||||
sampler.join(timeout=10)
|
||||
print(result.stdout.decode("utf-8", "replace").strip())
|
||||
check(result.returncode == 0, "tests/load.py failed: " + result.stderr.decode("utf-8", "replace")[-300:])
|
||||
rows = sorted(peaks.values(), key=lambda row: row["service"])
|
||||
STATS_JSON.write_text(json.dumps({"duration_seconds": DURATION, "concurrency": CONCURRENCY,
|
||||
"containers": rows}, indent=2) + "\n", encoding="utf-8")
|
||||
print("\nservice cpu % max RAM max / limit, MiB")
|
||||
for row in rows:
|
||||
print(f"{row['service']:<14} {row['cpu_percent_max']:>9.1f} {row['mem_mib_max']:>7.1f} / {row['mem_limit_mib']}")
|
||||
print(f"PASS: load profile saved to {LOAD_JSON.relative_to(ROOT).as_posix()} and "
|
||||
f"{STATS_JSON.relative_to(ROOT).as_posix()}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,120 @@
|
||||
"""Фоновая нагрузка для замеров во время отказа и rolling update
|
||||
(используют failover_metrics.py и rolling_update.py). Только стандартная библиотека.
|
||||
|
||||
WRITERS потоков без пауз пишут сообщения в один чат (closed loop: следующий запрос — сразу после
|
||||
ответа на предыдущий). Если запрос не подтверждён (обрыв, timeout, 5xx), поток повторяет ТОТ ЖЕ
|
||||
запрос с ТЕМ ЖЕ Idempotency-Key — так по контракту делает клиент. Один поток параллельно читает
|
||||
историю. Каждая попытка записывается: время, успех, код, реплика, задержка.
|
||||
В конце verify() читает всю историю и проверяет, что все подтверждённые сообщения на месте
|
||||
и дублей нет (тексты уникальны, поэтому дубль сразу виден).
|
||||
"""
|
||||
import math
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from helpers import Client, check, read_history
|
||||
from stand import try_call
|
||||
|
||||
WRITERS = 4
|
||||
CLIENT_TIMEOUT_SECONDS = 2
|
||||
|
||||
|
||||
class Load:
|
||||
def __init__(self, writers=WRITERS, timeout=CLIENT_TIMEOUT_SECONDS):
|
||||
self.api = Client()
|
||||
self.alice, self.bob = self.api.user("load_a"), self.api.user("load_b")
|
||||
self.chat = self.api.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat",
|
||||
body={"title": "load", "member_ids": [self.alice["id"], self.bob["id"]]})["json"]
|
||||
self.writers, self.timeout = writers, timeout
|
||||
self.events = [] # (время старта, "write"/"read", ok, код или "conn", реплика, задержка в с)
|
||||
self.confirmed = [] # сообщения, на которые пришёл 201
|
||||
self.lock = threading.Lock()
|
||||
self.stopping = threading.Event()
|
||||
self.threads = []
|
||||
|
||||
def _record(self, kind, started, reply, ok):
|
||||
code = reply.status if reply is not None else "conn"
|
||||
instance = reply.instance if reply is not None else None
|
||||
with self.lock:
|
||||
self.events.append((started, kind, ok, code, instance, time.monotonic() - started))
|
||||
|
||||
def _writer(self, number):
|
||||
path = f"/api/v1/chats/{self.chat['id']}/messages"
|
||||
sent = 0
|
||||
key, text = uuid.uuid4().hex, f"load-{number}-{sent}"
|
||||
while not self.stopping.is_set():
|
||||
started = time.monotonic()
|
||||
reply = try_call("POST", path, body={"text": text}, token=self.alice["token"],
|
||||
headers={"Idempotency-Key": key}, timeout=self.timeout)
|
||||
ok = reply is not None and reply.status == 201
|
||||
self._record("write", started, reply, ok)
|
||||
if ok:
|
||||
with self.lock:
|
||||
self.confirmed.append(reply.json)
|
||||
sent += 1
|
||||
key, text = uuid.uuid4().hex, f"load-{number}-{sent}"
|
||||
else:
|
||||
time.sleep(0.05) # и повторить тот же text с тем же ключом
|
||||
|
||||
def _reader(self):
|
||||
path = f"/api/v1/chats/{self.chat['id']}/messages?limit=20"
|
||||
while not self.stopping.is_set():
|
||||
started = time.monotonic()
|
||||
reply = try_call("GET", path, token=self.bob["token"], timeout=self.timeout)
|
||||
self._record("read", started, reply, reply is not None and reply.status == 200)
|
||||
time.sleep(0.05)
|
||||
|
||||
def start(self):
|
||||
self.threads = [threading.Thread(target=self._writer, args=(n,), daemon=True) for n in range(self.writers)]
|
||||
self.threads.append(threading.Thread(target=self._reader, daemon=True))
|
||||
for thread in self.threads:
|
||||
thread.start()
|
||||
|
||||
def stop(self):
|
||||
self.stopping.set()
|
||||
for thread in self.threads:
|
||||
thread.join(timeout=self.timeout + 5)
|
||||
|
||||
def window(self, start, end, kind=None):
|
||||
with self.lock:
|
||||
return [e for e in self.events if start <= e[0] < end and (kind is None or e[1] == kind)]
|
||||
|
||||
def verify(self):
|
||||
"""Все подтверждённые сообщения есть в истории, id и тексты не повторяются."""
|
||||
history, _ = read_history(self.api, self.bob, self.chat["id"])
|
||||
ids = [message["id"] for message in history]
|
||||
texts = [message["text"] for message in history]
|
||||
by_id = {message["id"]: message for message in history}
|
||||
check(len(ids) == len(set(ids)), "duplicated message ids in history")
|
||||
check(len(texts) == len(set(texts)), "a retried request created a duplicate message")
|
||||
lost = [m for m in self.confirmed if by_id.get(m["id"]) != m]
|
||||
check(not lost, f"{len(lost)} confirmed messages are lost or changed")
|
||||
return {"confirmed_writes": len(self.confirmed), "messages_in_history": len(history),
|
||||
"duplicates": 0, "lost": 0}
|
||||
|
||||
|
||||
def summary(load, start, end):
|
||||
"""Успешные записи в секунду, ошибки по кодам и задержки успешных записей на отрезке [start, end)."""
|
||||
events = load.window(start, end)
|
||||
writes = [e for e in events if e[1] == "write"]
|
||||
ok_writes = sorted(e[5] for e in writes if e[2])
|
||||
errors = [e for e in events if not e[2]]
|
||||
seconds = max(end - start, 1e-6)
|
||||
|
||||
def percentile(p):
|
||||
return round(1000 * ok_writes[max(0, math.ceil(p * len(ok_writes)) - 1)], 1) if ok_writes else None
|
||||
|
||||
codes = {}
|
||||
for e in errors:
|
||||
codes[str(e[3])] = codes.get(str(e[3]), 0) + 1
|
||||
return {
|
||||
"seconds": round(seconds, 2),
|
||||
"write_rps": round(len(ok_writes) / seconds, 1),
|
||||
"reads": len([e for e in events if e[1] == "read"]),
|
||||
"errors": len(errors),
|
||||
"error_codes": codes,
|
||||
"write_p50_ms": percentile(0.50),
|
||||
"write_p95_ms": percentile(0.95),
|
||||
"write_max_ms": round(1000 * ok_writes[-1], 1) if ok_writes else None,
|
||||
}
|
||||
@@ -0,0 +1,116 @@
|
||||
"""lab4, уровень 4: компенсация сбоев между S3 и PostgreSQL, grace period, обрыв загрузки.
|
||||
|
||||
make orphan-cleanup (= python student-tests/orphan_cleanup.py)
|
||||
|
||||
Внутри контейнера API создаются ровно те состояния, которые остаются после сбоев (attachments.py):
|
||||
- stale: pending-строка часовой давности + объект в S3 = «PUT прошёл, COMMIT ready не прошёл»
|
||||
(БД упала или реплику убили между шагами 4 и 5);
|
||||
- fresh: pending-строка «прямо сейчас» + объект = загрузка, которая идёт в эту секунду;
|
||||
- orphan: объект без строки = строка потеряна, объект остался.
|
||||
Затем уборщик (python -m messenger.cleanup) запускается так:
|
||||
1. --dry-run: всё найдено, ничего не удалено;
|
||||
2. обычный запуск (grace 900 с): удалены только stale (объект, потом строка); fresh и orphan
|
||||
моложе grace и не тронуты; готовое вложение на месте;
|
||||
3. повторный запуск: делать нечего (идемпотентность);
|
||||
4. --grace-seconds 2 через 3 с (только для теста): удалены и fresh, и orphan; готовое вложение на месте.
|
||||
Отдельно: клиент обрывает загрузку на трети файла — ни строки, ни объекта не появляется.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
|
||||
from filegen import cleanup_cli, in_api, png, psql, raw_upload, upload_when_ready
|
||||
from helpers import Client, check, idempotency, run
|
||||
|
||||
INJECT = """
|
||||
import io, json, uuid, psycopg
|
||||
from messenger import config, objects
|
||||
chat, user = "{chat}", "{user}"
|
||||
made = {{}}
|
||||
with psycopg.connect(config.DATABASE_URL, autocommit=True) as db:
|
||||
for name, age in (("stale", "1 hour"), ("fresh", "0 seconds")):
|
||||
key = objects.new_key()
|
||||
objects.put(key, io.BytesIO(b"x" * 100), 100, "image/png", "0" * 64)
|
||||
db.execute("INSERT INTO attachments (id, chat_id, owner_id, filename, content_type, size_bytes, sha256,"
|
||||
" width, height, storage_key, status, created_at) VALUES (%s, %s, %s, 'injected.png',"
|
||||
" 'image/png', 100, %s, 1, 1, %s, 'pending', now() - %s::interval)",
|
||||
(uuid.uuid4(), chat, user, "0" * 64, key, age))
|
||||
made[name] = key
|
||||
key = objects.new_key()
|
||||
objects.put(key, io.BytesIO(b"y" * 10), 10, "image/png", "1" * 64)
|
||||
made["orphan"] = key
|
||||
print(json.dumps(made))
|
||||
"""
|
||||
|
||||
EXISTS = """
|
||||
import json
|
||||
from messenger import objects
|
||||
keys = {{key for key, _ in objects.list_objects()}}
|
||||
print(json.dumps({{name: key in keys for name, key in json.loads('{keys}').items()}}))
|
||||
"""
|
||||
|
||||
|
||||
def exists(keys: dict) -> dict:
|
||||
return json.loads(in_api(EXISTS.format(keys=json.dumps(keys))))
|
||||
|
||||
|
||||
def main():
|
||||
api = Client()
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
ready = upload_when_ready(api, alice, chat, name="keep.png")["json"]
|
||||
api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, actor=alice, headers=idempotency(),
|
||||
body={"text": "", "attachment_ids": [ready["id"]]})
|
||||
keys = json.loads(in_api(INJECT.format(chat=uuid.UUID(chat["id"]), user=uuid.UUID(alice["id"]))))
|
||||
keys["ready"] = psql(f"SELECT storage_key FROM attachments WHERE id = '{uuid.UUID(ready['id'])}'")
|
||||
print("injected: stale pending row + object (PUT ok, COMMIT failed), fresh pending row + object "
|
||||
"(upload in progress), orphan object without a row; plus one ready attachment")
|
||||
|
||||
def still_ready():
|
||||
got = api.call("GET", f"/api/v1/attachments/{ready['id']}/content", actor=bob)["bytes"]
|
||||
return hashlib.sha256(got).hexdigest() == ready["sha256"]
|
||||
|
||||
dry = cleanup_cli("--dry-run")
|
||||
print("1. dry-run:", json.dumps(dry))
|
||||
check(dry["stale_pending"] >= 1 and dry["pending_deleted"] == 0 and dry["orphans_deleted"] == 0, "dry-run deleted")
|
||||
check(all(exists(keys).values()), "dry-run removed an object")
|
||||
|
||||
real = cleanup_cli()
|
||||
print("2. cleanup, grace 900 s:", json.dumps(real))
|
||||
state = exists(keys)
|
||||
check(not state["stale"], "stale object was not removed")
|
||||
check(state["fresh"] and state["orphan"] and state["ready"], "a fresh or ready object was removed")
|
||||
check(psql(f"SELECT count(*) FROM attachments WHERE storage_key = '{keys['stale']}'") == "0", "stale row left")
|
||||
check(still_ready(), "ready attachment changed")
|
||||
print(" stale object and row removed; fresh pending, fresh orphan and the ready attachment kept")
|
||||
|
||||
again = cleanup_cli()
|
||||
print("3. repeated run:", json.dumps(again))
|
||||
check(again["pending_deleted"] == 0 and again["orphans_deleted"] == 0, "repeated run is not a no-op")
|
||||
|
||||
time.sleep(3)
|
||||
short = cleanup_cli("--grace-seconds", "2")
|
||||
print("4. cleanup, grace 2 s (test only):", json.dumps(short))
|
||||
state = exists(keys)
|
||||
check(not state["fresh"] and not state["orphan"] and state["ready"], "grace 2 s: wrong objects removed")
|
||||
check(still_ready(), "ready attachment changed")
|
||||
print(" after the grace period the old pending upload and the orphan object are removed too; "
|
||||
"the ready attachment is never touched")
|
||||
|
||||
rows_before = psql(f"SELECT count(*) FROM attachments WHERE chat_id = '{uuid.UUID(chat['id'])}'")
|
||||
objects_before = cleanup_cli("--dry-run")["objects_in_bucket"]
|
||||
data = png(1000, 800, noise=True)
|
||||
raw_upload(f"/api/v1/chats/{chat['id']}/attachments?filename=abort.png", alice["token"], data,
|
||||
abort_after=len(data) // 3)
|
||||
time.sleep(2)
|
||||
rows_after = psql(f"SELECT count(*) FROM attachments WHERE chat_id = '{uuid.UUID(chat['id'])}'")
|
||||
objects_after = cleanup_cli("--dry-run")["objects_in_bucket"]
|
||||
print(f"5. client aborted an upload after {len(data) // 3} of {len(data)} bytes: rows in chat "
|
||||
f"{rows_before} -> {rows_after}, objects in bucket {objects_before} -> {objects_after}")
|
||||
check(rows_before == rows_after and objects_before == objects_after, "aborted upload left something behind")
|
||||
print("PASS: failures between S3 and PostgreSQL leave no permanent unaccounted objects; the grace period "
|
||||
"protects uploads in progress; dry-run and repeated runs are safe; an aborted upload stores nothing")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,75 @@
|
||||
"""Проверка гонок (уровень 4). Запуск: make race
|
||||
|
||||
1. 10 клиентов одновременно отправляют по 10 сообщений в один чат:
|
||||
в истории ровно 100 сообщений, все id уникальны, ни один текст не потерян.
|
||||
2. 20 клиентов одновременно регистрируют ОДИН И ТОТ ЖЕ username:
|
||||
ровно один получает 201, остальные 409; в базе один такой пользователь.
|
||||
Защита — уникальный индекс users.username в PostgreSQL, а не проверка в коде.
|
||||
"""
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from helpers import Client, check, idempotency, read_history, run
|
||||
|
||||
CLIENTS = 10
|
||||
PER_CLIENT = 10
|
||||
REGISTRATIONS = 20
|
||||
|
||||
|
||||
def concurrent_messages(api):
|
||||
users = [api.user(f"race{i}") for i in range(CLIENTS)]
|
||||
chat = api.call("POST", "/api/v1/chats", 201, actor=users[0], schema="Chat",
|
||||
body={"title": "race", "member_ids": [u["id"] for u in users]})["json"]
|
||||
path = f"/api/v1/chats/{chat['id']}/messages"
|
||||
start_together = threading.Barrier(CLIENTS) # все потоки стартуют одновременно
|
||||
|
||||
def send_all(index):
|
||||
client = Client() # у каждого «клиента» свои HTTP-соединения
|
||||
start_together.wait()
|
||||
for n in range(PER_CLIENT):
|
||||
client.call("POST", path, 201, actor=users[index], body={"text": f"client-{index}-msg-{n}"},
|
||||
headers=idempotency())
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=CLIENTS) as pool:
|
||||
list(pool.map(send_all, range(CLIENTS))) # list() пробрасывает ошибки из потоков
|
||||
elapsed = time.monotonic() - started
|
||||
|
||||
history, pages = read_history(api, users[0], chat["id"], limit=25)
|
||||
expected = {f"client-{i}-msg-{n}" for i in range(CLIENTS) for n in range(PER_CLIENT)}
|
||||
print(f"messages: sent {CLIENTS * PER_CLIENT} from {CLIENTS} parallel clients in {elapsed:.2f}s")
|
||||
print(f"messages: read {len(history)} in {pages} pages, unique ids: {len({m['id'] for m in history})}")
|
||||
check(len(history) == CLIENTS * PER_CLIENT, "wrong number of messages")
|
||||
check(len({m["id"] for m in history}) == len(history), "duplicate message ids")
|
||||
check({m["text"] for m in history} == expected, "lost or corrupted message texts")
|
||||
print("PASS: 100 concurrent messages stored without loss or duplicates")
|
||||
|
||||
|
||||
def concurrent_registration():
|
||||
username = "race_" + uuid.uuid4().hex[:12]
|
||||
start_together = threading.Barrier(REGISTRATIONS)
|
||||
|
||||
def register(index):
|
||||
client = Client()
|
||||
body = {"username": username, "display_name": f"Участник {index}", "password": f"Race-password-{index:03d}"}
|
||||
start_together.wait()
|
||||
return client.call("POST", "/api/v1/users", [201, 409], body=body)["status"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=REGISTRATIONS) as pool:
|
||||
statuses = list(pool.map(register, range(REGISTRATIONS)))
|
||||
created, conflicts = statuses.count(201), statuses.count(409)
|
||||
print(f"registration: {REGISTRATIONS} parallel requests for one username -> 201 x{created}, 409 x{conflicts}")
|
||||
check(created == 1 and conflicts == REGISTRATIONS - 1, "exactly one registration must win")
|
||||
print("PASS: concurrent registration of the same username created exactly one user")
|
||||
|
||||
|
||||
def main():
|
||||
api = Client()
|
||||
concurrent_messages(api)
|
||||
concurrent_registration()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,142 @@
|
||||
"""Таблицы замеров для REPORT.md из evidence/*.json (без ручного переписывания чисел).
|
||||
|
||||
make report-tables (= python student-tests/report_tables.py)
|
||||
|
||||
Берёт evidence/failover-metrics.json, rolling-update.json, load.json, load-stats.json
|
||||
и время из evidence/persistence.txt, собирает markdown-таблицы и вставляет их в REPORT.md
|
||||
между метками <!-- measurements:begin --> и <!-- measurements:end -->. Запускать после
|
||||
make failover-metrics, make rolling-update, make load-profile и make persistence.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
|
||||
from helpers import ROOT, check, run
|
||||
|
||||
EVIDENCE = ROOT / "evidence"
|
||||
REPORT = ROOT / "REPORT.md"
|
||||
BEGIN, END = "<!-- measurements:begin -->", "<!-- measurements:end -->"
|
||||
|
||||
|
||||
def load(name):
|
||||
path = EVIDENCE / name
|
||||
return json.loads(path.read_text(encoding="utf-8")) if path.exists() else None
|
||||
|
||||
|
||||
def codes(mapping):
|
||||
return ", ".join(f"{code}: {count}" for code, count in mapping.items()) or "-"
|
||||
|
||||
|
||||
def failover_table(data):
|
||||
lines = [
|
||||
f"Остановка каждой реплики под нагрузкой (`make failover-metrics`, evidence/failover-metrics.json): "
|
||||
f"{data['profile']['writers']} потока пишут сообщения без пауз, 1 читает историю, timeout клиента "
|
||||
f"{data['profile']['client_timeout_seconds']} с, неподтверждённая запись повторяется с тем же ключом; "
|
||||
f"{data['profile']['warmup_seconds']} с до отказа и {data['profile']['after_seconds']} с после. "
|
||||
"stop = `docker stop` (SIGTERM, плановая остановка), kill = `docker kill` (SIGKILL, авария).",
|
||||
"",
|
||||
"| Реплика | Отказ | Вывод из LB, с | Ошибок (коды) | Ошибки закончились через, с | Записей/с до → после | "
|
||||
"p95 записи после, мс | Возврат в LB после `docker start`, с | Потери / дубли |",
|
||||
"| --- | --- | --- | --- | --- | --- | --- | --- | --- |",
|
||||
]
|
||||
for r in data["runs"]:
|
||||
lines.append(f"| {r['replica']} | {r['mode']} | {r['lb_excluded_after_seconds']} | {r['errors']} "
|
||||
f"({codes(r['error_codes'])}) | {r['errors_stopped_after_seconds']} | "
|
||||
f"{r['before']['write_rps']} → {r['after']['write_rps']} | {r['after']['write_p95_ms']} | "
|
||||
f"{r['rejoin_seconds']} | 0 / 0 (подтверждено {r['integrity']['confirmed_writes']}) |")
|
||||
return lines
|
||||
|
||||
|
||||
def rolling_lines(data):
|
||||
during = data["during"]
|
||||
steps = "; ".join(f"{s['old']} → {s['new']}: новая готова через {s['new_ready_seconds']} с, шаг {s['step_seconds']} с"
|
||||
for s in data["steps"])
|
||||
return [f"Rolling update под той же нагрузкой (`make rolling-update`, evidence/rolling-update.json): версия "
|
||||
f"{data['from_version']} → {data['to_version']}, {data['replicas']} реплики заменены по одной за "
|
||||
f"{data['update_seconds']} с ({steps}). Записей/с до: {data['before']['write_rps']}, во время замены: "
|
||||
f"{during['write_rps']}; ошибок: {during['errors']} ({codes(during['error_codes'])}); p95 "
|
||||
f"{during['write_p95_ms']} мс, максимум {during['write_max_ms']} мс; подтверждено "
|
||||
f"{data['integrity']['confirmed_writes']} сообщений, потерь и дублей нет."]
|
||||
|
||||
|
||||
def load_lines(data, stats):
|
||||
latency = data["successful_latency_ms"]
|
||||
lines = [f"Публичный генератор нагрузки (`make load-profile` = `tests/load.py`, closed loop, {data['concurrency']} "
|
||||
f"потока, {data['requested_duration_seconds']:.0f} с, 2 реплики): {data['successful_rps']} успешных "
|
||||
f"POST/с, ошибок {data['failed_requests']} (доля {data['error_ratio']}), задержка успешных: p50 "
|
||||
f"{latency['p50']} мс, p95 {latency['p95']} мс, p99 {latency['p99']} мс."]
|
||||
if stats:
|
||||
lines += ["", "| Сервис | CPU, % макс. (100 % = 1 ядро) | RAM макс. / лимит, МиБ |", "| --- | --- | --- |"]
|
||||
lines += [f"| {row['service']} | {row['cpu_percent_max']:.1f} | {row['mem_mib_max']:.0f} / {row['mem_limit_mib']} |"
|
||||
for row in stats["containers"]]
|
||||
return lines
|
||||
|
||||
|
||||
def impacts(failover, rolling):
|
||||
rows = ["| Воздействие | Что ожидаем | Что наблюдали | Время восстановления / потеря данных |",
|
||||
"| --- | --- | --- | --- |"]
|
||||
if failover:
|
||||
for mode, title, expect in (
|
||||
("stop", "`docker stop` одной реплики (по очереди каждой)",
|
||||
"реплика сама уходит из балансировки до выхода; ошибок нет"),
|
||||
("kill", "`docker kill` одной реплики (по очереди каждой)",
|
||||
"несколько 502 у запросов, начатых на ней; клиент повторяет с тем же ключом")):
|
||||
runs = [r for r in failover["runs"] if r["mode"] == mode]
|
||||
if not runs:
|
||||
continue
|
||||
errors = sum(r["errors"] for r in runs)
|
||||
out = max(r["lb_excluded_after_seconds"] or 0 for r in runs)
|
||||
end = max(r["errors_stopped_after_seconds"] for r in runs)
|
||||
recovery = f"ошибки закончились не позже {end} с после отказа" if errors else "ошибок не было"
|
||||
rows.append(f"| {title} | {expect} | ошибок всего {errors} за {len(runs)} прогона; HAProxy вывел реплику "
|
||||
f"не позже {out} с; остановленная реплика после остановки не отвечала | {recovery}; "
|
||||
f"потерь и дублей 0 |")
|
||||
if rolling:
|
||||
rows.append(f"| Rolling update 2 реплик под нагрузкой | замена по одной без простоя | ошибок "
|
||||
f"{rolling['during']['errors']}, записей/с {rolling['during']['write_rps']} | "
|
||||
f"{rolling['update_seconds']} с на замену; потерь и дублей 0 |")
|
||||
persistence = EVIDENCE / "persistence.txt"
|
||||
if persistence.exists():
|
||||
found = re.search(r"test took ([\d.]+) s", persistence.read_text(encoding="utf-8"))
|
||||
if found:
|
||||
rows.append(f"| Перезапуск всего стенда (`make persistence`, hook restart) | данные и действующий токен "
|
||||
f"сохраняются | PASS: те же контейнеры с новым временем старта, прежний токен работает | "
|
||||
f"{found.group(1)} с на весь тест (hook + готовность); потерь нет |")
|
||||
# Отказы зависимостей (проверки lab2, теперь через балансировщик): строка — если тест прошёл.
|
||||
for name, title, expect, seen, recovery in (
|
||||
("failure-valkey.txt", "`docker compose stop valkey`", "API работает без кэша",
|
||||
"ready 200; вход, сообщения и logout работают через PostgreSQL",
|
||||
"кэш снова включается за 1–2 с после start; потерь нет"),
|
||||
("failure-postgres.txt", "`docker compose stop postgres`",
|
||||
"неготовые реплики исключены из маршрутизации, клиенту 503",
|
||||
"HAProxy вывел обе реплики (ready 503, live 200); запрос с действующим токеном из кэша -> 503 "
|
||||
"от балансировщика, до реплики не дошёл; запись не сохранилась",
|
||||
"после start прежний токен и данные на месте; запросы во время отказа не сохранены (503)"),
|
||||
("failure-valkey-pause.txt", "`docker compose pause valkey`, logout, `unpause`",
|
||||
"отозванный токен не оживает ни на одной реплике", "после unpause отозванный токен всегда 401",
|
||||
"поколение кэша сменилось после возвращения Valkey; отзыв не потерян")):
|
||||
path = EVIDENCE / name
|
||||
if path.exists() and "PASS" in path.read_text(encoding="utf-8"):
|
||||
rows.append(f"| {title} | {expect} | {seen} | {recovery} |")
|
||||
return rows if len(rows) > 2 else []
|
||||
|
||||
|
||||
def main():
|
||||
failover, rolling = load("failover-metrics.json"), load("rolling-update.json")
|
||||
load_result, stats = load("load.json"), load("load-stats.json")
|
||||
parts = []
|
||||
for block in (failover and failover_table(failover), rolling and rolling_lines(rolling),
|
||||
load_result and load_lines(load_result, stats), impacts(failover, rolling)):
|
||||
if block:
|
||||
parts += block + [""]
|
||||
check(parts, "no evidence/*.json yet: run make failover-metrics, rolling-update, load-profile first")
|
||||
text = REPORT.read_text(encoding="utf-8")
|
||||
check(BEGIN in text and END in text, "REPORT.md has no measurements markers")
|
||||
head, rest = text.split(BEGIN, 1)
|
||||
_, tail = rest.split(END, 1)
|
||||
REPORT.write_text(head + BEGIN + "\n" + "\n".join(parts).strip() + "\n" + END + tail, encoding="utf-8")
|
||||
print("\n".join(parts).strip())
|
||||
print("\nPASS: tables inserted into REPORT.md between the measurements markers")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,108 @@
|
||||
"""lab3, уровень 4: rolling update под нагрузкой — реплики по одной заменяются новой версией.
|
||||
|
||||
make rolling-update (= python student-tests/rolling_update.py)
|
||||
|
||||
1. Собирается новый образ с APP_VERSION=rolling-<время> (docker compose build api migrate).
|
||||
2. Миграции новой версии применяются ОДИН раз отдельным запуском: docker compose run --rm migrate.
|
||||
Миграции только добавляют (как 004: новые столбцы, которые могут быть NULL), поэтому старые
|
||||
реплики продолжают работать с новой схемой, пока их не заменят.
|
||||
3. Для каждой старой реплики: запустить ещё одну, новую (docker compose up --scale api=N+1
|
||||
--no-recreate), дождаться healthy и UP в HAProxy, затем остановить старую (docker stop:
|
||||
сначала readiness 503 и выход из балансировки) и удалить её. Реплик всё время не меньше N.
|
||||
4. Всё это время идёт нагрузка (loadgen.py): ошибки, RPS, задержки; в конце — проверка,
|
||||
что подтверждённые сообщения на месте и дублей нет.
|
||||
Итог: таблица в консоли и evidence/rolling-update.json. После скрипта стенд работает на новой
|
||||
версии. Обычный `docker compose up -d --build` потом вернёт версию dev, пересоздав реплики разом
|
||||
(это уже не rolling update).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import time
|
||||
|
||||
from helpers import ROOT, check, run
|
||||
from loadgen import CLIENT_TIMEOUT_SECONDS, WRITERS, Load, summary
|
||||
from stand import api_containers, compose_output, compose_quiet, docker, health, lb_summary, lb_up_count, wait_balanced
|
||||
|
||||
OUTPUT = ROOT / "evidence" / "rolling-update.json"
|
||||
|
||||
|
||||
def version_of(container):
|
||||
lines = docker("inspect", "-f", "{{range .Config.Env}}{{println .}}{{end}}", container).splitlines()
|
||||
env = dict(line.split("=", 1) for line in lines if "=" in line)
|
||||
return env.get("APP_VERSION")
|
||||
|
||||
|
||||
def wait_new_replica(container, up_needed, seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
while health(container) != "healthy" or lb_up_count() < up_needed:
|
||||
check(time.monotonic() < deadline, f"new replica {container[:12]} is not in the balancer after {seconds} s")
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def main():
|
||||
old = api_containers()
|
||||
replicas = len(old)
|
||||
check(replicas >= 2, "need at least 2 running api replicas")
|
||||
wait_balanced(replicas)
|
||||
old_version = version_of(old[0])
|
||||
version = time.strftime("rolling-%Y%m%d-%H%M%S")
|
||||
env = dict(os.environ, APP_VERSION=version)
|
||||
|
||||
print(f"old replicas {[c[:12] for c in old]}, version {old_version}; building version {version}")
|
||||
started = time.monotonic()
|
||||
compose_quiet("build", "api", "migrate", env=env)
|
||||
print(f"image built in {time.monotonic() - started:.1f} s")
|
||||
migrate_log = compose_output("run", "--rm", "--no-deps", "-T", "migrate", env=env)
|
||||
lines = [line for line in migrate_log.splitlines() if "Миграции" in line]
|
||||
print("migrations (one run, before replacing replicas): " + (lines[-1].split("messenger.db: ")[-1] if lines else "?"))
|
||||
|
||||
load = Load()
|
||||
load.start()
|
||||
time.sleep(3)
|
||||
t0 = time.monotonic()
|
||||
steps = []
|
||||
for container in old:
|
||||
step_start = time.monotonic()
|
||||
before = set(api_containers())
|
||||
compose_quiet("up", "-d", "--no-deps", "--no-recreate", "--scale", f"api={len(before) + 1}", "api", env=env)
|
||||
new = sorted(set(api_containers()) - before)
|
||||
check(len(new) == 1, f"expected one new container, got {len(new)}")
|
||||
wait_new_replica(new[0], replicas + 1)
|
||||
ready = time.monotonic() - step_start
|
||||
docker("stop", "--time", "15", container)
|
||||
docker("rm", container)
|
||||
steps.append({"old": container[:12], "new": new[0][:12], "new_ready_seconds": round(ready, 2),
|
||||
"step_seconds": round(time.monotonic() - step_start, 2)})
|
||||
print(f"replaced {container[:12]} -> {new[0][:12]}: new replica healthy and UP in HAProxy after "
|
||||
f"{ready:.1f} s, then the old one drained and stopped; step {steps[-1]['step_seconds']} s "
|
||||
f"(HAProxy: {lb_summary()})")
|
||||
t1 = time.monotonic()
|
||||
time.sleep(3)
|
||||
load.stop()
|
||||
|
||||
final = api_containers()
|
||||
versions = sorted({version_of(c) for c in final})
|
||||
integrity = load.verify()
|
||||
during = summary(load, t0, t1)
|
||||
before_stats = summary(load, t0 - 3, t0)
|
||||
print(f"now: replicas {[c[:12] for c in final]}, versions {versions}")
|
||||
print(f"under load: write RPS before {before_stats['write_rps']}, during the update {during['write_rps']}; "
|
||||
f"errors {during['errors']} {during['error_codes']}; p95 {during['write_p95_ms']} ms, "
|
||||
f"max {during['write_max_ms']} ms; update took {t1 - t0:.1f} s")
|
||||
print(f"confirmed {integrity['confirmed_writes']}, in history {integrity['messages_in_history']}, "
|
||||
f"lost 0, duplicates 0")
|
||||
check(len(final) == replicas and not set(final) & set(old), "old replicas are still running")
|
||||
check(versions == [version], "not every replica runs the new version")
|
||||
OUTPUT.parent.mkdir(exist_ok=True)
|
||||
OUTPUT.write_text(json.dumps({
|
||||
"from_version": old_version, "to_version": version, "replicas": replicas,
|
||||
"profile": {"writers": WRITERS, "readers": 1, "client_timeout_seconds": CLIENT_TIMEOUT_SECONDS},
|
||||
"steps": steps, "update_seconds": round(t1 - t0, 2),
|
||||
"before": before_stats, "during": during, "integrity": integrity,
|
||||
}, indent=2) + "\n", encoding="utf-8")
|
||||
print(f"PASS: all {replicas} replicas replaced one by one under load, "
|
||||
f"{during['errors']} errors, no lost or duplicated messages; saved {OUTPUT.relative_to(ROOT).as_posix()}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,69 @@
|
||||
"""Публичный тест отказа (tests/resilience.py --mode failover) для КАЖДОЙ реплики по очереди.
|
||||
|
||||
make failover (= python student-tests/run_failover.py)
|
||||
|
||||
Публичный тест сам выбирает реплику — ту, что ответила на его первое сообщение, — и вызывает
|
||||
hook scripts/stop-one.cmd (Windows) или scripts/stop-one.sh, который останавливает именно её.
|
||||
Этот скрипт печатает контейнеры до и после теста (видно, какой контейнер реально остановлен
|
||||
и что postgres, valkey и lb не тронуты), запускает реплику обратно (docker start), ждёт,
|
||||
пока HAProxy вернёт её в балансировку, и повторяет тест, пока каждая реплика не будет
|
||||
остановлена хотя бы раз (не больше 6 прогонов).
|
||||
|
||||
Как попасть в нужную реплику: при 2 репликах HAProxy отвечает строго по очереди, а до первого
|
||||
сообщения тест делает 9 запросов. Значит, его сообщение (10-й запрос) уйдёт на ту же реплику,
|
||||
что ответила на наш последний запрос. Поэтому перед прогоном один-два запроса /health/live
|
||||
«сдвигают» очередь так, чтобы последней ответила ещё не проверенная реплика.
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
|
||||
from helpers import ROOT, Client, check, run
|
||||
from stand import BASE_URL, api_containers, docker, lb_summary, ps_table, wait_balanced
|
||||
|
||||
HOOK = ROOT / "scripts" / ("stop-one.cmd" if os.name == "nt" else "stop-one.sh")
|
||||
|
||||
|
||||
def aim(api, wanted):
|
||||
"""Для 2 реплик: последним перед тестом должна ответить реплика из wanted."""
|
||||
probe = api.call("GET", "/health/live", schema="Health")["headers"]["X-Instance-Id"]
|
||||
if not any(container.startswith(probe) for container in wanted):
|
||||
api.call("GET", "/health/live", schema="Health") # теперь последней ответила другая реплика
|
||||
|
||||
|
||||
def main():
|
||||
api = Client()
|
||||
containers = api_containers()
|
||||
check(len(containers) >= 2, "need at least 2 running api replicas")
|
||||
print(f"hook: {HOOK.relative_to(ROOT).as_posix()}; api replicas: {[c[:12] for c in containers]}")
|
||||
stopped_once = set()
|
||||
for attempt in range(1, 7):
|
||||
wait_balanced(len(containers))
|
||||
if len(containers) == 2:
|
||||
aim(api, set(containers) - stopped_once)
|
||||
print(f"\n=== run {attempt}: containers before (HAProxy: {lb_summary()})")
|
||||
print(ps_table())
|
||||
env = dict(os.environ, PYTHONUTF8="1", PYTHONIOENCODING="utf-8")
|
||||
result = subprocess.run([sys.executable, "tests/resilience.py", "--mode", "failover",
|
||||
"--action-script", str(HOOK), "--base-url", BASE_URL],
|
||||
cwd=ROOT, capture_output=True, env=env)
|
||||
print((result.stdout + result.stderr).decode("utf-8", "replace").strip())
|
||||
check(result.returncode == 0, "public failover test failed")
|
||||
print(f"containers after (HAProxy: {lb_summary()})")
|
||||
print(ps_table())
|
||||
stopped = [container for container in containers if container not in api_containers()]
|
||||
check(len(stopped) == 1, f"expected exactly one stopped api container, got {len(stopped)}")
|
||||
print(f"the hook stopped {stopped[0][:12]} (X-Instance-Id of that replica = container ID); "
|
||||
f"other api containers, postgres, valkey, s3 and lb kept running")
|
||||
stopped_once.add(stopped[0])
|
||||
docker("start", stopped[0])
|
||||
wait_balanced(len(containers))
|
||||
print(f"restored: docker start {stopped[0][:12]} -> healthy and back in HAProxy ({lb_summary()})")
|
||||
if stopped_once == set(containers):
|
||||
break
|
||||
check(stopped_once == set(containers), "not every replica was stopped by the public test")
|
||||
print(f"\nPASS: public failover test passed {attempt} times; every api replica was stopped once and restored")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,60 @@
|
||||
"""Публичный тест сохранности (tests/resilience.py --mode persistence) и доказательство,
|
||||
что hook scripts/restart.cmd (Windows) или scripts/restart.sh действительно перезапустил процессы.
|
||||
|
||||
make persistence (= python student-tests/run_persistence.py)
|
||||
|
||||
До и после теста печатаются все контейнеры стенда с временем старта (StartedAt). После теста
|
||||
у postgres, valkey, s3, обеих реплик api и lb должен быть ТОТ ЖЕ ID контейнера (контейнеры и volumes
|
||||
те же, ничего не пересоздано) и НОВОЕ время старта (процесс перезапущен). Сам тест проверяет,
|
||||
что данные и прежний токен на месте. Сервис migrate при `docker compose start api` запускается
|
||||
снова как зависимость: он видит, что новых миграций нет, и сразу завершается.
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from helpers import ROOT, check, run
|
||||
from stand import BASE_URL, compose_output, inspect, ps_table
|
||||
|
||||
HOOK = ROOT / "scripts" / ("restart.cmd" if os.name == "nt" else "restart.sh")
|
||||
MUST_RESTART = ("api", "postgres", "valkey", "s3", "lb")
|
||||
|
||||
|
||||
def started_at():
|
||||
"""{ID контейнера: (сервис, время старта)} для работающих сервисов стенда."""
|
||||
result = {}
|
||||
for container in compose_output("ps", "-q").split():
|
||||
service = inspect(container, '{{index .Config.Labels "com.docker.compose.service"}}')
|
||||
result[container] = (service, inspect(container, "{{.State.StartedAt}}"))
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
print(f"hook: {HOOK.relative_to(ROOT).as_posix()}")
|
||||
print("=== containers before")
|
||||
print(ps_table())
|
||||
before = started_at()
|
||||
env = dict(os.environ, PYTHONUTF8="1", PYTHONIOENCODING="utf-8")
|
||||
t0 = time.monotonic()
|
||||
result = subprocess.run([sys.executable, "tests/resilience.py", "--mode", "persistence",
|
||||
"--action-script", str(HOOK), "--base-url", BASE_URL],
|
||||
cwd=ROOT, capture_output=True, env=env)
|
||||
took = time.monotonic() - t0
|
||||
print((result.stdout + result.stderr).decode("utf-8", "replace").strip())
|
||||
check(result.returncode == 0, "public persistence test failed")
|
||||
print(f"=== containers after (test took {took:.1f} s: hook + waiting for readiness + data checks)")
|
||||
print(ps_table())
|
||||
after = started_at()
|
||||
for container, (service, start) in sorted(before.items(), key=lambda item: item[1]):
|
||||
if service not in MUST_RESTART:
|
||||
continue
|
||||
check(container in after, f"{service} {container[:12]} was recreated or is not running")
|
||||
check(after[container][1] != start, f"{service} {container[:12]} was not restarted")
|
||||
print(f"{service:<9} {container[:12]}: same container, start time {start[11:19]} -> {after[container][1][11:19]}")
|
||||
print("PASS: api replicas, postgres, valkey, s3 and lb were restarted (same containers and volumes, "
|
||||
"new start time); data, the attachment bytes and the existing token survived")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,144 @@
|
||||
"""lab4, уровень 4: S3 приватный, у API минимальные права, консоль закрыта, bootstrap идемпотентен.
|
||||
|
||||
make s3-checks (= python student-tests/s3_checks.py)
|
||||
|
||||
Все проверки идут ВНЕ API (напрямую в S3, в PostgreSQL и в файловую систему контейнеров):
|
||||
1. анонимный GET объекта, список объектов bucket и список bucket'ов -> 403 (bucket приватный);
|
||||
2. с ключами API объект читается (байты действительно в S3), но создать bucket, сделать bucket
|
||||
публичным, удалить bucket или получить список всех bucket'ов нельзя -> AccessDenied;
|
||||
3. веб-интерфейсы SeaweedFS (master :9333, filer :8888, volume :8080) не слушают в сети,
|
||||
порт S3 не опубликован на хосте;
|
||||
4. в таблице attachments нет столбца с байтами (bytea), а на дисках реплик API нет файла оригинала;
|
||||
5. s3-init запускается ещё два раза: оба раза код 0, объекты на месте, файл скачивается.
|
||||
"""
|
||||
import hashlib
|
||||
import json
|
||||
import socket
|
||||
import subprocess
|
||||
import uuid
|
||||
|
||||
from filegen import SAMPLE_PNG, cleanup_cli, exec_python, in_api, psql, upload_when_ready
|
||||
from helpers import ROOT, Client, check, run
|
||||
from stand import api_containers
|
||||
|
||||
DIRECT = """
|
||||
import hashlib, json, socket, urllib.error, urllib.request
|
||||
from botocore.exceptions import ClientError
|
||||
from messenger import config, objects
|
||||
base, bucket, key = config.S3_ENDPOINT, config.S3_BUCKET, "{key}"
|
||||
def anonymous(url):
|
||||
try:
|
||||
return urllib.request.urlopen(url, timeout=5).status
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code
|
||||
out = {{"anonymous_get_object": anonymous(f"{{base}}/{{bucket}}/{{key}}"),
|
||||
"anonymous_list_bucket": anonymous(f"{{base}}/{{bucket}}?list-type=2"),
|
||||
"anonymous_list_buckets": anonymous(f"{{base}}/")}}
|
||||
s3 = objects.client()
|
||||
out["api_key_get_object_sha256"] = hashlib.sha256(s3.get_object(Bucket=bucket, Key=key)["Body"].read()).hexdigest()
|
||||
public = json.dumps({{"Version": "2012-10-17", "Statement": [{{"Effect": "Allow", "Principal": {{"AWS": ["*"]}},
|
||||
"Action": ["s3:GetObject"], "Resource": [f"arn:aws:s3:::{{bucket}}/*"]}}]}})
|
||||
try:
|
||||
out["api_key_list_buckets"] = sorted(b["Name"] for b in s3.list_buckets().get("Buckets", []))
|
||||
except ClientError as exc:
|
||||
out["api_key_list_buckets"] = exc.response["Error"]["Code"]
|
||||
for name, call in (("create_bucket", lambda: s3.create_bucket(Bucket="lab4-forbidden-bucket")),
|
||||
("make_bucket_public", lambda: s3.put_bucket_policy(Bucket=bucket, Policy=public)),
|
||||
("delete_bucket", lambda: s3.delete_bucket(Bucket=bucket))):
|
||||
try:
|
||||
call()
|
||||
out["api_key_" + name] = "ALLOWED"
|
||||
except ClientError as exc:
|
||||
out["api_key_" + name] = exc.response["Error"]["Code"]
|
||||
for port in (9333, 8888, 8080):
|
||||
try:
|
||||
socket.create_connection(("s3", port), timeout=2).close()
|
||||
out[f"admin_port_{{port}}"] = "open"
|
||||
except OSError:
|
||||
out[f"admin_port_{{port}}"] = "closed"
|
||||
out["bucket"] = bucket
|
||||
print(json.dumps(out))
|
||||
"""
|
||||
|
||||
FIND_LOCAL_COPY = """
|
||||
import hashlib, os
|
||||
size, wanted, found = {size}, "{sha}", []
|
||||
for root, dirs, files in os.walk("/"):
|
||||
dirs[:] = [d for d in dirs if os.path.join(root, d) not in ("/proc", "/sys", "/dev")]
|
||||
for name in files:
|
||||
path = os.path.join(root, name)
|
||||
try:
|
||||
if os.path.isfile(path) and os.path.getsize(path) == size:
|
||||
with open(path, "rb") as f:
|
||||
if hashlib.sha256(f.read()).hexdigest() == wanted:
|
||||
found.append(path)
|
||||
except OSError:
|
||||
pass
|
||||
print(len(found))
|
||||
"""
|
||||
|
||||
|
||||
def host_port_closed(port):
|
||||
try:
|
||||
socket.create_connection(("127.0.0.1", port), timeout=1).close()
|
||||
return False
|
||||
except OSError:
|
||||
return True
|
||||
|
||||
|
||||
def main():
|
||||
api = Client()
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
att = upload_when_ready(api, alice, chat, name="private.png")["json"]
|
||||
key = psql(f"SELECT storage_key FROM attachments WHERE id = '{uuid.UUID(att['id'])}'")
|
||||
check(key.startswith("originals/") and "private" not in key, "object key must be server-generated")
|
||||
print(f"object key is server-generated: originals/<random uuid> (filename is not used in the key)")
|
||||
|
||||
out = json.loads(in_api(DIRECT.format(key=key)))
|
||||
for name in ("anonymous_get_object", "anonymous_list_bucket", "anonymous_list_buckets"):
|
||||
print(f"{name}: HTTP {out[name]}")
|
||||
check(out[name] == 403, f"{name} must be 403")
|
||||
check(out["api_key_get_object_sha256"] == att["sha256"], "object in S3 differs from the upload")
|
||||
print("API key GetObject: same SHA-256 as uploaded (the bytes are in the bucket)")
|
||||
# SeaweedFS на ListBuckets показывает только bucket'ы, на которые у пользователя есть право List,
|
||||
# к которым у пользователя есть доступ: чужих bucket'ов API в любом случае не видит.
|
||||
listed = out["api_key_list_buckets"]
|
||||
print(f"API key list_buckets: {listed}")
|
||||
check(listed == "AccessDenied" or set(listed) <= {"messenger-attachments", out["bucket"]},
|
||||
"API key sees other buckets")
|
||||
for name in ("create_bucket", "make_bucket_public", "delete_bucket"):
|
||||
print(f"API key {name}: {out['api_key_' + name]}")
|
||||
check(out["api_key_" + name] != "ALLOWED", f"API key must not be allowed to {name}")
|
||||
for port in (9333, 8888, 8080):
|
||||
print(f"SeaweedFS admin/UI port {port} inside the network: {out[f'admin_port_{port}']}")
|
||||
check(out[f"admin_port_{port}"] == "closed", f"SeaweedFS port {port} must not be reachable")
|
||||
check(host_port_closed(9000) and host_port_closed(9333) and host_port_closed(8888),
|
||||
"S3 ports must not be published on the host")
|
||||
print("host 127.0.0.1:9000, :9333, :8888: closed (S3 is not published)")
|
||||
|
||||
columns = psql("SELECT string_agg(column_name || ':' || data_type, ', ' ORDER BY ordinal_position) "
|
||||
"FROM information_schema.columns WHERE table_name = 'attachments'")
|
||||
print(f"attachments columns: {columns}")
|
||||
check("bytea" not in columns, "attachment bytes must not be stored in PostgreSQL")
|
||||
for container in api_containers():
|
||||
code = FIND_LOCAL_COPY.format(size=len(SAMPLE_PNG), sha=att["sha256"])
|
||||
found = exec_python(container, code)
|
||||
print(f"api {container[:12]}: files with the same SHA-256 on disk: {found}")
|
||||
check(found == "0", "an API replica keeps a local copy of the original")
|
||||
|
||||
before = cleanup_cli("--dry-run")["objects_in_bucket"]
|
||||
for attempt in (1, 2):
|
||||
result = subprocess.run(["docker", "compose", "run", "--rm", "s3-init"], cwd=ROOT, capture_output=True)
|
||||
last = (result.stdout.decode("utf-8", "replace").strip().splitlines() or [""])[-1]
|
||||
print(f"s3-init run {attempt}: exit {result.returncode}: {last}")
|
||||
check(result.returncode == 0, "s3-init is not idempotent")
|
||||
after = cleanup_cli("--dry-run")["objects_in_bucket"]
|
||||
got = api.call("GET", f"/api/v1/attachments/{att['id']}/content", actor=bob)["bytes"]
|
||||
check(before == after and hashlib.sha256(got).hexdigest() == att["sha256"], "bootstrap changed the data")
|
||||
print(f"objects in bucket before/after bootstrap: {before}/{after}; the file still downloads")
|
||||
print("PASS: bucket is private outside the API, the API S3 user has least privilege, the console is "
|
||||
"closed, bytes are only in S3, bucket bootstrap is idempotent")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,193 @@
|
||||
"""Помощники lab3 для собственных проверок: реплики, балансировщик, Docker.
|
||||
|
||||
Только стандартная библиотека Python. Docker вызывается прямо из Python (`docker compose ...`),
|
||||
поэтому всё работает одинаково в Git Bash, PowerShell и cmd на Windows.
|
||||
Вывод проверок — латиницей и кириллицей в UTF-8 (в Git Bash задан PYTHONUTF8=1).
|
||||
"""
|
||||
import csv
|
||||
import http.client
|
||||
import io
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from helpers import ROOT, check
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
|
||||
LB_STATS_URL = os.environ.get("LB_STATS_URL", "http://127.0.0.1:8404/stats;csv")
|
||||
|
||||
|
||||
class Reply:
|
||||
"""Ответ без проверок: для нагрузки во время отказа, где ошибки — ожидаемая часть замера."""
|
||||
|
||||
def __init__(self, status, headers, data):
|
||||
self.status = status
|
||||
self.headers = {name.lower(): value for name, value in headers.items()}
|
||||
try:
|
||||
self.json = json.loads(data.decode("utf-8")) if data else None
|
||||
except ValueError:
|
||||
self.json = None
|
||||
|
||||
@property
|
||||
def instance(self):
|
||||
return self.headers.get("x-instance-id")
|
||||
|
||||
|
||||
def try_call(method, path, *, body=None, raw=None, token=None, headers=None, timeout=2.0):
|
||||
"""HTTP-запрос через балансировщик. Reply или None, если соединение оборвалось / вышел timeout.
|
||||
|
||||
Обрыв возможен и посреди ответа (реплику убили, когда заголовки уже ушли): http.client.HTTPException.
|
||||
"""
|
||||
all_headers = dict(headers or {})
|
||||
data = raw
|
||||
if body is not None:
|
||||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||||
if data is not None:
|
||||
all_headers.setdefault("Content-Type", "application/json")
|
||||
if token is not None:
|
||||
all_headers["Authorization"] = "Bearer " + token
|
||||
request = urllib.request.Request(BASE_URL + path, data=data, method=method, headers=all_headers)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=timeout) as reply:
|
||||
return Reply(reply.status, reply.headers, reply.read())
|
||||
except urllib.error.HTTPError as error:
|
||||
try:
|
||||
return Reply(error.code, error.headers, error.read())
|
||||
except (OSError, http.client.HTTPException):
|
||||
return None
|
||||
except (urllib.error.URLError, OSError, http.client.HTTPException):
|
||||
return None
|
||||
|
||||
|
||||
# ---------- Docker ----------
|
||||
|
||||
def docker(*args, check_exit=True):
|
||||
"""docker <args>; возвращает stdout."""
|
||||
result = subprocess.run(["docker", *args], cwd=ROOT, capture_output=True, check=check_exit)
|
||||
return result.stdout.decode("utf-8", "replace").strip()
|
||||
|
||||
|
||||
def compose_output(*args, env=None):
|
||||
"""docker compose <args> и его вывод (stdout + stderr). Секретов в нём нет: ps, logs, build."""
|
||||
result = subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, check=True, env=env)
|
||||
return result.stdout.decode("utf-8", "replace") + result.stderr.decode("utf-8", "replace")
|
||||
|
||||
|
||||
def compose_config():
|
||||
"""Итоговая конфигурация стенда (docker compose config) как словарь: только stdout, без предупреждений."""
|
||||
result = subprocess.run(["docker", "compose", "config", "--format", "json"], cwd=ROOT,
|
||||
capture_output=True, check=True)
|
||||
return json.loads(result.stdout.decode("utf-8"))
|
||||
|
||||
|
||||
def compose_quiet(*args, env=None):
|
||||
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True, env=env,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def api_containers(include_stopped=False):
|
||||
"""Полные ID контейнеров сервиса api (по умолчанию только запущенные), по порядку."""
|
||||
args = ["ps", "-q", "-a", "api"] if include_stopped else ["ps", "-q", "api"]
|
||||
return sorted(compose_output(*args).split())
|
||||
|
||||
|
||||
def inspect(container, template):
|
||||
return docker("inspect", "-f", template, container, check_exit=False)
|
||||
|
||||
|
||||
def health(container):
|
||||
"""Статус Docker healthcheck: starting / healthy / unhealthy / ''."""
|
||||
return inspect(container, "{{if .State.Health}}{{.State.Health.Status}}{{end}}")
|
||||
|
||||
|
||||
def ps_table():
|
||||
"""Все контейнеры стенда: сервис, короткий ID (= X-Instance-Id у api), состояние, время старта."""
|
||||
lines = []
|
||||
for container in sorted(compose_output("ps", "-a", "-q").split()):
|
||||
info = inspect(container, '{{index .Config.Labels "com.docker.compose.service"}}|{{.State.Status}}|'
|
||||
'{{.State.StartedAt}}|{{if .State.Health}}{{.State.Health.Status}}{{end}}')
|
||||
service, status, started, healthy = (info.split("|") + ["", "", "", ""])[:4]
|
||||
shown = f"{status} ({healthy})" if healthy and status == "running" else status
|
||||
lines.append((service, container[:12], shown, started[:23]))
|
||||
lines.sort()
|
||||
width = max((len(service) for service, *_ in lines), default=7)
|
||||
text = [f"{'SERVICE':<{width}} CONTAINER STATE STARTED AT (UTC)"]
|
||||
text += [f"{service:<{width}} {cid} {state:<19} {started}" for service, cid, state, started in lines]
|
||||
return "\n".join(text)
|
||||
|
||||
|
||||
# ---------- балансировщик ----------
|
||||
|
||||
def lb_rows(backend="api"):
|
||||
"""Строки статистики HAProxy (CSV) по серверам backend: имя, статус, backup-флаг, результат проверки."""
|
||||
with urllib.request.urlopen(LB_STATS_URL, timeout=2) as reply:
|
||||
rows = list(csv.reader(io.StringIO(reply.read().decode("utf-8", "replace"))))
|
||||
header = [name.lstrip("# ") for name in rows[0]]
|
||||
items = [dict(zip(header, row)) for row in rows[1:]]
|
||||
return [item for item in items
|
||||
if item.get("pxname") == backend and item.get("svname") not in ("FRONTEND", "BACKEND")]
|
||||
|
||||
|
||||
def lb_servers(backend="api"):
|
||||
"""Слоты backend в HAProxy: {имя: статус}, например {'api1': 'UP'}."""
|
||||
return {item["svname"]: item.get("status", "") for item in lb_rows(backend)}
|
||||
|
||||
|
||||
def lb_up_count():
|
||||
"""Сколько реплик (слоты api1..api6) HAProxy держит в балансировке (UP)."""
|
||||
return sum(1 for name, status in lb_servers().items() if name.startswith("api") and status.startswith("UP"))
|
||||
|
||||
|
||||
def lb_summary():
|
||||
"""Короткая строка состояния основных слотов: 'api1 UP, api2 DOWN' (пустые слоты MAINT не показываем)."""
|
||||
servers = lb_servers()
|
||||
shown = [f"{name} {status}" for name, status in sorted(servers.items())
|
||||
if name.startswith("api") and not status.startswith("MAINT")]
|
||||
return ", ".join(shown) or "no api servers"
|
||||
|
||||
|
||||
def wait_balanced(replicas, seconds=90):
|
||||
"""Ждёт, пока replicas контейнеров api healthy и HAProxy держит их в балансировке (UP)."""
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
running = api_containers()
|
||||
healthy = [container for container in running if health(container) == "healthy"]
|
||||
try:
|
||||
up = lb_up_count()
|
||||
except OSError:
|
||||
up = 0
|
||||
if len(healthy) >= replicas and up >= replicas:
|
||||
return running
|
||||
check(time.monotonic() < deadline,
|
||||
f"after {seconds} s: {len(healthy)} healthy api containers, {up} UP in HAProxy, need {replicas}")
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def replica_status(container, path):
|
||||
"""Код ответа реплики на GET path изнутри её контейнера, в обход балансировщика.
|
||||
|
||||
Так видно состояние самой реплики (жива ли, готова ли), когда балансировщик её уже исключил.
|
||||
Одна строка без переводов строк: так команда одинаково передаётся и на Windows, и на Linux.
|
||||
"""
|
||||
code = ("import http.client as h; c = h.HTTPConnection('127.0.0.1', 8080, timeout=5); "
|
||||
f"c.request('GET', '{path}'); print(c.getresponse().status)")
|
||||
return int(docker("exec", container, "python", "-c", code))
|
||||
|
||||
|
||||
def valkey_stats():
|
||||
"""keyspace_hits и keyspace_misses Valkey (пользователь health без пароля: только info/ping/dbsize)."""
|
||||
output = compose_output("exec", "-T", "valkey", "valkey-cli", "--user", "health", "--pass", "none",
|
||||
"--no-auth-warning", "info", "stats")
|
||||
stats = dict(line.strip().split(":", 1) for line in output.splitlines() if line.startswith("keyspace_"))
|
||||
return int(stats["keyspace_hits"]), int(stats["keyspace_misses"])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
# make restore: после `docker compose up -d --wait` дождаться, пока HAProxy вернёт в работу
|
||||
# ВСЕ запущенные реплики (DNS + 2 удачные проверки готовности — ещё несколько секунд).
|
||||
replicas = len(api_containers())
|
||||
wait_balanced(replicas)
|
||||
print(f"all {replicas} api replicas are healthy and UP in HAProxy: {lb_summary()}")
|
||||
@@ -0,0 +1,164 @@
|
||||
"""Собственные тесты API (перенесены из lab1, переведены на пароль и Bearer).
|
||||
|
||||
Тесты «чёрного ящика»: шлют настоящие HTTP-запросы на уже запущенный стенд
|
||||
(BASE_URL, по умолчанию http://127.0.0.1:8080 из Makefile; с lab3 это балансировщик,
|
||||
и запросы обслуживают разные реплики). С lab3 POST сообщения несёт Idempotency-Key.
|
||||
Запуск вместе с остальными test_*.py одной командой: make student-test
|
||||
"""
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
from helpers import Client, basic, idempotency, read_history
|
||||
|
||||
PASSWORD = "Test-password-123"
|
||||
|
||||
|
||||
class MessengerApiTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.api = Client()
|
||||
cls.alice, cls.bob, cls.eve, cls.chat = cls.api.bootstrap() # eve не состоит в чате
|
||||
|
||||
def messages_path(self, chat_id):
|
||||
return f"/api/v1/chats/{chat_id}/messages"
|
||||
|
||||
def send(self, actor, chat_id, text, expected=201):
|
||||
schema = "Message" if expected == 201 else None # клиент разбирает JSON успешного ответа только со схемой
|
||||
return self.api.call("POST", self.messages_path(chat_id), expected, actor=actor,
|
||||
body={"text": text}, headers=idempotency(), schema=schema)
|
||||
|
||||
def new_chat(self):
|
||||
body = {"title": "Тест", "member_ids": [self.alice["id"], self.bob["id"]]}
|
||||
return self.api.call("POST", "/api/v1/chats", 201, actor=self.alice, body=body, schema="Chat")["json"]
|
||||
|
||||
def test_malformed_json_returns_400(self):
|
||||
json_header = {"Content-Type": "application/json"}
|
||||
for raw in (b'{"username": "abc",', b"not json", b""):
|
||||
self.api.call("POST", "/api/v1/users", 400, raw=raw, headers=json_header)
|
||||
self.api.call("POST", self.messages_path(self.chat["id"]), 400,
|
||||
actor=self.alice, raw=raw, headers={**json_header, **idempotency()})
|
||||
|
||||
def test_wrong_types_and_extra_fields_return_400(self):
|
||||
self.api.call("POST", "/api/v1/users", 400,
|
||||
body={"username": 123, "display_name": "x", "password": PASSWORD})
|
||||
self.api.call("POST", "/api/v1/users", 400,
|
||||
body={"username": "valid_name", "display_name": "x", "password": PASSWORD, "is_admin": True})
|
||||
self.api.call("POST", "/api/v1/users", 400,
|
||||
body={"username": "Bad Name!", "display_name": "x", "password": PASSWORD})
|
||||
# Отправителя нельзя подставить: он берётся из сессии.
|
||||
self.api.call("POST", self.messages_path(self.chat["id"]), 400, actor=self.alice,
|
||||
body={"text": "hi", "sender_id": self.bob["id"]}, headers=idempotency())
|
||||
|
||||
def test_outsider_gets_404_for_foreign_chat(self):
|
||||
chat_id = self.chat["id"]
|
||||
self.api.call("GET", f"/api/v1/chats/{chat_id}", 404, actor=self.eve)
|
||||
self.api.call("GET", self.messages_path(chat_id), 404, actor=self.eve)
|
||||
self.send(self.eve, chat_id, "чужое", expected=404)
|
||||
# Несуществующий чат выглядит так же, как чужой: существование не раскрывается.
|
||||
self.api.call("GET", f"/api/v1/chats/{uuid.uuid4()}", 404, actor=self.eve)
|
||||
|
||||
def test_auth_checked_before_access_and_body(self):
|
||||
# Без токена — всегда 401, даже если тело кривое или чат чужой: сначала «кто ты».
|
||||
self.api.call("POST", self.messages_path(self.chat["id"]), 401, raw=b"not json",
|
||||
headers={"Content-Type": "application/json", **idempotency()})
|
||||
self.api.call("GET", f"/api/v1/chats/{uuid.uuid4()}", 401)
|
||||
|
||||
def test_empty_blank_and_too_long_messages_return_400(self):
|
||||
for text in ("", " ", "\n\t "):
|
||||
self.send(self.alice, self.chat["id"], text, expected=400)
|
||||
self.send(self.alice, self.chat["id"], "я" * 4001, expected=400)
|
||||
self.send(self.alice, self.chat["id"], "я" * 4000) # ровно на границе — можно
|
||||
|
||||
def test_duplicate_username_returns_409(self):
|
||||
body = {"username": "dup_" + uuid.uuid4().hex[:12], "display_name": "Первый", "password": PASSWORD}
|
||||
self.api.call("POST", "/api/v1/users", 201, body=body)
|
||||
self.api.call("POST", "/api/v1/users", 409, body=dict(body, display_name="Второй"))
|
||||
|
||||
def test_unicode_roundtrip(self):
|
||||
text = "Привет 👋 你好 ﷽ é"
|
||||
sent = self.send(self.alice, self.chat["id"], text)["json"]
|
||||
self.assertEqual(sent["text"], text)
|
||||
history, _ = read_history(self.api, self.bob, self.chat["id"])
|
||||
self.assertIn(text, [m["text"] for m in history])
|
||||
# Длина считается в символах Unicode: 100 эмодзи можно, 101 — нет.
|
||||
name = "n_" + uuid.uuid4().hex[:12]
|
||||
self.api.call("POST", "/api/v1/users", 400,
|
||||
body={"username": name, "display_name": "👋" * 101, "password": PASSWORD})
|
||||
self.api.call("POST", "/api/v1/users", 201,
|
||||
body={"username": name, "display_name": "👋" * 100, "password": PASSWORD})
|
||||
|
||||
def test_nul_character_is_stored(self):
|
||||
# Замечание к MR: U+0000 допустим по контракту и должен сохраняться как есть, а не давать 500.
|
||||
name = "nul_" + uuid.uuid4().hex[:10]
|
||||
password = "Pass\u0000word-123"
|
||||
user = self.api.call("POST", "/api/v1/users", 201, schema="User",
|
||||
body={"username": name, "display_name": "A\u0000B", "password": password})["json"]
|
||||
self.assertEqual(user["display_name"], "A\u0000B")
|
||||
session = self.api.call("POST", "/api/v1/auth/sessions", 201, schema="Session",
|
||||
headers={"Authorization": basic(name, password)})["json"]
|
||||
self.assertEqual(session["user"]["display_name"], "A\u0000B")
|
||||
chat = self.api.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat",
|
||||
body={"title": "T\u0000itle", "member_ids": [self.alice["id"], self.bob["id"]]})["json"]
|
||||
self.assertEqual(chat["title"], "T\u0000itle")
|
||||
sent = self.send(self.alice, chat["id"], "hello\u0000world")["json"]
|
||||
self.assertEqual(sent["text"], "hello\u0000world")
|
||||
history, _ = read_history(self.api, self.bob, chat["id"])
|
||||
self.assertEqual([m["text"] for m in history], ["hello\u0000world"])
|
||||
got = self.api.call("GET", f"/api/v1/chats/{chat['id']}", actor=self.bob, schema="Chat")["json"]
|
||||
self.assertEqual(got["title"], "T\u0000itle")
|
||||
# username с U+0000 существовать не может: вход — обычный 401, а не 500.
|
||||
self.api.call("POST", "/api/v1/auth/sessions", 401, headers={"Authorization": basic("ab\u0000c", password)})
|
||||
|
||||
def test_pagination_walks_several_pages(self):
|
||||
chat = self.new_chat()
|
||||
sent = [self.send(self.alice, chat["id"], f"msg {i}")["json"] for i in range(7)]
|
||||
history, pages = read_history(self.api, self.bob, chat["id"], limit=3)
|
||||
self.assertEqual(pages, 3) # 3 + 3 + 1
|
||||
self.assertEqual([m["id"] for m in history], [m["id"] for m in sent]) # без потерь, дублей и перестановок
|
||||
|
||||
def test_chat_list_pagination(self):
|
||||
created = [self.new_chat()["id"] for _ in range(3)]
|
||||
seen, cursor = [], None
|
||||
while True:
|
||||
query = "?limit=2" + (f"&cursor={cursor}" if cursor else "")
|
||||
page = self.api.call("GET", "/api/v1/chats" + query, actor=self.bob, schema="ChatPage")["json"]
|
||||
seen += [c["id"] for c in page["items"]]
|
||||
cursor = page["next_cursor"]
|
||||
if cursor is None:
|
||||
break
|
||||
self.assertEqual(len(seen), len(set(seen)))
|
||||
self.assertEqual(seen[-3:], created) # новые чаты в конце, порядок (created_at, id)
|
||||
|
||||
def test_bad_cursor_returns_400(self):
|
||||
chat_a, chat_b = self.new_chat(), self.new_chat()
|
||||
for i in range(2):
|
||||
self.send(self.alice, chat_a["id"], f"a{i}")
|
||||
first = self.api.call("GET", self.messages_path(chat_a["id"]) + "?limit=1",
|
||||
actor=self.alice, schema="MessagePage")["json"]
|
||||
foreign_cursor = first["next_cursor"]
|
||||
self.api.call("GET", self.messages_path(chat_b["id"]) + "?cursor=" + foreign_cursor, 400, actor=self.alice)
|
||||
self.api.call("GET", self.messages_path(chat_a["id"]) + "?cursor=garbage", 400, actor=self.alice)
|
||||
# Курсор правильной формы, но с испорченным временем/UUID: 400, а не ошибка БД (500).
|
||||
import base64
|
||||
import json
|
||||
scope = "messages:" + chat_a["id"]
|
||||
for bad in ([scope, "not-a-time", str(uuid.uuid4())],
|
||||
[scope, "2026-01-01T00:00:00.000000Z", "not-a-uuid"],
|
||||
[scope, "2026-01-01T00:00:00", str(uuid.uuid4())], # без часового пояса
|
||||
[scope, "0001-01-01T00:00:00+14:00", str(uuid.uuid4())], # в UTC это год 0
|
||||
[scope, "9999-12-31T23:59:59-14:00", str(uuid.uuid4())]): # в UTC это год 10000
|
||||
forged = base64.urlsafe_b64encode(json.dumps(bad).encode()).decode()
|
||||
self.api.call("GET", self.messages_path(chat_a["id"]) + "?cursor=" + forged, 400, actor=self.alice)
|
||||
for limit in ("0", "101", "abc"):
|
||||
self.api.call("GET", self.messages_path(chat_a["id"]) + "?limit=" + limit, 400, actor=self.alice)
|
||||
|
||||
def test_chat_membership_rules(self):
|
||||
alice, bob = self.alice["id"], self.bob["id"]
|
||||
for members in ([bob], [alice, alice], [alice, str(uuid.uuid4())]): # без себя, дубль, неизвестный
|
||||
self.api.call("POST", "/api/v1/chats", 400, actor=self.alice, body={"title": "x", "member_ids": members})
|
||||
chats = self.api.call("GET", "/api/v1/chats?limit=100", actor=self.eve, schema="ChatPage")["json"]
|
||||
self.assertNotIn(self.chat["id"], [c["id"] for c in chats["items"]])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,185 @@
|
||||
"""lab4: вложения через API (входит в make student-test; нужен только запущенный стенд).
|
||||
|
||||
Уровень 3: PNG и JPEG загружаются и скачиваются побайтно, посторонний получает 404.
|
||||
Уровень 4: слишком большой файл, «бомба» по пикселям, повреждённые файлы, подмена MIME,
|
||||
опасные filename, чужое attachment_id и вложение другого чата. Каждый случай проверяется
|
||||
по точному коду ответа: пользовательская ошибка никогда не превращается в 500.
|
||||
"""
|
||||
import hashlib
|
||||
import unittest
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
from filegen import (SAMPLE_JPEG, SAMPLE_PNG, bomb_png, corrupt_crc, png, raw_upload, truncated)
|
||||
from helpers import Client, idempotency
|
||||
|
||||
MAX = 10 * 1024 * 1024
|
||||
|
||||
|
||||
class AttachmentTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.api = Client()
|
||||
cls.alice, cls.bob, cls.eve, cls.chat = cls.api.bootstrap()
|
||||
# Второй чат Алисы (с Евой) и чат Евы с Бобом: для проверок «чужое» и «из другого чата».
|
||||
cls.other_chat = cls.chat_of(cls.alice, cls.eve)
|
||||
cls.eve_chat = cls.chat_of(cls.eve, cls.bob)
|
||||
|
||||
@classmethod
|
||||
def chat_of(cls, creator, other):
|
||||
return cls.api.call("POST", "/api/v1/chats", 201, actor=creator, schema="Chat",
|
||||
body={"title": "lab4", "member_ids": [creator["id"], other["id"]]})["json"]
|
||||
|
||||
def upload(self, data, ctype="image/png", name="photo.png", expected=201, actor=None, chat=None):
|
||||
chat = chat or self.chat
|
||||
query = "" if name is None else "?filename=" + quote(name, safe="")
|
||||
return self.api.call("POST", f"/api/v1/chats/{chat['id']}/attachments{query}", expected,
|
||||
actor=actor or self.alice, raw=data, headers={"Content-Type": ctype},
|
||||
schema="Attachment" if expected == 201 else None)
|
||||
|
||||
def post_message(self, body, expected=201, key=None):
|
||||
return self.api.call("POST", f"/api/v1/chats/{self.chat['id']}/messages", expected, actor=self.alice,
|
||||
body=body, headers=idempotency(key), schema="Message" if expected == 201 else None)
|
||||
|
||||
# ---------- уровень 3 ----------
|
||||
|
||||
def test_png_and_jpeg_roundtrip_for_member(self):
|
||||
for data, ctype, name in ((SAMPLE_PNG, "image/png", "sample.png"), (SAMPLE_JPEG, "image/jpeg", "кот 🐱.jpg")):
|
||||
att = self.upload(data, ctype, name)["json"]
|
||||
self.assertEqual((att["status"], att["variants"], att["error_code"]), ("ready", [], None))
|
||||
self.assertEqual((att["content_type"], att["filename"], att["size_bytes"]), (ctype, name, len(data)))
|
||||
self.assertEqual(att["sha256"], hashlib.sha256(data).hexdigest())
|
||||
meta = self.api.call("GET", f"/api/v1/attachments/{att['id']}", actor=self.bob, schema="Attachment")
|
||||
self.assertEqual(meta["json"], att)
|
||||
got = self.api.call("GET", f"/api/v1/attachments/{att['id']}/content", actor=self.bob)
|
||||
self.assertEqual(got["bytes"], data)
|
||||
self.assertEqual(got["headers"].get_content_type(), ctype)
|
||||
self.assertEqual(got["headers"].get("X-Content-Type-Options"), "nosniff")
|
||||
for suffix in ("", "/content"): # посторонний не узнаёт, что вложение существует
|
||||
self.api.call("GET", f"/api/v1/attachments/{att['id']}{suffix}", 404, actor=self.eve)
|
||||
self.api.call("GET", f"/api/v1/attachments/{att['id']}{suffix}", 401)
|
||||
|
||||
def test_outsider_and_anonymous_cannot_upload(self):
|
||||
self.upload(SAMPLE_PNG, actor=self.eve, expected=404) # Ева не участник чата
|
||||
self.api.call("POST", f"/api/v1/chats/{self.chat['id']}/attachments?filename=a.png", 401,
|
||||
raw=SAMPLE_PNG, headers={"Content-Type": "image/png"})
|
||||
self.upload(SAMPLE_PNG, chat={"id": str(uuid.uuid4())}, expected=404)
|
||||
self.upload(SAMPLE_PNG, chat={"id": "not-a-uuid"}, expected=400)
|
||||
|
||||
# ---------- уровень 4: размер ----------
|
||||
|
||||
def test_too_large_is_413_before_reading(self):
|
||||
# Заявлено 10 MiB + 1 байт: ответ 413 приходит сразу, сервер тело не читает.
|
||||
reply = raw_upload(f"/api/v1/chats/{self.chat['id']}/attachments?filename=big.png",
|
||||
self.alice["token"], b"", content_length=MAX + 1)
|
||||
self.assertIsNotNone(reply, "no HTTP response")
|
||||
status, _, body = reply
|
||||
self.assertEqual((status, body["error"]["code"]), (413, "payload_too_large"))
|
||||
|
||||
def test_too_large_stream_is_413(self):
|
||||
# Тот же размер по частям (chunked, без Content-Length): сервер считает байты при чтении.
|
||||
data = SAMPLE_PNG + b"\x00" * (MAX + 1 - len(SAMPLE_PNG))
|
||||
reply = raw_upload(f"/api/v1/chats/{self.chat['id']}/attachments?filename=big.png",
|
||||
self.alice["token"], data, content_length=-1)
|
||||
self.assertIsNotNone(reply, "no HTTP response")
|
||||
status, _, body = reply
|
||||
self.assertEqual((status, body["error"]["code"]), (413, "payload_too_large"))
|
||||
|
||||
def test_pixel_bomb_is_413(self):
|
||||
bomb = bomb_png()
|
||||
self.assertLess(len(bomb), MAX) # по байтам файл маленький
|
||||
reply = self.upload(bomb, expected=413)["json"]
|
||||
self.assertIn("пиксел", reply["error"]["message"]) # отклонён именно по пикселям
|
||||
|
||||
def test_large_real_image_within_limits_is_accepted(self):
|
||||
data = png(1600, 1200, noise=True) # ~5,8 МБ, 1,9 млн пикселей
|
||||
att = self.upload(data, name="noise.png")["json"]
|
||||
got = self.api.call("GET", f"/api/v1/attachments/{att['id']}/content", actor=self.bob)
|
||||
self.assertEqual(hashlib.sha256(got["bytes"]).hexdigest(), hashlib.sha256(data).hexdigest())
|
||||
|
||||
# ---------- уровень 4: содержимое ----------
|
||||
|
||||
def test_corrupted_images_are_415(self):
|
||||
for data, ctype in ((truncated(SAMPLE_PNG), "image/png"), (corrupt_crc(SAMPLE_PNG), "image/png"),
|
||||
(truncated(SAMPLE_JPEG), "image/jpeg"), (b"\x89PNG\r\n\x1a\n" + b"x" * 100, "image/png"),
|
||||
(bytes(range(256)) * 10, "image/png")):
|
||||
with self.subTest(size=len(data), ctype=ctype):
|
||||
self.assertEqual(self.upload(data, ctype, expected=415)["json"]["error"]["code"],
|
||||
"unsupported_media_type")
|
||||
self.upload(b"", expected=400) # пустое тело
|
||||
|
||||
def test_mime_spoofing_is_415(self):
|
||||
cases = ((SAMPLE_PNG, "image/jpeg"), # PNG под видом JPEG
|
||||
(SAMPLE_JPEG, "image/png"), # JPEG под видом PNG
|
||||
(b"GIF89a" + b"\x00" * 50, "image/png"), # GIF под видом PNG
|
||||
(b"<svg xmlns='http://www.w3.org/2000/svg'/>", "image/png"),
|
||||
(SAMPLE_PNG, "image/gif"), (SAMPLE_PNG, "text/plain"),
|
||||
(SAMPLE_PNG, "application/x-www-form-urlencoded")) # по сути «Content-Type не указан»
|
||||
for data, ctype in cases:
|
||||
with self.subTest(ctype=ctype, head=data[:4]):
|
||||
self.upload(data, ctype, expected=415)
|
||||
|
||||
def test_dangerous_filenames_are_400(self):
|
||||
for name in (None, "", " ", "a/b.png", "..\\b.png", "a\x00b.png", "a\nb.png", "a\tb.png", "..",
|
||||
"photognp.exe", "x" * 256):
|
||||
with self.subTest(name=repr(name)):
|
||||
self.upload(SAMPLE_PNG, name=name, expected=400)
|
||||
name = "отпуск 2026 (1).png" # Unicode и пробелы — можно
|
||||
self.assertEqual(self.upload(SAMPLE_PNG, name=name)["json"]["filename"], name)
|
||||
|
||||
# ---------- уровень 4: привязка к сообщению ----------
|
||||
|
||||
def test_message_with_attachments(self):
|
||||
a1 = self.upload(SAMPLE_PNG)["json"]["id"]
|
||||
a2 = self.upload(SAMPLE_JPEG, "image/jpeg", "b.jpg")["json"]["id"]
|
||||
message = self.post_message({"text": "", "attachment_ids": [a2, a1]})["json"]
|
||||
self.assertEqual(message["attachment_ids"], [a2, a1]) # порядок сохраняется
|
||||
page = self.api.call("GET", f"/api/v1/chats/{self.chat['id']}/messages?limit=100", actor=self.bob,
|
||||
schema="MessagePage")["json"]
|
||||
self.assertIn(message, page["items"]) # история отдаёт те же attachment_ids
|
||||
again = self.post_message({"text": "то же вложение ещё раз", "attachment_ids": [a1]})["json"]
|
||||
self.assertEqual(again["attachment_ids"], [a1]) # одно вложение — в нескольких сообщениях
|
||||
plain = self.post_message({"text": "без вложений"})["json"]
|
||||
self.assertEqual(plain["attachment_ids"], [])
|
||||
|
||||
def test_attachment_rules_without_500(self):
|
||||
att = self.upload(SAMPLE_PNG)["json"]["id"]
|
||||
foreign = self.upload(SAMPLE_PNG, actor=self.eve, chat=self.eve_chat)["json"]["id"] # чужое
|
||||
other = self.upload(SAMPLE_PNG, chat=self.other_chat)["json"]["id"] # Алисы, но другой чат
|
||||
self.post_message({"text": "", "attachment_ids": [foreign]}, 404)
|
||||
self.post_message({"text": "", "attachment_ids": [other]}, 404)
|
||||
self.post_message({"text": "x", "attachment_ids": [att, str(uuid.uuid4())]}, 404) # одно неизвестное
|
||||
self.post_message({"text": ""}, 400) # пусто и без вложений
|
||||
self.post_message({"text": " ", "attachment_ids": []}, 400)
|
||||
self.post_message({"text": "x", "attachment_ids": [att, att]}, 400) # дубликаты
|
||||
self.post_message({"text": "x", "attachment_ids": [str(uuid.uuid4()) for _ in range(11)]}, 400)
|
||||
self.post_message({"text": "x", "attachment_ids": ["not-a-uuid"]}, 400)
|
||||
self.post_message({"text": "x", "attachment_ids": att}, 400) # не массив
|
||||
# Провал не «занимает» сообщение: в истории нет ни одного из отклонённых.
|
||||
page = self.api.call("GET", f"/api/v1/chats/{self.chat['id']}/messages?limit=100", actor=self.alice,
|
||||
schema="MessagePage")["json"]["items"]
|
||||
self.assertFalse([m for m in page if foreign in m["attachment_ids"] or other in m["attachment_ids"]])
|
||||
|
||||
def test_idempotency_with_attachments(self):
|
||||
att = self.upload(SAMPLE_PNG)["json"]["id"]
|
||||
key = uuid.uuid4().hex
|
||||
first = self.post_message({"text": "фото"}, key=key)["json"]
|
||||
replay = self.post_message({"attachment_ids": [], "text": "фото"}, key=key)["json"] # [] == отсутствует
|
||||
self.assertEqual(first, replay)
|
||||
self.post_message({"text": "фото", "attachment_ids": [att]}, 409, key=key) # другое тело
|
||||
key2 = uuid.uuid4().hex
|
||||
with_att = self.post_message({"text": "", "attachment_ids": [att]}, key=key2)["json"]
|
||||
self.assertEqual(self.post_message({"text": "", "attachment_ids": [att]}, key=key2)["json"], with_att)
|
||||
|
||||
def test_variants_and_bad_ids(self):
|
||||
att = self.upload(SAMPLE_PNG)["json"]["id"]
|
||||
path = f"/api/v1/attachments/{att}/content"
|
||||
self.assertEqual(self.api.call("GET", path + "?variant=original", actor=self.bob)["bytes"], SAMPLE_PNG)
|
||||
self.api.call("GET", path + "?variant=thumbnail", 404, actor=self.bob) # варианты появятся в lab5
|
||||
self.api.call("GET", path + "?variant=huge", 400, actor=self.bob)
|
||||
self.api.call("GET", "/api/v1/attachments/not-a-uuid", 400, actor=self.bob)
|
||||
self.api.call("GET", f"/api/v1/attachments/{uuid.uuid4()}/content", 404, actor=self.bob)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,118 @@
|
||||
"""Собственные тесты аутентификации (уровень 4): пароль, Basic -> Bearer, logout.
|
||||
|
||||
Запуск: make student-test (вместе с test_api.py)
|
||||
"""
|
||||
import base64
|
||||
import datetime as dt
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
from helpers import Client, basic, login
|
||||
|
||||
PASSWORD = "Test-password-123"
|
||||
|
||||
|
||||
def iso(value):
|
||||
return dt.datetime.fromisoformat(value.replace("Z", "+00:00"))
|
||||
|
||||
|
||||
class AuthTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.api = Client()
|
||||
|
||||
def register(self, password=PASSWORD, expected=201):
|
||||
body = {"username": "a_" + uuid.uuid4().hex[:12], "display_name": "Auth", "password": password}
|
||||
user = self.api.call("POST", "/api/v1/users", expected, body=body,
|
||||
schema="User" if expected == 201 else None)["json"]
|
||||
return body, user
|
||||
|
||||
def me(self, token, expected=200):
|
||||
return self.api.call("GET", "/api/v1/users/me", expected, headers={"Authorization": "Bearer " + token},
|
||||
schema="User" if expected == 200 else None)
|
||||
|
||||
def test_login_returns_opaque_token_with_expiry(self):
|
||||
body, user = self.register()
|
||||
session = login(self.api, body["username"], body["password"])
|
||||
self.assertEqual(session["user"], user)
|
||||
token = session["token"]
|
||||
self.assertGreaterEqual(len(token), 43) # 32 случайных байта в base64url
|
||||
self.assertNotIn(body["username"], token)
|
||||
self.assertNotIn(user["id"], token)
|
||||
# Обычный стенд: TTL не меньше 300 с (по умолчанию 3600).
|
||||
left = iso(session["expires_at"]) - dt.datetime.now(dt.timezone.utc)
|
||||
self.assertGreater(left.total_seconds(), 290)
|
||||
self.assertEqual(self.me(token)["json"], user)
|
||||
|
||||
def test_user_never_contains_password(self):
|
||||
body, user = self.register()
|
||||
self.assertEqual(set(user), {"id", "username", "display_name", "created_at"})
|
||||
self.assertNotIn(body["password"], str(user))
|
||||
|
||||
def test_wrong_password_and_unknown_user_look_the_same(self):
|
||||
body, _ = self.register()
|
||||
wrong = login(self.api, body["username"], "Wrong-password-000", expected=401)
|
||||
unknown = login(self.api, "nobody_" + uuid.uuid4().hex[:8], body["password"], expected=401)
|
||||
# Одинаковый код и текст: по ответу нельзя узнать, существует ли username.
|
||||
self.assertEqual(wrong["error"]["code"], unknown["error"]["code"])
|
||||
self.assertEqual(wrong["error"]["message"], unknown["error"]["message"])
|
||||
|
||||
def test_malformed_basic_returns_401(self):
|
||||
path = "/api/v1/auth/sessions"
|
||||
no_colon = base64.b64encode(b"just_username").decode()
|
||||
for header in (None, "Basic", "Basic !!!not-base64!!!", "Basic " + no_colon, "Bearer something"):
|
||||
headers = {} if header is None else {"Authorization": header}
|
||||
self.api.call("POST", path, 401, headers=headers) # клиент проверяет WWW-Authenticate: Basic
|
||||
|
||||
def test_password_with_colon_and_unicode(self):
|
||||
password = "пароль:с:двоеточием 👋"
|
||||
body, user = self.register(password=password)
|
||||
session = login(self.api, body["username"], password)
|
||||
self.assertEqual(session["user"], user)
|
||||
|
||||
def test_password_length_rules(self):
|
||||
self.register(password="x" * 11, expected=400)
|
||||
self.register(password="x" * 129, expected=400)
|
||||
self.register(password=" " * 12, expected=400) # только пробелы — нельзя
|
||||
self.register(password="x" * 12)
|
||||
self.register(password="я" * 128) # 128 символов Unicode — можно
|
||||
|
||||
def test_bearer_required_on_business_endpoints(self):
|
||||
body, user = self.register()
|
||||
session = login(self.api, body["username"], body["password"])
|
||||
for headers in ({}, {"Authorization": basic(body["username"], body["password"])},
|
||||
{"X-User-Id": user["id"]}, {"Authorization": "Bearer " + "A" * 43},
|
||||
{"Authorization": "Bearer"}, {"Authorization": "Token " + session["token"]}):
|
||||
self.api.call("GET", "/api/v1/users/me", 401, headers=headers) # WWW-Authenticate: Bearer
|
||||
# Схема нечувствительна к регистру (RFC 7235).
|
||||
self.api.call("GET", "/api/v1/users/me", 200, headers={"Authorization": "bearer " + session["token"]})
|
||||
|
||||
def test_x_user_id_does_not_change_identity(self):
|
||||
body, user = self.register()
|
||||
_, other = self.register()
|
||||
session = login(self.api, body["username"], body["password"])
|
||||
me = self.api.call("GET", "/api/v1/users/me", headers={
|
||||
"Authorization": "Bearer " + session["token"], "X-User-Id": other["id"]}, schema="User")["json"]
|
||||
self.assertEqual(me["id"], user["id"])
|
||||
|
||||
def test_logout_revokes_only_current_session(self):
|
||||
body, _ = self.register()
|
||||
first = login(self.api, body["username"], body["password"])["token"]
|
||||
second = login(self.api, body["username"], body["password"])["token"]
|
||||
self.me(first) # запись попадает в кэш Valkey
|
||||
self.api.call("DELETE", "/api/v1/auth/sessions/current", 204, headers={"Authorization": "Bearer " + first})
|
||||
self.me(first, expected=401) # кэш инвалидирован: отозванный токен не принимается сразу
|
||||
self.api.call("DELETE", "/api/v1/auth/sessions/current", 401, headers={"Authorization": "Bearer " + first})
|
||||
self.me(second) # другая сессия того же пользователя продолжает работать
|
||||
|
||||
def test_relogin_after_logout(self):
|
||||
body, _ = self.register()
|
||||
token = login(self.api, body["username"], body["password"])["token"]
|
||||
self.api.call("DELETE", "/api/v1/auth/sessions/current", 204, headers={"Authorization": "Bearer " + token})
|
||||
again = login(self.api, body["username"], body["password"])["token"]
|
||||
self.assertNotEqual(token, again)
|
||||
self.me(again)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,85 @@
|
||||
"""lab3: несколько реплик API за балансировщиком и общее состояние.
|
||||
|
||||
Запуск при запущенном стенде: make balancing (или вместе со всеми: make student-test).
|
||||
Все запросы идут на BASE_URL = балансировщик HAProxy (127.0.0.1:8080).
|
||||
|
||||
1. Один токен обслуживают разные реплики (X-Instance-Id), повторный вход не нужен:
|
||||
сессии в общем PostgreSQL + кэш в общем Valkey, а не в памяти реплики.
|
||||
2. Записал через одну реплику — сразу читаешь через другую: данные в общем PostgreSQL.
|
||||
3. Logout через одну реплику действует на всех.
|
||||
4. X-Instance-Id есть в каждом ответе (и в ошибках, и в health) и совпадает с ID
|
||||
настоящего запущенного контейнера api: заголовок — не выдумка, это разные процессы.
|
||||
5. Кэш сессий общий: запись, положенную одной репликой, используют все (промахов кэша нет).
|
||||
"""
|
||||
import unittest
|
||||
from collections import Counter
|
||||
|
||||
from helpers import Client, idempotency
|
||||
from stand import api_containers, valkey_stats
|
||||
|
||||
|
||||
class BalancingTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.api = Client()
|
||||
cls.alice, cls.bob, cls.eve, cls.chat = cls.api.bootstrap()
|
||||
|
||||
def me(self, actor, expected=200):
|
||||
reply = self.api.call("GET", "/api/v1/users/me", expected, actor=actor,
|
||||
schema="User" if expected == 200 else None)
|
||||
return reply["headers"]["X-Instance-Id"], reply["json"]
|
||||
|
||||
def test_one_session_is_served_by_every_replica(self):
|
||||
replies = [self.me(self.alice) for _ in range(20)]
|
||||
served = Counter(instance for instance, _ in replies)
|
||||
self.assertTrue(all(user["id"] == self.alice["id"] for _, user in replies), "another user returned")
|
||||
self.assertGreaterEqual(len(served), 2, "all requests went to one replica: balancing does not work")
|
||||
running = api_containers()
|
||||
for instance in served:
|
||||
self.assertTrue(any(container.startswith(instance) for container in running),
|
||||
f"X-Instance-Id {instance} is not a running api container")
|
||||
print(f"\n 20 x GET /users/me с одним токеном -> реплики {dict(served)}; "
|
||||
f"это ID запущенных контейнеров api, повторный вход не нужен")
|
||||
|
||||
def test_write_on_one_replica_read_on_another(self):
|
||||
sent = self.api.message(self.alice, self.chat, "записано через одну реплику")
|
||||
writer = sent["headers"]["X-Instance-Id"]
|
||||
readers = set()
|
||||
for _ in range(6):
|
||||
page = self.api.call("GET", f"/api/v1/chats/{self.chat['id']}/messages?limit=100",
|
||||
actor=self.bob, schema="MessagePage")
|
||||
self.assertIn(sent["json"], page["json"]["items"], "confirmed message is not visible")
|
||||
readers.add(page["headers"]["X-Instance-Id"])
|
||||
self.assertTrue(readers - {writer}, "no read went to another replica")
|
||||
print(f"\n сообщение записала реплика {writer}, сразу прочитали {sorted(readers)}")
|
||||
|
||||
def test_logout_applies_on_every_replica(self):
|
||||
carol = self.api.user("carol")
|
||||
self.api.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=carol)
|
||||
after = [self.me(carol, expected=401)[0] for _ in range(6)]
|
||||
self.assertGreaterEqual(len(set(after)), 2, "401 came from one replica only")
|
||||
print(f"\n logout через одну реплику -> 401 на {sorted(set(after))}")
|
||||
|
||||
def test_instance_id_on_errors_and_health(self):
|
||||
# Клиент курса сам проверяет X-Request-Id и X-Instance-Id у каждого ответа.
|
||||
self.api.call("GET", "/health/live", schema="Health")
|
||||
self.api.call("GET", "/health/ready", schema="Health")
|
||||
self.api.call("GET", "/api/v1/no-such-path", 404, actor=self.alice)
|
||||
self.api.call("GET", "/api/v1/users/me", 401)
|
||||
self.api.call("POST", f"/api/v1/chats/{self.chat['id']}/messages", 400, actor=self.alice,
|
||||
body={"text": ""}, headers=idempotency())
|
||||
print("\n X-Instance-Id есть в health, 404, 401 и 400")
|
||||
|
||||
def test_session_cache_is_shared_between_replicas(self):
|
||||
dave = self.api.user("dave") # вход уже положил запись о сессии в общий Valkey
|
||||
hits_before, misses_before = valkey_stats()
|
||||
served = Counter(self.me(dave)[0] for _ in range(10))
|
||||
hits_after, misses_after = valkey_stats()
|
||||
self.assertGreaterEqual(len(served), 2, "requests did not reach both replicas")
|
||||
self.assertEqual(misses_after - misses_before, 0, "cache miss: a replica did not use the shared entry")
|
||||
print(f"\n 10 x GET /users/me через реплики {dict(served)}: попаданий в кэш "
|
||||
f"+{hits_after - hits_before}, промахов +{misses_after - misses_before} — кэш общий")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,159 @@
|
||||
"""lab3: Idempotency-Key у POST /chats/{id}/messages.
|
||||
|
||||
Запуск при запущенном стенде: make idempotency (или вместе со всеми: make student-test).
|
||||
Все запросы идут через балансировщик, поэтому повторы попадают на разные реплики.
|
||||
|
||||
- повтор того же запроса (в том числе через другую реплику) -> тот же 201 и то же сообщение;
|
||||
- 20 одновременных запросов с одним ключом через обе реплики -> ровно одно сообщение;
|
||||
- одновременные разные тела с одним ключом -> одно сообщение, остальным 409;
|
||||
- форматирование JSON не важно; другое тело с тем же ключом -> 409;
|
||||
- область ключа: пользователь + чат (тот же ключ у другого пользователя или в другом чате независим);
|
||||
- нет ключа или он неверный -> 400; ошибка 400 ключ не «занимает»;
|
||||
- повтор заново проверяет сессию (401 после logout) и доступ к чату (404 постороннему).
|
||||
"""
|
||||
import threading
|
||||
import unittest
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
|
||||
from helpers import Client, idempotency, login, read_history
|
||||
|
||||
PARALLEL = 20
|
||||
|
||||
|
||||
class IdempotencyTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.api = Client()
|
||||
cls.alice, cls.bob, cls.eve, cls.chat = cls.api.bootstrap()
|
||||
|
||||
def path(self, chat=None):
|
||||
return f"/api/v1/chats/{(chat or self.chat)['id']}/messages"
|
||||
|
||||
def post(self, actor, text, key, expected=201, chat=None, api=None):
|
||||
return (api or self.api).call("POST", self.path(chat), expected, actor=actor, body={"text": text},
|
||||
headers=idempotency(key), schema="Message" if expected == 201 else None)
|
||||
|
||||
def count_text(self, text, chat=None):
|
||||
history, _ = read_history(self.api, self.alice, (chat or self.chat)["id"])
|
||||
return sum(1 for message in history if message["text"] == text)
|
||||
|
||||
def test_replay_through_another_replica_returns_same_message(self):
|
||||
key, text = uuid.uuid4().hex, "повтор " + uuid.uuid4().hex
|
||||
first = self.post(self.alice, text, key)
|
||||
replies = [self.post(self.alice, text, key) for _ in range(4)]
|
||||
self.assertTrue(all(reply["json"] == first["json"] for reply in replies), "replay differs")
|
||||
instances = {first["headers"]["X-Instance-Id"]} | {r["headers"]["X-Instance-Id"] for r in replies}
|
||||
self.assertGreaterEqual(len(instances), 2, "replays did not switch replica")
|
||||
self.assertEqual(self.count_text(text), 1)
|
||||
print(f"\n 1 запрос + 4 повтора через реплики {sorted(instances)}: 201 и то же сообщение, в истории 1")
|
||||
|
||||
def test_parallel_same_key_through_replicas_creates_one_message(self):
|
||||
key, text = uuid.uuid4().hex, "параллельно " + uuid.uuid4().hex
|
||||
start = threading.Barrier(PARALLEL)
|
||||
|
||||
def send(_):
|
||||
client = Client() # у каждого «клиента» свои соединения
|
||||
start.wait()
|
||||
return self.post(self.alice, text, key, api=client)
|
||||
|
||||
with ThreadPoolExecutor(max_workers=PARALLEL) as pool:
|
||||
replies = list(pool.map(send, range(PARALLEL)))
|
||||
ids = {reply["json"]["id"] for reply in replies}
|
||||
instances = Counter(reply["headers"]["X-Instance-Id"] for reply in replies)
|
||||
self.assertEqual(len(ids), 1, "different messages for one key")
|
||||
self.assertGreaterEqual(len(instances), 2, "parallel requests did not reach both replicas")
|
||||
self.assertEqual(self.count_text(text), 1, "duplicate message created")
|
||||
print(f"\n {PARALLEL} одновременных POST с одним ключом через реплики {dict(instances)}: "
|
||||
f"все 201 с одним id, в истории 1 сообщение")
|
||||
|
||||
def test_parallel_different_bodies_same_key(self):
|
||||
key = uuid.uuid4().hex
|
||||
texts = [f"тело {n} {key}" for n in range(10)]
|
||||
start = threading.Barrier(len(texts))
|
||||
|
||||
def send(text):
|
||||
client = Client()
|
||||
start.wait()
|
||||
reply = client.call("POST", self.path(), [201, 409], actor=self.alice, body={"text": text},
|
||||
headers=idempotency(key))
|
||||
return text, reply["status"], reply["json"]
|
||||
|
||||
with ThreadPoolExecutor(max_workers=len(texts)) as pool:
|
||||
results = list(pool.map(send, texts))
|
||||
created = [text for text, status, _ in results if status == 201]
|
||||
self.assertEqual(len(created), 1, f"expected exactly one 201, got {len(created)}")
|
||||
self.assertEqual(sum(1 for _, status, _ in results if status == 409), len(texts) - 1)
|
||||
self.assertEqual(sum(self.count_text(text) for text in texts), 1)
|
||||
print(f"\n {len(texts)} одновременных разных тел с одним ключом: 201 x1, 409 x{len(texts) - 1}, "
|
||||
f"в истории 1 сообщение")
|
||||
|
||||
def test_json_formatting_does_not_matter(self):
|
||||
key, text = uuid.uuid4().hex, "формат " + uuid.uuid4().hex
|
||||
first = self.post(self.alice, text, key)["json"]
|
||||
for raw in (('{ "text" : "%s" }' % text).encode("utf-8"), ('{\n "text": "%s"\n}' % text).encode("utf-8")):
|
||||
again = self.api.call("POST", self.path(), 201, actor=self.alice, raw=raw, schema="Message",
|
||||
headers={"Content-Type": "application/json", **idempotency(key)})["json"]
|
||||
self.assertEqual(again, first)
|
||||
print("\n тот же JSON с другими пробелами и переносами -> тот же 201 и то же сообщение")
|
||||
|
||||
def test_same_key_other_body_is_409(self):
|
||||
key, text = uuid.uuid4().hex, "оригинал " + uuid.uuid4().hex
|
||||
self.post(self.alice, text, key)
|
||||
error = self.post(self.alice, text + " (изменено)", key, expected=409)["json"]["error"]
|
||||
self.assertEqual(error["code"], "conflict")
|
||||
self.assertEqual(self.count_text(text), 1)
|
||||
self.assertEqual(self.count_text(text + " (изменено)"), 0)
|
||||
print("\n другой текст с тем же ключом -> 409 conflict, второе сообщение не создано")
|
||||
|
||||
def test_key_scope_is_user_and_chat(self):
|
||||
key, text = uuid.uuid4().hex, "область " + uuid.uuid4().hex
|
||||
other_chat = self.api.call("POST", "/api/v1/chats", 201, actor=self.alice, schema="Chat",
|
||||
body={"title": "второй чат", "member_ids": [self.alice["id"], self.bob["id"]]})["json"]
|
||||
by_alice = self.post(self.alice, text, key)["json"]
|
||||
by_bob = self.post(self.bob, text, key)["json"]
|
||||
in_other_chat = self.post(self.alice, text, key, chat=other_chat)["json"]
|
||||
self.assertEqual(len({by_alice["id"], by_bob["id"], in_other_chat["id"]}), 3)
|
||||
print("\n тот же ключ у другого пользователя и в другом чате -> независимые сообщения")
|
||||
|
||||
def test_key_is_required_and_validated(self):
|
||||
text = "без ключа " + uuid.uuid4().hex
|
||||
self.api.call("POST", self.path(), 400, actor=self.alice, body={"text": text})
|
||||
for bad in ("", "a" * 129, "пробел есть", "a b", "slash/no", "ключ"):
|
||||
# Не-ASCII отправляем как есть, байтами UTF-8 (так их пришлёт реальный клиент).
|
||||
header = bad.encode("utf-8").decode("latin-1")
|
||||
self.api.call("POST", self.path(), 400, actor=self.alice, body={"text": text},
|
||||
headers={"Idempotency-Key": header})
|
||||
self.post(self.alice, text + " 128", "k" * 128)
|
||||
self.post(self.alice, text + " punct", "Az09._:-" + uuid.uuid4().hex)
|
||||
self.assertEqual(self.count_text(text), 0)
|
||||
print("\n нет ключа, пустой, 129 символов, пробел, '/', кириллица -> 400; 128 символов и ._:- -> 201")
|
||||
|
||||
def test_failed_request_does_not_burn_key(self):
|
||||
key, text = uuid.uuid4().hex, "после ошибки " + uuid.uuid4().hex
|
||||
self.post(self.alice, " ", key, expected=400) # пустой текст: 400, ничего не сохранено
|
||||
created = self.post(self.alice, text, key)["json"]
|
||||
self.assertEqual(created["text"], text)
|
||||
print("\n с тем же ключом: сначала 400 (пустой текст), потом 201 — ошибка ключ не заняла")
|
||||
|
||||
def test_replay_rechecks_session_and_access(self):
|
||||
key, text = uuid.uuid4().hex, "проверка доступа " + uuid.uuid4().hex
|
||||
frank = self.api.user("frank")
|
||||
chat = self.api.call("POST", "/api/v1/chats", 201, actor=frank, schema="Chat",
|
||||
body={"title": "frank", "member_ids": [frank["id"], self.bob["id"]]})["json"]
|
||||
first = self.post(frank, text, key, chat=chat)["json"]
|
||||
self.post(self.eve, text, key, expected=404, chat=chat) # посторонний: 404, а не сохранённый ответ
|
||||
token = frank["token"]
|
||||
self.api.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=frank)
|
||||
self.post(frank, text, key, expected=401, chat=chat) # отозванный токен: 401
|
||||
session = login(self.api, frank["registration"]["username"], frank["registration"]["password"])
|
||||
frank_again = dict(frank, token=session["token"]) # новый вход, новый токен
|
||||
self.assertNotEqual(frank_again["token"], token)
|
||||
again = self.post(frank_again, text, key, chat=chat)["json"]
|
||||
self.assertEqual(again, first)
|
||||
print("\n повтор: посторонний -> 404, после logout -> 401, после нового входа -> то же сообщение")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,162 @@
|
||||
"""lab4, уровень 4: эксперимент — ≥10 одновременных загрузок и пик памяти реплик API.
|
||||
|
||||
make upload-memory (= python student-tests/upload_memory.py [--count 12])
|
||||
|
||||
Гипотеза: память реплики почти не растёт с числом одновременных загрузок, потому что
|
||||
(1) тело читается кусками и в памяти держится не больше 1 МиБ на загрузку (остальное во временном
|
||||
файле), (2) картинки декодируются по одной (семафор), (3) слишком большой файл отклоняется
|
||||
по Content-Length и вообще не читается.
|
||||
Если бы тела держались в памяти целиком, только на них ушло бы count × размер файла.
|
||||
|
||||
Методика:
|
||||
1. обе реплики API перезапускаются (чистый счётчик пика памяти процесса);
|
||||
2. создаются пользователи и чат (вход — Argon2id, это тоже попадает в базовую линию);
|
||||
3. замер «до»: VmRSS и VmHWM (пик RSS процесса с момента старта) у PID 1 каждой реплики,
|
||||
memory.peak cgroup (включает файловый кэш временных файлов);
|
||||
4. профиль A: count одновременных загрузок PNG со случайными пикселями (8,8 МиБ, 1800×1700);
|
||||
профиль B: count одновременных запросов, заявляющих 11 МиБ (ожидается 413 без чтения тела);
|
||||
5. замер «после» и каждые ~0,5 с во время серии (docker exec, VmRSS).
|
||||
Результат: evidence/upload-memory.json и таблица в REPORT.md (между метками upload-memory).
|
||||
Ограничения: клиент и стенд на одной машине; VmHWM — пик за всё время процесса, поэтому реплики
|
||||
перезапускаются перед замером; опрос раз в ~0,5 с может пропустить короткий пик (для этого VmHWM).
|
||||
"""
|
||||
import argparse
|
||||
import concurrent.futures
|
||||
import hashlib
|
||||
import json
|
||||
import re
|
||||
import threading
|
||||
import time
|
||||
from datetime import datetime, timezone
|
||||
|
||||
from filegen import png, raw_upload
|
||||
from helpers import ROOT, Client, check, run
|
||||
from stand import api_containers, compose_quiet, docker, wait_balanced
|
||||
|
||||
MIB = 1024 * 1024
|
||||
PROBE = "grep -E '^(VmRSS|VmHWM)' /proc/1/status; cat /sys/fs/cgroup/memory.peak 2>/dev/null || echo 0"
|
||||
|
||||
|
||||
def memory(container):
|
||||
"""{'rss': МиБ, 'hwm': МиБ, 'cgroup_peak': МиБ} для PID 1 контейнера."""
|
||||
text = docker("exec", container, "sh", "-c", PROBE, check_exit=False)
|
||||
rss = re.search(r"VmRSS:\s+(\d+)", text)
|
||||
hwm = re.search(r"VmHWM:\s+(\d+)", text)
|
||||
last = text.strip().splitlines()[-1] if text.strip() else "0"
|
||||
return {"rss": round(int(rss.group(1)) / 1024, 1) if rss else None,
|
||||
"hwm": round(int(hwm.group(1)) / 1024, 1) if hwm else None,
|
||||
"cgroup_peak": round(int(last) / MIB, 1) if last.isdigit() and int(last) else None}
|
||||
|
||||
|
||||
class Poller(threading.Thread):
|
||||
"""Во время серии опрашивает VmRSS всех реплик и запоминает максимум."""
|
||||
|
||||
def __init__(self, containers):
|
||||
super().__init__(daemon=True)
|
||||
self.containers, self.stop, self.max_rss = containers, threading.Event(), {c: 0.0 for c in containers}
|
||||
|
||||
def run(self):
|
||||
while not self.stop.is_set():
|
||||
for container in self.containers:
|
||||
rss = memory(container)["rss"] or 0
|
||||
self.max_rss[container] = max(self.max_rss[container], rss)
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def burst(name, count, task):
|
||||
with concurrent.futures.ThreadPoolExecutor(count) as pool:
|
||||
started = time.monotonic()
|
||||
results = list(pool.map(task, range(count)))
|
||||
took = time.monotonic() - started
|
||||
print(f"{name}: {count} concurrent uploads in {took:.2f} s -> statuses {sorted(set(r[0] for r in results))}")
|
||||
return results, round(took, 2)
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser()
|
||||
parser.add_argument("--count", type=int, default=12)
|
||||
args = parser.parse_args()
|
||||
check(args.count >= 10, "the experiment needs >= 10 concurrent uploads")
|
||||
|
||||
compose_quiet("restart", "api")
|
||||
containers = wait_balanced(2)
|
||||
api = Client(timeout=60)
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
path = f"/api/v1/chats/{chat['id']}/attachments?filename=load.png"
|
||||
images = [png(1800, 1700, noise=True) for _ in range(args.count)]
|
||||
size = len(images[0])
|
||||
print(f"replicas: {[c[:12] for c in containers]}; {args.count} files x {size / MIB:.1f} MiB "
|
||||
f"(1800x1700, random pixels)")
|
||||
before = {c: memory(c) for c in containers}
|
||||
|
||||
poller = Poller(containers)
|
||||
poller.start()
|
||||
|
||||
def accepted(i):
|
||||
reply = Client(timeout=60).call("POST", path, 201, actor=alice, raw=images[i],
|
||||
headers={"Content-Type": "image/png"}, schema="Attachment")
|
||||
att = reply["json"]
|
||||
check(att["sha256"] == hashlib.sha256(images[i]).hexdigest(), "checksum mismatch")
|
||||
return reply["status"], reply["headers"]["X-Instance-Id"], att["id"]
|
||||
|
||||
results_a, took_a = burst("A (accepted)", args.count, accepted)
|
||||
after_a = {c: memory(c) for c in containers}
|
||||
|
||||
def rejected(_i):
|
||||
# Заявлено 11 МиБ: сервер должен ответить 413 по заголовку, не читая и не буферизуя тело.
|
||||
reply = raw_upload(path, alice["token"], b"", content_length=11 * MIB)
|
||||
return (reply[0] if reply else None), None, None
|
||||
|
||||
results_b, took_b = burst("B (11 MiB, rejected)", args.count, rejected)
|
||||
check(all(r[0] == 413 for r in results_b), "oversize uploads must get 413")
|
||||
poller.stop.set()
|
||||
poller.join()
|
||||
after_b = {c: memory(c) for c in containers}
|
||||
|
||||
# Все файлы профиля A скачиваются вторым участником без изменений.
|
||||
for (_s, _inst, att_id), data in zip(results_a, images):
|
||||
got = api.call("GET", f"/api/v1/attachments/{att_id}/content", actor=bob)["bytes"]
|
||||
check(got == data, "downloaded file differs")
|
||||
|
||||
rows = []
|
||||
for c in containers:
|
||||
served = sum(1 for r in results_a if c.startswith(r[1]))
|
||||
rows.append({"replica": c[:12], "uploads_served": served,
|
||||
"rss_before_mib": before[c]["rss"], "hwm_before_mib": before[c]["hwm"],
|
||||
"hwm_after_a_mib": after_a[c]["hwm"], "hwm_after_b_mib": after_b[c]["hwm"],
|
||||
"max_rss_polled_mib": poller.max_rss[c],
|
||||
"cgroup_peak_after_mib": after_b[c]["cgroup_peak"],
|
||||
"peak_growth_mib": round((after_a[c]["hwm"] or 0) - (before[c]["hwm"] or 0), 1),
|
||||
"growth_from_b_mib": round((after_b[c]["hwm"] or 0) - (after_a[c]["hwm"] or 0), 1),
|
||||
"bodies_if_in_memory_mib": round(served * size / MIB, 1)})
|
||||
result = {"date": datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"), "count": args.count,
|
||||
"file_mib": round(size / MIB, 2), "profile_a_seconds": took_a, "profile_b_seconds": took_b,
|
||||
"limits": {"api_memory": "512M", "spool_in_memory": "1 MiB per upload", "decode_concurrency": 1,
|
||||
"malloc_arena_max": 2},
|
||||
"replicas": rows}
|
||||
(ROOT / "evidence" / "upload-memory.json").write_text(json.dumps(result, indent=2), encoding="utf-8")
|
||||
|
||||
table = ["| Реплика | Загрузок A | RSS до, МиБ | Пик RSS до → после A, МиБ | Рост пика, МиБ "
|
||||
"| Тела целиком в памяти были бы, МиБ | Рост пика от B (11 МиБ ×{0}), МиБ | memory.peak cgroup, МиБ |"
|
||||
.format(args.count), "| --- | --- | --- | --- | --- | --- | --- | --- |"]
|
||||
for r in rows:
|
||||
table.append(f"| {r['replica']} | {r['uploads_served']} | {r['rss_before_mib']} | {r['hwm_before_mib']} → "
|
||||
f"{r['hwm_after_a_mib']} | {r['peak_growth_mib']} | {r['bodies_if_in_memory_mib']} | "
|
||||
f"{r['growth_from_b_mib']} | {r['cgroup_peak_after_mib']} |")
|
||||
summary = (f"Профиль A: {args.count} одновременных PNG по {size / MIB:.1f} МиБ за {took_a} с, все 201, SHA-256 "
|
||||
f"совпали при скачивании; профиль B: {args.count} одновременных по 11 МиБ за {took_b} с, все 413. "
|
||||
f"Лимит памяти реплики 512 МиБ. Сырые данные: evidence/upload-memory.json.")
|
||||
block = "\n".join([summary, "", *table])
|
||||
print(block)
|
||||
report = ROOT / "REPORT.md"
|
||||
text = report.read_text(encoding="utf-8")
|
||||
begin, end = "<!-- upload-memory:begin -->", "<!-- upload-memory:end -->"
|
||||
if begin in text and end in text:
|
||||
head, rest = text.split(begin, 1)
|
||||
report.write_text(head + begin + "\n" + block + "\n" + end + rest.split(end, 1)[1], encoding="utf-8")
|
||||
print("REPORT.md: table updated between upload-memory markers")
|
||||
print("PASS: >= 10 concurrent uploads measured; see the table above")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user