Собрать стенд лабораторной 5: очередь, worker и идемпотентность pipeline.
This commit is contained in:
@@ -0,0 +1,130 @@
|
||||
"""Негативные проверки 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"])
|
||||
body = json.dumps({"results": results}, 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
|
||||
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,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