лр7: Docker-прогон, evidence, исправления

This commit is contained in:
kalibr456
2026-11-07 20:17:11 +03:00
parent 20afc2c790
commit cb38fd5231
249 changed files with 114500 additions and 82 deletions
+41
View File
@@ -0,0 +1,41 @@
"""Failover hook (tests/resilience.py --mode failover): остановить ОДНУ реплику API по X-Instance-Id.
lab7: X-Instance-Id — случайный alias процесса, а не ID контейнера/hostname. Каждая реплика пишет его в
tmpfs-файл /tmp/instance-id (settings.INSTANCE_ID_FILE); hook читает файл в каждом запущенном контейнере api
и останавливает тот, чей alias совпал. Реплика остаётся остановленной (восстановление — отдельно).
"""
import os
import re
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
STOP_TIMEOUT_SECONDS = 8
READ_ALIAS = "import settings; print(open(settings.INSTANCE_ID_FILE).read().strip())"
def main() -> int:
target = os.environ.get("TARGET_INSTANCE_ID", "").strip().lower()
if not re.fullmatch(r"[0-9a-f]{8,64}", target):
print("TARGET_INSTANCE_ID must be the X-Instance-Id alias of an api replica", file=sys.stderr)
return 2
running = subprocess.run(["docker", "compose", "ps", "-q", "api"], cwd=ROOT,
capture_output=True, text=True, check=True).stdout.split()
matches = []
for container in running:
alias = subprocess.run(["docker", "exec", container, "python", "-c", READ_ALIAS], cwd=ROOT,
capture_output=True, text=True, check=False).stdout.strip()
if alias == target:
matches.append(container)
if len(matches) != 1:
print(f"no running api container with alias {target}", file=sys.stderr)
return 1
subprocess.run(["docker", "stop", "--time", str(STOP_TIMEOUT_SECONDS), matches[0]],
cwd=ROOT, check=True, stdout=subprocess.DEVNULL)
print(f"stopped api container {matches[0][:12]} (alias {target})")
return 0
if __name__ == "__main__":
sys.exit(main())