ЛР 6 — БПИ2303 — Лазарев — на 4
Перенесена реализация lab5 (API x2 за HAProxy, PostgreSQL, SeaweedFS S3, RabbitMQ, relay outbox, worker x2, janitor) без изменения бизнес-API. Наблюдаемость: - OpenTelemetry SDK в API, relay, worker, janitor: traces, metrics, logs по OTLP/HTTP; структурные JSON-логи с trace_id/span_id - OTel Collector (memory_limiter, batch, ограниченные очереди и retry), Prometheus (метрики, alert rules), Loki (логи), Tempo (трассы), Grafana с provisioning datasources и dashboard - W3C trace context API -> outbox -> RabbitMQ -> worker (parent-child, включая retry); метрики очереди, пула БД, загрузки worker, CPU/RAM - SLI/SLO, 10 alert rules с unit-тестами promtool и runbooks - инциденты: остановка worker, блокировка БД, отказ telemetry backend; по наблюдениям исправлен простой worker в цикле AMQP (разбор x2.4)
This commit is contained in:
@@ -0,0 +1,102 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Аудит F03: общий срок приёма тела нельзя обойти, присылая данные по байту.
|
||||
|
||||
python3 student-tests/slow_client.py --output evidence/slow-client.json
|
||||
|
||||
На время теста API пересоздаётся с UPLOAD_TIMEOUT_SECONDS=5 и JSON_BODY_TIMEOUT_SECONDS=3
|
||||
(чтобы не ждать 60 с), затем возвращается к .env. Сырой сокет через LB:
|
||||
upload: заголовки + первые 33 байта PNG, дальше по 1 байту каждые 0,5 с (тело 5000 байт —
|
||||
без ограничения передача длилась бы ~40 мин);
|
||||
JSON: POST /users с Content-Length 200, по 1 байту каждые 0,5 с.
|
||||
Ожидаем ответ 400 invalid_request (или закрытие соединения) не позже срок + 2 с, после чего
|
||||
обычный upload снова 202 (слоты освобождены).
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import socket
|
||||
import time
|
||||
from urllib.parse import urlsplit
|
||||
|
||||
from lab5lib import Client, Log, SAMPLE_PNG, check, recreate, upload
|
||||
|
||||
ENV = {"UPLOAD_TIMEOUT_SECONDS": "5", "JSON_BODY_TIMEOUT_SECONDS": "3"}
|
||||
|
||||
|
||||
def drip(base, head, body_first, total_len, limit_s):
|
||||
u = urlsplit(base)
|
||||
s = socket.create_connection((u.hostname, u.port or 80), timeout=2)
|
||||
s.sendall(head + body_first)
|
||||
started = time.monotonic()
|
||||
sent = len(body_first)
|
||||
resp = b""
|
||||
while time.monotonic() - started < limit_s:
|
||||
try:
|
||||
chunk = s.recv(65536)
|
||||
if not chunk:
|
||||
break
|
||||
resp += chunk
|
||||
if b"\r\n\r\n" in resp:
|
||||
break
|
||||
except socket.timeout:
|
||||
pass
|
||||
except OSError:
|
||||
break
|
||||
if sent < total_len:
|
||||
try:
|
||||
s.sendall(b"\0")
|
||||
sent += 1
|
||||
except OSError:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
elapsed = round(time.monotonic() - started, 2)
|
||||
s.close()
|
||||
status = int(resp.split(b" ", 2)[1]) if resp.startswith(b"HTTP/") else None
|
||||
body = resp.split(b"\r\n\r\n", 1)[1] if b"\r\n\r\n" in resp else b""
|
||||
code = None
|
||||
if body.startswith(b"{"):
|
||||
try:
|
||||
code = json.loads(body)["error"]["code"]
|
||||
except ValueError:
|
||||
pass
|
||||
return {"status": status, "code": code, "seconds": elapsed, "bytes_sent": sent, "of": total_len,
|
||||
"x_instance_id": b"x-instance-id" in resp.lower()}
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--output")
|
||||
args = p.parse_args()
|
||||
log = Log("slow client vs total body deadline")
|
||||
recreate("api", ENV)
|
||||
log.step("api recreated", env=ENV)
|
||||
res = {}
|
||||
try:
|
||||
c = Client(args.base_url, timeout=30)
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
u = urlsplit(args.base_url)
|
||||
head = ("POST /api/v1/chats/%s/attachments?filename=slow.png HTTP/1.1\r\nHost: %s\r\n"
|
||||
"Authorization: Bearer %s\r\nContent-Type: image/png\r\nContent-Length: 5000\r\n\r\n"
|
||||
% (chat["id"], u.netloc, alice["token"])).encode()
|
||||
res["upload"] = drip(args.base_url, head, SAMPLE_PNG[:33], 5000, 20)
|
||||
log.step("upload drip 1 B / 0.5 s", **res["upload"])
|
||||
check(res["upload"]["seconds"] <= 7 and res["upload"]["bytes_sent"] < 5000, "upload deadline not enforced")
|
||||
check(res["upload"]["status"] == 400 and res["upload"]["x_instance_id"], "upload: expected API 400")
|
||||
head = ("POST /api/v1/users HTTP/1.1\r\nHost: %s\r\nContent-Type: application/json\r\n"
|
||||
"Content-Length: 200\r\n\r\n" % u.netloc).encode()
|
||||
res["json"] = drip(args.base_url, head, b'{"username":', 200, 20)
|
||||
log.step("json drip 1 B / 0.5 s", **res["json"])
|
||||
check(res["json"]["seconds"] <= 5 and res["json"]["bytes_sent"] < 200, "json deadline not enforced")
|
||||
check(res["json"]["status"] == 400 and res["json"]["x_instance_id"], "json: expected API 400")
|
||||
att = upload(c, alice, chat, SAMPLE_PNG, "after-slow.png")
|
||||
res["normal_upload_after"] = att["status"]
|
||||
log.step("normal upload afterwards", status=att["status"])
|
||||
finally:
|
||||
recreate("api")
|
||||
log.step("api restored to .env configuration")
|
||||
log.save(args.output, results=res)
|
||||
print("PASS: slow clients are cut off by the total deadline")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user