Реализовать лабораторную работу 3

This commit is contained in:
Никита
2026-11-02 18:55:53 +03:00
parent 0ab3a341aa
commit d2ff198781
109 changed files with 25218 additions and 27 deletions
+57
View File
@@ -0,0 +1,57 @@
#!/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()