forked from mtusi2026/mtusi2026lab6
ЛР 6: реализация мессенджера и сценарии проверки
This commit is contained in:
@@ -0,0 +1,46 @@
|
||||
"""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))
|
||||
broker = keep(LOCAL / "broker_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 / "broker_url", f"redis://:{broker}@broker:6379/0")
|
||||
keep(LOCAL / "cursor_key", token_hex(32))
|
||||
keep(LOCAL / "grafana_password", token_hex(24))
|
||||
keep(LOCAL / "s3_root.env",
|
||||
f"RUSTFS_ACCESS_KEY=labroot{token_hex(8)}\nRUSTFS_SECRET_KEY={token_hex(24)}")
|
||||
keep(LOCAL / "s3_access", "messenger" + token_hex(6))
|
||||
keep(LOCAL / "s3_secret", token_hex(24))
|
||||
config = "\n".join((
|
||||
"bind 0.0.0.0", "protected-mode yes", "dir /data",
|
||||
"appendonly yes", "appendfsync always", "maxmemory 64mb",
|
||||
"maxmemory-policy noeviction",
|
||||
))
|
||||
keep(LOCAL / "redis.conf", f"{config}\nrequirepass {cache}")
|
||||
keep(LOCAL / "broker.conf", f"{config}\nrequirepass {broker}")
|
||||
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 s3 broker worker relay || exit /b 1
|
||||
docker compose restart db cache s3 broker || exit /b 1
|
||||
docker compose restart api lb relay worker || exit /b 1
|
||||
docker compose ps lb api db cache s3 broker worker relay
|
||||
Executable
+7
@@ -0,0 +1,7 @@
|
||||
#!/bin/sh
|
||||
set -eu
|
||||
cd "$(dirname "$0")/.."
|
||||
docker compose ps lb api db cache s3 broker worker relay
|
||||
docker compose restart db cache s3 broker
|
||||
docker compose restart api lb relay worker
|
||||
docker compose ps lb api db cache s3 broker worker relay
|
||||
@@ -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
|
||||
@@ -0,0 +1,104 @@
|
||||
"""Repeat a fixed workload while changing OTLP and trace sampling settings."""
|
||||
|
||||
import argparse
|
||||
import json
|
||||
import os
|
||||
import subprocess
|
||||
import sys
|
||||
import time
|
||||
import urllib.parse
|
||||
import urllib.request
|
||||
from pathlib import Path
|
||||
|
||||
ROOT = Path(__file__).resolve().parents[1]
|
||||
sys.path.insert(0, str(ROOT / "tests"))
|
||||
from client import Client, Failure # noqa: E402
|
||||
|
||||
SERVICES = ("api", "worker", "relay", "collector", "tempo", "loki", "prometheus")
|
||||
|
||||
|
||||
def docker(env, *args):
|
||||
result = subprocess.run(["docker", *args], check=True, cwd=ROOT, env=env,
|
||||
capture_output=True, text=True, encoding="utf-8", timeout=100)
|
||||
return result.stdout
|
||||
|
||||
|
||||
def apply(env, address):
|
||||
docker(env, "compose", "up", "-d", "--no-deps", "--wait", "api", "relay", "worker")
|
||||
client = Client(address, timeout=3)
|
||||
deadline = time.monotonic() + 30
|
||||
while time.monotonic() < deadline:
|
||||
try:
|
||||
client.call("GET", "/health/ready", schema="Health")
|
||||
return
|
||||
except Failure:
|
||||
time.sleep(0.4)
|
||||
raise RuntimeError("Messenger did not become ready")
|
||||
|
||||
|
||||
def scrape(base, query):
|
||||
url = base.rstrip("/") + "/api/v1/query?" + urllib.parse.urlencode({"query": query})
|
||||
with urllib.request.urlopen(url, timeout=4) as response:
|
||||
data = json.load(response)["data"]["result"]
|
||||
return float(data[0]["value"][1]) if data else None
|
||||
|
||||
|
||||
def profile(env, args):
|
||||
containers = docker(env, "compose", "ps", "-q", *SERVICES).split()
|
||||
load = [sys.executable, "-X", "utf8", "tests/load.py", "--base-url", args.base_url,
|
||||
"--concurrency", str(args.concurrency), "--duration", str(args.seconds)]
|
||||
samples = []
|
||||
with subprocess.Popen(load, cwd=ROOT, stdout=subprocess.PIPE, text=True, encoding="utf-8") as running:
|
||||
deadline = time.monotonic() + args.seconds + 25
|
||||
while running.poll() is None and time.monotonic() < deadline:
|
||||
raw = docker(env, "stats", "--no-stream", "--format", "{{json .}}", *containers)
|
||||
fields = [json.loads(line) for line in raw.splitlines() if line]
|
||||
samples.append([{"name": row["Name"], "cpu": row["CPUPerc"], "memory": row["MemUsage"]}
|
||||
for row in fields])
|
||||
time.sleep(2)
|
||||
if running.poll() is None:
|
||||
running.kill()
|
||||
raise RuntimeError("workload exceeded its deadline")
|
||||
stdout, _ = running.communicate(timeout=5)
|
||||
if running.returncode:
|
||||
raise RuntimeError(stdout)
|
||||
time.sleep(6)
|
||||
window = args.seconds + 12
|
||||
queries = {
|
||||
"accepted_spans": "otelcol_receiver_accepted_spans(_total)?",
|
||||
"dropped_spans": "otelcol_exporter_send_failed_spans(_total)?",
|
||||
"tempo_ingest_bytes": "tempo_distributor_bytes_received_total",
|
||||
}
|
||||
values = {label: scrape(args.prom_url, f'sum(increase({{__name__=~"{metric}"}}[{window}s]))')
|
||||
for label, metric in queries.items()}
|
||||
return {"workload": json.loads(stdout), "containers": samples, "ingest": values}
|
||||
|
||||
|
||||
def main():
|
||||
parser = argparse.ArgumentParser(description=__doc__)
|
||||
parser.add_argument("--base-url", default="http://localhost:8080")
|
||||
parser.add_argument("--prom-url", default="http://localhost:9090")
|
||||
parser.add_argument("--seconds", type=int, default=30)
|
||||
parser.add_argument("--concurrency", type=int, default=8)
|
||||
parser.add_argument("--repeat", type=int, default=3)
|
||||
parser.add_argument("--output", type=Path, default=ROOT / "evidence/telemetry-overhead.json")
|
||||
args = parser.parse_args()
|
||||
baseline = dict(os.environ)
|
||||
output = []
|
||||
try:
|
||||
for label, enabled, fraction in (("off", "0", "0"), ("all", "1", "1"),
|
||||
("quarter", "1", "0.25"), ("twentieth", "1", "0.05")):
|
||||
env = {**baseline, "TELEMETRY_ENABLED": enabled, "TRACE_SAMPLE_RATE": fraction}
|
||||
apply(env, args.base_url)
|
||||
# Allow old samples to expire before each new measurement window.
|
||||
time.sleep(args.seconds + 12)
|
||||
output.append({"mode": label, "sampling": float(fraction),
|
||||
"runs": [profile(env, args) for _ in range(args.repeat)]})
|
||||
finally:
|
||||
apply(baseline, args.base_url)
|
||||
args.output.write_text(json.dumps(output, indent=2) + "\n", encoding="utf-8")
|
||||
print(f"Saved {len(output)} observed telemetry profiles.")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
main()
|
||||
Reference in New Issue
Block a user