feat: add checks and limits for 4 grade
This commit is contained in:
@@ -11,6 +11,7 @@ help:
|
||||
@echo "app-up: prepare local environment, migrate, build and start HAProxy, two API replicas, PostgreSQL, Redis and frontend"
|
||||
@echo "app-down: stop application; keep database and session volumes"
|
||||
@echo "app-logs / app-status: inspect application"
|
||||
@echo "app-rolling-update: build, migrate once and replace API replicas one by one; test-grade4: limits, idempotency, failures and rolling load"
|
||||
@echo "test-backend: Go race tests against PostgreSQL and Redis"
|
||||
@echo "test-baseline / test-baseline-persistence: transferred lab2 API; second target stops and starts lab3"
|
||||
@echo "check: offline structure; validate: full OpenAPI (requirements-dev.txt); test: running API; load: synthetic writes"
|
||||
@@ -29,6 +30,17 @@ app-logs:
|
||||
app-status:
|
||||
$(COMPOSE) ps
|
||||
|
||||
.PHONY: app-rolling-update test-grade4
|
||||
app-rolling-update:
|
||||
$(COMPOSE) build api migrate
|
||||
$(PYTHON) scripts/rolling_update.py
|
||||
|
||||
test-grade4:
|
||||
$(PYTHON) scripts/check_resources.py
|
||||
$(PYTHON) scripts/check_idempotency.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
$(PYTHON) scripts/check_failover.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
$(PYTHON) scripts/check_rolling.py --base-url "$(BASE_URL)" $(TLS_ARGS)
|
||||
|
||||
test-backend:
|
||||
$(COMPOSE) --profile test run --build --rm backend-tests
|
||||
|
||||
|
||||
+28
@@ -2,6 +2,9 @@ name: highload-lab3
|
||||
|
||||
services:
|
||||
redis:
|
||||
cpus: 0.25
|
||||
mem_limit: 128m
|
||||
networks: [data]
|
||||
image: redis:7.4.11-bookworm
|
||||
command: ["redis-server", "--appendonly", "yes", "--appendfsync", "everysec", "--dir", "/data"]
|
||||
volumes:
|
||||
@@ -12,6 +15,9 @@ services:
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
db:
|
||||
cpus: 1.0
|
||||
mem_limit: 512m
|
||||
networks: [data]
|
||||
image: postgres:16.10-bookworm
|
||||
environment:
|
||||
POSTGRES_DB: ${POSTGRES_DB}
|
||||
@@ -25,6 +31,9 @@ services:
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
migrate:
|
||||
cpus: 0.5
|
||||
mem_limit: 128m
|
||||
networks: [data]
|
||||
build: ./src
|
||||
environment:
|
||||
DATABASE_URL: postgres://${POSTGRES_USER}:${POSTGRES_PASSWORD}@db:5432/${POSTGRES_DB}?sslmode=disable
|
||||
@@ -33,6 +42,9 @@ services:
|
||||
db:
|
||||
condition: service_healthy
|
||||
api:
|
||||
cpus: 0.5
|
||||
mem_limit: 128m
|
||||
networks: [proxy, data]
|
||||
build: ./src
|
||||
deploy:
|
||||
replicas: 2
|
||||
@@ -56,6 +68,9 @@ services:
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
haproxy:
|
||||
cpus: 0.5
|
||||
mem_limit: 128m
|
||||
networks: [edge, proxy]
|
||||
image: haproxy:3.2.25-alpine
|
||||
ports:
|
||||
- "127.0.0.1:8080:8080"
|
||||
@@ -71,6 +86,9 @@ services:
|
||||
timeout: 3s
|
||||
retries: 20
|
||||
backend-tests:
|
||||
cpus: 2.0
|
||||
mem_limit: 1g
|
||||
networks: [data]
|
||||
profiles: ["test"]
|
||||
build:
|
||||
context: ./src
|
||||
@@ -85,6 +103,9 @@ services:
|
||||
condition: service_healthy
|
||||
command: ["go", "test", "-race", "-count=1", "-v", "./backend/..."]
|
||||
frontend:
|
||||
cpus: 0.5
|
||||
mem_limit: 512m
|
||||
networks: [edge]
|
||||
build:
|
||||
context: ./src/frontend
|
||||
environment:
|
||||
@@ -106,3 +127,10 @@ services:
|
||||
volumes:
|
||||
postgres_data:
|
||||
redis_data:
|
||||
|
||||
networks:
|
||||
edge:
|
||||
proxy:
|
||||
internal: true
|
||||
data:
|
||||
internal: true
|
||||
|
||||
@@ -1,4 +1,6 @@
|
||||
global
|
||||
# Operator access only inside this container; no host port is published.
|
||||
stats socket ipv4@127.0.0.1:9999 level admin
|
||||
log stdout format raw local0
|
||||
maxconn 1024
|
||||
|
||||
@@ -42,5 +44,6 @@ backend api_replicas
|
||||
listen statistics
|
||||
bind :8404
|
||||
stats enable
|
||||
stats show-legends
|
||||
stats uri /stats
|
||||
stats refresh 2s
|
||||
|
||||
@@ -6,6 +6,8 @@ import time
|
||||
import uuid
|
||||
from pathlib import Path
|
||||
|
||||
from rolling_update import identity, stats
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, arguments, check, run
|
||||
@@ -46,16 +48,21 @@ def main():
|
||||
confirmed_text = "Before failure " + confirmed_key
|
||||
original = c.message(alice, chat, confirmed_text, key=confirmed_key)["json"]
|
||||
env = dict(os.environ, TARGET_INSTANCE_ID=target)
|
||||
addresses = {network["IPAddress"] for network in identity(container)["networks"].values()}
|
||||
slot = next(row["svname"] for row in stats() if row["addr"].split(":")[0] in addresses)
|
||||
started = time.monotonic()
|
||||
proc = subprocess.Popen([str(ROOT / "scripts" / "stop-one.sh")], cwd=ROOT, env=env,
|
||||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||||
successes, last_instances = [], []
|
||||
write_errors = read_errors = reads = 0
|
||||
first_write = first_read = None
|
||||
excluded = None
|
||||
key = uuid.uuid4().hex
|
||||
try:
|
||||
while time.monotonic() - started < 15:
|
||||
check(proc.poll() in (None, 0), "stop-one hook failed")
|
||||
if excluded is None and any(row["svname"] == slot and not row["status"].startswith("UP") for row in stats()):
|
||||
excluded = time.monotonic() - started
|
||||
try:
|
||||
result = c.message(alice, chat, "During failure " + key, key=key)
|
||||
successes.append(result["json"])
|
||||
@@ -74,10 +81,12 @@ def main():
|
||||
except Failure:
|
||||
read_errors += 1
|
||||
time.sleep(0.1)
|
||||
elapsed = time.monotonic() - started
|
||||
check(proc.poll() == 0, "stop-one hook did not finish")
|
||||
check(inspect(container)[1] == "exited", "target container did not stay stopped")
|
||||
check(first_write is not None and first_write <= 10, "writes did not recover within 10 seconds")
|
||||
check(first_read is not None and first_read <= 10, "reads did not recover within 10 seconds")
|
||||
check(excluded is not None and excluded <= 6, "HAProxy did not exclude stopped backend within the 6-second budget")
|
||||
check(len(last_instances) >= 5 and target not in last_instances[-5:], "stopped replica still serves responses")
|
||||
check(c.message(alice, chat, confirmed_text, key=confirmed_key)["json"] == original,
|
||||
"replay after switching replicas changed a confirmed message")
|
||||
@@ -88,6 +97,11 @@ def main():
|
||||
record = {"stopped_instance": target, "container_state": "exited", "successful_writes": len(successes),
|
||||
"successful_reads": reads, "write_errors": write_errors, "read_errors": read_errors,
|
||||
"first_write_seconds": round(first_write, 3), "first_read_seconds": round(first_read, 3)}
|
||||
record.update(elapsed_seconds=round(elapsed, 3),
|
||||
lb_exclusion_seconds=round(excluded, 3),
|
||||
successful_rps=round((len(successes) + reads) / elapsed, 3),
|
||||
attempted_rps=round((len(successes) + reads + write_errors + read_errors) / elapsed, 3),
|
||||
workload="one sequential writer and reader, 100ms pause; not a capacity benchmark")
|
||||
records.append(record)
|
||||
print(json.dumps(record), flush=True)
|
||||
finally:
|
||||
@@ -95,6 +109,8 @@ def main():
|
||||
proc.terminate()
|
||||
proc.wait(timeout=5)
|
||||
restore()
|
||||
ROOT.joinpath(".memory/grade4").mkdir(parents=True, exist_ok=True)
|
||||
ROOT.joinpath(".memory/grade4/failover.json").write_text(json.dumps(records, indent=2) + "\n")
|
||||
print("PASS: each API replica stopped in turn; reads, writes, sessions and confirmed messages preserved")
|
||||
|
||||
|
||||
|
||||
@@ -0,0 +1,55 @@
|
||||
import json
|
||||
|
||||
from rolling_update import COMPOSE, ROOT, command
|
||||
|
||||
|
||||
def main():
|
||||
records = []
|
||||
for service in ("db", "redis", "migrate", "api", "haproxy", "frontend"):
|
||||
ids = command(COMPOSE + ["ps", "--all", "-q", service]).split()
|
||||
assert ids, "missing service: " + service
|
||||
for container in ids:
|
||||
info = json.loads(
|
||||
command(
|
||||
[
|
||||
"docker",
|
||||
"inspect",
|
||||
"--format",
|
||||
'{"hostname":{{json .Config.Hostname}},"cpu":{{.HostConfig.NanoCpus}},"memory":{{.HostConfig.Memory}},"ports":{{json .HostConfig.PortBindings}},"networks":{{json .NetworkSettings.Networks}},"mounts":{{json .Mounts}}}',
|
||||
container,
|
||||
]
|
||||
)
|
||||
)
|
||||
assert info["cpu"] > 0 and info["memory"] > 0, "missing effective limits"
|
||||
networks = set(info["networks"])
|
||||
if service in ("api", "db", "redis"):
|
||||
assert not info["ports"], "unexpected public storage/API port"
|
||||
if service == "frontend":
|
||||
assert networks == {"highload-lab3_edge"}
|
||||
if service == "haproxy":
|
||||
assert "highload-lab3_data" not in networks
|
||||
if service == "api":
|
||||
assert not info["mounts"], "API must not mount persistent state"
|
||||
records.append(
|
||||
{
|
||||
"service": service,
|
||||
"instance": info["hostname"],
|
||||
"cpu_limit": info["cpu"] / 1e9,
|
||||
"memory_mib": info["memory"] // (1024 * 1024),
|
||||
"networks": sorted(networks),
|
||||
"public_ports": info["ports"],
|
||||
}
|
||||
)
|
||||
assert len([row for row in records if row["service"] == "api"]) == 2
|
||||
ROOT.joinpath(".memory/grade4").mkdir(parents=True, exist_ok=True)
|
||||
ROOT.joinpath(".memory/grade4/resources.json").write_text(
|
||||
json.dumps(records, indent=2) + "\n"
|
||||
)
|
||||
print(json.dumps(records, indent=2))
|
||||
print(
|
||||
"PASS: effective CPU/RAM limits, two API replicas, private storage/API, isolated frontend"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,113 @@
|
||||
import json
|
||||
import sys
|
||||
import threading
|
||||
import time
|
||||
import uuid
|
||||
from concurrent.futures import ThreadPoolExecutor
|
||||
from pathlib import Path
|
||||
|
||||
from rolling_update import replace_all
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure, arguments, check, run
|
||||
from resilience import history
|
||||
|
||||
|
||||
def main():
|
||||
args = arguments(__doc__)
|
||||
client = Client(args.base_url, args.ca_file)
|
||||
alice, bob, _, chat = client.bootstrap()
|
||||
key = uuid.uuid4().hex
|
||||
original = client.message(alice, chat, "before update " + key, key=key)["json"]
|
||||
stop = threading.Event()
|
||||
|
||||
def worker(index):
|
||||
local = Client(args.base_url, args.ca_file, timeout=3)
|
||||
result = {"writes": [], "reads": 0, "errors": 0, "instances": set()}
|
||||
pending = uuid.uuid4().hex
|
||||
while not stop.is_set():
|
||||
try:
|
||||
if index < 2:
|
||||
response = local.message(
|
||||
alice, chat, "rolling " + pending, key=pending
|
||||
)
|
||||
result["writes"].append(response["json"])
|
||||
pending = uuid.uuid4().hex
|
||||
else:
|
||||
response = local.call(
|
||||
"GET",
|
||||
"/api/v1/chats/" + chat["id"] + "/messages",
|
||||
actor=bob,
|
||||
schema="MessagePage",
|
||||
)
|
||||
result["reads"] += 1
|
||||
result["instances"].add(response["headers"]["X-Instance-Id"])
|
||||
except Failure:
|
||||
result["errors"] += 1 # Uncertain POST keeps its original key and text.
|
||||
time.sleep(0.02)
|
||||
return result
|
||||
|
||||
started = time.monotonic()
|
||||
with ThreadPoolExecutor(max_workers=4) as pool:
|
||||
futures = [pool.submit(worker, index) for index in range(4)]
|
||||
try:
|
||||
time.sleep(2)
|
||||
replacements = replace_all()
|
||||
time.sleep(2)
|
||||
finally:
|
||||
stop.set()
|
||||
results = [future.result() for future in futures]
|
||||
elapsed = time.monotonic() - started
|
||||
confirmed = [original] + [
|
||||
message for result in results for message in result["writes"]
|
||||
]
|
||||
messages = history(client, bob, chat)
|
||||
by_id = {message["id"]: message for message in messages}
|
||||
check(
|
||||
all(by_id.get(message["id"]) == message for message in confirmed),
|
||||
"confirmed message lost or changed",
|
||||
)
|
||||
texts = [message["text"] for message in messages]
|
||||
check(len(texts) == len(set(texts)), "retry created a duplicate")
|
||||
check(
|
||||
client.message(alice, chat, "before update " + key, key=key)["json"]
|
||||
== original,
|
||||
"idempotency lost",
|
||||
)
|
||||
instances = set().union(*(result["instances"] for result in results))
|
||||
check(
|
||||
all(
|
||||
record["old_instance"] in instances and record["new_instance"] in instances
|
||||
for record in replacements
|
||||
),
|
||||
"load did not observe all original and replacement processes",
|
||||
)
|
||||
writes = len(confirmed) - 1
|
||||
reads = sum(result["reads"] for result in results)
|
||||
errors = sum(result["errors"] for result in results)
|
||||
report = {
|
||||
"elapsed_seconds": round(elapsed, 3),
|
||||
"concurrency": 4,
|
||||
"successful_writes": writes,
|
||||
"successful_reads": reads,
|
||||
"errors": errors,
|
||||
"successful_rps": round((writes + reads) / elapsed, 3),
|
||||
"replacements": replacements,
|
||||
"confirmed_messages_preserved": True,
|
||||
"session_preserved": True,
|
||||
"workload": "two writers, two readers, 20ms pause per worker; not a capacity benchmark",
|
||||
}
|
||||
ROOT.joinpath(".memory/grade4").mkdir(parents=True, exist_ok=True)
|
||||
ROOT.joinpath(".memory/grade4/rolling.json").write_text(
|
||||
json.dumps(report, indent=2) + "\n"
|
||||
)
|
||||
print(json.dumps(report, indent=2))
|
||||
check(errors == 0, "planned replacement caused request errors; see metrics")
|
||||
print(
|
||||
"PASS: sequential replacement under load; all confirmed messages and sessions preserved"
|
||||
)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
@@ -0,0 +1,173 @@
|
||||
import csv
|
||||
import fcntl
|
||||
import io
|
||||
import json
|
||||
import subprocess
|
||||
import time
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
COMPOSE = [
|
||||
"docker",
|
||||
"compose",
|
||||
"--project-name",
|
||||
"highload-lab3",
|
||||
"--env-file",
|
||||
".env",
|
||||
"-f",
|
||||
"compose.yml",
|
||||
]
|
||||
|
||||
|
||||
def command(args, **kwargs):
|
||||
return subprocess.check_output(args, cwd=ROOT, text=True, **kwargs).strip()
|
||||
|
||||
|
||||
def containers():
|
||||
return command(COMPOSE + ["ps", "-q", "api"]).split()
|
||||
|
||||
|
||||
def identity(container):
|
||||
# Never dump Docker environment: it contains the database credential.
|
||||
return json.loads(
|
||||
command(
|
||||
[
|
||||
"docker",
|
||||
"inspect",
|
||||
"--format",
|
||||
'{"hostname":{{json .Config.Hostname}},"state":{{json .State.Status}},"networks":{{json .NetworkSettings.Networks}}}',
|
||||
container,
|
||||
]
|
||||
)
|
||||
)
|
||||
|
||||
|
||||
def stats():
|
||||
with urllib.request.urlopen(
|
||||
"http://localhost:8404/stats;csv", timeout=3
|
||||
) as response:
|
||||
rows = csv.DictReader(io.StringIO(response.read().decode().removeprefix("# ")))
|
||||
return [
|
||||
row
|
||||
for row in rows
|
||||
if row["pxname"] == "api_replicas" and row["svname"].startswith("api")
|
||||
]
|
||||
|
||||
|
||||
def runtime(slot, state):
|
||||
proxy = command(COMPOSE + ["ps", "-q", "haproxy"])
|
||||
reply = command(
|
||||
["docker", "exec", "-i", proxy, "sh", "-c", "nc -w 1 127.0.0.1 9999"],
|
||||
input=f"set server api_replicas/{slot} state {state}\n",
|
||||
)
|
||||
if reply:
|
||||
raise RuntimeError("HAProxy runtime command failed: " + reply)
|
||||
|
||||
|
||||
def wait_for(predicate, description, seconds=30):
|
||||
deadline = time.monotonic() + seconds
|
||||
while time.monotonic() < deadline:
|
||||
if predicate():
|
||||
return
|
||||
time.sleep(0.1)
|
||||
raise RuntimeError("Timed out: " + description)
|
||||
|
||||
|
||||
def replace_all():
|
||||
ROOT.joinpath(".memory").mkdir(exist_ok=True)
|
||||
with ROOT.joinpath(".memory/rolling.lock").open("w") as lock:
|
||||
fcntl.flock(lock, fcntl.LOCK_EX | fcntl.LOCK_NB)
|
||||
originals = containers()
|
||||
if len(originals) != 2:
|
||||
raise RuntimeError("Exactly two running API replicas are required")
|
||||
# One explicit migration job per operation, never one per replica.
|
||||
# Only backward-compatible migrations may be deployed while API is live.
|
||||
subprocess.run(
|
||||
COMPOSE + ["run", "--rm", "--no-deps", "migrate"], cwd=ROOT, check=True
|
||||
)
|
||||
records = []
|
||||
for old in originals:
|
||||
before = containers()
|
||||
if (
|
||||
len(before) != 2
|
||||
or len([row for row in stats() if row["status"].startswith("UP")]) != 2
|
||||
):
|
||||
raise RuntimeError(
|
||||
"Both replicas must be ready before taking one out of service"
|
||||
)
|
||||
survivor = next(container for container in before if container != old)
|
||||
info = identity(old)
|
||||
addresses = {network["IPAddress"] for network in info["networks"].values()}
|
||||
matches = [row for row in stats() if row["addr"].split(":")[0] in addresses]
|
||||
if len(matches) != 1 or not matches[0]["status"].startswith("UP"):
|
||||
raise RuntimeError("Target is not uniquely ready in HAProxy")
|
||||
slot = matches[0]["svname"]
|
||||
started = time.monotonic()
|
||||
try:
|
||||
runtime(slot, "drain")
|
||||
wait_for(
|
||||
lambda: any(
|
||||
row["svname"] == slot
|
||||
and row["status"].startswith("DRAIN")
|
||||
and int(row["scur"]) == 0
|
||||
for row in stats()
|
||||
),
|
||||
"drain in-flight requests",
|
||||
)
|
||||
command(["docker", "stop", "--timeout", "15", old])
|
||||
logs = command(["docker", "logs", old], stderr=subprocess.STDOUT)
|
||||
if "server stopped gracefully" not in logs:
|
||||
raise RuntimeError("Target did not finish graceful shutdown")
|
||||
command(["docker", "rm", old])
|
||||
# Compose fills the missing replica without recreating its survivor.
|
||||
subprocess.run(
|
||||
COMPOSE
|
||||
+ [
|
||||
"up",
|
||||
"-d",
|
||||
"--no-deps",
|
||||
"--no-recreate",
|
||||
"--wait",
|
||||
"--wait-timeout",
|
||||
"60",
|
||||
"api",
|
||||
],
|
||||
cwd=ROOT,
|
||||
check=True,
|
||||
)
|
||||
finally:
|
||||
runtime(slot, "ready")
|
||||
after = containers()
|
||||
if len(after) != 2 or survivor not in after or old in after:
|
||||
raise RuntimeError("Replacement changed the surviving container")
|
||||
new = next(container for container in after if container != survivor)
|
||||
new_info = identity(new)
|
||||
new_addresses = {
|
||||
network["IPAddress"] for network in new_info["networks"].values()
|
||||
}
|
||||
wait_for(
|
||||
lambda: (
|
||||
len([row for row in stats() if row["status"].startswith("UP")]) == 2
|
||||
and any(
|
||||
row["addr"].split(":")[0] in new_addresses
|
||||
and row["status"].startswith("UP")
|
||||
for row in stats()
|
||||
)
|
||||
),
|
||||
"new replica ready through HAProxy",
|
||||
)
|
||||
record = {
|
||||
"old_instance": info["hostname"],
|
||||
"new_instance": new_info["hostname"],
|
||||
"survivor_instance": identity(survivor)["hostname"],
|
||||
"replacement_seconds": round(time.monotonic() - started, 3),
|
||||
"graceful_shutdown": True,
|
||||
}
|
||||
records.append(record)
|
||||
print(json.dumps(record), flush=True)
|
||||
return records
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
replace_all()
|
||||
@@ -119,7 +119,8 @@ func readyHandler(health *services.HealthService) http.HandlerFunc {
|
||||
writeError(w, 405, "method_not_allowed", "method not allowed", requestID)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second)
|
||||
// Readiness must finish before HAProxy's one-second check read timeout.
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 500*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := health.Ready(ctx); err != nil {
|
||||
writeError(w, 503, "unavailable", "dependency unavailable", requestID)
|
||||
|
||||
Reference in New Issue
Block a user