forked from mtusi2026/mtusi2026lab3
fix: реплика не «замерзает» при потере сети к PostgreSQL; сети edge/data
Найдено тестом сценария рецензента (docker network disconnect одной API от сети хранилищ): по дедлайну задача psycopg отменялась, psycopg слал cancel-запрос, а libpq PQcancelStart синхронно резолвит имя хоста в потоке event loop — вся реплика, включая /health/live, висела ~1 минуту и не возвращалась в ротацию сама. Теперь задача по дедлайну не отменяется (запрос сразу получает 503, задача доживает сама), а мёртвые соединения рвёт TCP keepalive + tcp_user_timeout = DB_TIMEOUT_SECONDS. - compose: сеть edge (lb, api) и internal-сеть data (api, migrate, postgres, valkey) — LB не видит хранилища. - тесты: неготовая реплика (pg_hba и network disconnect) выводится из ротации, процесс отвечает на live, после восстановления сам UP за <= 15 с; пробельные Unicode-строки, 1e1000, байт FF в пароле, 101 участник, курсор одного списка в другом. - bench/track1: CPU реплик суммируется по каждому замеру, в raw и CSV — фактические лимиты контейнеров из docker inspect. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Opus 5.5
parent
2033440cdb
commit
3f45eb1b51
@@ -62,7 +62,7 @@ def hba_file() -> str:
|
||||
def isolated_from_postgres(replica: dict):
|
||||
"""Make ONE replica unable to reach PostgreSQL (pg_hba reject for its IP + terminate its
|
||||
connections), while it keeps running and answering /health/live. Always undone."""
|
||||
ip = replica["ips"][0]
|
||||
ip = replica["networks"]["data"] # PostgreSQL sees the replica's address on the data network
|
||||
path = hba_file()
|
||||
marker = "lab3-test-isolate"
|
||||
compose("exec", "-T", "postgres", "sh", "-c", f"sed -i '1i host all all {ip}/32 reject # {marker}' {path}")
|
||||
@@ -73,28 +73,51 @@ def isolated_from_postgres(replica: dict):
|
||||
finally:
|
||||
compose("exec", "-T", "postgres", "sh", "-c", f"sed -i '/{marker}/d' {path}")
|
||||
psql("SELECT pg_reload_conf()")
|
||||
lbctl.wait_up(REPLICAS, timeout=15) # self-heals: no restart of the replica needed
|
||||
wait_stand()
|
||||
|
||||
|
||||
@contextlib.contextmanager
|
||||
def disconnected_from_data_network(replica: dict):
|
||||
"""`docker network disconnect <project>_data <api>`: the replica keeps its edge link to the
|
||||
LB but loses PostgreSQL AND Valkey. Always reconnected."""
|
||||
network = next(n for n in json.loads(subprocess.run(
|
||||
["docker", "inspect", "-f", "{{json .NetworkSettings.Networks}}", replica["id"]],
|
||||
capture_output=True, text=True, check=True).stdout) if n.endswith("_data"))
|
||||
subprocess.run(["docker", "network", "disconnect", network, replica["id"]], check=True, capture_output=True)
|
||||
try:
|
||||
yield
|
||||
finally:
|
||||
subprocess.run(["docker", "network", "connect", network, replica["id"]], check=True, capture_output=True)
|
||||
lbctl.wait_up(REPLICAS, timeout=15) # self-heals: dead sockets are dropped (tcp_user_timeout)
|
||||
wait_stand()
|
||||
|
||||
|
||||
@pytest.mark.parametrize("how", ["pg_hba", "network"])
|
||||
@pytest.mark.parametrize("position", range(REPLICAS))
|
||||
def test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready(api, position):
|
||||
"""The reviewer's scenario: one API loses PostgreSQL but keeps running. Its /health/live is
|
||||
200, /health/ready 503 -> HAProxy must take it out; no business request may reach it."""
|
||||
def test_lb_stops_routing_to_a_replica_that_is_alive_but_not_ready(api, position, how):
|
||||
"""The reviewers' scenarios: one API loses PostgreSQL (pg_hba reject) or its whole data
|
||||
network (docker network disconnect) but keeps running. /health/live 200, /health/ready
|
||||
503 -> HAProxy must take it out; no business request may reach it."""
|
||||
replica = sorted(running_replicas(), key=lambda r: r["name"])[position]
|
||||
actor = api.user("ready")
|
||||
with isolated_from_postgres(replica):
|
||||
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():
|
||||
assert time.monotonic() - started < 5, "HAProxy did not mark the unready replica DOWN within 5 s"
|
||||
time.sleep(0.1)
|
||||
detected = time.monotonic() - started
|
||||
assert probe_inside(replica, "/health/live") == 200 # the process is alive ...
|
||||
assert probe_inside(replica, "/health/ready") == 503 # ... but not ready
|
||||
for _ in range(3): # the process stays responsive (event loop never blocked) ...
|
||||
started_probe = time.monotonic()
|
||||
assert probe_inside(replica, "/health/live") == 200
|
||||
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
|
||||
for i in range(20): # writes keep working, only through the ready replicas
|
||||
assert api.register(f"r{i}")["id"]
|
||||
print(f"{replica['name']}: unready replica out of rotation after {detected:.2f} s")
|
||||
print(f"{replica['name']} ({how}): unready replica out of rotation after {detected:.2f} s")
|
||||
|
||||
|
||||
# ------------------------------------------------------------------ stopping replicas under traffic
|
||||
@@ -273,6 +296,10 @@ def test_compose_policy_limits_ports_secrets_images():
|
||||
volumes = {name: [v["source"] for v in svc.get("volumes", []) if v["type"] == "volume"]
|
||||
for name, svc in services.items()}
|
||||
assert volumes == {"postgres": ["pgdata"], "valkey": ["valkeydata"], "migrate": [], "api": [], "lb": []}
|
||||
networks = {name: sorted(svc.get("networks", {})) for name, svc in services.items()}
|
||||
assert networks == {"postgres": ["data"], "valkey": ["data"], "migrate": ["data"], "api": ["data", "edge"],
|
||||
"lb": ["edge"]}, networks # the LB cannot reach the stores at all
|
||||
assert config["networks"]["data"].get("internal") is True
|
||||
|
||||
|
||||
def test_running_containers_have_limits_and_no_bypass_ports():
|
||||
|
||||
Reference in New Issue
Block a user