forked from mtusi2026/mtusi2026lab3
Реализовала лабораторную 3 на оценку 4
This commit is contained in:
@@ -0,0 +1,105 @@
|
||||
"""Stop api-1 and api-2 in turn and record bounded failover metrics."""
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
|
||||
|
||||
def command(*args, env=None):
|
||||
subprocess.run(args, cwd=ROOT, env=env, check=True,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def wait_instances(client, expected, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
found = set()
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
found.add(client.call("GET", "/health/ready", schema="Health")
|
||||
["headers"]["X-Instance-Id"])
|
||||
if expected.issubset(found):
|
||||
return
|
||||
except Failure:
|
||||
pass
|
||||
time.sleep(0.1)
|
||||
raise Failure("expected API replicas did not become visible")
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Sequential API failover metrics")
|
||||
client = Client(args.base_url, args.ca_file, timeout=2)
|
||||
command(str(ROOT / "scripts" / "start-api.sh"))
|
||||
wait_instances(client, {"api-1", "api-2"})
|
||||
alice, _, _, chat = client.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
results = []
|
||||
|
||||
for target in ("api-1", "api-2"):
|
||||
command(str(ROOT / "scripts" / "start-api.sh"))
|
||||
wait_instances(client, {"api-1", "api-2"})
|
||||
env = dict(os.environ)
|
||||
env["TARGET_INSTANCE_ID"] = target
|
||||
started = time.monotonic()
|
||||
process = subprocess.Popen([str(ROOT / "scripts" / "stop-one.sh")],
|
||||
cwd=ROOT, env=env,
|
||||
stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.DEVNULL)
|
||||
successes = failures = 0
|
||||
first_survivor = None
|
||||
deadline = started + 8
|
||||
key = uuid.uuid4().hex
|
||||
text = "failover-" + target + "-" + key
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
response = client.call("POST", path, 201, actor=alice,
|
||||
body={"text": text},
|
||||
headers={"Idempotency-Key": key},
|
||||
schema="Message")
|
||||
successes += 1
|
||||
if (process.poll() is not None
|
||||
and response["headers"]["X-Instance-Id"] != target
|
||||
and first_survivor is None):
|
||||
first_survivor = time.monotonic() - started
|
||||
key = uuid.uuid4().hex
|
||||
text = "failover-" + target + "-" + key
|
||||
except Failure:
|
||||
failures += 1
|
||||
# Repeat the same body and key after an uncertain result.
|
||||
code = process.wait(timeout=10)
|
||||
elapsed = time.monotonic() - started
|
||||
check(code == 0, "stop-one.sh failed")
|
||||
check(successes > 0 and first_survivor is not None,
|
||||
"surviving replica did not accept writes")
|
||||
check(first_survivor <= 10, "failover exceeded ten seconds")
|
||||
results.append({
|
||||
"stopped_instance": target,
|
||||
"duration_seconds": round(elapsed, 3),
|
||||
"successful_requests": successes,
|
||||
"failed_requests": failures,
|
||||
"successful_rps": round(successes / elapsed, 3),
|
||||
"first_survivor_success_seconds": round(first_survivor, 3),
|
||||
})
|
||||
|
||||
command(str(ROOT / "scripts" / "start-api.sh"))
|
||||
wait_instances(client, {"api-1", "api-2"})
|
||||
output = {"workload": "single-client closed-loop POST messages", "runs": results}
|
||||
(ROOT / "evidence").mkdir(exist_ok=True)
|
||||
(ROOT / "evidence" / "failover-grade4.json").write_text(
|
||||
json.dumps(output, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("PASS:", json.dumps(output, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
run(main)
|
||||
finally:
|
||||
subprocess.run([str(ROOT / "scripts" / "start-api.sh")], cwd=ROOT,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL,
|
||||
check=False)
|
||||
@@ -0,0 +1,91 @@
|
||||
"""Run concurrent writes while both API replicas are replaced one at a time."""
|
||||
import concurrent.futures
|
||||
import json
|
||||
import math
|
||||
import subprocess
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, arguments, check, run # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Rolling update under write load")
|
||||
base = Client(args.base_url, args.ca_file)
|
||||
alice, _, _, chat = base.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
workers = 4
|
||||
start_barrier = threading.Barrier(workers + 1)
|
||||
stop = threading.Event()
|
||||
|
||||
def worker(worker_id):
|
||||
client = Client(args.base_url, args.ca_file, timeout=3)
|
||||
successes = failures = 0
|
||||
latencies = []
|
||||
instances = set()
|
||||
index = 0
|
||||
start_barrier.wait()
|
||||
while not stop.is_set():
|
||||
key = uuid.uuid4().hex
|
||||
started = time.monotonic()
|
||||
try:
|
||||
result = client.call("POST", path, 201, actor=alice,
|
||||
body={"text": "rolling-%d-%d" % (worker_id, index)},
|
||||
headers={"Idempotency-Key": key}, schema="Message")
|
||||
successes += 1
|
||||
latencies.append(time.monotonic() - started)
|
||||
instances.add(result["headers"]["X-Instance-Id"])
|
||||
except Failure:
|
||||
failures += 1
|
||||
index += 1
|
||||
return successes, failures, latencies, instances
|
||||
|
||||
started = time.monotonic()
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
futures = [pool.submit(worker, i) for i in range(workers)]
|
||||
start_barrier.wait()
|
||||
update = subprocess.run([str(ROOT / "scripts" / "rolling-update.sh")],
|
||||
cwd=ROOT, stdout=subprocess.DEVNULL,
|
||||
stderr=subprocess.PIPE, text=True, timeout=120)
|
||||
time.sleep(3)
|
||||
stop.set()
|
||||
results = [future.result() for future in futures]
|
||||
elapsed = time.monotonic() - started
|
||||
check(update.returncode == 0, "rolling update failed: " + update.stderr[-500:])
|
||||
successes = sum(item[0] for item in results)
|
||||
failures = sum(item[1] for item in results)
|
||||
latencies = sorted(value for item in results for value in item[2])
|
||||
instances = sorted(set().union(*(item[3] for item in results)))
|
||||
check(successes > 0, "no successful writes during rolling update")
|
||||
check(set(instances) == {"api-1", "api-2"},
|
||||
"both replicas were not observed during rolling update")
|
||||
|
||||
def percentile(fraction):
|
||||
if not latencies:
|
||||
return None
|
||||
pos = max(0, math.ceil(fraction * len(latencies)) - 1)
|
||||
return round(latencies[pos] * 1000, 3)
|
||||
|
||||
output = {
|
||||
"workload": "four-client closed-loop POST messages",
|
||||
"elapsed_seconds": round(elapsed, 3),
|
||||
"successful_requests": successes,
|
||||
"failed_requests": failures,
|
||||
"successful_rps": round(successes / elapsed, 3),
|
||||
"latency_ms_successes": {"p50": percentile(.5), "p95": percentile(.95),
|
||||
"p99": percentile(.99)},
|
||||
"instances": instances,
|
||||
}
|
||||
(ROOT / "evidence").mkdir(exist_ok=True)
|
||||
(ROOT / "evidence" / "rolling-update.json").write_text(
|
||||
json.dumps(output, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("PASS:", json.dumps(output, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Executable
+58
@@ -0,0 +1,58 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Stop Redis and PostgreSQL separately and check bounded API failures."""
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
|
||||
|
||||
def compose(*args):
|
||||
subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT,
|
||||
check=True, stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def wait_ready(client, timeout=60):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(0.5)
|
||||
raise Failure("stack did not recover")
|
||||
|
||||
|
||||
def main():
|
||||
client = Client(timeout=5)
|
||||
actor = client.user("dependency")
|
||||
try:
|
||||
compose("stop", "redis")
|
||||
client.call("GET", "/health/ready", 503)
|
||||
client.call("GET", "/api/v1/users/me", 503, actor=actor)
|
||||
client.call("GET", "/api/v1/users/me", 401)
|
||||
finally:
|
||||
compose("start", "redis")
|
||||
wait_ready(client)
|
||||
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
|
||||
try:
|
||||
compose("stop", "postgres")
|
||||
client.call("GET", "/health/ready", 503)
|
||||
client.call("GET", "/api/v1/users/me", 503, actor=actor)
|
||||
finally:
|
||||
compose("start", "postgres")
|
||||
wait_ready(client)
|
||||
client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||
print("PASS: Redis/PostgreSQL failures returned 503; anonymous access stayed 401; state recovered")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (Failure, OSError, subprocess.CalledProcessError) as exc:
|
||||
print("FAIL:", exc)
|
||||
raise SystemExit(1)
|
||||
Executable
+56
@@ -0,0 +1,56 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Recreate the API with a two-second session TTL and prove expiry."""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, check # noqa: E402
|
||||
|
||||
|
||||
def compose(env, *args):
|
||||
subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT,
|
||||
env=env, check=True, stdout=subprocess.DEVNULL)
|
||||
|
||||
|
||||
def wait_ready(timeout=60):
|
||||
client = Client(timeout=2)
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(0.5)
|
||||
raise Failure("API did not become ready")
|
||||
|
||||
|
||||
def main():
|
||||
normal_env = dict(os.environ)
|
||||
normal_env.pop("SESSION_TTL_SECONDS", None)
|
||||
short_env = dict(normal_env)
|
||||
short_env["SESSION_TTL_SECONDS"] = "2"
|
||||
try:
|
||||
compose(short_env, "up", "-d", "--force-recreate", "--no-deps", "--wait", "api1", "api2")
|
||||
compose(short_env, "exec", "-T", "nginx", "nginx", "-s", "reload")
|
||||
wait_ready()
|
||||
client = Client()
|
||||
actor = client.user("expiry")
|
||||
time.sleep(3)
|
||||
client.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
print("PASS: two-second Redis session expired and was rejected")
|
||||
finally:
|
||||
compose(normal_env, "up", "-d", "--force-recreate", "--no-deps", "--wait", "api1", "api2")
|
||||
compose(normal_env, "exec", "-T", "nginx", "nginx", "-s", "reload")
|
||||
wait_ready()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
try:
|
||||
main()
|
||||
except (Failure, OSError, subprocess.CalledProcessError) as exc:
|
||||
print("FAIL:", exc)
|
||||
raise SystemExit(1)
|
||||
Executable
+59
@@ -0,0 +1,59 @@
|
||||
#!/usr/bin/env python3
|
||||
"""Black-box checks for the grade 4 registration, transaction and auth cases."""
|
||||
import base64
|
||||
import concurrent.futures
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "tests"))
|
||||
from client import Client, arguments, check, run # noqa: E402
|
||||
|
||||
|
||||
def basic(username, password):
|
||||
raw = (username + ":" + password).encode("utf-8")
|
||||
return {"Authorization": "Basic " + base64.b64encode(raw).decode("ascii")}
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Grade 4 API checks")
|
||||
base = Client(args.base_url, args.ca_file)
|
||||
suffix = uuid.uuid4().hex[:12]
|
||||
username = "race_" + suffix
|
||||
password = "Race-password-" + uuid.uuid4().hex
|
||||
registration = {"username": username, "display_name": "Гонка регистрации", "password": password}
|
||||
|
||||
workers = 4
|
||||
barrier = threading.Barrier(workers)
|
||||
|
||||
def register(_):
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
barrier.wait()
|
||||
return client.call("POST", "/api/v1/users", [201, 409], body=registration)["status"]
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
statuses = list(pool.map(register, range(workers)))
|
||||
check(statuses.count(201) == 1 and statuses.count(409) == workers - 1,
|
||||
"concurrent registration must create exactly one user")
|
||||
|
||||
base.call("POST", "/api/v1/auth/sessions", 401,
|
||||
headers=basic(username, "definitely-wrong-password"))
|
||||
session = base.call("POST", "/api/v1/auth/sessions", 201,
|
||||
headers=basic(username, password), schema="Session")["json"]
|
||||
actor = {"id": session["user"]["id"], "token": session["token"]}
|
||||
|
||||
title = "rollback-" + suffix
|
||||
base.call("POST", "/api/v1/chats", 400, actor=actor,
|
||||
body={"title": title, "member_ids": [actor["id"], str(uuid.uuid4())]})
|
||||
page = base.call("GET", "/api/v1/chats?limit=100", actor=actor, schema="ChatPage")["json"]
|
||||
check(all(chat["title"] != title for chat in page["items"]),
|
||||
"failed composite operation left a visible chat")
|
||||
|
||||
base.call("DELETE", "/api/v1/auth/sessions/current", 204, actor=actor)
|
||||
base.call("GET", "/api/v1/users/me", 401, actor=actor)
|
||||
print("PASS: registration race, transaction rollback, bad password and logout")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,58 @@
|
||||
"""Prove that one idempotency key creates one message across both replicas."""
|
||||
import concurrent.futures
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, arguments, check, run # noqa: E402
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments("Concurrent cross-replica idempotency check")
|
||||
base = Client(args.base_url, args.ca_file)
|
||||
alice, _, _, chat = base.bootstrap()
|
||||
path = "/api/v1/chats/" + chat["id"] + "/messages"
|
||||
key = "parallel-" + uuid.uuid4().hex
|
||||
body = {"text": "one logical concurrent message"}
|
||||
workers = 12
|
||||
barrier = threading.Barrier(workers)
|
||||
|
||||
def send(_):
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
barrier.wait()
|
||||
result = client.call("POST", path, 201, actor=alice, body=body,
|
||||
headers={"Idempotency-Key": key}, schema="Message")
|
||||
return result["json"], result["headers"]["X-Instance-Id"]
|
||||
|
||||
with concurrent.futures.ThreadPoolExecutor(max_workers=workers) as pool:
|
||||
responses = list(pool.map(send, range(workers)))
|
||||
|
||||
messages = [item[0] for item in responses]
|
||||
instances = sorted(set(item[1] for item in responses))
|
||||
ids = sorted(set(item["id"] for item in messages))
|
||||
check(len(ids) == 1, "one key created more than one message")
|
||||
check(all(item == messages[0] for item in messages),
|
||||
"idempotent responses differ")
|
||||
check(len(instances) >= 2, "requests did not cross two API replicas")
|
||||
|
||||
base.call("POST", path, 409, actor=alice, body={"text": "different body"},
|
||||
headers={"Idempotency-Key": key})
|
||||
page = base.call("GET", path + "?limit=100", actor=alice,
|
||||
schema="MessagePage")["json"]
|
||||
check(sum(item["id"] == ids[0] for item in page["items"]) == 1,
|
||||
"history contains a duplicate message")
|
||||
|
||||
result = {"parallel_requests": workers, "instances": instances,
|
||||
"unique_message_ids": len(ids), "conflicting_reuse_status": 409}
|
||||
(ROOT / "evidence").mkdir(exist_ok=True)
|
||||
(ROOT / "evidence" / "idempotency.json").write_text(
|
||||
json.dumps(result, ensure_ascii=False, indent=2) + "\n", encoding="utf-8")
|
||||
print("PASS:", json.dumps(result, ensure_ascii=False))
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user