forked from mtusi2026/mtusi2026lab4
194 lines
9.3 KiB
Python
194 lines
9.3 KiB
Python
"""Помощники lab3 для собственных проверок: реплики, балансировщик, Docker.
|
||
|
||
Только стандартная библиотека Python. Docker вызывается прямо из Python (`docker compose ...`),
|
||
поэтому всё работает одинаково в Git Bash, PowerShell и cmd на Windows.
|
||
Вывод проверок — латиницей и кириллицей в UTF-8 (в Git Bash задан PYTHONUTF8=1).
|
||
"""
|
||
import csv
|
||
import http.client
|
||
import io
|
||
import json
|
||
import os
|
||
import subprocess
|
||
import time
|
||
import urllib.error
|
||
import urllib.request
|
||
|
||
from helpers import ROOT, check
|
||
|
||
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080").rstrip("/")
|
||
LB_STATS_URL = os.environ.get("LB_STATS_URL", "http://127.0.0.1:8404/stats;csv")
|
||
|
||
|
||
class Reply:
|
||
"""Ответ без проверок: для нагрузки во время отказа, где ошибки — ожидаемая часть замера."""
|
||
|
||
def __init__(self, status, headers, data):
|
||
self.status = status
|
||
self.headers = {name.lower(): value for name, value in headers.items()}
|
||
try:
|
||
self.json = json.loads(data.decode("utf-8")) if data else None
|
||
except ValueError:
|
||
self.json = None
|
||
|
||
@property
|
||
def instance(self):
|
||
return self.headers.get("x-instance-id")
|
||
|
||
|
||
def try_call(method, path, *, body=None, raw=None, token=None, headers=None, timeout=2.0):
|
||
"""HTTP-запрос через балансировщик. Reply или None, если соединение оборвалось / вышел timeout.
|
||
|
||
Обрыв возможен и посреди ответа (реплику убили, когда заголовки уже ушли): http.client.HTTPException.
|
||
"""
|
||
all_headers = dict(headers or {})
|
||
data = raw
|
||
if body is not None:
|
||
data = json.dumps(body, ensure_ascii=False).encode("utf-8")
|
||
if data is not None:
|
||
all_headers.setdefault("Content-Type", "application/json")
|
||
if token is not None:
|
||
all_headers["Authorization"] = "Bearer " + token
|
||
request = urllib.request.Request(BASE_URL + path, data=data, method=method, headers=all_headers)
|
||
try:
|
||
with urllib.request.urlopen(request, timeout=timeout) as reply:
|
||
return Reply(reply.status, reply.headers, reply.read())
|
||
except urllib.error.HTTPError as error:
|
||
try:
|
||
return Reply(error.code, error.headers, error.read())
|
||
except (OSError, http.client.HTTPException):
|
||
return None
|
||
except (urllib.error.URLError, OSError, http.client.HTTPException):
|
||
return None
|
||
|
||
|
||
# ---------- Docker ----------
|
||
|
||
def docker(*args, check_exit=True):
|
||
"""docker <args>; возвращает stdout."""
|
||
result = subprocess.run(["docker", *args], cwd=ROOT, capture_output=True, check=check_exit)
|
||
return result.stdout.decode("utf-8", "replace").strip()
|
||
|
||
|
||
def compose_output(*args, env=None):
|
||
"""docker compose <args> и его вывод (stdout + stderr). Секретов в нём нет: ps, logs, build."""
|
||
result = subprocess.run(["docker", "compose", *args], cwd=ROOT, capture_output=True, check=True, env=env)
|
||
return result.stdout.decode("utf-8", "replace") + result.stderr.decode("utf-8", "replace")
|
||
|
||
|
||
def compose_config():
|
||
"""Итоговая конфигурация стенда (docker compose config) как словарь: только stdout, без предупреждений."""
|
||
result = subprocess.run(["docker", "compose", "config", "--format", "json"], cwd=ROOT,
|
||
capture_output=True, check=True)
|
||
return json.loads(result.stdout.decode("utf-8"))
|
||
|
||
|
||
def compose_quiet(*args, env=None):
|
||
subprocess.run(["docker", "compose", *args], cwd=ROOT, check=True, env=env,
|
||
stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
|
||
|
||
|
||
def api_containers(include_stopped=False):
|
||
"""Полные ID контейнеров сервиса api (по умолчанию только запущенные), по порядку."""
|
||
args = ["ps", "-q", "-a", "api"] if include_stopped else ["ps", "-q", "api"]
|
||
return sorted(compose_output(*args).split())
|
||
|
||
|
||
def inspect(container, template):
|
||
return docker("inspect", "-f", template, container, check_exit=False)
|
||
|
||
|
||
def health(container):
|
||
"""Статус Docker healthcheck: starting / healthy / unhealthy / ''."""
|
||
return inspect(container, "{{if .State.Health}}{{.State.Health.Status}}{{end}}")
|
||
|
||
|
||
def ps_table():
|
||
"""Все контейнеры стенда: сервис, короткий ID (= X-Instance-Id у api), состояние, время старта."""
|
||
lines = []
|
||
for container in sorted(compose_output("ps", "-a", "-q").split()):
|
||
info = inspect(container, '{{index .Config.Labels "com.docker.compose.service"}}|{{.State.Status}}|'
|
||
'{{.State.StartedAt}}|{{if .State.Health}}{{.State.Health.Status}}{{end}}')
|
||
service, status, started, healthy = (info.split("|") + ["", "", "", ""])[:4]
|
||
shown = f"{status} ({healthy})" if healthy and status == "running" else status
|
||
lines.append((service, container[:12], shown, started[:23]))
|
||
lines.sort()
|
||
width = max((len(service) for service, *_ in lines), default=7)
|
||
text = [f"{'SERVICE':<{width}} CONTAINER STATE STARTED AT (UTC)"]
|
||
text += [f"{service:<{width}} {cid} {state:<19} {started}" for service, cid, state, started in lines]
|
||
return "\n".join(text)
|
||
|
||
|
||
# ---------- балансировщик ----------
|
||
|
||
def lb_rows(backend="api"):
|
||
"""Строки статистики HAProxy (CSV) по серверам backend: имя, статус, backup-флаг, результат проверки."""
|
||
with urllib.request.urlopen(LB_STATS_URL, timeout=2) as reply:
|
||
rows = list(csv.reader(io.StringIO(reply.read().decode("utf-8", "replace"))))
|
||
header = [name.lstrip("# ") for name in rows[0]]
|
||
items = [dict(zip(header, row)) for row in rows[1:]]
|
||
return [item for item in items
|
||
if item.get("pxname") == backend and item.get("svname") not in ("FRONTEND", "BACKEND")]
|
||
|
||
|
||
def lb_servers(backend="api"):
|
||
"""Слоты backend в HAProxy: {имя: статус}, например {'api1': 'UP'}."""
|
||
return {item["svname"]: item.get("status", "") for item in lb_rows(backend)}
|
||
|
||
|
||
def lb_up_count():
|
||
"""Сколько реплик (слоты api1..api6) HAProxy держит в балансировке (UP)."""
|
||
return sum(1 for name, status in lb_servers().items() if name.startswith("api") and status.startswith("UP"))
|
||
|
||
|
||
def lb_summary():
|
||
"""Короткая строка состояния основных слотов: 'api1 UP, api2 DOWN' (пустые слоты MAINT не показываем)."""
|
||
servers = lb_servers()
|
||
shown = [f"{name} {status}" for name, status in sorted(servers.items())
|
||
if name.startswith("api") and not status.startswith("MAINT")]
|
||
return ", ".join(shown) or "no api servers"
|
||
|
||
|
||
def wait_balanced(replicas, seconds=90):
|
||
"""Ждёт, пока replicas контейнеров api healthy и HAProxy держит их в балансировке (UP)."""
|
||
deadline = time.monotonic() + seconds
|
||
while True:
|
||
running = api_containers()
|
||
healthy = [container for container in running if health(container) == "healthy"]
|
||
try:
|
||
up = lb_up_count()
|
||
except OSError:
|
||
up = 0
|
||
if len(healthy) >= replicas and up >= replicas:
|
||
return running
|
||
check(time.monotonic() < deadline,
|
||
f"after {seconds} s: {len(healthy)} healthy api containers, {up} UP in HAProxy, need {replicas}")
|
||
time.sleep(0.5)
|
||
|
||
|
||
def replica_status(container, path):
|
||
"""Код ответа реплики на GET path изнутри её контейнера, в обход балансировщика.
|
||
|
||
Так видно состояние самой реплики (жива ли, готова ли), когда балансировщик её уже исключил.
|
||
Одна строка без переводов строк: так команда одинаково передаётся и на Windows, и на Linux.
|
||
"""
|
||
code = ("import http.client as h; c = h.HTTPConnection('127.0.0.1', 8080, timeout=5); "
|
||
f"c.request('GET', '{path}'); print(c.getresponse().status)")
|
||
return int(docker("exec", container, "python", "-c", code))
|
||
|
||
|
||
def valkey_stats():
|
||
"""keyspace_hits и keyspace_misses Valkey (пользователь health без пароля: только info/ping/dbsize)."""
|
||
output = compose_output("exec", "-T", "valkey", "valkey-cli", "--user", "health", "--pass", "none",
|
||
"--no-auth-warning", "info", "stats")
|
||
stats = dict(line.strip().split(":", 1) for line in output.splitlines() if line.startswith("keyspace_"))
|
||
return int(stats["keyspace_hits"]), int(stats["keyspace_misses"])
|
||
|
||
|
||
if __name__ == "__main__":
|
||
# make restore: после `docker compose up -d --wait` дождаться, пока HAProxy вернёт в работу
|
||
# ВСЕ запущенные реплики (DNS + 2 удачные проверки готовности — ещё несколько секунд).
|
||
replicas = len(api_containers())
|
||
wait_balanced(replicas)
|
||
print(f"all {replicas} api replicas are healthy and UP in HAProxy: {lb_summary()}")
|