forked from mtusi2026/mtusi2026lab6
ЛР 6: реализация мессенджера и сценарии проверки
This commit is contained in:
@@ -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