Files
mtusi2026lab5-fork/scripts/deployment.py
T
2026-11-10 07:44:19 +03:00

61 lines
2.3 KiB
Python

"""Общие операции с репликами текущего Compose-проекта."""
from dataclasses import dataclass
import json
import os
from pathlib import Path
import subprocess
ROOT = Path(__file__).resolve().parents[1]
@dataclass(frozen=True)
class Replica:
"""Состояние контейнера API."""
id: str
image: str
instance_id: str
running: bool
health: str | None
class ComposeProject:
"""Работает только с выбранным Compose-проектом."""
def __init__(self) -> None:
self.command = ["docker", "compose", "--env-file", ".env"]
self.config = json.loads(self.run("config", "--format", "json"))
self.name = self.config["name"]
def docker(self, *args: str, timeout: int = 90, env=None) -> str:
"""Выполняет Docker-команду с ограничением времени."""
result = subprocess.run(
["docker", *args], cwd=ROOT, text=True, capture_output=True,
timeout=timeout, env={**os.environ, **(env or {})},
)
if result.returncode:
raise RuntimeError(result.stderr.strip() or result.stdout.strip())
return result.stdout.strip()
def run(self, *args: str, timeout: int = 90, env=None) -> str:
"""Выполняет команду Compose с текущими overrides."""
return self.docker(*self.command[1:], *args, timeout=timeout, env=env)
def replicas(self) -> list[Replica]:
"""Читает состояние API без окружения контейнеров."""
ids = self.run("ps", "--all", "--quiet", "api").splitlines()
if not ids:
return []
template = (
'{"id":{{json .Id}},"image":{{json .Image}},'
'"hostname":{{json .Config.Hostname}},"running":{{json .State.Running}},'
'"health":{{if .State.Health}}{{json .State.Health.Status}}{{else}}null{{end}}}'
)
rows = self.docker("inspect", "--format", template, *ids).splitlines()
configured = str(self.config["services"]["api"].get("environment", {}).get("INSTANCE_ID") or "").strip()
return [
Replica(row["id"], row["image"], configured or row["hostname"], row["running"], row["health"])
for row in map(json.loads, rows)
]