57 lines
1.8 KiB
Python
57 lines
1.8 KiB
Python
"""Управление только API-контейнерами текущего Compose-проекта."""
|
|
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import time
|
|
import urllib.request
|
|
from pathlib import Path
|
|
|
|
ROOT = Path(__file__).resolve().parents[1]
|
|
|
|
|
|
def docker(*args):
|
|
return subprocess.check_output(["docker", *args], cwd=ROOT, text=True).strip()
|
|
|
|
|
|
def compose(*args):
|
|
return docker("compose", "--env-file", os.environ.get("ENV_FILE", ".env"), *args)
|
|
|
|
|
|
def containers():
|
|
return compose("ps", "--all", "-q", "api").split()
|
|
|
|
|
|
def describe(container):
|
|
# Никогда не выводим Config.Env: там credentials.
|
|
return json.loads(docker("inspect", "--format", "{{json .State}}", container))
|
|
|
|
|
|
def instance_id(container):
|
|
code = "import urllib.request; r=urllib.request.urlopen('http://127.0.0.1:8080/health/ready', timeout=2); print(r.headers['X-Instance-Id'])"
|
|
return docker("exec", container, "python", "-c", code)
|
|
|
|
|
|
def wait_ready(container, timeout=60):
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
state = describe(container)
|
|
if state.get("Health", {}).get("Status") == "healthy":
|
|
return instance_id(container)
|
|
time.sleep(0.5)
|
|
raise RuntimeError("API container did not become healthy: " + container[:12])
|
|
|
|
|
|
def wait_visible(instance, timeout=30):
|
|
base = os.environ.get("BASE_URL", "http://localhost:8080").rstrip("/")
|
|
deadline = time.monotonic() + timeout
|
|
while time.monotonic() < deadline:
|
|
try:
|
|
with urllib.request.urlopen(base + "/health/ready", timeout=2) as response:
|
|
if response.headers.get("X-Instance-Id") == instance:
|
|
return
|
|
except OSError:
|
|
pass
|
|
time.sleep(0.1)
|
|
raise RuntimeError("New replica was not discovered by HAProxy")
|