forked from mtusi2026/mtusi2026lab3
95 lines
3.7 KiB
Python
95 lines
3.7 KiB
Python
"""Docker operations scoped to the configured local Compose project."""
|
|
import csv
|
|
import io
|
|
import json
|
|
import os
|
|
from pathlib import Path
|
|
import socket
|
|
import subprocess
|
|
import time
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def command(args, timeout=120, env=None):
|
|
result = subprocess.run(args, cwd=ROOT, capture_output=True, text=True,
|
|
encoding="utf-8", errors="replace", timeout=timeout, env=env)
|
|
if result.returncode:
|
|
# Commands and stderr can contain secrets. Keep detailed errors local.
|
|
raise RuntimeError("Local command failed: " + " ".join(args[:3]) + "\n" + result.stderr[-1500:])
|
|
return result.stdout.strip()
|
|
|
|
|
|
def compose(*args, timeout=120, env=None):
|
|
return command(["docker", "compose", "--env-file", ".env", *args], timeout, env)
|
|
|
|
|
|
def project():
|
|
return os.getenv("COMPOSE_PROJECT_NAME") or json.loads(compose("config", "--format", "json"))["name"]
|
|
|
|
|
|
def containers(service="api", running=True):
|
|
args = ["docker", "ps"] + ([] if running else ["-a"])
|
|
ids = command(args + ["--filter", "label=com.docker.compose.project=" + project(),
|
|
"--filter", "label=com.docker.compose.service=" + service,
|
|
"--filter", "label=com.docker.compose.oneoff=False", "--format", "{{.ID}}"])
|
|
return json.loads(command(["docker", "inspect", *ids.split()])) if ids else []
|
|
|
|
|
|
def summary():
|
|
result = []
|
|
for service in ("api", "postgres", "redis", "lb"):
|
|
for row in containers(service, running=False):
|
|
result.append({"service": service, "id": row["Id"], "name": row["Name"].lstrip("/"),
|
|
"started_at": row["State"]["StartedAt"], "status": row["State"]["Status"],
|
|
"image": row["Image"], "user": row["Config"]["User"],
|
|
"memory_bytes": row["HostConfig"]["Memory"], "nano_cpus": row["HostConfig"]["NanoCpus"],
|
|
"published_ports": row["HostConfig"]["PortBindings"],
|
|
"volumes": [m["Name"] for m in row["Mounts"] if m["Type"] == "volume"]})
|
|
return result
|
|
|
|
|
|
def runtime(line):
|
|
with socket.create_connection(("lb", 9999), timeout=3) as sock:
|
|
sock.sendall((line + "\n").encode())
|
|
sock.shutdown(socket.SHUT_WR)
|
|
chunks = []
|
|
while True:
|
|
data = sock.recv(65536)
|
|
if not data:
|
|
return b"".join(chunks).decode()
|
|
chunks.append(data)
|
|
|
|
|
|
def drain(address):
|
|
lines = runtime("show servers state messenger").splitlines()
|
|
fields = next(line[2:].split() for line in lines if line.startswith("# "))
|
|
for line in lines:
|
|
values = line.split()
|
|
if not values or line.startswith("#") or len(values) != len(fields):
|
|
continue
|
|
row = dict(zip(fields, values))
|
|
if row["srv_addr"] == address:
|
|
slot = "messenger/" + row["srv_name"]
|
|
runtime("set server " + slot + " state drain")
|
|
# Let requests already assigned to this replica finish (HTTP budget 5 s).
|
|
deadline = time.monotonic() + 7
|
|
while time.monotonic() < deadline:
|
|
stats = list(csv.DictReader(io.StringIO(runtime("show stat").lstrip("# "))))
|
|
active = [s for s in stats if s["pxname"] == "messenger" and s["svname"] == row["srv_name"]]
|
|
if active and int(active[0]["scur"]) == 0:
|
|
return slot
|
|
time.sleep(.1)
|
|
raise RuntimeError("Replica did not drain within 7 seconds")
|
|
raise RuntimeError("Backend address was not found in HAProxy")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
import sys
|
|
if sys.argv[1] == "drain":
|
|
print(drain(sys.argv[2]))
|
|
elif sys.argv[1] == "ready":
|
|
runtime("set server " + sys.argv[2] + " state ready")
|
|
elif sys.argv[1] == "summary":
|
|
print(json.dumps(summary(), indent=2))
|