forked from mtusi2026/mtusi2026lab4
ЛР4
This commit is contained in:
@@ -0,0 +1,60 @@
|
||||
"""Публичный тест сохранности (tests/resilience.py --mode persistence) и доказательство,
|
||||
что hook scripts/restart.cmd (Windows) или scripts/restart.sh действительно перезапустил процессы.
|
||||
|
||||
make persistence (= python student-tests/run_persistence.py)
|
||||
|
||||
До и после теста печатаются все контейнеры стенда с временем старта (StartedAt). После теста
|
||||
у postgres, valkey, s3, обеих реплик api и lb должен быть ТОТ ЖЕ ID контейнера (контейнеры и volumes
|
||||
те же, ничего не пересоздано) и НОВОЕ время старта (процесс перезапущен). Сам тест проверяет,
|
||||
что данные и прежний токен на месте. Сервис migrate при `docker compose start api` запускается
|
||||
снова как зависимость: он видит, что новых миграций нет, и сразу завершается.
|
||||
"""
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
|
||||
from helpers import ROOT, check, run
|
||||
from stand import BASE_URL, compose_output, inspect, ps_table
|
||||
|
||||
HOOK = ROOT / "scripts" / ("restart.cmd" if os.name == "nt" else "restart.sh")
|
||||
MUST_RESTART = ("api", "postgres", "valkey", "s3", "lb")
|
||||
|
||||
|
||||
def started_at():
|
||||
"""{ID контейнера: (сервис, время старта)} для работающих сервисов стенда."""
|
||||
result = {}
|
||||
for container in compose_output("ps", "-q").split():
|
||||
service = inspect(container, '{{index .Config.Labels "com.docker.compose.service"}}')
|
||||
result[container] = (service, inspect(container, "{{.State.StartedAt}}"))
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
print(f"hook: {HOOK.relative_to(ROOT).as_posix()}")
|
||||
print("=== containers before")
|
||||
print(ps_table())
|
||||
before = started_at()
|
||||
env = dict(os.environ, PYTHONUTF8="1", PYTHONIOENCODING="utf-8")
|
||||
t0 = time.monotonic()
|
||||
result = subprocess.run([sys.executable, "tests/resilience.py", "--mode", "persistence",
|
||||
"--action-script", str(HOOK), "--base-url", BASE_URL],
|
||||
cwd=ROOT, capture_output=True, env=env)
|
||||
took = time.monotonic() - t0
|
||||
print((result.stdout + result.stderr).decode("utf-8", "replace").strip())
|
||||
check(result.returncode == 0, "public persistence test failed")
|
||||
print(f"=== containers after (test took {took:.1f} s: hook + waiting for readiness + data checks)")
|
||||
print(ps_table())
|
||||
after = started_at()
|
||||
for container, (service, start) in sorted(before.items(), key=lambda item: item[1]):
|
||||
if service not in MUST_RESTART:
|
||||
continue
|
||||
check(container in after, f"{service} {container[:12]} was recreated or is not running")
|
||||
check(after[container][1] != start, f"{service} {container[:12]} was not restarted")
|
||||
print(f"{service:<9} {container[:12]}: same container, start time {start[11:19]} -> {after[container][1][11:19]}")
|
||||
print("PASS: api replicas, postgres, valkey, s3 and lb were restarted (same containers and volumes, "
|
||||
"new start time); data, the attachment bytes and the existing token survived")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
run(main)
|
||||
Reference in New Issue
Block a user