ЛР 3 — БПИ2303 — Лазарев — на 3
This commit is contained in:
@@ -0,0 +1,32 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Проверка диапазона дат cursor: некорректная дата должна давать 400, а не 500."""
|
||||
import base64
|
||||
import json
|
||||
import sys
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, arguments, run
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
client = Client(args.base_url, ca_file=args.ca_file)
|
||||
alice, _bob, _eve, chat = client.bootstrap()
|
||||
checks = 0
|
||||
for kind, scope, path in (
|
||||
("messages", chat["id"], "/api/v1/chats/" + chat["id"] + "/messages"),
|
||||
("chats", alice["id"], "/api/v1/chats"),
|
||||
):
|
||||
for timestamp, expected in ((-10**17, 400), (-62135596800000001, 400), (0, 200)):
|
||||
payload = {"k": kind, "s": scope, "t": timestamp, "i": str(uuid.uuid4())}
|
||||
cursor = base64.urlsafe_b64encode(json.dumps(payload).encode()).decode().rstrip("=")
|
||||
client.call("GET", path + "?cursor=" + quote(cursor, safe=""), expected, actor=alice)
|
||||
checks += 1
|
||||
print("PASS: %d cursor date boundary checks; invalid dates return 400." % checks)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,264 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Отказ/замена API-реплики ПОД НАГРУЗКОЙ: RPS, ошибки, время обнаружения и восстановления (lab3, уровень 4).
|
||||
|
||||
Что делает:
|
||||
* CONCURRENCY потоков в closed-loop шлют смесь запросов через LB: POST сообщения
|
||||
(с Idempotency-Key) и GET истории (limit=20) в пропорции 1:1;
|
||||
* после неуспешного/неопределённого POST поток повторяет ТОТ ЖЕ ключ и тело (как
|
||||
требует контракт), поэтому подтверждённых дублей быть не должно;
|
||||
* на секунде --action-at запускается --action (например, docker stop/kill контейнера
|
||||
или scripts/rolling-update.sh), его stdout/stderr пишутся в отдельный лог;
|
||||
* параллельно каждые 200 мс опрашивается CSV статистики HAProxy: фиксируются моменты
|
||||
UP -> DOWN / DOWN -> UP серверов backend (время обнаружения отказа LB);
|
||||
* в конце читается вся история чата (тем же токеном) и проверяется: все подтверждённые
|
||||
сообщения на месте, дублей нет.
|
||||
|
||||
Метрики (все времена — от старта action):
|
||||
errors_total / error_rate — неуспешные попытки (HTTP != ожидаемого, timeout, разрыв);
|
||||
error_window_s — от первой до последней ошибки после старта action;
|
||||
recovery_s — конец окна ошибок (дальше все запросы успешны), 0 если ошибок нет;
|
||||
post_action_ok_rps/capacity_ratio — успешный RPS после действия и его доля от базового;
|
||||
lb_down_detected_s — когда HAProxy пометил сервер DOWN;
|
||||
target_last_seen_s — последний ответ от остановленной реплики.
|
||||
|
||||
Ограничения: closed-loop генератор (coordinated omission), клиент на том же хосте, что и
|
||||
стенд; цифры RPS сравнимы только между прогонами этого же скрипта на этом же ноутбуке.
|
||||
"""
|
||||
import argparse
|
||||
import csv
|
||||
import io
|
||||
import json
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from collections import Counter, defaultdict
|
||||
from pathlib import Path
|
||||
from urllib.parse import quote
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client # noqa: E402
|
||||
|
||||
TIMEOUT = 2.0
|
||||
|
||||
|
||||
def percentile(values, p):
|
||||
if not values:
|
||||
return None
|
||||
s = sorted(values)
|
||||
return round(s[min(len(s) - 1, int(round(p / 100 * (len(s) - 1))))] * 1000, 1)
|
||||
|
||||
|
||||
class Bench:
|
||||
def __init__(self, a):
|
||||
self.a = a
|
||||
self.base = a.base_url.rstrip("/")
|
||||
self.lock = threading.Lock()
|
||||
self.t0 = None
|
||||
self.stop = threading.Event()
|
||||
self.per_sec = defaultdict(lambda: {"ok": 0, "err": 0, "inst": Counter(), "ver": Counter()})
|
||||
self.errors = [] # (t, kind)
|
||||
self.lat = [] # успешные задержки, с
|
||||
self.confirmed = {} # message id -> text
|
||||
self.retried_posts = 0
|
||||
self.lb_events = []
|
||||
self.inst_last_seen = {}
|
||||
|
||||
def now(self):
|
||||
return time.monotonic() - self.t0
|
||||
|
||||
def record(self, ok, dt, inst=None, ver=None, kind=None):
|
||||
t = self.now()
|
||||
with self.lock:
|
||||
b = self.per_sec[int(t)]
|
||||
if ok:
|
||||
b["ok"] += 1
|
||||
self.lat.append(dt)
|
||||
if inst:
|
||||
b["inst"][inst] += 1
|
||||
self.inst_last_seen[inst] = t
|
||||
if ver:
|
||||
b["ver"][ver] += 1
|
||||
else:
|
||||
b["err"] += 1
|
||||
self.errors.append((round(t, 3), kind))
|
||||
|
||||
def request(self, method, path, body=None, headers=None, expected=200):
|
||||
h = {"Authorization": "Bearer " + self.token}
|
||||
h.update(headers or {})
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(self.base + path, data=data, method=method, headers=h)
|
||||
start = time.monotonic()
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
|
||||
payload = json.loads(r.read())
|
||||
ok = r.status == expected
|
||||
self.record(ok, time.monotonic() - start, r.headers.get("X-Instance-Id"),
|
||||
r.headers.get("X-App-Version"), None if ok else "http_%d" % r.status)
|
||||
return payload if ok else None
|
||||
except urllib.error.HTTPError as e:
|
||||
self.record(False, 0, kind="http_%d" % e.code)
|
||||
except Exception as e: # noqa: BLE001
|
||||
self.record(False, 0, kind=type(e).__name__)
|
||||
return None
|
||||
|
||||
def worker(self, n):
|
||||
chat_path = "/api/v1/chats/" + self.chat["id"] + "/messages"
|
||||
key = text = None
|
||||
i = 0
|
||||
while not self.stop.is_set():
|
||||
i += 1
|
||||
if i % 2:
|
||||
if key is None: # новый логический запрос; после ошибки ключ НЕ меняется
|
||||
key = "bench-%d-%s" % (n, uuid.uuid4().hex)
|
||||
text = "Нагрузка " + key
|
||||
else:
|
||||
with self.lock:
|
||||
self.retried_posts += 1
|
||||
msg = self.request("POST", chat_path, {"text": text}, {"Idempotency-Key": key}, 201)
|
||||
if msg is not None:
|
||||
with self.lock:
|
||||
self.confirmed[msg["id"]] = msg["text"]
|
||||
key = None
|
||||
else:
|
||||
self.request("GET", chat_path + "?limit=20")
|
||||
|
||||
def poll_lb(self):
|
||||
prev = {}
|
||||
while not self.stop.is_set():
|
||||
try:
|
||||
with urllib.request.urlopen(self.a.stats_url, timeout=1) as r:
|
||||
rows = list(csv.reader(io.StringIO(r.read().decode().lstrip("# "))))
|
||||
head = rows[0]
|
||||
ix = {k: head.index(k) for k in ("pxname", "svname", "status", "addr")}
|
||||
for row in rows[1:]:
|
||||
if len(row) <= ix["addr"] or row[ix["pxname"]] != "be_api" or row[ix["svname"]] == "BACKEND":
|
||||
continue
|
||||
sv, st, addr = row[ix["svname"]], row[ix["status"]].split(" ")[0], row[ix["addr"]]
|
||||
if sv in prev and prev[sv] != (st, addr):
|
||||
self.lb_events.append({"t": round(self.now(), 2), "server": sv, "addr": addr,
|
||||
"from": prev[sv][0], "to": st})
|
||||
prev[sv] = (st, addr)
|
||||
except Exception: # noqa: BLE001 — статистика вспомогательная
|
||||
pass
|
||||
time.sleep(0.2)
|
||||
|
||||
def history(self):
|
||||
c, path, items = self.client, "/api/v1/chats/" + self.chat["id"] + "/messages?limit=100", []
|
||||
while True:
|
||||
page = c.call("GET", path, actor=self.alice, schema="MessagePage")["json"]
|
||||
items += page["items"]
|
||||
if page["next_cursor"] is None:
|
||||
return items
|
||||
path = "/api/v1/chats/" + self.chat["id"] + "/messages?limit=100&cursor=" + quote(page["next_cursor"], safe="")
|
||||
|
||||
def run(self):
|
||||
a = self.a
|
||||
self.client = Client(self.base, timeout=10)
|
||||
self.alice, _bob, _eve, self.chat = self.client.bootstrap()
|
||||
self.token = self.alice["token"]
|
||||
self.t0 = time.monotonic()
|
||||
threads = [threading.Thread(target=self.worker, args=(n,), daemon=True) for n in range(a.concurrency)]
|
||||
threads.append(threading.Thread(target=self.poll_lb, daemon=True))
|
||||
for t in threads:
|
||||
t.start()
|
||||
time.sleep(a.action_at)
|
||||
action = {"command": a.action, "started_s": round(self.now(), 3)}
|
||||
log = open(a.action_log, "w", encoding="utf-8") if a.action_log else subprocess.DEVNULL
|
||||
proc = subprocess.Popen(shlex.split(a.action), stdout=log, stderr=subprocess.STDOUT)
|
||||
rc = proc.wait(timeout=a.duration)
|
||||
action.update(finished_s=round(self.now(), 3), exit_code=rc)
|
||||
remaining = a.duration - self.now()
|
||||
if remaining > 0:
|
||||
time.sleep(remaining)
|
||||
self.stop.set()
|
||||
for t in threads:
|
||||
t.join(timeout=TIMEOUT + 1)
|
||||
return self.summarize(action)
|
||||
|
||||
def summarize(self, action):
|
||||
a, t_act = self.a, action["started_s"]
|
||||
secs = sorted(self.per_sec)
|
||||
base = [self.per_sec[s]["ok"] for s in secs if 1 <= s < int(t_act)] # 1-я секунда — прогрев
|
||||
baseline = sum(base) / len(base) if base else 0
|
||||
after = [(round(t - t_act, 3), k) for t, k in self.errors if t >= t_act]
|
||||
# Восстановление = конец окна ошибок: после этого момента все запросы до конца
|
||||
# прогона успешны. Если ошибок не было — 0. Мощность после отказа меряем отдельно:
|
||||
# при меньшем числе реплик RPS законно ниже (лимиты CPU на реплику).
|
||||
recovery = after[-1][0] if after else 0.0
|
||||
tail_secs = [s for s in secs if int(action.get("finished_s", t_act)) + 2 <= s < a.duration - 1]
|
||||
post = [self.per_sec[s]["ok"] for s in tail_secs]
|
||||
post_rps = sum(post) / len(post) if post else 0
|
||||
writes_after = any(self.per_sec[s]["ok"] > 0 for s in tail_secs)
|
||||
target = a.target_instance
|
||||
hist = self.history()
|
||||
ids = [m["id"] for m in hist]
|
||||
texts = [m["text"] for m in hist]
|
||||
lost = [i for i in self.confirmed if i not in set(ids)]
|
||||
timeline = [{"t": s, "ok": self.per_sec[s]["ok"], "err": self.per_sec[s]["err"],
|
||||
"instances": dict(self.per_sec[s]["inst"]), "versions": dict(self.per_sec[s]["ver"])}
|
||||
for s in secs]
|
||||
total_ok = sum(b["ok"] for b in self.per_sec.values())
|
||||
total_err = len(self.errors)
|
||||
summary = {
|
||||
"label": a.label,
|
||||
"concurrency": a.concurrency, "duration_s": a.duration, "request_timeout_s": TIMEOUT,
|
||||
"action": action,
|
||||
"baseline_ok_rps": round(baseline, 1),
|
||||
"overall_ok_rps": round(total_ok / a.duration, 1),
|
||||
"requests_ok": total_ok, "errors_total": total_err,
|
||||
"error_rate": round(total_err / max(1, total_ok + total_err), 5),
|
||||
"errors_by_kind": dict(Counter(k for _, k in self.errors)),
|
||||
"error_window_s": [after[0][0], after[-1][0]] if after else None,
|
||||
"recovery_s": recovery,
|
||||
"post_action_ok_rps": round(post_rps, 1),
|
||||
"capacity_ratio": round(post_rps / baseline, 2) if baseline else None,
|
||||
"latency_ok_ms": {"p50": percentile(self.lat, 50), "p95": percentile(self.lat, 95),
|
||||
"p99": percentile(self.lat, 99)},
|
||||
"target_instance": target,
|
||||
"target_last_seen_s": (round(self.inst_last_seen[target] - t_act, 3)
|
||||
if target in self.inst_last_seen else None),
|
||||
"lb_events": [dict(e, t=round(e["t"] - t_act, 2)) for e in self.lb_events],
|
||||
"posts_retried_same_key": self.retried_posts,
|
||||
"confirmed_messages": len(self.confirmed),
|
||||
"history_messages": len(hist), "lost_confirmed": len(lost),
|
||||
"duplicate_ids": len(ids) - len(set(ids)), "duplicate_texts": len(texts) - len(set(texts)),
|
||||
"timeline": timeline,
|
||||
}
|
||||
summary["pass"] = (summary["lost_confirmed"] == 0 and summary["duplicate_ids"] == 0
|
||||
and summary["duplicate_texts"] == 0 and action["exit_code"] == 0
|
||||
and writes_after and recovery <= 10)
|
||||
return summary
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description="Отказ/замена реплики под нагрузкой")
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--stats-url", default="http://127.0.0.1:8404/stats;csv")
|
||||
p.add_argument("--concurrency", type=int, default=8)
|
||||
p.add_argument("--duration", type=float, default=40)
|
||||
p.add_argument("--action-at", type=float, default=10)
|
||||
p.add_argument("--action", required=True, help="команда без shell, например 'docker stop -t 20 <id>'")
|
||||
p.add_argument("--action-log")
|
||||
p.add_argument("--target-instance", help="X-Instance-Id реплики, которую останавливает action")
|
||||
p.add_argument("--label", default="")
|
||||
p.add_argument("--output")
|
||||
a = p.parse_args()
|
||||
s = Bench(a).run()
|
||||
brief = {k: v for k, v in s.items() if k != "timeline"}
|
||||
print(json.dumps(brief, ensure_ascii=False, indent=2))
|
||||
if a.output:
|
||||
Path(a.output).write_text(json.dumps(s, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("PASS" if s["pass"] else "FAIL")
|
||||
return 0 if s["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,130 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Конкурентная идемпотентность через разные реплики (lab3, уровни 3–4).
|
||||
|
||||
Сценарий на каждый раунд:
|
||||
A) PARALLEL запросов одновременно отправляют ОДИН И ТОТ ЖЕ ключ и одинаковое тело.
|
||||
Ожидаем: все 201, у всех один и тот же Message.id, ответы пришли от >=2 реплик,
|
||||
в истории ровно одно сообщение с этим текстом.
|
||||
B) Тот же ключ, но половина запросов с другим телом. Ожидаем: побеждает ровно одно
|
||||
тело; запросы с ним — 201 и один id, запросы с другим телом — 409; дублей нет.
|
||||
|
||||
Каждый запрос — отдельное TCP-соединение, поэтому HAProxy (roundrobin) раскладывает их
|
||||
по репликам. Токены только в памяти; синтетические пользователи создаются заново.
|
||||
|
||||
python3 student-tests/idempotency_concurrency.py --rounds 20 --parallel 16
|
||||
"""
|
||||
import argparse
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from collections import Counter
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client # noqa: E402 (публичный клиент тестов: bootstrap пользователей/чата)
|
||||
|
||||
|
||||
def post(base, token, chat_id, key, text, barrier, out, idx):
|
||||
data = json.dumps({"text": text}).encode()
|
||||
req = urllib.request.Request(
|
||||
base + "/api/v1/chats/" + chat_id + "/messages", data=data, method="POST",
|
||||
headers={"Authorization": "Bearer " + token, "Content-Type": "application/json",
|
||||
"Idempotency-Key": key, "Connection": "close"})
|
||||
barrier.wait()
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as r:
|
||||
out[idx] = (r.status, json.loads(r.read()), r.headers.get("X-Instance-Id"), text)
|
||||
except urllib.error.HTTPError as e:
|
||||
out[idx] = (e.code, None, e.headers.get("X-Instance-Id"), text)
|
||||
except Exception as e: # noqa: BLE001 — считаем любую сетевую ошибку
|
||||
out[idx] = (0, repr(e), None, text)
|
||||
|
||||
|
||||
def burst(base, token, chat_id, key, texts):
|
||||
barrier = threading.Barrier(len(texts))
|
||||
out = [None] * len(texts)
|
||||
threads = [threading.Thread(target=post, args=(base, token, chat_id, key, t, barrier, out, i))
|
||||
for i, t in enumerate(texts)]
|
||||
for t in threads:
|
||||
t.start()
|
||||
for t in threads:
|
||||
t.join()
|
||||
return out
|
||||
|
||||
|
||||
def history_texts(c, actor, chat):
|
||||
from urllib.parse import quote
|
||||
texts, path = [], "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
|
||||
while True:
|
||||
page = c.call("GET", path, actor=actor, schema="MessagePage")["json"]
|
||||
texts += [m["text"] for m in page["items"]]
|
||||
if page["next_cursor"] is None:
|
||||
return texts
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100&cursor=" + quote(page["next_cursor"], safe="")
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser(description=__doc__.splitlines()[0])
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--rounds", type=int, default=20)
|
||||
p.add_argument("--parallel", type=int, default=16)
|
||||
p.add_argument("--output")
|
||||
a = p.parse_args()
|
||||
base = a.base_url.rstrip("/")
|
||||
c = Client(base)
|
||||
alice, _bob, _eve, chat = c.bootstrap()
|
||||
token = alice["token"]
|
||||
problems, instances = [], Counter()
|
||||
stats = {"same_body": Counter(), "conflicting_body": Counter()}
|
||||
|
||||
for rnd in range(a.rounds):
|
||||
# A) одинаковое тело
|
||||
key, text = "same-" + uuid.uuid4().hex, "Конкурентный повтор " + uuid.uuid4().hex
|
||||
res = burst(base, token, chat["id"], key, [text] * a.parallel)
|
||||
stats["same_body"].update(str(r[0]) for r in res)
|
||||
ids = {r[1]["id"] for r in res if r[0] == 201}
|
||||
seen = {r[2] for r in res if r[2]}
|
||||
instances.update(r[2] for r in res if r[2])
|
||||
if any(r[0] != 201 for r in res) or len(ids) != 1:
|
||||
problems.append("round %d same-body: statuses=%s ids=%d" % (rnd, Counter(r[0] for r in res), len(ids)))
|
||||
if len(seen) < 2:
|
||||
problems.append("round %d: only %d replica(s) answered" % (rnd, len(seen)))
|
||||
|
||||
# B) тот же ключ, два разных тела вперемешку
|
||||
key = "mixed-" + uuid.uuid4().hex
|
||||
t1, t2 = "Тело A " + key, "Тело B " + key
|
||||
res = burst(base, token, chat["id"], key, [t1, t2] * (a.parallel // 2))
|
||||
stats["conflicting_body"].update(str(r[0]) for r in res)
|
||||
winners = {r[3] for r in res if r[0] == 201}
|
||||
ids = {r[1]["id"] for r in res if r[0] == 201}
|
||||
bad = [r[0] for r in res if r[0] not in (201, 409)]
|
||||
losers_ok = all(r[0] == 409 for r in res if r[3] not in winners)
|
||||
if len(winners) != 1 or len(ids) != 1 or bad or not losers_ok:
|
||||
problems.append("round %d mixed-body: winners=%d ids=%d bad=%s" % (rnd, len(winners), len(ids), bad))
|
||||
|
||||
texts = history_texts(c, alice, chat)
|
||||
dupes = [t for t, n in Counter(texts).items() if n > 1]
|
||||
if dupes:
|
||||
problems.append("duplicated messages in history: %d" % len(dupes))
|
||||
summary = {
|
||||
"rounds": a.rounds, "parallel_per_burst": a.parallel,
|
||||
"requests_total": a.rounds * a.parallel * 2,
|
||||
"status_counts": {k: dict(v) for k, v in stats.items()},
|
||||
"replicas_answered": len(instances), "requests_per_replica": sorted(instances.values()),
|
||||
"messages_in_history": len(texts), "expected_messages": a.rounds * 2,
|
||||
"duplicates": len(dupes), "problems": problems,
|
||||
}
|
||||
if len(texts) != a.rounds * 2:
|
||||
problems.append("history has %d messages, expected %d" % (len(texts), a.rounds * 2))
|
||||
print(json.dumps(summary, ensure_ascii=False, indent=2))
|
||||
if a.output:
|
||||
Path(a.output).write_text(json.dumps(summary, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("PASS" if not problems else "FAIL")
|
||||
return 1 if problems else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
sys.exit(main())
|
||||
@@ -0,0 +1,172 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Шторм входов: много параллельных POST /auth/sessions с неверным паролем через LB.
|
||||
|
||||
Зачем: scrypt (N=2^15, r=8) берёт ~32 MiB на одну проверку пароля, лимит API-реплики
|
||||
256 MiB. Без ограничения параллельных проверок несколько одновременных входов
|
||||
приводят к OOM-kill реплики. Скрипт показывает, переживают ли реплики такой шторм.
|
||||
|
||||
Что измеряется:
|
||||
* статусы ответов шторма (ожидаем 401 и, при перегрузке, 503 с Retry-After) и
|
||||
ответы не в JSON-формате ошибки контракта (например HTML-страницы HAProxy);
|
||||
* «жертва»: параллельный поток раз в 50 мс читает /users/me действующим токеном —
|
||||
обычные пользователи не должны получать ошибки из-за шторма входов;
|
||||
* состояние API-контейнеров до/после: OOMKilled, RestartCount, StartedAt.
|
||||
|
||||
Пример: python3 student-tests/login_flood.py --parallel 24 --duration 20 --output evidence/login-flood.json
|
||||
"""
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
import threading
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
from collections import Counter
|
||||
|
||||
TIMEOUT = 10.0
|
||||
|
||||
|
||||
def http(base, method, path, headers=None, body=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
h = dict(headers or {})
|
||||
if data is not None:
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(base + path, data=data, method=method, headers=h)
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=TIMEOUT) as r:
|
||||
return r.status, r.headers, r.read()
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, e.headers, e.read()
|
||||
|
||||
|
||||
def is_contract_error(headers, raw):
|
||||
if not (headers.get("Content-Type") or "").startswith("application/json"):
|
||||
return False
|
||||
try:
|
||||
err = json.loads(raw)["error"]
|
||||
return bool(err["code"] and err["message"] and err["request_id"])
|
||||
except (ValueError, KeyError, TypeError):
|
||||
return False
|
||||
|
||||
|
||||
def api_containers():
|
||||
ids = subprocess.run(["docker", "compose", "ps", "-a", "-q", "api"], capture_output=True,
|
||||
text=True, check=True).stdout.split()
|
||||
out = {}
|
||||
for cid in ids:
|
||||
info = json.loads(subprocess.run(["docker", "inspect", cid], capture_output=True, text=True,
|
||||
check=True).stdout)[0]
|
||||
out[info["Name"].lstrip("/")] = {
|
||||
"status": info["State"]["Status"], "oom_killed": info["State"]["OOMKilled"],
|
||||
"restart_count": info["RestartCount"], "started_at": info["State"]["StartedAt"]}
|
||||
return out
|
||||
|
||||
|
||||
def oom_events(since):
|
||||
"""Имена контейнеров, получивших OOM с момента since (unix time): флаг OOMKilled
|
||||
сбрасывается после рестарта по restart-policy, поэтому смотрим события Docker."""
|
||||
out = subprocess.run(["docker", "events", "--since", str(int(since)), "--until", str(int(time.time()) + 1),
|
||||
"--filter", "type=container", "--filter", "event=oom",
|
||||
"--format", "{{.Actor.Attributes.name}}"], capture_output=True, text=True).stdout
|
||||
return sorted(Counter(out.split()).items())
|
||||
|
||||
|
||||
def main():
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default="http://localhost:8080")
|
||||
p.add_argument("--parallel", type=int, default=24)
|
||||
p.add_argument("--duration", type=float, default=20)
|
||||
p.add_argument("--output")
|
||||
a = p.parse_args()
|
||||
base = a.base_url.rstrip("/")
|
||||
|
||||
username = "flood_" + uuid.uuid4().hex[:10]
|
||||
password = "correct-horse-" + uuid.uuid4().hex[:8]
|
||||
st, _, _ = http(base, "POST", "/api/v1/users",
|
||||
body={"username": username, "display_name": "Flood", "password": password})
|
||||
assert st == 201, st
|
||||
basic = base64.b64encode(("%s:%s" % (username, password)).encode()).decode()
|
||||
st, _, raw = http(base, "POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + basic})
|
||||
assert st == 201, st
|
||||
token = json.loads(raw)["token"]
|
||||
bad = base64.b64encode(("%s:wrong-password-123" % username).encode()).decode()
|
||||
|
||||
before = api_containers()
|
||||
wall0 = time.time()
|
||||
stop = threading.Event()
|
||||
lock = threading.Lock()
|
||||
flood, victim = Counter(), Counter()
|
||||
non_json_errors = Counter()
|
||||
retry_after_503 = [0, 0] # [503 всего, из них с Retry-After]
|
||||
|
||||
def record(counter, status, headers, raw):
|
||||
with lock:
|
||||
counter[str(status)] += 1
|
||||
if status >= 400 and not is_contract_error(headers, raw):
|
||||
non_json_errors[str(status)] += 1
|
||||
if status == 503 and counter is flood:
|
||||
retry_after_503[0] += 1
|
||||
retry_after_503[1] += bool(headers.get("Retry-After"))
|
||||
|
||||
def flooder():
|
||||
while not stop.is_set():
|
||||
try:
|
||||
record(flood, *http(base, "POST", "/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + bad}))
|
||||
except Exception as exc: # обрыв соединения, timeout
|
||||
with lock:
|
||||
flood["exc:" + type(exc).__name__] += 1
|
||||
|
||||
def prober():
|
||||
while not stop.is_set():
|
||||
try:
|
||||
record(victim, *http(base, "GET", "/api/v1/users/me",
|
||||
headers={"Authorization": "Bearer " + token}))
|
||||
except Exception as exc:
|
||||
with lock:
|
||||
victim["exc:" + type(exc).__name__] += 1
|
||||
time.sleep(0.05)
|
||||
|
||||
threads = [threading.Thread(target=flooder, daemon=True) for _ in range(a.parallel)]
|
||||
threads.append(threading.Thread(target=prober, daemon=True))
|
||||
t0 = time.monotonic()
|
||||
for t in threads:
|
||||
t.start()
|
||||
time.sleep(a.duration)
|
||||
stop.set()
|
||||
for t in threads:
|
||||
t.join(TIMEOUT + 1)
|
||||
elapsed = time.monotonic() - t0
|
||||
time.sleep(3) # дать restart-policy отработать, если реплика упала
|
||||
after = api_containers()
|
||||
|
||||
restarted = [n for n in after if n in before and (
|
||||
after[n]["restart_count"] != before[n]["restart_count"]
|
||||
or after[n]["started_at"] != before[n]["started_at"])]
|
||||
victim_ok = victim.get("200", 0)
|
||||
victim_total = sum(victim.values())
|
||||
summary = {
|
||||
"parallel": a.parallel, "duration_s": round(elapsed, 1),
|
||||
"flood_statuses": dict(flood), "flood_rps": round(sum(flood.values()) / elapsed, 1),
|
||||
"flood_503_with_retry_after": "%d/%d" % (retry_after_503[1], retry_after_503[0]),
|
||||
"victim_statuses": dict(victim),
|
||||
"victim_error_rate": round(1 - victim_ok / victim_total, 4) if victim_total else None,
|
||||
"non_contract_error_bodies": dict(non_json_errors),
|
||||
"containers_before": before, "containers_after": after,
|
||||
"oom_events": dict(oom_events(wall0)),
|
||||
"restarted": restarted,
|
||||
}
|
||||
summary["pass"] = (not summary["oom_events"] and not restarted and victim_total > 0
|
||||
and victim_ok == victim_total and not non_json_errors)
|
||||
text = json.dumps(summary, ensure_ascii=False, indent=2)
|
||||
print(text)
|
||||
if a.output:
|
||||
with open(a.output, "w", encoding="utf-8") as f:
|
||||
f.write(text + "\n")
|
||||
return 0 if summary["pass"] else 1
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
Reference in New Issue
Block a user