forked from mtusi2026/mtusi2026lab7
feat: run a per-run OpenBao for failure checks, bench, CI and driver stands
Every stand with its own storages now brings up its own OpenBao and acts
as its operator: materials live in the run's temporary directory and are
removed on any outcome; the working stand's OpenBao is never touched.
- make failure_checks: own OpenBao, 20 s / 60 s token roles, six new
OpenBao fault checks, hook actions and the secrets log summary
- bao.py rewrite and waiting for the active node after unseal
- bench/: OpenBao in every fresh stand, "before" variants get secrets
via ${...} references, passport stand.secrets and limits.openbao
- CI job: BAO_ADDRESS, run OpenBao operator, override with openbao,
cleaner and migrate pairs, test_ci_override.py
- driver: shared temporary stand for freeze-lb and reconcile-signal
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
@@ -78,6 +78,25 @@ services:
|
||||
memory: ${BENCH_S3_MEMORY:?run make bench}
|
||||
memswap_limit: ${BENCH_S3_MEMORY:?run make bench}
|
||||
|
||||
# OpenBao прогона (change openbao-tooling, design, решение 6): тот же сервис
|
||||
# основного файла (образ, config.hcl, слушатель mTLS, healthcheck,
|
||||
# cap_drop) в каждом свежем стенде рабочих профилей; init, unseal, сведение
|
||||
# и наполнение паролями прогона делает run.py (bao.py ready) до
|
||||
# postgres-bootstrap и миграций. Порт основного файла —
|
||||
# 127.0.0.1:${BAO_OUT_PORT} (свободный порт метки из окружения run.py) —
|
||||
# единственный порт стенда на хосте и только для оркестратора; volume
|
||||
# основного файла уходит с down -v проекта. Лимиты — рабочего стенда, без
|
||||
# swap и без перезапуска
|
||||
openbao:
|
||||
container_name: mtusi-bench-openbao
|
||||
restart: "no"
|
||||
deploy:
|
||||
resources:
|
||||
limits:
|
||||
cpus: ${BENCH_BAO_CPUS:?run make bench}
|
||||
memory: ${BENCH_BAO_MEMORY:?run make bench}
|
||||
memswap_limit: ${BENCH_BAO_MEMORY:?run make bench}
|
||||
|
||||
# уборщик незавершённых загрузок (design change upload-consistency,
|
||||
# решение 9) описан, как s3; сервис не запускается: старт стенда
|
||||
# перечисляет сервисы, реплики — с --no-deps. Профиль сверки (change
|
||||
|
||||
+215
-18
@@ -33,6 +33,7 @@ import re
|
||||
import secrets
|
||||
import shutil
|
||||
import signal
|
||||
import socket
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
@@ -161,6 +162,31 @@ K6_CA_DIR = "/pki"
|
||||
K6_CA_FILE = f"{K6_CA_DIR}/ca.crt"
|
||||
# каталог файлов стенда PKI прогона: задаёт main() до первого вызова compose
|
||||
PKI_RUN: dict[str, str] = {"stand": ""}
|
||||
# OpenBao прогона (change openbao-tooling, design, решение 6): свободный порт
|
||||
# на 127.0.0.1 (один на метку) и каталог материалов оператора внутри каталога
|
||||
# PKI прогона — задаёт main() рядом с PKI_RUN
|
||||
BAO_RUN: dict[str, str] = {"port": "", "operator_dir": "", "run_dir": ""}
|
||||
BAO_SCRIPT = ROOT / "infra" / "openbao" / "bao.py"
|
||||
BAO_CONTAINER = "mtusi-bench-openbao"
|
||||
WORKING_OPERATOR_DIR = Path.home() / ".config" / "mtusi-lab7" / "operator"
|
||||
# паспорт: источник секретов процессов стенда (сроки ролей — умолчания
|
||||
# bao.py: ячейка короче срока токена, продлений в окнах замера нет)
|
||||
STAND_SECRETS = {
|
||||
"store": "openbao (per-run)",
|
||||
"auth": "cert",
|
||||
"token_ttl_s": 600,
|
||||
"token_max_ttl_s": 3600,
|
||||
"operator": "per-run temporary directory",
|
||||
}
|
||||
# варианты «до» (8bca554 загрузок, 56ccb79 входа — код до перехода на
|
||||
# OpenBao): секреты окружением реплики, как давал compose 34fac19 — в
|
||||
# override варианта только ссылки на переменные окружения прогона
|
||||
BEFORE_SECRET_ENV = {
|
||||
"DATABASE__PASSWORD": "${POSTGRES_API_PASSWORD}",
|
||||
"CACHE__PASSWORD": "${VALKEY_PASSWORD}",
|
||||
"S3__ACCESS_KEY_ID": "${S3_API_ACCESS_KEY}",
|
||||
"S3__SECRET_ACCESS_KEY": "${S3_API_SECRET_KEY}",
|
||||
}
|
||||
# CA прогона в контейнере сэмплера: psql к PostgreSQL стенда — только TLS с
|
||||
# проверкой сервера (sslmode=verify-full в bench/sampler.sh, change
|
||||
# storage-tls)
|
||||
@@ -661,6 +687,10 @@ class Profile:
|
||||
# профиль сверки (design change track2-reconcile-cost, решение 1)
|
||||
cleaner_cpus: str = "0.25"
|
||||
cleaner_memory: str = "256m"
|
||||
# OpenBao прогона (change openbao-tooling, design, решение 6): лимиты
|
||||
# рабочего стенда без swap — в каждом свежем стенде рабочих профилей
|
||||
bao_cpus: str = "0.25"
|
||||
bao_memory: str = "256m"
|
||||
# профиль сверки (design change track2-reconcile-cost, решения 1–3,
|
||||
# 7–10): этапы — (имя, свежий стенд, объектов всего, размер объекта,
|
||||
# ячейки bench/reconcile.py CELLS); отказ по пределу — commit образа
|
||||
@@ -997,6 +1027,8 @@ def queue_budget(
|
||||
profile.worker_cpus,
|
||||
profile.cleaner_cpus,
|
||||
profile.sampler_cpus,
|
||||
# OpenBao прогона (change openbao-tooling, design, решение 6)
|
||||
profile.bao_cpus,
|
||||
)
|
||||
)
|
||||
mem = profile.replicas * size_bytes(profile.memory) + sum(
|
||||
@@ -1012,6 +1044,7 @@ def queue_budget(
|
||||
profile.worker_memory,
|
||||
profile.cleaner_memory,
|
||||
profile.sampler_memory,
|
||||
profile.bao_memory,
|
||||
)
|
||||
)
|
||||
if profile.telemetry_on:
|
||||
@@ -2344,6 +2377,11 @@ def compose_env(profile: Profile) -> dict[str, str]:
|
||||
# TLS-шлюзы хранилищ (change telemetry-backends-tls, design, решение 11)
|
||||
"BENCH_STORAGE_GATEWAY_CPUS": profile.storage_gateway_cpus,
|
||||
"BENCH_STORAGE_GATEWAY_MEMORY": profile.storage_gateway_memory,
|
||||
# OpenBao прогона (change openbao-tooling, design, решение 6): лимиты
|
||||
# и свободный порт на 127.0.0.1 — только для оркестратора
|
||||
"BENCH_BAO_CPUS": profile.bao_cpus,
|
||||
"BENCH_BAO_MEMORY": profile.bao_memory,
|
||||
**({"BAO_OUT_PORT": BAO_RUN["port"]} if BAO_RUN["port"] else {}),
|
||||
}
|
||||
|
||||
|
||||
@@ -2393,6 +2431,8 @@ class Stand:
|
||||
self.label_dir = label_dir
|
||||
self.work_dir = label_dir / ".work"
|
||||
self.env = compose_env(profile)
|
||||
# время bao.py ready последнего свежего стенда (init на пустом volume)
|
||||
self.bao_ready_seconds: float | None = None
|
||||
# профиль uploads: override окружения реплики по варианту
|
||||
self.extra_files: list[Path] = []
|
||||
# включённая телеметрия (design change track1-telemetry-cost, решения
|
||||
@@ -2506,6 +2546,67 @@ class Stand:
|
||||
)
|
||||
return sh("docker", "image", "inspect", "-f", "{{.Id}}", FROM_IMAGE)
|
||||
|
||||
def before_variant(self) -> bool:
|
||||
"""У профиля есть вариант «до» — образ кода до перехода на OpenBao
|
||||
(загрузки `8bca554`, вход `56ccb79`)."""
|
||||
return bool(
|
||||
(self.profile.is_uploads and self.profile.uploads_before)
|
||||
or (self.profile.is_login and self.profile.login_before),
|
||||
)
|
||||
|
||||
def start_openbao(self, say: Callable[[str], None]) -> None:
|
||||
"""OpenBao прогона (change openbao-tooling, design, решение 6):
|
||||
`up -d openbao`, удаление материалов прежнего свежего стенда (сверка
|
||||
каталога — внутри каталога PKI прогона), затем `bao.py ready` —
|
||||
init, unseal, сведение и наполнение паролями прогона из модели
|
||||
compose стенда (те же файлы и проект — переменными `COMPOSE_*` только
|
||||
в окружении подпроцесса). Код ≠ 0 — `BenchError` с причиной."""
|
||||
self.compose("up", "-d", "--no-deps", "openbao")
|
||||
operator_dir = Path(BAO_RUN["operator_dir"])
|
||||
problem = operator_dir_problem(operator_dir, Path(BAO_RUN["run_dir"]))
|
||||
if problem:
|
||||
raise BenchError(problem)
|
||||
# volume нового свежего стенда пуст: материалы прежнего init не нужны
|
||||
# (init перенёс бы их в stale-<UTC>/ внутри того же каталога)
|
||||
shutil.rmtree(operator_dir, ignore_errors=True)
|
||||
files = [*COMPOSE_FILES, *self.telemetry_files, *self.extra_files]
|
||||
env = {
|
||||
**self.env,
|
||||
"COMPOSE_PROJECT_NAME": PROJECT,
|
||||
"COMPOSE_FILE": os.pathsep.join(str(path) for path in files),
|
||||
"COMPOSE_ENV_FILES": str(ENV_FILE),
|
||||
}
|
||||
started = time.monotonic()
|
||||
proc = subprocess.run(
|
||||
[
|
||||
sys.executable,
|
||||
str(BAO_SCRIPT),
|
||||
"--address",
|
||||
f"https://localhost:{BAO_RUN['port']}",
|
||||
"--project",
|
||||
PROJECT,
|
||||
"--operator-dir",
|
||||
str(operator_dir),
|
||||
"--pki-dir",
|
||||
PKI_RUN["stand"],
|
||||
"ready",
|
||||
],
|
||||
cwd=ROOT,
|
||||
capture_output=True,
|
||||
text=True,
|
||||
env=env,
|
||||
check=False,
|
||||
)
|
||||
if proc.returncode != 0:
|
||||
# вывод bao.py — состояние, пути и версии, без токенов и значений
|
||||
tail = (proc.stdout + proc.stderr).strip().splitlines()[-3:]
|
||||
raise BenchError(
|
||||
f"OpenBao of the run is not ready: bao.py ready exited "
|
||||
f"{proc.returncode}: {' | '.join(tail)}",
|
||||
)
|
||||
self.bao_ready_seconds = round(time.monotonic() - started, 1)
|
||||
say(f"openbao initialized and seeded in {self.bao_ready_seconds} s")
|
||||
|
||||
def script_env(self) -> dict[str, str]:
|
||||
"""Окружение `scripts/rolling-update.sh`: тот же проект compose, что
|
||||
у `compose()` — `-p`, оба `-f` и `--env-file` переменными docker
|
||||
@@ -2642,6 +2743,9 @@ class Stand:
|
||||
self.work_dir.mkdir(parents=True, exist_ok=True)
|
||||
self.compose("up", "-d", "--wait", "postgres", "valkey")
|
||||
say("postgres and valkey healthy")
|
||||
# секреты процессов — из OpenBao прогона до bootstrap ролей и миграций
|
||||
# (change openbao-tooling, design, решение 6)
|
||||
self.start_openbao(say)
|
||||
# роли процессов и владелец схемы — до миграций (change storage-roles)
|
||||
self.compose("run", "--rm", "--no-deps", "postgres-bootstrap")
|
||||
self.compose("run", "--rm", "--no-deps", "migrate")
|
||||
@@ -3154,7 +3258,13 @@ class Stand:
|
||||
check=False,
|
||||
)
|
||||
|
||||
def recycle_uploads(self, image: str, env: dict[str, str]) -> None:
|
||||
def recycle_uploads(
|
||||
self,
|
||||
image: str,
|
||||
env: dict[str, str],
|
||||
*,
|
||||
before: bool = False,
|
||||
) -> None:
|
||||
"""Перед прогоном профиля загрузок (решение 10): новый volume S3 с
|
||||
bootstrap и новый контейнер реплики на образе варианта `image` с
|
||||
окружением `env` (override `VARIANT_COMPOSE`), затем готовность
|
||||
@@ -3177,13 +3287,7 @@ class Stand:
|
||||
raise BenchError(f"volume {S3_VOLUME} was not removed")
|
||||
self.start_s3()
|
||||
sh("docker", "tag", image, APP_IMAGE)
|
||||
path = self.work_dir / VARIANT_COMPOSE
|
||||
self.extra_files = []
|
||||
if env:
|
||||
lines = ["services:", " api:", " environment:"]
|
||||
lines += [f' {key}: "{value}"' for key, value in env.items()]
|
||||
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
self.extra_files = [path]
|
||||
self.write_variant(env, before=before)
|
||||
self.compose(
|
||||
"up",
|
||||
"-d",
|
||||
@@ -3195,7 +3299,31 @@ class Stand:
|
||||
self.wait_processes_ready()
|
||||
self.wait_ready()
|
||||
|
||||
def recycle_login(self, image: str, env: dict[str, str]) -> None:
|
||||
def write_variant(self, env: dict[str, str], *, before: bool) -> None:
|
||||
"""Override окружения реплики варианта (`VARIANT_COMPOSE`). Реплике
|
||||
образа «до» (код до перехода на OpenBao) — ещё секреты окружением,
|
||||
как давал compose до change `openbao-secrets`: в файле только ссылки
|
||||
`${…}` на пароли прогона (`BEFORE_SECRET_ENV`), значения подставляет
|
||||
compose из `compose_env`; паспорт их не пишет (`SECRET_ENV_MARKS`)."""
|
||||
path = self.work_dir / VARIANT_COMPOSE
|
||||
self.extra_files = []
|
||||
items = list(env.items())
|
||||
if before:
|
||||
items += list(BEFORE_SECRET_ENV.items())
|
||||
if not items:
|
||||
return
|
||||
lines = ["services:", " api:", " environment:"]
|
||||
lines += [f' {key}: "{value}"' for key, value in items]
|
||||
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
self.extra_files = [path]
|
||||
|
||||
def recycle_login(
|
||||
self,
|
||||
image: str,
|
||||
env: dict[str, str],
|
||||
*,
|
||||
before: bool = False,
|
||||
) -> None:
|
||||
"""Перед прогоном профиля входа (change `auth-hardening`, решение 7):
|
||||
ключи предела входа в Valkey удалены, реплики — новые контейнеры на
|
||||
образе варианта с его окружением (пик памяти — прогона), затем
|
||||
@@ -3211,13 +3339,7 @@ class Stand:
|
||||
)
|
||||
self.compose("rm", "-s", "-f", APP_SERVICE, check=False)
|
||||
sh("docker", "tag", image, APP_IMAGE)
|
||||
path = self.work_dir / VARIANT_COMPOSE
|
||||
self.extra_files = []
|
||||
if env:
|
||||
lines = ["services:", " api:", " environment:"]
|
||||
lines += [f' {key}: "{value}"' for key, value in env.items()]
|
||||
path.write_text("\n".join(lines) + "\n", encoding="utf-8")
|
||||
self.extra_files = [path]
|
||||
self.write_variant(env, before=before)
|
||||
self.compose(
|
||||
"up",
|
||||
"-d",
|
||||
@@ -3592,6 +3714,8 @@ class Stand:
|
||||
)
|
||||
if self.telemetry:
|
||||
roles.update(TELEMETRY_CONTAINERS)
|
||||
# OpenBao прогона — в каждом свежем стенде (change openbao-tooling)
|
||||
roles["openbao"] = BAO_CONTAINER
|
||||
limits: dict[str, Any] = {}
|
||||
for role, name in roles.items():
|
||||
limits[role] = self.container_limits(name)
|
||||
@@ -4314,6 +4438,24 @@ class Stand:
|
||||
# прогона — смена методики относительно меток лаб 4–6 (change
|
||||
# https-tooling, design, решение 5)
|
||||
"tls": dict(STAND_TLS),
|
||||
# источник секретов процессов (change openbao-tooling, design,
|
||||
# решение 6): OpenBao прогона, вход по сертификату, сроки ролей;
|
||||
# у варианта «до» — окружение реплики (только имена). Метки до
|
||||
# change с новыми — разная методика
|
||||
"secrets": {
|
||||
**STAND_SECRETS,
|
||||
"image": image(BAO_CONTAINER).get("image"),
|
||||
# init, unseal, сведение и наполнение последнего свежего стенда
|
||||
"ready_seconds": self.bao_ready_seconds,
|
||||
**(
|
||||
{
|
||||
"before": "environment: "
|
||||
+ " ".join(sorted(BEFORE_SECRET_ENV)),
|
||||
}
|
||||
if self.before_variant()
|
||||
else {}
|
||||
),
|
||||
},
|
||||
# учётные данные процессов в хранилищах (change storage-roles,
|
||||
# design, решение 10): метки до change с новыми — разная методика;
|
||||
# у варианта «до» загрузок — роль api и обход кэша
|
||||
@@ -7509,7 +7651,7 @@ class Bench:
|
||||
else {}
|
||||
),
|
||||
}
|
||||
stand.recycle_uploads(image, env)
|
||||
stand.recycle_uploads(image, env, before=run["variant"] == "before")
|
||||
replica = stand.replicas()[0]
|
||||
if run["variant"] not in info["app_env"]:
|
||||
info["app_env"][run["variant"]] = stand.app_env(replica)
|
||||
@@ -7743,7 +7885,11 @@ class Bench:
|
||||
info = self.results.meta["login"]
|
||||
self.stage = name
|
||||
self.progress()
|
||||
stand.recycle_login(image, self.login_env(run["variant"]))
|
||||
stand.recycle_login(
|
||||
image,
|
||||
self.login_env(run["variant"]),
|
||||
before=run["variant"] == "before",
|
||||
)
|
||||
replicas = stand.replicas()
|
||||
for replica in replicas:
|
||||
self.check_login_variant(run, replica)
|
||||
@@ -10506,6 +10652,44 @@ def unsupported_profile(name: str) -> str | None:
|
||||
)
|
||||
|
||||
|
||||
def _inside(path: Path, parent: Path) -> bool:
|
||||
path, parent = path.resolve(), parent.resolve()
|
||||
return path == parent or parent in path.parents
|
||||
|
||||
|
||||
def operator_dir_problem(
|
||||
operator_dir: Path,
|
||||
run_dir: Path,
|
||||
working_dirs: tuple[Path, ...] = (WORKING_OPERATOR_DIR,),
|
||||
) -> str | None:
|
||||
"""Сверка каталога материалов OpenBao прогона до первого обращения к
|
||||
OpenBao (спек `secret-store`, «Каталог материалов вне прогона»): только
|
||||
внутри каталога PKI прогона (`mtusi-bench-pki-*`) и не внутри каталога
|
||||
оператора рабочего стенда. Текст отказа или None."""
|
||||
if not run_dir.name.startswith(PKI_DIR_PREFIX) or not _inside(
|
||||
operator_dir,
|
||||
run_dir,
|
||||
):
|
||||
return (
|
||||
f"OpenBao operator dir {operator_dir} is outside the run "
|
||||
f"directory {PKI_DIR_PREFIX}*"
|
||||
)
|
||||
for working in working_dirs:
|
||||
if _inside(operator_dir, working):
|
||||
return (
|
||||
f"OpenBao operator dir {operator_dir} is inside the working "
|
||||
f"operator directory {working}"
|
||||
)
|
||||
return None
|
||||
|
||||
|
||||
def free_port() -> str:
|
||||
"""Свободный TCP-порт на 127.0.0.1 (OpenBao прогона, один на метку)."""
|
||||
with socket.socket() as sock:
|
||||
sock.bind(("127.0.0.1", 0))
|
||||
return str(sock.getsockname()[1])
|
||||
|
||||
|
||||
def make_run_pki(pki_dir: Path) -> None:
|
||||
"""PKI прогона: `pki.sh stand` с каталогами внутри `pki_dir` — новый CA и
|
||||
leaf по `infra/pki/identities.conf`; каталог оператора и `.pki/stand`
|
||||
@@ -10542,6 +10726,18 @@ def main(argv: list[str]) -> int:
|
||||
pki_dir = Path(tempfile.mkdtemp(prefix=PKI_DIR_PREFIX))
|
||||
code = 1
|
||||
try:
|
||||
# OpenBao прогона (change openbao-tooling, design, решение 6):
|
||||
# материалы — внутри каталога PKI прогона, сверка до первого вызова
|
||||
operator_dir = pki_dir / "operator" / "openbao" / PROJECT
|
||||
problem = operator_dir_problem(operator_dir, pki_dir)
|
||||
if problem:
|
||||
print(problem, flush=True)
|
||||
return 2
|
||||
BAO_RUN.update(
|
||||
port=free_port(),
|
||||
operator_dir=str(operator_dir),
|
||||
run_dir=str(pki_dir),
|
||||
)
|
||||
make_run_pki(pki_dir)
|
||||
code = run_label(argv, args)
|
||||
except BenchError as exc:
|
||||
@@ -10555,6 +10751,7 @@ def main(argv: list[str]) -> int:
|
||||
signal.signal(signal.SIGINT, signal.SIG_IGN)
|
||||
shutil.rmtree(pki_dir, ignore_errors=True)
|
||||
PKI_RUN["stand"] = ""
|
||||
BAO_RUN.update(port="", operator_dir="", run_dir="")
|
||||
if pki_dir.exists():
|
||||
print(f"cleanup incomplete: remove {pki_dir}", flush=True)
|
||||
code = code or 1
|
||||
|
||||
Reference in New Issue
Block a user