Files
mtusi2026lab7/student-tests/track1.py
T
alenchha 861e7722b5 ЛР 7 — БВТ2301 — Курлова — на 4
Перенесён минимум lab6 (API без изменений), добавлена защита на границах доверия:
- внешний HTTPS; обязательный mTLS LB -> API с allowlist identity и отзывом по serial;
- TLS на всех связях: PostgreSQL verify-full, MinIO HTTPS, RabbitMQ AMQPS mTLS (EXTERNAL),
  Valkey TLS + ACL, Collector и хранилища телеметрии через mTLS с отдельными CA;
- OpenBao в server mode: cert auth, токены 15 мин, политики только на свой путь;
- роли БД, S3-политики и права брокера по принципу минимальных прав;
- Argon2id с замером, rehash, общий лимит входа, бюджет защиты от login DoS;
- hardening всех контейнеров, scan образов с разбором, модель угроз, матрица доверия;
- отрицательные тесты: TLS-аудит (135 проверок), ACL, ротации, sealed OpenBao.
2026-11-16 10:49:13 +03:00

344 lines
17 KiB
Python

#!/usr/bin/env python3
"""Track 5.1 "Цена наблюдаемости": the same open-loop load against several telemetry configurations.
Configurations (applied by recreating api-1, api-2, worker and otel-collector with shell env overrides):
off OTEL_SDK_DISABLED=true no SDK, no instrumentation (baseline)
on100 sampler ratio 1.0, collector profile default every span exported
head10 sampler ratio 0.1, collector profile default head sampling of root spans (children follow)
tail sampler ratio 1.0, collector profile tail balanced: errors + >500 ms + async pipeline + 10% rest
Per run: recreate -> ready -> warm-up 20 s -> idle 20 s -> counters A -> load (rate, duration) -> idle 30 s ->
counters B. Delta(B-A) = telemetry produced by the measured load. CPU is the exact cgroup delta over the load window
(Docker API); RSS is the maximum of `docker stats` samples taken every 5 s. Afterwards Tempo is searched in the load window for traces of injected slow/error requests and
upload pipelines, to count what survives sampling.
python3 student-tests/track1.py run [--configs off,on100,head10,tail] [--repeats 2] [--rate 60] [--duration 90]
python3 student-tests/track1.py summary # evidence/track1/results.jsonl -> evidence/track1/summary.md
"""
import argparse
import json
import os
import re
import statistics
import subprocess
import threading
import time
from pathlib import Path
import obs
from openloop import Load
from stand import Client, log
ROOT = Path(__file__).resolve().parents[1]
OUT = ROOT / "evidence/track1"
CONFIGS = {
"off": {"OTEL_SDK_DISABLED": "true", "OTEL_TRACES_SAMPLER_ARG": "1.0", "COLLECTOR_PROFILE": "default"},
"on100": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER_ARG": "1.0", "COLLECTOR_PROFILE": "default"},
"head10": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER_ARG": "0.1", "COLLECTOR_PROFILE": "default"},
"tail": {"OTEL_SDK_DISABLED": "false", "OTEL_TRACES_SAMPLER_ARG": "1.0", "COLLECTOR_PROFILE": "tail"},
}
SERVICES = ("api-1", "api-2", "worker", "otel-collector", "tempo", "loki", "prometheus", "postgres", "nginx")
COUNTERS = {
# SDK side (sum over all instances; absent when the SDK is off)
"sdk_span_decisions_sample": 'sum(messenger_telemetry_sampler_decisions_total{decision="sample"})',
"sdk_span_decisions_drop_ratio": 'sum(messenger_telemetry_sampler_decisions_total{decision="drop",rule=~"ratio|parent"})',
"sdk_spans_exported_ok": 'sum(messenger_telemetry_spans_exported_total{outcome="success"})',
"sdk_spans_exported_failed": 'sum(messenger_telemetry_spans_exported_total{outcome="failure"})',
# Collector
"col_spans_in": "sum(otelcol_receiver_accepted_spans_total)",
"col_logs_in": "sum(otelcol_receiver_accepted_log_records_total)",
"col_points_in": "sum(otelcol_receiver_accepted_metric_points_total)",
"col_spans_out": 'sum(otelcol_exporter_sent_spans_total{exporter="otlp/tempo"})',
"col_spans_refused": "sum(otelcol_receiver_refused_spans_total)",
"col_spans_dropped": 'sum(otelcol_exporter_enqueue_failed_spans_total) or vector(0)',
"col_otlp_bytes_in": 'sum({__name__="http.server.request.size_bytes_total"})',
# Backends
"tempo_spans_in": "sum(tempo_distributor_spans_received_total)",
"tempo_bytes_in": "sum(tempo_distributor_bytes_received_total)",
"loki_bytes_in": "sum(loki_distributor_bytes_received_total)",
"loki_lines_in": "sum(loki_distributor_lines_received_total)",
"prom_samples_in": "sum(prometheus_tsdb_head_samples_appended_total)",
}
def compose(*args, env=None, timeout=300):
done = subprocess.run(["docker", "compose", "--env-file", ".env", *args], cwd=ROOT, capture_output=True,
text=True, timeout=timeout, env={**os.environ, **(env or {})})
if done.returncode != 0:
raise RuntimeError("compose %s: %s" % (args[:2], done.stderr[-400:]))
return done.stdout
def apply(name):
env = CONFIGS[name]
compose("up", "-d", "--wait", "--force-recreate", "--no-deps", "otel-collector", "api-1", "api-2", "worker",
env=env)
compose("restart", "nginx") # re-resolve recreated replicas
c = Client()
deadline = time.monotonic() + 120
while time.monotonic() < deadline:
try:
c.call("GET", "/health/ready", 200)
break
except Exception:
time.sleep(1)
out = compose("exec", "-T", "api-1", "printenv", "OTEL_SDK_DISABLED", "OTEL_TRACES_SAMPLER_ARG")
log("config %s applied: api-1 env %s" % (name, out.split()))
def counters():
values = {}
for key, expr in COUNTERS.items():
try:
rows = obs.prom(expr)
values[key] = rows[0][1] if rows else None
except Exception:
values[key] = None
tail = {}
for metric, value in obs.prom('{__name__=~"otelcol_processor_tail_sampling_count_traces_sampled.*"}'):
tail["%s/%s" % (metric.get("policy"), metric.get("sampled"))] = value
values["tail_policies"] = tail
return values
def delta(a, b):
out = {}
for key in COUNTERS:
if a.get(key) is not None and b.get(key) is not None:
out[key] = b[key] - a[key]
elif b.get(key) is not None:
out[key] = b[key] # series appeared during the window (counter started at 0)
else:
out[key] = None
out["tail_policies"] = {k: v - a["tail_policies"].get(k, 0) for k, v in b["tail_policies"].items()}
return out
def parse_mem(text):
"""'123.4MiB' -> 123.4 (MiB)."""
match = re.match(r"\s*([\d.]+)\s*([A-Za-z]*)", text)
if not match:
return 0.0
scale = {"B": 1 / 1048576, "kB": 1 / 1024, "KiB": 1 / 1024, "MiB": 1, "MB": 1, "GiB": 1024, "GB": 1024}
return float(match.group(1)) * scale.get(match.group(2), 1)
def sample_stats(stop, samples):
while not stop.is_set():
out = subprocess.run(["docker", "stats", "--no-stream", "--format", "{{.Name}}\t{{.CPUPerc}}\t{{.MemUsage}}"],
capture_output=True, text=True).stdout
row = {}
for line in out.splitlines():
name, cpu, mem = line.split("\t")
if not name.startswith("mtusi-lab6-"):
continue
svc = name[len("mtusi-lab6-"):].rsplit("-", 1)[0]
cur = row.setdefault(svc, [0.0, 0.0])
cur[0] += float(cpu.rstrip("%") or 0)
cur[1] += parse_mem(mem.split(" / ")[0])
samples.append(row)
stop.wait(5)
def docker_socket():
host = subprocess.run(["docker", "context", "inspect", "--format", "{{.Endpoints.docker.Host}}"],
capture_output=True, text=True).stdout.strip()
return host.replace("unix://", "")
def cpu_seconds():
"""Cumulative container CPU seconds per service from the Docker API (exact over a window, unlike docker stats)."""
sock = docker_socket()
ids = subprocess.run(["docker", "ps", "--filter", "label=com.docker.compose.project=mtusi-lab6", "--format",
"{{.ID}} {{.Names}}"], capture_output=True, text=True).stdout.splitlines()
out = {}
for line in ids:
cid, name = line.split()
svc = name[len("mtusi-lab6-"):].rsplit("-", 1)[0]
raw = subprocess.run(["curl", "-s", "--unix-socket", sock,
"http://localhost/containers/%s/stats?stream=false&one-shot=true" % cid],
capture_output=True, text=True).stdout
out[svc] = out.get(svc, 0.0) + json.loads(raw)["cpu_stats"]["cpu_usage"]["total_usage"] / 1e9
return out
def count_traces(query, start, end):
try:
return len(obs.tempo_search(query, limit=10000, start=start, end=end))
except Exception as exc:
return "error:%s" % type(exc).__name__
def one_run(name, rep, rate, duration):
apply(name)
load = Load("https://localhost:8443", users=4, threads=96)
load.run(rate, 20, 0.5, 1, 1) # warm-up, same mix
time.sleep(20)
a = counters()
load = Load("https://localhost:8443", users=4, threads=96)
stop, samples = threading.Event(), []
sampler = threading.Thread(target=sample_stats, args=(stop, samples), daemon=True)
sampler.start()
cpu_a = cpu_seconds()
t_start = time.time()
summary = load.run(rate, duration, 1, 1, 1)
t_end = time.time()
cpu_b = cpu_seconds()
stop.set()
sampler.join(15)
time.sleep(30) # SDK batch (2 s) + collector batch (2 s) + tail decision_wait (10 s) + scrape (15 s)
b = counters()
d = delta(a, b)
# % of one core averaged over the load window (cumulative cgroup CPU; several replicas of a service are summed)
cpu = {svc: round((cpu_b[svc] - cpu_a[svc]) / (t_end - t_start) * 100, 2) for svc in cpu_b if svc in cpu_a}
mem = {svc: round(max(s[svc][1] for s in samples if svc in s), 1) for svc in samples[0]} if samples else {}
w0, w1 = int(t_start) - 2, int(t_end) + 15
traces = {
"server_api": count_traces('{resource.service.name="messenger-api" && kind=server}', w0, w1),
"slow": count_traces('{span.messenger.fault="slow"}', w0, w1),
"error": count_traces('{span.messenger.fault="error"}', w0, w1),
"pipeline_consumer": count_traces('{kind=consumer && span.messenger.job.outcome="succeeded"}', w0, w1),
}
result = {"config": name, "rep": rep, "env": CONFIGS[name], "load": summary, "cpu_pct_avg": cpu,
"mem_mib_max": mem, "telemetry_delta": d, "traces_in_tempo": traces,
"window": [t_start, t_end], "stats_samples": len(samples)}
log("%s#%d: ok_rps=%s p50/p95/p99=%s/%s/%s ms api_cpu=%s+%s%% spans_in=%s tempo_spans=%s slow=%s/%d err=%s/%d" % (
name, rep, summary["successful_rps"], summary["latency_ms_plain_ok"]["p50"],
summary["latency_ms_plain_ok"]["p95"], summary["latency_ms_plain_ok"]["p99"], cpu.get("api-1"),
cpu.get("api-2"), d.get("col_spans_in"), d.get("tempo_spans_in"), traces["slow"],
summary["faults_sent"]["slow"], traces["error"], summary["faults_sent"]["error"]))
return result
def cmd_run(args):
OUT.mkdir(parents=True, exist_ok=True)
path = OUT / "results.jsonl"
names = args.configs.split(",")
try:
for rep in range(1, args.repeats + 1):
for name in names:
result = one_run(name, rep, args.rate, args.duration)
result["hardware"] = HARDWARE
with path.open("a", encoding="utf-8") as handle:
handle.write(json.dumps(result, ensure_ascii=False) + "\n")
finally:
log("restore default configuration (on100)")
apply("on100")
def fmt(v, digits=0):
if v is None:
return "—"
if isinstance(v, str):
return v
return ("%%.%df" % digits) % v
def metric_500s(run_result):
"""Injected 500s as seen by METRICS for this run: metrics are computed in the SDK, before any trace sampling."""
start, end = run_result["window"]
if run_result["config"] == "off":
return None
# Exact counter difference at the window borders (increase() extrapolates and overstates by ~10% here).
expr = 'sum(http_server_request_duration_seconds_count{service_name="messenger-api",http_response_status_code="500"})'
try:
return obs.prom_scalar(expr, at=end + 20) - obs.prom_scalar(expr, at=start - 5)
except Exception:
return None
def cmd_summary(_args):
rows = [json.loads(line) for line in (OUT / "results.jsonl").read_text(encoding="utf-8").splitlines() if line]
by = {}
for r in rows:
by.setdefault(r["config"], []).append(r)
def values(items, fn):
return [v for v in (fn(x) for x in items) if isinstance(v, (int, float))]
def avg(items, fn):
vals = values(items, fn)
return statistics.mean(vals) if vals else None
def spread(items, fn, digits=1):
vals = values(items, fn)
if not vals:
return "—"
return "%s (%s…%s)" % (fmt(statistics.mean(vals), digits), fmt(min(vals), digits), fmt(max(vals), digits))
lat = lambda q: (lambda x: x["load"]["latency_ms_plain_ok"][q]) # noqa: E731
cpu = lambda *svc: (lambda x: sum(x["cpu_pct_avg"].get(s, 0) for s in svc)) # noqa: E731
delta_of = lambda key: (lambda x: x["telemetry_delta"].get(key)) # noqa: E731
traces = lambda key: (lambda x: x["traces_in_tempo"].get(key)) # noqa: E731
faults = lambda key: (lambda x: x["load"]["faults_sent"][key]) # noqa: E731
names = [n for n in CONFIGS if n in by]
lines = ["Среднее по прогонам (мин…макс). CPU — % одного ядра за окно нагрузки, реплики сервиса суммируются.", "",
"| Конфигурация | Прогонов | Успешн. RPS | Неожид. ошибки | p50, ms | p95, ms | p99, ms | CPU api-1+2, % | CPU worker, % |",
"|---|---|---|---|---|---|---|---|---|"]
for n in names:
i = by[n]
lines.append("| %s | %d | %s | %s | %s | %s | %s | %s | %s |" % (
n, len(i), fmt(avg(i, lambda x: x["load"]["successful_rps"]), 1),
fmt(avg(i, lambda x: x["load"]["server_errors_unexpected"])), spread(i, lat("p50")), spread(i, lat("p95")),
spread(i, lat("p99")), spread(i, cpu("api-1", "api-2")), spread(i, cpu("worker"))))
lines += ["", "| Конфигурация | CPU collector, % | CPU Tempo, % | CPU Loki, % | CPU Prometheus, % | RSS api-1 (макс), MiB | RSS collector, MiB | RSS Tempo, MiB |",
"|---|---|---|---|---|---|---|---|"]
for n in names:
i = by[n]
mem = lambda s: (lambda x: x["mem_mib_max"].get(s)) # noqa: E731
lines.append("| %s | %s | %s | %s | %s | %s | %s | %s |" % (
n, spread(i, cpu("otel-collector"), 2), spread(i, cpu("tempo"), 2), spread(i, cpu("loki"), 2),
spread(i, cpu("prometheus"), 2), fmt(avg(i, mem("api-1"))), fmt(avg(i, mem("otel-collector"))),
fmt(avg(i, mem("tempo")))))
lines += ["", "| Конфигурация | Spans → collector | Spans → Tempo | Отказы/отбросы collector | OTLP ingest, KiB | Tempo ingest, KiB | Loki ingest, KiB |",
"|---|---|---|---|---|---|---|"]
for n in names:
i = by[n]
kib = lambda key: (avg(i, delta_of(key)) / 1024 if avg(i, delta_of(key)) is not None else None) # noqa: E731
lost = avg(i, lambda x: (x["telemetry_delta"].get("col_spans_refused") or 0) + (x["telemetry_delta"].get("col_spans_dropped") or 0))
lines.append("| %s | %s | %s | %s | %s | %s | %s |" % (
n, fmt(avg(i, delta_of("col_spans_in"))), fmt(avg(i, delta_of("tempo_spans_in"))), fmt(lost),
fmt(kib("col_otlp_bytes_in")), fmt(kib("tempo_bytes_in")), fmt(kib("loki_bytes_in"))))
lines += ["", "Сумма по всем прогонам конфигурации: сохранено трасс / отправлено. «500 в метриках» — разность счётчика HTTP в Prometheus на границах окна.", "",
"| Конфигурация | Серверных трасс API | slow (+600 ms) | error (500) | upload-конвейеров | 500 в метриках / отправлено |",
"|---|---|---|---|---|---|"]
for n in names:
i = by[n]
total = lambda fn: sum(values(i, fn)) # noqa: E731
m500 = [metric_500s(x) for x in i]
lines.append("| %s | %d / %d | %d / %d | %d / %d | %d / %d | %s / %d |" % (
n, total(traces("server_api")), total(lambda x: x["load"]["requests"]),
total(traces("slow")), total(faults("slow")), total(traces("error")), total(faults("error")),
total(traces("pipeline_consumer")), total(lambda x: x["load"]["by_kind"]["upload"]["n"]),
"—" if None in m500 else "%.0f" % sum(m500), total(faults("error"))))
text = "\n".join(lines) + "\n"
(OUT / "summary.md").write_text(text, encoding="utf-8")
print(text)
HARDWARE = {}
def main():
p = argparse.ArgumentParser()
sub = p.add_subparsers(dest="cmd", required=True)
r = sub.add_parser("run")
r.add_argument("--configs", default="off,on100,head10,tail")
r.add_argument("--repeats", type=int, default=2)
r.add_argument("--rate", type=float, default=60)
r.add_argument("--duration", type=float, default=90)
sub.add_parser("summary")
args = p.parse_args()
if args.cmd == "run":
info = subprocess.run(["docker", "info", "--format", "{{.ServerVersion}} {{.NCPU}} {{.MemTotal}}"],
capture_output=True, text=True).stdout.split()
HARDWARE.update({"docker": info[0], "vm_cpus": int(info[1]), "vm_mem_gib": round(int(info[2]) / 2**30, 1)})
cmd_run(args)
else:
cmd_summary(args)
if __name__ == "__main__":
main()