Files
mtusi2026lab6/student-tests/lab5/stand.py

458 lines
25 KiB
Python

"""Observe and exercise a Compose stand. Business traffic always goes via the LB."""
from concurrent.futures import ThreadPoolExecutor
from contextlib import contextmanager
import http.client
import io
import json
from pathlib import Path
import os
import subprocess
import threading
import time
from urllib.parse import urlsplit
from checks import ROOT, Failure, Pending, assert_history, check, history, message_path, key, post, summarize, wait
from client import shape
class Stand:
# Whitelist inspect fields: no environment, mounts, or container log dumps.
FORMAT = "\t".join(("{{.Id}}", "{{.Config.Hostname}}", "{{.Image}}", "{{.State.Status}}",
"{{.State.StartedAt}}", "{{.State.FinishedAt}}", "{{.State.ExitCode}}",
"{{.State.OOMKilled}}", "{{.HostConfig.NanoCpus}}", "{{.HostConfig.CpuQuota}}",
"{{.HostConfig.CpuPeriod}}", "{{.HostConfig.Memory}}",
"{{json .NetworkSettings.Ports}}", "{{json .HostConfig.PortBindings}}",
"{{.HostConfig.NetworkMode}}", "{{.HostConfig.PublishAllPorts}}"))
def __init__(self, args, c):
self.a = args
self.c = c
self.e = c.evidence
self.compose = ["docker", "compose"]
if args.project:
self.compose += ["--project-name", args.project]
for file in args.compose_file:
self.compose += ["--file", str(Path(file).resolve())]
def command(self, name, argv, *, timeout=30, env=None, allow_failure=False):
start = time.monotonic()
try:
result = subprocess.run(argv, cwd=ROOT, env=env, stdout=subprocess.PIPE,
stderr=subprocess.PIPE, timeout=timeout)
except (OSError, subprocess.TimeoutExpired) as exc:
self.e.event("command", action=name, elapsed_s=time.monotonic()-start, error=type(exc).__name__)
raise Failure(f"{name}: {type(exc).__name__}") from None
self.e.event("command", action=name, elapsed_s=time.monotonic()-start, exit_code=result.returncode)
check(allow_failure or result.returncode == 0, f"{name}: exit {result.returncode}")
return result
def ids(self, service, all_states=True):
return self.command("compose ps " + service, self.compose + ["ps"] +
(["-a"] if all_states else []) + ["-q", service]).stdout.decode().split()
def containers(self, service):
results = []
for cid in self.ids(service):
result = self.command("inspect " + service, ["docker", "inspect", "--format", self.FORMAT, cid])
parts = result.stdout.decode().rstrip("\n").split("\t")
fields = ("id", "alias", "image", "state", "started_at", "finished_at", "exit_code", "oom",
"nano_cpus", "cpu_quota", "cpu_period", "memory", "ports", "bindings", "network", "publish_all")
check(len(parts) == len(fields), "unexpected docker inspect format")
for index in range(6, len(fields)):
parts[index] = json.loads(parts[index]) if fields[index] != "network" else parts[index]
results.append(dict(zip(fields, parts)))
return results
def public_topology(self):
try:
if not hasattr(self, "engine"):
fmt = "{{.ServerVersion}}\t{{.OSType}}\t{{.Architecture}}\t{{.NCPU}}\t{{.MemTotal}}"
result = self.command("Docker availability", ["docker", "info", "--format", fmt])
self.engine = result.stdout.decode().strip().split("\t")
check(len(self.engine) == 5, "unexpected Docker engine metadata")
self.e.event("docker_environment", version=self.engine[0], os=self.engine[1],
architecture=self.engine[2], logical_cpus=int(self.engine[3]),
memory_bytes=int(self.engine[4]))
except Failure:
raise Pending("Docker daemon not available") from None
services = self.command("Compose service names", self.compose + ["config", "--services"]).stdout.decode().split()
if self.a.api not in services or self.a.lb not in services:
raise Pending("Compose does not define API and LB services")
api = [r for r in self.containers(self.a.api) if r["state"] == "running"]
lb = [r for r in self.containers(self.a.lb) if r["state"] == "running"]
self.e.event("topology", api=api, lb=lb)
if len(api) < 2 or not lb:
raise Pending("stand needs two running API replicas and a public LB")
self.a_ids = {r["alias"] for r in api}
check(len(self.a_ids) == len(api), "API aliases are not unique")
self.lb = lb[0]
port = urlsplit(self.c.base).port or (443 if self.c.base.startswith("https:") else 80)
check(any(int(binding["HostPort"]) == port for r in lb
for group in (r["ports"] or {}).values() for binding in group or []),
"BASE_URL port is not published by the selected LB")
return api
def resources(self):
api = self.public_topology()
for r in api:
check(r["nano_cpus"] > 0 or (r["cpu_quota"] > 0 and r["cpu_period"] > 0),
"API CPU has no hard limit")
check(r["memory"] > 0, "API RAM has no hard limit")
check(not any((r["ports"] or {}).values()) and not any((r["bindings"] or {}).values())
and not r["publish_all"] and r["network"] != "host", "API bypasses LB via host ports/network")
self.stats()
def stats(self):
ids = self.ids(self.a.api, False) + [self.lb["id"]]
result = self.command("docker stats", ["docker", "stats", "--no-stream", "--format",
"{{.ID}}\t{{.CPUPerc}}\t{{.MemUsage}}", *ids], timeout=10)
self.e.event("resource_sample", samples=result.stdout.decode().splitlines())
def observe(self, actor, wanted=None, *, duration=3, forbidden=None):
wanted = self.a_ids if wanted is None else wanted
deadline, seen, attempts = time.monotonic() + duration, set(), 0
while time.monotonic() < deadline:
result = self.c.call("GET", "/api/v1/users/me", actor=actor, schema="User")
check(result["json"] == actor["user"], "same Bearer token resolved to another user")
alias = result["headers"]["X-Instance-Id"]
check(alias != forbidden, "LB routed authenticated request to the excluded replica")
check(alias in self.a_ids, "LB routed to an API outside this Compose project")
seen.add(alias)
attempts += 1
if forbidden is not None:
time.sleep(0.05)
if forbidden is None and wanted <= seen:
break
self.e.event("routing", wanted=sorted(wanted), observed=sorted(seen), excluded=forbidden, attempts=attempts)
check(wanted <= seen and attempts >= (10 if forbidden else 2), "LB did not exercise the required replicas")
return seen
def network_target(self, target):
fmt = "{{json .NetworkSettings.Networks}}"
def networks(cid):
r = self.command("container networks", ["docker", "inspect", "--format", fmt, cid])
return json.loads(r.stdout)
net = networks(target["id"])
shared = net.keys() & networks(self.lb["id"]).keys()
chosen = self.a.network or (sorted(shared)[0] if shared else None)
check(chosen in shared and net[chosen]["IPAddress"], "no shared API/LB network with IPv4")
return net[chosen]["IPAddress"]
def direct_health(self, target, endpoint, status):
# From the LB network namespace, bypass routing only for health diagnostics.
ip = self.network_target(target)
result = self.command("direct health/" + endpoint, [
"docker", "run", "--rm", "--pull", "never", "--network", "container:" + self.lb["id"],
"--entrypoint", "curl", self.a.probe_image, "--http1.1", "--noproxy", "*",
"--include", "--silent", "--show-error", "--max-time", "4",
f"http://{ip}:{self.a.api_port}/health/{endpoint}",
], timeout=12)
response = http.client.HTTPResponse(type("Socket", (), {"makefile": lambda *_: io.BytesIO(result.stdout)})())
with response:
response.begin()
self.e.event("direct_health", endpoint=endpoint, status=response.status,
instance=response.getheader("X-Instance-Id"))
check(response.status == status and response.getheader("X-Instance-Id") == target["alias"],
f"target /health/{endpoint}: expected {status}, got {response.status}")
value = json.loads(response.read())
rid = response.getheader("X-Request-Id")
check(bool(rid) and response.headers.get_content_type() == "application/json",
"direct health response is missing required headers")
if status == 200:
check(shape(value, "Health") == {"status": "ok"}, "direct health payload differs")
else:
check(shape(value, "Error")["error"]["code"] == "unavailable"
and value["error"]["request_id"] == rid, "readiness 503 error envelope differs")
return True
def hook(self, executable, target=None, timeout=90, **extra):
if not executable:
raise Pending("operator hook is not configured")
path = Path(executable).resolve()
check(path.is_file() and os.access(path, os.X_OK), "operator hook must be an executable file")
env = dict(os.environ, BASE_URL=self.c.base, **extra)
if self.a.project:
env["COMPOSE_PROJECT_NAME"] = self.a.project
if target:
env.update(TARGET_INSTANCE_ID=target["alias"], TARGET_CONTAINER_ID=target["id"])
self.command("hook " + path.name, [str(path)], env=env, timeout=timeout)
def unready(self):
api = self.public_topology()
if not (self.a.unready_hook and self.a.ready_hook):
raise Pending("configure hooks to fault and restore one API dependency without disconnecting LB")
alice = self.c.user("readiness")
self.observe(alice)
target = api[0]
self.direct_health(target, "live", 200)
self.direct_health(target, "ready", 200)
try:
self.hook(self.a.unready_hook, target, LAB5_HOOK_MODE="unready")
wait(lambda: self.direct_health(target, "ready", 503), 20, "target never returned readiness 503")
self.direct_health(target, "live", 200)
# Allow LB convergence, then require sustained exclusion while the
# target remains reachable from the LB network and answers 503.
others = self.a_ids - {target["alias"]}
def routed_elsewhere():
response = self.c.call("GET", "/api/v1/users/me", actor=alice, schema="User")
return response["headers"]["X-Instance-Id"] in others
wait(routed_elsewhere, 10, "no authenticated request routed to a ready replica")
wait(lambda: self.observe(alice, others, duration=3, forbidden=target["alias"]), 15,
"LB did not consistently exclude a running 503 replica")
self.direct_health(target, "live", 200)
self.direct_health(target, "ready", 503)
finally:
self.hook(self.a.ready_hook, target, LAB5_HOOK_MODE="ready")
wait(lambda: self.direct_health(target, "ready", 200), 20, "target stayed unready after restore")
wait(lambda: self.observe(alice), 20, "restored API did not rejoin LB")
def ready_aliases(self, actor):
api = self.public_topology()
self.observe(actor)
return api
def migration_snapshot(self):
service = self.a.migrate
rows = self.containers(service)
check(len(rows) == 1, "expected one migrator container")
row = rows[0]
check(row["state"] == "exited" and row["exit_code"] == 0, "migrator did not exit cleanly")
log = self.command("migrator logs", ["docker", "logs", row["id"]])
completions = []
for line in (log.stdout + log.stderr).splitlines():
try:
item = json.loads(line)
except (ValueError, UnicodeError):
continue
if isinstance(item, dict) and item.get("msg") == "migrations completed":
completions.append(item.get("applied"))
check(len(completions) == 1, "migrator must log exactly one successful invocation")
sql = ("SELECT version_id, is_applied, count(*) FROM goose_db_version "
"GROUP BY 1,2 ORDER BY 1,2;")
output = self.command("migration version counts", self.compose + [
"exec", "-T", self.a.db, "psql", "-X", "-v", "ON_ERROR_STOP=1", "-At",
"-U", self.a.db_user, "-d", self.a.db_name, "-c", sql,
]).stdout.decode().splitlines()
versions = sorted(int(p.name.split("_", 1)[0]) for p in (ROOT / "db/migrations").glob("*.sql"))
check(output == [f"{v}|t|1" for v in [0, *versions]], "migration history differs from one apply per version")
check(all(r["started_at"] >= row["finished_at"] for r in self.containers(self.a.api)
if r["state"] == "running"), "API started before migrations completed")
self.e.event("migrations", container=row, applied=completions, versions=output)
return row, output
def persistence(self):
api = self.public_topology()
if not self.a.restart_hook:
raise Pending("configure a hook that restarts API and stores without removing volumes")
stores = [self.a.db, *self.a.store]
before = {s: self.containers(s) for s in stores}
check(all(rows and all(r["state"] == "running" for r in rows) for rows in before.values()),
"configured persistence stores must be running")
alice, bob, _, chat = self.c.bootstrap()
self.observe(alice)
k, text = key(), "committed before restarting API and stores"
original = post(self.c, alice, chat, k, text)["json"]
self.hook(self.a.restart_hook)
wait(lambda: self.c.call("GET", "/health/ready", schema="Health"), 90, "LB did not recover after restart")
after = self.public_topology()
for s, previous, current in [(self.a.api, api, after)] + [
(s, before[s], self.containers(s)) for s in stores]:
check(len(previous) == len(current) and all(r["state"] == "running" for r in current)
and not {r["started_at"] for r in previous} & {r["started_at"] for r in current},
f"restart did not change StartedAt for every {s}")
self.e.event("restart_observed", service=s, before=previous, after=current)
self.observe(alice)
check(post(self.c, alice, chat, k, text)["json"] == original, "idempotency lost after restart")
assert_history(self.c, bob, chat, [original])
def verify_stopped(self, target):
now = {r["id"]: r for r in self.containers(self.a.api)}
row = now.get(target["id"])
check(row is not None and row["state"] == "exited", "SIGTERM did not stop the selected process")
check(row["exit_code"] == 0 and not row["oom"], "API did not exit gracefully on SIGTERM")
self.e.event("stopped", container=row)
def failover(self):
api = self.public_topology()
alice, bob, _, chat = self.c.bootstrap()
self.observe(alice)
with traffic(self.c, alice, bob, self.a.workers) as load:
self.sample_under_load(load)
for target in api:
self.e.event("target", action="SIGTERM", alias=target["alias"], container=target["id"])
k, text, sent = wait(lambda: write_from(self.c, alice, chat, target["alias"]), 10,
"could not confirm original POST on selected replica")
others = self.a_ids - {target["alias"]}
endpoint = self.network_target(target)
started = time.monotonic()
first_record = len(load.records)
# Race real client traffic and recovery probes with Docker stop.
with ThreadPoolExecutor(max_workers=1) as pool:
stop = pool.submit(self.command, "SIGTERM " + target["alias"], [
"docker", "stop", "--signal", "SIGTERM", "--time", "20", target["id"],
])
try:
recovered = self.recover(alice, bob, chat, target, stop, started)
self.e.event("recovery", target=target["alias"], seconds=recovered)
if recovered is not None:
print(f" {target['alias']}: read/write restored in {recovered:.3f} s", flush=True)
check(recovered is not None and recovered <= 10, "read and write recovery exceeded 10 seconds")
stop.result()
self.verify_stopped(target)
probe = self.command("fresh TCP to stopped API", ["docker", "exec", self.lb["id"],
"nc", "-w", "2", "-z", endpoint, str(self.a.api_port)],
allow_failure=True, timeout=5)
check(probe.returncode == 1, "fresh connection to stopped replica was accepted or probe failed")
replay = post(self.c, alice, chat, k, text)
check(replay["json"] == sent["json"] and replay["headers"]["X-Instance-Id"] in others,
"different replica did not replay the original Message")
self.observe(alice, others, duration=self.a.window, forbidden=target["alias"])
read_back = history(self.c, bob, chat)
check([m for m in read_back if m["text"] == text] == [sent["json"]],
"confirmed pre-stop POST missing, changed or duplicated")
check(len({m["text"] for m in read_back}) == len(read_back),
"an uncertain retry created duplicate effects")
finally:
summarize(self.e, load.records[first_record:], time.monotonic() - started,
window="target " + target["alias"])
# Settle the stop before starting the same container.
try:
stop.result()
finally:
self.command("restore " + target["alias"], ["docker", "start", target["id"]])
wait(lambda: self.observe(alice), 25, "restored replica did not rejoin LB")
def recover(self, alice, bob, chat, target, stop, started):
k, text = key(), "recovery probe " + key()
deadline = started + 10
while time.monotonic() < deadline:
if stop.done():
stop.result()
try:
result = post(self.c, alice, chat, k, text)
if result["headers"]["X-Instance-Id"] != target["alias"]:
page = self.c.call("GET", message_path(chat) + "?limit=100", actor=bob, schema="MessagePage")
if (page["headers"]["X-Instance-Id"] != target["alias"]
and result["json"] in page["json"]["items"]):
return time.monotonic() - started
except Failure:
pass # Keep the exact key/body after an uncertain write.
time.sleep(0.1)
return None
def sample_under_load(self, load):
time.sleep(self.a.warmup)
check(load.successes() >= 1, "no successful business request during load warm-up")
self.stats()
def rolling(self):
api = self.public_topology()
if not self.a.roll_hook:
raise Pending("awaiting rolling update hook/candidate image")
before = self.migration_snapshot()
alice, bob, _, _ = self.c.bootstrap()
self.observe(alice)
original_ids = {r["id"] for r in api}
previous = {r["id"]: r for r in api}
with traffic(self.c, alice, bob, self.a.workers) as load:
self.sample_under_load(load)
start_index = len(load.records)
for target in api:
step_at = time.monotonic()
self.e.event("target", action="rolling_update", alias=target["alias"], container=target["id"])
self.hook(self.a.roll_hook, target)
current = {r["id"]: r for r in self.public_topology()}
stable = set(previous) - {target["id"]}
new = set(current) - set(previous)
check(set(current) == stable | new and len(new) == 1, "rolling step did not replace exactly one API")
check(all(current[r] == previous[r] for r in stable), "rolling step also disturbed another API")
replacement = current[new.pop()]
check(replacement["image"] != target["image"], "rolling step did not apply a new immutable image")
self.observe(alice)
time.sleep(self.a.window)
self.e.event("rolling_step", previous=target, replacement=replacement,
seconds=time.monotonic() - step_at)
previous = current
check(not original_ids & set(previous), "some original replicas were not updated")
stats = load.records[start_index:]
check(stats and all(r["ok"] for r in stats), "business request failed during rolling update")
check(self.migration_snapshot() == before, "rolling update restarted migrations or changed version history")
def write_from(c, actor, chat, alias):
k, text = key(), "before SIGTERM " + key()
r = post(c, actor, chat, k, text)
return (k, text, r) if r["headers"]["X-Instance-Id"] == alias else None
class Traffic:
def __init__(self, c, actor, reader, chat):
self.c, self.actor, self.reader, self.chat = c, actor, reader, chat
self.stop = threading.Event()
self.records = []
self.confirmed = {}
self.offered = set()
self.lock = threading.Lock()
def lane(self):
while not self.stop.is_set():
k = key()
with self.lock:
self.offered.add(k)
for op in ("write", "read"):
started = time.monotonic()
ok = False
status = None
try:
if op == "write":
result = post(self.c, self.actor, self.chat, k, k)
with self.lock:
self.confirmed[k] = result["json"]
else:
result = self.c.call("GET", "/api/v1/users/me", actor=self.actor, schema="User")
check(result["json"] == self.actor["user"], "load token resolved to another user")
ok = True
except Failure:
pass
finally:
status = self.c.local.status
row = self.c.evidence.event("load_request", op=op, status=status, ok=ok,
instance=self.c.local.instance, elapsed_s=time.monotonic()-started)
with self.lock:
self.records.append(row)
if self.stop.is_set():
break
def successes(self):
with self.lock:
return sum(r["ok"] for r in self.records)
def reconcile(self):
found = history(self.c, self.reader, self.chat)
by_text = {m["text"]: m for m in found}
check(len(by_text) == len(found) and set(by_text) <= self.offered,
"load history contains duplicate writes or unknown data")
check(all(by_text.get(k) == v for k, v in self.confirmed.items()),
"confirmed load write missing or changed in history")
self.c.evidence.event("load_history", observed=len(found), confirmed=len(self.confirmed),
offered=len(self.offered))
@contextmanager
def traffic(c, actor, reader, workers):
chat = c.call("POST", "/api/v1/chats", 201, actor=actor, schema="Chat",
body={"title": "Lab 5 load", "member_ids": [actor["id"], reader["id"]]})["json"]
load = Traffic(c, actor, reader, chat)
started = time.monotonic()
with ThreadPoolExecutor(max_workers=workers) as pool:
futures = [pool.submit(load.lane) for _ in range(workers)]
try:
yield load
finally:
load.stop.set()
for future in futures:
future.result()
elapsed = time.monotonic() - started
summarize(c.evidence, load.records, elapsed)
load.reconcile()