forked from mtusi2026/mtusi2026lab4
feat: база из лабораторной 3 перенесена в лабу 4
This commit is contained in:
+157
-51
@@ -1,58 +1,164 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Small closed-loop HTTP write benchmark; not an open-loop capacity proof."""
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
import json
|
||||
import math
|
||||
from pathlib import Path
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
from client import Client, Failure, LAB, arguments, check, run
|
||||
from pathlib import Path
|
||||
|
||||
import requests
|
||||
|
||||
BASE = "http://localhost:8080"
|
||||
LOGIN = "test"
|
||||
PASSWORD = "test123"
|
||||
TIMEOUT = 5
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
RECOVERY_BUDGET = 10.0
|
||||
|
||||
failures = []
|
||||
|
||||
|
||||
def check(condition, message):
|
||||
if condition:
|
||||
print("PASS:", message)
|
||||
return True
|
||||
failures.append(message)
|
||||
print("FAIL:", message)
|
||||
return False
|
||||
|
||||
|
||||
def login():
|
||||
response = requests.post(
|
||||
BASE + "/api/auth/login",
|
||||
json={"login": LOGIN, "password": PASSWORD},
|
||||
timeout=TIMEOUT,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.json()["token"]
|
||||
|
||||
|
||||
def fetch(token):
|
||||
response = requests.get(
|
||||
BASE + "/api/messages",
|
||||
headers={"Authorization": "Bearer " + token},
|
||||
timeout=TIMEOUT,
|
||||
)
|
||||
response.raise_for_status()
|
||||
return response.headers.get("X-Instance-Id", "")
|
||||
|
||||
|
||||
def round_robin(token, count):
|
||||
instances = []
|
||||
lock = threading.Lock()
|
||||
|
||||
def worker():
|
||||
try:
|
||||
instance = fetch(token)
|
||||
except requests.RequestException:
|
||||
return
|
||||
with lock:
|
||||
instances.append(instance)
|
||||
|
||||
threads = [threading.Thread(target=worker) for _ in range(count)]
|
||||
for thread in threads:
|
||||
thread.start()
|
||||
for thread in threads:
|
||||
thread.join()
|
||||
return instances
|
||||
|
||||
|
||||
def compose(*args):
|
||||
return subprocess.run(
|
||||
["docker", "compose", *args],
|
||||
cwd=REPO_ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
check=False,
|
||||
)
|
||||
|
||||
|
||||
def main():
|
||||
def configure(p):
|
||||
p.add_argument('--duration',type=float,default=30)
|
||||
p.add_argument('--concurrency',type=int,default=4)
|
||||
p.add_argument('--output',default=None,help='Optional JSON metrics, no session tokens')
|
||||
args = arguments('Synthetic POST message load, closed loop; creates users/messages',configure)
|
||||
check(1<=args.duration<=3600,'duration must be 1..3600 seconds')
|
||||
check(1<=args.concurrency<=128,'concurrency must be 1..128')
|
||||
c = Client(args.base_url,args.ca_file)
|
||||
alice,bob,eve,chat = c.bootstrap()
|
||||
barrier = threading.Barrier(args.concurrency)
|
||||
def worker(worker_id):
|
||||
local = Client(args.base_url,args.ca_file,timeout=5)
|
||||
barrier.wait()
|
||||
deadline = time.monotonic()+args.duration
|
||||
latencies,errors = [],0
|
||||
index = 0
|
||||
while time.monotonic()<deadline:
|
||||
start = time.monotonic()
|
||||
try:
|
||||
local.message(alice,chat,'load-%s-%s' % (worker_id,index))
|
||||
latencies.append(time.monotonic()-start)
|
||||
except Failure:
|
||||
errors += 1
|
||||
index += 1
|
||||
return latencies,errors
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=args.concurrency) as pool:
|
||||
results = list(pool.map(worker,range(args.concurrency)))
|
||||
elapsed = time.monotonic()-started
|
||||
latencies = sorted(x for values,_ in results for x in values)
|
||||
errors = sum(n for _,n in results)
|
||||
total = len(latencies)+errors
|
||||
def percentile(p):
|
||||
return round(1000*latencies[max(0,math.ceil(p*len(latencies))-1)],3) if latencies else None
|
||||
report = {'lab':LAB,'workload':'closed-loop POST messages; no automatic retries','requested_duration_seconds':args.duration,'elapsed_seconds':round(elapsed,3),'concurrency':args.concurrency,'successful_requests':len(latencies),'failed_requests':errors,'error_ratio':round(errors/total,6) if total else None,'successful_rps':round(len(latencies)/elapsed,3),'successful_latency_ms':{'p50':percentile(.50),'p95':percentile(.95),'p99':percentile(.99)},'note':'Latency percentiles cover successes only. Timeouts/errors are counted separately; closed-loop has coordinated omission and client overhead.'}
|
||||
text = json.dumps(report,ensure_ascii=False,indent=2)
|
||||
if args.output:
|
||||
dest = Path(args.output)
|
||||
dest.parent.mkdir(parents=True,exist_ok=True)
|
||||
dest.write_text(text+'\n')
|
||||
print(text)
|
||||
check(bool(latencies),'no successful writes')
|
||||
# Errors are reported, not treated as a universal load-test threshold.
|
||||
token = login()
|
||||
auth = {"Authorization": "Bearer " + token}
|
||||
|
||||
if __name__=='__main__':
|
||||
run(main)
|
||||
probe = requests.post(
|
||||
BASE + "/api/messages",
|
||||
headers=dict(auth, **{"Idempotency-Key": "load-" + str(time.time_ns())}),
|
||||
json={"recipient": LOGIN, "body": "before failover"},
|
||||
timeout=TIMEOUT,
|
||||
)
|
||||
check(probe.status_code == 201, "message written before failover (got %d)" % probe.status_code)
|
||||
probe_id = probe.json().get("id")
|
||||
|
||||
instances = round_robin(token, 20)
|
||||
check(len(set(instances)) >= 2, "requests reached at least two replicas: %s" % sorted(set(instances)))
|
||||
|
||||
print("\n=== Stopping api1 ===")
|
||||
stop = compose("stop", "api1")
|
||||
check(stop.returncode == 0, "docker compose stop api1 succeeded")
|
||||
started = time.monotonic()
|
||||
|
||||
recovered_at = None
|
||||
served_after = []
|
||||
transient_errors = 0
|
||||
while time.monotonic() - started < RECOVERY_BUDGET + 5:
|
||||
try:
|
||||
instance = fetch(token)
|
||||
except requests.RequestException:
|
||||
transient_errors += 1
|
||||
time.sleep(0.2)
|
||||
continue
|
||||
if recovered_at is None:
|
||||
recovered_at = time.monotonic() - started
|
||||
served_after.append(instance)
|
||||
if len(served_after) >= 5:
|
||||
break
|
||||
time.sleep(0.1)
|
||||
|
||||
check(
|
||||
recovered_at is not None and recovered_at <= RECOVERY_BUDGET,
|
||||
"reads recovered within %.0fs (%.2fs, %d transient errors)"
|
||||
% (RECOVERY_BUDGET, recovered_at if recovered_at is not None else -1, transient_errors),
|
||||
)
|
||||
check(bool(served_after), "requests still served while api1 is down")
|
||||
check(all(x == "api2" for x in served_after), "api1 left rotation, served by: %s" % sorted(set(served_after)))
|
||||
|
||||
write = requests.post(
|
||||
BASE + "/api/messages",
|
||||
headers=dict(auth, **{"Idempotency-Key": "load-fail-" + str(time.time_ns())}),
|
||||
json={"recipient": LOGIN, "body": "written during failover"},
|
||||
timeout=TIMEOUT,
|
||||
)
|
||||
check(write.status_code == 201, "write works while api1 is down (got %d)" % write.status_code)
|
||||
|
||||
print("\n=== Starting api1 back ===")
|
||||
start = compose("start", "api1")
|
||||
check(start.returncode == 0, "docker compose start api1 succeeded")
|
||||
|
||||
deadline = time.monotonic() + 30
|
||||
back = set()
|
||||
while time.monotonic() < deadline:
|
||||
back = set(round_robin(token, 10))
|
||||
if "api1" in back:
|
||||
break
|
||||
time.sleep(1)
|
||||
check("api1" in back, "api1 is back in rotation: %s" % sorted(back))
|
||||
|
||||
history = requests.get(BASE + "/api/messages", headers=auth, timeout=TIMEOUT)
|
||||
check(history.status_code == 200, "history readable after failover (got %d)" % history.status_code)
|
||||
ids = [m.get("id") for m in history.json()]
|
||||
check(probe_id in ids, "message written before failover survived")
|
||||
check(len(ids) == len(set(ids)), "no duplicate messages in history")
|
||||
|
||||
if failures:
|
||||
print("\n%d check(s) failed" % len(failures))
|
||||
return 1
|
||||
print("\nFailover scenario passed")
|
||||
return 0
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
sys.exit(main())
|
||||
except requests.RequestException as exc:
|
||||
print("request failed:", exc)
|
||||
sys.exit(1)
|
||||
|
||||
Reference in New Issue
Block a user