lab7: Argon2id из env (замер bench/argon2_bench.py), лимит неудачных входов в Valkey (429 + Retry-After), cap_drop ALL и no-new-privileges, X-Instance-Id = случайный alias

This commit is contained in:
Alexey Bodanyuk
2026-11-27 16:57:24 +03:00
parent 876f610847
commit 05df1695fe
16 changed files with 431 additions and 50 deletions
+8 -8
View File
@@ -29,9 +29,9 @@ def instances_seen(api: Api, token: str, requests: int = 40) -> list[str]:
def test_one_session_is_served_by_every_real_replica(api):
actor = api.user("rr")
seen = instances_seen(api, actor["token"])
running = {r["hostname"] for r in running_replicas()}
running = {r["instance"] for r in running_replicas()}
assert len(running) == REPLICAS >= 2
assert set(seen) == running, "X-Instance-Id values must be exactly the hostnames of the running containers"
assert set(seen) == running, "X-Instance-Id values must be exactly the aliases of the running containers"
# Round robin on ONE keep-alive client connection: consecutive requests switch replicas,
# so there is no sticky session hiding split state.
switches = sum(1 for a, b in zip(seen, seen[1:]) if a != b)
@@ -104,7 +104,7 @@ def test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready(api, position
isolate = isolated_from_postgres if how == "pg_hba" else disconnected_from_data_network
with isolate(replica):
started = time.monotonic()
while replica["hostname"] in lbctl.up_instances():
while replica["instance"] in lbctl.up_instances():
assert time.monotonic() - started < 5, "HAProxy did not mark the unready replica DOWN within 5 s"
time.sleep(0.1)
detected = time.monotonic() - started
@@ -114,7 +114,7 @@ def test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready(api, position
assert probe_inside(replica, "/health/ready") == 503 # ... but not ready
assert time.monotonic() - started_probe < 4.5, "replica froze while its dependencies were unreachable"
seen = instances_seen(api, actor["token"], 40)
assert replica["hostname"] not in seen and len(seen) == 40
assert replica["instance"] not in seen and len(seen) == 40
for i in range(20): # writes keep working, only through the ready replicas
assert api.register(f"r{i}")["id"]
print(f"{replica['name']} ({how}): unready replica out of rotation after {detected:.2f} s")
@@ -195,7 +195,7 @@ def test_graceful_stop_of_each_replica_loses_no_request(api, position):
stopped_after = time.monotonic() - started
time.sleep(3)
after = [e for e in traffic.events if e[0] > time.monotonic() - 2]
assert after and replica["hostname"] not in {e[3] for e in after}
assert after and replica["instance"] not in {e[3] for e in after}
time.sleep(1)
state = json.loads(subprocess.run(["docker", "inspect", replica["id"]], capture_output=True, text=True,
check=True).stdout)[0]["State"]
@@ -220,7 +220,7 @@ def test_killed_replica_bounded_errors_recovery_and_no_duplicates(api, position)
post_ok = [e for e in traffic.events if e[0] > killed_at and e[1] == "POST" and e[2] == 201]
assert post_ok and post_ok[0][0] - killed_at <= 10, "writes did not recover within 10 s"
late = [e for e in traffic.events if e[0] > killed_at + 3.5]
assert late and replica["hostname"] not in {e[3] for e in late}
assert late and replica["instance"] not in {e[3] for e in late}
assert last_failure <= 10
traffic.check_history(api)
print(f"{replica['name']}: killed; {len(failures)} failed of {len(traffic.events)}, last failure +{last_failure:.2f} s")
@@ -248,11 +248,11 @@ def test_graceful_shutdown_order_in_logs(api):
# ------------------------------------------------------------------ discovery: restart and scaling
def test_full_restart_lb_rediscovers_all_replicas(api):
actor = api.user("restart")
before = {r["hostname"]: r["started_at"] for r in running_replicas()}
before = {r["instance"]: r["started_at"] for r in running_replicas()}
run_hook("restart.sh")
wait_healthy("postgres", "valkey", "api")
wait_stand()
after = {r["hostname"]: r["started_at"] for r in running_replicas()}
after = {r["instance"]: r["started_at"] for r in running_replicas()}
assert set(after) == set(before) and all(after[h] != before[h] for h in after), "every replica restarted"
assert set(instances_seen(api, actor["token"])) == set(after) # same token, both replicas, no LB restart needed
+1 -1
View File
@@ -273,7 +273,7 @@ def test_replay_after_the_serving_replica_is_stopped(api, pair):
key = uuid.uuid4().hex
first = api.post_message(alice, chat, {"text": "до остановки"}, key=key)
served_by = first.headers["x-instance-id"]
replica = next(r for r in running_replicas() if r["hostname"] == served_by)
replica = next(r for r in running_replicas() if r["instance"] == served_by)
with replica_stopped(replica):
for _ in range(5):
again = Api().post_message(alice, chat, {"text": "до остановки"}, key=key)
+3 -5
View File
@@ -20,7 +20,7 @@ import pytest
from PIL import Image
import imagegen
from conftest import (attachment_row, audit, compose, events_of, job_rows, jobctl, psql, queue_depth, s3_keys,
from conftest import (lbctl, attachment_row, audit, compose, events_of, job_rows, jobctl, psql, queue_depth, s3_keys,
s3_size, service_down, service_with_env, wait_healthy, wait_stand)
pytestmark = pytest.mark.stack
@@ -359,11 +359,9 @@ def test_bad_message_is_dead_lettered_not_processed(api, pair):
# ------------------------------------------------------------------ lease, hung worker, shutdown, concurrency
def worker_containers() -> dict[str, str]:
"""hostname (= lease_owner) -> container id of every running worker."""
"""instance alias (= lease_owner, lab 7: random, in /tmp/instance_id) -> container id of every running worker."""
ids = compose("ps", "-q", "worker").stdout.split()
out = subprocess.run(["docker", "inspect", "-f", "{{.Config.Hostname}} {{.Id}}", *ids], capture_output=True,
text=True, check=True).stdout
return dict(line.split() for line in out.splitlines())
return {lbctl.instance_alias(cid): cid for cid in ids}
def test_hung_worker_loses_its_lease_and_cannot_publish(api, pair):