forked from mtusi2026/mtusi2026lab3
62 lines
2.2 KiB
Python
62 lines
2.2 KiB
Python
"""Runtime API доступен только на loopback внутри контейнера HAProxy."""
|
|
|
|
import csv
|
|
import io
|
|
import re
|
|
import subprocess
|
|
import time
|
|
|
|
from replicas import ROOT, compose, docker
|
|
|
|
|
|
def runtime(command):
|
|
container = compose("ps", "-q", "lb")
|
|
return subprocess.check_output(
|
|
["docker", "exec", "-i", container, "nc", "-w", "1", "127.0.0.1", "9999"],
|
|
input=command + "\n",
|
|
text=True,
|
|
cwd=ROOT,
|
|
timeout=5,
|
|
).strip()
|
|
|
|
|
|
def drain(container):
|
|
address = docker(
|
|
"inspect", "--format", "{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}", container
|
|
)
|
|
lines = runtime("show servers state api_pool").splitlines()
|
|
header = next(line.lstrip("# ").split() for line in lines if line.startswith("#"))
|
|
rows = [
|
|
dict(zip(header, line.split()))
|
|
for line in lines
|
|
if line and not line.startswith("#") and line != "1"
|
|
]
|
|
names = [r["srv_name"] for r in rows if r.get("srv_addr") == address]
|
|
if not names or any(re.fullmatch(r"api[0-9]+", n) is None for n in names):
|
|
raise RuntimeError("Cannot map container to HAProxy backend")
|
|
for name in names:
|
|
result = runtime("set server api_pool/" + name + " state drain")
|
|
if result:
|
|
raise RuntimeError(result)
|
|
deadline = time.monotonic() + 10
|
|
while True:
|
|
rows = list(csv.DictReader(io.StringIO(runtime("show stat").lstrip("# "))))
|
|
active = sum(
|
|
int(r["scur"]) for r in rows if r["pxname"] == "api_pool" and r["svname"] in names
|
|
)
|
|
if active == 0:
|
|
return names
|
|
if time.monotonic() > deadline:
|
|
raise RuntimeError("Backend did not drain within 10s")
|
|
time.sleep(0.2)
|
|
|
|
|
|
def release(names):
|
|
# Старый процесс уже остановлен. Слот возвращаем под контроль health checks,
|
|
# но не объявляем здоровым принудительно: новая реплика должна пройти ready.
|
|
for name in names:
|
|
for setting in ["health down", "state ready"]:
|
|
result = runtime("set server api_pool/" + name + " " + setting)
|
|
if result:
|
|
raise RuntimeError(result)
|