7 — Т2302 — ебедев — на 5
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
"""Общие функции операторских скриптов lab7 (stdlib, Python 3.9+, Linux/macOS/Windows).
|
||||
Команды Docker Compose берутся из COMPOSE (по умолчанию `docker compose --env-file .env`)."""
|
||||
import json
|
||||
import os
|
||||
import shlex
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
DC = shlex.split(os.environ.get("COMPOSE", "docker compose --env-file .env"))
|
||||
|
||||
|
||||
def dc(*args, input=None, check=True, timeout=180, capture=True):
|
||||
"""docker compose …; секреты передаются только через stdin (input), не через argv."""
|
||||
r = subprocess.run(DC + list(args), cwd=ROOT, input=input, capture_output=capture, text=True, timeout=timeout)
|
||||
if check and r.returncode != 0:
|
||||
raise RuntimeError("docker compose %s → %d: %s" % (args[0], r.returncode, (r.stderr or "")[-400:]))
|
||||
return r
|
||||
|
||||
|
||||
def ops_exec(*args, input=None, check=True, timeout=180):
|
||||
"""Команда в контейнере ops (профиль tools; поднимается при необходимости)."""
|
||||
if not dc("--profile", "tools", "ps", "-q", "ops", check=False).stdout.strip():
|
||||
dc("--profile", "tools", "up", "-d", "ops")
|
||||
return dc("--profile", "tools", "exec", "-T", "ops", *args, input=input, check=check, timeout=timeout)
|
||||
|
||||
|
||||
def psql(sql, *, fetch=True):
|
||||
"""SQL суперпользователя postgres через unix-socket внутри контейнера (peer). Текст — через stdin."""
|
||||
r = dc("exec", "-T", "-u", "postgres", "postgres", "psql", "-X", "-q", "-At", "-v", "ON_ERROR_STOP=1",
|
||||
"-d", "messenger", input=sql)
|
||||
return [line for line in r.stdout.splitlines() if line] if fetch else None
|
||||
|
||||
|
||||
def reload_trust(services=None):
|
||||
"""Перечитать CRL/сертификаты/pinned_certs у всех потребителей (без рестарта и пересборки):
|
||||
HAProxy (lb, шлюзы) — seamless reload SIGUSR2; NATS — SIGHUP (закрывает соединения с исключёнными
|
||||
сертификатами); PostgreSQL — pg_reload_conf (ssl_* и CRL); OpenBao — SIGHUP (сертификат listener);
|
||||
API — сам перечитывает CRL/сертификат каждые 2 с; SeaweedFS — сам перечитывает сертификат."""
|
||||
done = []
|
||||
for svc in services or ("lb", "otel-gw", "prometheus-gw", "loki-gw", "tempo-gw"):
|
||||
if dc("kill", "-s", "USR2", svc, check=False).returncode == 0:
|
||||
done.append(svc + ":USR2")
|
||||
if services is None or "nats" in services:
|
||||
dc("kill", "-s", "HUP", "nats", check=False)
|
||||
done.append("nats:HUP")
|
||||
if services is None or "postgres" in services:
|
||||
dc("exec", "-T", "postgres", "sh", "-c", "install -m 600 /run/tls/self/tls.key /tmp/pgtls/tls.key", check=False)
|
||||
psql("SELECT pg_reload_conf();")
|
||||
done.append("postgres:reload")
|
||||
if services is None or "openbao" in services:
|
||||
dc("kill", "-s", "HUP", "openbao", check=False)
|
||||
done.append("openbao:HUP")
|
||||
return done
|
||||
|
||||
|
||||
def bao():
|
||||
sys.path.insert(0, str(ROOT / "scripts"))
|
||||
import bao_admin # noqa: E402
|
||||
return bao_admin
|
||||
|
||||
|
||||
def now():
|
||||
return time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime())
|
||||
|
||||
|
||||
def out(obj):
|
||||
print(json.dumps(obj, ensure_ascii=False, indent=1))
|
||||
Reference in New Issue
Block a user