forked from mtusi2026/mtusi2026lab3
58 lines
2.6 KiB
Python
58 lines
2.6 KiB
Python
#!/usr/bin/env python3
|
||
"""Stop one actual API container, show surviving responses, then always restore it."""
|
||
import argparse
|
||
import json
|
||
from pathlib import Path
|
||
import re
|
||
import signal
|
||
import sys
|
||
import time
|
||
from urllib.request import urlopen
|
||
|
||
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "student-tests"))
|
||
from cluster import alias, api_ids, docker, wait_api
|
||
|
||
|
||
def main():
|
||
parser = argparse.ArgumentParser(description=__doc__)
|
||
parser.add_argument("--instance", required=True)
|
||
parser.add_argument("--seconds", type=int, default=15)
|
||
parser.add_argument("--base-url", default="http://127.0.0.1:18080")
|
||
args = parser.parse_args()
|
||
if not re.fullmatch(r"[a-f0-9]{32}", args.instance) or not 8 <= args.seconds <= 60:
|
||
parser.error("instance must be a 32-character API ID; seconds must be 8–60")
|
||
containers = api_ids()
|
||
if len(containers) < 2:
|
||
parser.error("At least two running API replicas are required")
|
||
identities = {alias(container): container for container in containers}
|
||
if args.instance not in identities:
|
||
parser.error("This API instance is no longer running; copy a fresh command from the panel")
|
||
wait_api(args.base_url, len(containers))
|
||
target = identities[args.instance]
|
||
print("Останавливаем API " + args.instance[:8] + ". Откройте схему и отправляйте сообщения.", flush=True)
|
||
try:
|
||
docker("stop", "--time", "2", target)
|
||
until = time.monotonic() + args.seconds
|
||
while time.monotonic() < until:
|
||
started = time.monotonic()
|
||
try:
|
||
with urlopen(args.base_url + "/health/ready", timeout=2) as response:
|
||
print(json.dumps({"status": response.status,
|
||
"instance": response.headers.get("X-Instance-Id"),
|
||
"duration_ms": round((time.monotonic() - started) * 1000)}), flush=True)
|
||
except OSError:
|
||
print('{"status":"no_response"}', flush=True)
|
||
time.sleep(min(1, max(0, until - time.monotonic())))
|
||
finally:
|
||
print("Восстанавливаем остановленный контейнер…", flush=True)
|
||
docker("start", target)
|
||
wait_api(args.base_url, len(containers))
|
||
print("Готово. Оба API доступны. Новый ID восстановленного процесса: " + alias(target), flush=True)
|
||
|
||
|
||
if __name__ == "__main__":
|
||
def interrupted(*_):
|
||
raise KeyboardInterrupt
|
||
signal.signal(signal.SIGTERM, interrupted)
|
||
main()
|