Files
mtusi2026lab3/student-tests/check_stack.py
T

73 lines
3.8 KiB
Python

import json
import platform
import sys
from common import call, check, compose_output, docker, new_user, seen_instances
def main():
info = json.loads(docker("info", "--format", "{{json .}}"))
print(f"host: {platform.system()} {platform.release()}, {platform.processor() or platform.machine()}; "
f"client Python {platform.python_version()}")
print(f"Docker {docker('version', '--format', '{{.Server.Version}}')}, "
f"{compose_output('version').strip()}; Docker VM: {info.get('NCPU')} CPU, "
f"{int(info.get('MemTotal', 0)) / 2**30:.1f} GiB RAM, {info.get('OperatingSystem')}")
print()
print(compose_output("ps", "-a", "--format", "table {{.Service}}\t{{.ID}}\t{{.Status}}\t{{.Ports}}").strip())
migrate = compose_output("ps", "-a", "--format", "{{.Status}}", "migrate").strip()
check(migrate.startswith("Exited (0)"), "migrate service must finish with exit code 0")
config = json.loads(compose_output("config", "--format", "json"))
services = config["services"]
containers = compose_output("ps", "-q").split()
rows = [json.loads(line) for line in docker("inspect", "--format", "{{json .}}", *containers).splitlines()]
print()
print("container image cpus memory host ports networks")
api_count = 0
for row in sorted(rows, key=lambda r: r["Name"]):
labels = row["Config"]["Labels"]
service = labels.get("com.docker.compose.service")
limits = row["HostConfig"]
cpus = limits.get("NanoCpus", 0) / 1e9
memory = limits.get("Memory", 0) // 2**20
ports = sorted({f"{b['HostIp']}:{b['HostPort']}" for bindings in (row["NetworkSettings"]["Ports"] or {}).values()
for b in (bindings or [])})
networks = sorted(name.split("_", 1)[-1] for name in row["NetworkSettings"]["Networks"])
print(f"{row['Name'].lstrip('/'):<28} {row['Config']['Image']:<24} {cpus:>4.2f} {memory:>4} MiB "
f"{','.join(ports) or '-':<23} {','.join(networks)}")
check(cpus > 0 and memory > 0, f"{service}: no CPU/RAM limit")
if service == "api":
api_count += 1
check(not ports, "api must not publish ports: everything goes through the balancer")
if service == "lb":
check(ports and all(p.startswith("127.0.0.1:") for p in ports), "lb must listen on 127.0.0.1 only")
if service in ("postgres", "redis"):
check(not ports and networks == ["data"], f"{service} must be only in the internal data network")
check(api_count >= 2, "need at least 2 api replicas")
check(all("container_name" not in s for s in services.values()), "container_name prevents scaling")
check(config["networks"]["data"].get("internal") is True, "data network must be internal")
check("data" not in services["lb"]["networks"], "lb must not reach postgres/redis")
print()
for name, service in sorted(services.items()):
secrets = sorted(s["source"] for s in service.get("secrets", []))
print(f"secrets of {name}: {secrets or '-'}")
check(not services["lb"].get("secrets"), "lb gets no secrets")
check(sorted(s["source"] for s in services["migrate"]["secrets"]) == ["database_url"], "migrate needs only database_url")
user = new_user("stack")
served = seen_instances(user["token"])
print()
print(f"through http://127.0.0.1:8080 one session is served by {len(served)} replicas: {sorted(served)}")
check(len(served) >= 2, "requests are not balanced")
health = call("GET", "/health/ready", 200)
print(f"/health/ready -> {health.status} from {health.instance}")
print(f"PASS: {api_count} api replicas behind one entry point, no direct API ports, limits on every "
f"container, internal data network, secrets only where needed")
if __name__ == "__main__":
sys.exit(main())