Реализовать лабораторную работу 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
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
root="$(CDPATH= cd -- "$(dirname "$0")/.." && pwd)"
exec docker compose --project-name mtusi2026lab3 --project-directory "$root" "$@"
+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()
+19
View File
@@ -0,0 +1,19 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
umask 077
mkdir -p secrets
if [ -e secrets/postgres_password ] || [ -e secrets/database_url ]; then
if [ ! -s secrets/postgres_password ] || [ ! -s secrets/database_url ]; then
printf '%s\n' 'Incomplete secrets directory; repair it manually without replacing an existing database password.' >&2
exit 1
fi
exit 0
fi
password="$(openssl rand -hex 24)"
printf '%s' "$password" > secrets/postgres_password
printf 'Host=postgres;Port=5432;Database=messenger;Username=messenger;Password=%s' "$password" > secrets/database_url
printf '%s\n' 'Created local database secrets in ignored secrets/ directory.'
+16
View File
@@ -0,0 +1,16 @@
#!/usr/bin/env python3
import json
from pathlib import Path
import sys
root = Path(__file__).resolve().parents[1]
sys.path.insert(0, str(root / "student-tests"))
from scaling_research import summarize, make_chart, write_report
path = root / "evidence/scaling.json"
evidence = json.loads(path.read_text())
summarize(evidence)
path.write_text(json.dumps(evidence, ensure_ascii=False, indent=2) + "\n")
make_chart(evidence)
write_report(evidence)
print("Updated evidence/scaling.png, evidence/scaling.svg and docs/SCALING.md")
+7
View File
@@ -0,0 +1,7 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
./scripts/compose.sh restart postgres redis
./scripts/compose.sh up -d --wait --wait-timeout 60 postgres redis
./scripts/compose.sh restart api lb
./scripts/compose.sh up -d --wait --wait-timeout 60 api lb
+13
View File
@@ -0,0 +1,13 @@
#!/usr/bin/env python3
import argparse
import json
from pathlib import Path
import sys
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "student-tests"))
from cluster import rolling_replace
parser = argparse.ArgumentParser()
parser.add_argument("--base-url", default="http://127.0.0.1:18080")
args = parser.parse_args()
print(json.dumps(rolling_replace(args.base_url), indent=2))
+13
View File
@@ -0,0 +1,13 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
test -n "${TARGET_INSTANCE_ID:-}" || { echo "TARGET_INSTANCE_ID is required" >&2; exit 1; }
for id in $(./scripts/compose.sh ps -q api); do
instance="$(docker exec "$id" curl -fsS -D - -o /dev/null http://127.0.0.1:8080/health/live | tr -d '\r' | awk 'tolower($1) == "x-instance-id:" { print $2 }')"
if [ "$instance" = "$TARGET_INSTANCE_ID" ]; then
docker stop --time 8 "$id" >/dev/null
exit 0
fi
done
echo "Requested API instance was not found" >&2
exit 1
+19
View File
@@ -0,0 +1,19 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
mkdir -p evidence
exec 3>&1
exec > evidence/checks.txt 2>&1
date -u '+Verified: %Y-%m-%d %H:%M:%S UTC'
for target in build check validate test student-test test-auth test-ui test-persistence restore-api test-failover restore-api test-idempotency-modes test-expiry test-grade4 research-grade5 test student-test test-ui; do
printf '\n$ make %s\n' "$target"
printf 'Running: %s\n' "$target" >&3
./scripts/compose.sh ps --all
if ! make "$target" BASE_URL="${BASE_URL:-http://127.0.0.1:18080}"; then
tail -n 35 evidence/checks.txt >&3
exit 1
fi
done
git diff --exit-code -- contracts tests README.md COURSE.md
printf '\nPASS: Lab3 checks completed\n'
printf 'PASS: evidence/checks.txt\n' >&3