Files
mtusi2026lab6/scripts/stop_one.py
T
2026-11-01 20:38:50 +03:00

50 lines
2.2 KiB
Python

"""Failover hook logic for tests/resilience.py --mode failover (lab3).
Called by scripts/stop-one.sh (Linux/macOS) and scripts/stop-one.cmd (Windows).
The test puts X-Instance-Id of the replica that served its first message into
TARGET_INSTANCE_ID. In this solution X-Instance-Id is the container hostname, and
Docker sets the hostname to the short container ID. So the script finds that ID
among the RUNNING containers of the "api" service of this Compose project and
stops only that one container. Postgres, Valkey, the balancer and volumes are not
touched. The replica stays stopped; restore it with `make restore`
(docker compose up -d --wait) or `docker start <id>`.
docker stop sends SIGTERM: the replica first answers 503 on /health/ready for
SHUTDOWN_DRAIN_SECONDS (HAProxy takes it out of rotation), then finishes started
requests and exits. --time 8: SIGKILL after 8 s at most, so the hook always returns
within the 10 s the test allows.
This file is plain ASCII on purpose: scripts/check_contract.py reads every
scripts/*.py with the default encoding, which is cp1251 on a Russian Windows.
"""
import os
import re
import subprocess
import sys
from pathlib import Path
ROOT = Path(__file__).resolve().parents[1]
STOP_TIMEOUT_SECONDS = 8
def main() -> int:
target = os.environ.get("TARGET_INSTANCE_ID", "").strip().lower()
# The value comes from an HTTP header: accept only a hex container ID, nothing else.
if not re.fullmatch(r"[0-9a-f]{12,64}", target):
print("TARGET_INSTANCE_ID must be a container id (X-Instance-Id)", 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 = [container for container in running if container.startswith(target)]
if len(matches) != 1:
print("no running api container with id " + 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("stopped api container " + matches[0][:12])
return 0
if __name__ == "__main__":
sys.exit(main())