ЛР 3 — балансировка и отказ API-реплики

This commit is contained in:
Риц Дмитрий
2026-11-06 02:45:37 +03:00
parent 0ab3a341aa
commit 6dada9a6d0
34 changed files with 2245 additions and 36 deletions
+15
View File
@@ -0,0 +1,15 @@
"""Generate local Compose secrets once, without printing them."""
from pathlib import Path
from secrets import token_hex
root = Path(__file__).resolve().parents[1]
example = (root / ".env.example").read_text(encoding="utf-8")
try:
with (root / ".env").open("x", encoding="utf-8", newline="\n") as target:
target.write(example.replace("POSTGRES_PASSWORD=\n", f"POSTGRES_PASSWORD={token_hex(24)}\n")
.replace("CURSOR_SECRET=\n", f"CURSOR_SECRET={token_hex(32)}\n"))
except FileExistsError:
print("Using the existing .env")
else:
print("Created local .env")
+61
View File
@@ -0,0 +1,61 @@
"""Match an API response alias to a container in this Compose project."""
import json
import os
from pathlib import Path
import subprocess
import sys
from typing import NamedTuple
ROOT = Path(__file__).resolve().parents[1]
class Replica(NamedTuple):
id: str
alias: str
name: str
image: str
status: str
def docker(*args, timeout=30):
return subprocess.run(
["docker", *args], cwd=ROOT, text=True, encoding="utf-8",
stdout=subprocess.PIPE, check=True, timeout=timeout,
).stdout.strip()
def compose(*args, **kwargs):
return docker("compose", *args, **kwargs)
def replicas():
ids = compose("ps", "-a", "-q", "api").splitlines()
if not ids:
return []
fields = "{{.Id}} {{.Config.Hostname}} {{.Name}} {{.Image}} {{.State.Status}}"
return [Replica(*line.split()) for line in docker("inspect", "--format", fields, *ids).splitlines()]
def stop(replica):
docker("stop", "--time", "7", replica.id, timeout=9)
def main():
target = os.environ.get("TARGET_INSTANCE_ID")
running = [replica for replica in replicas() if replica.status == "running"]
matched = [replica for replica in running if replica.alias == target]
if len(matched) != 1 or len(running) < 2:
raise ValueError("TARGET_INSTANCE_ID must match one of at least two running API replicas")
replica = matched[0]
stop(replica)
print(json.dumps({"stopped_container": replica.name, "instance_id": replica.alias}))
if __name__ == "__main__":
try:
main()
except (ValueError, OSError, subprocess.SubprocessError) as error:
print(f"Stop hook failed: {error}", file=sys.stderr)
sys.exit(1)
+2
View File
@@ -0,0 +1,2 @@
@echo off
docker compose --project-directory "%~dp0.." restart postgres redis api lb
+4
View File
@@ -0,0 +1,4 @@
#!/bin/sh
set -eu
cd "$(dirname "$0")/.."
exec docker compose restart postgres redis api lb
+2
View File
@@ -0,0 +1,2 @@
@echo off
python "%~dp0replicas.py"
+3
View File
@@ -0,0 +1,3 @@
#!/bin/sh
set -eu
exec "${PYTHON:-python3}" "$(dirname "$0")/replicas.py"