forked from mtusi2026/mtusi2026lab7
ЛР7
This commit is contained in:
@@ -0,0 +1,394 @@
|
||||
"""lab7: права каждой identity — «что тебе можно» (contracts/trust-matrix.md, пункты 4–5).
|
||||
|
||||
make acl-matrix (контейнер sectest в сетях стенда: docker compose --profile tools run --rm sectest ...)
|
||||
|
||||
tls_matrix.py проверяет «кто ты» (транспорт). Здесь identity уже прошла TLS, и проверяется принцип
|
||||
наименьших привилегий: каждое разрешённое действие работает, а соседнее запрещённое — нет.
|
||||
|
||||
1. OpenBao (infra/openbao/policies/*.hcl, роли cert auth из scripts/bao.py):
|
||||
api/worker читают ТОЛЬКО свой путь KV; чужой путь, запись, list, политики, mounts, auth — 403;
|
||||
сертификат worker не входит в роль messenger-api (и наоборот), lb/intruder — ни в одну;
|
||||
в секрете worker нет пароля Valkey и ключей API — admin-credentials worker не получает.
|
||||
2. PostgreSQL (migrations/007_roles.sql): messenger_api — бизнес-таблицы без DELETE/DDL/TRUNCATE;
|
||||
messenger_worker не видит users (hash паролей), sessions, chats, messages; DDL/TRUNCATE запрещены;
|
||||
пароль одной роли не подходит к другой роли и к владельцу схемы.
|
||||
3. S3 (scripts/init-secrets.sh, s3_config.json): права по префиксам staging/ originals/ variants/;
|
||||
управление bucket'ами запрещено обоим.
|
||||
4. RabbitMQ (infra/rabbitmq/definitions.json): api только публикует в exchange attachments,
|
||||
worker только читает очередь attachments.process; объявлять очереди/exchange не может никто.
|
||||
5. Valkey (ACL в scripts/init-secrets.sh): пользователь messenger — только ключи sess:* rl:* и
|
||||
нужные команды; default выключен; health — только ping/info/dbsize.
|
||||
|
||||
Каждое действие выполняется по-настоящему, но без вреда: SQL — в транзакции с ROLLBACK, тестовые
|
||||
объекты S3 и ключи Valkey удаляются, сообщения в брокер уходят с routing key без привязки (теряются).
|
||||
Секреты для входа берутся из OpenBao так же, как их берёт сервис: сертификатом своей identity.
|
||||
"""
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
import uuid
|
||||
|
||||
import boto3
|
||||
import pika
|
||||
import psycopg
|
||||
import valkey
|
||||
from botocore.config import Config
|
||||
from botocore.exceptions import BotoCoreError, ClientError
|
||||
|
||||
from matrix import CA, Matrix, bao_call, bao_login, bao_secret, cert, client_context, short
|
||||
|
||||
BUCKET = "messenger-attachments"
|
||||
RUN = uuid.uuid4().hex[:12] # уникальные имена тестовых объектов и ключей этого запуска
|
||||
|
||||
|
||||
# ---------- 1. OpenBao ----------
|
||||
|
||||
def bao_part(m: Matrix):
|
||||
m.section("OpenBao: cert auth roles and KV policies")
|
||||
tokens = {}
|
||||
for identity in ("api", "worker"):
|
||||
status, payload = bao_login(identity, f"messenger-{identity}")
|
||||
policies = sorted(payload.get("auth", {}).get("token_policies", [])) if status == 200 else []
|
||||
m.allow(identity, f"login role messenger-{identity}", (status == 200, f"HTTP {status} policies={policies}"))
|
||||
m.row(identity, "token has no root/admin policy", "own", ",".join(policies) or "-",
|
||||
status == 200 and "root" not in policies and f"messenger-{identity}" in policies)
|
||||
if status == 200:
|
||||
tokens[identity] = payload["auth"]["client_token"]
|
||||
|
||||
# Чужая роль и посторонние identity нашего CA: вход отклоняется (CN не в allowed_common_names).
|
||||
for identity, role in (("worker", "messenger-api"), ("api", "messenger-worker"), ("lb", "messenger-api"),
|
||||
("intruder", "messenger-api"), ("intruder", "messenger-worker")):
|
||||
status, _ = bao_login(identity, role)
|
||||
m.deny(identity, f"login role {role}", (status == 200, f"HTTP {status}"))
|
||||
|
||||
for identity, token in tokens.items():
|
||||
other = "worker" if identity == "api" else "api"
|
||||
checks = [
|
||||
("allow", "GET", f"secret/data/messenger/{identity}", None, "read own KV path"),
|
||||
("deny", "GET", f"secret/data/messenger/{other}", None, f"read {other} KV path"),
|
||||
("deny", "POST", f"secret/data/messenger/{identity}", {"data": {"x": "y"}}, "write own KV path"),
|
||||
("deny", "LIST", "secret/metadata/messenger", None, "list KV paths"),
|
||||
("deny", "GET", f"secret/metadata/messenger/{identity}", None, "read KV metadata/versions"),
|
||||
("deny", "PUT", f"sys/policies/acl/messenger-{identity}", {"policy": 'path "*" {capabilities=["sudo"]}'},
|
||||
"rewrite own policy"),
|
||||
("deny", "GET", "sys/policies/acl/messenger-api", None, "read policies"),
|
||||
("deny", "GET", "sys/mounts", None, "list secret engines"),
|
||||
("deny", "LIST", "auth/cert/certs", None, "list cert auth roles"),
|
||||
("deny", "POST", "auth/token/create", {"policies": ["messenger-api", "messenger-worker"]},
|
||||
"create token with more policies"),
|
||||
]
|
||||
for expect, method, path, body, what in checks:
|
||||
status, _ = bao_call(method, path, token=token, body=body)
|
||||
outcome = (status in (200, 204), f"HTTP {status}")
|
||||
(m.allow if expect == "allow" else m.deny)(identity, what, outcome)
|
||||
|
||||
# Содержимое секрета worker: только его собственные учётные данные (ключи — без значений).
|
||||
if "worker" in tokens:
|
||||
status, payload = bao_call("GET", "secret/data/messenger/worker", token=tokens["worker"])
|
||||
keys = sorted(payload.get("data", {}).get("data", {})) if status == 200 else []
|
||||
m.row("worker", "secret has no Valkey/admin credentials", "none", ",".join(keys) or "-",
|
||||
status == 200 and "cache_password" not in keys and not any("admin" in k or "root" in k for k in keys))
|
||||
|
||||
|
||||
# ---------- 2. PostgreSQL ----------
|
||||
|
||||
def pg_connect(user: str, password: str):
|
||||
return psycopg.connect(host="postgres", port=5432, dbname="messenger", user=user, password=password,
|
||||
sslmode="verify-full", sslrootcert=CA, connect_timeout=5,
|
||||
application_name="acl-matrix")
|
||||
|
||||
|
||||
def sql_outcome(conn, statement: str) -> tuple[bool, str]:
|
||||
"""Выполнить и откатить. (True, ...) — сервер позволил; (False, причина) — отказал."""
|
||||
try:
|
||||
conn.execute(statement)
|
||||
return True, "executed (rolled back)"
|
||||
except psycopg.errors.InsufficientPrivilege:
|
||||
return False, "permission denied"
|
||||
except psycopg.Error as exc:
|
||||
return False, short(exc)
|
||||
finally:
|
||||
conn.rollback()
|
||||
|
||||
|
||||
def pg_part(m: Matrix, secrets: dict):
|
||||
m.section("PostgreSQL: roles messenger_api / messenger_worker")
|
||||
api_sql = [
|
||||
("allow", "SELECT id, password_hash FROM users LIMIT 1", "SELECT users"),
|
||||
("allow", "SELECT * FROM messages LIMIT 1", "SELECT messages"),
|
||||
("allow", "SELECT * FROM sessions LIMIT 1", "SELECT sessions"),
|
||||
("allow", "UPDATE chats SET title = title WHERE false", "UPDATE chats"),
|
||||
("allow", "DELETE FROM outbox WHERE false", "DELETE outbox"),
|
||||
("deny", "DELETE FROM users WHERE false", "DELETE users"),
|
||||
("deny", "DELETE FROM messages WHERE false", "DELETE messages"),
|
||||
("deny", "DELETE FROM schema_migrations WHERE false", "DELETE schema_migrations"),
|
||||
("deny", "TRUNCATE outbox", "TRUNCATE outbox"),
|
||||
("deny", f"CREATE TABLE acl_{RUN} (id int)", "CREATE TABLE"),
|
||||
("deny", "ALTER TABLE users ADD COLUMN acl_test int", "ALTER TABLE users"),
|
||||
("deny", "DROP TABLE job_events", "DROP TABLE"),
|
||||
("deny", "CREATE ROLE acl_intruder", "CREATE ROLE"),
|
||||
]
|
||||
worker_sql = [
|
||||
("allow", "SELECT * FROM attachments LIMIT 1", "SELECT attachments"),
|
||||
("allow", "SELECT * FROM attachment_jobs LIMIT 1", "SELECT attachment_jobs"),
|
||||
("allow", "UPDATE attachments SET status = status WHERE false", "UPDATE attachments"),
|
||||
("allow", "DELETE FROM outbox WHERE false", "DELETE outbox"),
|
||||
("deny", "SELECT id, password_hash FROM users LIMIT 1", "SELECT users (password hashes)"),
|
||||
("deny", "SELECT * FROM sessions LIMIT 1", "SELECT sessions"),
|
||||
("deny", "SELECT * FROM chats LIMIT 1", "SELECT chats"),
|
||||
("deny", "SELECT * FROM chat_members LIMIT 1", "SELECT chat_members"),
|
||||
("deny", "SELECT * FROM messages LIMIT 1", "SELECT messages"),
|
||||
("deny", "SELECT * FROM message_attachments LIMIT 1", "SELECT message_attachments"),
|
||||
("deny", "DELETE FROM attachments WHERE false", "DELETE attachments"),
|
||||
("deny", "TRUNCATE attachment_jobs", "TRUNCATE attachment_jobs"),
|
||||
("deny", f"CREATE TABLE acl_{RUN} (id int)", "CREATE TABLE"),
|
||||
("deny", "ALTER TABLE attachments ADD COLUMN acl_test int", "ALTER TABLE attachments"),
|
||||
]
|
||||
for identity, role, statements in (("api", "messenger_api", api_sql), ("worker", "messenger_worker", worker_sql)):
|
||||
password = secrets[identity]["db_password"]
|
||||
try:
|
||||
conn = pg_connect(role, password)
|
||||
except psycopg.Error as exc:
|
||||
m.allow(identity, f"connect as {role} (TLS verify-full)", (False, short(exc)))
|
||||
continue
|
||||
m.allow(identity, f"connect as {role} (TLS verify-full)", (True, "connected"))
|
||||
with conn:
|
||||
for expect, statement, what in statements:
|
||||
(m.allow if expect == "allow" else m.deny)(identity, what, sql_outcome(conn, statement))
|
||||
|
||||
# Пароль одной роли не открывает другую роль и владельца схемы.
|
||||
for identity, role in (("api", "messenger_worker"), ("worker", "messenger_api"),
|
||||
("api", "messenger"), ("worker", "messenger"), ("worker", "postgres")):
|
||||
try:
|
||||
pg_connect(role, secrets[identity]["db_password"]).close()
|
||||
outcome = (True, "connected")
|
||||
except psycopg.OperationalError as exc:
|
||||
text = str(exc)
|
||||
outcome = (False, "authentication failed" if "authentication" in text
|
||||
else "rejected by pg_hba.conf" if "pg_hba" in text else short(exc))
|
||||
m.deny(identity, f"{identity} password as role {role}", outcome)
|
||||
|
||||
|
||||
# ---------- 3. S3 ----------
|
||||
|
||||
def s3_client(secret: dict):
|
||||
return boto3.session.Session().client(
|
||||
"s3", endpoint_url="https://s3:9000", region_name="us-east-1", verify=CA,
|
||||
aws_access_key_id=secret["s3_access_key_id"], aws_secret_access_key=secret["s3_secret_access_key"],
|
||||
config=Config(s3={"addressing_style": "path"}, retries={"max_attempts": 1},
|
||||
connect_timeout=5, read_timeout=10,
|
||||
request_checksum_calculation="when_required", response_checksum_validation="when_required"))
|
||||
|
||||
|
||||
def s3_outcome(call) -> tuple[bool, str]:
|
||||
try:
|
||||
call()
|
||||
return True, "allowed"
|
||||
except ClientError as exc:
|
||||
return False, exc.response.get("Error", {}).get("Code", "ClientError")
|
||||
except BotoCoreError as exc:
|
||||
return False, short(exc)
|
||||
|
||||
|
||||
def other_buckets(client) -> tuple[bool, str]:
|
||||
"""SeaweedFS отдаёт в ListBuckets только bucket'ы, на которые есть права: чужих быть не должно."""
|
||||
try:
|
||||
names = sorted(b["Name"] for b in client.list_buckets().get("Buckets", []))
|
||||
except ClientError as exc:
|
||||
return False, exc.response.get("Error", {}).get("Code", "ClientError")
|
||||
others = [name for name in names if name != BUCKET]
|
||||
return bool(others), f"sees {names}"
|
||||
|
||||
|
||||
def s3_part(m: Matrix, secrets: dict):
|
||||
m.section(f"S3: prefixes in bucket {BUCKET}")
|
||||
api, worker = s3_client(secrets["api"]), s3_client(secrets["worker"])
|
||||
staging, original, variant = (f"staging/acl-{RUN}", f"originals/acl-{RUN}", f"variants/acl-{RUN}/v1/thumb")
|
||||
body = b"acl-matrix test object"
|
||||
|
||||
def put(client, key):
|
||||
return lambda: client.put_object(Bucket=BUCKET, Key=key, Body=body)
|
||||
|
||||
def get(client, key):
|
||||
return lambda: client.get_object(Bucket=BUCKET, Key=key)["Body"].read()
|
||||
|
||||
try:
|
||||
# api: пишет только staging/, читает только originals/ и variants/.
|
||||
m.allow("api", "PUT staging/<id>", s3_outcome(put(api, staging)))
|
||||
m.deny("api", "GET staging/<id> (unchecked upload)", s3_outcome(get(api, staging)))
|
||||
m.deny("api", "PUT originals/<id> (forge original)", s3_outcome(put(api, original)))
|
||||
m.deny("api", "PUT variants/<id>/... (forge variant)", s3_outcome(put(api, variant)))
|
||||
m.deny("api", "LIST bucket", s3_outcome(lambda: api.list_objects_v2(Bucket=BUCKET, MaxKeys=1)))
|
||||
# worker: читает staging/ и originals/, пишет в bucket, видит список.
|
||||
m.allow("worker", "GET staging/<id>", s3_outcome(get(worker, staging)))
|
||||
m.allow("worker", "PUT originals/<id>", s3_outcome(put(worker, original)))
|
||||
m.allow("worker", "PUT variants/<id>/...", s3_outcome(put(worker, variant)))
|
||||
m.allow("worker", "LIST bucket", s3_outcome(lambda: worker.list_objects_v2(Bucket=BUCKET, MaxKeys=1)))
|
||||
m.deny("worker", "GET variants/<id>/... (not its job)", s3_outcome(get(worker, variant)))
|
||||
# api отдаёт пользователю только проверенное.
|
||||
m.allow("api", "GET originals/<id>", s3_outcome(get(api, original)))
|
||||
m.allow("api", "GET variants/<id>/...", s3_outcome(get(api, variant)))
|
||||
m.deny("api", "DELETE originals/<id>", s3_outcome(lambda: api.delete_object(Bucket=BUCKET, Key=original)))
|
||||
# Управление bucket'ами — только у s3-init (admin), у приложений нет.
|
||||
forbidden = f"acl-matrix-{RUN}"
|
||||
for identity, client in (("api", api), ("worker", worker)):
|
||||
m.deny(identity, "CREATE bucket", s3_outcome(lambda c=client: c.create_bucket(Bucket=forbidden)))
|
||||
m.deny(identity, "DELETE other bucket", s3_outcome(lambda c=client: c.delete_bucket(Bucket=forbidden)))
|
||||
for identity, client in (("api", api), ("worker", worker)):
|
||||
m.deny(identity, "see other buckets (ListBuckets)", other_buckets(client))
|
||||
finally:
|
||||
for key in (staging, original, variant): # уборка тестовых объектов (worker может удалять)
|
||||
try:
|
||||
worker.delete_object(Bucket=BUCKET, Key=key)
|
||||
except (ClientError, BotoCoreError):
|
||||
pass
|
||||
|
||||
|
||||
# ---------- 4. RabbitMQ ----------
|
||||
|
||||
def broker_connect(identity: str) -> pika.BlockingConnection:
|
||||
context = client_context(identity)
|
||||
return pika.BlockingConnection(pika.ConnectionParameters(
|
||||
host="broker", port=5671, virtual_host="messenger", credentials=pika.credentials.ExternalCredentials(),
|
||||
ssl_options=pika.SSLOptions(context, server_hostname="broker"),
|
||||
connection_attempts=1, socket_timeout=5, blocked_connection_timeout=5))
|
||||
|
||||
|
||||
def amqp_outcome(conn: pika.BlockingConnection, action) -> tuple[bool, str]:
|
||||
"""Каждое действие — в своём канале: отказ брокера закрывает канал (403 ACCESS_REFUSED), не соединение."""
|
||||
channel = conn.channel()
|
||||
try:
|
||||
detail = action(channel)
|
||||
return True, detail if isinstance(detail, str) else "allowed"
|
||||
except pika.exceptions.ChannelClosedByBroker as exc:
|
||||
return False, f"{exc.reply_code} {exc.reply_text.split(' - ')[0]}"
|
||||
except pika.exceptions.AMQPError as exc:
|
||||
return False, short(exc)
|
||||
finally:
|
||||
if channel.is_open:
|
||||
channel.close()
|
||||
|
||||
|
||||
def publish(exchange: str):
|
||||
def action(channel):
|
||||
channel.confirm_delivery()
|
||||
# routing key без привязки: сообщение принято брокером и отброшено, worker его не получит.
|
||||
channel.basic_publish(exchange=exchange, routing_key=f"acl-matrix.noop.{RUN}", body=b"{}")
|
||||
return "published (unroutable, dropped)"
|
||||
return action
|
||||
|
||||
|
||||
def read(queue: str):
|
||||
def action(channel):
|
||||
method, _, _ = channel.basic_get(queue=queue, auto_ack=False)
|
||||
if method is not None: # настоящее задание — вернуть в очередь, не трогая
|
||||
channel.basic_nack(method.delivery_tag, requeue=True)
|
||||
return "read allowed (message requeued)"
|
||||
return "read allowed (queue empty)"
|
||||
return action
|
||||
|
||||
|
||||
def broker_part(m: Matrix):
|
||||
m.section("RabbitMQ: users = certificate CN (SASL EXTERNAL), vhost messenger")
|
||||
rules = {
|
||||
"api": [("allow", "publish to exchange attachments", publish("attachments")),
|
||||
("deny", "publish to exchange attachments.dlx", publish("attachments.dlx")),
|
||||
("deny", "publish to default exchange", publish("")),
|
||||
("deny", "read queue attachments.process", read("attachments.process")),
|
||||
("deny", "read queue attachments.dead", read("attachments.dead"))],
|
||||
"worker": [("allow", "read queue attachments.process", read("attachments.process")),
|
||||
("deny", "read queue attachments.dead", read("attachments.dead")),
|
||||
("deny", "publish to exchange attachments", publish("attachments")),
|
||||
("deny", "publish to exchange attachments.dlx", publish("attachments.dlx"))],
|
||||
}
|
||||
for identity, checks in rules.items():
|
||||
try:
|
||||
conn = broker_connect(identity)
|
||||
except (pika.exceptions.AMQPError, OSError) as exc:
|
||||
m.allow(identity, "connect amqps://broker:5671/messenger", (False, short(exc)))
|
||||
continue
|
||||
try:
|
||||
for expect, what, action in checks:
|
||||
(m.allow if expect == "allow" else m.deny)(identity, what, amqp_outcome(conn, action))
|
||||
m.deny(identity, "declare own queue", amqp_outcome(
|
||||
conn, lambda ch: ch.queue_declare(queue=f"acl-matrix-{RUN}", exclusive=True)))
|
||||
m.deny(identity, "declare exchange", amqp_outcome(
|
||||
conn, lambda ch: ch.exchange_declare(exchange=f"acl-matrix-{RUN}", exchange_type="fanout")))
|
||||
m.deny(identity, "delete queue attachments.process", amqp_outcome(
|
||||
conn, lambda ch: ch.queue_delete(queue="attachments.process")))
|
||||
finally:
|
||||
conn.close()
|
||||
|
||||
|
||||
# ---------- 5. Valkey ----------
|
||||
|
||||
def valkey_client(username: str | None, password: str | None):
|
||||
return valkey.Valkey(host="valkey", port=6379, username=username, password=password, ssl=True,
|
||||
ssl_ca_certs=CA, ssl_cert_reqs="required", ssl_check_hostname=True,
|
||||
socket_timeout=5, socket_connect_timeout=5)
|
||||
|
||||
|
||||
def valkey_outcome(call) -> tuple[bool, str]:
|
||||
try:
|
||||
call()
|
||||
return True, "allowed"
|
||||
except valkey.exceptions.ValkeyError as exc:
|
||||
text = str(exc)
|
||||
for code in ("NOPERM", "NOAUTH", "WRONGPASS"):
|
||||
if code in text or code.lower() in type(exc).__name__.lower():
|
||||
return False, code
|
||||
return False, type(exc).__name__
|
||||
|
||||
|
||||
def valkey_part(m: Matrix, secrets: dict):
|
||||
m.section("Valkey: ACL users messenger / health / default")
|
||||
api = valkey_client("messenger", secrets["api"]["cache_password"])
|
||||
key = f"sess:acl-matrix-{RUN}"
|
||||
try:
|
||||
m.allow("api", "SET/GET sess:* (session cache)",
|
||||
valkey_outcome(lambda: api.set(key, "1", ex=30) and api.get(key)))
|
||||
m.allow("api", "INCRBY rl:* (rate limit counter)",
|
||||
valkey_outcome(lambda: api.incrby(f"rl:acl-matrix-{RUN}", 1)))
|
||||
m.deny("api", "SET key outside sess:*/rl:*", valkey_outcome(lambda: api.set(f"other:acl-{RUN}", "1")))
|
||||
m.deny("api", "KEYS * (enumerate sessions)", valkey_outcome(lambda: api.keys("*")))
|
||||
m.deny("api", "SCAN", valkey_outcome(lambda: api.scan(0)))
|
||||
m.deny("api", "FLUSHALL", valkey_outcome(lambda: api.flushall()))
|
||||
m.deny("api", "CONFIG GET *", valkey_outcome(lambda: api.config_get("*")))
|
||||
m.deny("api", "ACL LIST", valkey_outcome(lambda: api.acl_list()))
|
||||
m.deny("api", "EVAL (Lua)", valkey_outcome(lambda: api.eval("return 1", 0)))
|
||||
m.deny("api", "PUBLISH", valkey_outcome(lambda: api.publish("acl", "1")))
|
||||
finally:
|
||||
try:
|
||||
api.delete(key, f"rl:acl-matrix-{RUN}")
|
||||
except valkey.exceptions.ValkeyError:
|
||||
pass
|
||||
|
||||
health = valkey_client("health", "any") # nopass: любой пароль, но только ping/info/dbsize
|
||||
m.allow("health", "PING", valkey_outcome(lambda: health.ping()))
|
||||
m.deny("health", "GET sess:*", valkey_outcome(lambda: health.get(key)))
|
||||
anonymous = valkey_client(None, None)
|
||||
m.deny("anonymous", "PING without AUTH (default user off)", valkey_outcome(lambda: anonymous.ping()))
|
||||
m.deny("anonymous", "GET sess:* without AUTH", valkey_outcome(lambda: anonymous.get(key)))
|
||||
guess = valkey_client("default", secrets["api"]["cache_password"])
|
||||
m.deny("anonymous", "AUTH default <api password>", valkey_outcome(lambda: guess.ping()))
|
||||
m.deny("worker", "worker has no Valkey credentials", (
|
||||
"cache_password" in secrets["worker"], "absent" if "cache_password" not in secrets["worker"] else "present"))
|
||||
|
||||
|
||||
def main() -> int:
|
||||
socket.setdefaulttimeout(10)
|
||||
m = Matrix("ACL matrix (lab7): what each identity may do")
|
||||
bao_part(m)
|
||||
secrets = {identity: bao_secret(identity) for identity in ("api", "worker")}
|
||||
pg_part(m, secrets)
|
||||
s3_part(m, secrets)
|
||||
broker_part(m)
|
||||
valkey_part(m, secrets)
|
||||
return m.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except ssl.SSLError as exc:
|
||||
sys.exit(f"TLS failure: {exc.reason}: check make pki / CA in /pki/tls/ca")
|
||||
@@ -0,0 +1,34 @@
|
||||
"""lab7: замер стоимости Argon2id для выбора параметров (README, уровень 3).
|
||||
|
||||
make argon2-bench (выполняется внутри контейнера api: те же CPU-лимит и библиотека, что у реплики)
|
||||
|
||||
Для каждого набора параметров — медиана и p95 времени одного hash (= одной проверки пароля при входе)
|
||||
по 15 повторам, и сколько входов в секунду выдержит одно ядро. Пароли синтетические, не печатаются.
|
||||
"""
|
||||
import statistics
|
||||
import time
|
||||
|
||||
from argon2 import PasswordHasher
|
||||
|
||||
CANDIDATES = [(19456, 2, 1), (19456, 3, 1), (47104, 1, 1), (65536, 2, 1)] # m (КиБ), t, p
|
||||
REPEATS = 15
|
||||
|
||||
|
||||
def main():
|
||||
print(f"{'m, MiB':>7} {'t':>2} {'p':>2} {'median ms':>10} {'p95 ms':>8} {'logins/s per core':>18}")
|
||||
for memory, time_cost, parallelism in CANDIDATES:
|
||||
hasher = PasswordHasher(time_cost=time_cost, memory_cost=memory, parallelism=parallelism)
|
||||
hasher.hash("warm up the allocator")
|
||||
samples = []
|
||||
for i in range(REPEATS):
|
||||
started = time.perf_counter()
|
||||
hasher.hash(f"synthetic password {i:04d}")
|
||||
samples.append((time.perf_counter() - started) * 1000)
|
||||
samples.sort()
|
||||
median = statistics.median(samples)
|
||||
p95 = samples[int(len(samples) * 0.95) - 1]
|
||||
print(f"{memory / 1024:>7.0f} {time_cost:>2} {parallelism:>2} {median:>10.1f} {p95:>8.1f} {1000 / median:>18.1f}")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,53 @@
|
||||
"""lab4–lab5, уровень 3: upload -> СРАЗУ остановка обслужившей реплики -> ready и download через другую.
|
||||
|
||||
make attachment-failover (= python student-tests/attachment_failover.py)
|
||||
|
||||
С lab5 реплика останавливается сразу после ответа 202, ещё до обработки. Это доказывает две вещи:
|
||||
- остановка API после ответа не теряет работу: оригинал уже в staging S3, задание — в PostgreSQL,
|
||||
worker доводит вложение до ready без этой реплики;
|
||||
- оригинал не лежит на диске реплики: другая реплика отдаёт тот же файл байт в байт (SHA-256).
|
||||
В конце остановленная реплика запускается обратно (`docker start`).
|
||||
"""
|
||||
import hashlib
|
||||
|
||||
from filegen import upload_when_ready, wait_status, wait_until
|
||||
from helpers import Client, check, run
|
||||
from stand import alias_of, 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 alias_of(c) == served]
|
||||
check(len(target) == 1, f"X-Instance-Id {served} does not match a running api container")
|
||||
print(f"uploaded {attachment['size_bytes']} bytes -> 202 {attachment['status']}, "
|
||||
f"sha256 {attachment['sha256'][:16]}..., 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) right after 202; HAProxy: {lb_summary()}")
|
||||
ready = wait_status(api, bob, attachment["id"], seconds=90)
|
||||
print(f"the worker finished the job without that replica: status {ready['status']}, "
|
||||
f"variants {[v['name'] for v in ready['variants']]}")
|
||||
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 right after 202; the job still became ready and "
|
||||
"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,98 @@
|
||||
"""lab6, уровни 3–4: dashboard и источники данных импортируются из Git, а запросы панелей работают.
|
||||
|
||||
make dashboard-check (= python student-tests/check_dashboard.py)
|
||||
|
||||
1. Grafana (https://127.0.0.1:3000): здорова; источники prometheus, loki, tempo созданы provisioning
|
||||
(а не руками) и проходят проверку подключения; dashboard messenger-lab6 импортирован из
|
||||
infra/grafana/dashboards/messenger.json (тот же набор панелей), помечен как provisioned.
|
||||
2. Каждый запрос каждой панели из JSON выполняется в своём хранилище без ошибок: PromQL — в
|
||||
Prometheus, LogQL — в Loki, TraceQL — в Tempo. Пустой результат разрешён только у панелей,
|
||||
которые показывают отказы (например, потери Collector при здоровом стенде), — они перечислены.
|
||||
3. Alert rules загружены в Prometheus (HighErrorRate, QueueLagHigh, TelemetryExportFailing) и здоровы.
|
||||
Выводится таблица «панель — единица — запрос» для REPORT.md.
|
||||
GRAFANA_URL=none — пропустить шаг 1 (например, если проверяются только запросы).
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
|
||||
import obs
|
||||
from helpers import ROOT, check, run
|
||||
|
||||
DASHBOARD = ROOT / "infra" / "grafana" / "dashboards" / "messenger.json"
|
||||
# Эти запросы при здоровом стенде законно пусты: отказов нет.
|
||||
MAY_BE_EMPTY = ("send_failed", "ALERTS", "outcome=\"ready\"", "time_to_ready", "4..", "5..")
|
||||
|
||||
|
||||
def panels(dashboard):
|
||||
for panel in dashboard["panels"]:
|
||||
if panel.get("type") == "row":
|
||||
continue
|
||||
yield panel
|
||||
|
||||
|
||||
def grafana_checks(dashboard):
|
||||
health = obs.get_json(obs.GRAFANA_URL + "/api/health")
|
||||
check(health.get("database") == "ok", f"grafana health: {health}")
|
||||
sources = {ds["uid"]: ds for ds in obs.grafana("/api/datasources")}
|
||||
for uid, kind in (("prometheus", "prometheus"), ("loki", "loki"), ("tempo", "tempo")):
|
||||
check(uid in sources and sources[uid]["type"] == kind, f"datasource {uid} is not provisioned")
|
||||
check(sources[uid].get("readOnly") is True, f"datasource {uid} must come from provisioning (readOnly)")
|
||||
if uid == "tempo":
|
||||
# Плагин Tempo в Grafana 12 не реализует /health через API (404 plugin.notImplemented):
|
||||
# проверяем подключение настоящим запросом к Tempo через прокси Grafana.
|
||||
check(isinstance(obs.grafana("/api/datasources/proxy/uid/tempo/api/search?limit=1"), dict),
|
||||
"tempo datasource: search through Grafana failed")
|
||||
continue
|
||||
result = obs.grafana(f"/api/datasources/uid/{uid}/health")
|
||||
check(result.get("status") == "OK", f"datasource {uid} health: {result}")
|
||||
print("1. Grafana " + health.get("version", "?") + ": datasources prometheus, loki, tempo — provisioned "
|
||||
"(readOnly); prometheus, loki health OK; tempo answers a search through Grafana")
|
||||
imported = obs.grafana("/api/dashboards/uid/" + dashboard["uid"])
|
||||
check(imported["meta"].get("provisioned") is True, "dashboard must be provisioned from a file")
|
||||
got = sorted(p["title"] for p in imported["dashboard"]["panels"])
|
||||
want = sorted(p["title"] for p in dashboard["panels"])
|
||||
check(got == want, "imported dashboard differs from infra/grafana/dashboards/messenger.json")
|
||||
print(f" dashboard '{imported['dashboard']['title']}' provisioned from {imported['meta'].get('provisionedExternalId')}, "
|
||||
f"{len(got)} panels (same as the JSON in Git)")
|
||||
|
||||
|
||||
def main():
|
||||
dashboard = json.loads(DASHBOARD.read_text(encoding="utf-8"))
|
||||
if os.environ.get("GRAFANA_URL", "") != "none":
|
||||
grafana_checks(dashboard)
|
||||
else:
|
||||
print("1. Grafana checks skipped (GRAFANA_URL=none)")
|
||||
|
||||
print("2. every panel query against its store:")
|
||||
print(f" {'panel':<46} {'unit':<11} {'series':>6} query")
|
||||
empty = []
|
||||
for panel in panels(dashboard):
|
||||
unit = panel.get("fieldConfig", {}).get("defaults", {}).get("unit", "-")
|
||||
for target in panel["targets"]:
|
||||
kind = target["datasource"]["uid"]
|
||||
if kind == "prometheus":
|
||||
rows = obs.prom(target["expr"])
|
||||
query = target["expr"]
|
||||
elif kind == "loki":
|
||||
rows = obs.loki(target["expr"], minutes=60, limit=20)
|
||||
query = target["expr"]
|
||||
else:
|
||||
rows = obs.tempo_search(target["query"], limit=5)
|
||||
query = target["query"]
|
||||
if not rows:
|
||||
empty.append((panel["title"], query))
|
||||
print(f" {panel['title'][:46]:<46} {unit:<11} {len(rows):>6} {' '.join(query.split())[:150]}")
|
||||
unexpected = [(title, q) for title, q in empty if not any(m in q for m in MAY_BE_EMPTY)]
|
||||
check(not unexpected, f"queries without data: {unexpected}")
|
||||
print(f" all queries succeeded; empty (allowed: failure-only panels): {len(empty)}")
|
||||
|
||||
names = {r["name"]: r for r in obs.rules()}
|
||||
for alert in ("HighErrorRate", "QueueLagHigh", "TelemetryExportFailing"):
|
||||
check(alert in names and names[alert]["health"] == "ok", f"alert rule {alert} missing or unhealthy")
|
||||
print("3. alert rules loaded and healthy: " + ", ".join(f"{n} ({names[n]['state']}, for {names[n].get('duration', 0)} s)"
|
||||
for n in ("HighErrorRate", "QueueLagHigh", "TelemetryExportFailing")))
|
||||
print("PASS: provisioning from Git, every panel query returns data from Prometheus/Loki/Tempo, alert rules loaded")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,149 @@
|
||||
"""lab3–lab7, уровни 3–4: устройство стенда по реальным контейнерам и docker compose config.
|
||||
|
||||
make check-stack (= python student-tests/check_stack.py)
|
||||
|
||||
С lab7 добавлено (hardening, README уровни 3–4):
|
||||
- ни один контейнер не privileged, без host network/pid и без Docker socket;
|
||||
- у всех: no-new-privileges и cap_drop ALL; cap_add только у объяснённых исключений
|
||||
(entrypoint образа стартует от root и переключается на своего пользователя);
|
||||
- read_only корень + tmpfs у всех сервисов, кроме объяснённых stateful-исключений;
|
||||
- api и worker работают не от root (uid процесса в контейнере);
|
||||
- у каждого работающего контейнера лимиты CPU и RAM;
|
||||
- наружу опубликованы только lb (8443, 8444, 8404) и grafana (3000), и только на 127.0.0.1;
|
||||
- loki и tempo без своей сети: только loopback шлюза tsdb-gw (allowlist identity, infra/tsdb/gateway.cfg);
|
||||
Prometheus с lab7 наружу НЕ опубликован (у него mTLS с allowlist identity);
|
||||
- все сети, кроме public и ops, internal; api/worker видят только нужные сети;
|
||||
- файлы-секреты (Docker secrets) получает только тот, кому они нужны; у api и worker их нет совсем
|
||||
(секреты — из OpenBao), TLS-ключ каждой identity смонтирован только в свой сервис.
|
||||
Сохранены проверки lab3–lab6: >= 2 реплик api без портов, все реплики под проверкой готовности,
|
||||
нет container_name, закреплённые версии образов, volumes хранилищ.
|
||||
"""
|
||||
import json
|
||||
|
||||
from helpers import check, run
|
||||
from stand import api_containers, compose_config, compose_output, docker, inspect, lb_rows
|
||||
|
||||
# Сервисы, которым нужны capabilities: entrypoint образа делает chown volume и переключается
|
||||
# на своего пользователя (gosu / su-exec), либо одноразово меняет владельца volume.
|
||||
CAP_EXCEPTIONS = {"postgres": {"CHOWN", "DAC_OVERRIDE", "FOWNER", "SETUID", "SETGID"},
|
||||
"broker": {"CHOWN", "DAC_OVERRIDE", "FOWNER", "SETUID", "SETGID"},
|
||||
"openbao-init": {"CHOWN", "DAC_OVERRIDE", "FOWNER"},
|
||||
"tempo-init": {"CHOWN"}}
|
||||
# Корень не read-only: stateful-сервисы, чей entrypoint пишет вне volume (/var/run/postgresql,
|
||||
# конфиг RabbitMQ, ~/.erlang.cookie), и одноразовые init-контейнеры без сети.
|
||||
RW_EXCEPTIONS = {"postgres", "broker", "openbao-init", "tempo-init"}
|
||||
# Какие сервисы смонтированы с каким каталогом secrets/tls/<identity> (/run/tls).
|
||||
TLS_IDENTITY = {"lb": "lb", "api": "api", "worker": "worker", "postgres": "postgres", "valkey": "valkey",
|
||||
"s3": "s3", "broker": "broker", "otlp-gw": "otel-collector", "otel-collector": "otel-collector",
|
||||
"prometheus": "prometheus", "grafana": "grafana",
|
||||
"openbao": "openbao"}
|
||||
SECRETS = {"api": [], "worker": [], "lb": [], "migrate": ["postgres_password"],
|
||||
"postgres": ["db_api_password", "db_worker_password", "postgres_password"],
|
||||
"valkey": ["valkey_acl"], "s3": ["s3_config"], "s3-init": ["s3_root_password", "s3_root_user"],
|
||||
"broker": [], "openbao": [], "grafana": ["grafana_admin_password"], "otel-collector": [],
|
||||
"otlp-gw": [], "tsdb-gw": [], "prometheus": [], "loki": [], "tempo": []}
|
||||
NETWORKS = {"lb": ["edge", "public", "telemetry"], "api": ["backend", "edge", "otlp", "vault"],
|
||||
"worker": ["backend", "otlp", "vault"], "postgres": ["backend"], "valkey": ["backend"],
|
||||
"s3": ["backend"], "broker": ["backend"], "openbao": ["vault"], "otlp-gw": ["otlp", "telemetry"],
|
||||
"prometheus": ["telemetry"], "tsdb-gw": ["telemetry"],
|
||||
"grafana": ["ops", "telemetry"]}
|
||||
PUBLISHED = {"lb": {"8443", "8444", "8404"}, "grafana": {"3000"}}
|
||||
|
||||
|
||||
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 [n for n, svc in services.items() if "container_name" in svc], "container_name is set")
|
||||
replicas = api_containers()
|
||||
check(len(replicas) >= 2, f"need >= 2 running api replicas, got {len(replicas)}")
|
||||
print(f"api replicas running: {len(replicas)}; container_name not set anywhere")
|
||||
|
||||
print(f"\n{'service':<15} {'cpus':>5} {'mem':>6} {'user':<12} {'ro':<3} {'caps added':<28} published")
|
||||
published = {}
|
||||
for container in sorted(compose_output("ps", "-q").split()):
|
||||
service = inspect(container, '{{index .Config.Labels "com.docker.compose.service"}}')
|
||||
host = json.loads(inspect(container, "{{json .HostConfig}}"))
|
||||
ports = json.loads(inspect(container, "{{json .NetworkSettings.Ports}}") or "{}") or {}
|
||||
bindings = [(b["HostIp"], b["HostPort"]) for items in ports.values() for b in (items or [])]
|
||||
published.setdefault(service, []).extend(bindings)
|
||||
caps = {c.removeprefix("CAP_") for c in host.get("CapAdd") or []}
|
||||
user = docker("exec", container, "id", "-u", check_exit=False).strip() or "?"
|
||||
print(f"{service:<15} {host['NanoCpus'] / 1e9:>5.2f} {host['Memory'] // 2**20:>4}Mi {user:<12} "
|
||||
f"{'yes' if host.get('ReadonlyRootfs') else 'no':<3} {','.join(sorted(caps)) or '-':<28} "
|
||||
f"{', '.join(f'{ip}:{port}' for ip, port in bindings) or '-'}")
|
||||
check(host["NanoCpus"] > 0 and host["Memory"] > 0, f"{service}: no CPU/RAM limit")
|
||||
check(not host.get("Privileged"), f"{service}: privileged")
|
||||
check(host.get("NetworkMode") != "host" and host.get("PidMode") != "host", f"{service}: host namespace")
|
||||
check("no-new-privileges:true" in (host.get("SecurityOpt") or []), f"{service}: no no-new-privileges")
|
||||
check("ALL" in (host.get("CapDrop") or []), f"{service}: capabilities are not dropped")
|
||||
check(caps <= CAP_EXCEPTIONS.get(service, set()), f"{service}: unexpected cap_add {caps}")
|
||||
check(host.get("ReadonlyRootfs") or service in RW_EXCEPTIONS, f"{service}: root filesystem is writable")
|
||||
mounts = json.loads(inspect(container, "{{json .Mounts}}"))
|
||||
check(not any("docker.sock" in (m.get("Source") or "") for m in mounts), f"{service}: Docker socket mounted")
|
||||
tls = [m["Source"].replace("\\", "/").rstrip("/").rsplit("/", 1)[-1] for m in mounts
|
||||
if (m.get("Destination") == "/run/tls")]
|
||||
if service in TLS_IDENTITY:
|
||||
check(tls == [TLS_IDENTITY[service]], f"{service}: /run/tls must be secrets/tls/{TLS_IDENTITY[service]}, got {tls}")
|
||||
if service in ("loki", "tempo"):
|
||||
# Слушают только loopback шлюза tsdb-gw: своего сертификата и своей сети у них нет.
|
||||
check(not tls and host.get("NetworkMode", "").startswith("container:"),
|
||||
f"{service} must share the tsdb-gw namespace and have no TLS key of its own")
|
||||
if service == "tsdb-gw":
|
||||
keys = sorted(m["Destination"] for m in mounts if m.get("Destination", "").startswith("/run/tls-"))
|
||||
check(keys == ["/run/tls-loki", "/run/tls-tempo"], f"tsdb-gw must hold the loki and tempo keys, got {keys}")
|
||||
if service in ("api", "worker"):
|
||||
check(user not in ("0", "?"), f"{service} runs as root")
|
||||
print()
|
||||
|
||||
for service, bindings in published.items():
|
||||
if not bindings:
|
||||
continue
|
||||
check(service in PUBLISHED, f"{service} must not publish ports: {bindings}")
|
||||
check(all(ip == "127.0.0.1" for ip, _ in bindings), f"{service} must be published on 127.0.0.1 only")
|
||||
check({port for _, port in bindings} <= PUBLISHED[service], f"{service}: unexpected ports {bindings}")
|
||||
print("published: lb 127.0.0.1:8443 (HTTPS API), :8444 (short TTL), :8404 (stats, HTTPS); "
|
||||
"grafana 127.0.0.1:3000 (HTTPS). api, OpenBao, Prometheus, Loki, Tempo, Collector, stores: none")
|
||||
print("hardening: no privileged/host namespaces/Docker socket; no-new-privileges and cap_drop ALL everywhere; "
|
||||
f"cap_add only for {', '.join(sorted(CAP_EXCEPTIONS))}; read-only root except {', '.join(sorted(RW_EXCEPTIONS))}; "
|
||||
"api/worker are not root; CPU/RAM limits everywhere")
|
||||
|
||||
for name, wanted in NETWORKS.items():
|
||||
got = sorted(services[name].get("networks", {}) or [])
|
||||
check(got == wanted, f"{name} networks {got} != {wanted}")
|
||||
for name, item in networks.items():
|
||||
check(item.get("internal") is True or name in ("public", "ops"), f"network {name} must be internal")
|
||||
print("networks: only public (lb) and ops (grafana) are not internal; " +
|
||||
"; ".join(f"{n}: {'+'.join(w)}" for n, w in NETWORKS.items()))
|
||||
|
||||
servers = lb_rows("api")
|
||||
check(not [r for r in servers if r.get("bck") == "1"], "backup servers in the balancer")
|
||||
check(not [r for r in servers if not r.get("status", "").startswith("MAINT") and not r.get("check_status")],
|
||||
"servers without a readiness check in the balancer")
|
||||
print("balancer: every api server under the /health/ready check over mTLS, no backup servers")
|
||||
|
||||
for name, wanted in SECRETS.items():
|
||||
got = sorted(item["source"] for item in services[name].get("secrets", []))
|
||||
check(got == wanted, f"{name} secrets {got} != {wanted}")
|
||||
for name in ("api", "worker"):
|
||||
env = services[name].get("environment", {})
|
||||
check(not any("TOKEN" in key or "SECRET_ID" in key or "PASSWORD" in key for key in env),
|
||||
f"{name} has a token/password variable in its environment")
|
||||
print("secrets: api and worker get NO Docker secrets and no token variables (only their TLS identity "
|
||||
"-> OpenBao cert auth); " + "; ".join(f"{n} -> {', '.join(w)}" for n, w in SECRETS.items() if w))
|
||||
|
||||
images = {name: services[name]["image"] for name in services if "image" in services[name]}
|
||||
check(all(":" in image and not image.endswith(":latest") for image in images.values()), "unpinned image")
|
||||
volumes = {"postgres": "pgdata", "s3": "s3data", "broker": "rabbitmqdata", "openbao": "baodata",
|
||||
"prometheus": "promdata", "loki": "lokidata", "tempo": "tempodata", "grafana": "grafanadata"}
|
||||
for name, volume in volumes.items():
|
||||
check(any(v.get("source") == volume for v in services[name].get("volumes", [])), f"{name} needs {volume}")
|
||||
print("images: " + "; ".join(f"{n} {i}" for n, i in sorted(images.items()) if not i.startswith("mtusi")))
|
||||
print("PASS: hardening, ports, networks, per-service secrets and TLS identities match the trust matrix")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,183 @@
|
||||
"""lab6, уровни 3–4: сигналы своего приложения в хранилищах и связь запрос -> лог -> trace -> задание.
|
||||
|
||||
make telemetry-check (= python student-tests/check_telemetry.py)
|
||||
|
||||
1. Контролируемый HTTP-запрос (POST сообщения): по X-Request-Id ответа в Loki находится структурный
|
||||
лог (event=http.request, severity, service.name, trace_id, span_id), по его trace_id в Tempo —
|
||||
server span того же запроса (тот же request_id) с дочерними SQL-спанами.
|
||||
2. Upload с одной внедрённой временной ошибкой worker (точка worker_transient): одна трасса
|
||||
upload (SERVER) -> send (PRODUCER) -> process (CONSUMER, попытка 1, retry) -> jobs.retry ->
|
||||
send (PRODUCER) -> process (CONSUMER, попытка 2, ready) -> S3 PutObject + SQL COMMIT результата.
|
||||
Связь parent-child проверяется по span_id; логи worker по trace_id: job.retry и job.ready.
|
||||
3. Метрики своего приложения: HTTP (метод, маршрут-шаблон, код), задания (тип, исход),
|
||||
длительности (histogram), очередь, пул БД, насыщение worker, CPU/RAM процессов.
|
||||
Ни у одной серии нет labels с ID (user/chat/message/attachment/request), маршрут — шаблон.
|
||||
4. Запрещённые данные: текст сообщения, пароль и токен не находятся ни в логах (поиск по Loki),
|
||||
ни в атрибутах спанов этих трасс; query-строки (filename) в спанах нет.
|
||||
Токены и пароли в вывод не попадают: ищутся по значениям в памяти процесса.
|
||||
"""
|
||||
import re
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import obs
|
||||
import ops
|
||||
from filegen import wait_status
|
||||
from helpers import Client, check, idempotency, run
|
||||
|
||||
UUID = re.compile(r"[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}")
|
||||
FORBIDDEN_LABELS = {"user_id", "chat_id", "message_id", "attachment_id", "request_id", "url_path", "filename",
|
||||
"messenger_attachment_id", "messenger_request_id", "messenger_job_id", "job_id", "trace_id"}
|
||||
|
||||
|
||||
def child_of(spans, parent, **match):
|
||||
return [s for s in spans if s["parent"] == parent["span_id"]
|
||||
and all(s.get(k) == v or s["attrs"].get(k) == v for k, v in match.items())]
|
||||
|
||||
|
||||
def controlled_request(api, alice, chat, marker):
|
||||
response = api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, actor=alice, headers=idempotency(),
|
||||
body={"text": marker}, schema="Message")
|
||||
request_id = response["headers"]["X-Request-Id"]
|
||||
logs = obs.wait_logs(f'{{service_name="messenger-api"}} | request_id="{request_id}"')
|
||||
entry = logs[-1]["labels"]
|
||||
for field in ("service_name", "trace_id", "span_id", "event", "severity_text"):
|
||||
check(entry.get(field), f"log for X-Request-Id has no {field}: {sorted(entry)}")
|
||||
check(entry["event"] == "http.request", f"unexpected event {entry['event']}")
|
||||
trace_id = entry["trace_id"]
|
||||
spans = obs.tempo_trace(trace_id)
|
||||
server = [s for s in spans if s["kind"] == "SERVER"]
|
||||
check(len(server) == 1, f"expected one server span, got {len(server)}")
|
||||
server = server[0]
|
||||
check(server["attrs"].get("messenger.request_id") == request_id, "server span request_id differs from header")
|
||||
check(server["attrs"].get("http.route") == "/api/v1/chats/{chat_id}/messages", "route template expected")
|
||||
check(entry["span_id"] == server["span_id"], "log span_id must be the server span")
|
||||
sql = [s for s in spans if s["kind"] == "CLIENT" and s["attrs"].get("db.system") == "postgresql"]
|
||||
check(any(s["name"] == "INSERT" for s in sql), "no INSERT span under the request")
|
||||
print(f"1. POST message: X-Request-Id={request_id} -> Loki: event={entry['event']} severity={entry['severity_text']} "
|
||||
f"service={entry['service_name']} instance={entry.get('service_instance_id')} trace_id={trace_id} "
|
||||
f"span_id={entry['span_id']}")
|
||||
print(f" Tempo: trace {trace_id}, server span {server['span_id']} (request_id matches), {len(sql)} SQL spans:")
|
||||
for line in obs.tree(spans):
|
||||
print(" " + line)
|
||||
return spans
|
||||
|
||||
|
||||
def upload_chain(api, alice, bob, chat):
|
||||
ops.arm("worker", "worker_transient", "1")
|
||||
att, _content = api.attachment(alice, chat)
|
||||
print(f"2. upload with one injected transient failure: attachment_id={att['id']} -> 202 queued")
|
||||
ready = wait_status(api, bob, att["id"], ("ready",), seconds=90)
|
||||
check(ready["status"] == "ready", "attachment must become ready after the retry")
|
||||
|
||||
def complete(spans):
|
||||
return sum(1 for s in spans if s["kind"] == "CONSUMER") >= 2 and \
|
||||
any(s["attrs"].get("messenger.job.outcome") == "ready" for s in spans)
|
||||
|
||||
trace_id, spans = obs.wait_trace(f'{{ span.messenger.attachment.id = "{att["id"]}" && kind = server }}', complete, 90)
|
||||
by_kind = {k: [s for s in spans if s["kind"] == k] for k in ("SERVER", "PRODUCER", "CONSUMER")}
|
||||
upload = by_kind["SERVER"][0]
|
||||
check(upload["service"] == "messenger-api" and upload["attrs"].get("http.response.status_code") == 202,
|
||||
"upload server span expected")
|
||||
send1 = child_of(spans, upload, kind="PRODUCER")
|
||||
check(len(send1) == 1, "producer span must be a child of the upload span")
|
||||
consume1 = child_of(spans, send1[0], kind="CONSUMER")
|
||||
check(len(consume1) == 1 and consume1[0]["service"] == "messenger-worker", "consumer must be a child of producer")
|
||||
consume1 = consume1[0]
|
||||
check(consume1["attrs"].get("messenger.job.attempt") == 1 and consume1["attrs"].get("messenger.job.outcome") == "retry"
|
||||
and consume1["status"] == "ERROR", "attempt 1 must be a failed (retry) consumer span")
|
||||
retry = child_of(spans, consume1, name="jobs.retry")
|
||||
check(len(retry) == 1, "jobs.retry span expected under attempt 1")
|
||||
send2 = child_of(spans, retry[0], kind="PRODUCER")
|
||||
check(len(send2) == 1 and send2[0]["attrs"].get("messenger.job.attempt") == 2,
|
||||
"the retry message must be published as a child of jobs.retry")
|
||||
consume2 = child_of(spans, send2[0], kind="CONSUMER")
|
||||
check(len(consume2) == 1 and consume2[0]["attrs"].get("messenger.job.outcome") == "ready", "attempt 2 must be ready")
|
||||
consume2 = consume2[0]
|
||||
puts = [s for s in spans if s["attrs"].get("rpc.method") == "PutObject" and s["service"] == "messenger-worker"]
|
||||
check(len(puts) >= 4, "original + 3 variants must be written to S3 in the trace")
|
||||
completes = [s for s in spans if s["name"] == "jobs.complete" and s["parent"] == consume2["span_id"]]
|
||||
check(completes and [s for s in spans if s["parent"] == completes[0]["span_id"] and s["name"] == "UPDATE"],
|
||||
"COMMIT of the result (SQL UPDATE under jobs.complete) expected")
|
||||
check({s["service"] for s in spans} == {"messenger-api", "messenger-worker"}, "both services must be in one trace")
|
||||
print(f" one trace {trace_id}: SERVER -> PRODUCER -> CONSUMER(attempt 1, retry, ERROR) -> jobs.retry -> "
|
||||
f"PRODUCER(attempt 2) -> CONSUMER(attempt 2, ready) -> {len(puts)} x S3 PutObject, SQL under jobs.complete")
|
||||
for line in obs.tree([s for s in spans if not (s["kind"] == "CLIENT" and "rpc.method" not in s["attrs"])]):
|
||||
print(" " + line)
|
||||
worker_logs = obs.wait_logs(f'{{service_name="messenger-worker"}} | trace_id="{trace_id}"', count=2)
|
||||
events = [e["labels"].get("event") for e in worker_logs]
|
||||
check("job.retry" in events and "job.ready" in events, f"worker logs of the trace: {events}")
|
||||
api_logs = obs.loki(f'{{service_name="messenger-api"}} | trace_id="{trace_id}"')
|
||||
print(f" Loki by trace_id: worker events {events}; api events {[e['labels'].get('event') for e in api_logs]}")
|
||||
return spans, att
|
||||
|
||||
|
||||
def metrics_check():
|
||||
wanted = {
|
||||
"HTTP requests (counter, method/route/code)":
|
||||
'sum by (http_request_method, http_route, http_response_status_code) '
|
||||
'(http_server_request_duration_seconds_count{job="messenger-api", http_route="/api/v1/chats/{chat_id}/messages"})',
|
||||
"HTTP duration histogram buckets": 'count(http_server_request_duration_seconds_bucket{job="messenger-api"})',
|
||||
"jobs processed by outcome": 'sum by (messenger_job_type, outcome) (messenger_jobs_processed_total)',
|
||||
"job duration histogram": 'sum by (outcome) (messenger_job_duration_seconds_count)',
|
||||
"time to ready histogram": 'sum(messenger_attachment_time_to_ready_seconds_count)',
|
||||
"queue depth": 'max by (queue, state) (messenger_queue_depth)',
|
||||
"oldest job age": 'max by (queue) (messenger_queue_oldest_age_seconds)',
|
||||
"DB pool": 'sum by (job, db_client_connection_state) (db_client_connection_count)',
|
||||
"worker busy/capacity": 'sum(messenger_worker_capacity)',
|
||||
"process CPU": 'sum by (job) (process_cpu_time_seconds_total{job=~"messenger-.*"})',
|
||||
"process RAM": 'sum by (job) (process_memory_usage_bytes{job=~"messenger-.*"})',
|
||||
}
|
||||
deadline = time.monotonic() + 40 # метрики уходят раз в 10 с
|
||||
while True:
|
||||
missing = [name for name, query in wanted.items() if not obs.prom(query)]
|
||||
outcomes = {r["metric"].get("outcome") for r in obs.prom(wanted["jobs processed by outcome"])}
|
||||
if not missing and {"ready", "retry"} <= outcomes:
|
||||
break
|
||||
check(time.monotonic() < deadline, f"metrics missing: {missing}, job outcomes {outcomes}")
|
||||
time.sleep(3)
|
||||
print("3. metrics of the application in Prometheus:")
|
||||
for name, query in wanted.items():
|
||||
rows = obs.prom(query)
|
||||
sample = ", ".join(f"{ {k: v for k, v in r['metric'].items()} }={r['value']:g}" for r in rows[:3])
|
||||
print(f" {name}: {len(rows)} series; {sample[:220]}")
|
||||
base, auth = obs._via(obs.PROM_URL, "prometheus")
|
||||
series = obs.get_json(base + "/api/v1/series?match[]=" + "%7Bjob%3D~%22messenger-.*%22%7D", auth)["data"]
|
||||
labels = set().union(*(s.keys() for s in series))
|
||||
check(not labels & FORBIDDEN_LABELS, f"forbidden labels in metrics: {labels & FORBIDDEN_LABELS}")
|
||||
routes = {s.get("http_route") for s in series if s.get("http_route")}
|
||||
check(not any(UUID.search(r) for r in routes), f"raw IDs in http_route: {routes}")
|
||||
print(f" {len(series)} series of messenger-api/worker; label names: {', '.join(sorted(labels))}")
|
||||
print(f" no ID labels; http_route values are templates: {', '.join(sorted(routes))}")
|
||||
|
||||
|
||||
def forbidden_data(alice, marker, traces):
|
||||
secrets = {"message text": marker, "password": alice["registration"]["password"], "session token": alice["token"]}
|
||||
for what, value in secrets.items():
|
||||
found = obs.loki(f'{{service_name=~"messenger-api|messenger-worker"}} |= `{value}`', minutes=30)
|
||||
check(not found, f"{what} found in logs")
|
||||
for spans in traces:
|
||||
for span in spans:
|
||||
text = repr(span["attrs"])
|
||||
for what, value in secrets.items():
|
||||
check(value not in text, f"{what} found in span {span['name']}")
|
||||
check("filename=" not in text and "Bearer" not in text and "authorization" not in text.lower(),
|
||||
f"query string or auth header in span {span['name']}")
|
||||
print("4. message text, password and session token: 0 hits in Loki (30 min) and in span attributes; "
|
||||
"no query strings / Authorization in spans")
|
||||
|
||||
|
||||
def main():
|
||||
api = Client(timeout=20)
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
marker = "секретный текст " + uuid.uuid4().hex
|
||||
message_spans = controlled_request(api, alice, chat, marker)
|
||||
upload_spans, _att = upload_chain(api, alice, bob, chat)
|
||||
metrics_check()
|
||||
forbidden_data(alice, marker, [message_spans, upload_spans])
|
||||
print("PASS: request -> log -> trace by X-Request-Id/trace_id; upload -> publish -> consume -> retry -> S3/DB in one "
|
||||
"trace with parent-child links; app metrics without ID labels; no secrets or message bodies in telemetry")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,200 @@
|
||||
"""Замечание к MR: уборщик S3 не удаляет текущую работу — воспроизведение на стенде с «барьерами».
|
||||
|
||||
make cleanup-race (= python student-tests/cleanup_race.py)
|
||||
|
||||
Порядок событий закрепляют точки-паузы (src/messenger/faults.py): процесс один раз ждёт
|
||||
несколько секунд в опасном месте, а тест в это время делает следующий шаг. Grace period = 0,
|
||||
чтобы уборщик рассматривал даже свежие объекты (так же, как в воспроизведении из замечания).
|
||||
Настоящие PostgreSQL, S3, CLI уборщика, replay, API и worker.
|
||||
|
||||
A. Как в замечании. failed-вложение с истёкшим retention (состояние и возраст заданы через
|
||||
updated_at, как в замечании). Уборщик прочитал ссылки и остановился (cleanup_pause) ->
|
||||
оператор делает replay (queued) -> уборщик продолжает. Было: staging удалён, worker ->
|
||||
failed / source_missing. Стало: уборщик перепроверяет состояние под блокировкой и staging
|
||||
не трогает; после запуска worker вложение становится ready.
|
||||
B. Обратный порядок. Уборщик под блокировкой уже решил удалить staging истёкшего failed и пометил
|
||||
его удалённым, COMMIT ещё нет (cleanup_pause_locked) -> replay ждёт блокировку и безопасно
|
||||
отказывает (source_missing), задание остаётся failed, в журнале — запись уборщика и отказ
|
||||
replay; сам объект уборщик удаляет после COMMIT.
|
||||
C. Загрузка между PUT в staging и COMMIT строки вложения (api_pause_after_staging): уборщик
|
||||
пропускает это вложение (занято), загрузка заканчивается 202 -> ready.
|
||||
D. Worker записал оригинал и варианты в S3, COMMIT ещё нет (worker_pause_after_objects):
|
||||
уборщик ничего не удаляет (задание в processing), worker коммитит -> ready, файлы на месте.
|
||||
"""
|
||||
import hashlib
|
||||
import threading
|
||||
import time
|
||||
|
||||
import ops
|
||||
from filegen import SAMPLE_PNG, png, wait_status
|
||||
from helpers import Client, check, run
|
||||
|
||||
# Секунд в точке-паузе: столько длится «окно» гонки. С запасом: на Windows каждый docker exec — около секунды.
|
||||
PAUSE = {"cleanup_pause": "10", "cleanup_pause_locked": "8", "api_pause_after_staging": "10",
|
||||
"worker_pause_after_objects": "12"}
|
||||
|
||||
|
||||
def background(fn, *args):
|
||||
result = {}
|
||||
|
||||
def target():
|
||||
try:
|
||||
result["value"] = fn(*args)
|
||||
except BaseException as exc: # noqa: BLE001 — передаём в основной поток
|
||||
result["error"] = exc
|
||||
thread = threading.Thread(target=target, daemon=True)
|
||||
thread.start()
|
||||
return thread, result
|
||||
|
||||
|
||||
def finish(step, seconds=60):
|
||||
thread, result = step
|
||||
thread.join(seconds)
|
||||
check(not thread.is_alive(), "a background step did not finish")
|
||||
if "error" in result:
|
||||
raise result["error"]
|
||||
return result["value"]
|
||||
|
||||
|
||||
def wait_paused(container, point, seconds=40):
|
||||
"""Точка-пауза сработала (процесс удалил её файл и ждёт) — можно делать следующий шаг."""
|
||||
deadline = time.monotonic() + seconds
|
||||
while ops.armed(container, point):
|
||||
check(time.monotonic() < deadline, f"{point} did not fire")
|
||||
time.sleep(0.2)
|
||||
|
||||
|
||||
def janitor(container, attachment_id):
|
||||
return ops.cli_in(container, "messenger.cleanup", "--grace-seconds", "0", "--attachment", attachment_id)
|
||||
|
||||
|
||||
def mark_failed_long_ago(attachment_id):
|
||||
ops.psql(f"""UPDATE attachment_jobs SET status = 'failed', finished_at = now(),
|
||||
last_error_code = 'storage_unavailable', last_error = 'cleanup-race'
|
||||
WHERE attachment_id = '{attachment_id}';
|
||||
UPDATE attachments SET status = 'failed', error_code = 'retry_exhausted',
|
||||
updated_at = now() - interval '2 days'
|
||||
WHERE id = '{attachment_id}'""")
|
||||
|
||||
|
||||
def staging_exists(attachment_id):
|
||||
return ops.objects(f"staging/{attachment_id}") == [f"staging/{attachment_id}"]
|
||||
|
||||
|
||||
def upload(api, actor, chat, data, name):
|
||||
return api.call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename={name}", 202, actor=actor,
|
||||
raw=data, headers={"Content-Type": "image/png"}, schema="Attachment")["json"]
|
||||
|
||||
|
||||
def main():
|
||||
api = Client(timeout=30)
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
container = ops.containers("api")[0] # здесь запускается уборщик и включаются его паузы
|
||||
|
||||
# ---------- A и B: подготовка двух failed-вложений с истёкшим retention ----------
|
||||
ops.stop("worker")
|
||||
try:
|
||||
a = upload(api, alice, chat, SAMPLE_PNG, "race-a.png")
|
||||
b = upload(api, alice, chat, png(40, 30), "race-b.png")
|
||||
for att in (a, b):
|
||||
mark_failed_long_ago(att["id"])
|
||||
|
||||
# ---------- A ----------
|
||||
ops.arm("api", "cleanup_pause", PAUSE["cleanup_pause"], container=container)
|
||||
cleanup = background(janitor, container, a["id"])
|
||||
wait_paused(container, "cleanup_pause")
|
||||
print(f"A. failed {a['id']} (retention expired); the janitor read the references and stopped")
|
||||
replayed = ops.replay(a["id"])
|
||||
check(replayed.get("result") == "queued", f"replay: {replayed}")
|
||||
print(f" operator replay while the janitor waits -> {replayed}")
|
||||
out = finish(cleanup)
|
||||
check(out["deleted"] == 0 and out["kept_after_recheck"] == {"current_work": 1}, f"janitor: {out}")
|
||||
check(staging_exists(a["id"]), "the staging of the replayed job was deleted")
|
||||
print(f" janitor continued: deleted {out['deleted']}, re-checked under the lock -> kept "
|
||||
f"{out['kept_after_recheck']}; staging/{a['id'][:8]}... is still in S3")
|
||||
|
||||
# ---------- B ----------
|
||||
ops.arm("api", "cleanup_pause_locked", PAUSE["cleanup_pause_locked"], container=container)
|
||||
cleanup = background(janitor, container, b["id"])
|
||||
wait_paused(container, "cleanup_pause_locked")
|
||||
print(f"B. failed {b['id']} (retention expired); the janitor holds the lock: staging marked deleted, "
|
||||
f"no COMMIT yet")
|
||||
started = time.monotonic()
|
||||
refused = ops.replay(b["id"])
|
||||
waited = time.monotonic() - started
|
||||
out = finish(cleanup)
|
||||
check(refused.get("result") == "refused" and refused.get("reason") == "source_missing", f"replay: {refused}")
|
||||
check(out["deleted"] == 1 and out["to_delete"]["staging_failed_expired"] == 1, f"janitor: {out}")
|
||||
job = ops.job(b["id"])
|
||||
events = [e["event"] for e in job["events"] if e["event"] in ("staging_expired", "replay_refused")]
|
||||
check(job["job"]["status"] == "failed" and events == ["staging_expired", "replay_refused"], f"{job}")
|
||||
check(not staging_exists(b["id"]), "the expired staging must be deleted")
|
||||
print(f" replay waited {waited:.1f} s for the lock -> {refused['result']} ({refused['reason']}); "
|
||||
f"job stays failed; journal: {' -> '.join(events)}")
|
||||
finally:
|
||||
ops.start("worker")
|
||||
ops.wait_healthy("worker", 1)
|
||||
ready = wait_status(api, bob, a["id"], ("ready", "failed"), seconds=90)
|
||||
check(ready["status"] == "ready", f"A must become ready, got {ready['status']} / {ready['error_code']}")
|
||||
print(f" A: worker started -> ready with {[v['name'] for v in ready['variants']]} (before the fix: "
|
||||
f"failed / source_missing)")
|
||||
|
||||
# ---------- C ----------
|
||||
before = set(ops.objects("staging/"))
|
||||
ops.arm("api", "api_pause_after_staging", PAUSE["api_pause_after_staging"])
|
||||
try:
|
||||
sending = background(upload, api, alice, chat, png(48, 36), "race-c.png")
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
new = sorted(set(ops.objects("staging/")) - before)
|
||||
if new:
|
||||
break
|
||||
check(time.monotonic() < deadline, "the upload did not reach staging")
|
||||
time.sleep(0.2)
|
||||
c_id = new[0].split("/", 1)[1]
|
||||
rows = ops.psql(f"SELECT count(*) FROM attachments WHERE id = '{c_id}'")
|
||||
check(rows == "0", "the row must not be committed yet")
|
||||
print(f"C. upload {c_id}: staging written, no row in the database yet (API paused before COMMIT)")
|
||||
out = janitor(container, c_id)
|
||||
check(out["deleted"] == 0 and out["skipped_busy"] == 1, f"janitor: {out}")
|
||||
print(f" janitor (grace 0): skipped_busy {out['skipped_busy']}, deleted {out['deleted']} — "
|
||||
f"the upload holds the attachment lock")
|
||||
att = finish(sending)
|
||||
check(att["id"] == c_id, "unexpected attachment id")
|
||||
finally:
|
||||
ops.disarm("api", "api_pause_after_staging")
|
||||
meta = wait_status(api, bob, c_id, seconds=60)
|
||||
print(f" upload -> 202, then {meta['status']} with {len(meta['variants'])} variants")
|
||||
|
||||
# ---------- D ----------
|
||||
ops.arm("worker", "worker_pause_after_objects", PAUSE["worker_pause_after_objects"])
|
||||
try:
|
||||
d = upload(api, alice, chat, SAMPLE_PNG, "race-d.png")
|
||||
deadline = time.monotonic() + 60
|
||||
while len(ops.objects(f"variants/{d['id']}/")) < 3 or not ops.objects(f"originals/{d['id']}"):
|
||||
check(time.monotonic() < deadline, "the worker did not write the objects")
|
||||
time.sleep(0.2)
|
||||
status = ops.job(d["id"])["attachment_status"]
|
||||
check(status == "processing", f"expected processing, got {status}")
|
||||
print(f"D. {d['id']}: worker wrote the original and 3 variants, COMMIT not yet (status {status})")
|
||||
out = janitor(container, d["id"])
|
||||
# По снимку ссылок оригинал и 3 варианта — ничьи (на них ещё нет COMMIT), staging — нужен.
|
||||
check(out["deleted"] == 0 and out["kept_after_recheck"].get("current_work", 0) == 4, f"janitor: {out}")
|
||||
print(f" janitor (grace 0): the snapshot marked the original and 3 variants as unreferenced; re-checked "
|
||||
f"under the lock -> kept {out['kept_after_recheck']}, deleted {out['deleted']}")
|
||||
finally:
|
||||
ops.disarm("worker", "worker_pause_after_objects")
|
||||
meta = wait_status(api, bob, d["id"], seconds=60)
|
||||
body = api.call("GET", f"/api/v1/attachments/{d['id']}/content", 200, actor=bob)["bytes"]
|
||||
check(hashlib.sha256(body).hexdigest() == d["sha256"], "the original changed")
|
||||
for variant in meta["variants"]:
|
||||
got = api.call("GET", f"/api/v1/attachments/{d['id']}/content?variant={variant['name']}", 200, actor=bob)
|
||||
check(hashlib.sha256(got["bytes"]).hexdigest() == variant["sha256"], "variant bytes differ")
|
||||
print(f" worker committed -> {meta['status']}; the original and all variants download with the same SHA-256")
|
||||
print("PASS: the janitor re-checks the state under the attachment lock before deleting: a replay accepted "
|
||||
"after its snapshot keeps the staging (A), a replay after the janitor's decision is refused safely (B), "
|
||||
"an upload in progress (C) and objects of a job in processing (D) are not deleted")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,64 @@
|
||||
"""lab5, уровень 4: ограниченная конкуренция worker и prefetch брокера.
|
||||
|
||||
make concurrency (= python student-tests/concurrency.py)
|
||||
|
||||
Точка worker_slow=6: каждая обработка «работает» 6 с. В очередь сразу попадают 6 заданий.
|
||||
Раз в 0,5 с смотрим:
|
||||
- сколько заданий в processing (PostgreSQL) — не больше WORKER_CONCURRENCY (2);
|
||||
- сколько сообщений выдано worker и не подтверждено (RabbitMQ messages_unacknowledged) — не больше
|
||||
prefetch (2), остальные лежат в очереди (messages_ready) и ждут: worker не набирает работу впрок,
|
||||
и при втором worker они достались бы ему.
|
||||
Все 6 вложений в итоге ready.
|
||||
"""
|
||||
import time
|
||||
|
||||
import ops
|
||||
from filegen import upload_when_ready, wait_status
|
||||
from helpers import Client, check, run
|
||||
|
||||
COUNT = 6
|
||||
LIMIT = 2
|
||||
|
||||
|
||||
def main():
|
||||
api = Client(timeout=15)
|
||||
ops.scale("worker", 1)
|
||||
worker = ops.wait_healthy("worker", 1)[0]
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
try:
|
||||
ops.arm("worker", "worker_slow", "6", container=worker)
|
||||
ids = [upload_when_ready(api, alice, chat, name=f"conc-{i}.png")["json"]["id"] for i in range(COUNT)]
|
||||
quoted = ", ".join(f"'{i}'" for i in ids)
|
||||
samples = []
|
||||
started = time.monotonic()
|
||||
while time.monotonic() - started < 60:
|
||||
rows = ops.psql(f"SELECT status, count(*) FROM attachment_jobs WHERE attachment_id IN ({quoted}) "
|
||||
"GROUP BY status").splitlines()
|
||||
by_status = {status: int(n) for status, n in (row.split("|") for row in rows if row)}
|
||||
ready_q, unacked = ops.queues().get("attachments.process", (0, 0))
|
||||
samples.append((round(time.monotonic() - started, 1), by_status.get("processing", 0), unacked, ready_q))
|
||||
if by_status.get("ready", 0) == COUNT:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
finally:
|
||||
ops.disarm("worker", "worker_slow")
|
||||
for attachment_id in ids:
|
||||
wait_status(api, bob, attachment_id, seconds=60)
|
||||
peak_processing = max(s[1] for s in samples)
|
||||
peak_unacked = max(s[2] for s in samples)
|
||||
waited = max(s[3] for s in samples)
|
||||
print("time s | processing (DB) | unacked (broker) | waiting in queue")
|
||||
for sample in samples[:: max(1, len(samples) // 12)]:
|
||||
print(f"{sample[0]:>6} | {sample[1]:>15} | {sample[2]:>16} | {sample[3]:>16}")
|
||||
check(peak_processing <= LIMIT, f"more than {LIMIT} jobs were processed at once: {peak_processing}")
|
||||
check(peak_unacked <= LIMIT, f"the worker took more than prefetch={LIMIT} messages: {peak_unacked}")
|
||||
check(peak_processing == LIMIT, "the worker did not use its parallelism")
|
||||
check(waited >= 1, "the other jobs should wait in the broker, not in the worker")
|
||||
print(f"peak: {peak_processing} jobs in processing, {peak_unacked} unacknowledged messages, up to {waited} "
|
||||
f"waiting in the queue; all {COUNT} ready after {samples[-1][0]} s")
|
||||
print(f"PASS: at most WORKER_CONCURRENCY={LIMIT} jobs run at once and the broker gives the worker at most "
|
||||
f"prefetch={LIMIT} messages; the rest wait in the durable queue")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,249 @@
|
||||
"""Замечание к MR: уборщик S3 не удаляет текущую работу — решение под блокировками в настоящей PostgreSQL.
|
||||
|
||||
Выполняется ВНУТРИ контейнера приложения вместе с остальными тестами БД:
|
||||
make db-test == docker compose --profile tools run --rm db-test
|
||||
|
||||
Уборщик проверяется без S3: вместо удаления объекта ему передаётся функция-«барьер», которая
|
||||
запоминает ключ и, если нужно, ждёт сигнала теста. Так порядок событий задаётся точно, как
|
||||
в воспроизведении из замечания (барьер в тестовом драйвере), а не надеждой на тайминги:
|
||||
1. снимок ссылок -> replay коммитит queued -> уборщик продолжает: staging НЕ удаляется
|
||||
(решение перепроверяется по текущему состоянию под блокировкой);
|
||||
2. уборщик под блокировкой уже пометил staging истёкшего failed-вложения удалённым, COMMIT ещё
|
||||
нет -> replay ждёт и безопасно отказывает source_missing, задание остаётся failed, в журнале
|
||||
обе записи; сам объект удаляется после COMMIT;
|
||||
3. replay держит блокировку (проверяет исходник) -> уборщик ждёт и видит queued: не удаляет;
|
||||
4. загрузка записала staging, COMMIT строки ещё не было -> уборщик вложение пропускает;
|
||||
5. задание в processing (worker пишет оригинал и варианты) -> ничего не удаляется;
|
||||
6. обычная уборка не сломана: «сирота» без строки, staging готового и объекты failed-вложения
|
||||
после retention удаляются; опубликованное и всё failed-вложения до конца retention — нет.
|
||||
"""
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
from messenger import config, db, faults, jobs
|
||||
from messenger.store import PostgresStore
|
||||
|
||||
RETENTION = 3600
|
||||
|
||||
|
||||
class Barrier:
|
||||
"""«Удаление объекта» для уборщика: запоминает ключи; может остановиться и ждать сигнала."""
|
||||
|
||||
def __init__(self, hold: bool = False):
|
||||
self.deleted, self.entered, self.release = [], threading.Event(), threading.Event()
|
||||
if not hold:
|
||||
self.release.set()
|
||||
|
||||
def __call__(self, key):
|
||||
self.deleted.append(key)
|
||||
self.entered.set()
|
||||
assert self.release.wait(20), "the test never released the barrier"
|
||||
|
||||
|
||||
class CleanupRaceTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
config.validate()
|
||||
db.migrate()
|
||||
cls.pool = db.create_pool(max_size=6)
|
||||
cls.pool.open(wait=True)
|
||||
cls.store = PostgresStore(cls.pool)
|
||||
cls.jobs = jobs.JobStore(cls.pool, "operator:db-test")
|
||||
cls.worker = jobs.JobStore(cls.pool, "worker-db-test")
|
||||
cls.user = cls.store.create_user("cl_" + uuid.uuid4().hex[:12], "Cleanup test", "not-a-real-hash")
|
||||
cls.chat = cls.store.create_chat(cls.user.id, "cleanup", [cls.user.id])
|
||||
|
||||
@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 execute(self, sql, *params):
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute(sql, params)
|
||||
|
||||
def queued(self):
|
||||
attachment_id = str(uuid.uuid4())
|
||||
self.store.create_queued_attachment(
|
||||
attachment_id, self.user.id, self.chat.id, "c.png", "image/png", 10, "0" * 64, 2, 2,
|
||||
staging_key="staging/" + attachment_id, storage_key="originals/" + attachment_id, actor="db-test")
|
||||
return attachment_id
|
||||
|
||||
def failed(self, expired: bool):
|
||||
"""failed-вложение; expired — retention истёк (как в замечании: возраст через updated_at)."""
|
||||
attachment_id = self.queued()
|
||||
job_id = str(self.scalar("SELECT job_id FROM attachment_jobs WHERE attachment_id = %s", uuid.UUID(attachment_id)))
|
||||
message = {"job_id": job_id, "attachment_id": attachment_id, "pipeline_version": 1, "attempt": 1}
|
||||
lease = self.worker.claim(message, "host/1").lease
|
||||
self.worker.fail(lease, "invalid_image", "test")
|
||||
if expired:
|
||||
self.execute("UPDATE attachments SET updated_at = now() - interval '2 days' WHERE id = %s",
|
||||
uuid.UUID(attachment_id))
|
||||
return attachment_id, job_id
|
||||
|
||||
def state(self, attachment_id):
|
||||
with self.pool.connection() as conn:
|
||||
return conn.execute("""SELECT a.status, a.staging_key IS NOT NULL, j.status FROM attachments a
|
||||
JOIN attachment_jobs j ON j.attachment_id = a.id WHERE a.id = %s""",
|
||||
(uuid.UUID(attachment_id),)).fetchone()
|
||||
|
||||
def events(self, job_id):
|
||||
with self.pool.connection() as conn:
|
||||
return [r[0] for r in conn.execute("SELECT event FROM job_events WHERE job_id = %s ORDER BY id",
|
||||
(uuid.UUID(job_id),))]
|
||||
|
||||
def test_1_replay_after_snapshot_keeps_staging(self):
|
||||
attachment_id, job_id = self.failed(expired=True)
|
||||
staging = "staging/" + attachment_id
|
||||
refs = self.store.storage_references(RETENTION) # уборщик прочитал ссылки...
|
||||
self.assertNotIn(staging, refs["needed"]) # ...по снимку staging лишний
|
||||
self.assertEqual(self.jobs.replay(attachment_id, lambda key: True)["result"], "queued") # барьер: replay
|
||||
barrier = Barrier()
|
||||
outcome = self.store.cleanup_attachment(attachment_id, [staging], RETENTION, barrier) # уборщик продолжает
|
||||
self.assertEqual((outcome["delete"], outcome["keep"]), ([], [(staging, "current_work")]))
|
||||
self.assertEqual(barrier.deleted, [])
|
||||
self.assertEqual(self.state(attachment_id), ("queued", True, "queued"))
|
||||
print(f"\n snapshot -> replay (queued) -> cleanup: kept {outcome['keep']}, nothing deleted")
|
||||
|
||||
def test_2_cleanup_first_then_replay_waits_and_refuses(self):
|
||||
attachment_id, job_id = self.failed(expired=True)
|
||||
staging = "staging/" + attachment_id
|
||||
locked, release = threading.Event(), threading.Event()
|
||||
real_pause = faults.pause
|
||||
|
||||
def pause(name): # барьер внутри транзакции уборщика (точка cleanup_pause_locked)
|
||||
if name == "cleanup_pause_locked":
|
||||
locked.set()
|
||||
release.wait(20)
|
||||
faults.pause = pause
|
||||
try:
|
||||
barrier, cleanup = Barrier(), {}
|
||||
janitor = threading.Thread(target=lambda: cleanup.update(
|
||||
self.store.cleanup_attachment(attachment_id, [staging], RETENTION, barrier)))
|
||||
janitor.start()
|
||||
self.assertTrue(locked.wait(10), "cleanup did not reach its decision") # держит блокировки
|
||||
replay = {}
|
||||
operator = threading.Thread(target=lambda: replay.update(self.jobs.replay(attachment_id, lambda key: True)))
|
||||
operator.start()
|
||||
time.sleep(1.0)
|
||||
self.assertTrue(operator.is_alive(), "replay must wait for the cleanup's lock")
|
||||
self.assertEqual(barrier.deleted, []) # до COMMIT в S3 ничего не удаляется
|
||||
release.set()
|
||||
janitor.join(10)
|
||||
operator.join(10)
|
||||
finally:
|
||||
faults.pause = real_pause
|
||||
self.assertEqual(cleanup["delete"], [(staging, "staging_failed_expired")])
|
||||
self.assertEqual(barrier.deleted, [staging]) # удалён после COMMIT
|
||||
self.assertEqual((replay["result"], replay["reason"]), ("refused", "source_missing"))
|
||||
self.assertEqual(self.state(attachment_id), ("failed", False, "failed"))
|
||||
# Порядок в журнале: сначала уборщик, потом отказ replay (записи worker стенда, если он
|
||||
# успел увидеть тестовое задание, сюда не относятся).
|
||||
ours = [e for e in self.events(job_id) if e in ("staging_expired", "replay_refused", "replay_requested")]
|
||||
self.assertEqual(ours, ["staging_expired", "replay_refused"])
|
||||
print(f"\n cleanup marked the staging deleted, holds the lock -> replay waited 1 s+ -> {replay['result']} "
|
||||
f"({replay['reason']}); job stays failed; journal: staging_expired, replay_refused")
|
||||
|
||||
def test_3_replay_first_then_cleanup_waits_and_keeps(self):
|
||||
attachment_id, job_id = self.failed(expired=True)
|
||||
staging = "staging/" + attachment_id
|
||||
checking, release = threading.Event(), threading.Event()
|
||||
|
||||
def slow_head(key): # replay проверяет исходник в S3, держа блокировки
|
||||
checking.set()
|
||||
return release.wait(20)
|
||||
replay = {}
|
||||
operator = threading.Thread(target=lambda: replay.update(self.jobs.replay(attachment_id, slow_head)))
|
||||
operator.start()
|
||||
self.assertTrue(checking.wait(10))
|
||||
cleanup, barrier = {}, Barrier()
|
||||
janitor = threading.Thread(target=lambda: cleanup.update(
|
||||
self.store.cleanup_attachment(attachment_id, [staging], RETENTION, barrier) or {"busy": True}))
|
||||
janitor.start()
|
||||
time.sleep(1.0)
|
||||
self.assertTrue(janitor.is_alive(), "cleanup must wait for the replay's lock")
|
||||
release.set()
|
||||
operator.join(10)
|
||||
janitor.join(10)
|
||||
self.assertEqual(replay["result"], "queued")
|
||||
self.assertEqual(cleanup.get("keep"), [(staging, "current_work")])
|
||||
self.assertEqual(barrier.deleted, [])
|
||||
print(f"\n replay holds the lock -> cleanup waited -> kept {cleanup['keep']}")
|
||||
|
||||
def test_4_upload_in_progress_is_skipped(self):
|
||||
attachment_id = str(uuid.uuid4())
|
||||
staging = "staging/" + attachment_id
|
||||
inside, finish = threading.Event(), threading.Event()
|
||||
|
||||
def upload(): # как attachments.accept: PUT в staging, потом строка, COMMIT
|
||||
with self.store.receiving(attachment_id) as conn:
|
||||
inside.set() # «PUT в staging прошёл»
|
||||
finish.wait(20)
|
||||
self.store.create_queued_attachment(
|
||||
attachment_id, self.user.id, self.chat.id, "u.png", "image/png", 10, "0" * 64, 2, 2,
|
||||
staging_key=staging, storage_key="originals/" + attachment_id, actor="db-test", conn=conn)
|
||||
api = threading.Thread(target=upload)
|
||||
api.start()
|
||||
self.assertTrue(inside.wait(10))
|
||||
barrier = Barrier()
|
||||
self.assertIsNone(self.store.cleanup_attachment(attachment_id, [staging], RETENTION, barrier)) # занято
|
||||
finish.set()
|
||||
api.join(10)
|
||||
after = self.store.cleanup_attachment(attachment_id, [staging], RETENTION, barrier)
|
||||
self.assertEqual((after["keep"], barrier.deleted), ([(staging, "current_work")], []))
|
||||
self.assertEqual(self.state(attachment_id), ("queued", True, "queued"))
|
||||
print("\n upload between PUT and COMMIT -> cleanup skipped it (busy); after COMMIT -> current work, kept")
|
||||
|
||||
def test_5_objects_of_processing_job_are_kept(self):
|
||||
attachment_id = self.queued()
|
||||
job_id = str(self.scalar("SELECT job_id FROM attachment_jobs WHERE attachment_id = %s", uuid.UUID(attachment_id)))
|
||||
self.worker.claim({"job_id": job_id, "attachment_id": attachment_id, "pipeline_version": 1, "attempt": 1},
|
||||
"host/1")
|
||||
keys = [f"originals/{attachment_id}", f"variants/{attachment_id}/v1/thumbnail.jpg", f"staging/{attachment_id}"]
|
||||
barrier = Barrier()
|
||||
outcome = self.store.cleanup_attachment(attachment_id, keys, RETENTION, barrier)
|
||||
self.assertEqual((outcome["delete"], barrier.deleted), ([], []))
|
||||
self.assertEqual({why for _key, why in outcome["keep"]}, {"current_work"})
|
||||
print("\n processing job (worker writes the original and variants before COMMIT) -> all 3 objects kept")
|
||||
|
||||
def test_6_regular_cleanup_still_works(self):
|
||||
barrier = Barrier()
|
||||
orphan = str(uuid.uuid4()) # строки нет, загрузка не идёт
|
||||
out = self.store.cleanup_attachment(orphan, [f"staging/{orphan}"], RETENTION, barrier)
|
||||
self.assertEqual(out["delete"], [(f"staging/{orphan}", "orphan")])
|
||||
kept_id, _job = self.failed(expired=False) # retention не истёк: нужен для replay
|
||||
out = self.store.cleanup_attachment(kept_id, [f"staging/{kept_id}", f"originals/{kept_id}"], RETENTION, barrier)
|
||||
self.assertEqual(out["keep"], [(f"staging/{kept_id}", "staging_kept_for_replay"),
|
||||
(f"originals/{kept_id}", "failed_kept_for_replay")]) # replay перезапишет
|
||||
dead_id, dead_job = self.failed(expired=True) # retention истёк: удаляется всё
|
||||
out = self.store.cleanup_attachment(dead_id, [f"originals/{dead_id}"], RETENTION, barrier)
|
||||
self.assertEqual(out["delete"], [(f"originals/{dead_id}", "orphan")])
|
||||
self.assertEqual(self.state(dead_id)[1], False) # staging помечен удалённым до удаления
|
||||
self.assertEqual(self.jobs.replay(dead_id, lambda key: True)["reason"], "source_missing")
|
||||
ready = self.queued()
|
||||
job_id = str(self.scalar("SELECT job_id FROM attachment_jobs WHERE attachment_id = %s", uuid.UUID(ready)))
|
||||
lease = self.worker.claim({"job_id": job_id, "attachment_id": ready, "pipeline_version": 1, "attempt": 1},
|
||||
"host/1").lease
|
||||
variants = [{"name": n, "storage_key": f"variants/{ready}/v1/{n}.jpg", "content_type": "image/jpeg",
|
||||
"size_bytes": 5, "width": 1, "height": 1, "sha256": "a" * 64} for n in ("thumbnail", "crop")]
|
||||
self.assertIsNotNone(self.worker.complete(lease, variants))
|
||||
keys = [f"staging/{ready}", f"originals/{ready}", f"variants/{ready}/v1/thumbnail.jpg",
|
||||
f"variants/{ready}/v1/stale.jpg"]
|
||||
out = self.store.cleanup_attachment(ready, keys, RETENTION, barrier)
|
||||
self.assertEqual(sorted(out["delete"]), sorted([(f"staging/{ready}", "staging_after_ready"),
|
||||
(f"variants/{ready}/v1/stale.jpg", "orphan")]))
|
||||
self.assertEqual({why for _key, why in out["keep"]}, {"published"})
|
||||
dry = self.store.cleanup_attachment(orphan, [f"staging/{orphan}"], RETENTION, None) # пробный прогон
|
||||
self.assertEqual(dry["delete"], [(f"staging/{orphan}", "orphan")])
|
||||
self.assertEqual(len(barrier.deleted), 4) # dry-run ничего не удалил
|
||||
print("\n orphan, staging after ready, objects of a failed attachment after retention -> deleted; "
|
||||
"published original and variants, a failed attachment within retention -> kept; dry-run deletes nothing")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,194 @@
|
||||
"""lab5: состояние заданий в настоящей PostgreSQL — claim, lease, fencing, повторы, replay, outbox.
|
||||
|
||||
Выполняются ВНУТРИ контейнера приложения вместе с test_store.py:
|
||||
make db-test == docker compose --profile tools run --rm db-test
|
||||
|
||||
Здесь проверяется сама логика jobs.py без брокера и S3 — точно и без ожидания таймеров:
|
||||
- claim берёт задание один раз; конкурентные claim (10 потоков) — ровно один успех;
|
||||
- дубль ready-задания и устаревшее сообщение (старая попытка) не обрабатываются;
|
||||
- результат с чужим жетоном lease не принимается (fencing), повторный complete — тоже;
|
||||
- временная ошибка -> следующая попытка через backoff с jitter в [d/2, d] и новая строка outbox;
|
||||
после JOB_MAX_ATTEMPTS -> failed / retry_exhausted; постоянная ошибка -> failed сразу;
|
||||
- истёкший lease забирает reap(); lease прежнего запуска того же контейнера — сразу;
|
||||
- продление lease: свой жетон продлевается, забранный — нет;
|
||||
- replay: failed -> queued с записью в журнале; ready/queued — no-op; нет staging — отказ;
|
||||
- две транзакции relay с FOR UPDATE SKIP LOCKED берут разные строки outbox.
|
||||
"""
|
||||
import threading
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
import psycopg
|
||||
|
||||
from messenger import broker, config, db, jobs
|
||||
from messenger.store import PostgresStore
|
||||
|
||||
|
||||
class JobsIntegrationTest(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)
|
||||
cls.jobs = jobs.JobStore(cls.pool, "db-test")
|
||||
cls.user = cls.store.create_user("jb_" + uuid.uuid4().hex[:12], "Jobs test", "not-a-real-hash")
|
||||
cls.chat = cls.store.create_chat(cls.user.id, "jobs", [cls.user.id])
|
||||
|
||||
@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 execute(self, sql, *params):
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute(sql, params)
|
||||
|
||||
def new_job(self):
|
||||
attachment_id = str(uuid.uuid4())
|
||||
self.store.create_queued_attachment(
|
||||
attachment_id, self.user.id, self.chat.id, "t.png", "image/png", 10, "0" * 64, 2, 2,
|
||||
staging_key="staging/" + attachment_id, storage_key="originals/" + attachment_id, actor="db-test")
|
||||
job_id = str(self.scalar("SELECT job_id FROM attachment_jobs WHERE attachment_id = %s", uuid.UUID(attachment_id)))
|
||||
return attachment_id, job_id
|
||||
|
||||
def message(self, attachment_id, job_id, attempt=1):
|
||||
return broker.parse(broker.encode(broker.build_message(job_id, attachment_id, 1, attempt)))
|
||||
|
||||
def status(self, attachment_id):
|
||||
with self.pool.connection() as conn:
|
||||
return conn.execute("""SELECT a.status, a.error_code, j.status, j.attempt FROM attachments a
|
||||
JOIN attachment_jobs j ON j.attachment_id = a.id WHERE a.id = %s""",
|
||||
(uuid.UUID(attachment_id),)).fetchone()
|
||||
|
||||
def variants(self):
|
||||
return [{"name": n, "storage_key": f"variants/{uuid.uuid4()}/{n}", "content_type": "image/jpeg",
|
||||
"size_bytes": 5, "width": 1, "height": 1, "sha256": "a" * 64} for n in ("thumbnail", "crop", "optimized")]
|
||||
|
||||
def test_upload_creates_job_and_outbox_in_one_transaction(self):
|
||||
attachment_id, job_id = self.new_job()
|
||||
self.assertEqual(self.status(attachment_id), ("queued", None, "queued", 1))
|
||||
payload = self.scalar("SELECT payload FROM outbox WHERE job_id = %s", uuid.UUID(job_id))
|
||||
self.assertEqual(broker.parse(broker.encode(payload))["attachment_id"], attachment_id)
|
||||
self.assertEqual(set(payload), {"schema_version", "job_id", "type", "attachment_id", "pipeline_version",
|
||||
"attempt", "created_at"}) # только ID и служебные поля
|
||||
|
||||
def test_claim_once_and_concurrent_claims(self):
|
||||
attachment_id, job_id = self.new_job()
|
||||
results = []
|
||||
barrier = threading.Barrier(10)
|
||||
|
||||
def claim(n):
|
||||
barrier.wait()
|
||||
results.append(self.jobs.claim(self.message(attachment_id, job_id), f"host{n}/w").kind)
|
||||
|
||||
threads = [threading.Thread(target=claim, args=(n,)) for n in range(10)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
self.assertEqual(results.count("claimed"), 1, results)
|
||||
self.assertEqual(results.count("in_progress"), 9, results)
|
||||
self.assertEqual(self.status(attachment_id)[0], "processing")
|
||||
print(f"\n 10 concurrent claims of one job: {results.count('claimed')} claimed, "
|
||||
f"{results.count('in_progress')} in_progress")
|
||||
|
||||
def test_fencing_and_duplicates(self):
|
||||
attachment_id, job_id = self.new_job()
|
||||
lease = self.jobs.claim(self.message(attachment_id, job_id), "hostA/1").lease
|
||||
stolen = jobs.Lease(**{**lease.__dict__, "token": str(uuid.uuid4())})
|
||||
self.assertIsNone(self.jobs.complete(stolen, self.variants())) # чужой жетон: не принимается
|
||||
self.assertIsNotNone(self.jobs.complete(lease, self.variants()))
|
||||
self.assertIsNone(self.jobs.complete(lease, self.variants())) # второй раз: lease уже снят
|
||||
self.assertEqual(self.status(attachment_id), ("ready", None, "ready", 1))
|
||||
self.assertEqual(self.jobs.claim(self.message(attachment_id, job_id), "hostB/1").kind, "ready")
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM attachment_variants WHERE attachment_id = %s",
|
||||
uuid.UUID(attachment_id)), 3)
|
||||
|
||||
def test_retry_backoff_then_exhausted(self):
|
||||
attachment_id, job_id = self.new_job()
|
||||
for attempt in range(1, config.JOB_MAX_ATTEMPTS + 1):
|
||||
lease = self.jobs.claim(self.message(attachment_id, job_id, attempt), "hostA/1").lease
|
||||
self.assertIsNotNone(lease, attempt)
|
||||
outcome = self.jobs.retry(lease, "storage_unavailable", "S3 недоступен")
|
||||
if attempt < config.JOB_MAX_ATTEMPTS:
|
||||
self.assertEqual(outcome, "retry")
|
||||
delay = self.scalar("""SELECT extract(epoch FROM available_at - created_at) FROM outbox
|
||||
WHERE job_id = %s AND attempt = %s""", uuid.UUID(job_id), attempt + 1)
|
||||
limit = min(config.RETRY_MAX_SECONDS, config.RETRY_BASE_SECONDS * 2 ** (attempt - 1))
|
||||
self.assertTrue(limit / 2 - 0.01 <= float(delay) <= limit + 0.01, (attempt, delay))
|
||||
# Сообщение прошлой попытки теперь устаревшее.
|
||||
self.assertEqual(self.jobs.claim(self.message(attachment_id, job_id, attempt), "hostB/1").kind, "stale")
|
||||
else:
|
||||
self.assertEqual(outcome, "failed")
|
||||
self.assertEqual(self.status(attachment_id), ("failed", "retry_exhausted", "failed", config.JOB_MAX_ATTEMPTS))
|
||||
|
||||
def test_permanent_error_fails_at_once(self):
|
||||
attachment_id, job_id = self.new_job()
|
||||
lease = self.jobs.claim(self.message(attachment_id, job_id), "hostA/1").lease
|
||||
self.assertTrue(self.jobs.fail(lease, "invalid_image", "не декодируется"))
|
||||
self.assertEqual(self.status(attachment_id), ("failed", "invalid_image", "failed", 1))
|
||||
self.assertEqual(self.jobs.claim(self.message(attachment_id, job_id), "hostA/2").kind, "failed")
|
||||
|
||||
def test_expired_lease_and_dead_predecessor(self):
|
||||
attachment_id, job_id = self.new_job()
|
||||
lease = self.jobs.claim(self.message(attachment_id, job_id), "hostA/1").lease
|
||||
self.assertEqual(self.jobs.claim(self.message(attachment_id, job_id), "hostB/1").kind, "in_progress")
|
||||
self.assertEqual(self.jobs.renew([lease.token]), {lease.token}) # живой worker продлевает
|
||||
self.execute("UPDATE attachment_jobs SET lease_until = now() - interval '1 second' WHERE job_id = %s",
|
||||
uuid.UUID(job_id))
|
||||
reaped = [r for r in self.jobs.reap() if r[0] == attachment_id]
|
||||
self.assertEqual(reaped, [(attachment_id, "retry")])
|
||||
self.assertEqual(self.status(attachment_id)[2:], ("queued", 2))
|
||||
self.assertEqual(self.jobs.renew([lease.token]), set()) # забранный lease не продлевается
|
||||
self.assertIsNone(self.jobs.complete(lease, self.variants())) # и результат не принимается
|
||||
# Прежний запуск того же контейнера держит lease -> следующая попытка сразу, без ожидания срока.
|
||||
lease2 = self.jobs.claim(self.message(attachment_id, job_id, 2), "hostC/old").lease
|
||||
decision = self.jobs.claim(self.message(attachment_id, job_id, 2), "hostC/new")
|
||||
self.assertEqual((decision.kind, decision.detail), ("rescheduled", "retry"))
|
||||
self.assertEqual(self.status(attachment_id)[2:], ("queued", 3))
|
||||
self.assertIsNotNone(lease2)
|
||||
|
||||
def test_replay_rules(self):
|
||||
attachment_id, job_id = self.new_job()
|
||||
self.assertEqual(self.jobs.replay(attachment_id, lambda key: True), {"result": "noop", "reason": "queued"})
|
||||
lease = self.jobs.claim(self.message(attachment_id, job_id), "hostA/1").lease
|
||||
self.jobs.fail(lease, "invalid_image", "битый файл")
|
||||
self.assertEqual(self.jobs.replay(attachment_id, lambda key: False)["reason"], "source_missing")
|
||||
result = self.jobs.replay(attachment_id, lambda key: True)
|
||||
self.assertEqual(result["result"], "queued")
|
||||
self.assertEqual(self.status(attachment_id), ("queued", None, "queued", 2))
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM job_events WHERE job_id = %s AND event = 'replay_requested'",
|
||||
uuid.UUID(job_id)), 1)
|
||||
lease = self.jobs.claim(self.message(attachment_id, job_id, 2), "hostA/1").lease
|
||||
self.jobs.complete(lease, self.variants())
|
||||
before = self.scalar("SELECT count(*) FROM outbox WHERE job_id = %s", uuid.UUID(job_id))
|
||||
self.assertEqual(self.jobs.replay(attachment_id, lambda key: True), {"result": "noop", "reason": "ready"})
|
||||
self.assertEqual(self.scalar("SELECT count(*) FROM outbox WHERE job_id = %s", uuid.UUID(job_id)), before)
|
||||
|
||||
def test_outbox_rows_are_taken_by_one_relay(self):
|
||||
for _ in range(4):
|
||||
self.new_job()
|
||||
sql = """SELECT id FROM outbox WHERE published_at IS NULL ORDER BY available_at, id LIMIT 2
|
||||
FOR UPDATE SKIP LOCKED"""
|
||||
with psycopg.connect(config.DATABASE_URL, autocommit=True) as one, \
|
||||
psycopg.connect(config.DATABASE_URL, autocommit=True) as two:
|
||||
with one.transaction(), two.transaction(): # как две реплики relay одновременно
|
||||
a = {r[0] for r in one.execute(sql)}
|
||||
b = {r[0] for r in two.execute(sql)}
|
||||
self.assertTrue(a and b and not (a & b), (a, b))
|
||||
|
||||
def test_backoff_bounds(self):
|
||||
for attempt in range(1, 8):
|
||||
limit = min(config.RETRY_MAX_SECONDS, config.RETRY_BASE_SECONDS * 2 ** (attempt - 1))
|
||||
samples = [jobs.backoff(attempt) for _ in range(200)]
|
||||
self.assertTrue(all(limit / 2 <= s <= limit for s in samples), attempt)
|
||||
self.assertGreater(max(samples) - min(samples), limit * 0.2) # действительно случайно
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -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,102 @@
|
||||
"""lab6: контекст трассы в outbox (W3C traceparent) и время до ready — в настоящей PostgreSQL.
|
||||
|
||||
make db-test == docker compose --profile tools run --rm db-test
|
||||
|
||||
- задание, созданное внутри span (как при HTTP upload), пишет в outbox traceparent этого span,
|
||||
и сообщение проходит проверку по contracts/jobs.schema.json;
|
||||
- повтор без активного span (истёкший lease в фоновом потоке, replay оператора) копирует traceparent
|
||||
прошлой строки: следующая попытка остаётся в той же трассе;
|
||||
- повтор внутри span worker пишет traceparent этого span (новый родитель, тот же trace_id);
|
||||
- complete() возвращает время от принятия загрузки до ready (секунды, >= 0), чужой lease — None.
|
||||
SDK OpenTelemetry используется без экспорта (провайдер в памяти теста).
|
||||
"""
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
from opentelemetry.sdk.trace import TracerProvider
|
||||
|
||||
from messenger import broker, config, db, jobs, telemetry
|
||||
from messenger.store import PostgresStore
|
||||
|
||||
TRACER = TracerProvider().get_tracer("db-test")
|
||||
|
||||
|
||||
class TraceContextTest(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)
|
||||
cls.jobs = jobs.JobStore(cls.pool, "db-test")
|
||||
cls.user = cls.store.create_user("tc_" + uuid.uuid4().hex[:12], "Trace test", "not-a-real-hash")
|
||||
cls.chat = cls.store.create_chat(cls.user.id, "trace", [cls.user.id])
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.pool.close()
|
||||
|
||||
def new_job(self):
|
||||
attachment_id = str(uuid.uuid4())
|
||||
self.store.create_queued_attachment(
|
||||
attachment_id, self.user.id, self.chat.id, "t.png", "image/png", 10, "0" * 64, 2, 2,
|
||||
staging_key="staging/" + attachment_id, storage_key="originals/" + attachment_id, actor="db-test")
|
||||
with self.pool.connection() as conn:
|
||||
job_id = conn.execute("SELECT job_id FROM attachment_jobs WHERE attachment_id = %s",
|
||||
(uuid.UUID(attachment_id),)).fetchone()[0]
|
||||
return attachment_id, str(job_id)
|
||||
|
||||
def outbox(self, job_id):
|
||||
with self.pool.connection() as conn:
|
||||
return [r[0] for r in conn.execute("SELECT payload FROM outbox WHERE job_id = %s ORDER BY id",
|
||||
(uuid.UUID(job_id),)).fetchall()]
|
||||
|
||||
def claim(self, payload):
|
||||
decision = self.jobs.claim(broker.parse(broker.encode(payload)), "worker-test/1")
|
||||
self.assertEqual(decision.kind, "claimed")
|
||||
return decision.lease
|
||||
|
||||
def test_upload_span_and_retries_stay_in_one_trace(self):
|
||||
with TRACER.start_as_current_span("POST /attachments") as upload:
|
||||
attachment_id, job_id = self.new_job()
|
||||
trace_id = format(upload.get_span_context().trace_id, "032x")
|
||||
span_id = format(upload.get_span_context().span_id, "016x")
|
||||
first = self.outbox(job_id)[0]
|
||||
# Флаги: 01 = sampled (SDK 1.45 добавляет бит random trace id, получается 03).
|
||||
self.assertEqual(first["traceparent"][:-3], f"00-{trace_id}-{span_id}")
|
||||
self.assertIn(first["traceparent"][-2:], ("01", "03"))
|
||||
self.assertEqual(broker.parse(broker.encode(first))["traceparent"], first["traceparent"])
|
||||
|
||||
# Повтор без активного span (как reap в фоновом потоке): копия traceparent прошлой строки.
|
||||
lease = self.claim(first)
|
||||
self.assertEqual(self.jobs.retry(lease, "storage_unavailable", "test"), "retry")
|
||||
second = self.outbox(job_id)[1]
|
||||
self.assertEqual((second["attempt"], second["traceparent"]), (2, first["traceparent"]))
|
||||
|
||||
# Повтор внутри span worker: новый родитель (span worker), та же трасса.
|
||||
with self.pool.connection() as conn:
|
||||
conn.execute("UPDATE attachment_jobs SET next_attempt_at = now() WHERE job_id = %s", (uuid.UUID(job_id),))
|
||||
lease = self.claim(second)
|
||||
# Как в worker: consumer span — дочерний для traceparent из сообщения.
|
||||
with TRACER.start_as_current_span("process attachments.process", context=telemetry.extract(second)) as consume:
|
||||
self.assertEqual(self.jobs.retry(lease, "storage_unavailable", "test"), "retry")
|
||||
third = self.outbox(job_id)[2]
|
||||
self.assertEqual(third["traceparent"].split("-")[1], trace_id)
|
||||
self.assertEqual(third["traceparent"].split("-")[2], format(consume.get_span_context().span_id, "016x"))
|
||||
|
||||
def test_complete_returns_time_to_ready(self):
|
||||
attachment_id, job_id = self.new_job()
|
||||
lease = self.claim(self.outbox(job_id)[0])
|
||||
variants = [{"name": n, "storage_key": f"variants/{attachment_id}/{n}", "content_type": "image/jpeg",
|
||||
"size_bytes": 5, "width": 1, "height": 1, "sha256": "a" * 64}
|
||||
for n in ("thumbnail", "crop", "optimized")]
|
||||
waited = self.jobs.complete(lease, variants)
|
||||
self.assertIsInstance(waited, float)
|
||||
self.assertGreaterEqual(waited, 0.0)
|
||||
self.assertLess(waited, 60.0)
|
||||
self.assertIsNone(self.jobs.complete(lease, variants)) # lease уже снят: результат не принимается
|
||||
|
||||
|
||||
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:8444. База и кэш общие с основным 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", "https://127.0.0.1:8444"))
|
||||
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,149 @@
|
||||
"""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 alias_of, 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_alias = alias_of(container)
|
||||
target_hits = sum(1 for instance in served_after if instance and instance == target_alias)
|
||||
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,77 @@
|
||||
"""lab4–lab5, уровень 3: недоступность S3.
|
||||
|
||||
make failure-s3 (= python student-tests/failure_s3.py)
|
||||
|
||||
С lab5 S3 входит в /health/ready: без него нельзя принять файл в staging, а это обязательный путь
|
||||
(без staging нельзя честно ответить 202). Поэтому при остановке контейнера s3 (SeaweedFS):
|
||||
- каждая реплика: /health/live = 200 (процесс жив), /health/ready = 503 (не может обслужить путь);
|
||||
- HAProxy выводит обе реплики из балансировки и сам отвечает 503 в формате ошибки контракта —
|
||||
быстро, без зависаний и без 500;
|
||||
после запуска S3 реплики возвращаются, файл, загруженный до сбоя, скачивается без изменений,
|
||||
новая загрузка снова 202 -> ready.
|
||||
"""
|
||||
import hashlib
|
||||
import time
|
||||
|
||||
from filegen import SAMPLE_PNG, upload_when_ready, wait_status, wait_until
|
||||
from helpers import Client, Failure, check, run
|
||||
from stand import api_containers, compose_quiet, lb_summary, lb_up_count, ps_table, replica_status, try_call
|
||||
|
||||
|
||||
def main():
|
||||
api = Client()
|
||||
replicas = api_containers()
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
att = upload_when_ready(api, alice, chat, name="before.png")["json"]
|
||||
wait_status(api, bob, att["id"])
|
||||
content = f"/api/v1/attachments/{att['id']}/content"
|
||||
compose_quiet("stop", "s3")
|
||||
stopped = time.monotonic()
|
||||
try:
|
||||
print("=== s3 stopped")
|
||||
print(ps_table())
|
||||
wait_until(lambda: lb_up_count() == 0, 30, "HAProxy kept a replica that cannot reach S3")
|
||||
took = time.monotonic() - stopped
|
||||
print(f"both api replicas are out of the balancer after {took:.1f} s: {lb_summary()}")
|
||||
for container in replicas:
|
||||
live, ready = replica_status(container, "/health/live"), replica_status(container, "/health/ready")
|
||||
print(f"replica {container[:12]}: /health/live {live}, /health/ready {ready}")
|
||||
check(live == 200 and ready == 503, "expected live 200 and ready 503")
|
||||
for method, path, body, ctype in (("GET", "/health/ready", None, None),
|
||||
("POST", f"/api/v1/chats/{chat['id']}/attachments?filename=x.png",
|
||||
SAMPLE_PNG, "image/png"),
|
||||
("GET", content, None, None),
|
||||
("GET", f"/api/v1/chats/{chat['id']}/messages", None, None)):
|
||||
started = time.monotonic()
|
||||
reply = try_call(method, path, raw=body, token=alice["token"],
|
||||
headers={"Content-Type": ctype} if ctype else None, timeout=15)
|
||||
check(reply is not None and reply.status == 503, f"{method} {path}: expected 503")
|
||||
check(reply.json["error"]["code"] == "unavailable" and reply.headers.get("x-request-id"),
|
||||
"the balancer must answer in the contract error format")
|
||||
print(f"{method} {path.split('?')[0]} -> {reply.status} {reply.json['error']['code']} "
|
||||
f"in {time.monotonic() - started:.2f} s (answered by the balancer)")
|
||||
finally:
|
||||
compose_quiet("start", "s3")
|
||||
print("=== s3 started")
|
||||
started = time.monotonic()
|
||||
wait_until(lambda: lb_up_count() == len(replicas), 120, "replicas did not come back")
|
||||
print(f"replicas are back in the balancer after {time.monotonic() - started:.1f} s: {lb_summary()}")
|
||||
|
||||
def downloaded():
|
||||
try:
|
||||
return api.call("GET", content, actor=bob)["bytes"] == SAMPLE_PNG
|
||||
except Failure:
|
||||
return False
|
||||
|
||||
wait_until(downloaded, 60, "the old file is not downloadable after S3 restart")
|
||||
print(f"the file uploaded before the outage is intact (sha256 {hashlib.sha256(SAMPLE_PNG).hexdigest()[:16]}...)")
|
||||
new = upload_when_ready(api, alice, chat, name="after.png")["json"]
|
||||
wait_status(api, bob, new["id"])
|
||||
print(f"new upload -> 202 -> ready ({new['id']})")
|
||||
print(ps_table())
|
||||
print("PASS: S3 down -> replicas not ready (live 200, ready 503), the balancer answers 503 in the contract "
|
||||
"format, no 500 and no hanging; after S3 is back the original is intact and uploads work again")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,468 @@
|
||||
"""lab4–lab5: тестовые картинки и низкоуровневая загрузка — только стандартная библиотека Python.
|
||||
|
||||
- png(): настоящий PNG любого размера (шум не сжимается — так получаются файлы на 9 МБ);
|
||||
- bomb_png(): «бомба» — файл ~150 КБ, внутри 42 млн пикселей (больше лимита 40 млн);
|
||||
- SAMPLE_JPEG: синтетический JPEG 48×32 (781 байт), создан для курса программно;
|
||||
- garbage_scan_jpeg(): JPEG с правильной структурой, но мусором вместо сжатых данных (lab5:
|
||||
API его принимает — структура цела, а worker при строгом декодировании даёт invalid_image);
|
||||
- bad_filter_png(): PNG с недопустимым типом фильтра строки (lab5: 415 уже в API);
|
||||
- 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 ssl
|
||||
import subprocess
|
||||
import time
|
||||
import zlib
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from helpers import ROOT, Failure, check
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "https://127.0.0.1:8443").rstrip("/")
|
||||
CA_FILE = os.environ.get("CA_FILE") or None # с lab7: CA стенда для проверки сертификата балансировщика
|
||||
|
||||
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==")
|
||||
# Ещё два синтетических JPEG 40×24 (созданы для курса Pillow): progressive и с маркерами RST (DRI = 1 MCU).
|
||||
PROGRESSIVE_JPEG = base64.b64decode(
|
||||
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA0JCgsKCA0LCgsODg0PEyAVExISEyccHhcgLikxMC4pLSwzOko+MzZGNywtQFdBRkxOUlNS"
|
||||
"Mj5aYVpQYEpRUk//2wBDAQ4ODhMREyYVFSZPNS01T09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09P"
|
||||
"T0//wgARCAAYACgDASIAAhEBAxEB/8QAFwABAQEBAAAAAAAAAAAAAAAAAAMEBf/EABgBAAMBAQAAAAAAAAAAAAAAAAIDBAEG/9oADAMB"
|
||||
"AAIQAxAAAAHg11WxeWuqzbMreOuNSLlrVG22B1f/xAAWEAADAAAAAAAAAAAAAAAAAAAAAQL/2gAIAQEAAQUCUCgUCgUCgUCgUCgUCgUC"
|
||||
"gUH/xAAXEQADAQAAAAAAAAAAAAAAAAAAAQID/9oACAEDAQE/AY2I2FsRTIpipn//xAAXEQEBAQEAAAAAAAAAAAAAAAABABAR/9oACAEC"
|
||||
"AQE/ARhuxGf/xAAUEAEAAAAAAAAAAAAAAAAAAAAw/9oACAEBAAY/An//xAAUEAEAAAAAAAAAAAAAAAAAAAAw/9oACAEBAAE/IXAAAAA/"
|
||||
"/9oADAMBAAIAAwAAABBpk59wP//EABcRAQADAAAAAAAAAAAAAAAAABAAESH/2gAIAQMBAT8QKydq0//EABYRAQEBAAAAAAAAAAAAAAAA"
|
||||
"AAEAEP/aAAgBAgEBPxDPK2bC3//EABUQAQEAAAAAAAAAAAAAAAAAAABh/9oACAEBAAE/EJJJJJJJJJJJJJJJP//Z")
|
||||
RESTART_JPEG = base64.b64decode(
|
||||
"/9j/4AAQSkZJRgABAQAAAQABAAD/2wBDAA0JCgsKCA0LCgsODg0PEyAVExISEyccHhcgLikxMC4pLSwzOko+MzZGNywtQFdBRkxOUlNS"
|
||||
"Mj5aYVpQYEpRUk//2wBDAQ4ODhMREyYVFSZPNS01T09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09PT09P"
|
||||
"T0//wAARCAAYACgDASIAAhEBAxEB/8QAHwAAAQUBAQEBAQEAAAAAAAAAAAECAwQFBgcICQoL/8QAtRAAAgEDAwIEAwUFBAQAAAF9AQID"
|
||||
"AAQRBRIhMUEGE1FhByJxFDKBkaEII0KxwRVS0fAkM2JyggkKFhcYGRolJicoKSo0NTY3ODk6Q0RFRkdISUpTVFVWV1hZWmNkZWZnaGlq"
|
||||
"c3R1dnd4eXqDhIWGh4iJipKTlJWWl5iZmqKjpKWmp6ipqrKztLW2t7i5usLDxMXGx8jJytLT1NXW19jZ2uHi4+Tl5ufo6erx8vP09fb3"
|
||||
"+Pn6/8QAHwEAAwEBAQEBAQEBAQAAAAAAAAECAwQFBgcICQoL/8QAtREAAgECBAQDBAcFBAQAAQJ3AAECAxEEBSExBhJBUQdhcRMiMoEI"
|
||||
"FEKRobHBCSMzUvAVYnLRChYkNOEl8RcYGRomJygpKjU2Nzg5OkNERUZHSElKU1RVVldYWVpjZGVmZ2hpanN0dXZ3eHl6goOEhYaHiImK"
|
||||
"kpOUlZaXmJmaoqOkpaanqKmqsrO0tba3uLm6wsPExcbHyMnK0tPU1dbX2Nna4uPk5ebn6Onq8vP09fb3+Pn6/90ABAAB/9oADAMBAAIR"
|
||||
"AxEAPwDg4rP2q3FZ+1akVn7Vbis/alCZz0MYf//Q5mKz9qtxWftWpFZ+1W4rP2rohM9GhjD/0c+Kz9qK34rP2orvUz6aGM0P/9J0Vn7V"
|
||||
"bis/aiiuSDZ8pQqyP//T2IrP2q3FZ+1FFTBs82hVkf/U66Kz9qKKK1TZcKsrH//Z")
|
||||
|
||||
|
||||
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 png_exact_size(total: int) -> bytes:
|
||||
"""Корректный PNG ровно total байт: маленькая картинка + служебный блок-заполнитель (tEXt)."""
|
||||
base = png(64, 64, noise=True)
|
||||
head, iend = base[:-12], base[-12:]
|
||||
filler = total - len(base) - 12 # 12 байт — длина, тип и CRC блока-заполнителя
|
||||
check(filler >= 6, "total is too small")
|
||||
return head + _chunk(b"tEXt", b"pad\x00" + b"x" * (filler - 4)) + iend
|
||||
|
||||
|
||||
def gray_png(width: int, height: int) -> bytes:
|
||||
"""Оттенки серого, нули: 40 млн пикселей сжимаются в ~40 КБ."""
|
||||
compressor = zlib.compressobj(9)
|
||||
row = b"\x00" + bytes(width)
|
||||
data = b"".join(compressor.compress(row) for _ in range(height)) + compressor.flush()
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 0, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", ihdr) + _chunk(b"IDAT", data) + _chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def bad_filter_png() -> bytes:
|
||||
"""PNG 40×30, у 11-й строки тип фильтра 7 (допустимы 0–4)."""
|
||||
raw = b"".join(bytes([7 if y == 10 else 0]) + bytes(40 * 3) for y in range(30))
|
||||
ihdr = struct.pack(">IIBBBBB", 40, 30, 8, 2, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", ihdr) + _chunk(b"IDAT", zlib.compress(raw)) + _chunk(b"IEND", b"")
|
||||
|
||||
|
||||
# ---------- JPEG по сегментам: чтобы портить структуру точечно ----------
|
||||
|
||||
def jpeg_parts(data: bytes) -> list:
|
||||
"""JPEG -> [("seg", маркер, данные) | ("scan", заголовок SOS, сжатые данные) | ("eoi", хвост)]."""
|
||||
i, parts = 2, []
|
||||
while True:
|
||||
marker = data[i + 1]
|
||||
i += 2
|
||||
if marker == 0xD9:
|
||||
parts.append(("eoi", data[i:]))
|
||||
return parts
|
||||
length = int.from_bytes(data[i:i + 2], "big")
|
||||
payload, i = data[i + 2:i + length], i + length
|
||||
if marker != 0xDA:
|
||||
parts.append(("seg", marker, payload))
|
||||
continue
|
||||
j = i
|
||||
while data[j] != 0xFF or data[j + 1] == 0x00 or 0xD0 <= data[j + 1] <= 0xD7:
|
||||
j += 1
|
||||
parts.append(("scan", payload, data[i:j]))
|
||||
i = j
|
||||
|
||||
|
||||
def jpeg_join(parts: list) -> bytes:
|
||||
out = bytearray(b"\xff\xd8")
|
||||
for part in parts:
|
||||
if part[0] == "seg":
|
||||
out += bytes([0xFF, part[1]]) + struct.pack(">H", len(part[2]) + 2) + part[2]
|
||||
elif part[0] == "scan":
|
||||
out += b"\xff\xda" + struct.pack(">H", len(part[1]) + 2) + part[1] + part[2]
|
||||
else:
|
||||
out += b"\xff\xd9" + part[1]
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def _edit(data: bytes, kind, fn, index: int = 0) -> bytes:
|
||||
"""Поменять index-й сегмент вида kind (маркер или "scan"): fn(bytearray) -> bytes."""
|
||||
parts, seen = jpeg_parts(data), 0
|
||||
for k, part in enumerate(parts):
|
||||
hit = part[0] == "scan" if kind == "scan" else part[0] == "seg" and part[1] == kind
|
||||
if hit:
|
||||
if seen == index:
|
||||
if kind == "scan":
|
||||
parts[k] = ("scan", fn(bytearray(part[1])), part[2])
|
||||
else:
|
||||
parts[k] = ("seg", kind, fn(bytearray(part[2])))
|
||||
return jpeg_join(parts)
|
||||
seen += 1
|
||||
raise AssertionError(f"segment {kind} #{index} not found")
|
||||
|
||||
|
||||
def _set(position: int, value: int):
|
||||
def change(payload: bytearray) -> bytes:
|
||||
payload[position] = value
|
||||
return bytes(payload)
|
||||
return change
|
||||
|
||||
|
||||
def teacher_bad_sos_jpeg() -> bytes:
|
||||
"""Воспроизведение из замечания: в первом SOS (FF DA по смещению i) байт i+5 — первый
|
||||
идентификатор компонента — заменить на 250, которого нет в SOF."""
|
||||
data = bytearray(SAMPLE_JPEG)
|
||||
i = data.index(b"\xff\xda")
|
||||
data[i + 5] = 250
|
||||
return bytes(data)
|
||||
|
||||
|
||||
def broken_structure_jpegs() -> list[tuple[str, bytes]]:
|
||||
"""JPEG, которые строгий декодер worker отвергает по маркерам и заголовкам (API: 415)."""
|
||||
def drop(data, test):
|
||||
return jpeg_join([p for p in jpeg_parts(data) if not test(p)])
|
||||
|
||||
def scans(data):
|
||||
return [p for p in jpeg_parts(data) if p[0] == "scan"]
|
||||
|
||||
def swap_rst(entropy: bytes) -> bytes:
|
||||
e = bytearray(entropy)
|
||||
positions = [k for k in range(len(e) - 1) if e[k] == 0xFF and 0xD0 <= e[k + 1] <= 0xD7]
|
||||
e[positions[0] + 1], e[positions[1] + 1] = e[positions[1] + 1], e[positions[0] + 1]
|
||||
return bytes(e)
|
||||
|
||||
seq_scan = scans(SAMPLE_JPEG)[0]
|
||||
first_progressive = scans(PROGRESSIVE_JPEG)[0]
|
||||
no_jfif = drop(SAMPLE_JPEG, lambda p: p[0] == "seg" and p[1] == 0xE0)
|
||||
restart_parts = jpeg_parts(RESTART_JPEG)
|
||||
return [
|
||||
("SOS: компонент 250, которого нет в SOF (замечание к MR)", teacher_bad_sos_jpeg()),
|
||||
("SOS: один компонент дважды в скане", _edit(SAMPLE_JPEG, "scan", _set(3, 1))),
|
||||
("SOS: таблица Хаффмана DC 2 не определена", _edit(SAMPLE_JPEG, "scan", _set(2, 0x20))),
|
||||
("SOS: номер таблицы Хаффмана AC 5", _edit(SAMPLE_JPEG, "scan", _set(4, 0x05))),
|
||||
("SOS: Se=62 в последовательном JPEG", _edit(SAMPLE_JPEG, "scan", _set(-2, 62))),
|
||||
("SOS: Ah/Al не нули в последовательном JPEG", _edit(SAMPLE_JPEG, "scan", _set(-1, 0x10))),
|
||||
("SOS: 5 компонентов в скане", _edit(SAMPLE_JPEG, "scan", _set(0, 5))),
|
||||
("SOF: таблица квантования 3 не определена", _edit(SAMPLE_JPEG, 0xC0, _set(8, 3))),
|
||||
("SOF: повторяется идентификатор компонента", _edit(SAMPLE_JPEG, 0xC0, _set(9, 1))),
|
||||
("SOF: субдискретизация 1×4 (не понимает декодер)", _edit(SAMPLE_JPEG, 0xC0, _set(7, 0x14))),
|
||||
("SOF: коэффициент субдискретизации 0", _edit(SAMPLE_JPEG, 0xC0, _set(10, 0x01))),
|
||||
("SOF: 12 бит на канал", _edit(SAMPLE_JPEG, 0xC0, _set(0, 12))),
|
||||
("SOF: 2 компонента", _edit(SAMPLE_JPEG, 0xC0, lambda p: bytes(p[:5]) + b"\x02" + bytes(p[6:12]))),
|
||||
("DHT: коды не помещаются в длину (3 кода по 1 биту)",
|
||||
_edit(SAMPLE_JPEG, 0xC4, lambda p: b"\x00" + bytes([3] + [0] * 15) + b"\x00\x01\x02")),
|
||||
("DHT: символ 16 в таблице DC", _edit(SAMPLE_JPEG, 0xC4, lambda p: bytes(p[:-1]) + b"\x10")),
|
||||
("DHT: номер таблицы 4", _edit(SAMPLE_JPEG, 0xC4, _set(0, 0x04))),
|
||||
("DQT: таблица обрезана", _edit(SAMPLE_JPEG, 0xDB, lambda p: bytes(p[:-1]))),
|
||||
("сегмент с зарезервированным маркером 0xF0",
|
||||
jpeg_join([("seg", 0xF0, b"\x00\x00")] + jpeg_parts(SAMPLE_JPEG))),
|
||||
("мусорные байты между сегментами", SAMPLE_JPEG.replace(b"\xff\xdb", b"\x00\x00\xff\xdb", 1)),
|
||||
("APP0: JFIF версии 3", _edit(SAMPLE_JPEG, 0xE0, _set(5, 3))),
|
||||
("APP14: неизвестное преобразование Adobe 7",
|
||||
jpeg_join([("seg", 0xEE, b"Adobe\x00\x64\x00\x00\x00\x00\x07")] + jpeg_parts(no_jfif))),
|
||||
("второй скан после полного скана",
|
||||
jpeg_join(jpeg_parts(SAMPLE_JPEG)[:-1] + [seq_scan, ("eoi", b"")])),
|
||||
("progressive: AC-скан раньше DC-скана", drop(PROGRESSIVE_JPEG, lambda p: p is not None and p == first_progressive)),
|
||||
("progressive: Al=14", _edit(PROGRESSIVE_JPEG, "scan", _set(-1, 14))),
|
||||
("RST: маркеры RST0 и RST1 поменяны местами",
|
||||
jpeg_join([("scan", p[1], swap_rst(p[2])) if p[0] == "scan" else p for p in restart_parts])),
|
||||
("RST: маркеры есть, а интервала DRI нет", drop(RESTART_JPEG, lambda p: p[0] == "seg" and p[1] == 0xDD)),
|
||||
("RST: интервал DRI 2 вместо 1", _edit(RESTART_JPEG, 0xDD, lambda p: b"\x00\x02")),
|
||||
]
|
||||
|
||||
|
||||
def garbage_scan_jpeg() -> bytes:
|
||||
"""SAMPLE_JPEG с мусором вместо сжатых данных скана: маркеры и длины целы, данные — нет."""
|
||||
sos = SAMPLE_JPEG.index(b"\xff\xda")
|
||||
length = int.from_bytes(SAMPLE_JPEG[sos + 2:sos + 4], "big")
|
||||
noise = bytes((i * 37 + 11) % 255 for i in range(400)) # без 0xFF: маркеры не появятся
|
||||
return SAMPLE_JPEG[:sos + 2 + length] + noise + b"\xff\xd9"
|
||||
|
||||
|
||||
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 (443 if url.scheme == "https" else 80)), timeout=timeout)
|
||||
if url.scheme == "https": # с lab7: TLS с проверкой сертификата и имени (без отключения проверки)
|
||||
sock = ssl.create_default_context(cafile=CA_FILE).wrap_socket(sock, server_hostname=url.hostname)
|
||||
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]
|
||||
early_data = b""
|
||||
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"))
|
||||
step = 16 * 1024 if url.scheme == "https" else 64 * 1024
|
||||
for start in range(0, len(to_send), step):
|
||||
# Сервер уже ответил (например, 413 до конца тела)? Тогда перестаём слать и читаем ответ:
|
||||
# продолжение отправки в закрытое соединение может стереть ответ (RST).
|
||||
early = _early_reply(sock)
|
||||
if early is not None:
|
||||
early_data = early
|
||||
break
|
||||
sock.sendall(to_send[start:start + step])
|
||||
except OSError:
|
||||
pass # сервер закрыл соединение раньше — читаем то, что он успел ответить
|
||||
if abort_after is not None:
|
||||
sock.close()
|
||||
return None
|
||||
data = early_data
|
||||
try:
|
||||
while not _complete(data):
|
||||
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 _early_reply(sock) -> bytes | None:
|
||||
"""Байты ответа, если сервер уже начал отвечать, иначе None (без ожидания).
|
||||
|
||||
Для TLS select() не годится: читаемым сокет делают и служебные записи TLS 1.3 (session ticket),
|
||||
поэтому пробуем прочитать данные приложения без блокировки.
|
||||
"""
|
||||
if not hasattr(sock, "pending"):
|
||||
return b"" if select.select([sock], [], [], 0)[0] else None
|
||||
timeout = sock.gettimeout()
|
||||
sock.settimeout(0)
|
||||
try:
|
||||
return sock.recv(65536) or None
|
||||
except (ssl.SSLWantReadError, ssl.SSLWantWriteError, BlockingIOError):
|
||||
return None
|
||||
finally:
|
||||
sock.settimeout(timeout)
|
||||
|
||||
|
||||
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, ctype="image/png"):
|
||||
"""Загрузить файл; пока стенд только запускается (503) — повторять до seconds. Возвращает ответ 202."""
|
||||
path = f"/api/v1/chats/{chat['id']}/attachments?filename={name}"
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
try:
|
||||
reply = api.call("POST", path, [202, 503], actor=actor, raw=data or SAMPLE_PNG,
|
||||
headers={"Content-Type": ctype}, schema="Attachment")
|
||||
except Failure: # балансировщик без готовых реплик или обрыв соединения
|
||||
reply = {"status": 0}
|
||||
if reply["status"] == 202:
|
||||
check(reply["json"]["status"] == "queued", "upload must return a queued snapshot")
|
||||
return reply
|
||||
check(time.monotonic() < deadline, f"stand is not ready for uploads after {seconds} s")
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def wait_status(api, actor, attachment_id, statuses=("ready",), seconds=60, step=0.3):
|
||||
"""Опрашивать GET вложения, пока статус не станет одним из statuses. Возвращает Attachment."""
|
||||
deadline = time.monotonic() + seconds
|
||||
last = None
|
||||
while True:
|
||||
try:
|
||||
last = api.call("GET", f"/api/v1/attachments/{attachment_id}", actor=actor, schema="Attachment")["json"]
|
||||
if last["status"] in statuses:
|
||||
return last
|
||||
check(last["status"] != "failed" or "failed" in statuses,
|
||||
f"attachment failed with {last['error_code']}")
|
||||
except Failure as exc:
|
||||
if "attachment failed" in str(exc):
|
||||
raise
|
||||
check(time.monotonic() < deadline,
|
||||
f"attachment is {last and last['status']} after {seconds} s, expected {statuses}")
|
||||
time.sleep(step)
|
||||
|
||||
|
||||
def webp_size(data: bytes) -> tuple[int, int]:
|
||||
"""Ширина и высота WebP по заголовку RIFF (VP8, VP8L или VP8X) — без библиотек."""
|
||||
check(data[:4] == b"RIFF" and data[8:12] == b"WEBP", "not a WebP file")
|
||||
kind = data[12:16]
|
||||
if kind == b"VP8 ":
|
||||
return int.from_bytes(data[26:28], "little") & 0x3FFF, int.from_bytes(data[28:30], "little") & 0x3FFF
|
||||
if kind == b"VP8L":
|
||||
bits = int.from_bytes(data[21:25], "little")
|
||||
return (bits & 0x3FFF) + 1, ((bits >> 14) & 0x3FFF) + 1
|
||||
check(kind == b"VP8X", "unknown WebP chunk")
|
||||
return int.from_bytes(data[24:27], "little") + 1, int.from_bytes(data[27:30], "little") + 1
|
||||
|
||||
|
||||
def webp_chunks(data: bytes) -> list[bytes]:
|
||||
"""Типы блоков RIFF внутри WebP (EXIF, XMP , ICCP — метаданные)."""
|
||||
kinds, i = [], 12
|
||||
while i + 8 <= len(data):
|
||||
kinds.append(data[i:i + 4])
|
||||
i += 8 + ((int.from_bytes(data[i + 4:i + 8], "little") + 1) & ~1)
|
||||
return kinds
|
||||
|
||||
|
||||
def jpeg_markers(data: bytes) -> list[int]:
|
||||
"""Маркеры JPEG до начала скана: по ним видно, есть ли EXIF (APP1) или ICC (APP2)."""
|
||||
found, i = [], 2
|
||||
while i + 4 <= len(data) and data[i] == 0xFF:
|
||||
marker = data[i + 1]
|
||||
found.append(marker)
|
||||
if marker == 0xDA:
|
||||
break
|
||||
i += 2 + int.from_bytes(data[i + 2:i + 4], "big")
|
||||
return found
|
||||
|
||||
|
||||
# ---------- внутри стенда ----------
|
||||
|
||||
def in_api(code: str) -> str:
|
||||
"""Выполнить Python-код в контейнере API (сеть backend, модули messenger). Возвращает stdout.
|
||||
|
||||
С lab7 секретов в файлах контейнера нет: код сначала входит в OpenBao identity api
|
||||
и получает только её секреты — проверка видит ровно права API.
|
||||
"""
|
||||
prelude = "from messenger import secretsource\nsecretsource.load()\n"
|
||||
result = subprocess.run(["docker", "compose", "exec", "-T", "api", "python", "-"], cwd=ROOT,
|
||||
input=(prelude + 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 внутри контейнера worker -> словарь счётчиков.
|
||||
|
||||
С lab7 — в worker: список объектов bucket разрешён только ключам worker (уборщик работает там же).
|
||||
"""
|
||||
result = subprocess.run(["docker", "compose", "exec", "-T", "worker", "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,188 @@
|
||||
"""lab6, уровень 4, инцидент 2: медленная / недоступная БД и чем она отличается от медленного обработчика.
|
||||
|
||||
make incident-db (= python student-tests/incident_db.py) ~6 минут
|
||||
make incident-db-down (= python student-tests/incident_db.py --down) ещё ~5 минут
|
||||
|
||||
A. Медленный HTTP handler при здоровой БД (точка api_slow_handler = 1.5 с в обеих репликах):
|
||||
трасса — server span ~1.5 с, а SQL-спаны внутри по миллисекунде («пустое» время — код обработчика);
|
||||
метрики — растёт p95 маршрута, 5xx нет, пул БД свободен.
|
||||
B. Медленная БД: отдельная сессия держит LOCK TABLE messages (как долгая миграция или забытая
|
||||
транзакция). POST сообщения ждёт блокировку до statement_timeout (5 с) -> 503. Трасса — server span
|
||||
~5 с и SQL INSERT ~5 с со статусом ERROR; метрики — 5xx у приложения и на входе, заняты соединения пула.
|
||||
Alert HighErrorRate -> firing; блокировка снята -> resolved.
|
||||
C. (--down) БД недоступна: docker compose pause postgres. Реплики не проходят /health/ready, HAProxy сам
|
||||
отвечает 503: 5xx есть только на входе, у приложения запросов нет совсем. HighErrorRate firing -> unpause -> resolved.
|
||||
Выводы — для evidence/incident-db*.txt и REPORT.md. Токены не печатаются.
|
||||
"""
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
import obs
|
||||
import ops
|
||||
from helpers import ROOT, Client, check, idempotency, run
|
||||
from traffic import Traffic
|
||||
|
||||
ROUTE = 'http_route="/api/v1/chats/{chat_id}/messages"'
|
||||
P95_ROUTE = ('histogram_quantile(0.95, sum by (le) (rate(http_server_request_duration_seconds_bucket'
|
||||
f'{{job="messenger-api",{ROUTE}}}[1m])))')
|
||||
APP_5XX = ('sum(rate(http_server_request_duration_seconds_count{job="messenger-api",http_response_status_code=~"5.."}[1m]))'
|
||||
' or vector(0)')
|
||||
APP_RPS = 'sum(rate(http_server_request_duration_seconds_count{job="messenger-api"}[1m])) or vector(0)'
|
||||
EDGE = "messenger:edge_error_ratio:rate2m"
|
||||
POOL_USED = 'sum(db_client_connection_count{db_client_connection_pool_name="messenger-api",db_client_connection_state="used"})'
|
||||
POOL_WAIT = 'sum(db_client_connection_pending_requests{db_client_connection_pool_name="messenger-api"})'
|
||||
READY = 'haproxy_backend_active_servers{proxy="api"}'
|
||||
LOCK_TAG = "lab6-incident-db-lock"
|
||||
|
||||
|
||||
def val(query):
|
||||
v = obs.prom_value(query)
|
||||
return "—" if v is None else f"{v:.3f}".rstrip("0").rstrip(".")
|
||||
|
||||
|
||||
def snapshot(started, traffic):
|
||||
state = obs.alerts().get("HighErrorRate", "inactive")
|
||||
print(f" t={time.monotonic() - started:5.0f}s edge_5xx_ratio={val(EDGE):>6} app_5xx/s={val(APP_5XX):>6} "
|
||||
f"app_rps={val(APP_RPS):>6} p95_messages={val(P95_ROUTE):>6}s pool_used={val(POOL_USED):>3} "
|
||||
f"pool_waiting={val(POOL_WAIT):>3} ready_replicas={val(READY):>2} HighErrorRate={state:<8} http={traffic.snapshot()}")
|
||||
return state
|
||||
|
||||
|
||||
def wait_state(started, traffic, want, seconds):
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
state = snapshot(started, traffic)
|
||||
if state in want:
|
||||
return time.monotonic() - started
|
||||
check(time.monotonic() < deadline, f"HighErrorRate {want} not reached in {seconds} s")
|
||||
time.sleep(15)
|
||||
|
||||
|
||||
def traced(api, actor, chat, expected):
|
||||
"""POST сообщения -> (код, X-Request-Id, trace_id, спаны) через лог в Loki."""
|
||||
response = api.call("POST", f"/api/v1/chats/{chat['id']}/messages", expected, actor=actor,
|
||||
headers=idempotency(), body={"text": "диагностика"})
|
||||
request_id = response["headers"]["X-Request-Id"]
|
||||
entry = obs.wait_logs(f'{{service_name="messenger-api"}} | request_id="{request_id}"')[-1]["labels"]
|
||||
trace_id = entry["trace_id"]
|
||||
time.sleep(4)
|
||||
return response["status"], request_id, entry, trace_id, obs.tempo_trace(trace_id)
|
||||
|
||||
|
||||
def describe(spans):
|
||||
server = [s for s in spans if s["kind"] == "SERVER"][0]
|
||||
sql = [s for s in spans if s["attrs"].get("db.system") == "postgresql"]
|
||||
total = (server["end"] - server["start"]) / 1e6
|
||||
in_sql = sum((s["end"] - s["start"]) / 1e6 for s in sql)
|
||||
slowest = max(sql, key=lambda s: s["end"] - s["start"]) if sql else None
|
||||
return total, in_sql, slowest
|
||||
|
||||
|
||||
def phase_slow_handler(api, alice, chat):
|
||||
print("A. slow HTTP handler, healthy DB (fault api_slow_handler=1.5 s in every api replica)")
|
||||
ops.arm("api", "api_slow_handler", "1.5")
|
||||
try:
|
||||
for _ in range(6):
|
||||
api.message(alice, chat, "медленный обработчик")
|
||||
status, request_id, entry, trace_id, spans = traced(api, alice, chat, 201)
|
||||
finally:
|
||||
ops.disarm("api", "api_slow_handler")
|
||||
total, in_sql, slowest = describe(spans)
|
||||
print(f" request {request_id} -> {status}; log event={entry['event']} severity={entry['severity_text']}; trace {trace_id}")
|
||||
for line in obs.tree(spans):
|
||||
print(" " + line)
|
||||
time.sleep(12)
|
||||
print(f" server span {total:.0f} ms, of it in SQL {in_sql:.1f} ms (slowest SQL {slowest['name']} "
|
||||
f"{(slowest['end'] - slowest['start']) / 1e6:.1f} ms): the time is spent in the handler, not in the DB")
|
||||
print(f" metrics: p95 POST messages = {val(P95_ROUTE)} s, app 5xx/s = {val(APP_5XX)}, pool waiting = {val(POOL_WAIT)}")
|
||||
check(total > 1400 and in_sql < 300, "slow handler: long server span with short SQL spans expected")
|
||||
return total, in_sql
|
||||
|
||||
|
||||
def phase_slow_db(api, alice, bob, chat):
|
||||
print("B. slow DB: a session holds LOCK TABLE messages; POST message waits until statement_timeout (5 s) -> 503")
|
||||
check(obs.alerts().get("HighErrorRate") is None, "HighErrorRate must be inactive before the incident")
|
||||
traffic = Traffic(api, bob, chat, threads=3, pause=0.2, timeout=20).start()
|
||||
started = time.monotonic()
|
||||
lock = None
|
||||
try:
|
||||
time.sleep(20)
|
||||
snapshot(started, traffic)
|
||||
sql = (f"/* {LOCK_TAG} */ BEGIN; LOCK TABLE messages IN ACCESS EXCLUSIVE MODE; SELECT pg_sleep(600); COMMIT;")
|
||||
lock = subprocess.Popen(["docker", "compose", "exec", "-T", "postgres", "psql", "-X", "-q", "-U", "messenger",
|
||||
"-d", "messenger", "-c", sql], cwd=ROOT, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
locked_at = time.monotonic() - started
|
||||
print(f" t={locked_at:.0f}s lock taken")
|
||||
time.sleep(8)
|
||||
status, request_id, entry, trace_id, spans = traced(api, alice, chat, 503)
|
||||
total, in_sql, slowest = describe(spans)
|
||||
print(f" request {request_id} -> {status}; log event={entry['event']} severity={entry['severity_text']}; trace {trace_id}")
|
||||
for line in obs.tree(spans):
|
||||
print(" " + line)
|
||||
print(f" server span {total:.0f} ms, of it in SQL {in_sql:.0f} ms; slowest SQL {slowest['name']} "
|
||||
f"{(slowest['end'] - slowest['start']) / 1e6:.0f} ms status {slowest['status']}: the DB is slow")
|
||||
check(slowest["status"] == "ERROR" and (slowest["end"] - slowest["start"]) / 1e6 > 4000,
|
||||
"slow DB: a long SQL span with an error expected")
|
||||
firing_at = wait_state(started, traffic, ("firing",), 300)
|
||||
print(f" HighErrorRate FIRING at t={firing_at:.0f}s ({firing_at - locked_at:.0f} s after the lock)")
|
||||
finally:
|
||||
ops.psql(f"SELECT count(pg_cancel_backend(pid)) FROM pg_stat_activity WHERE query LIKE '%{LOCK_TAG}%' "
|
||||
"AND pid <> pg_backend_pid()")
|
||||
if lock is not None:
|
||||
lock.wait(timeout=30)
|
||||
released_at = time.monotonic() - started
|
||||
print(f" t={released_at:.0f}s lock released (pg_cancel_backend)")
|
||||
resolved_at = wait_state(started, traffic, ("inactive",), 300)
|
||||
traffic.stop()
|
||||
print(f" HighErrorRate RESOLVED at t={resolved_at:.0f}s ({resolved_at - released_at:.0f} s after the release); "
|
||||
f"http codes: {traffic.snapshot()}")
|
||||
return total, in_sql, firing_at - locked_at, resolved_at - released_at
|
||||
|
||||
|
||||
def phase_db_down(api, bob, chat):
|
||||
print("C. DB unavailable: docker compose pause postgres")
|
||||
check(obs.alerts().get("HighErrorRate") is None, "HighErrorRate must be inactive before the incident")
|
||||
traffic = Traffic(api, bob, chat, threads=3, pause=0.2, timeout=20).start()
|
||||
started = time.monotonic()
|
||||
try:
|
||||
time.sleep(20)
|
||||
snapshot(started, traffic)
|
||||
ops.compose("pause", "postgres")
|
||||
paused_at = time.monotonic() - started
|
||||
print(f" t={paused_at:.0f}s postgres paused")
|
||||
firing_at = wait_state(started, traffic, ("firing",), 300)
|
||||
print(f" HighErrorRate FIRING at t={firing_at:.0f}s; ready replicas {val(READY)}, app requests/s {val(APP_RPS)}: "
|
||||
"503 comes from HAProxy itself — no replica passes /health/ready (PostgreSQL)")
|
||||
logs = obs.loki('{service_name="messenger-api"} | event="http.request" | http_route="/health/ready"', minutes=5)
|
||||
print(f" logs: {len(logs)} failed /health/ready checks in 5 min, e.g. "
|
||||
f"{logs[-1]['line'][:90] if logs else '—'}")
|
||||
finally:
|
||||
ops.compose("unpause", "postgres")
|
||||
unpaused_at = time.monotonic() - started
|
||||
print(f" t={unpaused_at:.0f}s postgres unpaused")
|
||||
resolved_at = wait_state(started, traffic, ("inactive",), 300)
|
||||
traffic.stop()
|
||||
print(f" HighErrorRate RESOLVED at t={resolved_at:.0f}s ({resolved_at - unpaused_at:.0f} s after unpause); "
|
||||
f"http codes: {traffic.snapshot()}")
|
||||
|
||||
|
||||
def main():
|
||||
api = Client(timeout=20)
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
if "--down" in sys.argv:
|
||||
phase_db_down(api, bob, chat)
|
||||
print("PASS: DB unavailable -> 5xx only at the entry (HAProxy), HighErrorRate firing -> resolved")
|
||||
return
|
||||
handler_total, handler_sql = phase_slow_handler(api, alice, chat)
|
||||
db_total, db_sql, fire, resolve = phase_slow_db(api, alice, bob, chat)
|
||||
print("Summary: how to tell them apart")
|
||||
print(f" slow handler: server span {handler_total:.0f} ms, SQL {handler_sql:.0f} ms, no 5xx, pool free")
|
||||
print(f" slow DB: server span {db_total:.0f} ms, SQL {db_sql:.0f} ms (ERROR, statement timeout), 5xx, "
|
||||
f"pool connections busy; HighErrorRate firing in {fire:.0f} s, resolved {resolve:.0f} s after the fix")
|
||||
print("PASS: slow DB vs slow handler distinguished by trace (time in SQL spans) and metrics (5xx, pool); "
|
||||
"HighErrorRate firing -> resolved")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,106 @@
|
||||
"""lab6, уровень 4, инцидент 1: worker остановлен -> растёт возраст задач -> QueueLagHigh firing -> resolved.
|
||||
|
||||
make incident-worker (= python student-tests/incident_worker.py)
|
||||
|
||||
Сценарий (около 5 минут):
|
||||
1. фон: сообщения (3 потока) и загрузка картинки раз в 5 с; базовая линия метрик;
|
||||
2. docker compose stop worker; загрузки продолжают получать 202, задания копятся;
|
||||
3. каждые 15 с — снимок: глубина очереди, возраст старейшего задания, доставки worker в секунду,
|
||||
состояние alert QueueLagHigh; ждём firing (порог 60 с, for 1m);
|
||||
4. docker compose start worker; backlog уменьшается до 0, все загрузки — ready; ждём resolved;
|
||||
5. диагностика «только по сохранённым наблюдениям»: что видно в метриках, логах и трассе одной
|
||||
загрузки, сделанной во время отказа (разрыв между send и process).
|
||||
Вывод — таймлайн для evidence/incident-worker.txt и REPORT.md. Токены не печатаются.
|
||||
"""
|
||||
import time
|
||||
|
||||
import obs
|
||||
import ops
|
||||
from filegen import wait_status
|
||||
from helpers import Client, check, run
|
||||
from traffic import Traffic
|
||||
|
||||
Q_DEPTH = 'max(messenger_queue_depth{job="messenger-api",state="ready"})'
|
||||
Q_AGE = 'max(messenger_queue_oldest_age_seconds{job="messenger-api"})'
|
||||
DELIVERIES = 'sum(rate(messenger_jobs_processed_total[1m]))'
|
||||
BUSY = 'sum(messenger_worker_busy) / sum(messenger_worker_capacity)'
|
||||
|
||||
|
||||
def snapshot(started, traffic, note=""):
|
||||
def val(query):
|
||||
v = obs.prom_value(query)
|
||||
return "—" if v is None else f"{v:.2f}".rstrip("0").rstrip(".")
|
||||
state = obs.alerts().get("QueueLagHigh", "inactive")
|
||||
print(f" t={time.monotonic() - started:5.0f}s ready={val(Q_DEPTH):>4} oldest_age={val(Q_AGE):>6}s "
|
||||
f"worker_deliveries/s={val(DELIVERIES):>5} worker_busy={val(BUSY):>4} QueueLagHigh={state:<8} "
|
||||
f"http={traffic.snapshot()} {note}")
|
||||
return state
|
||||
|
||||
|
||||
def wait_state(started, traffic, predicate, seconds, what):
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
state = snapshot(started, traffic)
|
||||
if predicate(state):
|
||||
return time.monotonic() - started
|
||||
check(time.monotonic() < deadline, f"{what} not reached in {seconds} s")
|
||||
time.sleep(15)
|
||||
|
||||
|
||||
def main():
|
||||
api = Client(timeout=20)
|
||||
ops.wait_healthy("worker", 1)
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
check(obs.alerts().get("QueueLagHigh") is None, "QueueLagHigh must be inactive before the incident")
|
||||
traffic = Traffic(api, alice, chat, threads=3, pause=0.3, uploads_every=5).start()
|
||||
started = time.monotonic()
|
||||
try:
|
||||
print("1. baseline (worker running):")
|
||||
time.sleep(15)
|
||||
snapshot(started, traffic)
|
||||
ops.stop("worker")
|
||||
stopped_at = time.monotonic() - started
|
||||
print(f"2. t={stopped_at:.0f}s docker compose stop worker; uploads continue")
|
||||
pending_at = wait_state(started, traffic, lambda s: s in ("pending", "firing"), 240, "QueueLagHigh pending")
|
||||
firing_at = wait_state(started, traffic, lambda s: s == "firing", 180, "QueueLagHigh firing")
|
||||
print(f"3. QueueLagHigh pending at t={pending_at:.0f}s, FIRING at t={firing_at:.0f}s "
|
||||
f"({firing_at - stopped_at:.0f} s after the worker stopped)")
|
||||
during = list(traffic.uploads)
|
||||
finally:
|
||||
ops.start("worker")
|
||||
started_at = time.monotonic() - started
|
||||
print(f"4. t={started_at:.0f}s docker compose start worker")
|
||||
ops.wait_healthy("worker", 1)
|
||||
resolved_at = wait_state(started, traffic, lambda s: s == "inactive", 240, "QueueLagHigh resolved")
|
||||
traffic.stop()
|
||||
print(f" QueueLagHigh RESOLVED at t={resolved_at:.0f}s ({resolved_at - started_at:.0f} s after the worker started)")
|
||||
uploads = traffic.uploads
|
||||
for attachment_id, _ in uploads:
|
||||
wait_status(api, bob, attachment_id, ("ready",), seconds=120)
|
||||
print(f" all {len(uploads)} uploads of the run are ready (none lost); final http codes: {traffic.snapshot()}")
|
||||
|
||||
# Диагностика по сохранённым наблюдениям.
|
||||
print("5. diagnosis from stored telemetry:")
|
||||
rows = obs.prom(f'max_over_time({Q_AGE}[10m:15s])')
|
||||
print(f" metrics: max oldest_age over 10 min = {rows[0]['value']:.0f} s; worker deliveries/s fell to 0 "
|
||||
"while API kept answering 2xx — the queue is not drained, the API is healthy")
|
||||
stop_logs = obs.loki('{service_name="messenger-worker"} | event=~"worker.stopped|worker.started"', minutes=15)
|
||||
print(" logs: " + "; ".join(f"{e['labels'].get('event')} ({e['labels'].get('service_instance_id')})"
|
||||
for e in stop_logs[-4:]))
|
||||
victim = during[len(during) // 2][0] if during else uploads[0][0]
|
||||
trace_id, spans = obs.wait_trace(f'{{ span.messenger.attachment.id = "{victim}" && kind = server }}',
|
||||
lambda s: any(x["attrs"].get("messenger.job.outcome") == "ready" for x in s), 90)
|
||||
send = [s for s in spans if s["kind"] == "PRODUCER"][0]
|
||||
consume = [s for s in spans if s["kind"] == "CONSUMER"][0]
|
||||
gap = (consume["start"] - send["end"]) / 1e9
|
||||
print(f" trace {trace_id} of upload {victim} made during the outage: send -> process gap {gap:.0f} s "
|
||||
f"(message waited in the queue), processing itself {(consume['end'] - consume['start']) / 1e9:.2f} s")
|
||||
for line in obs.tree([s for s in spans if not (s["kind"] == "CLIENT" and "rpc.method" not in s["attrs"])]):
|
||||
print(" " + line)
|
||||
check(gap > 30, "the trace must show the waiting time in the queue")
|
||||
print(f"PASS: worker stopped -> oldest job age grew -> QueueLagHigh firing in {firing_at - stopped_at:.0f} s; "
|
||||
f"worker started -> backlog drained, alert resolved in {resolved_at - started_at:.0f} s; no uploads lost")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,96 @@
|
||||
"""lab5, уровень 4: lease для зависшего processing — как отличить зависший worker от долго работающего.
|
||||
|
||||
make lease (= python student-tests/lease_takeover.py)
|
||||
|
||||
1. Долгая задача: точка worker_slow=35 — обработка «идёт» 35 с. Пока worker жив, он продлевает
|
||||
lease каждые JOB_HEARTBEAT_SECONDS (10 с): lease_until в БД сдвигается вперёд. Задание никто
|
||||
не забирает, хотя оно дольше JOB_LEASE_SECONDS (30 с).
|
||||
2. Зависание: запускается второй worker B (docker compose up --scale worker=2), затем контейнер
|
||||
worker A замораживается (docker pause) — процесс есть, но ничего не делает, как при зависании.
|
||||
Продлений нет, lease истекает. Проверка lease в B видит истёкшую аренду, засчитывает попытку
|
||||
как неудачную и назначает следующую. B обрабатывает задание -> ready (попытка 2).
|
||||
3. «Оживший» A: после docker unpause он пытается продлить lease, но жетон уже не его —
|
||||
обработка прерывается, результат не записывается (fencing). В БД ровно один ready и один
|
||||
набор вариантов, автор результата — B.
|
||||
Неконтролируемых дублей нет: одновременно задание держит только владелец действующего lease,
|
||||
а записать результат может только владелец текущего жетона.
|
||||
"""
|
||||
import time
|
||||
|
||||
import ops
|
||||
from filegen import upload_when_ready, wait_status
|
||||
from helpers import Client, check, run
|
||||
|
||||
|
||||
def main():
|
||||
api = Client(timeout=15)
|
||||
ops.scale("worker", 1)
|
||||
worker_a = ops.wait_healthy("worker", 1)[0]
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
paused = False
|
||||
try:
|
||||
ops.arm("worker", "worker_slow", "35", container=worker_a)
|
||||
att = upload_when_ready(api, alice, chat, name="lease.png")["json"]
|
||||
wait_status(api, bob, att["id"], ("processing",), seconds=30, step=0.2)
|
||||
leases = []
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
value = ops.job(att["id"])["job"]["lease_until"]
|
||||
if value and value not in leases:
|
||||
leases.append(value)
|
||||
if len(leases) >= 3:
|
||||
break
|
||||
time.sleep(1)
|
||||
check(len(leases) >= 3, f"the lease was not renewed while the job was running: {leases}")
|
||||
owner = ops.job(att["id"])["job"]["lease_owner"]
|
||||
print(f"1. long job (35 s > lease 30 s) on {owner}: lease_until moved forward "
|
||||
f"{len(leases) - 1} times: {' -> '.join(v[11:19] for v in leases)}")
|
||||
|
||||
ops.scale("worker", 2)
|
||||
ops.wait_healthy("worker", 2)
|
||||
worker_b = [c for c in ops.containers("worker") if c != worker_a][0]
|
||||
print(f"2. worker B {worker_b[:12]} started (the job is still held by A's lease)")
|
||||
ops.pause(worker_a)
|
||||
paused = True
|
||||
frozen_at = time.monotonic()
|
||||
print(f" worker A {worker_a[:12]} frozen (docker pause): no more renewals")
|
||||
ready = wait_status(api, bob, att["id"], seconds=120)
|
||||
job = ops.job(att["id"])
|
||||
took = time.monotonic() - frozen_at
|
||||
winner = [e for e in job["events"] if e["event"] == "ready"]
|
||||
check(job["job"]["attempt"] == 2 and len(winner) == 1, "expected exactly one result at attempt 2")
|
||||
check(not winner[0]["actor"].endswith(owner), "the frozen worker must not be the one who committed")
|
||||
print(f" lease expired -> attempt 2 -> ready {took:.0f} s after the freeze; result committed by "
|
||||
f"{winner[0]['actor']}")
|
||||
print(" events: " + " -> ".join(f"{e['event']}({e['attempt']})" for e in job["events"]))
|
||||
|
||||
ops.unpause(worker_a)
|
||||
paused = False
|
||||
deadline = time.monotonic() + 40
|
||||
lost = []
|
||||
while not lost:
|
||||
lines = [line for line in ops.logs("worker", "5m").splitlines() if job["job"]["job_id"] in line]
|
||||
lost = [line for line in lines if "не продлён" in line or "брошена" in line]
|
||||
if not lost:
|
||||
check(time.monotonic() < deadline, "the woken worker A did not notice that its lease was lost")
|
||||
time.sleep(2)
|
||||
after = ops.job(att["id"])
|
||||
check(after["attachment_status"] == "ready" and after["job"]["attempt"] == 2, "state changed after unpause")
|
||||
check(sum(e["event"] == "ready" for e in after["events"]) == 1 and len(after["variants"]) == 3,
|
||||
"the stale worker wrote a second result")
|
||||
meta = api.call("GET", f"/api/v1/attachments/{att['id']}", actor=bob, schema="Attachment")["json"]
|
||||
check(meta == ready, "metadata changed after the stale worker woke up")
|
||||
print("3. worker A unpaused: " + lost[-1].split(": ", 1)[-1])
|
||||
print(" still exactly one result: status ready, attempt 2, 3 variant rows, metadata unchanged")
|
||||
finally:
|
||||
if paused:
|
||||
ops.unpause(worker_a)
|
||||
ops.disarm("worker", "worker_slow")
|
||||
ops.scale("worker", 1)
|
||||
ops.wait_healthy("worker", 1)
|
||||
print("PASS: a running worker keeps its lease by renewing it; a frozen one loses it, the job moves to another "
|
||||
"worker, and the stale worker cannot overwrite the result (fencing token)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -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,125 @@
|
||||
"""Общее для tls_matrix.py и acl_matrix.py: пути к сертификатам, TLS-контексты, вход в OpenBao, таблица.
|
||||
|
||||
Оба скрипта выполняются в контейнере sectest (make tls-matrix / make acl-matrix): он в сетях
|
||||
edge, backend, otlp, telemetry, vault и видит сертификаты только на чтение:
|
||||
/pki/tls/<identity>/tls.{crt,key} сертификаты сервисов (наш CA)
|
||||
/pki/tls/ca/ca.crt наш CA
|
||||
/pki/test/intruder наш CA, но identity, которой нет в матрице
|
||||
/pki/test/rogue-lb identity "lb", но выдан ЧУЖИМ CA
|
||||
/pki/test/lb-expired identity "lb" нашего CA, срок истёк
|
||||
Хост-утилит (docker, psql) здесь нет: всё проверяется по сети, как это видит любой сервис стенда.
|
||||
Значения секретов не печатаются никогда — только «есть / нет / разрешено / запрещено».
|
||||
"""
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import sys
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
PKI = Path(os.environ.get("PKI_DIR", "/pki"))
|
||||
CA = str(PKI / "tls" / "ca" / "ca.crt")
|
||||
ROGUE_CA = str(PKI / "test" / "rogue-ca" / "ca.crt")
|
||||
BAO = "https://openbao:8200"
|
||||
|
||||
|
||||
def cert(identity: str) -> tuple[str, str]:
|
||||
"""(cert, key) identity: сервисы — из /pki/tls, тестовые intruder/rogue-lb/lb-expired — из /pki/test."""
|
||||
base = PKI / ("test" if identity in ("intruder", "rogue-lb", "lb-expired") else "tls") / identity
|
||||
return str(base / "tls.crt"), str(base / "tls.key")
|
||||
|
||||
|
||||
def client_context(identity: str | None = None, cafile: str = CA, hostname: bool = True) -> ssl.SSLContext:
|
||||
"""Клиентский TLS: сервер проверяется нашим CA (и по имени), клиент предъявляет identity (если задана)."""
|
||||
context = ssl.create_default_context(cafile=cafile)
|
||||
context.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
context.check_hostname = hostname
|
||||
if identity:
|
||||
context.load_cert_chain(*cert(identity))
|
||||
return context
|
||||
|
||||
|
||||
class Matrix:
|
||||
"""Строки «кто -> куда: действие | ожидание | результат». В конце — итог и код выхода."""
|
||||
|
||||
def __init__(self, title: str):
|
||||
self.title, self.rows, self.failed = title, 0, []
|
||||
print(title)
|
||||
print("=" * len(title))
|
||||
|
||||
def section(self, name: str):
|
||||
print(f"\n## {name}")
|
||||
|
||||
def row(self, who: str, what: str, expect: str, got: str, ok: bool):
|
||||
self.rows += 1
|
||||
mark = "OK " if ok else "FAIL"
|
||||
print(f"{mark} {who:<16} {what:<52} expect {expect:<8} got {got}")
|
||||
if not ok:
|
||||
self.failed.append(f"{who}: {what} (expect {expect}, got {got})")
|
||||
|
||||
def allow(self, who: str, what: str, outcome: tuple[bool, str]):
|
||||
self.row(who, what, "allow", outcome[1], outcome[0])
|
||||
|
||||
def deny(self, who: str, what: str, outcome: tuple[bool, str]):
|
||||
"""outcome = (allowed?, подробность). Для deny успех — когда НЕ разрешено."""
|
||||
self.row(who, what, "deny", outcome[1], not outcome[0])
|
||||
|
||||
def finish(self) -> int:
|
||||
print()
|
||||
if self.failed:
|
||||
print(f"FAIL: {len(self.failed)} of {self.rows} checks")
|
||||
for line in self.failed:
|
||||
print(" - " + line)
|
||||
return 1
|
||||
print(f"PASS: {self.rows} checks")
|
||||
return 0
|
||||
|
||||
|
||||
def bao_call(method: str, path: str, identity: str | None = None, token: str | None = None,
|
||||
body: dict | None = None, cafile: str = CA) -> tuple[int, dict]:
|
||||
"""HTTP к OpenBao. Возвращает (status, json). Ошибку TLS-рукопожатия пробрасывает как ssl.SSLError."""
|
||||
request = urllib.request.Request(f"{BAO}/v1/{path}", method=method,
|
||||
data=None if body is None else json.dumps(body).encode())
|
||||
request.add_header("Content-Type", "application/json")
|
||||
if token:
|
||||
request.add_header("X-Vault-Token", token)
|
||||
try:
|
||||
with urllib.request.urlopen(request, context=client_context(identity, cafile), timeout=10) as response:
|
||||
raw, status = response.read(), response.status
|
||||
except urllib.error.HTTPError as exc:
|
||||
raw, status = exc.read(), exc.code
|
||||
except urllib.error.URLError as exc:
|
||||
if isinstance(exc.reason, ssl.SSLError):
|
||||
raise exc.reason from None
|
||||
raise
|
||||
try:
|
||||
return status, json.loads(raw or b"{}")
|
||||
except ValueError:
|
||||
return status, {}
|
||||
|
||||
|
||||
def bao_login(identity: str, role: str) -> tuple[int, dict]:
|
||||
"""POST auth/cert/login {"name": role} с сертификатом identity."""
|
||||
return bao_call("POST", "auth/cert/login", identity=identity, body={"name": role})
|
||||
|
||||
|
||||
def bao_secret(identity: str) -> dict:
|
||||
"""Секрет своей роли (api -> messenger-api, worker -> messenger-worker): нужен для проверок БД/S3/Valkey."""
|
||||
status, payload = bao_login(identity, f"messenger-{identity}")
|
||||
if status != 200:
|
||||
sys.exit(f"cannot log in to OpenBao as {identity}: HTTP {status} (is OpenBao unsealed? make bao-unseal)")
|
||||
token = payload["auth"]["client_token"]
|
||||
status, payload = bao_call("GET", f"secret/data/messenger/{identity}", token=token)
|
||||
if status != 200:
|
||||
sys.exit(f"cannot read the secret of {identity}: HTTP {status}")
|
||||
return payload["data"]["data"]
|
||||
|
||||
|
||||
def short(exc: BaseException) -> str:
|
||||
"""Короткое имя ошибки без значений (в тексте исключений драйверов бывает DSN)."""
|
||||
text = str(exc).strip().splitlines()[0] if str(exc).strip() else ""
|
||||
for word in ("password", "secret"):
|
||||
if word in text.lower():
|
||||
text = ""
|
||||
return f"{type(exc).__name__}{': ' + text[:70] if text else ''}"
|
||||
@@ -0,0 +1,217 @@
|
||||
"""lab6: запросы к хранилищам телеметрии для собственных проверок (только стандартная библиотека).
|
||||
|
||||
С lab7 ни Prometheus, ни Loki, ни Tempo наружу не опубликованы (у всех mTLS с allowlist identity):
|
||||
все запросы идут через Grafana — https://127.0.0.1:3000 (сертификат проверяется CA стенда, CA_FILE),
|
||||
прокси источника данных /api/datasources/proxy/uid/<uid>/... Grafana ходит к хранилищам своим
|
||||
сертификатом identity grafana.
|
||||
Пароль администратора Grafana читается из secrets/grafana_admin_password и не печатается.
|
||||
Адреса можно переопределить: PROM_URL, GRAFANA_URL, LOKI_URL, TEMPO_URL (прямой адрес без Grafana).
|
||||
"""
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import ssl
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
|
||||
from helpers import ROOT, check
|
||||
|
||||
PROM_URL = os.environ.get("PROM_URL", "").rstrip("/") # пусто = через Grafana
|
||||
GRAFANA_URL = os.environ.get("GRAFANA_URL", "https://127.0.0.1:3000").rstrip("/")
|
||||
CA_FILE = os.environ.get("CA_FILE") or str(ROOT / "secrets" / "tls" / "ca" / "ca.crt")
|
||||
_TLS = ssl.create_default_context(cafile=CA_FILE)
|
||||
LOKI_URL = os.environ.get("LOKI_URL", "").rstrip("/")
|
||||
TEMPO_URL = os.environ.get("TEMPO_URL", "").rstrip("/")
|
||||
|
||||
|
||||
def _grafana_auth() -> str:
|
||||
path = ROOT / "secrets" / "grafana_admin_password"
|
||||
check(path.exists(), "secrets/grafana_admin_password not found: run sh scripts/init-secrets.sh")
|
||||
password = path.read_text(encoding="utf-8").strip()
|
||||
return "Basic " + base64.b64encode(f"admin:{password}".encode()).decode()
|
||||
|
||||
|
||||
def get_json(url: str, auth: str | None = None, timeout: float = 15.0):
|
||||
request = urllib.request.Request(url, headers={"Authorization": auth} if auth else {})
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=timeout, context=_TLS) as response:
|
||||
return json.loads(response.read() or b"null")
|
||||
except urllib.error.HTTPError as exc:
|
||||
body = exc.read()[:300].decode("utf-8", "replace")
|
||||
raise RuntimeError(f"HTTP {exc.code} from {url.split('?')[0]}: {body}") from None
|
||||
|
||||
|
||||
def grafana(path: str):
|
||||
return get_json(GRAFANA_URL + path, _grafana_auth())
|
||||
|
||||
|
||||
def _via(direct: str, uid: str) -> tuple[str, str | None]:
|
||||
if direct:
|
||||
return direct, None
|
||||
return f"{GRAFANA_URL}/api/datasources/proxy/uid/{uid}", _grafana_auth()
|
||||
|
||||
|
||||
# ---------- Prometheus ----------
|
||||
|
||||
def prom(query: str, at: float | None = None) -> list[dict]:
|
||||
"""Instant query (сейчас или на момент at, unix-время) -> [{'metric': {...}, 'value': float}]."""
|
||||
params = {"query": query} | ({"time": f"{at:.3f}"} if at else {})
|
||||
base, auth = _via(PROM_URL, "prometheus")
|
||||
data = get_json(base + "/api/v1/query?" + urllib.parse.urlencode(params), auth)
|
||||
check(data["status"] == "success", f"prometheus: {data}")
|
||||
result = data["data"]["result"]
|
||||
if data["data"]["resultType"] == "scalar":
|
||||
return [{"metric": {}, "value": float(result[1])}]
|
||||
return [{"metric": r["metric"], "value": float(r["value"][1])} for r in result]
|
||||
|
||||
|
||||
def prom_value(query: str, default: float | None = None, at: float | None = None) -> float | None:
|
||||
rows = prom(query, at)
|
||||
return rows[0]["value"] if rows else default
|
||||
|
||||
|
||||
def alerts() -> dict:
|
||||
"""{alertname: 'pending'|'firing'} — активные alerts Prometheus."""
|
||||
base, auth = _via(PROM_URL, "prometheus")
|
||||
data = get_json(base + "/api/v1/alerts", auth)
|
||||
return {a["labels"]["alertname"]: a["state"] for a in data["data"]["alerts"]}
|
||||
|
||||
|
||||
def rules() -> list[dict]:
|
||||
base, auth = _via(PROM_URL, "prometheus")
|
||||
data = get_json(base + "/api/v1/rules", auth)
|
||||
return [r for g in data["data"]["groups"] for r in g["rules"]]
|
||||
|
||||
|
||||
# ---------- Loki ----------
|
||||
|
||||
def loki(query: str, minutes: int = 15, limit: int = 200) -> list[dict]:
|
||||
"""Записи логов: [{'labels': {...}, 'line': str, 'ts': int}] (labels включают structured metadata)."""
|
||||
base, auth = _via(LOKI_URL, "loki")
|
||||
end = time.time_ns()
|
||||
params = {"query": query, "limit": limit, "start": end - minutes * 60 * 10**9, "end": end, "direction": "backward"}
|
||||
data = get_json(base + "/loki/api/v1/query_range?" + urllib.parse.urlencode(params), auth)
|
||||
out = []
|
||||
for stream in data["data"]["result"]:
|
||||
for ts, line in stream["values"]:
|
||||
out.append({"labels": stream["stream"], "line": line, "ts": int(ts)})
|
||||
return sorted(out, key=lambda e: e["ts"])
|
||||
|
||||
|
||||
def wait_logs(query: str, count: int = 1, seconds: float = 60) -> list[dict]:
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
rows = loki(query)
|
||||
if len(rows) >= count:
|
||||
return rows
|
||||
check(time.monotonic() < deadline, f"loki: no logs for {query}")
|
||||
time.sleep(2)
|
||||
|
||||
|
||||
# ---------- Tempo ----------
|
||||
|
||||
def tempo_search(traceql: str, limit: int = 20, minutes: int = 60) -> list[dict]:
|
||||
base, auth = _via(TEMPO_URL, "tempo")
|
||||
now = int(time.time())
|
||||
params = {"q": traceql, "limit": limit, "start": now - minutes * 60, "end": now + 60}
|
||||
data = get_json(base + "/api/search?" + urllib.parse.urlencode(params), auth)
|
||||
return data.get("traces", [])
|
||||
|
||||
|
||||
def tempo_trace(trace_id: str) -> list[dict]:
|
||||
"""Все спаны трассы: [{'service', 'name', 'kind', 'span_id', 'parent', 'start', 'end', 'status', 'attrs'}]."""
|
||||
base, auth = _via(TEMPO_URL, "tempo")
|
||||
data = get_json(f"{base}/api/traces/{trace_id}", auth)
|
||||
spans = []
|
||||
for batch in data.get("batches", data.get("resourceSpans", [])):
|
||||
resource = {a["key"]: _value(a["value"]) for a in batch["resource"].get("attributes", [])}
|
||||
for scope in batch.get("scopeSpans", []):
|
||||
for s in scope["spans"]:
|
||||
spans.append({
|
||||
"service": resource.get("service.name"), "instance": resource.get("service.instance.id"),
|
||||
"name": s["name"], "kind": s.get("kind", "").replace("SPAN_KIND_", ""),
|
||||
"span_id": _hex(s["spanId"]), "parent": _hex(s.get("parentSpanId", "")),
|
||||
"start": int(s["startTimeUnixNano"]), "end": int(s["endTimeUnixNano"]),
|
||||
"status": s.get("status", {}).get("code", "").replace("STATUS_CODE_", ""),
|
||||
"attrs": {a["key"]: _value(a["value"]) for a in s.get("attributes", [])},
|
||||
})
|
||||
return sorted(spans, key=lambda sp: sp["start"])
|
||||
|
||||
|
||||
def wait_trace(traceql: str, predicate=lambda spans: True, seconds: float = 60) -> tuple[str, list[dict]]:
|
||||
"""Дождаться трассы по TraceQL, у которой выполняется predicate(спаны). Возвращает (trace_id, спаны)."""
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
for found in tempo_search(traceql):
|
||||
spans = tempo_trace(found["traceID"])
|
||||
if spans and predicate(spans):
|
||||
return _hex(found["traceID"]), spans
|
||||
check(time.monotonic() < deadline, f"tempo: no complete trace for {traceql}")
|
||||
time.sleep(3)
|
||||
|
||||
|
||||
def _hex(value: str) -> str:
|
||||
"""Tempo отдаёт ID в hex (/api/traces) или base64 (часть версий): приводим к hex."""
|
||||
if not value:
|
||||
return ""
|
||||
if all(c in "0123456789abcdefABCDEF" for c in value) and len(value) in (16, 32):
|
||||
return value.lower()
|
||||
try:
|
||||
return base64.b64decode(value).hex()
|
||||
except ValueError:
|
||||
return value
|
||||
|
||||
|
||||
def _value(v: dict):
|
||||
if "intValue" in v:
|
||||
return int(v["intValue"]) # в JSON Tempo int64 приходит строкой
|
||||
for key in ("stringValue", "doubleValue", "boolValue"):
|
||||
if key in v:
|
||||
return v[key]
|
||||
return json.dumps(v)
|
||||
|
||||
|
||||
def tree(spans: list[dict]) -> list[str]:
|
||||
"""Дерево трассы для evidence: отступ = вложенность, длительность в мс."""
|
||||
by_id = {s["span_id"]: s for s in spans}
|
||||
children = {}
|
||||
for s in spans:
|
||||
parent = s["parent"] if s["parent"] in by_id else ""
|
||||
children.setdefault(parent, []).append(s)
|
||||
lines = []
|
||||
|
||||
def walk(span, depth):
|
||||
keys = ("http.route", "http.response.status_code", "messenger.job.attempt", "messenger.job.outcome",
|
||||
"messenger.job.error_code", "rpc.method")
|
||||
extra = " ".join(f"{k.split('.')[-1]}={span['attrs'][k]}" for k in keys if k in span["attrs"])
|
||||
name = span["name"] if span["kind"] != "CLIENT" or "rpc.method" in span["attrs"] \
|
||||
else f"SQL {span['name']}"
|
||||
lines.append(f"{' ' * depth}{span['service']:<17}{span['kind']:<9}{name[:48]:<48}"
|
||||
f"{(span['end'] - span['start']) / 1e6:9.1f} ms {span['status'] or ''} {extra}".rstrip())
|
||||
for child in children.get(span["span_id"], []):
|
||||
walk(child, depth + 1)
|
||||
|
||||
for root in children.get("", []):
|
||||
walk(root, 0)
|
||||
return lines
|
||||
|
||||
|
||||
def main(argv):
|
||||
if argv[:1] == ["alerts"]:
|
||||
for rule in rules():
|
||||
if rule.get("type") == "alerting":
|
||||
print(f"{rule['name']:<24} {rule['state']:<9} for {rule.get('duration', 0):>4.0f} s health={rule['health']}")
|
||||
elif argv[:1] == ["logs"]:
|
||||
for entry in loki('{service_name=~"messenger-api|messenger-worker"} | severity_text=~"WARN.*|ERROR"', minutes=30, limit=30):
|
||||
labels = entry["labels"]
|
||||
print(f"{labels.get('service_name')} {labels.get('severity_text')} {labels.get('event')} "
|
||||
f"trace_id={labels.get('trace_id', '-')} {entry['line'][:120]}")
|
||||
else:
|
||||
print("usage: python student-tests/obs.py alerts|logs")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
import sys
|
||||
main(sys.argv[1:])
|
||||
@@ -0,0 +1,202 @@
|
||||
"""lab5: управление стендом для собственных проверок — всё, что делается через Docker.
|
||||
|
||||
Тесты останавливают и запускают сервисы, ставят worker на паузу, включают точки отказа
|
||||
(src/messenger/faults.py) и смотрят в PostgreSQL и RabbitMQ только через этот модуль.
|
||||
Так в самих тестах видно, ЧТО делается со стендом, а не КАК вызвать docker.
|
||||
|
||||
Точка отказа включается файлом /tmp/faults/<имя> внутри контейнера (docker exec). Процесс
|
||||
сам удаляет файл, когда точка сработала, поэтому после перезапуска он работает нормально.
|
||||
Секреты не печатаются: код внутри контейнеров сам читает их из /run/secrets.
|
||||
"""
|
||||
import json
|
||||
import re
|
||||
import subprocess
|
||||
import time
|
||||
|
||||
from helpers import ROOT, check
|
||||
|
||||
_NAME = re.compile(r"^[a-z_]{1,40}$")
|
||||
_VALUE = re.compile(r"^[0-9.]{1,10}$")
|
||||
|
||||
|
||||
def _run(args, stdin: bytes | None = None, check_exit: bool = True) -> str:
|
||||
result = subprocess.run(args, cwd=ROOT, input=stdin, capture_output=True)
|
||||
if check_exit and result.returncode != 0:
|
||||
last = (result.stderr.decode("utf-8", "replace").strip().splitlines() or [""])[-1]
|
||||
check(False, f"`{' '.join(args[:4])} ...` failed: {last[:300]}")
|
||||
return result.stdout.decode("utf-8", "replace").strip()
|
||||
|
||||
|
||||
def compose(*args, stdin: bytes | None = None, check_exit: bool = True) -> str:
|
||||
return _run(["docker", "compose", *args], stdin, check_exit)
|
||||
|
||||
|
||||
def docker(*args, check_exit: bool = True) -> str:
|
||||
return _run(["docker", *args], None, check_exit)
|
||||
|
||||
|
||||
# ---------- сервисы и контейнеры ----------
|
||||
|
||||
def containers(service: str, include_stopped: bool = False) -> list[str]:
|
||||
"""Полные ID контейнеров сервиса (по умолчанию только запущенные)."""
|
||||
args = ["ps", "-q", "-a", service] if include_stopped else ["ps", "-q", service]
|
||||
return sorted(compose(*args).split())
|
||||
|
||||
|
||||
def stop(*services: str) -> None:
|
||||
compose("stop", *services)
|
||||
|
||||
|
||||
def start(*services: str) -> None:
|
||||
compose("start", *services)
|
||||
|
||||
|
||||
def restart(*services: str) -> None:
|
||||
compose("restart", *services)
|
||||
|
||||
|
||||
def pause(container: str) -> None:
|
||||
docker("pause", container)
|
||||
|
||||
|
||||
def unpause(container: str) -> None:
|
||||
docker("unpause", container)
|
||||
|
||||
|
||||
def scale(service: str, replicas: int) -> None:
|
||||
"""Число контейнеров сервиса; существующие не пересоздаются."""
|
||||
compose("up", "-d", "--no-recreate", "--scale", f"{service}={replicas}", service)
|
||||
|
||||
|
||||
def restarts(container: str) -> int:
|
||||
"""Сколько раз Docker перезапускал контейнер (restart: unless-stopped после падения)."""
|
||||
return int(docker("inspect", "-f", "{{.RestartCount}}", container) or 0)
|
||||
|
||||
|
||||
def health(container: str) -> str:
|
||||
return docker("inspect", "-f", "{{if .State.Health}}{{.State.Health.Status}}{{else}}{{.State.Status}}{{end}}",
|
||||
container, check_exit=False)
|
||||
|
||||
|
||||
def wait_healthy(service: str, count: int, seconds: float = 120) -> list[str]:
|
||||
"""Дождаться count запущенных и healthy контейнеров сервиса."""
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
running = containers(service)
|
||||
ready = [c for c in running if health(c) == "healthy"]
|
||||
if len(ready) >= count:
|
||||
return ready
|
||||
check(time.monotonic() < deadline, f"{service}: {len(ready)} healthy of {count} after {seconds} s")
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def logs(service: str, since: str = "10m") -> str:
|
||||
return compose("logs", "--no-color", "--since", since, service, check_exit=False)
|
||||
|
||||
|
||||
# ---------- точки отказа ----------
|
||||
|
||||
def arm(service: str, point: str, value: str = "1", container: str | None = None) -> list[str]:
|
||||
"""Включить точку отказа во всех контейнерах сервиса (или в одном). Возвращает ID контейнеров."""
|
||||
check(bool(_NAME.match(point)) and bool(_VALUE.match(value)), "bad fault point")
|
||||
targets = [container] if container else containers(service)
|
||||
for target in targets:
|
||||
docker("exec", target, "sh", "-c", f"mkdir -p /tmp/faults && printf '%s' {value} > /tmp/faults/{point}")
|
||||
return targets
|
||||
|
||||
|
||||
def disarm(service: str, point: str) -> None:
|
||||
check(bool(_NAME.match(point)), "bad fault point")
|
||||
for target in containers(service):
|
||||
docker("exec", target, "rm", "-f", f"/tmp/faults/{point}", check_exit=False)
|
||||
|
||||
|
||||
def armed(container: str, point: str) -> bool:
|
||||
check(bool(_NAME.match(point)), "bad fault point")
|
||||
return docker("exec", container, "sh", "-c", f"test -e /tmp/faults/{point} && echo yes || echo no",
|
||||
check_exit=False) == "yes"
|
||||
|
||||
|
||||
# ---------- код и данные внутри стенда ----------
|
||||
|
||||
def python(service: str, code: str, container: str | None = None) -> str:
|
||||
"""Python-код внутри контейнера (модули messenger и секреты есть только там). Возвращает stdout.
|
||||
|
||||
С lab7 секретов в файлах контейнера нет: код сначала входит в OpenBao identity этого контейнера
|
||||
(api или worker) и получает только её секреты — тест видит ровно права этого сервиса.
|
||||
"""
|
||||
target = container or containers(service)[0]
|
||||
prelude = "from messenger import secretsource\nsecretsource.load()\n"
|
||||
return _run(["docker", "exec", "-i", target, "python", "-"], (prelude + code).encode("utf-8"))
|
||||
|
||||
|
||||
def cli(service: str, *args: str) -> dict:
|
||||
"""python -m <модуль> ... внутри контейнера, последний вывод — одна строка JSON."""
|
||||
out = _run(["docker", "compose", "exec", "-T", service, "python", "-m", *args])
|
||||
lines = [line for line in out.splitlines() if line.startswith("{") or line.startswith("[")]
|
||||
check(bool(lines), f"no JSON from {' '.join(args)}")
|
||||
return json.loads(lines[-1])
|
||||
|
||||
|
||||
def cli_in(container: str, *args: str) -> dict:
|
||||
"""То же, что cli(), но в конкретном контейнере (там, где включена точка-пауза)."""
|
||||
out = _run(["docker", "exec", "-i", container, "python", "-m", *args])
|
||||
lines = [line for line in out.splitlines() if line.startswith("{") or line.startswith("[")]
|
||||
check(bool(lines), f"no JSON from {' '.join(args)}")
|
||||
return json.loads(lines[-1])
|
||||
|
||||
|
||||
def job(attachment_id: str, service: str = "api") -> dict:
|
||||
"""Состояние задания, журнал, строки outbox и варианты (python -m messenger.jobs show)."""
|
||||
return cli(service, "messenger.jobs", "show", attachment_id)
|
||||
|
||||
|
||||
def replay(attachment_id: str) -> dict:
|
||||
# С lab7 — в контейнере worker: replay проверяет staging/originals в S3, читать staging может только worker.
|
||||
return cli("worker", "messenger.jobs", "replay", attachment_id, "--actor", "student-test")
|
||||
|
||||
|
||||
def psql(sql: str) -> str:
|
||||
"""SQL в PostgreSQL стенда (значения в SQL — проверенные UUID и числа)."""
|
||||
return compose("exec", "-T", "postgres", "psql", "-X", "-q", "-t", "-A", "-U", "messenger", "-d", "messenger",
|
||||
"-v", "ON_ERROR_STOP=1", "-c", sql)
|
||||
|
||||
|
||||
def queues(seconds: float = 30) -> dict:
|
||||
"""{очередь: (готовых к выдаче, выдано и не подтверждено)} — rabbitmqctl внутри контейнера брокера.
|
||||
|
||||
Сразу после перезапуска брокер уже отвечает на ping, но quorum-очереди ещё восстанавливаются
|
||||
с диска, и list_queues может один раз не ответить: тогда повторяем до seconds секунд.
|
||||
"""
|
||||
args = ("exec", "-T", "broker", "rabbitmqctl", "-q", "list_queues", "-p", "messenger",
|
||||
"name", "messages_ready", "messages_unacknowledged", "--formatter", "json")
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
out = compose(*args, check_exit=False) # при ошибке rabbitmqctl печатает справку, не JSON
|
||||
try:
|
||||
rows = json.loads(out or "[]")
|
||||
return {q["name"]: (int(q["messages_ready"]), int(q["messages_unacknowledged"])) for q in rows}
|
||||
except (ValueError, KeyError, TypeError):
|
||||
pass
|
||||
check(time.monotonic() < deadline, "rabbitmqctl list_queues: the broker does not answer")
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def objects(prefix: str) -> list[str]:
|
||||
"""Ключи объектов S3 под префиксом (с lab7 — из контейнера worker: list есть только у его ключей)."""
|
||||
out = python("worker", "import json\nfrom messenger import objects\n"
|
||||
f"print(json.dumps([k for k, _ in objects.list_objects({prefix!r})]))")
|
||||
return json.loads(out.splitlines()[-1])
|
||||
|
||||
|
||||
def publish(message: dict) -> None:
|
||||
"""Отправить сообщение в очередь заданий напрямую (имитация повторной доставки)."""
|
||||
python("api", "import json\nfrom messenger import broker\n"
|
||||
f"p = broker.Publisher('student-test')\np.publish(json.loads({json.dumps(message)!r}))\np.close()")
|
||||
|
||||
|
||||
def publish_raw(body: bytes) -> None:
|
||||
"""Отправить в очередь произвольное тело (проверка, что worker отвергает чужой формат)."""
|
||||
python("api", "import pika\nfrom messenger import broker\n"
|
||||
"c = broker.connect('student-test'); ch = c.channel(); ch.confirm_delivery()\n"
|
||||
f"ch.basic_publish(broker.EXCHANGE, broker.ROUTING_KEY, {body!r}, mandatory=True)\nc.close()")
|
||||
@@ -0,0 +1,150 @@
|
||||
"""lab5, уровень 4: разрыв между PostgreSQL и брокером закрыт transactional outbox.
|
||||
|
||||
make outbox-crash (= python student-tests/outbox_crash.py)
|
||||
|
||||
Три окна отказа из contracts/attachment-states.md, в каждом процесс API падает по-настоящему
|
||||
(os._exit, как SIGKILL: без ответа, без finally) в точке отказа (src/messenger/faults.py):
|
||||
|
||||
A. api_after_commit — вложение, задание и строка outbox закоммичены, ответ 202 ещё не отправлен.
|
||||
Клиент получает ошибку балансировщика (502), но работа принята: relay другой реплики (или этой
|
||||
после перезапуска) отправляет задание, worker его выполняет. Новое задание вручную не создаётся.
|
||||
B. relay_before_publish — relay взял строки outbox, но в брокер ничего не отправил. Транзакция
|
||||
откатывается вместе с упавшим процессом, строки остаются неотправленными, их отправляют позже.
|
||||
C. relay_after_publish — брокер подтвердил приём, но строка не отмечена отправленной. После
|
||||
перезапуска её отправляют ещё раз: worker получает дубль и подтверждает его без обработки.
|
||||
D. Брокер остановлен целиком: загрузка всё равно получает 202 (брокер не входит в readiness),
|
||||
строка outbox ждёт в PostgreSQL неотправленной; после запуска брокера relay её отправляет.
|
||||
Точка включается во всех репликах API: какая бы реплика ни взялась за строку, она упадёт.
|
||||
Docker сам перезапускает упавшие контейнеры (restart: unless-stopped); файл точки удаляется до
|
||||
падения, поэтому после перезапуска реплика работает нормально.
|
||||
В каждом сценарии проверяется: вложение стало ready, у задания одна попытка и один набор вариантов.
|
||||
"""
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import ops
|
||||
from filegen import SAMPLE_PNG, upload_when_ready, wait_status
|
||||
from helpers import Client, check, run
|
||||
from stand import lb_up_count, try_call
|
||||
|
||||
|
||||
def stand_ready(seconds=120):
|
||||
ops.wait_healthy("api", 2, seconds)
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
try:
|
||||
if lb_up_count() >= 2:
|
||||
return
|
||||
except OSError:
|
||||
pass
|
||||
check(time.monotonic() < deadline, "HAProxy does not see 2 ready api replicas")
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def restart_counts():
|
||||
return {c[:12]: ops.restarts(c) for c in ops.containers("api")}
|
||||
|
||||
|
||||
def finished(api, bob, attachment_id):
|
||||
meta = wait_status(api, bob, attachment_id, ("ready",), seconds=120)
|
||||
job = ops.job(attachment_id)
|
||||
check(job["job"]["attempt"] == 1, "the job must finish in its first attempt")
|
||||
check(len(job["variants"]) == 3, "exactly one set of variants expected")
|
||||
check(sum(e["event"] == "ready" for e in job["events"]) == 1, "the result must be committed once")
|
||||
return meta, job
|
||||
|
||||
|
||||
def show(job):
|
||||
outbox = "; ".join(f"row {o['id']} published {o['published_at']} by {o['published_by']}" for o in job["outbox"])
|
||||
events = " -> ".join(f"{e['event']}" for e in job["events"])
|
||||
return f"outbox: {outbox}\n events: {events}"
|
||||
|
||||
|
||||
def main():
|
||||
api = Client(timeout=15)
|
||||
ops.wait_healthy("worker", 1)
|
||||
stand_ready()
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
|
||||
# ---------- A ----------
|
||||
before = restart_counts()
|
||||
ops.arm("api", "api_after_commit")
|
||||
name = f"outbox-a-{uuid.uuid4().hex[:8]}.png"
|
||||
reply = try_call("POST", f"/api/v1/chats/{chat['id']}/attachments?filename={name}", raw=SAMPLE_PNG,
|
||||
token=alice["token"], headers={"Content-Type": "image/png"}, timeout=30)
|
||||
status = reply.status if reply else "no response"
|
||||
check(reply is None or reply.status >= 500, "the client must NOT get 202 when the API crashed after COMMIT")
|
||||
ops.disarm("api", "api_after_commit") # реплика, которая не упала, ещё «заряжена»
|
||||
attachment_id = ops.psql(f"SELECT id FROM attachments WHERE filename = '{name}'")
|
||||
check(bool(attachment_id), "the committed attachment row must exist")
|
||||
print(f"A. api_after_commit: the client got {status} instead of 202, but the attachment {attachment_id} "
|
||||
f"and its outbox row were committed before the crash")
|
||||
_meta, job = finished(api, bob, attachment_id)
|
||||
stand_ready()
|
||||
after = restart_counts()
|
||||
crashed = [c for c in after if after[c] > before.get(c, after[c])]
|
||||
print(f" ready without creating a new job by hand; api restarted by Docker: {crashed or 'see logs'}")
|
||||
print(" " + show(job))
|
||||
|
||||
# ---------- B ----------
|
||||
before = restart_counts()
|
||||
ops.arm("api", "relay_before_publish")
|
||||
att = upload_when_ready(api, alice, chat, name="outbox-b.png")["json"]
|
||||
print(f"B. relay_before_publish: upload -> 202 ({att['id']}); every relay that takes the row crashes "
|
||||
f"before publishing")
|
||||
_meta, job = finished(api, bob, att["id"])
|
||||
stand_ready()
|
||||
after = restart_counts()
|
||||
crashed = [c for c in after if after[c] > before.get(c, after[c])]
|
||||
check(crashed, "at least one relay must have crashed")
|
||||
check(not any(e["event"].startswith("duplicate") for e in job["events"]), "nothing was published twice here")
|
||||
print(f" crashed and restarted: {crashed}; after restart the row was published once -> ready")
|
||||
print(" " + show(job))
|
||||
|
||||
# ---------- C ----------
|
||||
before = restart_counts()
|
||||
ops.arm("api", "relay_after_publish")
|
||||
att = upload_when_ready(api, alice, chat, name="outbox-c.png")["json"]
|
||||
print(f"C. relay_after_publish: upload -> 202 ({att['id']}); the broker confirms, the relay crashes before "
|
||||
f"marking the row")
|
||||
_meta, job = finished(api, bob, att["id"])
|
||||
deadline = time.monotonic() + 60
|
||||
while not any(e["event"].startswith("duplicate") for e in job["events"]):
|
||||
check(time.monotonic() < deadline, "the duplicate delivery was not observed")
|
||||
time.sleep(1)
|
||||
job = ops.job(att["id"])
|
||||
stand_ready()
|
||||
after = restart_counts()
|
||||
crashed = [c for c in after if after[c] > before.get(c, after[c])]
|
||||
duplicates = [e for e in job["events"] if e["event"].startswith("duplicate")]
|
||||
print(f" crashed and restarted: {crashed}; the same message was delivered again "
|
||||
f"{len(duplicates)} time(s): " + ", ".join(e["event"] for e in duplicates))
|
||||
print(" " + show(job))
|
||||
keys = ops.objects(f"variants/{att['id']}/")
|
||||
check(len(keys) == 3, "duplicates must not create more objects")
|
||||
print(f" still one set of variants: {len(job['variants'])} rows, {len(keys)} objects")
|
||||
# ---------- D ----------
|
||||
ops.stop("broker")
|
||||
try:
|
||||
att = upload_when_ready(api, alice, chat, name="outbox-d.png")["json"]
|
||||
time.sleep(5)
|
||||
job = ops.job(att["id"])
|
||||
check(job["outbox"] and not job["outbox"][0]["published_at"], "the row must wait while the broker is down")
|
||||
meta = api.call("GET", f"/api/v1/attachments/{att['id']}", actor=bob, schema="Attachment")["json"]
|
||||
print(f"D. broker stopped: upload -> 202 ({att['id']}), after 5 s status {meta['status']}, outbox row "
|
||||
f"{job['outbox'][0]['id']} not published yet (it waits in PostgreSQL)")
|
||||
finally:
|
||||
ops.start("broker")
|
||||
ops.wait_healthy("broker", 1, 180)
|
||||
started = time.monotonic()
|
||||
_meta, job = finished(api, bob, att["id"])
|
||||
print(f" broker started: the relay published the row, ready {time.monotonic() - started:.1f} s later")
|
||||
print(" " + show(job))
|
||||
print("PASS: a crash between COMMIT and publish (A, B) loses nothing — the outbox row is published later and "
|
||||
"the job becomes ready without manual action; a crash after publish (C) only causes a duplicate "
|
||||
"delivery, which the worker acknowledges without a second set of variants; while the broker is down (D) "
|
||||
"uploads are still accepted and the jobs wait in the outbox")
|
||||
|
||||
|
||||
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,80 @@
|
||||
"""lab5, уровень 3: повторная доставка — нормальная ситуация, она не создаёт второй набор вариантов.
|
||||
|
||||
make redelivery (= python student-tests/redelivery.py)
|
||||
|
||||
1. upload -> ready: запоминаем варианты (SHA-256), объекты под variants/<id>/ и строки в БД;
|
||||
2. в очередь ещё дважды отправляется ТО ЖЕ сообщение (тот же job_id и attempt) — так выглядит
|
||||
повторная доставка (например, relay упал после подтверждения брокера, но до отметки в outbox);
|
||||
3. worker получает оба дубля и подтверждает их без обработки: в журнале задания duplicate_ignored,
|
||||
вариантов по-прежнему 3, объектов 3, SHA-256 те же, статус ready, попытка 1;
|
||||
4. сообщение не по схеме jobs.schema.json (лишнее поле с URL; число вместо UUID; не JSON) worker
|
||||
не обрабатывает и не падает: reject -> DLQ (attachments.dead), обычная работа продолжается.
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
|
||||
import ops
|
||||
from filegen import upload_when_ready, wait_status
|
||||
from helpers import Client, check, run
|
||||
|
||||
|
||||
def wait_events(attachment_id, name, count, seconds=30):
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
job = ops.job(attachment_id)
|
||||
found = [e for e in job["events"] if e["event"] == name]
|
||||
if len(found) >= count:
|
||||
return job
|
||||
check(time.monotonic() < deadline, f"expected {count} {name} events, got {len(found)}")
|
||||
time.sleep(1)
|
||||
|
||||
|
||||
def main():
|
||||
api = Client(timeout=15)
|
||||
ops.wait_healthy("worker", 1)
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
att = upload_when_ready(api, alice, chat, name="redelivery.png")["json"]
|
||||
ready = wait_status(api, bob, att["id"])
|
||||
before = ops.job(att["id"])
|
||||
keys = ops.objects(f"variants/{att['id']}/")
|
||||
check(len(before["variants"]) == 3 and len(keys) == 3, "one set of variants expected")
|
||||
print(f"1. attachment {att['id']} ready: 3 variant rows, objects {keys}")
|
||||
|
||||
message = {"schema_version": 1, "job_id": before["job"]["job_id"], "type": "attachment.process.v1",
|
||||
"attachment_id": att["id"], "pipeline_version": 1, "attempt": 1,
|
||||
"created_at": "2026-10-25T12:00:00Z"}
|
||||
for _ in range(2):
|
||||
ops.publish(message)
|
||||
print("2. the same message (same job_id and attempt) published twice more")
|
||||
after = wait_events(att["id"], "duplicate_ignored", 2)
|
||||
keys_after = ops.objects(f"variants/{att['id']}/")
|
||||
check(after["variants"] == before["variants"], "variants changed after a duplicate")
|
||||
check(sorted(keys_after) == sorted(keys), "a second set of objects appeared")
|
||||
check(after["job"]["attempt"] == 1 and after["attachment_status"] == "ready", "duplicate changed the job")
|
||||
meta = api.call("GET", f"/api/v1/attachments/{att['id']}", actor=bob, schema="Attachment")["json"]
|
||||
check(meta == ready, "metadata changed after a duplicate")
|
||||
print("3. both duplicates acknowledged without processing: " +
|
||||
", ".join(f"{e['event']}({e['detail']})" for e in after["events"] if e["event"] == "duplicate_ignored"))
|
||||
print(f" variants: {[(v['name'], v['sha256'][:12]) for v in after['variants']]} — same rows, same objects, "
|
||||
f"status ready, attempt 1")
|
||||
|
||||
dead_before = ops.queues().get("attachments.dead", (0, 0))[0]
|
||||
bad = [dict(message, url="http://example.invalid/steal"), dict(message, job_id=42), None]
|
||||
for body in bad:
|
||||
ops.publish_raw(b"not json at all" if body is None else json.dumps(body).encode())
|
||||
deadline = time.monotonic() + 30
|
||||
while ops.queues().get("attachments.dead", (0, 0))[0] < dead_before + len(bad):
|
||||
check(time.monotonic() < deadline, "invalid messages did not reach the DLQ")
|
||||
time.sleep(1)
|
||||
dead_after = ops.queues().get("attachments.dead", (0, 0))[0]
|
||||
print(f"4. 3 messages that do not match jobs.schema.json -> reject -> DLQ attachments.dead: "
|
||||
f"{dead_before} -> {dead_after}")
|
||||
second = upload_when_ready(api, alice, chat, name="after-bad.png")["json"]
|
||||
wait_status(api, bob, second["id"])
|
||||
print(" the worker keeps working: a new upload became ready")
|
||||
print("PASS: redelivery of a finished job is a no-op with ack (no second set of variants); "
|
||||
"malformed messages go to the DLQ without crashing the worker")
|
||||
|
||||
|
||||
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,122 @@
|
||||
"""lab5, уровень 4: ограниченные повторы с backoff и jitter, постоянные и временные ошибки, DLQ и replay.
|
||||
|
||||
make retry-replay (= python student-tests/retry_replay.py)
|
||||
|
||||
A. Временная ошибка, потом успех: точка worker_transient=2 — две попытки подряд «падают», как при
|
||||
недоступном S3. Каждая назначает следующую с паузой backoff + jitter (случайно в [d/2, d],
|
||||
d = 2, 4, 8… с). Третья попытка успешна -> ready. Паузы берутся из outbox (available_at).
|
||||
B. Попытки исчерпаны: worker_transient=99 -> 5 попыток (JOB_MAX_ATTEMPTS) -> failed с
|
||||
error_code=retry_exhausted; сообщение уходит в DLQ (attachments.dead), задание — в реестр failed
|
||||
(python -m messenger.jobs failed); /content -> 409, прикрепить к сообщению -> 409.
|
||||
C. Постоянная ошибка: JPEG с испорченными сжатыми данными -> invalid_image сразу, без повторов (попытка 1).
|
||||
D. Replay оператора (python -m messenger.jobs replay): failed из B -> queued -> ready (новая попытка,
|
||||
запись в журнале с автором). Replay готового вложения — no-op: дубль успешной работы не запускается.
|
||||
Replay постоянной ошибки из C снова даёт invalid_image: replay не обходит проверку файла.
|
||||
"""
|
||||
import time
|
||||
from datetime import datetime
|
||||
|
||||
import ops
|
||||
from filegen import garbage_scan_jpeg, upload_when_ready, wait_status
|
||||
from helpers import Client, check, idempotency, run
|
||||
|
||||
|
||||
def parse(value):
|
||||
return datetime.fromisoformat(value)
|
||||
|
||||
|
||||
def delays(job):
|
||||
"""Пауза перед каждой следующей попыткой: available_at - created_at строки outbox этой попытки."""
|
||||
created = {e["attempt"]: e["at"] for e in job["events"] if e["event"] == "retry_scheduled"}
|
||||
rows = {o["attempt"]: o for o in job["outbox"]}
|
||||
out = []
|
||||
for attempt in sorted(created):
|
||||
row = rows.get(attempt + 1)
|
||||
if row:
|
||||
out.append((attempt + 1, (parse(row["available_at"]) - parse(created[attempt])).total_seconds()))
|
||||
return out
|
||||
|
||||
|
||||
def main():
|
||||
api = Client(timeout=15)
|
||||
worker = ops.wait_healthy("worker", 1)[0]
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
try:
|
||||
# ---------- A ----------
|
||||
ops.arm("worker", "worker_transient", "2", container=worker)
|
||||
att_a = upload_when_ready(api, alice, chat, name="retry-a.png")["json"]
|
||||
wait_status(api, bob, att_a["id"], seconds=90)
|
||||
job = ops.job(att_a["id"])
|
||||
check(job["job"]["attempt"] == 3, "expected success at attempt 3")
|
||||
pauses = delays(job)
|
||||
for attempt, pause in pauses:
|
||||
limit = min(60, 2 * 2 ** (attempt - 2))
|
||||
check(limit / 2 - 0.05 <= pause <= limit + 0.05, f"pause {pause:.2f} s before attempt {attempt} "
|
||||
f"is outside [{limit / 2}, {limit}]")
|
||||
print(f"A. transient errors twice, then success: ready at attempt {job['job']['attempt']}")
|
||||
print(" pauses before attempts: " + ", ".join(f"#{a}: {p:.2f} s" for a, p in pauses) +
|
||||
" (backoff 2^n with random jitter in [d/2, d])")
|
||||
print(" events: " + " -> ".join(f"{e['event']}({e['attempt']})" for e in job["events"]))
|
||||
|
||||
# ---------- B ----------
|
||||
dead_before = ops.queues().get("attachments.dead", (0, 0))[0]
|
||||
ops.arm("worker", "worker_transient", "99", container=worker)
|
||||
att_b = upload_when_ready(api, alice, chat, name="retry-b.png")["json"]
|
||||
failed = wait_status(api, bob, att_b["id"], ("failed",), seconds=180)
|
||||
ops.disarm("worker", "worker_transient")
|
||||
job = ops.job(att_b["id"])
|
||||
check(failed["error_code"] == "retry_exhausted" and job["job"]["attempt"] == 5, "expected 5 attempts")
|
||||
api.call("GET", f"/api/v1/attachments/{att_b['id']}/content", 409, actor=bob)
|
||||
api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 409, actor=alice, headers=idempotency(),
|
||||
body={"text": "", "attachment_ids": [att_b["id"]]})
|
||||
deadline = time.monotonic() + 30
|
||||
while ops.queues().get("attachments.dead", (0, 0))[0] <= dead_before:
|
||||
check(time.monotonic() < deadline, "the final failure did not reach the DLQ")
|
||||
time.sleep(1)
|
||||
registry = ops.cli("api", "messenger.jobs", "failed")
|
||||
check(isinstance(registry, list) and any(r["attachment_id"] == att_b["id"] for r in registry),
|
||||
"the failed job is missing from the registry")
|
||||
entry = [r for r in registry if r["attachment_id"] == att_b["id"]][0]
|
||||
print(f"B. transient error every time: {job['job']['attempt']} attempts -> failed, "
|
||||
f"error_code={failed['error_code']} (last error {entry['last_error_code']})")
|
||||
print(" pauses: " + ", ".join(f"#{a}: {p:.2f} s" for a, p in delays(job)))
|
||||
print(f" DLQ attachments.dead: {dead_before} -> {ops.queues()['attachments.dead'][0]}; "
|
||||
f"registry: python -m messenger.jobs failed lists it; content -> 409, attach -> 409")
|
||||
|
||||
# ---------- C ----------
|
||||
att_c = upload_when_ready(api, alice, chat, data=garbage_scan_jpeg(), name="broken.jpg",
|
||||
ctype="image/jpeg")["json"]
|
||||
failed_c = wait_status(api, bob, att_c["id"], ("failed",), seconds=60)
|
||||
job_c = ops.job(att_c["id"])
|
||||
check(failed_c["error_code"] == "invalid_image" and job_c["job"]["attempt"] == 1, "no retries for a bad file")
|
||||
print(f"C. permanent error: broken JPEG scan -> failed at attempt 1, error_code={failed_c['error_code']} "
|
||||
f"(no retries)")
|
||||
finally:
|
||||
ops.disarm("worker", "worker_transient")
|
||||
|
||||
# ---------- D ----------
|
||||
result = ops.replay(att_b["id"])
|
||||
check(result.get("result") == "queued", f"replay of a failed job must queue it: {result}")
|
||||
ready = wait_status(api, bob, att_b["id"], seconds=90)
|
||||
job = ops.job(att_b["id"])
|
||||
audit = [e for e in job["events"] if e["event"] == "replay_requested"]
|
||||
check(audit and audit[-1]["actor"].startswith("operator:"), "replay must be audited")
|
||||
print(f"D. replay of the failed job: {result} -> ready at attempt {job['job']['attempt']}; "
|
||||
f"audit: {audit[-1]['actor']}: {audit[-1]['detail']}")
|
||||
outbox_rows, variants = len(job["outbox"]), job["variants"]
|
||||
noop = ops.replay(att_b["id"])
|
||||
after = ops.job(att_b["id"])
|
||||
check(noop == {"result": "noop", "reason": "ready"}, f"replay of a ready job must be a no-op: {noop}")
|
||||
check(len(after["outbox"]) == outbox_rows and after["variants"] == variants, "replay of ready changed something")
|
||||
print(f" replay of the now ready job: {noop} — no new message, variants unchanged "
|
||||
f"({len(variants)} rows), status {ready['status']}")
|
||||
again = ops.replay(att_c["id"])
|
||||
failed_again = wait_status(api, bob, att_c["id"], ("failed",), seconds=60)
|
||||
check(again.get("result") == "queued" and failed_again["error_code"] == "invalid_image", "bad file must fail again")
|
||||
print(f" replay of the permanent failure: {again} -> failed again with {failed_again['error_code']}")
|
||||
print("PASS: bounded retries with backoff and jitter; permanent errors fail at once; final failures go to the "
|
||||
"DLQ and the failed registry; replay re-runs only failed jobs and is audited")
|
||||
|
||||
|
||||
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, alias_of, 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 probe not in {alias_of(container) 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]} (its alias was in TARGET_INSTANCE_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, broker (с lab5), worker, обеих реплик api и lb должен быть ТОТ ЖЕ ID контейнера
|
||||
(контейнеры и volumes те же, ничего не пересоздано) и НОВОЕ время старта (процесс перезапущен).
|
||||
Сам тест проверяет, что данные, прежний токен и файл (с lab5 — после ready) на месте. Сервис 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", "worker", "postgres", "valkey", "s3", "broker", "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, worker, postgres, valkey, s3, broker 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,162 @@
|
||||
"""lab4–lab5, уровень 4: S3 приватный, у API минимальные права, консоль закрыта, bootstrap идемпотентен.
|
||||
(lab7: S3 по HTTPS, у API права только на префиксы — см. scripts/init-secrets.sh.)
|
||||
|
||||
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 и worker нет файла
|
||||
оригинала (у worker есть только временная копия на время обработки, она удаляется);
|
||||
5. s3-init запускается ещё два раза: оба раза код 0, объекты на месте, файл скачивается;
|
||||
6. (lab5) сообщение для брокера (строка outbox) содержит только поля contracts/jobs.schema.json:
|
||||
ID и служебные данные, без байтов, ключей S3, URL и паролей.
|
||||
"""
|
||||
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, wait_status
|
||||
from helpers import ROOT, Client, check, run
|
||||
from stand import api_containers, compose_output
|
||||
|
||||
DIRECT = """
|
||||
import hashlib, json, socket, ssl, urllib.error, urllib.request
|
||||
from botocore.exceptions import ClientError
|
||||
from messenger import config, objects
|
||||
base, bucket, key = config.S3_ENDPOINT, config.S3_BUCKET, "{key}"
|
||||
tls = ssl.create_default_context(cafile=config.TLS_CA_FILE) # с lab7 S3 только по HTTPS
|
||||
def anonymous(url):
|
||||
try:
|
||||
return urllib.request.urlopen(url, timeout=5, context=tls).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"]
|
||||
wait_status(api, bob, att["id"])
|
||||
key = psql(f"SELECT storage_key FROM attachments WHERE id = '{uuid.UUID(att['id'])}'")
|
||||
check(key == f"originals/{att['id']}" and "private" not in key, "object key must be server-generated")
|
||||
print("object keys are server-generated: staging/<attachment uuid> -> originals/<attachment uuid>, "
|
||||
"variants/<attachment uuid>/v1/<variant> (filename is not used in keys)")
|
||||
|
||||
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")
|
||||
workers = sorted(compose_output("ps", "-q", "worker").split())
|
||||
for role, container in [("api", c) for c in api_containers()] + [("worker", c) for c in workers]:
|
||||
code = FIND_LOCAL_COPY.format(size=len(SAMPLE_PNG), sha=att["sha256"])
|
||||
found = exec_python(container, code)
|
||||
print(f"{role} {container[:12]}: files with the same SHA-256 on disk: {found}")
|
||||
check(found == "0", f"{role} keeps a local copy of the original")
|
||||
|
||||
payload = json.loads(psql(f"""SELECT o.payload::text FROM outbox o JOIN attachment_jobs j ON j.job_id = o.job_id
|
||||
WHERE j.attachment_id = '{uuid.UUID(att['id'])}' ORDER BY o.id LIMIT 1"""))
|
||||
allowed = {"schema_version", "job_id", "type", "attachment_id", "pipeline_version", "attempt", "created_at",
|
||||
"traceparent", "tracestate"}
|
||||
text = json.dumps(payload)
|
||||
check(set(payload) <= allowed, f"unexpected fields in the broker message: {set(payload) - allowed}")
|
||||
check(not any(word in text for word in ("staging/", "originals/", "http", "secret", "password")),
|
||||
"the broker message must not contain keys, URLs or credentials")
|
||||
print(f"broker message ({len(text)} bytes): {sorted(payload)} — only IDs and service fields")
|
||||
|
||||
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,112 @@
|
||||
"""lab5, уровень 4: очистка staging после безопасной фиксации и уборка объектов без ссылок из БД.
|
||||
|
||||
make staging-cleanup (= python student-tests/staging_cleanup.py)
|
||||
|
||||
1. Обычный путь: после COMMIT результата worker сам удаляет staging/<id>; остаются originals/<id>
|
||||
и три варианта.
|
||||
2. Состояния, которые оставляют сбои (создаются напрямую в S3 и через API):
|
||||
- staging готового вложения (worker упал между COMMIT и удалением staging);
|
||||
- staging без строки в БД (API упал между PUT в staging и COMMIT);
|
||||
- вариант без строки в БД (worker записал объекты, а задание потом ушло в failed);
|
||||
- staging failed-вложения (битый JPEG) — хранится STAGING_RETENTION_SECONDS для replay;
|
||||
- staging задания в очереди (worker остановлен) — нужен, его трогать нельзя.
|
||||
3. python -m messenger.cleanup:
|
||||
--dry-run все найдены, ничего не удалено;
|
||||
обычный запуск (grace 900 с) ничего не удалено: объекты моложе grace (это может быть
|
||||
идущая прямо сейчас работа);
|
||||
--grace-seconds 2 (только тест) удалены «сироты» и staging готового; staging задания в очереди,
|
||||
staging failed (в пределах retention), оригиналы и варианты на месте;
|
||||
--retention-seconds 0 удалён staging failed; replay такого вложения отказывается
|
||||
(source_missing) вместо падения worker;
|
||||
повторный запуск удалять нечего.
|
||||
4. worker запущен: задание из очереди стало ready, его staging удалён.
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
import uuid
|
||||
|
||||
import ops
|
||||
from filegen import garbage_scan_jpeg, upload_when_ready, wait_status
|
||||
from helpers import Client, check, run
|
||||
|
||||
PUT = """
|
||||
import io
|
||||
from messenger import objects
|
||||
for key in %s:
|
||||
objects.put(key, io.BytesIO(b"left-behind"), 11, "image/png", "0" * 64)
|
||||
print("ok")
|
||||
"""
|
||||
|
||||
|
||||
def exists(keys):
|
||||
present = set(ops.objects("staging/")) | set(ops.objects("originals/")) | set(ops.objects("variants/"))
|
||||
return {name: key in present for name, key in keys.items()}
|
||||
|
||||
|
||||
def cleanup(*args):
|
||||
return ops.cli("api", "messenger.cleanup", *args)
|
||||
|
||||
|
||||
def main():
|
||||
api = Client(timeout=15)
|
||||
ops.wait_healthy("worker", 1)
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
|
||||
ready = upload_when_ready(api, alice, chat, name="keep.png")["json"]
|
||||
wait_status(api, bob, ready["id"])
|
||||
rid = ready["id"]
|
||||
state = exists({"staging": f"staging/{rid}", "original": f"originals/{rid}",
|
||||
"thumbnail": f"variants/{rid}/v1/thumbnail.jpg"})
|
||||
check(state == {"staging": False, "original": True, "thumbnail": True}, f"unexpected objects: {state}")
|
||||
print(f"1. ready {rid}: staging removed by the worker right after COMMIT; original and variants kept")
|
||||
|
||||
failed = upload_when_ready(api, alice, chat, data=garbage_scan_jpeg(), name="bad.jpg", ctype="image/jpeg")["json"]
|
||||
wait_status(api, bob, failed["id"], ("failed",))
|
||||
try:
|
||||
ops.stop("worker")
|
||||
queued = upload_when_ready(api, alice, chat, name="queued.png")["json"]
|
||||
keys = {"ready_original": f"originals/{rid}", "ready_variant": f"variants/{rid}/v1/crop.jpg",
|
||||
"ready_staging_leftover": f"staging/{rid}", "orphan_staging": f"staging/{uuid.uuid4()}",
|
||||
"orphan_variant": f"variants/{uuid.uuid4()}/v1/thumbnail.jpg",
|
||||
"failed_staging": f"staging/{failed['id']}", "queued_staging": f"staging/{queued['id']}"}
|
||||
ops.python("api", PUT % json.dumps([keys["ready_staging_leftover"], keys["orphan_staging"],
|
||||
keys["orphan_variant"]]))
|
||||
check(all(exists(keys).values()), "setup failed")
|
||||
print("2. prepared: staging leftover of a ready attachment, orphan staging, orphan variant, "
|
||||
"staging of a failed attachment, staging of a queued job (worker stopped)")
|
||||
|
||||
dry = cleanup("--dry-run", "--grace-seconds", "0")
|
||||
check(dry["deleted"] == 0 and all(exists(keys).values()), "dry-run deleted something")
|
||||
print(f"3. dry-run: {json.dumps(dry['to_delete'])} found, deleted {dry['deleted']}")
|
||||
normal = cleanup()
|
||||
check(all(exists(keys).values()), "grace 900 s must protect young objects")
|
||||
print(f" grace 900 s: deleted {normal['deleted']} — everything is younger than the grace period")
|
||||
time.sleep(3)
|
||||
short = cleanup("--grace-seconds", "2")
|
||||
state = exists(keys)
|
||||
check(not state["ready_staging_leftover"] and not state["orphan_staging"] and not state["orphan_variant"],
|
||||
f"leftovers must be deleted: {state}")
|
||||
check(state["ready_original"] and state["ready_variant"] and state["failed_staging"] and state["queued_staging"],
|
||||
f"needed objects were deleted: {state}")
|
||||
print(f" grace 2 s: {json.dumps(short['to_delete'])}, deleted {short['deleted']}; kept: ready original "
|
||||
f"and variants, staging of the queued job, staging of the failed attachment (retention)")
|
||||
expired = cleanup("--grace-seconds", "2", "--retention-seconds", "0")
|
||||
check(not exists(keys)["failed_staging"], "failed staging past retention must be deleted")
|
||||
refused = ops.replay(failed["id"])
|
||||
check(refused.get("result") == "refused" and refused.get("reason") == "source_missing", f"{refused}")
|
||||
print(f" retention 0 s: failed staging deleted ({json.dumps(expired['to_delete'])}); replay now: {refused}")
|
||||
again = cleanup("--grace-seconds", "2", "--retention-seconds", "0")
|
||||
check(again["deleted"] == 0, "repeated run is not a no-op")
|
||||
print(f" repeated run: deleted {again['deleted']}")
|
||||
finally:
|
||||
ops.start("worker")
|
||||
wait_status(api, bob, queued["id"], seconds=90)
|
||||
check(not exists({"q": f"staging/{queued['id']}"})["q"], "staging of the processed job must be removed")
|
||||
print(f"4. worker started: {queued['id']} ready, its staging removed")
|
||||
print("PASS: staging is removed after the result is committed; objects without a reference in the database are "
|
||||
"removed only after the grace period; the staging of failed uploads is kept for replay until retention "
|
||||
"ends; dry-run and repeated runs are safe")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,225 @@
|
||||
"""Помощники 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 ssl
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
|
||||
from helpers import ROOT, check
|
||||
|
||||
BASE_URL = os.environ.get("BASE_URL", "https://127.0.0.1:8443").rstrip("/")
|
||||
LB_STATS_URL = os.environ.get("LB_STATS_URL", "https://127.0.0.1:8404/stats;csv")
|
||||
CA_FILE = os.environ.get("CA_FILE") or None # с lab7: CA стенда (сертификат lb проверяется)
|
||||
|
||||
|
||||
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 _tls_opener():
|
||||
"""urllib с проверкой сертификата балансировщика нашим CA (с lab7). --insecure нигде нет."""
|
||||
context = ssl.create_default_context(cafile=CA_FILE)
|
||||
return urllib.request.build_opener(urllib.request.HTTPSHandler(context=context))
|
||||
|
||||
|
||||
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 _tls_opener().open(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 alias_of(container):
|
||||
"""Alias реплики (X-Instance-Id) по контейнеру: с lab7 это случайная строка, а не ID контейнера.
|
||||
|
||||
Процесс пишет её в INSTANCE_ID_FILE (/tmp/instance-id, tmpfs контейнера). Сопоставление
|
||||
alias -> контейнер доступно только тому, у кого есть доступ к Docker, то есть оператору:
|
||||
по заголовку ответа нельзя узнать ни hostname, ни адрес реплики (контракт lab7).
|
||||
"""
|
||||
return docker("exec", container, "cat", "/tmp/instance-id", check_exit=False).strip()
|
||||
|
||||
|
||||
def container_of(alias, include_stopped=False):
|
||||
"""Контейнер api, который отвечает этим alias, или None."""
|
||||
for container in api_containers(include_stopped):
|
||||
if alias and alias_of(container) == alias:
|
||||
return container
|
||||
return None
|
||||
|
||||
|
||||
def aliases():
|
||||
"""{контейнер: alias} для всех запущенных реплик api."""
|
||||
return {container: alias_of(container) for container in api_containers()}
|
||||
|
||||
|
||||
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 _tls_opener().open(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", "--tls", "--cacert", "/run/ca/ca.crt",
|
||||
"-h", "127.0.0.1", "--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,126 @@
|
||||
"""lab6, уровень 4, сценарий 3: хранилища телеметрии недоступны — API работает, память ограничена.
|
||||
|
||||
make telemetry-outage (= python student-tests/telemetry_outage.py) ~7 минут
|
||||
|
||||
1. фон: сообщения (3 потока) и загрузка картинки раз в 5 с;
|
||||
2. docker compose stop tempo loki — на 3 минуты. Каждые 15 с: коды ответов API, RSS Collector,
|
||||
очереди его exporter (пачки), неудачные отправки, состояние alert TelemetryExportFailing.
|
||||
Ожидаем: все бизнес-запросы успешны, загрузки становятся ready, очередь растёт, но не выше ёмкости,
|
||||
куча Collector ниже memory_limiter (400 МиБ), RSS ниже лимита контейнера (512 МиБ);
|
||||
3. docker compose start tempo loki: очереди разгружаются, alert resolved. Данные, ждавшие в очереди
|
||||
меньше 5 минут (retry max_elapsed_time), доезжают: трасса и лог загрузки, сделанной во время
|
||||
отказа, находятся. Отброшенное (если очередь переполнилась) посчитано otelcol_exporter_send_failed_*;
|
||||
4. docker compose stop otel-collector на 60 с: API работает (SDK отправляет в фоне и отбрасывает
|
||||
не влезшее в очередь 2048 записей), RSS реплик API не растёт; после запуска телеметрия идёт снова.
|
||||
"""
|
||||
import time
|
||||
|
||||
import obs
|
||||
import ops
|
||||
from filegen import wait_status
|
||||
from helpers import Client, check, run
|
||||
from traffic import Traffic
|
||||
|
||||
RSS = 'max(otelcol_process_memory_rss_bytes)'
|
||||
HEAP = 'max(otelcol_process_runtime_heap_alloc_bytes)'
|
||||
QUEUE = 'sum by (exporter) (otelcol_exporter_queue_size)'
|
||||
CAPACITY = 'max(otelcol_exporter_queue_capacity)'
|
||||
FAILED = ('sum(otelcol_exporter_send_failed_spans_total) + sum(otelcol_exporter_send_failed_log_records_total)'
|
||||
' + sum(otelcol_exporter_send_failed_metric_points_total)')
|
||||
API_RSS = 'max(process_memory_usage_bytes{job="messenger-api"})'
|
||||
MIB = 2 ** 20
|
||||
|
||||
|
||||
def snapshot(started, traffic):
|
||||
queues = {r["metric"].get("exporter", "?").split("/")[-1]: int(r["value"]) for r in obs.prom(QUEUE)}
|
||||
rss, heap = obs.prom_value(RSS, 0) / MIB, obs.prom_value(HEAP, 0) / MIB
|
||||
state = obs.alerts().get("TelemetryExportFailing", "inactive")
|
||||
print(f" t={time.monotonic() - started:5.0f}s collector heap={heap:5.1f} rss={rss:6.1f} MiB queues={queues} "
|
||||
f"send_failed_total={obs.prom_value(FAILED, 0):.0f} TelemetryExportFailing={state:<8} http={traffic.snapshot()}")
|
||||
return max(rss, 0), heap, queues, state
|
||||
|
||||
|
||||
def main():
|
||||
api = Client(timeout=20)
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
traffic = Traffic(api, alice, chat, threads=3, pause=0.3, uploads_every=5).start()
|
||||
started = time.monotonic()
|
||||
capacity = obs.prom_value(CAPACITY, 0)
|
||||
failed_before = obs.prom_value(FAILED, 0)
|
||||
max_rss, max_heap, max_queue = 0.0, 0.0, 0
|
||||
try:
|
||||
time.sleep(15)
|
||||
print(f"1. baseline (exporter queue capacity {capacity:.0f} batches, memory_limiter 400 MiB heap, "
|
||||
"container limit 512 MiB):")
|
||||
snapshot(started, traffic)
|
||||
ops.stop("tempo", "loki")
|
||||
stopped_at = time.monotonic() - started
|
||||
print(f"2. t={stopped_at:.0f}s docker compose stop tempo loki (traces and logs stores)")
|
||||
firing = None
|
||||
while time.monotonic() - started - stopped_at < 180:
|
||||
time.sleep(15)
|
||||
rss, heap, queues, state = snapshot(started, traffic)
|
||||
max_rss, max_heap = max(max_rss, rss), max(max_heap, heap)
|
||||
max_queue = max([max_queue] + list(queues.values()))
|
||||
if state == "firing" and firing is None:
|
||||
firing = time.monotonic() - started
|
||||
during = list(traffic.uploads)
|
||||
check(during, "no uploads during the outage")
|
||||
victim = during[-3][0]
|
||||
ready = wait_status(api, alice, victim, ("ready",), seconds=60)
|
||||
print(f" upload {victim} made during the outage -> {ready['status']} (business path unaffected)")
|
||||
codes = traffic.snapshot()
|
||||
bad = {k: v for k, v in codes.items() if not k.endswith(("201", "202"))}
|
||||
check(not bad, f"business requests failed during the telemetry outage: {bad}")
|
||||
check(max_heap < 400, f"collector heap {max_heap:.0f} MiB exceeded memory_limiter")
|
||||
check(max_rss < 512, f"collector RSS {max_rss:.0f} MiB above the container limit")
|
||||
check(max_queue <= capacity, "exporter queue above its capacity")
|
||||
alert = f"firing at t={firing:.0f}s" if firing else "not firing yet"
|
||||
print(f" during the outage: every business request succeeded {codes}; collector RSS max {max_rss:.0f} MiB "
|
||||
f"(heap max {max_heap:.0f} MiB < 400 MiB limit); exporter queue max {max_queue} of {capacity:.0f} batches; "
|
||||
f"TelemetryExportFailing {alert}")
|
||||
finally:
|
||||
ops.start("tempo", "loki")
|
||||
started_at = time.monotonic() - started
|
||||
print(f"3. t={started_at:.0f}s docker compose start tempo loki")
|
||||
deadline = time.monotonic() + 300
|
||||
while True:
|
||||
time.sleep(15)
|
||||
_rss, _heap, queues, state = snapshot(started, traffic)
|
||||
if not any(queues.values()) and state == "inactive":
|
||||
break
|
||||
check(time.monotonic() < deadline, "queues did not drain / alert did not resolve")
|
||||
print(f" queues drained and TelemetryExportFailing resolved at t={time.monotonic() - started:.0f}s")
|
||||
lost = obs.prom_value(FAILED, 0) - failed_before
|
||||
attachment_id, request_id = during[len(during) // 2]
|
||||
logs = obs.wait_logs(f'{{service_name="messenger-api"}} | request_id="{request_id}"', seconds=120)
|
||||
trace_id, _spans = obs.wait_trace(f'{{ span.messenger.attachment.id = "{attachment_id}" && kind = server }}',
|
||||
seconds=120)
|
||||
print(f" upload {attachment_id} from the middle of the outage: log (X-Request-Id {request_id}) and trace "
|
||||
f"{trace_id} arrived after recovery (they waited in the collector queue); "
|
||||
f"telemetry items dropped by exporters during the run: {lost:.0f}")
|
||||
|
||||
print("4. docker compose stop otel-collector for 60 s (the SDK cannot export at all)")
|
||||
api_rss_before = obs.prom_value(API_RSS, 0) / MIB
|
||||
before = traffic.snapshot()
|
||||
ops.stop("otel-collector")
|
||||
try:
|
||||
time.sleep(60)
|
||||
finally:
|
||||
ops.start("otel-collector")
|
||||
after = traffic.snapshot()
|
||||
delta = {k: after.get(k, 0) - before.get(k, 0) for k in after}
|
||||
bad = {k: v for k, v in delta.items() if v and not k.endswith(("201", "202"))}
|
||||
check(not bad, f"business requests failed while the collector was down: {bad}")
|
||||
time.sleep(30)
|
||||
traffic.stop()
|
||||
api_rss_after = obs.prom_value(API_RSS, 0) / MIB
|
||||
print(f" API answered {delta} while the collector was down (no errors); API replica RSS "
|
||||
f"{api_rss_before:.0f} -> {api_rss_after:.0f} MiB (SDK queues are bounded: 2048 records per signal)")
|
||||
check(api_rss_after < api_rss_before + 60, "API memory grew while the collector was down")
|
||||
print("PASS: telemetry stores and the collector down -> business API unaffected, bounded collector memory and "
|
||||
"queues, delayed telemetry delivered after recovery, drops are counted")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,68 @@
|
||||
"""lab6, уровень 3: persistent volumes хранилищ телеметрии сохраняют историю после перезапуска.
|
||||
|
||||
make telemetry-persistence (= python student-tests/telemetry_persistence.py)
|
||||
|
||||
До перезапуска запоминаются: трасса последней загрузки (Tempo), лог запроса по X-Request-Id (Loki),
|
||||
значение HTTP-счётчика на момент 2 минуты назад (Prometheus). Затем
|
||||
docker compose restart prometheus loki tempo grafana (те же контейнеры и volumes promdata,
|
||||
lokidata, tempodata, grafanadata) — и те же данные находятся снова, dashboard по-прежнему импортирован.
|
||||
"""
|
||||
import time
|
||||
|
||||
import obs
|
||||
import ops
|
||||
from helpers import Client, check, idempotency, run
|
||||
|
||||
COUNTER = 'sum(http_server_request_duration_seconds_count{job="messenger-api"})'
|
||||
|
||||
|
||||
def wait_up(seconds=180):
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
try:
|
||||
obs.prom("up")
|
||||
obs.loki('{service_name="messenger-api"}', minutes=1, limit=1)
|
||||
obs.tempo_search("{ kind = server }", limit=1, minutes=5)
|
||||
return
|
||||
except Exception: # хранилища ещё стартуют
|
||||
check(time.monotonic() < deadline, "telemetry stores did not come back")
|
||||
time.sleep(3)
|
||||
|
||||
|
||||
def main():
|
||||
api = Client(timeout=20)
|
||||
alice, _bob, _eve, chat = api.bootstrap()
|
||||
att, _ = api.attachment(alice, chat)
|
||||
response = api.call("POST", f"/api/v1/chats/{chat['id']}/messages", 201, actor=alice, headers=idempotency(),
|
||||
body={"text": "до перезапуска хранилищ"})
|
||||
request_id = response["headers"]["X-Request-Id"]
|
||||
log_before = obs.wait_logs(f'{{service_name="messenger-api"}} | request_id="{request_id}"')[-1]
|
||||
trace_id, spans = obs.wait_trace(f'{{ span.messenger.attachment.id = "{att["id"]}" && kind = server }}')
|
||||
at = time.time() - 120
|
||||
counter_before = obs.prom_value(COUNTER, at=at)
|
||||
check(counter_before is not None, "no HTTP counter 2 minutes ago: run make test first and wait 2 minutes")
|
||||
print(f"before: trace {trace_id} ({len(spans)} spans), log of X-Request-Id {request_id}, "
|
||||
f"HTTP requests counter at t-120s = {counter_before:.0f}")
|
||||
|
||||
ops.restart("prometheus", "loki", "tempo", "grafana")
|
||||
print("docker compose restart prometheus loki tempo grafana (same containers, volumes kept)")
|
||||
wait_up()
|
||||
|
||||
spans_after = obs.tempo_trace(trace_id)
|
||||
check(len(spans_after) == len(spans), f"trace changed after restart: {len(spans)} -> {len(spans_after)} spans")
|
||||
log_after = obs.wait_logs(f'{{service_name="messenger-api"}} | request_id="{request_id}"', seconds=90)[-1]
|
||||
check(log_after["line"] == log_before["line"], "log line changed after restart")
|
||||
counter_after = obs.prom_value(COUNTER, at=at)
|
||||
check(counter_after == counter_before, f"metric history changed: {counter_before} -> {counter_after}")
|
||||
print(f"after: trace {trace_id} — {len(spans_after)} spans; log found; counter at the same past moment "
|
||||
f"= {counter_after:.0f}")
|
||||
try:
|
||||
dashboard = obs.grafana("/api/dashboards/uid/messenger-lab6")
|
||||
print(f" Grafana: dashboard '{dashboard['dashboard']['title']}' still provisioned")
|
||||
except Exception as exc: # без Grafana (например, проверка только хранилищ) — не ошибка этой проверки
|
||||
print(f" Grafana not checked: {type(exc).__name__}")
|
||||
print("PASS: Prometheus, Loki and Tempo keep their history in volumes across a restart")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -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,290 @@
|
||||
"""lab4–lab5: вложения через API (входит в make student-test; нужен только запущенный стенд).
|
||||
|
||||
С lab5 загрузка отвечает 202 queued, а ready выясняется опросом GET (worker обрабатывает асинхронно).
|
||||
Уровень 3: PNG и JPEG принимаются, после обработки оригинал скачивается побайтно, у каждого
|
||||
вложения ровно один набор вариантов; посторонний получает 404.
|
||||
Варианты по контракту: thumbnail — JPEG, вписан в 256×256 без увеличения (fixture 320×200 ->
|
||||
256×160); crop — JPEG 128×128 (маленькие увеличиваются); optimized — WebP, вписан в 1280×1280
|
||||
без увеличения. Размеры проверяются по самим байтам (заголовки JPEG и WebP), а не только по JSON.
|
||||
Без метаданных: в вариантах нет EXIF (APP1), ICC (APP2), блоков EXIF/XMP/ICCP у WebP.
|
||||
Уровень 4 (lab4, сохранено): слишком большой файл, «бомба» по пикселям, повреждённые файлы,
|
||||
подмена MIME, опасные filename, чужое attachment_id и вложение другого чата — точные коды, без 500.
|
||||
Замечание к MR (lab5): JPEG с ошибками в заголовках (SOS ссылается на компонент, которого нет в SOF,
|
||||
неопределённые таблицы, неверные параметры сканов, RST не по порядку и др.) — 415 сразу, а не 202 -> failed.
|
||||
lab5: failed-вложение нельзя прикрепить (409), его байты — 409; ровно 10 MiB и ровно 40 млн
|
||||
пикселей принимаются, на байт/пиксель больше — 413.
|
||||
"""
|
||||
import hashlib
|
||||
import unittest
|
||||
import uuid
|
||||
from urllib.parse import quote
|
||||
|
||||
from filegen import (PROGRESSIVE_JPEG, RESTART_JPEG, SAMPLE_JPEG, SAMPLE_PNG, bad_filter_png, bomb_png,
|
||||
broken_structure_jpegs, corrupt_crc, garbage_scan_jpeg, gray_png, jpeg_markers, png, png_exact_size,
|
||||
raw_upload, truncated, wait_status, webp_chunks, webp_size)
|
||||
from helpers import Client, idempotency
|
||||
from image_probe import jpeg_size
|
||||
|
||||
MAX = 10 * 1024 * 1024
|
||||
FIXTURE_VARIANTS = {"thumbnail": ("image/jpeg", 256, 160), "crop": ("image/jpeg", 128, 128),
|
||||
"optimized": ("image/webp", 320, 200)}
|
||||
|
||||
|
||||
class AttachmentTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.api = Client(timeout=30)
|
||||
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": "lab5", "member_ids": [creator["id"], other["id"]]})["json"]
|
||||
|
||||
def upload(self, data, ctype="image/png", name="photo.png", expected=202, 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 == 202 else None)
|
||||
|
||||
def ready(self, attachment_id, actor=None):
|
||||
return wait_status(self.api, actor or self.bob, attachment_id, ("ready",))
|
||||
|
||||
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)
|
||||
|
||||
def content(self, attachment_id, variant=None, expected=200, actor=None):
|
||||
suffix = "" if variant is None else "?variant=" + variant
|
||||
return self.api.call("GET", f"/api/v1/attachments/{attachment_id}/content{suffix}", expected,
|
||||
actor=actor or self.bob)
|
||||
|
||||
# ---------- уровень 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"]
|
||||
# 202 — снимок «принято в обработку»: статус queued, вариантов ещё нет.
|
||||
self.assertEqual((att["status"], att["variants"], att["error_code"]), ("queued", [], 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.ready(att["id"])
|
||||
self.assertEqual((meta["status"], meta["error_code"]), ("ready", None))
|
||||
self.assertEqual([v["name"] for v in meta["variants"]], ["thumbnail", "crop", "optimized"])
|
||||
# size_bytes/sha256/content_type по-прежнему описывают ОРИГИНАЛ.
|
||||
self.assertEqual((meta["size_bytes"], meta["sha256"], meta["content_type"]),
|
||||
(att["size_bytes"], att["sha256"], att["content_type"]))
|
||||
got = self.content(att["id"])
|
||||
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", "/content?variant=thumbnail"): # посторонний не узнаёт, что вложение есть
|
||||
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_variants_follow_the_contract(self):
|
||||
att = self.upload(SAMPLE_PNG, name="variants.png")["json"]
|
||||
meta = self.ready(att["id"])
|
||||
for variant in meta["variants"]:
|
||||
name = variant["name"]
|
||||
ctype, width, height = FIXTURE_VARIANTS[name]
|
||||
self.assertEqual((variant["content_type"], variant["width"], variant["height"]), (ctype, width, height))
|
||||
got = self.content(att["id"], name)
|
||||
body = got["bytes"]
|
||||
self.assertEqual(got["headers"].get_content_type(), ctype)
|
||||
self.assertEqual((len(body), hashlib.sha256(body).hexdigest()), (variant["size_bytes"], variant["sha256"]))
|
||||
if ctype == "image/jpeg":
|
||||
self.assertEqual(jpeg_size(body), (width, height)) # реальный размер из заголовка JPEG
|
||||
markers = jpeg_markers(body)
|
||||
self.assertNotIn(0xE1, markers, f"{name}: EXIF/XMP (APP1) must be stripped")
|
||||
self.assertNotIn(0xE2, markers, f"{name}: ICC (APP2) must be stripped")
|
||||
else:
|
||||
self.assertEqual(webp_size(body), (width, height))
|
||||
self.assertFalse({b"EXIF", b"XMP ", b"ICCP"} & set(webp_chunks(body)), "WebP metadata must be stripped")
|
||||
# Маленький JPEG 48×32: thumbnail и optimized не увеличиваются, crop — увеличивается до 128×128.
|
||||
small = self.ready(self.upload(SAMPLE_JPEG, "image/jpeg", "small.jpg")["json"]["id"])
|
||||
sizes = {v["name"]: (v["width"], v["height"]) for v in small["variants"]}
|
||||
self.assertEqual(sizes, {"thumbnail": (48, 32), "crop": (128, 128), "optimized": (48, 32)})
|
||||
print(f"\n fixture 320×200 -> thumbnail 256×160 JPEG, crop 128×128 JPEG, optimized 320×200 WebP; "
|
||||
f"48×32 -> {sizes}")
|
||||
|
||||
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_exact_limits(self):
|
||||
# Ровно 10 485 760 байт и ровно 40 000 000 пикселей — принимаются; на 1 больше — 413.
|
||||
exact = png_exact_size(MAX)
|
||||
self.assertEqual(len(exact), MAX)
|
||||
self.ready(self.upload(exact, name="exact-10mib.png")["json"]["id"])
|
||||
self.upload(png_exact_size(MAX + 1), name="over.png", expected=413)
|
||||
self.ready(self.upload(gray_png(6400, 6250), name="exact-40mp.png")["json"]["id"])
|
||||
self.upload(gray_png(40_000_001, 1), name="over-40mp.png", expected=413)
|
||||
print("\n 10 485 760 байт и 6400×6250 = 40 000 000 px: 202 -> ready; на 1 байт/пиксель больше: 413")
|
||||
|
||||
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"]
|
||||
meta = self.ready(att["id"])
|
||||
got = self.content(att["id"])
|
||||
self.assertEqual(hashlib.sha256(got["bytes"]).hexdigest(), hashlib.sha256(data).hexdigest())
|
||||
sizes = {v["name"]: (v["width"], v["height"]) for v in meta["variants"]}
|
||||
self.assertEqual(sizes, {"thumbnail": (256, 192), "crop": (128, 128), "optimized": (1280, 960)})
|
||||
|
||||
# ---------- уровень 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"), (bad_filter_png(), "image/png"),
|
||||
(SAMPLE_PNG + b"<html>tail</html>", "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_structurally_broken_jpeg_is_415(self):
|
||||
# Замечание к MR: первый SOS ссылался на компонент 250, которого нет в SOF, а API отвечал
|
||||
# 202 (потом failed/invalid_image). Теперь всё, что строгий декодер worker отвергает по
|
||||
# маркерам и заголовкам, отклоняется сразу: 415, в БД и S3 ничего не появляется.
|
||||
for name, data in broken_structure_jpegs():
|
||||
with self.subTest(name):
|
||||
reply = self.upload(data, "image/jpeg", "broken.jpg", expected=415)
|
||||
self.assertEqual(reply["json"]["error"]["code"], "unsupported_media_type")
|
||||
|
||||
def test_valid_jpeg_variants_are_accepted(self):
|
||||
# Обратная сторона: строгая проверка не отклоняет правильные progressive JPEG и JPEG
|
||||
# с маркерами RST — они проходят и доходят до ready с тремя вариантами.
|
||||
for name, data in (("progressive", PROGRESSIVE_JPEG), ("restart-markers", RESTART_JPEG)):
|
||||
with self.subTest(name):
|
||||
att = self.upload(data, "image/jpeg", f"{name}.jpg")["json"]
|
||||
ready = self.ready(att["id"])
|
||||
self.assertEqual(sorted(v["name"] for v in ready["variants"]), ["crop", "optimized", "thumbnail"])
|
||||
self.assertEqual(self.content(att["id"])["bytes"], data)
|
||||
|
||||
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", "c1\u0085.png", "line
break.png", "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)
|
||||
|
||||
def test_broken_scan_becomes_failed_and_cannot_be_attached(self):
|
||||
# Структура JPEG цела (API принимает: 202), но сжатые данные — мусор: worker при строгом
|
||||
# декодировании даёт постоянную ошибку -> failed с invalid_image, без повторов.
|
||||
att = self.upload(garbage_scan_jpeg(), "image/jpeg", "broken.jpg")["json"]
|
||||
failed = wait_status(self.api, self.bob, att["id"], ("failed",))
|
||||
self.assertEqual((failed["error_code"], failed["variants"]), ("invalid_image", []))
|
||||
self.content(att["id"], expected=409)
|
||||
self.content(att["id"], "thumbnail", expected=409)
|
||||
self.post_message({"text": "", "attachment_ids": [att["id"]]}, 409)
|
||||
good = self.upload(SAMPLE_PNG, name="good.png")["json"]["id"]
|
||||
self.post_message({"text": "x", "attachment_ids": [good, att["id"]]}, 409) # одно failed — отказ целиком
|
||||
self.post_message({"text": "x", "attachment_ids": [att["id"], str(uuid.uuid4())]}, 404) # неизвестное — 404
|
||||
|
||||
# ---------- уровень 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"]
|
||||
# Ещё не обработанное (queued/processing) вложение прикреплять можно (lab5).
|
||||
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) # не массив
|
||||
self.post_message({"attachment_ids": [att]}, 400) # нет text
|
||||
self.post_message({"text": None, "attachment_ids": [att]}, 400)
|
||||
self.post_message({"text": "x", "attachment_ids": None}, 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"]
|
||||
self.ready(att)
|
||||
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", actor=self.bob)
|
||||
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)
|
||||
self.api.call("GET", f"/api/v1/attachments/{uuid.uuid4()}", 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,84 @@
|
||||
"""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 aliases, 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")
|
||||
known = set(aliases().values())
|
||||
for instance in served:
|
||||
self.assertIn(instance, known, f"X-Instance-Id {instance} is not a running api replica")
|
||||
print(f"\n 20 x GET /users/me с одним токеном -> реплики {dict(served)}; "
|
||||
f"это alias запущенных реплик api (с lab7 — случайные, не hostname), повторный вход не нужен")
|
||||
|
||||
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,171 @@
|
||||
"""Собственные тесты лимитов входа и запросов (lab7, README уровни 3–4).
|
||||
|
||||
Запуск: make limits-test (входит и в make student-test)
|
||||
|
||||
1. Перебор пароля одного аккаунта: после LOGIN_FAILURES_PER_USER (10) неудачных входов следующий вход
|
||||
получает 429 rate_limited с Retry-After — даже с ВЕРНЫМ паролем. Попытки расходятся по разным
|
||||
репликам (X-Instance-Id), а лимит всё равно срабатывает: счётчик общий (Valkey, rl:*), а не на реплику.
|
||||
Лимит привязан к username: соседний аккаунт входит как обычно (нет «глобальной блокировки»).
|
||||
2. Тело JSON больше MAX_JSON_BODY_BYTES (64 КиБ) -> 413 payload_too_large: и с Content-Length, и
|
||||
chunked (без Content-Length, сервер считает байты сам). Отказ раньше проверки токена.
|
||||
3. Rehash: hash пароля со старыми (слабее текущих) параметрами Argon2id пересчитывается при успешном входе.
|
||||
"""
|
||||
import json
|
||||
import subprocess
|
||||
import unittest
|
||||
import uuid
|
||||
|
||||
from filegen import psql
|
||||
from helpers import ROOT, Client, basic, login
|
||||
from stand import api_containers
|
||||
|
||||
PASSWORD = "Limits-password-123"
|
||||
FAILURES_PER_USER = 10 # LOGIN_FAILURES_PER_USER из .env.example
|
||||
FAILURE_WINDOW = 300 # LOGIN_FAILURE_WINDOW_SECONDS
|
||||
MAX_JSON_BODY = 65536 # MAX_JSON_BODY_BYTES
|
||||
|
||||
# Старые параметры: заведомо слабее текущих (m=19456 КиБ, t=2). Hash строится в контейнере api,
|
||||
# там есть argon2-cffi; код (с тестовым паролем) идёт через stdin, а не аргументом командной строки.
|
||||
WEAK_HASH = """
|
||||
from argon2 import PasswordHasher
|
||||
print(PasswordHasher(time_cost=1, memory_cost=8192, parallelism=1).hash({password!r}))
|
||||
"""
|
||||
|
||||
|
||||
def weak_hash(password):
|
||||
code = WEAK_HASH.format(password=password)
|
||||
result = subprocess.run(["docker", "compose", "exec", "-T", "api", "python", "-"], cwd=ROOT,
|
||||
input=code.encode("utf-8"), capture_output=True)
|
||||
if result.returncode != 0:
|
||||
raise AssertionError("cannot build a weak hash in the api container")
|
||||
return result.stdout.decode().strip()
|
||||
|
||||
|
||||
def stored_hash(user_id):
|
||||
return psql(f"SELECT password_hash FROM users WHERE id = '{uuid.UUID(user_id)}'")
|
||||
|
||||
|
||||
class LimitsTest(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.api = Client()
|
||||
|
||||
def register(self):
|
||||
body = {"username": "l_" + uuid.uuid4().hex[:12], "display_name": "Limits", "password": PASSWORD}
|
||||
user = self.api.call("POST", "/api/v1/users", 201, body=body, schema="User")["json"]
|
||||
return body, user
|
||||
|
||||
# ---------- 1. частота входа ----------
|
||||
|
||||
def test_login_failures_lead_to_429_with_retry_after_across_replicas(self):
|
||||
body, _ = self.register()
|
||||
instances = set()
|
||||
for _ in range(FAILURES_PER_USER):
|
||||
response = self.api.call("POST", "/api/v1/auth/sessions", 401,
|
||||
headers={"Authorization": basic(body["username"], "Wrong-password-000")})
|
||||
instances.add(response["headers"]["X-Instance-Id"])
|
||||
replicas = len(api_containers())
|
||||
if replicas > 1:
|
||||
# Без общего счётчика 10 неудач, разбросанных по репликам, не дали бы 429.
|
||||
self.assertGreater(len(instances), 1, "попытки не разошлись по репликам: проверка общего счётчика пуста")
|
||||
print(f"\n {FAILURES_PER_USER} wrong passwords -> 401, served by {len(instances)} of {replicas} replicas")
|
||||
|
||||
for password in ("Wrong-password-000", body["password"]): # и неверный, и ВЕРНЫЙ пароль
|
||||
limited = self.api.call("POST", "/api/v1/auth/sessions", 429,
|
||||
headers={"Authorization": basic(body["username"], password)})
|
||||
self.assertEqual(limited["json"]["error"]["code"], "rate_limited")
|
||||
retry_after = limited["headers"].get("Retry-After")
|
||||
self.assertIsNotNone(retry_after, "429 без Retry-After")
|
||||
self.assertTrue(retry_after.isdigit(), f"Retry-After должен быть числом секунд: {retry_after!r}")
|
||||
self.assertTrue(1 <= int(retry_after) <= FAILURE_WINDOW, f"Retry-After вне окна: {retry_after}")
|
||||
print(f" next login (even with the right password) -> 429 rate_limited, Retry-After: {retry_after} s")
|
||||
|
||||
def test_limit_is_per_username(self):
|
||||
victim, _ = self.register()
|
||||
neighbour, _ = self.register()
|
||||
for _ in range(FAILURES_PER_USER):
|
||||
login(self.api, victim["username"], "Wrong-password-000", expected=401)
|
||||
login(self.api, victim["username"], victim["password"], expected=429)
|
||||
session = login(self.api, neighbour["username"], neighbour["password"]) # соседа лимит не задел
|
||||
self.assertTrue(session["token"])
|
||||
|
||||
def test_success_resets_failure_counter(self):
|
||||
body, _ = self.register()
|
||||
for _ in range(FAILURES_PER_USER - 1):
|
||||
login(self.api, body["username"], "Wrong-password-000", expected=401)
|
||||
login(self.api, body["username"], body["password"]) # успех сбрасывает счётчик
|
||||
for _ in range(FAILURES_PER_USER - 1):
|
||||
login(self.api, body["username"], "Wrong-password-000", expected=401)
|
||||
login(self.api, body["username"], body["password"]) # снова 9 < 10: вход проходит
|
||||
|
||||
# ---------- 2. размер запроса ----------
|
||||
|
||||
def big_body(self, size=MAX_JSON_BODY + 1024):
|
||||
filler = "x" * size
|
||||
return json.dumps({"username": "big_" + uuid.uuid4().hex[:8], "display_name": filler,
|
||||
"password": PASSWORD}).encode()
|
||||
|
||||
def test_body_over_limit_with_content_length_is_413(self):
|
||||
raw = self.big_body()
|
||||
response = self.api.call("POST", "/api/v1/users", 413, raw=raw,
|
||||
headers={"Content-Type": "application/json", "Content-Length": str(len(raw))})
|
||||
self.assertEqual(response["json"]["error"]["code"], "payload_too_large")
|
||||
print(f"\n POST /users, Content-Length {len(raw)} -> 413 payload_too_large")
|
||||
|
||||
def test_body_over_limit_chunked_is_413(self):
|
||||
raw = self.big_body()
|
||||
chunks = iter([raw[i:i + 8192] for i in range(0, len(raw), 8192)]) # итератор -> Transfer-Encoding: chunked
|
||||
response = self.api.call("POST", "/api/v1/users", 413, raw=chunks, headers={"Content-Type": "application/json"})
|
||||
self.assertEqual(response["json"]["error"]["code"], "payload_too_large")
|
||||
print(f"\n POST /users, chunked {len(raw)} bytes without Content-Length -> 413 payload_too_large")
|
||||
|
||||
def test_big_body_rejected_before_authentication(self):
|
||||
# Без токена: 413, а не 401 — тело отклонено по размеру ещё до проверки Bearer.
|
||||
raw = json.dumps({"text": "x" * (MAX_JSON_BODY + 1)}).encode()
|
||||
path = f"/api/v1/chats/{uuid.uuid4()}/messages"
|
||||
response = self.api.call("POST", path, 413, raw=raw,
|
||||
headers={"Content-Type": "application/json", "Idempotency-Key": uuid.uuid4().hex})
|
||||
self.assertEqual(response["json"]["error"]["code"], "payload_too_large")
|
||||
|
||||
def test_body_under_limit_is_accepted(self):
|
||||
# Граница: тело чуть меньше лимита — не 413 (display_name слишком длинный -> обычная 400 валидации).
|
||||
raw = self.big_body(size=MAX_JSON_BODY - 1024)
|
||||
self.assertLessEqual(len(raw), MAX_JSON_BODY)
|
||||
self.api.call("POST", "/api/v1/users", 400, raw=raw, headers={"Content-Type": "application/json"})
|
||||
|
||||
# ---------- 3. rehash ----------
|
||||
|
||||
def test_old_hash_is_rehashed_on_login(self):
|
||||
body, user = self.register()
|
||||
current = stored_hash(user["id"])
|
||||
self.assertIn("m=19456,t=2", current) # текущие параметры (ARGON2_MEMORY_KIB, ARGON2_ITERATIONS)
|
||||
|
||||
old = weak_hash(body["password"])
|
||||
self.assertIn("m=8192,t=1", old)
|
||||
psql(f"UPDATE users SET password_hash = '{old}' WHERE id = '{uuid.UUID(user['id'])}'")
|
||||
self.assertEqual(stored_hash(user["id"]), old)
|
||||
|
||||
login(self.api, body["username"], body["password"]) # старый hash всё ещё проверяется
|
||||
new = stored_hash(user["id"])
|
||||
self.assertNotEqual(new, old, "hash не пересчитан при входе")
|
||||
self.assertTrue(new.startswith("$argon2id$"))
|
||||
self.assertIn("m=19456,t=2", new)
|
||||
print(f"\n stored hash params: {_params(old)} -> after login {_params(new)}")
|
||||
|
||||
login(self.api, body["username"], body["password"]) # новый hash принимает тот же пароль
|
||||
self.assertEqual(stored_hash(user["id"]), new, "hash с текущими параметрами пересчитывать не нужно")
|
||||
|
||||
def test_wrong_password_does_not_rehash(self):
|
||||
body, user = self.register()
|
||||
old = weak_hash(body["password"])
|
||||
psql(f"UPDATE users SET password_hash = '{old}' WHERE id = '{uuid.UUID(user['id'])}'")
|
||||
login(self.api, body["username"], "Wrong-password-000", expected=401)
|
||||
self.assertEqual(stored_hash(user["id"]), old, "без верного пароля пересчитывать нечего")
|
||||
|
||||
|
||||
def _params(password_hash):
|
||||
return password_hash.split("$")[3] # $argon2id$v=19$m=...,t=...,p=...$соль$hash
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,355 @@
|
||||
"""lab7: TLS-аудит всей матрицы доверия — «кто ты» (contracts/trust-matrix.md, пункты 1–3).
|
||||
|
||||
make tls-matrix (контейнер sectest в сетях edge, backend, otlp, telemetry, vault)
|
||||
|
||||
Для каждой связи матрицы:
|
||||
- правильная identity с нашим CA -> соединение и ответ сервиса (успех);
|
||||
- клиент проверяет СЕРВЕР: пустой/чужой trust store и неверное имя -> ошибка проверки сертификата;
|
||||
- сервер проверяет КЛИЕНТА (где mTLS): без сертификата, сертификат чужого CA (rogue-lb),
|
||||
истёкший (lb-expired) -> отказ в рукопожатии; identity нашего CA, которой связь не разрешена
|
||||
(intruder, worker вместо lb, ...) -> отказ после рукопожатия (закрытие, 403, вход отклонён).
|
||||
Главное: сертификат нашего CA ещё не даёт прав. Пример — API: сертификат worker выдан тем же CA,
|
||||
но реплика пускает только lb (TLS_ALLOWED_CLIENTS, src/messenger/tlsserver.py).
|
||||
|
||||
Каждый отказ должен быть именно ОТКАЗОМ ПРОВЕРКИ: TCP-соединение до сервера есть, а в ответ —
|
||||
TLS alert, неверный сертификат сервера, закрытие после рукопожатия или HTTP 403. «Сервер
|
||||
недоступен» (нет TCP, таймаут) засчитывается как FAIL: такой тест ничего не доказывает.
|
||||
"""
|
||||
import socket
|
||||
import ssl
|
||||
import sys
|
||||
from typing import NamedTuple
|
||||
|
||||
import pika
|
||||
import psycopg
|
||||
|
||||
from matrix import CA, ROGUE_CA, Matrix, bao_login, bao_secret, cert, short
|
||||
|
||||
# Идентичности для отрицательных проверок (scripts/pki.py, secrets/tls-test/).
|
||||
NO_CERT, ROGUE, EXPIRED, INTRUDER = None, "rogue-lb", "lb-expired", "intruder"
|
||||
BAD_CERTS = {"no client cert": NO_CERT, "foreign CA (rogue-lb)": ROGUE, "expired (lb-expired)": EXPIRED}
|
||||
|
||||
|
||||
class Outcome(NamedTuple):
|
||||
kind: str # unreachable | server-cert | tls-refused | closed | reply | http
|
||||
detail: str
|
||||
status: int = 0 # HTTP-статус для kind == "http"
|
||||
|
||||
|
||||
def context(identity: str | None, trust: str = "ours") -> ssl.SSLContext:
|
||||
"""trust: ours — наш CA; rogue — CA атакующего; empty — пустое хранилище."""
|
||||
ctx = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) # check_hostname + CERT_REQUIRED
|
||||
ctx.minimum_version = ssl.TLSVersion.TLSv1_2
|
||||
if trust == "ours":
|
||||
ctx.load_verify_locations(CA)
|
||||
elif trust == "rogue":
|
||||
ctx.load_verify_locations(ROGUE_CA)
|
||||
if identity:
|
||||
ctx.load_cert_chain(*cert(identity))
|
||||
return ctx
|
||||
|
||||
|
||||
def probe(host: str, port: int, identity: str | None = None, trust: str = "ours", name: str | None = None,
|
||||
http: tuple[str, str] | None = ("GET", "/"), send: bytes | None = None, headers: str = "") -> Outcome:
|
||||
"""Одно TLS-подключение. http=(метод, путь) — HTTP/1.1-запрос; send — свои байты (AMQP и т.п.)."""
|
||||
try:
|
||||
raw = socket.create_connection((host, port), timeout=5)
|
||||
except OSError as exc:
|
||||
return Outcome("unreachable", short(exc))
|
||||
try:
|
||||
try:
|
||||
tls = context(identity, trust).wrap_socket(raw, server_hostname=name or host)
|
||||
except ssl.SSLCertVerificationError as exc:
|
||||
return Outcome("server-cert", f"client rejected server cert: {exc.verify_message}")
|
||||
except ssl.SSLError as exc:
|
||||
return Outcome("tls-refused", f"handshake refused: {exc.reason or exc}")
|
||||
except OSError:
|
||||
return Outcome("tls-refused", "closed during handshake")
|
||||
version = tls.version()
|
||||
if http is None and send is None:
|
||||
tls.close()
|
||||
return Outcome("reply", f"handshake ok {version}")
|
||||
if http is not None:
|
||||
method, path = http
|
||||
send = (f"{method} {path} HTTP/1.1\r\nHost: {name or host}\r\n{headers}"
|
||||
f"Content-Length: 0\r\nConnection: close\r\n\r\n").encode()
|
||||
try:
|
||||
tls.sendall(send)
|
||||
data = tls.recv(4096)
|
||||
except ssl.SSLError as exc: # TLS 1.3: отказ клиентскому сертификату приходит после рукопожатия
|
||||
return Outcome("tls-refused", f"server alert: {exc.reason or exc}")
|
||||
except OSError:
|
||||
return Outcome("closed", f"{version} ok, then closed by server")
|
||||
finally:
|
||||
tls.close()
|
||||
if not data:
|
||||
return Outcome("closed", f"{version} ok, then closed by server")
|
||||
if http is not None and data.startswith(b"HTTP/"):
|
||||
status = int(data.split()[1])
|
||||
return Outcome("http", f"{version} HTTP {status}", status)
|
||||
return Outcome("reply", f"{version} ok, server answered")
|
||||
finally:
|
||||
raw.close()
|
||||
|
||||
|
||||
def plain(host: str, port: int, payload: bytes) -> Outcome:
|
||||
"""Без TLS: открытого порта у сервиса быть не должно (или он отвечает отказом)."""
|
||||
try:
|
||||
with socket.create_connection((host, port), timeout=5) as sock:
|
||||
sock.sendall(payload)
|
||||
data = sock.recv(512)
|
||||
except OSError as exc:
|
||||
return Outcome("closed", f"plaintext: {short(exc)}")
|
||||
if not data:
|
||||
return Outcome("closed", "plaintext: closed by server")
|
||||
first = data.split(b"\r\n")[0][:40].decode("latin-1")
|
||||
if data.startswith(b"HTTP/"):
|
||||
return Outcome("http", f"plaintext: {first}", int(data.split()[1]))
|
||||
return Outcome("reply", f"plaintext answered: {first!r}")
|
||||
|
||||
|
||||
# ---------- ожидания ----------
|
||||
|
||||
def ok_http(outcome: Outcome, statuses=(200,)) -> bool:
|
||||
return outcome.kind == "http" and outcome.status in statuses
|
||||
|
||||
|
||||
def refused(outcome: Outcome) -> bool:
|
||||
"""Отказ проверки (не «недоступен»): TLS alert, закрытие после рукопожатия или 403."""
|
||||
return outcome.kind in ("tls-refused", "closed") or (outcome.kind == "http" and outcome.status == 403)
|
||||
|
||||
|
||||
def server_rejected(outcome: Outcome) -> bool:
|
||||
return outcome.kind == "server-cert"
|
||||
|
||||
|
||||
def server_checks(m: Matrix, who: str, host: str, port: int, name: str, http=("GET", "/")):
|
||||
"""Клиент проверяет сервер: чужой/пустой trust store и неверное имя -> ошибка проверки сертификата."""
|
||||
for trust, label in (("empty", "empty trust store"), ("rogue", "foreign CA trust store")):
|
||||
result = probe(host, port, trust=trust, name=name, http=http)
|
||||
m.row(who, f"{label} -> server cert", "verify-err", result.detail, server_rejected(result))
|
||||
result = probe(host, port, name="wrong-name.invalid", http=http)
|
||||
m.row(who, f"wrong hostname (not {name})", "verify-err", result.detail, server_rejected(result))
|
||||
|
||||
|
||||
def client_checks(m: Matrix, target: str, host: str, port: int, name: str, http=("GET", "/"),
|
||||
send: bytes | None = None, intruders=(INTRUDER,), headers: str = ""):
|
||||
"""Сервер проверяет клиента: без сертификата / чужой CA / истёкший / не та identity -> отказ."""
|
||||
for label, identity in list(BAD_CERTS.items()) + [(f"our CA, identity {i}", i) for i in intruders]:
|
||||
result = probe(host, port, identity, name=name, http=http, send=send, headers=headers)
|
||||
m.row(label.split(" (")[0] if identity is None else identity, f"-> {target}", "refuse", result.detail,
|
||||
refused(result))
|
||||
|
||||
|
||||
# ---------- связи матрицы ----------
|
||||
|
||||
def client_to_lb(m: Matrix):
|
||||
m.section("1. client -> lb:8443 (external TLS; client verifies server identity lb)")
|
||||
for name in ("lb",):
|
||||
result = probe("lb", 8443, name=name, http=("GET", "/health/ready"))
|
||||
m.row("client", f"our CA, hostname {name}, GET /health/ready", "200", result.detail, ok_http(result))
|
||||
server_checks(m, "client", "lb", 8443, "lb", http=("GET", "/health/ready"))
|
||||
m.row("client", "plaintext HTTP on :8443", "refuse", (r := plain("lb", 8443, b"GET / HTTP/1.1\r\n\r\n")).detail,
|
||||
r.kind != "http" or r.status >= 400)
|
||||
|
||||
|
||||
def lb_to_api(m: Matrix):
|
||||
m.section("2. lb -> api:8080 (mTLS; replica allows ONLY identity lb, CRL checked)")
|
||||
replicas = sorted({info[4][0] for info in socket.getaddrinfo("api", 8080, type=socket.SOCK_STREAM)})
|
||||
m.row("dns", "api replicas", ">=1", ", ".join(replicas) or "-", bool(replicas))
|
||||
for ip in replicas:
|
||||
target = f"api@{ip}"
|
||||
result = probe(ip, 8080, "lb", name="api", http=("GET", "/health/ready"))
|
||||
m.row("lb", f"-> {target} GET /health/ready", "200", result.detail, ok_http(result))
|
||||
# Реплика предъявляет identity api: если ждать от неё lb — проверка имени не проходит.
|
||||
result = probe(ip, 8080, "lb", name="lb", http=("GET", "/health/ready"))
|
||||
m.row("lb", f"-> {target} expecting name lb", "verify-err", result.detail, server_rejected(result))
|
||||
# Сертификат нашего CA — но не lb: worker, api, grafana, intruder. Всех — отказ.
|
||||
client_checks(m, target, ip, 8080, "api", http=("GET", "/health/ready"),
|
||||
intruders=(INTRUDER, "worker", "api", "grafana", "otel-collector"))
|
||||
|
||||
|
||||
def api_to_collector(m: Matrix):
|
||||
m.section("3. api/worker -> otel-collector:4318 (mTLS gateway otlp-gw; allowlist CN api, worker)")
|
||||
request = ("POST", "/v1/metrics")
|
||||
headers = "Content-Type: application/x-protobuf\r\n"
|
||||
for identity in ("api", "worker"):
|
||||
result = probe("otel-collector", 4318, identity, http=request, headers=headers)
|
||||
m.row(identity, "-> otel-collector POST /v1/metrics", "200", result.detail, ok_http(result))
|
||||
server_checks(m, "api", "otel-collector", 4318, "otel-collector", http=request)
|
||||
client_checks(m, "otel-collector", "otel-collector", 4318, "otel-collector", http=request, headers=headers,
|
||||
intruders=(INTRUDER, "lb", "grafana", "prometheus"))
|
||||
# Сам Collector слушает только 127.0.0.1:14318 общего namespace — из сети в обход шлюза не попасть.
|
||||
try:
|
||||
socket.create_connection(("otel-collector", 14318), timeout=3).close()
|
||||
bypass = Outcome("reply", "port 14318 open")
|
||||
except OSError:
|
||||
bypass = Outcome("closed", "port 14318 closed")
|
||||
m.row("any", "bypass gateway: otel-collector:14318", "closed", bypass.detail, bypass.kind == "closed")
|
||||
|
||||
|
||||
def telemetry_backends(m: Matrix):
|
||||
m.section("4. otel-collector / grafana -> prometheus, loki, tempo (mTLS)")
|
||||
# buildinfo, а не /ready: проверяется транспорт, а не прогрев ring/ingester (там бывает 503).
|
||||
# У каждого хранилища свой список разрешённых identity (contracts/trust-matrix.md):
|
||||
# prometheus и loki — otel-collector (пишет) и grafana (читает); tempo:3200 (API запросов) читает
|
||||
# только grafana, tempo:4318 (приём OTLP) пишет только otel-collector.
|
||||
backends = [("prometheus", 9090, "/-/ready", ("otel-collector", "grafana")),
|
||||
("loki", 3100, "/loki/api/v1/status/buildinfo", ("otel-collector", "grafana")),
|
||||
("tempo", 3200, "/api/status/buildinfo", ("grafana",))]
|
||||
for host, port, path, allowed in backends:
|
||||
for identity in allowed:
|
||||
result = probe(host, port, identity, http=("GET", path))
|
||||
m.row(identity, f"-> {host}:{port} GET {path}", "200", result.detail, ok_http(result))
|
||||
server_checks(m, allowed[0], host, port, host, http=("GET", path))
|
||||
# Любая другая identity нашего CA (intruder, api, lb и не разрешённая здесь из пары
|
||||
# otel-collector/grafana) должна получить отказ.
|
||||
refused = tuple(i for i in ("otel-collector", "grafana") if i not in allowed)
|
||||
client_checks(m, f"{host}:{port}", host, port, host, http=("GET", path),
|
||||
intruders=(INTRUDER, "api", "lb") + refused)
|
||||
# Приём OTLP у Tempo: пишет только Collector, grafana тоже должна получить отказ.
|
||||
result = probe("tempo", 4318, "otel-collector", http=("POST", "/v1/traces"),
|
||||
headers="Content-Type: application/x-protobuf\r\n")
|
||||
m.row("otel-collector", "-> tempo:4318 POST /v1/traces", "200", result.detail, ok_http(result))
|
||||
client_checks(m, "tempo:4318", "tempo", 4318, "tempo", http=("POST", "/v1/traces"),
|
||||
headers="Content-Type: application/x-protobuf\r\n", intruders=(INTRUDER, "api", "lb", "grafana"))
|
||||
|
||||
|
||||
def to_openbao(m: Matrix):
|
||||
m.section("5. api/worker -> openbao:8200 (TLS + cert auth: role accepts only CN api / worker)")
|
||||
result = probe("openbao", 8200, "api", http=("GET", "/v1/sys/health"))
|
||||
m.row("api", "-> openbao GET /v1/sys/health", "200", result.detail, ok_http(result))
|
||||
server_checks(m, "api", "openbao", 8200, "openbao", http=("GET", "/v1/sys/health"))
|
||||
# Listener OpenBao клиентский сертификат только запрашивает (tls_require_and_verify_client_cert не
|
||||
# включён: оператор ходит с root token без сертификата). Проверяет его cert auth при входе: цепочка
|
||||
# до нашего CA, срок, CN из allowed_common_names роли. Поэтому отказ здесь — на login, а не в TLS.
|
||||
for identity, role in ((None, "messenger-api"), (ROGUE, "messenger-api"), (EXPIRED, "messenger-api"),
|
||||
(INTRUDER, "messenger-api"), ("lb", "messenger-worker"), ("worker", "messenger-api")):
|
||||
error = ""
|
||||
try:
|
||||
status, payload = bao_login(identity, role)
|
||||
error = (payload.get("errors") or [""])[0].replace("\n", " ")
|
||||
outcome = Outcome("http", f"login HTTP {status}" + (f": {error[:60]}" if error else ""), status)
|
||||
except ssl.SSLError as exc:
|
||||
outcome = Outcome("tls-refused", f"handshake refused: {exc.reason}")
|
||||
# Истёкший сертификат OpenBao 2.4 отклоняет с HTTP 500 ("certificate has expired"): токена нет,
|
||||
# но 500 засчитываем только с такой причиной — иначе это мог быть просто сбой сервиса.
|
||||
ok = outcome.kind == "tls-refused" or (outcome.kind == "http" and (
|
||||
outcome.status in (400, 403) or (outcome.status == 500 and "certificate has expired" in error)))
|
||||
m.row(identity or "no client cert", f"-> openbao login role {role}", "refuse", outcome.detail, ok)
|
||||
for identity in ("api", "worker"):
|
||||
status, _ = bao_login(identity, f"messenger-{identity}")
|
||||
m.row(identity, f"-> openbao login role messenger-{identity}", "200", f"login HTTP {status}", status == 200)
|
||||
|
||||
|
||||
AMQP_HEADER = b"AMQP\x00\x00\x09\x01"
|
||||
|
||||
|
||||
def broker_login(identity: str) -> Outcome:
|
||||
ctx = context(identity)
|
||||
params = pika.ConnectionParameters(host="broker", port=5671, virtual_host="messenger",
|
||||
credentials=pika.credentials.ExternalCredentials(),
|
||||
ssl_options=pika.SSLOptions(ctx, server_hostname="broker"),
|
||||
connection_attempts=1, socket_timeout=5)
|
||||
try:
|
||||
pika.BlockingConnection(params).close()
|
||||
return Outcome("reply", "SASL EXTERNAL login ok")
|
||||
except (pika.exceptions.ProbableAuthenticationError, pika.exceptions.ProbableAccessDeniedError,
|
||||
pika.exceptions.AuthenticationError) as exc:
|
||||
return Outcome("closed", f"login refused: {type(exc).__name__}")
|
||||
except pika.exceptions.AMQPError as exc:
|
||||
return Outcome("unreachable", short(exc))
|
||||
|
||||
|
||||
def to_broker(m: Matrix):
|
||||
m.section("6. api/worker -> broker:5671 (mTLS + SASL EXTERNAL: user = certificate CN)")
|
||||
for identity in ("api", "worker"):
|
||||
result = broker_login(identity)
|
||||
m.row(identity, "-> broker login", "allow", result.detail, result.kind == "reply")
|
||||
server_checks(m, "api", "broker", 5671, "broker", http=None)
|
||||
for label, identity in BAD_CERTS.items():
|
||||
result = probe("broker", 5671, identity, name="broker", http=None, send=AMQP_HEADER)
|
||||
m.row(label.split(" (")[0] if identity is None else identity, "-> broker (TLS)", "refuse",
|
||||
result.detail, refused(result))
|
||||
# Сертификат нашего CA с CN, которого нет среди пользователей брокера: TLS проходит, вход — нет.
|
||||
for identity in (INTRUDER, "lb", "grafana"):
|
||||
result = broker_login(identity)
|
||||
m.row(identity, "-> broker login", "refuse", result.detail, result.kind == "closed")
|
||||
try:
|
||||
socket.create_connection(("broker", 5672), timeout=3).close()
|
||||
result = Outcome("reply", "5672 open")
|
||||
except OSError:
|
||||
result = Outcome("closed", "5672 closed")
|
||||
m.row("any", "plaintext AMQP broker:5672", "closed", result.detail, result.kind == "closed")
|
||||
|
||||
|
||||
def to_postgres(m: Matrix, secrets: dict):
|
||||
m.section("7. api/worker -> postgres:5432 (TLS verify-full, hostssl only, SCRAM)")
|
||||
|
||||
def connect(user, password, host="postgres", **tls):
|
||||
options = {"sslmode": "verify-full", "sslrootcert": CA} | tls
|
||||
try:
|
||||
with psycopg.connect(host=host, port=5432, dbname="messenger", user=user, password=password,
|
||||
connect_timeout=5, **options) as conn:
|
||||
version = conn.execute("SELECT version FROM pg_stat_ssl WHERE pid = pg_backend_pid()").fetchone()
|
||||
return True, f"connected, {version[0] if version else 'no TLS?'}"
|
||||
except psycopg.OperationalError as exc:
|
||||
text = str(exc)
|
||||
for marker, label in (("does not match host name", "hostname mismatch"),
|
||||
("certificate verify failed", "server cert verify failed"),
|
||||
("no encryption", "pg_hba: no encryption -> reject"),
|
||||
("pg_hba.conf rejects", "pg_hba reject")):
|
||||
if marker in text:
|
||||
return False, label
|
||||
return False, short(exc)
|
||||
|
||||
for identity, role in (("api", "messenger_api"), ("worker", "messenger_worker")):
|
||||
ok, detail = connect(role, secrets[identity]["db_password"])
|
||||
m.row(identity, f"-> postgres as {role} (verify-full)", "allow", detail, ok and "TLS" in detail)
|
||||
password = secrets["api"]["db_password"]
|
||||
ok, detail = connect("messenger_api", password, sslmode="disable", sslrootcert="")
|
||||
m.row("api", "-> postgres without TLS (right password)", "refuse", detail, not ok and "pg_hba" in detail)
|
||||
ok, detail = connect("messenger_api", password, sslrootcert=ROGUE_CA)
|
||||
m.row("api", "-> postgres, foreign CA trust store", "verify-err", detail, not ok and "verify" in detail)
|
||||
ip = socket.gethostbyname("postgres")
|
||||
ok, detail = connect("messenger_api", password, host=ip)
|
||||
m.row("api", f"-> postgres by IP {ip} (name != SAN)", "verify-err", detail, not ok and "hostname" in detail)
|
||||
|
||||
|
||||
def to_valkey(m: Matrix):
|
||||
m.section("8. api -> valkey:6379 (TLS; identity = ACL user, checked in acl_matrix.py)")
|
||||
result = probe("valkey", 6379, http=None, send=b"PING\r\n")
|
||||
m.row("api", "-> valkey TLS, PING without AUTH", "NOAUTH", result.detail, result.kind == "reply")
|
||||
server_checks(m, "api", "valkey", 6379, "valkey", http=None)
|
||||
result = plain("valkey", 6379, b"PING\r\n")
|
||||
m.row("api", "-> valkey plaintext PING", "refuse", result.detail, result.kind == "closed")
|
||||
|
||||
|
||||
def to_s3(m: Matrix):
|
||||
m.section("9. api/worker -> s3:9000 (HTTPS; identity = S3 keys, checked in acl_matrix.py)")
|
||||
result = probe("s3", 9000, http=("GET", "/healthz"))
|
||||
m.row("api", "-> s3 GET /healthz", "200", result.detail, ok_http(result))
|
||||
server_checks(m, "api", "s3", 9000, "s3", http=("GET", "/healthz"))
|
||||
result = plain("s3", 9000, b"GET /healthz HTTP/1.1\r\nHost: s3\r\n\r\n")
|
||||
m.row("api", "-> s3 plaintext HTTP", "refuse", result.detail, result.kind != "http" or result.status >= 400)
|
||||
|
||||
|
||||
def main() -> int:
|
||||
socket.setdefaulttimeout(10)
|
||||
m = Matrix("TLS matrix (lab7): who may connect where")
|
||||
client_to_lb(m)
|
||||
lb_to_api(m)
|
||||
api_to_collector(m)
|
||||
telemetry_backends(m)
|
||||
to_openbao(m)
|
||||
to_broker(m)
|
||||
secrets = {identity: bao_secret(identity) for identity in ("api", "worker")}
|
||||
to_postgres(m, secrets)
|
||||
to_valkey(m)
|
||||
to_s3(m)
|
||||
print("\n## 10. replication / cluster channels: N/A (single node PostgreSQL, Valkey, broker, OpenBao)")
|
||||
return m.finish()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,73 @@
|
||||
"""lab6: фоновая нагрузка для инцидентов — несколько потоков пишут сообщения (и по желанию грузят картинки).
|
||||
|
||||
Нагрузка честная для наблюдения: ошибки не повторяются прозрачно, каждый ответ (код или таймаут)
|
||||
считается. Токены живут только в памяти и не печатаются.
|
||||
"""
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
from helpers import ROOT, Client
|
||||
|
||||
SAMPLE = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
|
||||
|
||||
class Traffic:
|
||||
def __init__(self, api: Client, actor: dict, chat: dict, threads: int = 3, pause: float = 0.2,
|
||||
uploads_every: float = 0.0, timeout: float = 15.0):
|
||||
self.base, self.token, self.chat = api.base, actor["token"], chat["id"]
|
||||
self.threads, self.pause, self.uploads_every, self.timeout = threads, pause, uploads_every, timeout
|
||||
self.stop_event = threading.Event()
|
||||
self.lock = threading.Lock()
|
||||
self.codes = Counter()
|
||||
self.uploads = [] # (attachment_id, X-Request-Id)
|
||||
self._workers = []
|
||||
|
||||
def _request(self, method, path, data, headers):
|
||||
headers = dict(headers, Authorization="Bearer " + self.token)
|
||||
request = urllib.request.Request(self.base + path, data=data, method=method, headers=headers)
|
||||
try:
|
||||
with urllib.request.urlopen(request, timeout=self.timeout) as response:
|
||||
return response.status, response.read(), response.headers
|
||||
except urllib.error.HTTPError as exc:
|
||||
return exc.code, exc.read(), exc.headers
|
||||
except (urllib.error.URLError, TimeoutError, OSError):
|
||||
return "timeout", b"", {}
|
||||
|
||||
def _loop(self, number):
|
||||
last_upload = time.monotonic()
|
||||
while not self.stop_event.is_set():
|
||||
body = json.dumps({"text": f"нагрузка {number} {uuid.uuid4().hex[:6]}"}).encode()
|
||||
status, _, _ = self._request("POST", f"/api/v1/chats/{self.chat}/messages", body,
|
||||
{"Content-Type": "application/json", "Idempotency-Key": uuid.uuid4().hex})
|
||||
with self.lock:
|
||||
self.codes[str(status)] += 1
|
||||
if number == 0 and self.uploads_every and time.monotonic() - last_upload >= self.uploads_every:
|
||||
last_upload = time.monotonic()
|
||||
status, raw, headers = self._request("POST", f"/api/v1/chats/{self.chat}/attachments?filename=load.png",
|
||||
SAMPLE, {"Content-Type": "image/png"})
|
||||
with self.lock:
|
||||
self.codes["upload " + str(status)] += 1
|
||||
if status == 202:
|
||||
self.uploads.append((json.loads(raw)["id"], headers.get("X-Request-Id")))
|
||||
self.stop_event.wait(self.pause)
|
||||
|
||||
def start(self):
|
||||
for number in range(self.threads):
|
||||
thread = threading.Thread(target=self._loop, args=(number,), daemon=True)
|
||||
thread.start()
|
||||
self._workers.append(thread)
|
||||
return self
|
||||
|
||||
def stop(self):
|
||||
self.stop_event.set()
|
||||
for thread in self._workers:
|
||||
thread.join(timeout=self.timeout + 5)
|
||||
|
||||
def snapshot(self) -> dict:
|
||||
with self.lock:
|
||||
return dict(self.codes)
|
||||
@@ -0,0 +1,165 @@
|
||||
"""lab4 (с lab5 — с ответом 202): эксперимент — ≥10 одновременных загрузок и пик памяти реплик API.
|
||||
|
||||
make upload-memory (= python student-tests/upload_memory.py [--count 12])
|
||||
|
||||
Гипотеза: память реплики почти не растёт с числом одновременных загрузок, потому что
|
||||
(1) тело читается кусками и в памяти держится не больше 1 МиБ на загрузку (остальное во временном
|
||||
файле), (2) с lab5 API картинку не декодирует, а только проверяет структуру потоком (по 1 МиБ),
|
||||
декодирует worker в отдельном процессе, (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, wait_status
|
||||
from helpers import ROOT, Client, check, run
|
||||
from stand import alias_of, 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, 202, 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 после обработки worker скачиваются вторым участником без изменений.
|
||||
for (_s, _inst, att_id), data in zip(results_a, images):
|
||||
wait_status(api, bob, att_id, seconds=180)
|
||||
got = api.call("GET", f"/api/v1/attachments/{att_id}/content", actor=bob)["bytes"]
|
||||
check(got == data, "downloaded file differs")
|
||||
|
||||
rows = []
|
||||
by_alias = {container: alias_of(container) for container in containers}
|
||||
for c in containers:
|
||||
served = sum(1 for r in results_a if by_alias[c] == 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", "structure_checks_concurrency": 2,
|
||||
"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} с, все 202, 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)
|
||||
@@ -0,0 +1,357 @@
|
||||
"""lab5: обработка картинок worker (imaging.py, sandbox.py) — проверки внутри образа (там есть Pillow).
|
||||
|
||||
make imaging-test == docker compose --profile tools run --rm imaging-test
|
||||
|
||||
Уровень 3–4 (contracts/README.md, «Фоновая обработка»):
|
||||
- геометрия: thumbnail вписан в 256×256 без увеличения, размеры вниз, минимум 1 px (320×200 -> 256×160);
|
||||
crop — центральный квадрат 128×128 (маленькие увеличиваются); optimized — WebP в 1280×1280 без увеличения;
|
||||
- EXIF-ориентация применяется (фото «на боку» в вариантах стоит правильно);
|
||||
- прозрачность накладывается на белый в JPEG, а WebP её сохраняет;
|
||||
- EXIF, GPS, XMP и ICC-профиль в варианты не попадают;
|
||||
- 16-битные, палитровые, CMYK-картинки обрабатываются;
|
||||
- одинаковый вход даёт одинаковые байты (повтор задания идемпотентен);
|
||||
- лимиты worker: пиксели (до декодирования), память (RLIMIT_AS дочернего процесса), время (SIGKILL).
|
||||
Замечание к MR: проверка структуры JPEG в API (images.py) сверяется здесь с настоящим декодером
|
||||
worker (libjpeg-turbo в строгом режиме, та же версия, что в образе):
|
||||
- случайные повреждения заголовков: если API файл пропустил, декодер может споткнуться только
|
||||
о сжатые данные скана (их без декодирования не проверить), но не о заголовки; если декодер
|
||||
файл целиком принял, API его тоже не отклоняет;
|
||||
- полный перебор коэффициентов субдискретизации: API и TurboJPEG принимают одни и те же схемы.
|
||||
"""
|
||||
import hashlib
|
||||
import io
|
||||
import itertools
|
||||
import os
|
||||
import random
|
||||
import struct
|
||||
import tempfile
|
||||
import time
|
||||
import unittest
|
||||
import warnings
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
import simplejpeg
|
||||
from PIL import Image, ImageCms, ImageOps
|
||||
|
||||
from messenger import images, imaging, sandbox
|
||||
|
||||
FIXTURE = Path(__file__).resolve().parents[2] / "tests" / "fixtures" / "sample.png"
|
||||
|
||||
|
||||
def _chunk(kind, data):
|
||||
return struct.pack(">I", len(data)) + kind + data + struct.pack(">I", zlib.crc32(kind + data) & 0xFFFFFFFF)
|
||||
|
||||
|
||||
def big_rgba_png(width, height):
|
||||
"""Большой RGBA PNG без Pillow (нули сжимаются в килобайты), чтобы проверить лимиты памяти."""
|
||||
compressor = zlib.compressobj(1)
|
||||
row = b"\x00" + bytes(width * 4)
|
||||
data = b"".join(compressor.compress(row) for _ in range(height)) + compressor.flush()
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 6, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + _chunk(b"IHDR", ihdr) + _chunk(b"IDAT", data) + _chunk(b"IEND", b"")
|
||||
|
||||
|
||||
# ---------- JPEG по сегментам (для сверки проверки API с декодером) ----------
|
||||
|
||||
def jpeg_parts(data):
|
||||
"""JPEG -> [("seg", маркер, данные) | ("scan", заголовок SOS, сжатые данные) | ("eoi", хвост)]."""
|
||||
i, parts = 2, []
|
||||
while True:
|
||||
marker = data[i + 1]
|
||||
i += 2
|
||||
if marker == 0xD9:
|
||||
parts.append(("eoi", data[i:]))
|
||||
return parts
|
||||
length = int.from_bytes(data[i:i + 2], "big")
|
||||
payload, i = data[i + 2:i + length], i + length
|
||||
if marker != 0xDA:
|
||||
parts.append(("seg", marker, payload))
|
||||
continue
|
||||
j = i
|
||||
while data[j] != 0xFF or data[j + 1] == 0x00 or 0xD0 <= data[j + 1] <= 0xD7:
|
||||
j += 1
|
||||
parts.append(("scan", payload, data[i:j]))
|
||||
i = j
|
||||
|
||||
|
||||
def jpeg_join(parts):
|
||||
out = bytearray(b"\xff\xd8")
|
||||
for part in parts:
|
||||
if part[0] == "seg":
|
||||
out += bytes([0xFF, part[1]]) + struct.pack(">H", len(part[2]) + 2) + part[2]
|
||||
elif part[0] == "scan":
|
||||
out += b"\xff\xda" + struct.pack(">H", len(part[1]) + 2) + part[1] + part[2]
|
||||
else:
|
||||
out += b"\xff\xd9" + part[1]
|
||||
return bytes(out)
|
||||
|
||||
|
||||
def gradient_jpeg(mode="RGB", size=(48, 32), **options):
|
||||
image = Image.new(mode, size)
|
||||
pixels = image.load()
|
||||
for y in range(size[1]):
|
||||
for x in range(size[0]):
|
||||
value = (x * 7 + y * 13) % 256
|
||||
pixels[x, y] = value if mode == "L" else tuple((value + k * 60) % 256 for k in range(len(mode)))
|
||||
out = io.BytesIO()
|
||||
image.save(out, "JPEG", **options)
|
||||
return out.getvalue()
|
||||
|
||||
|
||||
def api_verdict(data):
|
||||
"""Что ответит API: accept или причина 415 (images.inspect без HTTP)."""
|
||||
try:
|
||||
width, height = images._header_size(io.BytesIO(data), "JPEG")
|
||||
images.check_jpeg(data, width, height)
|
||||
return "accept"
|
||||
except Exception as exc: # UnsupportedMediaType / Broken
|
||||
return f"reject: {exc}"
|
||||
|
||||
|
||||
def worker_verdict(data):
|
||||
"""Что скажет worker: строгий libjpeg-turbo (как imaging._strict_jpeg_check) и Pillow."""
|
||||
try:
|
||||
_h, _w, colorspace, _sub = simplejpeg.decode_jpeg_header(data)
|
||||
target = "CMYK" if colorspace in ("CMYK", "YCCK") else ("GRAY" if colorspace == "Gray" else "RGB")
|
||||
simplejpeg.decode_jpeg(data, colorspace=target, strict=True, min_factor=8)
|
||||
with warnings.catch_warnings():
|
||||
warnings.simplefilter("ignore")
|
||||
with Image.open(io.BytesIO(data)) as image:
|
||||
image.load()
|
||||
except Exception as exc:
|
||||
return str(exc)
|
||||
return "ok"
|
||||
|
||||
|
||||
# Ошибки, которые libjpeg находит только внутри сжатых данных скана (без декодирования не проверить):
|
||||
# неверный код Хаффмана, данные кончились раньше блоков, лишние байты в конце данных,
|
||||
# RST не на границе интервала.
|
||||
ENTROPY_ERRORS = ("bad Huffman code", "premature end of data segment", "extraneous bytes before marker",
|
||||
"instead of RST")
|
||||
|
||||
|
||||
class ImagingTest(unittest.TestCase):
|
||||
def setUp(self):
|
||||
self.tmp = tempfile.TemporaryDirectory()
|
||||
self.dir = self.tmp.name
|
||||
|
||||
def tearDown(self):
|
||||
self.tmp.cleanup()
|
||||
|
||||
def save(self, image, fmt, **kwargs):
|
||||
path = os.path.join(self.dir, f"in-{len(os.listdir(self.dir))}.{fmt.lower()}")
|
||||
image.save(path, fmt, **kwargs)
|
||||
return path
|
||||
|
||||
def run_variants(self, path, content_type, params=imaging.Params()):
|
||||
out = os.path.join(self.dir, f"out-{len(os.listdir(self.dir))}")
|
||||
result = imaging.process(path, out, content_type, params)
|
||||
return {v["name"]: v for v in result["variants"]}
|
||||
|
||||
def opened(self, variant):
|
||||
img = Image.open(variant["path"])
|
||||
img.load()
|
||||
return img
|
||||
|
||||
def test_fixture_variants(self):
|
||||
variants = self.run_variants(str(FIXTURE), "image/png")
|
||||
expected = {"thumbnail": ("JPEG", (256, 160)), "crop": ("JPEG", (128, 128)), "optimized": ("WEBP", (320, 200))}
|
||||
for name, (fmt, size) in expected.items():
|
||||
img = self.opened(variants[name])
|
||||
self.assertEqual((img.format, img.size), (fmt, size), name)
|
||||
self.assertEqual((variants[name]["width"], variants[name]["height"]), size)
|
||||
self.assertEqual(variants[name]["size_bytes"], os.path.getsize(variants[name]["path"]))
|
||||
print("\n fixture 320×200 -> thumbnail JPEG 256×160, crop JPEG 128×128, optimized WebP 320×200")
|
||||
|
||||
def test_geometry(self):
|
||||
cases = {(3000, 1000): ((256, 85), (1280, 426)), (1000, 3000): ((85, 256), (426, 1280)),
|
||||
(10, 5): ((10, 5), (10, 5)), (5000, 10): ((256, 1), (1280, 2)),
|
||||
(256, 256): ((256, 256), (256, 256)), (257, 256): ((256, 255), (257, 256)),
|
||||
(2000, 1999): ((256, 255), (1280, 1279))}
|
||||
for (w, h), (thumb, optimized) in cases.items():
|
||||
with self.subTest(size=(w, h)):
|
||||
variants = self.run_variants(self.save(Image.new("RGB", (w, h), (90, 120, 150)), "PNG"), "image/png")
|
||||
self.assertEqual(self.opened(variants["thumbnail"]).size, thumb)
|
||||
self.assertEqual(self.opened(variants["optimized"]).size, optimized)
|
||||
self.assertEqual(self.opened(variants["crop"]).size, (128, 128)) # маленькие увеличиваются
|
||||
|
||||
def test_exif_orientation_is_applied(self):
|
||||
img = Image.new("RGB", (400, 200), (0, 0, 255))
|
||||
img.paste((255, 0, 0), (0, 0, 200, 200)) # левая половина красная
|
||||
exif = Image.Exif()
|
||||
exif[imaging.EXIF_ORIENTATION] = 6 # «повернуть на 90° по часовой» при показе
|
||||
path = self.save(img, "JPEG", exif=exif.tobytes(), quality=95)
|
||||
with Image.open(path) as source:
|
||||
reference = ImageOps.exif_transpose(source) # как картинку покажет просмотрщик
|
||||
variants = self.run_variants(path, "image/jpeg")
|
||||
thumb = self.opened(variants["thumbnail"])
|
||||
self.assertEqual((reference.size, thumb.size), ((200, 400), (128, 256)))
|
||||
top, bottom = thumb.getpixel((64, 20)), thumb.getpixel((64, 236))
|
||||
self.assertGreater(top[0], 200) # красная половина — сверху, как у reference
|
||||
self.assertGreater(bottom[2], 200)
|
||||
self.assertEqual(reference.getpixel((100, 20))[0] > 200, True)
|
||||
self.assertEqual(self.opened(variants["optimized"]).size, (200, 400))
|
||||
print("\n EXIF orientation 6: stored 400×200 -> variants 128×256 / 200×400, upright like a viewer shows it")
|
||||
|
||||
def test_alpha_is_white_in_jpeg_and_kept_in_webp(self):
|
||||
transparent = Image.new("RGBA", (100, 80), (0, 0, 0, 0))
|
||||
variants = self.run_variants(self.save(transparent, "PNG"), "image/png")
|
||||
for name in ("thumbnail", "crop"):
|
||||
pixel = self.opened(variants[name]).convert("RGB").getpixel((5, 5))
|
||||
self.assertTrue(all(c >= 250 for c in pixel), f"{name}: {pixel}")
|
||||
webp = self.opened(variants["optimized"])
|
||||
self.assertEqual((webp.mode, webp.getpixel((5, 5))[3]), ("RGBA", 0))
|
||||
palette = Image.new("P", (60, 40), 0)
|
||||
palette.putpalette([0, 0, 0] * 256)
|
||||
variants = self.run_variants(self.save(palette, "PNG", transparency=0), "image/png")
|
||||
self.assertTrue(all(c >= 250 for c in self.opened(variants["thumbnail"]).convert("RGB").getpixel((3, 3))))
|
||||
|
||||
def test_metadata_is_stripped(self):
|
||||
exif = Image.Exif()
|
||||
exif[0x010F] = "Camera Maker"
|
||||
exif[0x8825] = {1: "N", 2: (55.0, 45.0, 0.0)} # GPS-координаты
|
||||
icc = ImageCms.ImageCmsProfile(ImageCms.createProfile("sRGB")).tobytes()
|
||||
path = self.save(Image.new("RGB", (300, 200), (10, 200, 30)), "JPEG", exif=exif.tobytes(), icc_profile=icc)
|
||||
with Image.open(path) as source:
|
||||
self.assertIn("exif", source.info)
|
||||
self.assertIn("icc_profile", source.info)
|
||||
for name, variant in self.run_variants(path, "image/jpeg").items():
|
||||
data = Path(variant["path"]).read_bytes()
|
||||
img = self.opened(variant)
|
||||
self.assertNotIn("exif", img.info, name)
|
||||
self.assertNotIn("icc_profile", img.info, name)
|
||||
self.assertNotIn(b"Exif\x00\x00", data, name)
|
||||
self.assertNotIn(b"ICC_PROFILE", data, name)
|
||||
self.assertNotIn(b"Camera Maker", data, name)
|
||||
|
||||
def test_modes(self):
|
||||
sixteen = Image.new("I;16", (300, 200), 32768)
|
||||
variants = self.run_variants(self.save(sixteen, "PNG"), "image/png")
|
||||
self.assertAlmostEqual(self.opened(variants["thumbnail"]).getpixel((10, 10)), 128, delta=2)
|
||||
cmyk = self.save(Image.new("CMYK", (300, 200), (0, 255, 255, 0)), "JPEG")
|
||||
thumb = self.opened(self.run_variants(cmyk, "image/jpeg")["thumbnail"]).convert("RGB")
|
||||
self.assertGreater(thumb.getpixel((10, 10))[0], 200) # красный остался красным
|
||||
for mode in ("1", "L", "LA", "P", "RGB", "RGBA"):
|
||||
with self.subTest(mode=mode):
|
||||
variants = self.run_variants(self.save(Image.new(mode, (64, 48)), "PNG"), "image/png")
|
||||
self.assertEqual(self.opened(variants["thumbnail"]).size, (64, 48))
|
||||
|
||||
def test_same_input_same_bytes(self):
|
||||
first = self.run_variants(str(FIXTURE), "image/png")
|
||||
second = self.run_variants(str(FIXTURE), "image/png")
|
||||
self.assertEqual({k: v["sha256"] for k, v in first.items()}, {k: v["sha256"] for k, v in second.items()})
|
||||
for variant in first.values():
|
||||
self.assertEqual(hashlib.sha256(Path(variant["path"]).read_bytes()).hexdigest(), variant["sha256"])
|
||||
|
||||
def test_broken_jpeg_scan_is_invalid(self):
|
||||
good = io.BytesIO()
|
||||
Image.new("RGB", (64, 48), (200, 100, 50)).save(good, "JPEG")
|
||||
data = good.getvalue()
|
||||
sos = data.index(b"\xff\xda")
|
||||
length = int.from_bytes(data[sos + 2:sos + 4], "big")
|
||||
broken = data[:sos + 2 + length] + bytes((i * 37 + 11) % 255 for i in range(300)) + b"\xff\xd9"
|
||||
path = os.path.join(self.dir, "broken.jpg")
|
||||
Path(path).write_bytes(broken)
|
||||
with Image.open(path) as lenient:
|
||||
lenient.load() # Pillow такой файл молча «декодирует»...
|
||||
with self.assertRaises(imaging.InvalidImage): # ...а строгая проверка libjpeg-turbo — нет
|
||||
imaging.process(path, os.path.join(self.dir, "o"), "image/jpeg")
|
||||
|
||||
def test_jpeg_header_check_matches_strict_decoder(self):
|
||||
bases = [gradient_jpeg(), gradient_jpeg(subsampling=0), gradient_jpeg(subsampling=1),
|
||||
gradient_jpeg(progressive=True), gradient_jpeg(progressive=True, optimize=True),
|
||||
gradient_jpeg(restart_marker_blocks=1), gradient_jpeg("L"), gradient_jpeg("CMYK"),
|
||||
gradient_jpeg(size=(130, 70), restart_marker_rows=1),
|
||||
gradient_jpeg(size=(64, 64), progressive=True, restart_marker_blocks=2)]
|
||||
for data in bases:
|
||||
self.assertEqual((api_verdict(data), worker_verdict(data)), ("accept", "ok"))
|
||||
rnd = random.Random(20261026)
|
||||
counts = {"both accept": 0, "both reject": 0, "accepted, entropy error in worker": 0}
|
||||
for _ in range(800):
|
||||
parts = jpeg_parts(rnd.choice(bases))
|
||||
k = rnd.choice([n for n, part in enumerate(parts) if part[0] != "eoi"])
|
||||
operation = rnd.randrange(6)
|
||||
if operation <= 2: # байт в заголовке сегмента или скана
|
||||
part = parts[k]
|
||||
payload = bytearray(part[2] if part[0] == "seg" else part[1])
|
||||
if payload:
|
||||
position = rnd.randrange(len(payload))
|
||||
payload[position] = rnd.choice([rnd.randrange(256), (payload[position] + 1) % 256,
|
||||
payload[position] ^ (1 << rnd.randrange(8))])
|
||||
parts[k] = ("seg", part[1], bytes(payload)) if part[0] == "seg" else ("scan", bytes(payload), part[2])
|
||||
elif operation == 3: # сегмент или скан пропал
|
||||
del parts[k]
|
||||
elif operation == 4: # сегмент или скан повторился
|
||||
parts.insert(k, parts[k])
|
||||
else: # лишний или чужой маркер RST в сжатых данных
|
||||
scans = [n for n, part in enumerate(parts) if part[0] == "scan"]
|
||||
n = rnd.choice(scans)
|
||||
entropy = bytearray(parts[n][2])
|
||||
position = rnd.randrange(len(entropy))
|
||||
entropy[position:position] = bytes([0xFF, 0xD0 + rnd.randrange(8)])
|
||||
parts[n] = ("scan", parts[n][1], bytes(entropy))
|
||||
data = jpeg_join(parts)
|
||||
api, worker = api_verdict(data), worker_verdict(data)
|
||||
with self.subTest(api=api, worker=worker):
|
||||
if api == "accept":
|
||||
# Пропущенный API файл не должен падать в worker на заголовках.
|
||||
self.assertTrue(worker == "ok" or any(e in worker for e in ENTROPY_ERRORS))
|
||||
else:
|
||||
# Отклонённый API файл декодер тоже не принимает целиком.
|
||||
self.assertNotEqual(worker, "ok")
|
||||
if api == "accept":
|
||||
counts["both accept" if worker == "ok" else "accepted, entropy error in worker"] += 1
|
||||
else:
|
||||
counts["both reject"] += 1
|
||||
print(f"\n 800 random header mutations: {counts}")
|
||||
|
||||
def test_subsampling_rule_matches_turbojpeg(self):
|
||||
factors = [(h, v) for h in range(1, 5) for v in range(1, 5)]
|
||||
cases = [(gradient_jpeg("L"), [(f,) for f in factors]),
|
||||
(gradient_jpeg(), list(itertools.product(factors, repeat=3))),
|
||||
(gradient_jpeg("CMYK"), [(y, c, c, k) for y in factors for c in factors for k in factors])]
|
||||
compared = 0
|
||||
for data, combinations in cases:
|
||||
parts = jpeg_parts(data)
|
||||
sof = next(n for n, part in enumerate(parts) if part[0] == "seg" and part[1] == 0xC0)
|
||||
for combination in combinations:
|
||||
payload = bytearray(parts[sof][2])
|
||||
for k, (h, v) in enumerate(combination):
|
||||
payload[7 + 3 * k] = h * 16 + v
|
||||
parts[sof] = ("seg", 0xC0, bytes(payload))
|
||||
try:
|
||||
simplejpeg.decode_jpeg_header(jpeg_join(parts))
|
||||
decoder = True
|
||||
except (ValueError, KeyError): # KeyError: схема, которой нет в simplejpeg (4:4:1)
|
||||
decoder = False
|
||||
self.assertEqual(images._subsampling_supported(list(combination)), decoder, combination)
|
||||
compared += 1
|
||||
print(f"\n {compared} sampling-factor combinations: API and TurboJPEG agree on every one")
|
||||
|
||||
def test_limits_in_child_process(self):
|
||||
path = os.path.join(self.dir, "big.png")
|
||||
Path(path).write_bytes(big_rgba_png(6000, 6000)) # 36 млн пикселей RGBA
|
||||
params = imaging.Params()
|
||||
started = time.monotonic()
|
||||
result = sandbox.run(path, os.path.join(self.dir, "ok"), "image/png", params, timeout=60, memory_limit_mb=640)
|
||||
normal = time.monotonic() - started
|
||||
self.assertEqual({v["name"] for v in result["variants"]}, {"thumbnail", "crop", "optimized"})
|
||||
with self.assertRaises(imaging.ImageTooLarge): # память: RLIMIT_AS 200 МиБ
|
||||
sandbox.run(path, os.path.join(self.dir, "m"), "image/png", params, timeout=60, memory_limit_mb=200)
|
||||
started = time.monotonic()
|
||||
with self.assertRaises(sandbox.ProcessingTimeout): # время: SIGKILL дочернему процессу
|
||||
sandbox.run(path, os.path.join(self.dir, "t"), "image/png", params, timeout=0.2, memory_limit_mb=640)
|
||||
killed_after = time.monotonic() - started
|
||||
self.assertLess(killed_after, 2)
|
||||
with self.assertRaises(imaging.ImageTooLarge): # пиксели: до декодирования
|
||||
imaging.process(str(FIXTURE), os.path.join(self.dir, "p"), "image/png", imaging.Params(max_pixels=1000))
|
||||
direct = imaging.process(str(FIXTURE), os.path.join(self.dir, "d"), "image/png")
|
||||
child = sandbox.run(str(FIXTURE), os.path.join(self.dir, "c"), "image/png", params, 60, 640)
|
||||
self.assertEqual([v["sha256"] for v in direct["variants"]], [v["sha256"] for v in child["variants"]])
|
||||
print(f"\n 36 Mpx RGBA in a child process: ok in {normal:.2f} s with 640 MiB; MemoryError -> image_too_large "
|
||||
f"with 200 MiB; timeout 0.2 s -> killed after {killed_after:.2f} s; 1000 px limit -> image_too_large")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main(verbosity=2)
|
||||
@@ -0,0 +1,94 @@
|
||||
"""lab5, уровень 4: worker падает после записи объектов, но до ack — повтор даёт тот же результат.
|
||||
|
||||
make worker-crash (= python student-tests/worker_crash.py)
|
||||
|
||||
A. worker_after_objects: оригинал и три варианта уже записаны в S3, COMMIT результата и ack — нет.
|
||||
Процесс worker падает (os._exit, как SIGKILL), Docker перезапускает контейнер. Брокер снова
|
||||
доставляет неподтверждённое сообщение; новый процесс видит, что lease держит прежний запуск
|
||||
ЭТОГО ЖЕ контейнера (значит, тот мёртв), считает попытку неудачной и назначает следующую.
|
||||
Вторая попытка пишет варианты в ТЕ ЖЕ ключи (ключ эффекта attachment_id/версия/вариант) теми же
|
||||
байтами, коммитит и подтверждает. Итог: ready, попытка 2, ровно 3 строки и 3 объекта вариантов,
|
||||
SHA-256 вариантов равны тем, что записала упавшая попытка (вычисляются по самим объектам в S3).
|
||||
B. worker_after_commit: результат закоммичен, ack не отправлен, worker падает. Повторная доставка
|
||||
видит ready и подтверждает сообщение без обработки (duplicate_ignored); попытка остаётся 1.
|
||||
"""
|
||||
import json
|
||||
import time
|
||||
|
||||
import ops
|
||||
from filegen import upload_when_ready, wait_status
|
||||
from helpers import Client, check, run
|
||||
|
||||
# С lab7 у API нет права list, а у worker — права читать variants/: список ключей берём в worker,
|
||||
# содержимое (SHA-256) читаем ключами API.
|
||||
SNAPSHOT = """
|
||||
import hashlib, json
|
||||
from messenger import objects, config
|
||||
out = {}
|
||||
for key in json.loads(%r):
|
||||
body = objects.client().get_object(Bucket=config.S3_BUCKET, Key=key)["Body"].read()
|
||||
out[key] = hashlib.sha256(body).hexdigest()
|
||||
print(json.dumps(out))
|
||||
"""
|
||||
|
||||
|
||||
def snapshot(attachment_id):
|
||||
keys = ops.objects(f"variants/{attachment_id}/")
|
||||
return json.loads(ops.python("api", SNAPSHOT % json.dumps(keys)).splitlines()[-1])
|
||||
|
||||
|
||||
def wait_until(condition, seconds, message):
|
||||
deadline = time.monotonic() + seconds
|
||||
while True:
|
||||
value = condition()
|
||||
if value:
|
||||
return value
|
||||
check(time.monotonic() < deadline, message)
|
||||
time.sleep(0.5)
|
||||
|
||||
|
||||
def main():
|
||||
api = Client(timeout=15)
|
||||
worker = ops.wait_healthy("worker", 1)[0]
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
|
||||
# ---------- A ----------
|
||||
restarts = ops.restarts(worker)
|
||||
ops.arm("worker", "worker_after_objects", container=worker)
|
||||
att = upload_when_ready(api, alice, chat, name="worker-crash-a.png")["json"]
|
||||
print(f"A. worker_after_objects armed; upload -> 202 ({att['id']})")
|
||||
wait_until(lambda: ops.restarts(worker) > restarts, 60, "the worker did not crash")
|
||||
crashed = snapshot(att["id"])
|
||||
print(f" the worker crashed after writing objects (restart count {restarts} -> {ops.restarts(worker)}); "
|
||||
f"objects left by the crashed attempt: {len(crashed)}")
|
||||
ready = wait_status(api, bob, att["id"], seconds=120)
|
||||
job = ops.job(att["id"])
|
||||
final = snapshot(att["id"])
|
||||
check(job["job"]["attempt"] == 2, "the retry must be the second attempt")
|
||||
check(len(job["variants"]) == 3 and len(final) == 3, "exactly one set of variants expected")
|
||||
check(all(final[key] == digest for key, digest in crashed.items()), "the retry produced different bytes")
|
||||
check({v["sha256"] for v in ready["variants"]} == set(final.values()), "metadata does not match the objects")
|
||||
print(" events: " + " -> ".join(f"{e['event']}({e['attempt']})" for e in job["events"]))
|
||||
print(f" ready at attempt 2; same keys and the same SHA-256 as the crashed attempt wrote: "
|
||||
f"{sorted(k.rsplit('/', 1)[1] for k in final)}; 3 variant rows")
|
||||
ops.wait_healthy("worker", 1)
|
||||
|
||||
# ---------- B ----------
|
||||
restarts = ops.restarts(worker)
|
||||
ops.arm("worker", "worker_after_commit", container=worker)
|
||||
att = upload_when_ready(api, alice, chat, name="worker-crash-b.png")["json"]
|
||||
print(f"B. worker_after_commit armed; upload -> 202 ({att['id']})")
|
||||
wait_until(lambda: ops.restarts(worker) > restarts, 60, "the worker did not crash")
|
||||
wait_status(api, bob, att["id"], seconds=60)
|
||||
job = wait_until(lambda: (lambda j: j if any(e["event"] == "duplicate_ignored" for e in j["events"]) else None)(
|
||||
ops.job(att["id"])), 90, "the redelivered message was not seen")
|
||||
check(job["job"]["attempt"] == 1 and len(job["variants"]) == 3, "the duplicate must not reprocess the job")
|
||||
print(" events: " + " -> ".join(f"{e['event']}({e['attempt']})" for e in job["events"]))
|
||||
print(" the redelivered message found the job ready and was acknowledged without processing")
|
||||
ops.wait_healthy("worker", 1)
|
||||
print("PASS: a worker crash after writing objects but before ack is finished by a retry with the same result; "
|
||||
"a crash after COMMIT but before ack ends with a no-op redelivery")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,101 @@
|
||||
"""lab5, уровень 3: демонстрация из README — worker остановлен, перезапуск API и брокера, задание не потеряно.
|
||||
|
||||
make worker-outage (= python student-tests/worker_outage.py)
|
||||
|
||||
1. worker остановлен (docker compose stop worker);
|
||||
2. upload -> 202 queued; GET -> queued; /content -> 409 (и для варианта); API ничего не уменьшает сам;
|
||||
3. сообщение с этим вложением -> 201; обычное текстовое сообщение и история работают;
|
||||
4. через 5 с вложение всё ещё queued: без worker никто картинку не обрабатывает;
|
||||
5. задание уже в брокере: строка outbox отправлена (published_at) — до любых перезапусков;
|
||||
6. перезапуск API (обе реплики) и брокера с сохранением volumes;
|
||||
7. worker запущен -> то же вложение ready за <= 60 с, thumbnail 256×160 доступен, оригинал тот же.
|
||||
В outbox для задания по-прежнему одна строка: сообщение пережило перезапуск брокера в его
|
||||
очереди (quorum queue на volume), его никто не отправлял заново.
|
||||
ID печатаются, токены — нет.
|
||||
"""
|
||||
import hashlib
|
||||
import time
|
||||
|
||||
import ops
|
||||
from filegen import SAMPLE_PNG, upload_when_ready, wait_status
|
||||
from helpers import Client, check, idempotency, run, wait_ready
|
||||
from image_probe import jpeg_size
|
||||
|
||||
|
||||
def main():
|
||||
api = Client(timeout=15)
|
||||
ops.wait_healthy("worker", 1)
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
path = f"/api/v1/chats/{chat['id']}"
|
||||
try:
|
||||
ops.stop("worker")
|
||||
print("1. worker stopped:", ops.containers("worker") or "no running worker containers")
|
||||
|
||||
att = upload_when_ready(api, alice, chat, name="while-worker-down.png")["json"]
|
||||
print(f"2. upload -> 202 {att['status']}, attachment_id={att['id']}")
|
||||
meta = api.call("GET", f"/api/v1/attachments/{att['id']}", actor=bob, schema="Attachment")["json"]
|
||||
check(meta["status"] == "queued" and meta["variants"] == [], "must stay queued without a worker")
|
||||
for suffix in ("", "?variant=thumbnail"):
|
||||
api.call("GET", f"/api/v1/attachments/{att['id']}/content{suffix}", 409, actor=bob)
|
||||
print(" GET -> queued, /content -> 409, /content?variant=thumbnail -> 409")
|
||||
|
||||
with_att = api.call("POST", f"{path}/messages", 201, actor=alice, headers=idempotency(),
|
||||
body={"text": "фото пока обрабатывается", "attachment_ids": [att["id"]]},
|
||||
schema="Message")["json"]
|
||||
text = api.call("POST", f"{path}/messages", 201, actor=bob, headers=idempotency(),
|
||||
body={"text": "обычное сообщение"}, schema="Message")["json"]
|
||||
print(f"3. message with the queued attachment -> 201 ({with_att['id']}); text message -> 201 ({text['id']})")
|
||||
|
||||
time.sleep(5)
|
||||
meta = api.call("GET", f"/api/v1/attachments/{att['id']}", actor=bob, schema="Attachment")["json"]
|
||||
check(meta["status"] == "queued", "the API must not process images itself")
|
||||
print("4. after 5 s still queued: the API does not resize synchronously")
|
||||
|
||||
job = ops.job(att["id"])
|
||||
published = [o for o in job["outbox"] if o["published_at"]]
|
||||
check(len(job["outbox"]) == 1 and len(published) == 1, "the job must already be published to the broker")
|
||||
print(f"5. job {job['job']['job_id']} attempt {job['job']['attempt']}: outbox row published at "
|
||||
f"{published[0]['published_at']} by {published[0]['published_by']}; queues: {ops.queues()}")
|
||||
|
||||
ops.restart("api")
|
||||
wait_ready(api, 120)
|
||||
print("6. api replicas restarted (same containers, volumes kept)")
|
||||
ops.restart("broker")
|
||||
ops.wait_healthy("broker", 1, 180)
|
||||
# Счётчики quorum queue после старта брокера появляются через несколько секунд (очередь
|
||||
# восстанавливается из журнала на диске), поэтому немного ждём.
|
||||
deadline = time.monotonic() + 30
|
||||
while True:
|
||||
queues = ops.queues()
|
||||
if queues.get("attachments.process", (0, 0))[0] >= 1 or time.monotonic() > deadline:
|
||||
break
|
||||
time.sleep(1)
|
||||
print(f" broker restarted with volume rabbitmqdata; queues after restart: {queues}")
|
||||
meta = api.call("GET", f"/api/v1/attachments/{att['id']}", actor=bob, schema="Attachment")["json"]
|
||||
check(meta["status"] == "queued", "nothing should process the job while the worker is stopped")
|
||||
finally:
|
||||
ops.start("worker")
|
||||
|
||||
started = time.monotonic()
|
||||
ready = wait_status(api, bob, att["id"], ("ready",), seconds=90)
|
||||
took = time.monotonic() - started
|
||||
print(f"7. worker started -> ready after {took:.1f} s")
|
||||
thumb = [v for v in ready["variants"] if v["name"] == "thumbnail"][0]
|
||||
got = api.call("GET", f"/api/v1/attachments/{att['id']}/content?variant=thumbnail", actor=bob)["bytes"]
|
||||
check(jpeg_size(got) == (256, 160) and hashlib.sha256(got).hexdigest() == thumb["sha256"], "thumbnail mismatch")
|
||||
original = api.call("GET", f"/api/v1/attachments/{att['id']}/content", actor=bob)["bytes"]
|
||||
check(original == SAMPLE_PNG, "original changed")
|
||||
history = api.call("GET", f"{path}/messages?limit=100", actor=bob, schema="MessagePage")["json"]["items"]
|
||||
check(any(m["id"] == with_att["id"] and m["attachment_ids"] == [att["id"]] for m in history), "message lost")
|
||||
job = ops.job(att["id"])
|
||||
check(len(job["outbox"]) == 1, "the message must survive the broker restart, not be published again")
|
||||
check(len(job["variants"]) == 3, "exactly one set of variants expected")
|
||||
print(f" thumbnail 256×160 JPEG, original SHA-256 unchanged, message {with_att['id']} keeps the attachment; "
|
||||
f"outbox rows for the job: {len(job['outbox'])} (published once, before the broker restart)")
|
||||
print(" job events: " + " -> ".join(f"{e['event']}({e['attempt']})" for e in job["events"]))
|
||||
print("PASS: with the worker down uploads are accepted (202) and wait; the accepted job survives API and "
|
||||
"broker restarts and becomes ready once the worker is started")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user