forked from mtusi2026/mtusi2026lab6
ЛР6
This commit is contained in:
@@ -0,0 +1,96 @@
|
||||
"""lab5, уровень 4: lease для зависшего processing — как отличить зависший worker от долго работающего.
|
||||
|
||||
make lease (= python student-tests/lease_takeover.py)
|
||||
|
||||
1. Долгая задача: точка worker_slow=35 — обработка «идёт» 35 с. Пока worker жив, он продлевает
|
||||
lease каждые JOB_HEARTBEAT_SECONDS (10 с): lease_until в БД сдвигается вперёд. Задание никто
|
||||
не забирает, хотя оно дольше JOB_LEASE_SECONDS (30 с).
|
||||
2. Зависание: запускается второй worker B (docker compose up --scale worker=2), затем контейнер
|
||||
worker A замораживается (docker pause) — процесс есть, но ничего не делает, как при зависании.
|
||||
Продлений нет, lease истекает. Проверка lease в B видит истёкшую аренду, засчитывает попытку
|
||||
как неудачную и назначает следующую. B обрабатывает задание -> ready (попытка 2).
|
||||
3. «Оживший» A: после docker unpause он пытается продлить lease, но жетон уже не его —
|
||||
обработка прерывается, результат не записывается (fencing). В БД ровно один ready и один
|
||||
набор вариантов, автор результата — B.
|
||||
Неконтролируемых дублей нет: одновременно задание держит только владелец действующего lease,
|
||||
а записать результат может только владелец текущего жетона.
|
||||
"""
|
||||
import time
|
||||
|
||||
import ops
|
||||
from filegen import upload_when_ready, wait_status
|
||||
from helpers import Client, check, run
|
||||
|
||||
|
||||
def main():
|
||||
api = Client(timeout=15)
|
||||
ops.scale("worker", 1)
|
||||
worker_a = ops.wait_healthy("worker", 1)[0]
|
||||
alice, bob, _eve, chat = api.bootstrap()
|
||||
paused = False
|
||||
try:
|
||||
ops.arm("worker", "worker_slow", "35", container=worker_a)
|
||||
att = upload_when_ready(api, alice, chat, name="lease.png")["json"]
|
||||
wait_status(api, bob, att["id"], ("processing",), seconds=30, step=0.2)
|
||||
leases = []
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
value = ops.job(att["id"])["job"]["lease_until"]
|
||||
if value and value not in leases:
|
||||
leases.append(value)
|
||||
if len(leases) >= 3:
|
||||
break
|
||||
time.sleep(1)
|
||||
check(len(leases) >= 3, f"the lease was not renewed while the job was running: {leases}")
|
||||
owner = ops.job(att["id"])["job"]["lease_owner"]
|
||||
print(f"1. long job (35 s > lease 30 s) on {owner}: lease_until moved forward "
|
||||
f"{len(leases) - 1} times: {' -> '.join(v[11:19] for v in leases)}")
|
||||
|
||||
ops.scale("worker", 2)
|
||||
ops.wait_healthy("worker", 2)
|
||||
worker_b = [c for c in ops.containers("worker") if c != worker_a][0]
|
||||
print(f"2. worker B {worker_b[:12]} started (the job is still held by A's lease)")
|
||||
ops.pause(worker_a)
|
||||
paused = True
|
||||
frozen_at = time.monotonic()
|
||||
print(f" worker A {worker_a[:12]} frozen (docker pause): no more renewals")
|
||||
ready = wait_status(api, bob, att["id"], seconds=120)
|
||||
job = ops.job(att["id"])
|
||||
took = time.monotonic() - frozen_at
|
||||
winner = [e for e in job["events"] if e["event"] == "ready"]
|
||||
check(job["job"]["attempt"] == 2 and len(winner) == 1, "expected exactly one result at attempt 2")
|
||||
check(not winner[0]["actor"].endswith(owner), "the frozen worker must not be the one who committed")
|
||||
print(f" lease expired -> attempt 2 -> ready {took:.0f} s after the freeze; result committed by "
|
||||
f"{winner[0]['actor']}")
|
||||
print(" events: " + " -> ".join(f"{e['event']}({e['attempt']})" for e in job["events"]))
|
||||
|
||||
ops.unpause(worker_a)
|
||||
paused = False
|
||||
deadline = time.monotonic() + 40
|
||||
lost = []
|
||||
while not lost:
|
||||
lines = [line for line in ops.logs("worker", "5m").splitlines() if job["job"]["job_id"] in line]
|
||||
lost = [line for line in lines if "не продлён" in line or "брошена" in line]
|
||||
if not lost:
|
||||
check(time.monotonic() < deadline, "the woken worker A did not notice that its lease was lost")
|
||||
time.sleep(2)
|
||||
after = ops.job(att["id"])
|
||||
check(after["attachment_status"] == "ready" and after["job"]["attempt"] == 2, "state changed after unpause")
|
||||
check(sum(e["event"] == "ready" for e in after["events"]) == 1 and len(after["variants"]) == 3,
|
||||
"the stale worker wrote a second result")
|
||||
meta = api.call("GET", f"/api/v1/attachments/{att['id']}", actor=bob, schema="Attachment")["json"]
|
||||
check(meta == ready, "metadata changed after the stale worker woke up")
|
||||
print("3. worker A unpaused: " + lost[-1].split(": ", 1)[-1])
|
||||
print(" still exactly one result: status ready, attempt 2, 3 variant rows, metadata unchanged")
|
||||
finally:
|
||||
if paused:
|
||||
ops.unpause(worker_a)
|
||||
ops.disarm("worker", "worker_slow")
|
||||
ops.scale("worker", 1)
|
||||
ops.wait_healthy("worker", 1)
|
||||
print("PASS: a running worker keeps its lease by renewing it; a frozen one loses it, the job moves to another "
|
||||
"worker, and the stale worker cannot overwrite the result (fencing token)")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user