forked from mtusi2026/mtusi2026lab3
ЛР 3: реализация мессенджера и сценарии проверки
This commit is contained in:
@@ -0,0 +1,37 @@
|
||||
"""Create local credentials once. Run from the repository on Windows or Linux."""
|
||||
|
||||
from pathlib import Path
|
||||
from secrets import token_hex
|
||||
|
||||
|
||||
ROOT = Path(__file__).resolve().parent.parent
|
||||
LOCAL = ROOT / "secrets"
|
||||
|
||||
|
||||
def keep(path, value):
|
||||
try:
|
||||
with path.open("x", encoding="utf-8", newline="\n") as stream:
|
||||
stream.write(value + "\n")
|
||||
except FileExistsError:
|
||||
pass
|
||||
return path.read_text(encoding="utf-8").strip()
|
||||
|
||||
|
||||
def main():
|
||||
LOCAL.mkdir(mode=0o700, exist_ok=True)
|
||||
db = keep(LOCAL / "db_password", token_hex(24))
|
||||
cache = keep(LOCAL / "cache_password", token_hex(24))
|
||||
keep(LOCAL / "database_url", f"postgresql://messenger:{db}@db:5432/messenger")
|
||||
keep(LOCAL / "cache_url", f"redis://:{cache}@cache:6379/0")
|
||||
keep(LOCAL / "cursor_key", token_hex(32))
|
||||
keep(LOCAL / "redis.conf", "\n".join((
|
||||
"bind 0.0.0.0", "protected-mode yes", "dir /data",
|
||||
"appendonly yes", "appendfsync always", "maxmemory 64mb",
|
||||
"maxmemory-policy noeviction", f"requirepass {cache}",
|
||||
)))
|
||||
keep(ROOT / ".env", "HTTP_PORT=8080\nSESSION_TTL_SECONDS=3600")
|
||||
print("Локальная конфигурация готова.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,51 @@
|
||||
"""Map a live process alias to a Compose container, then control that container."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
PROBE = """
|
||||
import urllib.request
|
||||
response = urllib.request.urlopen("http://127.0.0.1:8080/health/live", timeout=3)
|
||||
print(response.headers["X-Instance-Id"])
|
||||
"""
|
||||
|
||||
|
||||
def docker(*args, capture=True):
|
||||
return subprocess.run(
|
||||
("docker", *args), cwd=ROOT, capture_output=capture, text=True,
|
||||
check=True, timeout=60,
|
||||
).stdout
|
||||
|
||||
|
||||
def replicas():
|
||||
result = {}
|
||||
for container in docker("compose", "ps", "-q", "api").split():
|
||||
try:
|
||||
alias = docker("exec", container, "python", "-c", PROBE).strip()
|
||||
except subprocess.CalledProcessError:
|
||||
continue
|
||||
if alias and alias not in result:
|
||||
result[alias] = container
|
||||
return result
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("operation", choices=("list", "stop"))
|
||||
args = parser.parse_args()
|
||||
mapping = replicas()
|
||||
if args.operation == "list":
|
||||
print(json.dumps(mapping, indent=2))
|
||||
return
|
||||
alias = os.environ.get("TARGET_INSTANCE_ID")
|
||||
if not alias or alias not in mapping:
|
||||
raise SystemExit("TARGET_INSTANCE_ID must match a running API process")
|
||||
docker("stop", "--timeout", "10", mapping[alias], capture=False)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,6 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
docker compose ps lb api db cache || exit /b 1
|
||||
docker compose restart db cache || exit /b 1
|
||||
docker compose restart api lb || exit /b 1
|
||||
docker compose ps lb api db cache
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose ps lb api db cache
|
||||
docker compose restart db cache
|
||||
docker compose restart api lb
|
||||
docker compose ps lb api db cache
|
||||
@@ -0,0 +1,100 @@
|
||||
"""Repeat the same load over 1, 2 and 4 replicas under two resource strategies."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import statistics
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure # noqa: E402
|
||||
|
||||
|
||||
def compose(env, *args):
|
||||
return subprocess.run(["docker", "compose", *args], cwd=ROOT, env=env,
|
||||
capture_output=True, text=True, check=True, timeout=90).stdout
|
||||
|
||||
|
||||
def start(env):
|
||||
compose(env, "up", "-d", "--no-deps", "--wait", "api")
|
||||
client = Client(env["BASE_URL"], timeout=2)
|
||||
target = int(env["API_REPLICAS"])
|
||||
deadline = time.monotonic() + 40
|
||||
seen = set()
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
seen.add(client.call("GET", "/health/ready", schema="Health")["headers"]["X-Instance-Id"])
|
||||
except Failure:
|
||||
time.sleep(0.2)
|
||||
else:
|
||||
if len(seen) >= target:
|
||||
return
|
||||
raise RuntimeError("Configured replica count not visible through HAProxy")
|
||||
|
||||
|
||||
def sample_stats(env):
|
||||
ids = compose(env, "ps", "-q", "api", "db", "cache", "lb").split()
|
||||
snapshot = subprocess.run(
|
||||
["docker", "stats", "--no-stream", "--format", "{{json .}}", *ids],
|
||||
cwd=ROOT, env=env, capture_output=True, check=True, text=True, timeout=12,
|
||||
).stdout
|
||||
rows = [json.loads(line) for line in snapshot.splitlines() if line.strip()]
|
||||
return [{"name": row["Name"], "cpu": row["CPUPerc"], "memory": row["MemUsage"]} for row in rows]
|
||||
|
||||
|
||||
def load(env, seconds, concurrency):
|
||||
with subprocess.Popen(
|
||||
[sys.executable, "-X", "utf8", "tests/load.py", "--duration", str(seconds),
|
||||
"--concurrency", str(concurrency)], cwd=ROOT, env=env, text=True,
|
||||
encoding="utf-8", stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
||||
) as process:
|
||||
observed = []
|
||||
started = time.monotonic()
|
||||
try:
|
||||
while process.poll() is None and time.monotonic() - started < seconds + 20:
|
||||
observed.append(sample_stats(env))
|
||||
time.sleep(2)
|
||||
output, errors = process.communicate(timeout=15)
|
||||
except BaseException:
|
||||
process.kill()
|
||||
raise
|
||||
if process.returncode:
|
||||
raise RuntimeError(f"load script failed: {errors or output}")
|
||||
return {"load": json.loads(output), "resource_samples": observed}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--seconds", type=int, default=15)
|
||||
parser.add_argument("--repeat", type=int, default=3)
|
||||
parser.add_argument("--concurrency", type=int, default=12)
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "evidence/scaling.json")
|
||||
args = parser.parse_args()
|
||||
base = {**os.environ, "BASE_URL": args.base_url}
|
||||
original = {**base, "API_REPLICAS": base.get("API_REPLICAS", "2"),
|
||||
"API_CPUS": base.get("API_CPUS", "0.75"), "API_MEMORY": base.get("API_MEMORY", "256m")}
|
||||
rows = []
|
||||
try:
|
||||
for strategy in ("fixed_total", "fixed_per_replica"):
|
||||
for replicas in (1, 2, 4):
|
||||
cpu, memory = (2 / replicas, 1024 // replicas) if strategy == "fixed_total" else (0.5, 256)
|
||||
env = {**base, "API_REPLICAS": str(replicas), "API_CPUS": str(cpu), "API_MEMORY": f"{memory}m"}
|
||||
start(env)
|
||||
load(env, 4, args.concurrency)
|
||||
attempts = [load(env, args.seconds, args.concurrency) for _ in range(args.repeat)]
|
||||
rows.append({"strategy": strategy, "replicas": replicas, "cpu_per_replica": cpu,
|
||||
"memory_mib_per_replica": memory, "runs": attempts,
|
||||
"median_success_rps": statistics.median(x["load"]["successful_rps"] for x in attempts)})
|
||||
finally:
|
||||
start(original)
|
||||
args.output.write_text(json.dumps(rows, indent=2) + "\n", encoding="utf-8")
|
||||
print(f"Saved {len(rows)} observed resource profiles")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
@@ -0,0 +1,3 @@
|
||||
@echo off
|
||||
cd /d "%~dp0.."
|
||||
python scripts/replicas.py stop
|
||||
Executable
+4
@@ -0,0 +1,4 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
exec python3 scripts/replicas.py stop
|
||||
Reference in New Issue
Block a user