#!/usr/bin/env python3 """Build and verify an isolated lab1 container; save sanitized evidence. python3 student-tests/container_level4.py --build --output evidence/level4.json Requires Docker, make and Python 3.9+. Removes only its own test container. """ import argparse import datetime as dt import hashlib import json from pathlib import Path import platform import shutil import socket import subprocess import sys import tempfile import time import urllib.error import urllib.request import uuid ROOT = Path(__file__).resolve().parents[1] sys.path.insert(0, str(ROOT / "tests")) from client import Client, Failure, check # noqa: E402 def command(args, timeout=60, required=True): result = subprocess.run(args, cwd=ROOT, capture_output=True, text=True, timeout=timeout) if required and result.returncode: raise Failure("command failed: " + args[0] + " (exit %d)" % result.returncode) return result def docker(*args, required=True): result = command(["docker", *args], required=required) return (result.stdout + result.stderr if args[0] == "logs" else result.stdout).strip() def inspect(name): return json.loads(docker("inspect", name))[0] def wait_for(predicate, seconds, message): deadline = time.monotonic() + seconds while time.monotonic() < deadline: if predicate(): return time.sleep(0.1) raise Failure(message) def source_fingerprint(): paths = [ROOT / name for name in ("Dockerfile", ".dockerignore", "go.mod", "go.sum")] paths += list((ROOT / "cmd").rglob("*.go")) + list((ROOT / "internal").rglob("*.go")) digest = hashlib.sha256() for path in sorted(paths): digest.update(str(path.relative_to(ROOT)).encode() + b"\0" + path.read_bytes() + b"\0") return digest.hexdigest() def main(): parser = argparse.ArgumentParser(description=__doc__) parser.add_argument("--image", default="highload-lab1-audit:local") parser.add_argument("--build", action="store_true") parser.add_argument("--output", default="evidence/level4.json") args = parser.parse_args() output = ROOT / args.output output.parent.mkdir(parents=True, exist_ok=True) evidence = { "checked_at_utc": dt.datetime.now(dt.timezone.utc).isoformat(), "git_head": command(["git", "rev-parse", "HEAD"]).stdout.strip(), "uncommitted_working_files": bool(command(["git", "status", "--porcelain"]).stdout), "source_sha256": source_fingerprint(), "host": {"system": platform.system(), "architecture": platform.machine()}, "limits": {"cpu": 1, "memory_bytes": 128 * 1024 * 1024}, "checks": [], } if platform.system() == "Darwin": hardware = command(["sysctl", "-n", "machdep.cpu.brand_string", "hw.memsize", "hw.ncpu"], required=False) if hardware.returncode == 0: cpu, memory, cores = hardware.stdout.splitlines() evidence["host"].update({"cpu": cpu, "memory_bytes": int(memory), "logical_cpus": int(cores)}) name = "highload-lab1-check-" + uuid.uuid4().hex[:12] created = False markers = [] def record(label, scenario): try: details = scenario() status = "FAIL" if isinstance(details, dict) and details.get("exit_code", 0) else "PASS" evidence["checks"].append({"name": label, "status": status, "details": details}) print(status + ":", label, flush=True) if status == "FAIL": print(details.get("output", ""), flush=True) except (Failure, OSError, ValueError, subprocess.SubprocessError) as exc: evidence["checks"].append({"name": label, "status": "FAIL", "details": str(exc)}) print("FAIL: %s: %s" % (label, exc), flush=True) try: info = json.loads(docker("info", "--format", "{{json .}}")) evidence["docker"] = {key: info.get(key) for key in ("ServerVersion", "OperatingSystem", "Architecture", "NCPU", "MemTotal")} if args.build: started = time.monotonic() # Use current contents of tracked files; omit untracked IDE/runtime files. with tempfile.TemporaryDirectory(prefix="highload-clean-build-") as directory: tracked = command(["git", "ls-files", "-z"]).stdout.split("\0") for relative in filter(None, tracked): source = ROOT / relative if source.is_file(): target = Path(directory) / relative target.parent.mkdir(parents=True, exist_ok=True) shutil.copy2(source, target) build = command(["docker", "build", "--progress=plain", "-t", args.image, directory], timeout=300, required=False) build_log = output.with_name(output.stem + "-build.txt") build_log.write_text(build.stdout + build.stderr) evidence["build"] = { "command": "docker build --progress=plain -t %s " % args.image, "context": "current tracked working files, not a committed clone", "exit_code": build.returncode, "seconds": round(time.monotonic() - started, 3), "log": str(build_log.relative_to(ROOT)), } check(build.returncode == 0, "Docker build failed; see saved build log") image = json.loads(docker("image", "inspect", args.image))[0] evidence["image"] = {"tag": args.image, "id": image["Id"], "configured_user": image["Config"].get("User"), "healthcheck": image["Config"].get("Healthcheck")} docker("run", "-d", "--name", name, "--cpus=1", "--memory=128m", "-p", "127.0.0.1::8080", "-e", "APP_HOST=0.0.0.0", "-e", "APP_PORT=8080", args.image) created = True binding = inspect(name)["NetworkSettings"]["Ports"]["8080/tcp"][0] base = "http://127.0.0.1:" + binding["HostPort"] client = Client(base, timeout=2) def ready(): try: client.call("GET", "/health/ready", schema="Health") return True except Failure: return False wait_for(ready, 15, "container did not become ready") def external(invocation, display=None): result = command(invocation, required=False) return {"command": display or " ".join(invocation), "exit_code": result.returncode, "output": (result.stdout + result.stderr).strip()} record("offline structure", lambda: external(["make", "check"])) record("public smoke", lambda: external(["make", "test", "BASE_URL=" + base])) record("own contract and 100-message tests", lambda: external( [sys.executable, "student-tests/level4.py", "--base-url", base], "python3 student-tests/level4.py --base-url " + base)) def configuration(): other = name + "-port" docker("run", "-d", "--name", other, "--cpus=1", "--memory=128m", "-p", "127.0.0.1::8091", "-e", "APP_HOST=0.0.0.0", "-e", "APP_PORT=8091", args.image) try: port = inspect(other)["NetworkSettings"]["Ports"]["8091/tcp"][0]["HostPort"] alternate = Client("http://127.0.0.1:" + port, timeout=2) def alternate_ready(): try: alternate.call("GET", "/health/ready", schema="Health") return True except Failure: return False wait_for(alternate_ready, 10, "APP_PORT=8091 did not change listening port") return {"APP_HOST": "0.0.0.0", "APP_PORT": "8091", "ready_status": 200, "note": "image healthcheck remains fixed to 8080; this tests HTTP configuration only"} finally: command(["docker", "rm", "--force", other], required=False) record("configuration from environment", configuration) def runtime(): uid = int(docker("exec", name, "id", "-u")) check(uid != 0, "runtime user is root") compiler = command(["docker", "exec", name, "which", "go"], required=False) check(compiler.returncode == 1, "Go compiler present in runtime") return {"uid": uid, "go_compiler_present": False, "app_files": docker("exec", name, "ls", "/app")} record("non-root and separate runtime", runtime) def health(): check(image["Config"].get("Healthcheck"), "image has no healthcheck") wait_for(lambda: inspect(name)["State"].get("Health", {}).get("Status") == "healthy", 35, "Docker healthcheck did not become healthy") return {"status": "healthy"} record("Docker healthcheck", health) def lifecycle(): nonlocal binding, base actor = client.user("lifecycle") chat = client.call("POST", "/api/v1/chats", 201, actor=actor, body={"title": "Lifecycle", "member_ids": [actor["id"]]}, schema="Chat")["json"] text = "private-test-marker-" + uuid.uuid4().hex markers.append(text) message = client.message(actor, chat, text)["json"] history = client.call("GET", "/api/v1/chats/" + chat["id"] + "/messages", actor=actor, schema="MessagePage")["json"] check(history["items"] == [message], "message not visible before restart") docker("restart", "--time", "10", name) binding = inspect(name)["NetworkSettings"]["Ports"]["8080/tcp"][0] base = "http://127.0.0.1:" + binding["HostPort"] client.base = base wait_for(ready, 15, "container not ready after restart") response = client.call("GET", "/api/v1/users/me", 401, actor=actor) return {"message_visible_before_restart": True, "old_user_after_restart": response["status"]} record("in-memory lifecycle", lifecycle) def shutdown(): actor = client.user("shutdown") chat = client.call("POST", "/api/v1/chats", 201, actor=actor, body={"title": "Shutdown", "member_ids": [actor["id"]]}, schema="Chat")["json"] text = "drain-test-marker-" + uuid.uuid4().hex markers.append(text) body = json.dumps({"text": text}).encode() headers = ("POST /api/v1/chats/%s/messages HTTP/1.1\r\nHost: localhost\r\n" "X-User-Id: %s\r\nContent-Type: application/json\r\nContent-Length: %d\r\n" "Connection: close\r\n\r\n" % (chat["id"], actor["id"], len(body))).encode() baseline = docker("logs", name).count("shutdown signal received") with socket.create_connection(("127.0.0.1", int(binding["HostPort"])), timeout=3) as active: active.sendall(headers + body[:-1]) time.sleep(0.2) started = time.monotonic() docker("kill", "--signal=TERM", name) wait_for(lambda: docker("logs", name).count("shutdown signal received") > baseline, 3, "SIGTERM not observed in logs") check(inspect(name)["State"]["Running"], "process exited before draining active request") rejected = 0 for _ in range(5): request = urllib.request.Request(base + "/health/live", headers={"Connection": "close"}) try: with urllib.request.urlopen(request, timeout=0.5): pass except (urllib.error.URLError, OSError): rejected += 1 check(rejected == 5, "new requests were accepted after SIGTERM") active.sendall(body[-1:]) response = b"" while True: chunk = active.recv(65536) if not chunk: break response += chunk check(response.split(b"\r\n", 1)[0].startswith(b"HTTP/1.1 201"), "active valid request did not finish with 201") wait_for(lambda: not inspect(name)["State"]["Running"], 9, "process did not stop") elapsed = time.monotonic() - started state = inspect(name)["State"] check(elapsed <= 10 and state["ExitCode"] == 0, "SIGTERM exceeded 10 seconds or exited abnormally") return {"seconds": round(elapsed, 3), "exit_code": state["ExitCode"], "new_requests_rejected": rejected, "active_request_status": 201} record("SIGTERM, new requests and active request drain", shutdown) def logging(): result = command(["docker", "logs", name]) logs = result.stdout + result.stderr check(all(marker not in logs for marker in markers), "message body found in logs") lines = logs.splitlines() request_lines = [line for line in lines if "http request" in line] check(request_lines, "no useful request logs") check(all("method=" in line and "status=" in line and "duration=" in line and "request_id=" in line and 'request_id=""' not in line for line in request_lines), "request logs lack useful fields or request IDs") check("server started" in logs and "shutdown signal received" in logs, "missing lifecycle logs") return {"request_lines": len(request_lines), "message_markers_present": False, "fields": ["method", "path", "status", "duration", "request_id"]} record("useful logs without message contents", logging) except (Failure, OSError, ValueError, subprocess.SubprocessError) as exc: evidence["checks"].append({"name": "setup", "status": "FAIL", "details": str(exc)}) print("FAIL: setup:", exc, flush=True) finally: if created: command(["docker", "rm", "--force", name], required=False) evidence["status"] = "PASS" if evidence["checks"] and all( item["status"] == "PASS" for item in evidence["checks"]) else "FAIL" output.write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n") print("SUMMARY: %s; evidence: %s" % (evidence["status"], args.output), flush=True) return 0 if evidence["status"] == "PASS" else 1 if __name__ == "__main__": raise SystemExit(main())