Lab7: HTTPS, mTLS, OpenBao, трек 2 PKI на оценку 5
Skeleton contracts / contracts (pull_request) Canceled after 0s
Skeleton contracts / contracts (pull_request) Canceled after 0s
This commit is contained in:
@@ -0,0 +1,74 @@
|
||||
#!/usr/bin/env python3
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=str(ROOT),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
try:
|
||||
urllib.request.urlopen("http://127.0.0.1:8080/health/live", timeout=5).read()
|
||||
except urllib.error.HTTPError:
|
||||
pass
|
||||
time.sleep(10)
|
||||
end = int(time.time())
|
||||
start = end - 1800
|
||||
for query in (
|
||||
'{service_name="messenger-api"}',
|
||||
'{service_name="messenger-worker"}',
|
||||
'{service_name=~".+"}',
|
||||
):
|
||||
url = "http://127.0.0.1:3100/loki/api/v1/query_range?" + urllib.parse.urlencode(
|
||||
{
|
||||
"query": query,
|
||||
"start": str(start) + "000000000",
|
||||
"end": str(end) + "000000000",
|
||||
"limit": "20",
|
||||
}
|
||||
)
|
||||
out = compose("exec", "-T", "loki", "wget", "-qO-", url)
|
||||
try:
|
||||
data = json.loads(out.stdout)
|
||||
streams = data.get("data", {}).get("result", [])
|
||||
lines = sum(len(item.get("values", [])) for item in streams)
|
||||
print(query, "streams", len(streams), "lines", lines)
|
||||
if streams and streams[0].get("values"):
|
||||
print("sample", streams[0]["values"][0][1][:240])
|
||||
except Exception as exc:
|
||||
print(query, "err", exc, out.stdout[:200], out.stderr[:200])
|
||||
print("collector tail:")
|
||||
print(compose("logs", "otel-collector", "--since", "2m").stdout[-2000:])
|
||||
q = '{service_name="messenger-api"} |= "http_request"'
|
||||
url = "http://127.0.0.1:3100/loki/api/v1/query_range?" + urllib.parse.urlencode(
|
||||
{
|
||||
"query": q,
|
||||
"start": str(start) + "000000000",
|
||||
"end": str(end) + "000000000",
|
||||
"limit": "10",
|
||||
}
|
||||
)
|
||||
out = compose("exec", "-T", "loki", "wget", "-qO-", url)
|
||||
data = json.loads(out.stdout)
|
||||
streams = data.get("data", {}).get("result", [])
|
||||
print("http_request streams", len(streams), "lines", sum(len(s.get("values", [])) for s in streams))
|
||||
for stream in streams[:3]:
|
||||
for value in stream.get("values", [])[:2]:
|
||||
print(value[1][:400])
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,126 @@
|
||||
#!/usr/bin/env python3
|
||||
import base64
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BASE = "http://127.0.0.1:8080"
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run(
|
||||
["docker", "compose", "--env-file", ".env", *args],
|
||||
cwd=str(ROOT),
|
||||
capture_output=True,
|
||||
text=True,
|
||||
)
|
||||
|
||||
|
||||
def http(method, path, body=None, headers=None):
|
||||
data = None if body is None else json.dumps(body).encode()
|
||||
req = urllib.request.Request(BASE + path, data=data, method=method, headers=headers or {})
|
||||
if data is not None:
|
||||
req.add_header("Content-Type", "application/json")
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
raw = resp.read()
|
||||
payload = json.loads(raw.decode()) if raw else None
|
||||
return resp.status, dict(resp.headers), payload
|
||||
|
||||
|
||||
def main():
|
||||
stamp = uuid.uuid4().hex[:10]
|
||||
users = []
|
||||
for idx in range(2):
|
||||
username = f"tr_{stamp}_{idx}"
|
||||
http("POST", "/api/v1/users", {"username": username, "display_name": username, "password": "Password123!"})
|
||||
auth = "Basic " + base64.b64encode(f"{username}:Password123!".encode()).decode()
|
||||
_status, _headers, session = http("POST", "/api/v1/auth/sessions", headers={"Authorization": auth})
|
||||
users.append(session)
|
||||
_status, _headers, chat = http(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
{"title": "t", "member_ids": [users[0]["user"]["id"], users[1]["user"]["id"]]},
|
||||
headers={"Authorization": "Bearer " + users[0]["token"]},
|
||||
)
|
||||
png = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
req = urllib.request.Request(
|
||||
BASE + f"/api/v1/chats/{chat['id']}/attachments?filename=t.png",
|
||||
data=png,
|
||||
method="POST",
|
||||
headers={"Authorization": "Bearer " + users[0]["token"], "Content-Type": "image/png"},
|
||||
)
|
||||
with urllib.request.urlopen(req) as resp:
|
||||
attachment = json.loads(resp.read().decode())
|
||||
request_id = resp.headers.get("X-Request-Id")
|
||||
print("upload", resp.status, attachment["id"], request_id)
|
||||
for _ in range(60):
|
||||
_status, _headers, payload = http(
|
||||
"GET",
|
||||
f"/api/v1/attachments/{attachment['id']}",
|
||||
headers={"Authorization": "Bearer " + users[0]["token"]},
|
||||
)
|
||||
if payload.get("status") == "ready":
|
||||
print("ready")
|
||||
break
|
||||
time.sleep(0.5)
|
||||
time.sleep(6)
|
||||
for service in ("messenger-api", "messenger-worker"):
|
||||
q = urllib.parse.urlencode({"tags": f"service.name={service}", "limit": "20"})
|
||||
out = compose("exec", "-T", "tempo", "wget", "-qO-", f"http://127.0.0.1:3200/api/search?{q}")
|
||||
print(service, out.stdout[:800])
|
||||
q = urllib.parse.urlencode({"query": '{service_name="messenger-api"} |= "http_request"', "limit": "5"})
|
||||
out = compose("exec", "-T", "loki", "wget", "-qO-", "http://127.0.0.1:3100/loki/api/v1/query?" + q)
|
||||
print("loki", out.stdout[:600])
|
||||
# worker stop age probe
|
||||
compose("stop", "worker")
|
||||
req = urllib.request.Request(
|
||||
BASE + f"/api/v1/chats/{chat['id']}/attachments?filename=lag.png",
|
||||
data=png,
|
||||
method="POST",
|
||||
headers={"Authorization": "Bearer " + users[0]["token"], "Content-Type": "image/png"},
|
||||
)
|
||||
with urllib.request.urlopen(req) as resp:
|
||||
queued = json.loads(resp.read().decode())
|
||||
print("queued", resp.status, queued["id"])
|
||||
ages = []
|
||||
fired = None
|
||||
started = time.time()
|
||||
while time.time() - started < 150:
|
||||
q = urllib.parse.urlencode(
|
||||
{
|
||||
"query": 'max(messenger_queue_oldest_job_age_seconds{messaging_destination_name="attachments.process"})'
|
||||
}
|
||||
)
|
||||
out = compose("exec", "-T", "prometheus", "wget", "-qO-", "http://localhost:9090/api/v1/query?" + q)
|
||||
age = None
|
||||
try:
|
||||
payload = json.loads(out.stdout)
|
||||
rows = payload.get("data", {}).get("result", [])
|
||||
if rows:
|
||||
age = float(rows[0]["value"][1])
|
||||
except Exception:
|
||||
age = None
|
||||
ages.append({"t": round(time.time() - started, 1), "age": age})
|
||||
alerts = compose("exec", "-T", "prometheus", "wget", "-qO-", "http://localhost:9090/api/v1/alerts")
|
||||
try:
|
||||
alert_payload = json.loads(alerts.stdout)
|
||||
for item in alert_payload.get("data", {}).get("alerts", []):
|
||||
if item.get("labels", {}).get("alertname") == "GrowingQueueLag" and item.get("state") == "firing":
|
||||
fired = round(time.time() - started, 1)
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
if fired is not None:
|
||||
break
|
||||
time.sleep(5)
|
||||
compose("start", "worker")
|
||||
print(json.dumps({"ages": ages[-8:], "fired_after_seconds": fired}, ensure_ascii=False, indent=2))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,136 @@
|
||||
"""Негативные проверки API. Токены и пароли не печатаются."""
|
||||
import json
|
||||
import struct
|
||||
import sys
|
||||
import uuid
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure # noqa: E402
|
||||
|
||||
|
||||
def png(width, height, payload=b""):
|
||||
def chunk(tag, data):
|
||||
return struct.pack(">I", len(data)) + tag + data + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
|
||||
|
||||
ihdr = struct.pack(">IIBBBBB", width, height, 8, 2, 0, 0, 0)
|
||||
return b"\x89PNG\r\n\x1a\n" + chunk(b"IHDR", ihdr) + payload + chunk(b"IEND", b"")
|
||||
|
||||
|
||||
def main():
|
||||
base = sys.argv[1] if len(sys.argv) > 1 else "http://127.0.0.1:8080"
|
||||
client = Client(base)
|
||||
alice = client.user("n1")
|
||||
bob = client.user("n2")
|
||||
eve = client.user("n3")
|
||||
chat = client.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=alice,
|
||||
body={"title": "Негативные", "member_ids": [alice["id"].upper(), bob["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
other = client.call(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
201,
|
||||
actor=alice,
|
||||
body={"title": "Другой", "member_ids": [alice["id"], bob["id"]]},
|
||||
schema="Chat",
|
||||
)["json"]
|
||||
upper = client.call("GET", "/api/v1/chats/" + chat["id"].upper(), actor=bob, schema="Chat")["json"]
|
||||
results = []
|
||||
|
||||
def record(name, status):
|
||||
results.append({"name": name, "status": status})
|
||||
|
||||
record("chat_uuid_case", 200 if upper["id"] == chat["id"] else 0)
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
record("blank_text", client.call("POST", path, 400, actor=alice, body={"text": " "}, headers={"Idempotency-Key": "blank-1"})["status"])
|
||||
record("bad_json", client.call("POST", path, 400, actor=alice, raw=b"{", headers={"Content-Type": "application/json", "Idempotency-Key": "bad-json"})["status"])
|
||||
record("short_password", client.call("POST", "/api/v1/users", 400, body={"username": "abc", "display_name": "Имя", "password": "short"})["status"])
|
||||
key = uuid.uuid4().hex
|
||||
first = client.call("POST", path, 201, actor=alice, body={"text": "одно"}, headers={"Idempotency-Key": key}, schema="Message")["json"]
|
||||
second = client.call(
|
||||
"POST",
|
||||
path,
|
||||
201,
|
||||
actor=alice,
|
||||
body={"text": "одно", "attachment_ids": []},
|
||||
headers={"Idempotency-Key": key},
|
||||
schema="Message",
|
||||
)["json"]
|
||||
record("omitted_equals_empty", 201 if first == second else 0)
|
||||
record("same_key_other_body", client.call("POST", path, 409, actor=alice, body={"text": "другое"}, headers={"Idempotency-Key": key})["status"])
|
||||
history = client.call("GET", path.replace("/messages", "/messages?limit=100"), actor=bob, schema="MessagePage")["json"]
|
||||
record("no_second_row", 200 if sum(1 for item in history["items"] if item["text"] in ("одно", "другое")) == 1 else 0)
|
||||
other_path = "/api/v1/chats/" + other["id"] + "/messages"
|
||||
other_message = client.call(
|
||||
"POST",
|
||||
other_path,
|
||||
201,
|
||||
actor=alice,
|
||||
body={"text": "одно"},
|
||||
headers={"Idempotency-Key": key},
|
||||
schema="Message",
|
||||
)["json"]
|
||||
record("same_key_other_chat", 201 if other_message["id"] != first["id"] else 0)
|
||||
record("foreign_chat", client.call("GET", "/api/v1/chats/" + chat["id"], 404, actor=eve)["status"])
|
||||
record("bad_cursor", client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?cursor=not-a-cursor", 400, actor=alice)["status"])
|
||||
upload = "/api/v1/chats/" + chat["id"] + "/attachments"
|
||||
record("slash_name", client.call("POST", upload + "?filename=a/b.png", 400, actor=alice, raw=png(1, 1), headers={"Content-Type": "image/png"})["status"])
|
||||
record("huge_pixels", client.call("POST", upload + "?filename=big.png", 413, actor=alice, raw=png(8000, 8000), headers={"Content-Type": "image/png"})["status"])
|
||||
record("bad_png", client.call("POST", upload + "?filename=bad.png", 415, actor=alice, raw=b"\x89PNG\r\n\x1a\nbroken", headers={"Content-Type": "image/png"})["status"])
|
||||
record("type_mismatch", client.call("POST", upload + "?filename=no.jpg", 415, actor=alice, raw=png(1, 1), headers={"Content-Type": "image/jpeg"})["status"])
|
||||
record("oversize", client.call("POST", upload + "?filename=over.png", 413, actor=alice, raw=b"x" * (10 * 1024 * 1024 + 1), headers={"Content-Type": "image/png"})["status"])
|
||||
missing = str(uuid.uuid4())
|
||||
record("unknown_attachment", client.call("GET", "/api/v1/attachments/" + missing.upper(), 404, actor=alice)["status"])
|
||||
record("no_token", client.call("GET", "/api/v1/users/me", 401)["status"])
|
||||
payload = {
|
||||
"command": "python -X utf8 student-tests/run_negative.py",
|
||||
"result": "PASS negative",
|
||||
"results": results,
|
||||
}
|
||||
body = json.dumps(payload, ensure_ascii=False, indent=2)
|
||||
print(body)
|
||||
failed = [item for item in results if item["status"] not in (200, 201, 400, 401, 404, 409, 413, 415)]
|
||||
if failed:
|
||||
return 1
|
||||
expected = {
|
||||
"chat_uuid_case": 200,
|
||||
"blank_text": 400,
|
||||
"bad_json": 400,
|
||||
"short_password": 400,
|
||||
"omitted_equals_empty": 201,
|
||||
"same_key_other_body": 409,
|
||||
"no_second_row": 200,
|
||||
"same_key_other_chat": 201,
|
||||
"foreign_chat": 404,
|
||||
"bad_cursor": 400,
|
||||
"slash_name": 400,
|
||||
"huge_pixels": 413,
|
||||
"bad_png": 415,
|
||||
"type_mismatch": 415,
|
||||
"oversize": 413,
|
||||
"unknown_attachment": 404,
|
||||
"no_token": 401,
|
||||
}
|
||||
for name, status in expected.items():
|
||||
got = next(item["status"] for item in results if item["name"] == name)
|
||||
if got != status:
|
||||
print("mismatch " + name, file=sys.stderr)
|
||||
return 1
|
||||
(ROOT / "evidence" / "negative.json").write_text(body + "\n", encoding="utf-8")
|
||||
print("PASS negative")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except Failure as exc:
|
||||
print("FAIL " + str(exc), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
@@ -0,0 +1,474 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Учебные проверки наблюдаемости и инцидентов. Пароли не печатает."""
|
||||
from __future__ import annotations
|
||||
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
BASE = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
|
||||
OUT = ROOT / "evidence" / "observability.json"
|
||||
|
||||
|
||||
def http_json(method, path, body=None, headers=None, timeout=30):
|
||||
data = None if body is None else json.dumps(body).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
BASE + path,
|
||||
data=data,
|
||||
method=method,
|
||||
headers=headers or {},
|
||||
)
|
||||
if data is not None:
|
||||
req.add_header("Content-Type", "application/json")
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=timeout) as resp:
|
||||
raw = resp.read()
|
||||
payload = json.loads(raw.decode("utf-8")) if raw else None
|
||||
return resp.status, dict(resp.headers), payload
|
||||
except urllib.error.HTTPError as exc:
|
||||
raw = exc.read()
|
||||
payload = None
|
||||
if raw:
|
||||
try:
|
||||
payload = json.loads(raw.decode("utf-8"))
|
||||
except ValueError:
|
||||
payload = {"raw": raw.decode("utf-8", errors="replace")[:200]}
|
||||
return exc.code, dict(exc.headers), payload
|
||||
|
||||
|
||||
def compose(*args):
|
||||
cmd = ["docker", "compose", "--env-file", ".env", *args]
|
||||
return subprocess.run(cmd, cwd=str(ROOT), capture_output=True, text=True, check=False)
|
||||
|
||||
|
||||
def prom_query(expr):
|
||||
q = urllib.parse.urlencode({"query": expr})
|
||||
url = "http://127.0.0.1:9090/api/v1/query?" + q
|
||||
# Prometheus не опубликован наружу. Читаем через docker exec.
|
||||
result = compose("exec", "-T", "prometheus", "wget", "-qO-", "http://localhost:9090/api/v1/query?" + q)
|
||||
if result.returncode != 0:
|
||||
return None
|
||||
try:
|
||||
payload = json.loads(result.stdout)
|
||||
except ValueError:
|
||||
return None
|
||||
rows = payload.get("data", {}).get("result", [])
|
||||
if not rows:
|
||||
return 0.0
|
||||
return float(rows[0]["value"][1])
|
||||
|
||||
|
||||
def prom_alerts():
|
||||
result = compose("exec", "-T", "prometheus", "wget", "-qO-", "http://localhost:9090/api/v1/alerts")
|
||||
if result.returncode != 0:
|
||||
return []
|
||||
try:
|
||||
payload = json.loads(result.stdout)
|
||||
except ValueError:
|
||||
return []
|
||||
return payload.get("data", {}).get("alerts", [])
|
||||
|
||||
|
||||
def tempo_search(service, name=None, limit=10):
|
||||
# Tag search + TraceQL fallback.
|
||||
tags = "service.name=" + service
|
||||
q = urllib.parse.urlencode({"tags": tags, "limit": str(limit)})
|
||||
result = compose("exec", "-T", "tempo", "wget", "-qO-", "http://127.0.0.1:3200/api/search?" + q)
|
||||
traces = []
|
||||
if result.returncode == 0:
|
||||
try:
|
||||
traces = json.loads(result.stdout).get("traces", [])
|
||||
except ValueError:
|
||||
traces = []
|
||||
if name:
|
||||
traces = [t for t in traces if name in (t.get("rootTraceName") or "")]
|
||||
if traces:
|
||||
return traces
|
||||
query = f'{{resource.service.name="{service}"}}'
|
||||
if name:
|
||||
query = f'{{resource.service.name="{service}" && name="{name}"}}'
|
||||
q = urllib.parse.urlencode({"q": query, "limit": str(limit)})
|
||||
result = compose("exec", "-T", "tempo", "wget", "-qO-", "http://127.0.0.1:3200/api/search?" + q)
|
||||
if result.returncode != 0:
|
||||
return []
|
||||
try:
|
||||
return json.loads(result.stdout).get("traces", [])
|
||||
except ValueError:
|
||||
return []
|
||||
|
||||
|
||||
def register_and_chat():
|
||||
stamp = datetime.now(timezone.utc).strftime("%Y%m%d%H%M%S%f")
|
||||
users = []
|
||||
for idx in range(2):
|
||||
username = f"obs_{stamp}_{idx}"
|
||||
status, _, user = http_json(
|
||||
"POST",
|
||||
"/api/v1/users",
|
||||
{"username": username, "display_name": username, "password": "Password123!"},
|
||||
)
|
||||
assert status == 201, status
|
||||
status, _, session = http_json(
|
||||
"POST",
|
||||
"/api/v1/auth/sessions",
|
||||
headers={"Authorization": "Basic " + __import__("base64").b64encode(f"{username}:Password123!".encode()).decode()},
|
||||
)
|
||||
assert status == 201, status
|
||||
users.append({"user": user, "token": session["token"]})
|
||||
status, _, chat = http_json(
|
||||
"POST",
|
||||
"/api/v1/chats",
|
||||
{"title": "obs", "member_ids": [users[0]["user"]["id"], users[1]["user"]["id"]]},
|
||||
headers={"Authorization": "Bearer " + users[0]["token"]},
|
||||
)
|
||||
assert status == 201, status
|
||||
return users, chat
|
||||
|
||||
|
||||
def upload_png(token, chat_id, name="probe.png"):
|
||||
data = (ROOT / "tests" / "fixtures" / "sample.png").read_bytes()
|
||||
req = urllib.request.Request(
|
||||
f"{BASE}/api/v1/chats/{chat_id}/attachments?filename={urllib.parse.quote(name)}",
|
||||
data=data,
|
||||
method="POST",
|
||||
headers={
|
||||
"Authorization": "Bearer " + token,
|
||||
"Content-Type": "image/png",
|
||||
"Content-Length": str(len(data)),
|
||||
},
|
||||
)
|
||||
with urllib.request.urlopen(req, timeout=30) as resp:
|
||||
payload = json.loads(resp.read().decode("utf-8"))
|
||||
return resp.status, dict(resp.headers), payload
|
||||
|
||||
|
||||
def api_direct(method, path, token=None, timeout=3):
|
||||
"""Запрос внутрь контейнера API, минуя HAProxy. Нужен, когда ready уже красный."""
|
||||
headers = ["-H", "Accept: application/json"]
|
||||
if token:
|
||||
headers.extend(["-H", f"Authorization: Bearer {token}"])
|
||||
cmd = [
|
||||
"exec",
|
||||
"-T",
|
||||
"api",
|
||||
"python",
|
||||
"-c",
|
||||
(
|
||||
"import os,urllib.request,sys\n"
|
||||
f"req=urllib.request.Request('http://127.0.0.1:8080{path}', method='{method}')\n"
|
||||
),
|
||||
]
|
||||
# Проще через wget/python one-liner in api container.
|
||||
py = (
|
||||
"import urllib.request,urllib.error\n"
|
||||
f"req=urllib.request.Request('http://127.0.0.1:8080{path}', method='{method}')\n"
|
||||
)
|
||||
if token:
|
||||
py += f"req.add_header('Authorization', 'Bearer {token}')\n"
|
||||
py += (
|
||||
"try:\n"
|
||||
f" r=urllib.request.urlopen(req, timeout={timeout})\n"
|
||||
" print(r.status)\n"
|
||||
"except urllib.error.HTTPError as e:\n"
|
||||
" print(e.code)\n"
|
||||
"except Exception as e:\n"
|
||||
" print(type(e).__name__)\n"
|
||||
)
|
||||
result = compose("exec", "-T", "api", "python", "-c", py)
|
||||
text = (result.stdout or "").strip().splitlines()
|
||||
return text[-1] if text else "empty"
|
||||
|
||||
|
||||
def wait_ready_attachment(token, attachment_id, timeout=60):
|
||||
deadline = time.time() + timeout
|
||||
while time.time() < deadline:
|
||||
status, _, payload = http_json(
|
||||
"GET",
|
||||
f"/api/v1/attachments/{attachment_id}",
|
||||
headers={"Authorization": "Bearer " + token},
|
||||
)
|
||||
if status == 200 and payload.get("status") == "ready":
|
||||
return payload
|
||||
time.sleep(0.5)
|
||||
raise TimeoutError(attachment_id)
|
||||
|
||||
|
||||
def scenario_trace_link():
|
||||
users, chat = register_and_chat()
|
||||
token = users[0]["token"]
|
||||
status, headers, attachment = upload_png(token, chat["id"])
|
||||
assert status == 202, status
|
||||
ready = wait_ready_attachment(token, attachment["id"])
|
||||
time.sleep(3)
|
||||
api_traces = tempo_search("messenger-api", "POST /api/v1/chats/{chat_id}/attachments")
|
||||
worker_traces = tempo_search("messenger-worker", "attachments.process consume")
|
||||
return {
|
||||
"ok": True,
|
||||
"attachment_id": attachment["id"],
|
||||
"attachment_status": ready["status"],
|
||||
"request_id": headers.get("X-Request-Id") or headers.get("x-request-id"),
|
||||
"api_upload_traces": len(api_traces),
|
||||
"worker_consume_traces": len(worker_traces),
|
||||
"sample_api_trace": api_traces[0]["traceID"] if api_traces else None,
|
||||
"sample_worker_trace": worker_traces[0]["traceID"] if worker_traces else None,
|
||||
}
|
||||
|
||||
|
||||
def scenario_worker_stop():
|
||||
users, chat = register_and_chat()
|
||||
token = users[0]["token"]
|
||||
compose("stop", "worker")
|
||||
time.sleep(2)
|
||||
status, _, attachment = upload_png(token, chat["id"], "queued.png")
|
||||
assert status == 202, status
|
||||
started = time.time()
|
||||
fired_at = None
|
||||
age_samples = []
|
||||
while time.time() - started < 90:
|
||||
age = prom_query('max(messenger_queue_oldest_job_age_seconds{messaging_destination_name="attachments.process"})')
|
||||
age_samples.append({"t": round(time.time() - started, 1), "age": age})
|
||||
alerts = [a for a in prom_alerts() if a.get("labels", {}).get("alertname") == "GrowingQueueLag" and a.get("state") == "firing"]
|
||||
if alerts and fired_at is None:
|
||||
fired_at = round(time.time() - started, 1)
|
||||
break
|
||||
time.sleep(5)
|
||||
compose("start", "worker")
|
||||
ready = wait_ready_attachment(token, attachment["id"], timeout=120)
|
||||
resolved_at = None
|
||||
recover_started = time.time()
|
||||
while time.time() - recover_started < 120:
|
||||
alerts = [a for a in prom_alerts() if a.get("labels", {}).get("alertname") == "GrowingQueueLag" and a.get("state") == "firing"]
|
||||
if not alerts and fired_at is not None:
|
||||
resolved_at = round(time.time() - recover_started, 1)
|
||||
break
|
||||
time.sleep(5)
|
||||
return {
|
||||
"ok": ready["status"] == "ready",
|
||||
"attachment_id": attachment["id"],
|
||||
"fired_after_seconds": fired_at,
|
||||
"resolved_after_seconds": resolved_at,
|
||||
"age_samples": age_samples[-6:],
|
||||
"final_age": prom_query('messenger_queue_oldest_job_age_seconds{messaging_destination_name="attachments.process"}'),
|
||||
}
|
||||
|
||||
|
||||
def scenario_db_stop():
|
||||
# Отказ Postgres. Через HAProxy ready красный, поэтому бизнес-5xx снимаю прямым
|
||||
# запросом в контейнер API, чтобы метрики и traces остались от приложения.
|
||||
users, chat = register_and_chat()
|
||||
token = users[0]["token"]
|
||||
before_5xx = prom_query('sum(messenger_http_requests_total{http_response_status_class="5xx"}) or vector(0)')
|
||||
compose("stop", "postgres")
|
||||
started = time.time()
|
||||
business_codes = []
|
||||
ready_via_lb = []
|
||||
while time.time() - started < 90:
|
||||
business_codes.append(api_direct("GET", "/api/v1/users/me", token=token))
|
||||
try:
|
||||
ready_status, _, _ = http_json("GET", "/health/ready", timeout=3)
|
||||
except Exception as exc:
|
||||
ready_status = type(exc).__name__
|
||||
ready_via_lb.append(ready_status)
|
||||
time.sleep(1)
|
||||
high_fired = None
|
||||
for sample_t in range(0, 90, 5):
|
||||
pass
|
||||
compose("start", "postgres")
|
||||
deadline = time.time() + 90
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
status, _, payload = http_json("GET", "/health/ready", timeout=3)
|
||||
if status == 200 and payload and payload.get("status") == "ok":
|
||||
break
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(2)
|
||||
# ждём for: 1m у HighHttpErrorRate и запись метрик
|
||||
watch_started = time.time()
|
||||
alerts_timeline = []
|
||||
while time.time() - watch_started < 150:
|
||||
alerts = [
|
||||
a
|
||||
for a in prom_alerts()
|
||||
if a.get("labels", {}).get("alertname")
|
||||
in ("HighHttpErrorRate", "ErrorBudgetBurnFast", "ErrorBudgetBurnSlow")
|
||||
]
|
||||
alerts_timeline.append(
|
||||
{
|
||||
"t": round(time.time() - watch_started, 1),
|
||||
"alerts": [
|
||||
{"alertname": a.get("labels", {}).get("alertname"), "state": a.get("state")}
|
||||
for a in alerts
|
||||
],
|
||||
}
|
||||
)
|
||||
if any(a.get("state") == "firing" for a in alerts) and high_fired is None:
|
||||
high_fired = round(time.time() - watch_started, 1)
|
||||
if high_fired is not None and not any(a.get("state") == "firing" for a in alerts):
|
||||
break
|
||||
time.sleep(5)
|
||||
after_5xx = prom_query('sum(messenger_http_requests_total{http_response_status_class="5xx"}) or vector(0)')
|
||||
return {
|
||||
"ok": True,
|
||||
"business_statuses_direct_api": business_codes[:8] + ["..."] + business_codes[-4:],
|
||||
"ready_via_lb": ready_via_lb[:4] + ["..."] + ready_via_lb[-3:],
|
||||
"http_5xx_before": before_5xx,
|
||||
"http_5xx_after": after_5xx,
|
||||
"high_error_seen_after_seconds": high_fired,
|
||||
"alerts_timeline_tail": alerts_timeline[-6:],
|
||||
"note": "Прямые запросы в api-контейнер, потому что HAProxy при красном ready отдаёт свою 503-страницу",
|
||||
}
|
||||
|
||||
|
||||
def scenario_telemetry_backend_down():
|
||||
users, chat = register_and_chat()
|
||||
token = users[0]["token"]
|
||||
compose("stop", "tempo")
|
||||
compose("stop", "loki")
|
||||
compose("stop", "prometheus")
|
||||
time.sleep(2)
|
||||
mem_before = compose("stats", "--no-stream", "--format", "{{.MemUsage}}", "otel-collector").stdout.strip()
|
||||
status, _, attachment = upload_png(token, chat["id"], "tel.png")
|
||||
assert status == 202, status
|
||||
# API должен жить без telemetry backends
|
||||
ready_status, _, ready_body = http_json("GET", "/health/ready")
|
||||
text_status, _, message = http_json(
|
||||
"POST",
|
||||
f"/api/v1/chats/{chat['id']}/messages",
|
||||
{"text": "telemetry backends down"},
|
||||
headers={
|
||||
"Authorization": "Bearer " + token,
|
||||
"Idempotency-Key": "obs-tel-1",
|
||||
},
|
||||
)
|
||||
time.sleep(8)
|
||||
mem_after = compose("stats", "--no-stream", "--format", "{{.MemUsage}}", "otel-collector").stdout.strip()
|
||||
compose("start", "prometheus")
|
||||
compose("start", "loki")
|
||||
compose("start", "tempo")
|
||||
time.sleep(5)
|
||||
compose("restart", "otel-collector")
|
||||
wait_ready_attachment(token, attachment["id"], timeout=120)
|
||||
return {
|
||||
"ok": ready_status == 200 and text_status == 201,
|
||||
"upload_status": status,
|
||||
"ready_status": ready_status,
|
||||
"message_status": text_status,
|
||||
"message_id": None if not message else message.get("id"),
|
||||
"otel_mem_before": mem_before,
|
||||
"otel_mem_after": mem_after,
|
||||
}
|
||||
|
||||
|
||||
def scenario_burn_rate_spike():
|
||||
# Короткий всплеск и затем более длинная деградация для multi-window burn-rate.
|
||||
users, _chat = register_and_chat()
|
||||
token = users[0]["token"]
|
||||
|
||||
def outage(seconds):
|
||||
compose("stop", "postgres")
|
||||
end = time.time() + seconds
|
||||
while time.time() < end:
|
||||
api_direct("GET", "/api/v1/users/me", token=token)
|
||||
time.sleep(0.5)
|
||||
compose("start", "postgres")
|
||||
deadline = time.time() + 90
|
||||
while time.time() < deadline:
|
||||
try:
|
||||
status, _, payload = http_json("GET", "/health/ready", timeout=3)
|
||||
if status == 200 and payload and payload.get("status") == "ok":
|
||||
return
|
||||
except Exception:
|
||||
pass
|
||||
time.sleep(2)
|
||||
|
||||
# краткий всплеск ~25 с
|
||||
brief_started = time.time()
|
||||
outage(25)
|
||||
brief_high = None
|
||||
brief_burn = None
|
||||
watch = time.time()
|
||||
while time.time() - watch < 120:
|
||||
alerts = prom_alerts()
|
||||
if brief_high is None and any(
|
||||
a.get("labels", {}).get("alertname") == "HighHttpErrorRate" and a.get("state") == "firing" for a in alerts
|
||||
):
|
||||
brief_high = round(time.time() - brief_started, 1)
|
||||
if brief_burn is None and any(
|
||||
a.get("labels", {}).get("alertname") == "ErrorBudgetBurnFast" and a.get("state") == "firing" for a in alerts
|
||||
):
|
||||
brief_burn = round(time.time() - brief_started, 1)
|
||||
if brief_high is not None:
|
||||
break
|
||||
time.sleep(5)
|
||||
|
||||
# длительная деградация ~6 минут
|
||||
long_started = time.time()
|
||||
outage(360)
|
||||
long_slow = None
|
||||
long_fast = None
|
||||
watch = time.time()
|
||||
while time.time() - watch < 240:
|
||||
alerts = prom_alerts()
|
||||
if long_slow is None and any(
|
||||
a.get("labels", {}).get("alertname") == "ErrorBudgetBurnSlow" and a.get("state") == "firing" for a in alerts
|
||||
):
|
||||
long_slow = round(time.time() - long_started, 1)
|
||||
if long_fast is None and any(
|
||||
a.get("labels", {}).get("alertname") == "ErrorBudgetBurnFast" and a.get("state") == "firing" for a in alerts
|
||||
):
|
||||
long_fast = round(time.time() - long_started, 1)
|
||||
if long_slow is not None:
|
||||
break
|
||||
time.sleep(5)
|
||||
return {
|
||||
"ok": True,
|
||||
"brief_spike_seconds": 25,
|
||||
"brief_high_error_fired_after_seconds": brief_high,
|
||||
"brief_burn_fast_fired_after_seconds": brief_burn,
|
||||
"long_degradation_seconds": 360,
|
||||
"long_burn_slow_fired_after_seconds": long_slow,
|
||||
"long_burn_fast_fired_after_seconds": long_fast,
|
||||
"error_ratio_5m": prom_query("messenger:http_error_ratio:5m"),
|
||||
"error_ratio_30m": prom_query("messenger:http_error_ratio:30m"),
|
||||
"note": "Короткий всплеск может не зажечь BurnFast (нет ложного page). Длинная деградация должна зажечь BurnSlow.",
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
report = {
|
||||
"started_at": datetime.now(timezone.utc).isoformat(),
|
||||
"base_url": BASE,
|
||||
"scenarios": {},
|
||||
}
|
||||
for name, func in [
|
||||
("trace_link", scenario_trace_link),
|
||||
("worker_stop", scenario_worker_stop),
|
||||
("db_stop", scenario_db_stop),
|
||||
("telemetry_backend_down", scenario_telemetry_backend_down),
|
||||
("burn_rate_spike", scenario_burn_rate_spike),
|
||||
]:
|
||||
print("RUN", name, flush=True)
|
||||
try:
|
||||
report["scenarios"][name] = func()
|
||||
print("OK", name, flush=True)
|
||||
except Exception as exc:
|
||||
report["scenarios"][name] = {"ok": False, "error": type(exc).__name__, "detail": str(exc)[:300]}
|
||||
print("FAIL", name, type(exc).__name__, flush=True)
|
||||
report["finished_at"] = datetime.now(timezone.utc).isoformat()
|
||||
OUT.write_text(json.dumps(report, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("WROTE", OUT)
|
||||
failed = [k for k, v in report["scenarios"].items() if not v.get("ok")]
|
||||
return 1 if failed else 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
raise SystemExit(main())
|
||||
@@ -0,0 +1,653 @@
|
||||
"""Проверки очереди и трека 2. Токены и пароли не печатаются."""
|
||||
import hashlib
|
||||
import json
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure # noqa: E402
|
||||
from image_probe import jpeg_size # noqa: E402
|
||||
|
||||
BASE = "http://127.0.0.1:8080"
|
||||
EVIDENCE = ROOT / "evidence" / "pipeline.json"
|
||||
INSIDE = r"""
|
||||
import json, logging, os, hashlib
|
||||
from datetime import datetime, timezone
|
||||
logging.disable(logging.CRITICAL)
|
||||
req = json.loads(REQUEST_JSON)
|
||||
from blobs import read_secret, read_bytes, put_bytes, delete_quiet
|
||||
from jobs import bump_pipeline, replay_job, republish
|
||||
import psycopg
|
||||
from psycopg.rows import dict_row
|
||||
url = read_secret(os.environ["DATABASE_URL_FILE"])
|
||||
action = req["action"]
|
||||
out = {"action": action}
|
||||
with psycopg.connect(url, row_factory=dict_row) as conn:
|
||||
if action == "republish":
|
||||
out["ok"] = bool(republish(conn, req["job_id"], req.get("attempt")))
|
||||
elif action == "bump":
|
||||
out["result"] = bump_pipeline(conn, req["attachment_id"])
|
||||
elif action == "replay":
|
||||
out["result"] = replay_job(conn, req["job_id"])
|
||||
elif action == "corrupt":
|
||||
row = conn.execute(
|
||||
"SELECT staging_key FROM attachments WHERE id = %s",
|
||||
(req["attachment_id"],),
|
||||
).fetchone()
|
||||
key = row["staging_key"]
|
||||
data = read_bytes(key)
|
||||
stamp = datetime.now(timezone.utc)
|
||||
put_bytes(key + ".held", data, "application/octet-stream", stamp)
|
||||
put_bytes(key, b"not-an-image", "image/png", stamp)
|
||||
out["original_sha256"] = hashlib.sha256(data).hexdigest()
|
||||
out["bytes"] = len(data)
|
||||
elif action == "restore":
|
||||
row = conn.execute(
|
||||
"SELECT staging_key FROM attachments WHERE id = %s",
|
||||
(req["attachment_id"],),
|
||||
).fetchone()
|
||||
key = row["staging_key"]
|
||||
data = read_bytes(key + ".held")
|
||||
put_bytes(key, data, "image/png", datetime.now(timezone.utc))
|
||||
delete_quiet(key + ".held")
|
||||
out["restored_sha256"] = hashlib.sha256(data).hexdigest()
|
||||
out["bytes"] = len(data)
|
||||
else:
|
||||
raise SystemExit("unknown")
|
||||
print(json.dumps(out))
|
||||
"""
|
||||
|
||||
|
||||
def run(args, timeout=180, check=True):
|
||||
proc = subprocess.run(
|
||||
args,
|
||||
cwd=str(ROOT),
|
||||
capture_output=True,
|
||||
timeout=timeout,
|
||||
)
|
||||
if check and proc.returncode != 0:
|
||||
err = proc.stderr.decode("utf-8", "replace")[-1200:]
|
||||
raise RuntimeError(args[0] + " failed: " + err)
|
||||
return proc
|
||||
|
||||
|
||||
def compose(*args, timeout=180):
|
||||
run(["docker", "compose", "--env-file", ".env", *args], timeout=timeout)
|
||||
|
||||
|
||||
def inspect(name, template):
|
||||
proc = run(["docker", "inspect", "-f", template, name], timeout=30)
|
||||
return proc.stdout.decode().strip()
|
||||
|
||||
|
||||
def wait_health(name, seconds=180):
|
||||
deadline = time.monotonic() + seconds
|
||||
last = ""
|
||||
while time.monotonic() < deadline:
|
||||
last = inspect(name, "{{.State.Status}} {{if .State.Health}}{{.State.Health.Status}}{{end}}")
|
||||
if last.startswith("running healthy"):
|
||||
return last
|
||||
time.sleep(1)
|
||||
raise RuntimeError(name + " not healthy: " + last)
|
||||
|
||||
|
||||
def restart_service(service, containers, seconds=180):
|
||||
if isinstance(containers, str):
|
||||
containers = [containers]
|
||||
before = {name: inspect(name, "{{.State.StartedAt}}") for name in containers}
|
||||
compose("restart", service)
|
||||
deadline = time.monotonic() + seconds
|
||||
last = ""
|
||||
while time.monotonic() < deadline:
|
||||
ready = True
|
||||
for name in containers:
|
||||
started = inspect(name, "{{.State.StartedAt}}")
|
||||
last = inspect(name, "{{.State.Status}} {{if .State.Health}}{{.State.Health.Status}}{{end}}")
|
||||
if started == before[name] or not last.startswith("running healthy"):
|
||||
ready = False
|
||||
if ready:
|
||||
return
|
||||
time.sleep(1)
|
||||
raise RuntimeError(service + " did not restart: " + last)
|
||||
|
||||
|
||||
def psql(sql):
|
||||
proc = run(
|
||||
[
|
||||
"docker", "compose", "--env-file", ".env", "exec", "-T", "postgres",
|
||||
"psql", "-U", "messenger", "-d", "messenger",
|
||||
"-v", "ON_ERROR_STOP=1", "-q", "-t", "-A", "-c", sql,
|
||||
],
|
||||
timeout=30,
|
||||
)
|
||||
return proc.stdout.decode("utf-8").strip()
|
||||
|
||||
|
||||
def state(attachment_id):
|
||||
sql = """
|
||||
SELECT json_build_object(
|
||||
'status', a.status,
|
||||
'error_code', a.error_code,
|
||||
'pipeline_version', a.pipeline_version,
|
||||
'jobs', (
|
||||
SELECT coalesce(json_agg(json_build_object(
|
||||
'id', j.id, 'status', j.status, 'attempt', j.attempt,
|
||||
'pipeline_version', j.pipeline_version, 'error_code', j.error_code
|
||||
) ORDER BY j.pipeline_version), '[]'::json)
|
||||
FROM attachment_jobs j WHERE j.attachment_id = a.id
|
||||
),
|
||||
'variants', (
|
||||
SELECT coalesce(json_agg(json_build_object(
|
||||
'name', v.name, 'pipeline_version', v.pipeline_version,
|
||||
'width', v.width, 'height', v.height, 'content_type', v.content_type
|
||||
) ORDER BY v.pipeline_version, v.name), '[]'::json)
|
||||
FROM attachment_variants v WHERE v.attachment_id = a.id
|
||||
),
|
||||
'unpublished', (
|
||||
SELECT count(*) FROM outbox o
|
||||
JOIN attachment_jobs j ON j.id = o.job_id
|
||||
WHERE j.attachment_id = a.id AND o.published_at IS NULL
|
||||
),
|
||||
'events', (
|
||||
SELECT coalesce(json_agg(e.kind ORDER BY e.created_at), '[]'::json)
|
||||
FROM job_events e WHERE e.attachment_id = a.id
|
||||
)
|
||||
)::text
|
||||
FROM attachments a WHERE a.id = '{id}'::uuid
|
||||
""".format(id=attachment_id)
|
||||
return json.loads(psql(sql))
|
||||
|
||||
|
||||
def arm(kind, attachment_id):
|
||||
target = "NULL" if attachment_id is None else "'" + attachment_id + "'::uuid"
|
||||
psql(
|
||||
"INSERT INTO fault_injections (id, kind, attachment_id, armed) "
|
||||
"VALUES (gen_random_uuid(), '{kind}', {target}, true)".format(kind=kind, target=target)
|
||||
)
|
||||
|
||||
|
||||
def queues():
|
||||
proc = run(
|
||||
[
|
||||
"docker", "compose", "--env-file", ".env", "exec", "-T", "rabbitmq",
|
||||
"rabbitmqctl", "list_queues", "name", "messages", "--quiet",
|
||||
],
|
||||
timeout=30,
|
||||
)
|
||||
found = {}
|
||||
for line in proc.stdout.decode().splitlines():
|
||||
parts = line.split()
|
||||
if len(parts) == 2 and parts[1].isdigit():
|
||||
found[parts[0]] = int(parts[1])
|
||||
return found
|
||||
|
||||
|
||||
def depth():
|
||||
last = ""
|
||||
for _ in range(20):
|
||||
try:
|
||||
found = queues()
|
||||
return found.get("attachments.process", -1)
|
||||
except RuntimeError as exc:
|
||||
last = str(exc)
|
||||
time.sleep(1)
|
||||
raise RuntimeError(last)
|
||||
|
||||
|
||||
def inside(req, timeout=90):
|
||||
code = INSIDE.replace("REQUEST_JSON", json.dumps(json.dumps(req)))
|
||||
proc = run(
|
||||
[
|
||||
"docker", "compose", "--env-file", ".env", "run", "--rm", "--no-deps", "-T",
|
||||
"--entrypoint", "python", "worker", "-c", code,
|
||||
],
|
||||
timeout=timeout,
|
||||
)
|
||||
lines = [line for line in proc.stdout.decode("utf-8").splitlines() if line.startswith("{")]
|
||||
if not lines:
|
||||
raise RuntimeError("no json from worker helper")
|
||||
return json.loads(lines[-1])
|
||||
|
||||
|
||||
def stop_worker():
|
||||
compose("stop", "worker")
|
||||
|
||||
|
||||
def start_worker():
|
||||
compose("start", "worker")
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
if inspect("mtusi-lab5-worker-1", "{{.State.Status}}") == "running":
|
||||
return
|
||||
time.sleep(0.5)
|
||||
raise RuntimeError("worker did not start")
|
||||
|
||||
|
||||
def restart_count():
|
||||
return int(inspect("mtusi-lab5-worker-1", "{{.RestartCount}}"))
|
||||
|
||||
|
||||
def wait_status(actor, attachment_id, want, seconds=90):
|
||||
deadline = time.monotonic() + seconds
|
||||
last = None
|
||||
while time.monotonic() < deadline:
|
||||
body = client.call(
|
||||
"GET", "/api/v1/attachments/" + attachment_id, actor=actor, schema="Attachment"
|
||||
)["json"]
|
||||
last = body["status"]
|
||||
if last == want:
|
||||
return body
|
||||
if want != "failed" and last == "failed":
|
||||
raise Failure("attachment failed " + attachment_id)
|
||||
time.sleep(0.4)
|
||||
raise Failure("timeout status=" + str(last) + " want=" + want)
|
||||
|
||||
|
||||
def check_picture(actor, ready, original):
|
||||
download = client.call("GET", "/api/v1/attachments/" + ready["id"] + "/content", actor=actor)
|
||||
if download["bytes"] != original:
|
||||
raise Failure("original bytes differ")
|
||||
names = {item["name"]: item for item in ready["variants"]}
|
||||
thumb = client.call(
|
||||
"GET", "/api/v1/attachments/" + ready["id"] + "/content?variant=thumbnail", actor=actor
|
||||
)
|
||||
crop = client.call(
|
||||
"GET", "/api/v1/attachments/" + ready["id"] + "/content?variant=crop", actor=actor
|
||||
)
|
||||
optimized = client.call(
|
||||
"GET", "/api/v1/attachments/" + ready["id"] + "/content?variant=optimized", actor=actor
|
||||
)
|
||||
if jpeg_size(thumb["bytes"]) != (256, 160):
|
||||
raise Failure("thumbnail size")
|
||||
if jpeg_size(crop["bytes"]) != (128, 128):
|
||||
raise Failure("crop size")
|
||||
if optimized["bytes"][:4] != b"RIFF" or optimized["bytes"][8:12] != b"WEBP":
|
||||
raise Failure("optimized is not webp")
|
||||
if names["thumbnail"]["width"] != 256 or names["thumbnail"]["height"] != 160:
|
||||
raise Failure("thumbnail metadata")
|
||||
if names["crop"]["width"] != 128 or names["crop"]["height"] != 128:
|
||||
raise Failure("crop metadata")
|
||||
if names["optimized"]["width"] != 320 or names["optimized"]["height"] != 200:
|
||||
raise Failure("optimized metadata")
|
||||
if hashlib.sha256(thumb["bytes"]).hexdigest() != names["thumbnail"]["sha256"]:
|
||||
raise Failure("thumbnail sha")
|
||||
rows = state(ready["id"])
|
||||
version_rows = [row for row in rows["variants"] if row["pipeline_version"] == rows["pipeline_version"]]
|
||||
if len(version_rows) != 4:
|
||||
raise Failure("variant rows " + str(len(version_rows)))
|
||||
return {
|
||||
"pipeline_version": rows["pipeline_version"],
|
||||
"variant_rows": len(version_rows),
|
||||
"thumbnail": [names["thumbnail"]["width"], names["thumbnail"]["height"]],
|
||||
"crop": [names["crop"]["width"], names["crop"]["height"]],
|
||||
"optimized": [names["optimized"]["width"], names["optimized"]["height"]],
|
||||
"original_sha256": hashlib.sha256(original).hexdigest(),
|
||||
}
|
||||
|
||||
|
||||
def upload(actor, chat):
|
||||
att, content = client.attachment(actor, chat)
|
||||
return att, content
|
||||
|
||||
|
||||
results = []
|
||||
|
||||
|
||||
def scenario(name, fn):
|
||||
started = time.monotonic()
|
||||
try:
|
||||
detail = fn()
|
||||
results.append({"name": name, "ok": True, "seconds": round(time.monotonic() - started, 3), "detail": detail})
|
||||
except Exception as exc:
|
||||
results.append({"name": name, "ok": False, "seconds": round(time.monotonic() - started, 3), "error": type(exc).__name__ + ": " + str(exc)})
|
||||
raise
|
||||
|
||||
|
||||
client = Client(BASE, timeout=20)
|
||||
|
||||
|
||||
def durability():
|
||||
stop_worker()
|
||||
alice, bob, _eve, chat = client.bootstrap()
|
||||
att, content = upload(alice, chat)
|
||||
blocked = client.call("GET", "/api/v1/attachments/" + att["id"] + "/content", 409, actor=bob)
|
||||
text = client.message(alice, chat, "текст пока файл в очереди")["json"]
|
||||
linked = client.message(alice, chat, "", attachments=[att["id"]])["json"]
|
||||
before_api = depth()
|
||||
if before_api < 1:
|
||||
raise Failure("job was not in the durable queue")
|
||||
restart_service("api", ["mtusi-lab5-api-1", "mtusi-lab5-api-2"])
|
||||
after_api = depth()
|
||||
restart_service("rabbitmq", "mtusi-lab5-rabbitmq-1", 180)
|
||||
after_rabbit = depth()
|
||||
if after_api < 1 or after_rabbit < 1:
|
||||
raise Failure("queue lost the job")
|
||||
start_worker()
|
||||
ready = wait_status(bob, att["id"], "ready", 90)
|
||||
picture = check_picture(bob, ready, content)
|
||||
return {
|
||||
"upload_status": att["status"],
|
||||
"content_while_queued": blocked["status"],
|
||||
"text_status": 201,
|
||||
"text_id": text["id"],
|
||||
"linked_id": linked["id"],
|
||||
"queue_before_api_restart": before_api,
|
||||
"queue_after_api_restart": after_api,
|
||||
"queue_after_rabbit_restart": after_rabbit,
|
||||
"picture": picture,
|
||||
}
|
||||
|
||||
|
||||
def outbox_gap():
|
||||
stop_worker()
|
||||
alice, bob, _eve, chat = client.bootstrap()
|
||||
arm("skip_inline_publish", None)
|
||||
before = depth()
|
||||
att, content = upload(alice, chat)
|
||||
info = state(att["id"])
|
||||
queued = depth()
|
||||
if info["unpublished"] != 1 or queued != before:
|
||||
raise Failure("outbox was published early")
|
||||
start_worker()
|
||||
ready = wait_status(bob, att["id"], "ready", 90)
|
||||
picture = check_picture(bob, ready, content)
|
||||
return {"unpublished_before_worker": info["unpublished"], "queue_depth": queued, "picture": picture}
|
||||
|
||||
|
||||
def duplicate():
|
||||
stop_worker()
|
||||
alice, bob, _eve, chat = client.bootstrap()
|
||||
att, content = upload(alice, chat)
|
||||
info = state(att["id"])
|
||||
job_id = info["jobs"][0]["id"]
|
||||
published = inside({"action": "republish", "job_id": job_id})
|
||||
start_worker()
|
||||
ready = wait_status(bob, att["id"], "ready", 90)
|
||||
picture = check_picture(bob, ready, content)
|
||||
return {"republish": published["ok"], "picture": picture}
|
||||
|
||||
|
||||
def reorder():
|
||||
stop_worker()
|
||||
alice, bob, _eve, chat = client.bootstrap()
|
||||
att, content = upload(alice, chat)
|
||||
info = state(att["id"])
|
||||
job_id = info["jobs"][0]["id"]
|
||||
inside({"action": "republish", "job_id": job_id, "attempt": 2})
|
||||
start_worker()
|
||||
ready = wait_status(bob, att["id"], "ready", 90)
|
||||
picture = check_picture(bob, ready, content)
|
||||
after = state(att["id"])
|
||||
if after["jobs"][0]["attempt"] != 1 or after["status"] != "ready":
|
||||
raise Failure("reorder changed the job")
|
||||
return {"attempt": after["jobs"][0]["attempt"], "picture": picture}
|
||||
|
||||
|
||||
def stale_version():
|
||||
stop_worker()
|
||||
alice, bob, _eve, chat = client.bootstrap()
|
||||
att, content = upload(alice, chat)
|
||||
info = state(att["id"])
|
||||
old_job = info["jobs"][0]["id"]
|
||||
bumped = inside({"action": "bump", "attachment_id": att["id"]})
|
||||
start_worker()
|
||||
ready = wait_status(bob, att["id"], "ready", 90)
|
||||
before = check_picture(bob, ready, content)
|
||||
thumb_before = client.call(
|
||||
"GET", "/api/v1/attachments/" + att["id"] + "/content?variant=thumbnail", actor=bob
|
||||
)["bytes"]
|
||||
inside({"action": "republish", "job_id": old_job, "attempt": 1})
|
||||
time.sleep(2)
|
||||
ready2 = client.call("GET", "/api/v1/attachments/" + att["id"], actor=bob, schema="Attachment")["json"]
|
||||
thumb_after = client.call(
|
||||
"GET", "/api/v1/attachments/" + att["id"] + "/content?variant=thumbnail", actor=bob
|
||||
)["bytes"]
|
||||
after = state(att["id"])
|
||||
old = [job for job in after["jobs"] if job["id"] == old_job][0]
|
||||
if ready2["status"] != "ready" or after["pipeline_version"] != 2:
|
||||
raise Failure("new version was overwritten")
|
||||
if old["status"] != "superseded":
|
||||
raise Failure("old job was not superseded")
|
||||
if thumb_before != thumb_after:
|
||||
raise Failure("old job changed thumbnail")
|
||||
return {
|
||||
"bump": bumped["result"],
|
||||
"old_job_status": old["status"],
|
||||
"old_error_code": old["error_code"],
|
||||
"attachment_error_code": after["error_code"],
|
||||
"picture": before,
|
||||
"thumbnail_unchanged": True,
|
||||
}
|
||||
|
||||
|
||||
def crash(kind):
|
||||
stop_worker()
|
||||
alice, bob, _eve, chat = client.bootstrap()
|
||||
att, content = upload(alice, chat)
|
||||
arm(kind, att["id"])
|
||||
start_worker()
|
||||
born = inspect("mtusi-lab5-worker-1", "{{.State.StartedAt}}")
|
||||
ready = wait_status(bob, att["id"], "ready", 120)
|
||||
picture = check_picture(bob, ready, content)
|
||||
restarted = inspect("mtusi-lab5-worker-1", "{{.State.StartedAt}}")
|
||||
if born == restarted:
|
||||
raise Failure("worker did not exit")
|
||||
return {"started_at": born, "restarted_at": restarted, "picture": picture}
|
||||
|
||||
|
||||
def transient():
|
||||
alice, bob, _eve, chat = client.bootstrap()
|
||||
stop_worker()
|
||||
att, _content = upload(alice, chat)
|
||||
arm("transient_once", att["id"])
|
||||
start_worker()
|
||||
wait_status(bob, att["id"], "ready", 90)
|
||||
info = state(att["id"])
|
||||
version_rows = [row for row in info["variants"] if row["pipeline_version"] == info["pipeline_version"]]
|
||||
if info["jobs"][0]["attempt"] != 2 or "retry" not in info["events"] or len(version_rows) != 4:
|
||||
raise Failure("transient retry did not keep one result")
|
||||
return {
|
||||
"attempt": info["jobs"][0]["attempt"],
|
||||
"events": info["events"],
|
||||
"variant_rows": len(version_rows),
|
||||
"status": info["status"],
|
||||
}
|
||||
|
||||
|
||||
def permanent_and_replay():
|
||||
stop_worker()
|
||||
alice, bob, _eve, chat = client.bootstrap()
|
||||
att, content = upload(alice, chat)
|
||||
corrupted = inside({"action": "corrupt", "attachment_id": att["id"]})
|
||||
start_worker()
|
||||
failed = wait_status(bob, att["id"], "failed", 90)
|
||||
info = state(att["id"])
|
||||
restored = inside({"action": "restore", "attachment_id": att["id"]})
|
||||
replayed = inside({"action": "replay", "job_id": info["jobs"][0]["id"]})
|
||||
ready = wait_status(bob, att["id"], "ready", 90)
|
||||
picture = check_picture(bob, ready, content)
|
||||
again = inside({"action": "replay", "job_id": info["jobs"][0]["id"]})
|
||||
after = state(att["id"])
|
||||
version_rows = [row for row in after["variants"] if row["pipeline_version"] == after["pipeline_version"]]
|
||||
if failed["error_code"] != "invalid_image" or info["jobs"][0]["attempt"] != 1:
|
||||
raise Failure("permanent error was retried")
|
||||
if replayed["result"].get("result") != "queued" or again["result"].get("result") != "already_ready":
|
||||
raise Failure("replay result")
|
||||
if len(version_rows) != 4 or restored["restored_sha256"] != corrupted["original_sha256"]:
|
||||
raise Failure("replay did not keep one result")
|
||||
return {
|
||||
"corrupt_sha256": corrupted["original_sha256"],
|
||||
"failed_code": failed["error_code"],
|
||||
"attempt_at_fail": info["jobs"][0]["attempt"],
|
||||
"restored_sha256": restored["restored_sha256"],
|
||||
"replay": replayed["result"],
|
||||
"second_replay": again["result"],
|
||||
"variant_rows": len(version_rows),
|
||||
"picture": picture,
|
||||
}
|
||||
|
||||
|
||||
def lease():
|
||||
stop_worker()
|
||||
alice, bob, _eve, chat = client.bootstrap()
|
||||
arm("skip_inline_publish", None)
|
||||
before = depth()
|
||||
att, content = upload(alice, chat)
|
||||
info = state(att["id"])
|
||||
if info["unpublished"] != 1 or depth() != before:
|
||||
raise Failure("lease setup published the job")
|
||||
job_id = info["jobs"][0]["id"]
|
||||
psql(
|
||||
"UPDATE attachment_jobs SET status = 'processing', lease_owner = 'dead', "
|
||||
"lease_until = now() - interval '2 minutes', updated_at = now() "
|
||||
"WHERE id = '{id}'::uuid".format(id=job_id)
|
||||
)
|
||||
psql(
|
||||
"UPDATE attachments SET status = 'processing', updated_at = now() WHERE id = '{id}'::uuid".format(
|
||||
id=att["id"]
|
||||
)
|
||||
)
|
||||
psql("DELETE FROM outbox WHERE job_id = '{id}'::uuid AND published_at IS NULL".format(id=job_id))
|
||||
started = time.monotonic()
|
||||
start_worker()
|
||||
ready = wait_status(bob, att["id"], "ready", 90)
|
||||
elapsed = round(time.monotonic() - started, 3)
|
||||
picture = check_picture(bob, ready, content)
|
||||
info = state(att["id"])
|
||||
if "lease_expired" not in info["events"] or info["jobs"][0]["attempt"] != 1:
|
||||
raise Failure("expired lease was not resumed")
|
||||
return {
|
||||
"seconds_until_ready": elapsed,
|
||||
"events": info["events"],
|
||||
"attempt": info["jobs"][0]["attempt"],
|
||||
"picture": picture,
|
||||
}
|
||||
|
||||
|
||||
def http_status(url):
|
||||
req = urllib.request.Request(url, headers={"Accept": "application/json"})
|
||||
try:
|
||||
with urllib.request.urlopen(req, timeout=10) as response:
|
||||
return response.status, response.read(4096).decode("utf-8", "replace")
|
||||
except urllib.error.HTTPError as error:
|
||||
return error.code, error.read(4096).decode("utf-8", "replace")
|
||||
|
||||
|
||||
def leaked(text):
|
||||
lowered = text.lower()
|
||||
return [
|
||||
word for word in (
|
||||
"redis", "postgres", "minio", "password", "select", "rabbit", "amqp",
|
||||
"secret", "database", "bucket", "messenger-attachments",
|
||||
)
|
||||
if word in lowered
|
||||
]
|
||||
|
||||
|
||||
def ready_503():
|
||||
compose("stop", "redis")
|
||||
time.sleep(2)
|
||||
lb_status, lb_body = http_status(BASE + "/health/ready")
|
||||
proc = run(
|
||||
[
|
||||
"docker", "exec", "mtusi-lab5-api-1", "python", "-c",
|
||||
"import urllib.request,urllib.error\n"
|
||||
"req=urllib.request.Request('http://127.0.0.1:8080/health/ready')\n"
|
||||
"try:\n"
|
||||
" r=urllib.request.urlopen(req, timeout=5)\n"
|
||||
" print(r.status)\n"
|
||||
" print(r.read(4096).decode())\n"
|
||||
"except urllib.error.HTTPError as e:\n"
|
||||
" print(e.code)\n"
|
||||
" print(e.read(4096).decode())\n",
|
||||
],
|
||||
timeout=20,
|
||||
)
|
||||
lines = proc.stdout.decode("utf-8", "replace").splitlines()
|
||||
api_status = int(lines[0])
|
||||
api_body = "\n".join(lines[1:])
|
||||
compose("start", "redis")
|
||||
wait_health("mtusi-lab5-redis-1")
|
||||
started = time.monotonic()
|
||||
deadline = started + 40
|
||||
recovered = None
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
recovered, _body = http_status(BASE + "/health/ready")
|
||||
except (urllib.error.URLError, TimeoutError, OSError):
|
||||
recovered = 0
|
||||
if recovered == 200:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
recovery_seconds = round(time.monotonic() - started, 3)
|
||||
if lb_status != 503 or api_status != 503 or leaked(lb_body) or leaked(api_body):
|
||||
raise Failure("ready 503 text")
|
||||
if "Сервис временно недоступен" not in api_body or recovered != 200:
|
||||
raise Failure("ready 503 text")
|
||||
return {
|
||||
"lb_status": lb_status,
|
||||
"lb_body": lb_body,
|
||||
"api_status": api_status,
|
||||
"api_message": "Сервис временно недоступен",
|
||||
"forbidden": [],
|
||||
"recovered": recovered,
|
||||
"recovery_seconds": recovery_seconds,
|
||||
}
|
||||
|
||||
|
||||
def main():
|
||||
wait_health("mtusi-lab5-api-1")
|
||||
wait_health("mtusi-lab5-api-2")
|
||||
psql("UPDATE fault_injections SET armed = false WHERE armed")
|
||||
start_worker()
|
||||
deadline = time.monotonic() + 60
|
||||
while time.monotonic() < deadline:
|
||||
if depth() == 0 and queues().get("attachments.retry", 0) == 0:
|
||||
break
|
||||
time.sleep(0.5)
|
||||
steps = [
|
||||
("durability", durability),
|
||||
("outbox_gap", outbox_gap),
|
||||
("duplicate", duplicate),
|
||||
("reorder", reorder),
|
||||
("stale_version", stale_version),
|
||||
("crash_before_effect", lambda: crash("crash_before_effect")),
|
||||
("crash_after_objects", lambda: crash("crash_after_objects")),
|
||||
("crash_after_commit", lambda: crash("crash_after_commit")),
|
||||
("transient_once", transient),
|
||||
("permanent_replay", permanent_and_replay),
|
||||
("lease", lease),
|
||||
("ready_503", ready_503),
|
||||
]
|
||||
if len(sys.argv) > 1 and sys.argv[1] == "resume" and EVIDENCE.is_file():
|
||||
done = [
|
||||
item for item in json.loads(EVIDENCE.read_text(encoding="utf-8"))["results"] if item.get("ok")
|
||||
]
|
||||
results.extend(done)
|
||||
steps = [item for item in steps if item[0] not in {row["name"] for row in done}]
|
||||
failed = None
|
||||
for name, fn in steps:
|
||||
try:
|
||||
scenario(name, fn)
|
||||
except Exception as exc:
|
||||
failed = exc
|
||||
break
|
||||
EVIDENCE.write_text(json.dumps({"results": results}, ensure_ascii=False, indent=2), encoding="utf-8")
|
||||
if failed is not None:
|
||||
print("FAIL " + type(failed).__name__ + ": " + str(failed), file=sys.stderr)
|
||||
return 1
|
||||
print("PASS pipeline")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
raise SystemExit(main())
|
||||
except Failure as exc:
|
||||
print("FAIL " + str(exc), file=sys.stderr)
|
||||
raise SystemExit(1)
|
||||
Reference in New Issue
Block a user