реализация 3 лабы

This commit is contained in:
Ванек
2026-10-29 14:51:19 +03:00
parent 74aa224251
commit 64ea89d040
28 changed files with 2411 additions and 243 deletions
+1 -1
View File
@@ -8,4 +8,4 @@ if [[ ! -x .venv/bin/python ]]; then
fi
./scripts/build.sh
mkdir -p evidence
.venv/bin/python -u student-tests/docker_lifecycle.py 2>&1 | tee evidence/docker-checks.txt
.venv/bin/python -u student-tests/docker_lifecycle.py 2>&1 | sed -E 's/[[:blank:]]+$//' | tee evidence/lab3-checks.txt
+2 -1
View File
@@ -22,6 +22,7 @@ chat_id="$(jq -nc --arg a "$alice_id" --arg b "$bob_id" '{title:"Учебный
--data-binary @- "$base_url/api/v1/chats" | jq -er '.id')"
for token in "$alice_token" "$bob_token"; do
curl -fsS -H "Authorization: Bearer $token" -H 'Content-Type: application/json' \
-d '{"text":"Привет из lab2! 👋"}' "$base_url/api/v1/chats/$chat_id/messages" | jq .
-H "Idempotency-Key: demo-$RANDOM-$RANDOM" \
-d '{"text":"Привет из lab3! 👋"}' "$base_url/api/v1/chats/$chat_id/messages" | jq .
done
curl -fsS -H "Authorization: Bearer $bob_token" "$base_url/api/v1/chats/$chat_id/messages" | jq .
+2 -1
View File
@@ -2,4 +2,5 @@
set -euo pipefail
project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$project_dir"
docker compose exec -T api python -m src.migrate
python3 scripts/init_local.py
docker compose run --rm --build migrate
+90
View File
@@ -0,0 +1,90 @@
"""Управление репликами только текущего Compose project через Docker CLI."""
import argparse
import json
import os
from pathlib import Path
import subprocess
import time
from urllib.request import urlopen
ROOT = Path(__file__).resolve().parents[1]
def command(*args):
return subprocess.check_output(args, cwd=ROOT, text=True, timeout=120).strip()
def replicas():
ids = command("docker", "compose", "ps", "-q", "api").split()
return json.loads(command("docker", "inspect", *ids)) if ids else []
def base_url():
config = json.loads(command("docker", "compose", "config", "--format", "json"))
port = config["services"]["lb"]["ports"][0]["published"]
return os.environ.get("BASE_URL", "http://127.0.0.1:" + str(port)).rstrip("/")
def wait_ready():
url = base_url() + "/health/ready"
deadline = time.monotonic() + 90
seen = set()
while time.monotonic() < deadline:
current = replicas()
expected = {info["Config"]["Hostname"] for info in current}
if expected and all(info["State"].get("Health", {}).get("Status") == "healthy" for info in current):
try:
with urlopen(url, timeout=2) as response:
if response.status == 200:
seen.add(response.headers.get("X-Instance-Id"))
if expected <= seen:
print("API ready through LB:", ", ".join(sorted(expected)), flush=True)
return
except OSError:
pass
time.sleep(0.2)
raise RuntimeError("Не все работающие API-реплики готовы через LB за 90 секунд")
def stop_one():
target = os.environ.get("TARGET_INSTANCE_ID")
if not target:
raise RuntimeError("Задайте TARGET_INSTANCE_ID из X-Instance-Id")
current = replicas()
matches = [info for info in current if info["Config"]["Hostname"] == target]
if len(current) < 2 or len(matches) != 1:
raise RuntimeError("Нужны минимум две работающие реплики и ровно одна выбранная")
selected = matches[0]
command("docker", "stop", "--time", "8", selected["Id"])
print("Stopped API:", target, "container=" + selected["Id"], flush=True)
def rolling():
wait_ready()
originals = replicas()
count = len(originals)
if count < 2:
raise RuntimeError("Для поочерёдной замены нужны минимум две API-реплики")
for old in originals:
active = replicas()
healthy = [info for info in active if info["Id"] != old["Id"]
and info["State"].get("Health", {}).get("Status") == "healthy"]
if not healthy:
raise RuntimeError("Нет готовой реплики, которая продолжит обслуживать запросы")
print("Replacing API:", old["Config"]["Hostname"], flush=True)
command("docker", "stop", "--time", "8", old["Id"])
command("docker", "rm", old["Id"])
# --no-recreate сохраняет остальные процессы; Compose создаёт только недостающий.
command("docker", "compose", "up", "-d", "--no-deps", "--no-recreate", "--scale", f"api={count}", "api")
wait_ready()
assert len(replicas()) == count
final = replicas()
assert not ({info["Id"] for info in originals} & {info["Id"] for info in final})
print("PASS: all API containers replaced sequentially; stores and LB kept running", flush=True)
if __name__ == "__main__":
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("action", choices=["wait", "stop", "rolling"])
action = parser.parse_args().action
{"wait": wait_ready, "stop": stop_one, "rolling": rolling}[action]()
+1 -1
View File
@@ -2,5 +2,5 @@
set -euo pipefail
project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$project_dir"
docker compose restart --timeout 10 postgres valkey api
docker compose restart --timeout 8 postgres valkey api lb
./scripts/wait-ready.sh
+8
View File
@@ -0,0 +1,8 @@
#!/usr/bin/env bash
set -euo pipefail
project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$project_dir"
# Сначала собираем образ и применяем только обратно совместимые миграции.
./scripts/build.sh
./scripts/migrate.sh
exec python3 scripts/replicas.py rolling
+1 -1
View File
@@ -1,5 +1,5 @@
#!/usr/bin/env bash
set -euo pipefail
# В lab2 локальный запуск включает API, PostgreSQL и Valkey.
# Локальный стенд: HAProxy, две API-реплики, PostgreSQL и Valkey.
project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
exec "$project_dir/scripts/start.sh"
+1 -1
View File
@@ -3,5 +3,5 @@ set -euo pipefail
project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$project_dir"
python3 scripts/init_local.py
docker compose up -d --build api
docker compose up -d --build lb
./scripts/wait-ready.sh
+5
View File
@@ -0,0 +1,5 @@
#!/usr/bin/env bash
set -euo pipefail
project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$project_dir"
exec python3 scripts/replicas.py stop
+1 -9
View File
@@ -2,12 +2,4 @@
set -euo pipefail
project_dir="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$project_dir"
for ((attempt = 0; attempt < 60; attempt++)); do
if docker compose exec -T api python -m src.healthcheck >/dev/null 2>&1; then
echo "API ready"
exit 0
fi
sleep 1
done
echo "API не готов за 60 секунд. Проверь docker compose logs api" >&2
exit 1
exec python3 scripts/replicas.py wait