Исправить замечания ревью: ACL при повторе, повтор POST в nginx, активная проверка готовности
This commit is contained in:
@@ -26,10 +26,10 @@ wait_instances() {
|
||||
|
||||
for cfg in $CONFIGS; do
|
||||
IFS=: read -r label replicas cpus mem <<< "$cfg"
|
||||
export REPLICAS=$replicas API_CPUS=$cpus API_MEM=$mem
|
||||
apis=$(seq -f "api-%g" 1 "$replicas" | tr '\n' ' ')
|
||||
export API_CPUS=$cpus API_MEM=$mem API_UPSTREAMS="${apis% }"
|
||||
files=(-f compose.yaml -f infra/scaling/limits.yaml)
|
||||
[ "$replicas" -eq 4 ] && files+=(-f infra/scaling/replicas-4.yaml)
|
||||
apis=$(seq -f "api-%g" 1 "$replicas" | tr '\n' ' ')
|
||||
|
||||
echo "=== $label: $replicas x ${cpus} CPU / $mem ==="
|
||||
docker compose "${files[@]}" up -d --force-recreate $apis >/dev/null 2>&1
|
||||
@@ -63,7 +63,7 @@ for cfg in $CONFIGS; do
|
||||
| grep -E '" [45][0-9][0-9] |\[(error|warn)\]' > "$OUT/${label}_nginx_problems.txt" || true
|
||||
done
|
||||
|
||||
export REPLICAS=2 API_CPUS=0.50 API_MEM=256M
|
||||
unset API_CPUS API_MEM API_UPSTREAMS
|
||||
docker compose -f compose.yaml -f infra/scaling/replicas-4.yaml rm -sf api-3 api-4 >/dev/null 2>&1 || true
|
||||
docker compose up -d --force-recreate api-1 api-2 nginx >/dev/null 2>&1
|
||||
wait_instances 2
|
||||
|
||||
@@ -0,0 +1,191 @@
|
||||
#!/usr/bin/env python3
|
||||
import argparse
|
||||
import base64
|
||||
import json
|
||||
import os
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.error
|
||||
import urllib.request
|
||||
import uuid
|
||||
|
||||
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
|
||||
BASE = "http://localhost:8080"
|
||||
failures = []
|
||||
|
||||
|
||||
def check(cond, message):
|
||||
print(("PASS: " if cond else "FAIL: ") + message)
|
||||
if not cond:
|
||||
failures.append(message)
|
||||
|
||||
|
||||
def compose(*args, check_rc=True):
|
||||
return subprocess.run(["docker", "compose", *args], cwd=ROOT, check=check_rc,
|
||||
capture_output=True, text=True).stdout
|
||||
|
||||
|
||||
def psql(sql):
|
||||
return compose("exec", "-T", "postgres", "psql", "-U", "messenger", "-d", "messenger",
|
||||
"-tAc", sql).strip()
|
||||
|
||||
|
||||
def api(method, path, body=None, headers=None):
|
||||
h = {"Accept": "application/json"}
|
||||
h.update(headers or {})
|
||||
data = None
|
||||
if body is not None:
|
||||
data = json.dumps(body).encode()
|
||||
h["Content-Type"] = "application/json"
|
||||
req = urllib.request.Request(BASE + path, data=data, headers=h, method=method)
|
||||
try:
|
||||
resp = urllib.request.urlopen(req, timeout=10)
|
||||
except urllib.error.HTTPError as e:
|
||||
resp = e
|
||||
raw = resp.read()
|
||||
return resp.code, (json.loads(raw) if raw else None), resp.headers.get("X-Instance-Id", "")
|
||||
|
||||
|
||||
def setup():
|
||||
pw = "Review-" + uuid.uuid4().hex[:12]
|
||||
users = []
|
||||
for name in ("alice", "bob"):
|
||||
username = "rv_%s_%s" % (name, uuid.uuid4().hex[:8])
|
||||
_, user, _ = api("POST", "/api/v1/users", {"username": username, "display_name": name, "password": pw})
|
||||
users.append((username, user))
|
||||
cred = base64.b64encode(("%s:%s" % (users[0][0], pw)).encode()).decode()
|
||||
_, sess, _ = api("POST", "/api/v1/auth/sessions", headers={"Authorization": "Basic " + cred})
|
||||
auth = {"Authorization": "Bearer " + sess["token"]}
|
||||
return users[0][1], users[1][1], auth
|
||||
|
||||
|
||||
def new_chat(alice, bob, auth, title):
|
||||
return api("POST", "/api/v1/chats", {"title": title, "member_ids": [alice["id"], bob["id"]]}, auth)
|
||||
|
||||
|
||||
def scenario_replay_acl(alice, bob, auth):
|
||||
print("== 1. Idempotent replay after membership removal")
|
||||
_, chat, _ = new_chat(alice, bob, auth, "ACL replay")
|
||||
key = uuid.uuid4().hex
|
||||
path = "/api/v1/chats/%s/messages" % chat["id"]
|
||||
code, _, _ = api("POST", path, {"text": "before removal"}, dict(auth, **{"Idempotency-Key": key}))
|
||||
check(code == 201, "first POST with key -> 201 (got %s)" % code)
|
||||
psql("DELETE FROM chat_members WHERE chat_id = '%s' AND user_id = '%s'" % (chat["id"], alice["id"]))
|
||||
code, _, _ = api("GET", path, headers=auth)
|
||||
check(code == 404, "history after removal -> 404 (got %s)" % code)
|
||||
code, _, _ = api("POST", path, {"text": "before removal"}, dict(auth, **{"Idempotency-Key": key}))
|
||||
check(code == 404, "replay with same key and body after removal -> 404 (got %s)" % code)
|
||||
|
||||
|
||||
def api1_ip():
|
||||
cid = compose("ps", "-q", "api-1").strip()
|
||||
return subprocess.run(["docker", "inspect", "-f", "{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}", cid],
|
||||
check=True, capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def api1_health():
|
||||
cid = compose("ps", "-q", "api-1").strip()
|
||||
return subprocess.run(["docker", "inspect", "-f", "{{.State.Health.Status}}", cid],
|
||||
capture_output=True, text=True).stdout.strip()
|
||||
|
||||
|
||||
def break_api1_db():
|
||||
compose("exec", "-T", "-u", "root", "api-1", "sh", "-c",
|
||||
"cp /etc/hosts /tmp/hosts.orig && echo '10.255.255.1 postgres' >> /etc/hosts")
|
||||
psql("SELECT count(pg_terminate_backend(pid)) FROM pg_stat_activity WHERE client_addr = '%s'" % api1_ip())
|
||||
|
||||
|
||||
def restore_api1_db():
|
||||
compose("exec", "-T", "-u", "root", "api-1", "sh", "-c",
|
||||
"[ -f /tmp/hosts.orig ] && cat /tmp/hosts.orig > /etc/hosts", check_rc=False)
|
||||
|
||||
|
||||
def wait_for(pred, timeout):
|
||||
deadline = time.monotonic() + timeout
|
||||
while time.monotonic() < deadline:
|
||||
if pred():
|
||||
return True
|
||||
time.sleep(1)
|
||||
return False
|
||||
|
||||
|
||||
def nginx_upstreams():
|
||||
return compose("exec", "-T", "nginx", "cat", "/etc/nginx/upstream/servers.conf", check_rc=False)
|
||||
|
||||
|
||||
def scenario_unready_replica(alice, bob, auth):
|
||||
print("== 2. Live but not ready api-1 (no route to PostgreSQL)")
|
||||
for _ in range(4):
|
||||
api("GET", "/api/v1/users/me", headers=auth)
|
||||
since = time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
break_api1_db()
|
||||
try:
|
||||
before = int(psql("SELECT count(*) FROM chat_members WHERE user_id = '%s'" % alice["id"]))
|
||||
codes = []
|
||||
for i in range(10):
|
||||
codes.append(new_chat(alice, bob, auth, "no-retry %d" % i)[0])
|
||||
time.sleep(0.5)
|
||||
|
||||
marked = wait_for(lambda: "api-1:8080 resolve max_fails=1 fail_timeout=10s down;" in nginx_upstreams(), 20)
|
||||
check(marked, "nginx active check marks api-1 down in upstream")
|
||||
became = wait_for(lambda: api1_health() == "unhealthy", 40)
|
||||
check(became, "Docker marks api-1 unhealthy")
|
||||
|
||||
served = []
|
||||
for _ in range(40):
|
||||
code, _, inst = api("GET", "/api/v1/users/me", headers=auth)
|
||||
served.append((code, inst))
|
||||
time.sleep(0.5)
|
||||
by_api1 = sum(1 for _, inst in served if inst == "api-1")
|
||||
ok = sum(1 for code, _ in served if code == 200)
|
||||
check(by_api1 == 0, "40 GET /users/me with warm session: served by not-ready api-1 = %d" % by_api1)
|
||||
check(ok == 40, "40 GET /users/me: 200 responses = %d" % ok)
|
||||
|
||||
code, chat, _ = new_chat(alice, bob, auth, "messages during outage")
|
||||
if code == 201:
|
||||
msg_codes = []
|
||||
for i in range(20):
|
||||
msg_codes.append(api("POST", "/api/v1/chats/%s/messages" % chat["id"], {"text": "m%d" % i},
|
||||
dict(auth, **{"Idempotency-Key": uuid.uuid4().hex}))[0])
|
||||
check(msg_codes.count(201) == 20, "20 POST messages during outage -> all 201 (got %s)" % sorted(set(msg_codes)))
|
||||
after = int(psql("SELECT count(*) FROM chat_members WHERE user_id = '%s'" % alice["id"]))
|
||||
|
||||
print("== 3. LB does not transparently retry non-idempotent POST /chats")
|
||||
created = codes.count(201) + (1 if code == 201 else 0)
|
||||
check(after - before == created, "chats in DB (%d) == 201 responses (%d), POST /chats codes=%s"
|
||||
% (after - before, created, codes))
|
||||
log = compose("logs", "--no-log-prefix", "--since", since, "nginx")
|
||||
chat_posts = [l for l in log.splitlines() if '"POST /api/v1/chats HTTP' in l]
|
||||
retried = [l for l in chat_posts if re.search(r":8080, [0-9]", l)]
|
||||
check(bool(chat_posts) and not retried,
|
||||
"nginx access log: %d POST /chats, sent to two upstreams: %d" % (len(chat_posts), len(retried)))
|
||||
conf = compose("exec", "-T", "nginx", "nginx", "-T")
|
||||
blocks = re.findall(r"location ([^{]+)\{([^}]*)\}", conf)
|
||||
policy = {loc.strip(): "non_idempotent" in body for loc, body in blocks}
|
||||
check(policy.get("/") is False and policy.get("~ ^/api/v1/chats/[^/]+/messages$") is True,
|
||||
"non_idempotent only on messages route: %s" % policy)
|
||||
finally:
|
||||
restore_api1_db()
|
||||
back = wait_for(lambda: api1_health() == "healthy", 40)
|
||||
check(back, "api-1 healthy again after PostgreSQL route restored")
|
||||
seen = wait_for(lambda: any(api("GET", "/health/live")[2] == "api-1" for _ in range(6)), 20)
|
||||
check(seen, "api-1 returns to LB rotation")
|
||||
check("down" not in nginx_upstreams(), "nginx upstream has no servers marked down")
|
||||
|
||||
|
||||
def main():
|
||||
global BASE
|
||||
p = argparse.ArgumentParser()
|
||||
p.add_argument("--base-url", default=BASE)
|
||||
BASE = p.parse_args().base_url.rstrip("/")
|
||||
alice, bob, auth = setup()
|
||||
scenario_replay_acl(alice, bob, auth)
|
||||
scenario_unready_replica(alice, bob, auth)
|
||||
print("RESULT: %s" % ("PASS" if not failures else "FAIL (%d)" % len(failures)))
|
||||
sys.exit(1 if failures else 0)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user