246 lines
8.6 KiB
Python
246 lines
8.6 KiB
Python
"""Docker/admin helpers for lab5 failure probes (host-side, no secrets printed).
|
|
|
|
Requires the deployed Swarm stack and a Docker socket. All commands operate only
|
|
on services named ${STACK_NAME}_*; object listings use MinIO's own mc with the
|
|
read-only root credentials already mounted in the container, and never print them.
|
|
"""
|
|
from __future__ import annotations
|
|
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
TESTS = ROOT / "tests"
|
|
for candidate in (str(TESTS), str(Path(__file__).resolve().parent)):
|
|
if candidate not in sys.path:
|
|
sys.path.insert(0, candidate)
|
|
|
|
from client import Client, Failure # noqa: E402
|
|
|
|
STACK = os.environ.get("STACK_NAME", "lab5")
|
|
BASE_URL = os.environ.get("BASE_URL", "http://127.0.0.1:8080")
|
|
BUCKET = os.environ.get("S3_BUCKET", "messenger-attachments")
|
|
|
|
|
|
class ProbeError(RuntimeError):
|
|
pass
|
|
|
|
|
|
def run(args: list[str], *, check: bool = True, timeout: float = 120.0) -> subprocess.CompletedProcess:
|
|
result = subprocess.run(args, capture_output=True, text=True, encoding="utf-8", errors="replace", timeout=timeout)
|
|
if check and result.returncode != 0:
|
|
raise ProbeError("%s failed: %s" % (" ".join(args[:4]), (result.stderr or result.stdout).strip()[:500]))
|
|
return result
|
|
|
|
|
|
def docker(*args: str, check: bool = True, timeout: float = 120.0) -> str:
|
|
return run(["docker", *args], check=check, timeout=timeout).stdout.strip()
|
|
|
|
|
|
def api_container() -> str:
|
|
value = docker("ps", "-q", "-f", "name=%s_api" % STACK, "-f", "status=running")
|
|
containers = [line for line in value.splitlines() if line.strip()]
|
|
if not containers:
|
|
raise ProbeError("no running %s_api container" % STACK)
|
|
return containers[0]
|
|
|
|
|
|
def admin_json(*args: str) -> dict:
|
|
output = docker("exec", api_container(), "python", "-m", "messenger.admin", *args, timeout=120)
|
|
return json.loads(output)
|
|
|
|
|
|
def upload(api: Client, actor: dict, chat: dict, content: bytes, filename: str = "probe.png") -> dict:
|
|
from urllib.parse import quote
|
|
|
|
return api.call(
|
|
"POST",
|
|
"/api/v1/chats/%s/attachments?filename=%s" % (chat["id"], quote(filename, safe="")),
|
|
202,
|
|
actor=actor,
|
|
raw=content,
|
|
headers={"Content-Type": "image/png"},
|
|
schema="Attachment",
|
|
)["json"]
|
|
|
|
|
|
def wait_attachment(api: Client, actor: dict, attachment_id: str, status: str, timeout: float = 90.0) -> dict:
|
|
deadline = time.monotonic() + timeout
|
|
last = None
|
|
while time.monotonic() < deadline:
|
|
last = api.call("GET", "/api/v1/attachments/" + attachment_id, actor=actor, schema="Attachment")["json"]
|
|
if last["status"] == status:
|
|
return last
|
|
if last["status"] == "failed" and status != "failed":
|
|
raise ProbeError("attachment failed with %s while waiting for %s" % (last["error_code"], status))
|
|
time.sleep(0.25)
|
|
raise ProbeError("attachment did not reach %s: %s" % (status, last))
|
|
|
|
|
|
def wait_job(api: Client, actor: dict, attachment_id: str, state: str, timeout: float = 90.0) -> dict:
|
|
deadline = time.monotonic() + timeout
|
|
last = None
|
|
while time.monotonic() < deadline:
|
|
report = admin_json("show", "--attachment", attachment_id)
|
|
states = [job["state"] for job in report.get("jobs", [])]
|
|
if state in states:
|
|
return report
|
|
last = states
|
|
time.sleep(0.25)
|
|
raise ProbeError("job did not reach %s: %s" % (state, last))
|
|
|
|
|
|
def scale(service: str, replicas: int) -> None:
|
|
docker("service", "scale", "%s_%s=%d" % (STACK, service, replicas), timeout=180)
|
|
|
|
|
|
def wait_service(service: str, replicas: int, timeout: float = 180.0) -> None:
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
tasks = docker(
|
|
"service", "ps", "-q", "%s_%s" % (STACK, service), "--filter", "desired-state=running"
|
|
)
|
|
if len([line for line in tasks.splitlines() if line.strip()]) >= replicas:
|
|
return
|
|
time.sleep(1.0)
|
|
raise ProbeError("%s did not reach %d running tasks" % (service, replicas))
|
|
|
|
|
|
def restart(service: str, timeout: float = 240.0) -> None:
|
|
docker("service", "update", "--force", "%s_%s" % (STACK, service), timeout=timeout)
|
|
|
|
|
|
def minio_container() -> str:
|
|
value = docker("ps", "-q", "-f", "name=%s_minio" % STACK, "-f", "status=running")
|
|
containers = [line for line in value.splitlines() if line.strip()]
|
|
if not containers:
|
|
raise ProbeError("minio container not found")
|
|
return containers[0]
|
|
|
|
|
|
def rabbitmq_container() -> str:
|
|
value = docker("ps", "-q", "-f", "name=%s_rabbitmq" % STACK, "-f", "status=running")
|
|
containers = [line for line in value.splitlines() if line.strip()]
|
|
if not containers:
|
|
raise ProbeError("rabbitmq container not found")
|
|
return containers[0]
|
|
|
|
|
|
def list_objects(prefix: str) -> list[str]:
|
|
"""Ключи S3 через admin CLI внутри API (без печати credentials)."""
|
|
items = admin_json("objects", "--prefix", prefix)
|
|
return [item["key"] for item in items]
|
|
|
|
|
|
def wait_queue_messages(queue: str, minimum: int, timeout: float = 60.0) -> dict:
|
|
deadline = time.monotonic() + timeout
|
|
stats = {}
|
|
while time.monotonic() < deadline:
|
|
stats = queue_stats()
|
|
if stats.get(queue, {}).get("messages", 0) >= minimum:
|
|
return stats
|
|
time.sleep(0.5)
|
|
raise ProbeError("queue %s did not reach %d messages: %s" % (queue, minimum, stats))
|
|
|
|
|
|
def queue_stats() -> dict:
|
|
output = docker(
|
|
"exec", rabbitmq_container(), "rabbitmqctl", "list_queues", "name", "messages", "messages_ready", "messages_unacknowledged"
|
|
)
|
|
stats = {}
|
|
for line in output.splitlines():
|
|
parts = line.split()
|
|
if len(parts) >= 4 and parts[0] not in ("name", "Timeout:"):
|
|
try:
|
|
stats[parts[0]] = {
|
|
"messages": int(parts[1]),
|
|
"ready": int(parts[2]),
|
|
"unacknowledged": int(parts[3]),
|
|
}
|
|
except ValueError:
|
|
continue
|
|
return stats
|
|
|
|
|
|
def worker_container_for(hostname: str) -> str | None:
|
|
containers = [
|
|
line for line in docker("ps", "-q", "-f", "name=%s_worker" % STACK).splitlines() if line.strip()
|
|
]
|
|
for container in containers:
|
|
value = docker("inspect", "-f", "{{.Config.Hostname}}", container, check=False)
|
|
if value.strip() == hostname:
|
|
return container
|
|
return None
|
|
|
|
|
|
def pause_container(container: str) -> None:
|
|
run(["docker", "kill", "--signal=STOP", container], check=False)
|
|
|
|
|
|
def resume_container(container: str) -> None:
|
|
# Swarm мог заменить task, пока контейнер был остановлен; это не ошибка пробы.
|
|
run(["docker", "kill", "--signal=CONT", container], check=False)
|
|
|
|
|
|
def wait_ready(timeout: float = 180.0) -> None:
|
|
api = Client(BASE_URL, None, 5)
|
|
deadline = time.monotonic() + timeout
|
|
last = "not attempted"
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
api.call("GET", "/health/ready", schema="Health")
|
|
return
|
|
except (Failure, OSError) as exc:
|
|
last = str(exc)
|
|
time.sleep(0.5)
|
|
raise ProbeError("stand did not become ready: %s" % last)
|
|
|
|
|
|
def wait_broker(timeout: float = 180.0) -> None:
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
result = run(
|
|
["docker", "exec", rabbitmq_container(), "rabbitmqctl", "status"],
|
|
check=False,
|
|
timeout=20,
|
|
)
|
|
if result.returncode == 0:
|
|
return
|
|
time.sleep(1.0)
|
|
raise ProbeError("rabbitmq did not become ready")
|
|
|
|
|
|
def service_logs(service: str, since: str = "20m") -> list[dict]:
|
|
"""JSON-логи всех task-контейнеров сервиса (включая завершившиеся crash-и)."""
|
|
containers = [
|
|
line
|
|
for line in docker(
|
|
"ps", "-a", "-q", "-f", "name=%s_%s" % (STACK, service), check=False
|
|
).splitlines()
|
|
if line.strip()
|
|
]
|
|
events = []
|
|
for container in containers:
|
|
output = run(
|
|
["docker", "logs", "--since", since, container],
|
|
check=False,
|
|
timeout=120,
|
|
)
|
|
for line in (output.stdout + "\n" + output.stderr).splitlines():
|
|
line = line.strip()
|
|
if not line.startswith("{"):
|
|
continue
|
|
try:
|
|
events.append(json.loads(line))
|
|
except ValueError:
|
|
continue
|
|
return events
|
|
|
|
|
|
def client(timeout: float = 15.0) -> Client:
|
|
return Client(BASE_URL, None, timeout)
|