lab3: second tiny fix

This commit is contained in:
yurtaev.va
2026-10-23 19:29:40 +03:00
parent 3a3302c5b4
commit 088961a433
24 changed files with 477 additions and 134 deletions
+60
View File
@@ -0,0 +1,60 @@
#!/usr/bin/env python3
"""Check that HAProxy removes a live API with failed database readiness."""
import json
from pathlib import Path
import subprocess
import time
from client import Client, Failure
PROJECT = "mtusi2026lab3-yurtaev"
TARGET = PROJECT + "-api-1"
NETWORK = PROJECT + "_data"
def docker(*args):
return subprocess.check_output(["docker", *args], text=True).strip()
def main():
client = Client("http://127.0.0.1:8080", timeout=2)
alice, _, _, chat = client.bootstrap()
target_id = docker("exec", TARGET, "python", "-c",
"import urllib.request; print(urllib.request.urlopen('http://127.0.0.1:8080/health/live').headers['X-Instance-Id'])")
before = {client.call("GET", "/api/v1/users/me", actor=alice, schema="User")["headers"]["X-Instance-Id"]
for _ in range(40)}
assert len(before) == 2 and target_id in before, (before, target_id)
start = time.monotonic()
docker("network", "disconnect", NETWORK, TARGET)
try:
consecutive = 0
errors = 0
detected_at = None
while time.monotonic() - start < 10:
try:
response = client.call("GET", "/api/v1/users/me", actor=alice, schema="User")
assert response["headers"]["X-Instance-Id"] != target_id
consecutive += 1
except Failure:
errors += 1
consecutive = 0
if consecutive >= 20:
detected_at = time.monotonic() - start
break
time.sleep(0.05)
assert detected_at is not None, "HAProxy did not exclude unready replica"
messages = [client.message(alice, chat, "readiness probe " + str(n))["json"] for n in range(10)]
assert len({message["id"] for message in messages}) == 10
report = {"target_instance_id": target_id, "observed_before": sorted(before),
"excluded_within_seconds": round(detected_at, 3), "transient_errors": errors,
"successful_writes_after_exclusion": len(messages)}
Path("evidence/readiness_failover.json").write_text(json.dumps(report, indent=2) + "\n")
print(json.dumps(report, indent=2))
finally:
docker("network", "connect", NETWORK, TARGET)
if __name__ == "__main__":
main()
+124
View File
@@ -0,0 +1,124 @@
#!/usr/bin/env python3
"""Inherited lab 2 level 4 checks through the lab 3 load balancer."""
import base64
import concurrent.futures
import json
import os
from pathlib import Path
import subprocess
import threading
import time
import urllib.error
import urllib.request
import uuid
ROOT = Path(__file__).resolve().parents[1]
BASE = os.environ.get("BASE_URL", "http://localhost:8080")
def compose(*args, env=None):
return subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT, env=env, check=True, capture_output=True, text=True).stdout
def psql(sql):
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger", "-t", "-A", "-c", sql)
def call(method, path, data=None, auth=None):
headers = {"Accept": "application/json"}
if method == "POST" and path.endswith("/messages"):
headers["Idempotency-Key"] = uuid.uuid4().hex
if data is not None:
headers["Content-Type"] = "application/json"
if auth:
headers["Authorization"] = auth
request = urllib.request.Request(BASE + path, method=method, headers=headers, data=json.dumps(data).encode() if data is not None else None)
try:
with urllib.request.urlopen(request, timeout=10) as response:
return response.status, json.loads(response.read() or b"null")
except urllib.error.HTTPError as error:
return error.code, json.loads(error.read())
def register(name, password):
return call("POST", "/api/v1/users", {"username": name, "display_name": "Synthetic", "password": password})
def login(name, password):
basic = base64.b64encode((name + ":" + password).encode()).decode()
return call("POST", "/api/v1/auth/sessions", auth="Basic " + basic)
def main():
assert register("spaces_" + uuid.uuid4().hex[:12], " " * 12)[0] == 400
name = "race_" + uuid.uuid4().hex[:12]
password = "synthetic-" + uuid.uuid4().hex
gate = threading.Barrier(16)
def competing_register(_):
gate.wait()
return register(name, password)[0]
with concurrent.futures.ThreadPoolExecutor(max_workers=16) as workers:
statuses = list(workers.map(competing_register, range(16)))
assert statuses.count(201) == 1 and statuses.count(409) == 15, statuses
status, session = login(name, password)
assert status == 201
basic = base64.b64encode((name + ":" + password).encode()).decode()
assert call("POST", "/api/v1/auth/sessions", {"unexpected": "body"}, "Basic " + basic)[0] == 400
token = "Bearer " + session["token"]
user_id = session["user"]["id"]
status, chat = call("POST", "/api/v1/chats", {"title": "Failure test", "member_ids": [user_id]}, token)
assert status == 201
probe = "rollback_" + uuid.uuid4().hex
psql("CREATE FUNCTION lab2_rollback_guard() RETURNS trigger LANGUAGE plpgsql AS $$ "
f"BEGIN IF EXISTS (SELECT 1 FROM chats WHERE id=NEW.chat_id AND title='{probe}') "
"THEN RAISE EXCEPTION 'rollback probe'; END IF; RETURN NEW; END $$;")
psql("CREATE TRIGGER lab2_rollback_guard BEFORE INSERT ON chat_members "
"FOR EACH ROW EXECUTE FUNCTION lab2_rollback_guard();")
try:
assert call("POST", "/api/v1/chats", {"title": probe, "member_ids": [user_id]}, token)[0] == 500
assert psql(f"SELECT count(*) FROM chats WHERE title='{probe}'").strip() == "0"
finally:
psql("DROP TRIGGER lab2_rollback_guard ON chat_members; DROP FUNCTION lab2_rollback_guard();")
path = "/api/v1/chats/" + chat["id"] + "/messages"
assert call("POST", path, {"text": "before outage"}, token)[0] == 201
malformed = base64.urlsafe_b64encode(json.dumps([chat["id"], 17, user_id]).encode()).decode().rstrip("=")
assert call("GET", path + "?cursor=" + malformed, auth=token)[0] == 400
assert call("GET", path + "?limit=" + "9" * 100, auth=token)[0] == 400
missing_status, missing_body = call("GET", "/api/v1/missing", auth=token)
assert missing_status == 404 and missing_body["error"]["code"] == "not_found"
compose("stop", "redis")
try:
assert call("GET", path, auth=token)[0] == 200
assert call("POST", path, {"text": "during cache outage"}, token)[0] == 201
assert call("GET", path, auth=token)[1]["items"][-1]["text"] == "during cache outage"
assert call("GET", "/api/v1/users/me", auth="Bearer invalid")[0] == 401
finally:
compose("start", "redis")
compose("stop", "postgres")
try:
assert call("GET", "/health/ready")[0] == 503
assert call("GET", "/api/v1/users/me", auth=token)[0] == 503
finally:
compose("start", "postgres")
for _ in range(40):
if call("GET", "/health/ready")[0] == 200:
break
time.sleep(0.5)
else:
raise AssertionError("PostgreSQL did not recover")
# Expiry is checked against PostgreSQL time, without a Redis dependency.
env = dict(os.environ, SESSION_TTL_SECONDS="2")
compose("up", "-d", "--force-recreate", "--wait", "api", env=env)
try:
short = login(name, password)[1]["token"]
time.sleep(3)
assert call("GET", "/api/v1/users/me", auth="Bearer " + short)[0] == 401
finally:
compose("up", "-d", "--force-recreate", "--wait", "api")
print("PASS: username race, chat rollback, Redis fallback, PostgreSQL failure, session expiry")
if __name__ == "__main__":
main()
+58 -19
View File
@@ -2,6 +2,7 @@
"""Exercise a real Swarm worker loss while reading and writing through the LB."""
import argparse
from collections import Counter
from concurrent.futures import ThreadPoolExecutor
import json
from pathlib import Path
@@ -9,6 +10,7 @@ import statistics
import subprocess
import time
import uuid
from urllib.parse import quote
from client import Client, Failure
@@ -16,10 +18,23 @@ from client import Client, Failure
def tasks():
result = subprocess.check_output([
"docker", "exec", "lab3-manager", "docker", "service", "ps",
"--filter", "desired-state=running", "--format", "{{.Node}} {{.CurrentState}}",
"--filter", "desired-state=running", "--format", "{{.ID}} {{.Node}} {{.CurrentState}}",
"lab3app_api",
], text=True)
return [line.split()[0] for line in result.splitlines() if "Running" in line]
return [{"task_id": parts[0], "node": parts[1]} for line in result.splitlines()
if len(parts := line.split()) >= 3 and parts[2] == "Running"]
def history(client, actor, chat):
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100"
items = []
for _ in range(100):
page = client.call("GET", path, actor=actor, schema="MessagePage")["json"]
items.extend(page["items"])
if page["next_cursor"] is None:
return items
path = "/api/v1/chats/" + chat["id"] + "/messages?limit=100&cursor=" + quote(page["next_cursor"], safe="")
raise AssertionError("history pagination did not terminate")
def main():
@@ -31,7 +46,7 @@ def main():
client = Client(args.base_url, timeout=2)
alice, bob, _, chat = client.bootstrap()
before = tasks()
assert len(before) == 2 and args.worker in before, before
assert len(before) == 2 and args.worker in {task["node"] for task in before}, before
instances = {
client.call("GET", "/api/v1/users/me", actor=alice, schema="User")["headers"]["X-Instance-Id"]
for _ in range(40)
@@ -41,13 +56,19 @@ def main():
key = uuid.uuid4().hex
body = "concurrent " + key
with ThreadPoolExecutor(max_workers=16) as executor:
results = list(executor.map(lambda _: client.message(alice, chat, body, key=key)["json"], range(16)))
responses = list(executor.map(lambda _: client.message(alice, chat, body, key=key), range(16)))
results = [response["json"] for response in responses]
concurrent_instances = {response["headers"]["X-Instance-Id"] for response in responses}
assert all(item == results[0] for item in results)
assert len(concurrent_instances) >= 2, concurrent_instances
subprocess.run(["docker", "stop", "-t", "1", args.worker], check=True, stdout=subprocess.DEVNULL)
start = time.monotonic()
successes = []
errors = 0
subprocess.run(["docker", "stop", "-t", "1", args.worker], check=True, stdout=subprocess.DEVNULL)
stop_return_seconds = time.monotonic() - start
successes = {}
post_errors = 0
read_errors = 0
successful_reads = 0
latencies = []
moved_at = None
first_success = None
@@ -56,35 +77,53 @@ def main():
while time.monotonic() - start < 75:
try:
response = client.message(alice, chat, pending_text, key=pending_key)
successes.append(response["json"])
assert pending_key not in successes
successes[pending_key] = response["json"]
latest_id = response["json"]["id"]
latencies.append(response["elapsed"] * 1000)
if first_success is None:
first_success = time.monotonic() - start
client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=1", actor=bob, schema="MessagePage")
pending_key = uuid.uuid4().hex
pending_text = "node-fail " + pending_key
except Failure:
errors += 1
post_errors += 1
else:
try:
assert latest_id in {item["id"] for item in history(client, bob, chat)}
successful_reads += 1
except Failure:
read_errors += 1
current = tasks()
if len(current) == 2 and args.worker not in current and moved_at is None:
if len(current) == 2 and args.worker not in {task["node"] for task in current} and moved_at is None:
moved_at = time.monotonic() - start
if moved_at is not None and time.monotonic() - start > moved_at + 5:
break
time.sleep(0.15)
assert moved_at is not None, tasks()
assert successes, "no writes during node failure"
page = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages?limit=100", actor=bob, schema="MessagePage")["json"]
seen = {item["id"] for item in page["items"]}
assert results[0]["id"] in seen and all(item["id"] in seen for item in successes)
assert sum(item["text"] == body for item in page["items"]) == 1
items = history(client, bob, chat)
ids = Counter(item["id"] for item in items)
texts = Counter(item["text"] for item in items)
assert ids[results[0]["id"]] == 1 and texts[body] == 1
assert all(ids[item["id"]] == 1 and texts[item["text"]] == 1 for item in successes.values())
after_instances = {
client.call("GET", "/api/v1/users/me", actor=alice, schema="User")["headers"]["X-Instance-Id"]
for _ in range(40)
}
assert after_instances - instances, (instances, after_instances)
report = {
"before_nodes": before,
"after_nodes": tasks(),
"before_instance_count": len(instances),
"before_tasks": before,
"after_tasks": tasks(),
"before_instance_ids": sorted(instances),
"after_instance_ids": sorted(after_instances),
"concurrent_replays": len(results),
"concurrent_message_count": 1,
"concurrent_instance_ids": sorted(concurrent_instances),
"successful_writes": len(successes),
"failed_attempts": errors,
"successful_reads": successful_reads,
"failed_post_attempts": post_errors,
"failed_read_attempts": read_errors,
"docker_stop_seconds": round(stop_return_seconds, 3),
"first_success_seconds": round(first_success, 3),
"replacement_running_seconds": round(moved_at, 3),
"confirmed_messages_preserved": True,