Files
mtusi2026lab7/research/analyze_pki.py
T

241 lines
8.4 KiB
Python

"""Summarize only completed PKI observations and their actual time intervals."""
import argparse
import csv
import json
import math
import re
import statistics
from collections import Counter
from itertools import pairwise
from pathlib import Path
import matplotlib
matplotlib.use("Agg")
import matplotlib.pyplot as plt
def quantile(values, fraction):
ordered = sorted(values)
return (
ordered[max(0, math.ceil(len(ordered) * fraction) - 1)]
if ordered
else None
)
def main():
parser = argparse.ArgumentParser(description=__doc__)
parser.add_argument("input", type=Path)
parser.add_argument("--output", required=True, type=Path)
args = parser.parse_args()
report = json.loads(args.input.read_text())
assert report["complete"], (
"An incomplete experiment cannot yield a final analysis"
)
with args.input.with_name(
args.input.stem + "-requests.csv"
).open() as stream:
rows = list(csv.DictReader(stream))
for row in rows:
row["started_at"] = float(row["started_at"])
row["duration_seconds"] = float(row["duration_seconds"])
row["status"] = int(row["status"])
phases = []
for phase in report["phases"]:
observed = [
r
for r in rows
if phase["started_at"] <= r["started_at"] < phase["ended_at"]
]
successful = [
r["duration_seconds"] for r in observed if r["status"] == 201
]
duration = phase["ended_at"] - phase["started_at"]
phases.append(
{
"phase": phase["name"],
"seconds": round(duration, 3),
"scheduled_messages": len(observed),
"statuses": dict(Counter(str(r["status"]) for r in observed)),
"successful_rps": round(len(successful) / duration, 4),
"http_errors": sum(
r["status"] not in {201, 0, -1} for r in observed
),
"transport_errors": sum(r["status"] == 0 for r in observed),
"client_backpressure_drops": sum(
r["status"] == -1 for r in observed
),
"attempted_request_error_fraction": (
sum(r["status"] not in {201, -1} for r in observed)
/ sum(r["status"] != -1 for r in observed)
)
if any(r["status"] != -1 for r in observed)
else None,
**{
f"success_p{int(q * 100)}_seconds": quantile(successful, q)
for q in [0.5, 0.95, 0.99]
},
}
)
args.output.mkdir(parents=True, exist_ok=True)
summary = {
"source_commit": report["source_commit"],
"complete": True,
"phase_assignment": "actual request start within measured phase wall-clock bounds",
"preservation": report["preservation"],
"phases": phases,
"all_statuses": dict(Counter(str(r["status"]) for r in rows)),
}
resources = {}
for sample in report.get("resource_samples", []):
for observation in sample["containers"]:
name = observation["Name"]
result = resources.setdefault(
name,
{
"observations": 0,
"maximum_observed_cpu_cores": 0,
"maximum_observed_memory_mib": 0,
},
)
result["observations"] += 1
result["maximum_observed_cpu_cores"] = max(
result["maximum_observed_cpu_cores"],
float(observation["CPUPerc"].rstrip("%")) / 100,
)
value, unit = re.fullmatch(
r"([\d.]+)([KMGT]?i?B)",
observation["MemUsage"].split("/")[0].strip(),
).groups()
factor = {
"B": 1,
"KiB": 1024,
"MiB": 1024**2,
"GiB": 1024**3,
"TiB": 1024**4,
"kB": 1000,
"MB": 1000**2,
"GB": 1000**3,
}[unit]
result["maximum_observed_memory_mib"] = max(
result["maximum_observed_memory_mib"],
float(value) * factor / 1024**2,
)
samples = report.get("resource_samples", [])
intervals = [
b["started_at"] - a["started_at"] for a, b in pairwise(samples)
]
summary["sampling_intervals_seconds"] = (
{
"min": min(intervals),
"median": statistics.median(intervals),
"max": max(intervals),
}
if intervals
else None
)
summary["resources"] = {
"measurement": report.get("resource_measurement"),
"limits": report.get("resource_limits"),
"sampled_maxima_not_absolute_peaks": resources,
"sampling_errors": report.get("resource_sampling_errors", []),
}
(args.output / "summary.json").write_text(
json.dumps(summary, ensure_ascii=False, indent=2) + "\n"
)
with (args.output / "phases.csv").open("w") as stream:
writer = csv.DictWriter(stream, fieldnames=list(phases[0]))
writer.writeheader()
writer.writerows(
{**p, "statuses": json.dumps(p["statuses"])} for p in phases
)
origin = report["phases"][0]["started_at"]
finish = max(r["started_at"] + r["duration_seconds"] for r in rows)
count = math.ceil((finish - origin) / 10)
windows = [
[
r
for r in rows
if origin + i * 10 <= r["started_at"] < origin + (i + 1) * 10
]
for i in range(count)
]
fig, axes = plt.subplots(
2, 1, figsize=(12, 7), sharex=True, constrained_layout=True
)
positions = [i * 10 + 5 for i in range(count)]
bottom = [0] * count
for label, color, predicate in [
("201: подтверждено", "#238b45", lambda s: s == 201),
("Ошибки HTTP", "#d95f0e", lambda s: s not in {201, 0, -1}),
("Ошибка TLS / сети", "#756bb1", lambda s: s == 0),
("Генератор занят", "#969696", lambda s: s == -1),
]:
values = [
sum(predicate(r["status"]) for r in window) for window in windows
]
axes[0].bar(
positions,
values,
width=9.5,
bottom=bottom,
label=label,
color=color,
)
bottom = [a + b for a, b in zip(bottom, values, strict=True)]
for q, label in [(0.5, "p50"), (0.95, "p95")]:
values = [
quantile(
[r["duration_seconds"] for r in window if r["status"] == 201],
q,
)
for window in windows
]
axes[1].plot(
positions,
[v if v is not None else math.nan for v in values],
label=label,
)
labels = ["1", "2", "3", "4", "5", "6", "7"]
for i, phase in enumerate(report["phases"]):
left, right = phase["started_at"] - origin, phase["ended_at"] - origin
for axis in axes:
axis.axvspan(
left,
right,
color="#d9e5ef",
alpha=0.22 if i % 2 == 0 else 0.04,
)
axis.axvline(left, color="#51616c", lw=0.6)
axes[0].text(
(left + right) / 2,
1.02,
labels[i],
transform=axes[0].get_xaxis_transform(),
ha="center",
fontsize=8,
)
axes[0].set_ylabel("Запросы сообщений за 10 с")
axes[1].set_ylabel("Задержка успешного запроса, с")
axes[1].set_xlabel("Секунды от начала первого этапа")
for axis in axes:
axis.legend(loc="upper left", fontsize=8)
axis.grid(axis="y", alpha=0.2)
fig.suptitle("Жизненный цикл сертификатов под нагрузкой HTTPS", y=1.04)
fig.text(
0.5,
-0.04,
"1 — Обновление; 2 — Смена рабочего ключа; 3 — Отзыв; 4 — Истечение;\n5 — Блокировка OpenBao; 6 — Замена CA; 7 — После восстановления",
ha="center",
fontsize=9,
)
fig.savefig(args.output / "pki-results.png", dpi=170, bbox_inches="tight")
plt.close(fig)
print("PASS: observed phase summaries and PKI figure")
if __name__ == "__main__":
main()