forked from mtusi2026/mtusi2026lab5
84 lines
2.5 KiB
Python
84 lines
2.5 KiB
Python
"""Явные операторские действия только над API текущего Compose-проекта."""
|
|
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import time
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def command(*args):
|
|
return subprocess.check_output(args, cwd=ROOT, text=True).strip()
|
|
|
|
|
|
def containers():
|
|
ids = command("docker", "compose", "ps", "-q", "api").split()
|
|
return json.loads(command("docker", "inspect", *ids)) if ids else []
|
|
|
|
|
|
def alias(cid):
|
|
code = (
|
|
"import urllib.request; r=urllib.request.urlopen("
|
|
"'http://127.0.0.1:8080/health/live',timeout=2); "
|
|
"print(r.headers['X-Instance-Id'])"
|
|
)
|
|
return command("docker", "exec", cid, "python", "-c", code)
|
|
|
|
|
|
def wait_count(count):
|
|
deadline = time.monotonic() + 60
|
|
while time.monotonic() < deadline:
|
|
data = containers()
|
|
if len(data) == count and all(
|
|
c["State"].get("Health", {}).get("Status") == "healthy"
|
|
for c in data
|
|
):
|
|
# DNS и проверки HAProxy должны успеть увидеть новый адрес.
|
|
time.sleep(3)
|
|
return
|
|
time.sleep(0.5)
|
|
raise TimeoutError("Replica readiness")
|
|
|
|
|
|
def main():
|
|
action = sys.argv[1]
|
|
data = containers()
|
|
if action == "stop":
|
|
target = os.environ["TARGET_INSTANCE_ID"]
|
|
matches = [c for c in data if alias(c["Id"]) == target]
|
|
if len(matches) != 1 or len(data) < 2:
|
|
raise RuntimeError("Target must identify one running replica")
|
|
command("docker", "stop", "--time", "10", matches[0]["Id"])
|
|
print("Selected API stopped")
|
|
elif action == "rolling":
|
|
count = len(data)
|
|
if count < 2:
|
|
raise RuntimeError("Need at least two replicas")
|
|
# Сначала добавляется готовая реплика, затем удаляется одна старая.
|
|
for old in data:
|
|
command(
|
|
"docker",
|
|
"compose",
|
|
"up",
|
|
"-d",
|
|
"--no-deps",
|
|
"--no-recreate",
|
|
"--scale",
|
|
f"api={count + 1}",
|
|
"api",
|
|
)
|
|
wait_count(count + 1)
|
|
command("docker", "stop", "--time", "10", old["Id"])
|
|
command("docker", "rm", old["Id"])
|
|
wait_count(count)
|
|
print("Sequential replacement completed")
|
|
else:
|
|
raise ValueError("Unknown action")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|