test(openbao): lab7 check replica recovery after unseal
This commit is contained in:
@@ -0,0 +1,110 @@
|
|||||||
|
"""Проверка работающей сессии и холодного старта одной реплики при sealed OpenBao."""
|
||||||
|
import getpass
|
||||||
|
import json
|
||||||
|
import shlex
|
||||||
|
import ssl
|
||||||
|
import subprocess
|
||||||
|
import sys
|
||||||
|
import time
|
||||||
|
import urllib.request
|
||||||
|
from pathlib import Path
|
||||||
|
|
||||||
|
ROOT = Path(__file__).resolve().parents[1]
|
||||||
|
sys.path.insert(0, str(ROOT / "tests"))
|
||||||
|
from client import Client, Failure
|
||||||
|
|
||||||
|
CA = ROOT / "certs/private/ingress/ca.crt"
|
||||||
|
TLS = ssl.create_default_context(cafile=str(CA))
|
||||||
|
|
||||||
|
|
||||||
|
def docker(*args):
|
||||||
|
return subprocess.check_output(["docker", *args], cwd=ROOT, text=True, timeout=60).strip()
|
||||||
|
|
||||||
|
|
||||||
|
def inspect(cid):
|
||||||
|
return json.loads(docker("inspect", cid))[0]
|
||||||
|
|
||||||
|
|
||||||
|
def bao(path, token=None):
|
||||||
|
req = urllib.request.Request("https://127.0.0.1:18200/v1/sys/" + path)
|
||||||
|
if token:
|
||||||
|
req.method = "PUT"
|
||||||
|
req.add_header("X-Vault-Token", token)
|
||||||
|
with urllib.request.urlopen(req, context=TLS, timeout=5) as response:
|
||||||
|
return json.loads(response.read() or b"null")
|
||||||
|
|
||||||
|
|
||||||
|
def wait_for(label, predicate, seconds=100):
|
||||||
|
end = time.monotonic() + seconds
|
||||||
|
while time.monotonic() < end:
|
||||||
|
if predicate():
|
||||||
|
return
|
||||||
|
time.sleep(1)
|
||||||
|
raise RuntimeError("Истекло время ожидания: " + label)
|
||||||
|
|
||||||
|
|
||||||
|
def main():
|
||||||
|
ids = docker("compose", "ps", "-q", "api").split()
|
||||||
|
if len(ids) != 2 or any(inspect(i)["State"]["Health"]["Status"] != "healthy" for i in ids):
|
||||||
|
raise SystemExit("Для проверки нужны две здоровые реплики API.")
|
||||||
|
first, second = map(inspect, ids)
|
||||||
|
project = first["Config"]["Labels"]["com.docker.compose.project"]
|
||||||
|
if bao("seal-status")["sealed"]:
|
||||||
|
raise SystemExit("Сначала распечатайте OpenBao.")
|
||||||
|
client = Client(ca_file=str(CA), timeout=3)
|
||||||
|
actor = client.user("seal")
|
||||||
|
names = {node["Config"]["Hostname"] for node in (first, second)}
|
||||||
|
survivor = second["Config"]["Hostname"]
|
||||||
|
|
||||||
|
def session_replica():
|
||||||
|
response = client.call("GET", "/api/v1/users/me", actor=actor, schema="User")
|
||||||
|
if response["json"]["id"] != actor["id"]:
|
||||||
|
raise RuntimeError("Сессия вернула другого пользователя.")
|
||||||
|
return response["headers"]["X-Instance-Id"]
|
||||||
|
|
||||||
|
def both():
|
||||||
|
seen = set()
|
||||||
|
def poll():
|
||||||
|
try:
|
||||||
|
seen.add(session_replica())
|
||||||
|
except Failure:
|
||||||
|
pass
|
||||||
|
return seen == names
|
||||||
|
wait_for("ответы обеих реплик", poll)
|
||||||
|
|
||||||
|
both()
|
||||||
|
command = "docker compose -p " + shlex.quote(project) + " exec openbao bao operator unseal"
|
||||||
|
print("Откройте второй терминал WSL в каталоге проекта. Для восстановления нужны две разные доли.", flush=True)
|
||||||
|
token = getpass.getpass("Токен оператора с правом sys/seal: ")
|
||||||
|
if not token:
|
||||||
|
raise SystemExit("Пустой токен.")
|
||||||
|
try:
|
||||||
|
bao("seal", token)
|
||||||
|
del token
|
||||||
|
if not bao("seal-status")["sealed"]:
|
||||||
|
raise RuntimeError("OpenBao не перешёл в sealed.")
|
||||||
|
both()
|
||||||
|
docker("restart", ids[0])
|
||||||
|
wait_for("отказ запуска реплики при sealed", lambda: inspect(ids[0])["RestartCount"] > 0)
|
||||||
|
seen = set()
|
||||||
|
failures = 0
|
||||||
|
for _ in range(12):
|
||||||
|
try:
|
||||||
|
seen.add(session_replica())
|
||||||
|
except Failure:
|
||||||
|
failures += 1
|
||||||
|
time.sleep(0.5)
|
||||||
|
print(f"При sealed успешных ответов {12-failures}/12, ошибок {failures}/12.")
|
||||||
|
if seen != {survivor} or not bao("seal-status")["sealed"]:
|
||||||
|
raise RuntimeError("Не подтверждена работа сессии на оставшейся реплике.")
|
||||||
|
finally:
|
||||||
|
print("Если OpenBao запечатан, дважды выполните во втором терминале, вводя разные доли:\n" + command, flush=True)
|
||||||
|
wait_for("ручное раскрытие OpenBao", lambda: not bao("seal-status")["sealed"], 600)
|
||||||
|
wait_for("восстановление обеих реплик", lambda: all(
|
||||||
|
inspect(i)["State"].get("Health", {}).get("Status") == "healthy" for i in ids), 180)
|
||||||
|
both()
|
||||||
|
print("PASS: сессия сохранилась, обе реплики отвечают после unseal.")
|
||||||
|
|
||||||
|
|
||||||
|
if __name__ == "__main__":
|
||||||
|
main()
|
||||||
Reference in New Issue
Block a user