forked from mtusi2026/mtusi2026lab3
ЛР 3: реализация мессенджера и сценарии проверки
This commit is contained in:
@@ -0,0 +1,112 @@
|
||||
"""Concurrent idempotency, failover of each alias and rolling replacement."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
from uuid import uuid4
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path[:0] = [str(ROOT / "tests"), str(ROOT / "scripts")]
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
from replicas import docker, replicas # noqa: E402
|
||||
|
||||
|
||||
def await_replicas(client, actor, expected, deadline_seconds=45):
|
||||
deadline = time.monotonic() + deadline_seconds
|
||||
observed = set()
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
latest = client.call("GET", "/api/v1/users/me", actor=actor, schema="User")["headers"]["X-Instance-Id"]
|
||||
except Failure:
|
||||
time.sleep(0.15)
|
||||
continue
|
||||
if latest in expected:
|
||||
observed.add(latest)
|
||||
if expected <= observed:
|
||||
return
|
||||
raise Failure("HAProxy did not return every expected API instance")
|
||||
|
||||
|
||||
def traffic(base, actor, chat, stop, target=None):
|
||||
client = Client(base, timeout=2)
|
||||
results = []
|
||||
while not stop():
|
||||
started = time.monotonic()
|
||||
try:
|
||||
response = client.message(actor, chat, "failover probe")
|
||||
instance = response["headers"]["X-Instance-Id"]
|
||||
results.append({"s": time.monotonic() - started, "ok": True, "on_target": instance == target,
|
||||
"time": time.monotonic()})
|
||||
except Failure:
|
||||
results.append({"s": time.monotonic() - started, "ok": False, "time": time.monotonic()})
|
||||
time.sleep(0.035)
|
||||
return results
|
||||
|
||||
|
||||
def summarize(results, started, end):
|
||||
successes = sum(item["ok"] for item in results)
|
||||
recovery = next((row["time"] - started for row in results if row["ok"] and not row["on_target"]), None)
|
||||
return {"seconds": round(end - started, 3), "successes": successes, "failures": len(results) - successes,
|
||||
"rps": round(successes / (end - started), 3), "first_other_replica_seconds": recovery}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "evidence/replicas.json")
|
||||
args = parser.parse_args()
|
||||
client = Client(args.base_url, timeout=3)
|
||||
actor, _, _, chat = client.bootstrap()
|
||||
key = uuid4().hex
|
||||
baseline = replicas()
|
||||
check(len(baseline) == 2, "run this scenario on the default two-replica stack")
|
||||
await_replicas(client, actor, set(baseline))
|
||||
|
||||
def send(_):
|
||||
return Client(args.base_url).message(actor, chat, "same logical message", key=key)
|
||||
|
||||
with ThreadPoolExecutor(8) as pool:
|
||||
reports = list(pool.map(send, range(16)))
|
||||
identifiers = {item["json"]["id"] for item in reports}
|
||||
serving = {item["headers"]["X-Instance-Id"] for item in reports}
|
||||
check(len(identifiers) == 1 and len(serving) >= 2, "race did not converge across replicas")
|
||||
replies = {"same_id": True, "served_on": len(serving), "attempts": len(reports)}
|
||||
progression = []
|
||||
for alias, container in baseline.items():
|
||||
alive = set(replicas()) - {alias}
|
||||
started = time.monotonic()
|
||||
deadline = started + 12
|
||||
with ThreadPoolExecutor(1) as pool:
|
||||
running = pool.submit(traffic, args.base_url, actor, chat, lambda: time.monotonic() >= deadline, alias)
|
||||
try:
|
||||
docker("stop", "--timeout", "8", container)
|
||||
resumed = client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
check(resumed["headers"]["X-Instance-Id"] in alive, "stopped alias still serves")
|
||||
results = running.result()
|
||||
report = summarize(results, started, time.monotonic())
|
||||
check(report["first_other_replica_seconds"] is not None and
|
||||
report["first_other_replica_seconds"] <= 10, "write did not recover within 10 s")
|
||||
finally:
|
||||
docker("start", container)
|
||||
newer = replicas()
|
||||
deadline = time.monotonic() + 35
|
||||
while len(newer) != 2 and time.monotonic() < deadline:
|
||||
time.sleep(0.3)
|
||||
newer = replicas()
|
||||
check(len(newer) == 2, "replacement did not start")
|
||||
await_replicas(client, actor, set(newer))
|
||||
check(client.message(actor, chat, "same logical message", key=key)["json"]["id"] in identifiers,
|
||||
"replay changed after rolling replacement")
|
||||
progression.append(report)
|
||||
args.output.write_text(json.dumps({"concurrent": replies, "rolling": progression}, indent=2) + "\n",
|
||||
encoding="utf-8")
|
||||
print("PASS: concurrent replay across APIs and sequential stop/start under write load")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user