forked from mtusi2026/mtusi2026lab3
204 lines
9.9 KiB
Python
Executable File
204 lines
9.9 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Render portable SVG graphs and a Markdown summary from grade-4 results."""
|
|
import argparse
|
|
from collections import defaultdict
|
|
import html
|
|
import json
|
|
from pathlib import Path
|
|
|
|
|
|
STYLE = """
|
|
text { font-family: Inter, Segoe UI, sans-serif; fill: #eceef0; }
|
|
.title { font-size: 26px; font-weight: 650; }
|
|
.label { font-size: 14px; fill: #c8cbd0; }
|
|
.small { font-size: 12px; fill: #a2a5aa; }
|
|
.grid { stroke: #34373d; stroke-width: 1; }
|
|
.bar { fill: #cfd2d6; }
|
|
.bar2 { fill: #73777f; }
|
|
.line { fill: none; stroke: #f4f5f6; stroke-width: 3; }
|
|
.error { fill: #8f949c; stroke: #f4f5f6; stroke-width: 1; }
|
|
.event { stroke: #a2a5aa; stroke-width: 2; stroke-dasharray: 6 5; }
|
|
"""
|
|
|
|
|
|
def svg(title, body, width=1100, height=560):
|
|
return f"""<svg xmlns="http://www.w3.org/2000/svg" width="{width}" height="{height}" viewBox="0 0 {width} {height}">
|
|
<rect width="100%" height="100%" fill="#0e1013"/>
|
|
<style>{STYLE}</style>
|
|
<text x="48" y="42" class="title">{html.escape(title)}</text>
|
|
{body}
|
|
</svg>
|
|
"""
|
|
|
|
|
|
def grid(maximum, left, top, width, height):
|
|
parts = []
|
|
for step in range(6):
|
|
value = maximum * step / 5
|
|
y = top + height - height * step / 5
|
|
parts.append(f'<line x1="{left}" y1="{y:.1f}" x2="{left+width}" y2="{y:.1f}" class="grid"/>')
|
|
parts.append(f'<text x="{left-12}" y="{y+4:.1f}" text-anchor="end" class="small">{value:.0f}</text>')
|
|
return parts
|
|
|
|
|
|
def throughput(phases, output):
|
|
left, top, width, height = 80, 90, 960, 360
|
|
maximum = max((phase["successful_rps"] for phase in phases), default=1) or 1
|
|
parts = grid(maximum, left, top, width, height)
|
|
slot = width / max(1, len(phases))
|
|
for index, phase in enumerate(phases):
|
|
bar_width = min(120, slot * 0.5)
|
|
x = left + slot * index + (slot - bar_width) / 2
|
|
bar_height = height * phase["successful_rps"] / maximum
|
|
y = top + height - bar_height
|
|
parts.append(f'<rect x="{x:.1f}" y="{y:.1f}" width="{bar_width:.1f}" height="{bar_height:.1f}" rx="10" class="bar"/>')
|
|
parts.append(f'<text x="{x+bar_width/2:.1f}" y="{y-10:.1f}" text-anchor="middle" class="label">{phase["successful_rps"]:.1f} RPS</text>')
|
|
parts.append(f'<text x="{x+bar_width/2:.1f}" y="{top+height+28}" text-anchor="middle" class="label">{html.escape(phase["name"])}</text>')
|
|
parts.append(f'<text x="{x+bar_width/2:.1f}" y="{top+height+48}" text-anchor="middle" class="small">errors {phase["error_ratio"]*100:.2f}%</text>')
|
|
parts.append(f'<text x="24" y="{top+height/2}" transform="rotate(-90 24 {top+height/2})" class="label">Successful requests per second</text>')
|
|
output.write_text(svg("Grade 4: throughput and errors", "\n".join(parts)))
|
|
|
|
|
|
def latency(phases, output):
|
|
left, top, width, height = 80, 90, 960, 360
|
|
values = [value for phase in phases
|
|
for value in phase["successful_latency_ms"].values()
|
|
if value is not None]
|
|
maximum = max(values, default=1) or 1
|
|
parts = grid(maximum, left, top, width, height)
|
|
slot = width / max(1, len(phases))
|
|
for phase_index, phase in enumerate(phases):
|
|
group_x = left + slot * phase_index
|
|
bar_width = min(42, slot / 5)
|
|
for metric_index, metric in enumerate(("p50", "p95", "p99")):
|
|
value = phase["successful_latency_ms"][metric] or 0
|
|
bar_height = height * value / maximum
|
|
x = group_x + slot * 0.2 + metric_index * (bar_width + 8)
|
|
y = top + height - bar_height
|
|
css = "bar" if metric_index == 0 else "bar2"
|
|
parts.append(f'<rect x="{x:.1f}" y="{y:.1f}" width="{bar_width:.1f}" height="{bar_height:.1f}" rx="7" class="{css}"/>')
|
|
parts.append(f'<text x="{x+bar_width/2:.1f}" y="{y-7:.1f}" text-anchor="middle" class="small">{value:.0f}</text>')
|
|
parts.append(f'<text x="{x+bar_width/2:.1f}" y="{top+height+20}" text-anchor="middle" class="small">{metric}</text>')
|
|
parts.append(f'<text x="{group_x+slot/2:.1f}" y="{top+height+48}" text-anchor="middle" class="label">{html.escape(phase["name"])}</text>')
|
|
parts.append(f'<text x="24" y="{top+height/2}" transform="rotate(-90 24 {top+height/2})" class="label">Successful latency, ms</text>')
|
|
output.write_text(svg("Grade 4: successful latency percentiles", "\n".join(parts)))
|
|
|
|
|
|
def timeline(phases, output):
|
|
left, top, width, height = 70, 90, 980, 390
|
|
rows, events, offset = [], [], 0
|
|
for phase in phases:
|
|
buckets = phase["per_second"]
|
|
for second, counts in sorted(buckets.items(), key=lambda item: int(item[0])):
|
|
rows.append((offset + int(second), counts))
|
|
if phase.get("action"):
|
|
events.append((offset + phase["action"]["started_at"], phase["name"]))
|
|
offset += max([int(key) for key in buckets] or [0]) + 2
|
|
maximum = max((counts["successful"] for _, counts in rows), default=1) or 1
|
|
max_x = max((second for second, _ in rows), default=1) or 1
|
|
parts, points = grid(maximum, left, top, width, height), []
|
|
for second, counts in rows:
|
|
x = left + width * second / max_x
|
|
y = top + height - height * counts["successful"] / maximum
|
|
points.append(f"{x:.1f},{y:.1f}")
|
|
if counts["failed"]:
|
|
radius = min(12, 3 + counts["failed"])
|
|
parts.append(f'<circle cx="{x:.1f}" cy="{top+height-8}" r="{radius}" class="error"/>')
|
|
parts.append(f'<polyline points="{" ".join(points)}" class="line"/>')
|
|
for second, label in events:
|
|
x = left + width * second / max_x
|
|
parts.append(f'<line x1="{x:.1f}" y1="{top}" x2="{x:.1f}" y2="{top+height}" class="event"/>')
|
|
parts.append(f'<text x="{x+6:.1f}" y="{top+18}" class="small">{html.escape(label)} action</text>')
|
|
parts.append(f'<text x="{left}" y="{top+height+32}" class="label">One-second buckets; circles mark failed requests</text>')
|
|
output.write_text(svg("Grade 4: request timeline", "\n".join(parts), height=600))
|
|
|
|
|
|
def resources(phases, output):
|
|
combined = defaultdict(lambda: {"cpu": [], "memory": []})
|
|
for phase in phases:
|
|
for name, values in phase["resources"].items():
|
|
combined[name]["cpu"].append(values["cpu_percent_max"])
|
|
combined[name]["memory"].append(values["memory_mib_max"])
|
|
names, parts = sorted(combined), []
|
|
panels = [
|
|
("Peak CPU, %", "cpu", 80, 90, 420, 360),
|
|
("Peak memory, MiB", "memory", 600, 90, 420, 360),
|
|
]
|
|
for title, metric, left, top, width, height in panels:
|
|
maximum = max((max(combined[name][metric]) for name in names), default=1) or 1
|
|
parts.append(f'<text x="{left}" y="{top-18}" class="label">{title}</text>')
|
|
slot = width / max(1, len(names))
|
|
for index, name in enumerate(names):
|
|
value = max(combined[name][metric])
|
|
bar_width = min(70, slot * 0.55)
|
|
x = left + slot * index + (slot - bar_width) / 2
|
|
bar_height = height * value / maximum
|
|
y = top + height - bar_height
|
|
parts.append(f'<rect x="{x:.1f}" y="{y:.1f}" width="{bar_width:.1f}" height="{bar_height:.1f}" rx="9" class="bar"/>')
|
|
parts.append(f'<text x="{x+bar_width/2:.1f}" y="{y-8:.1f}" text-anchor="middle" class="small">{value:.1f}</text>')
|
|
parts.append(f'<text x="{x+bar_width/2:.1f}" y="{top+height+25}" text-anchor="middle" class="small">{html.escape(name)}</text>')
|
|
output.write_text(svg("Grade 4: peak container resources", "\n".join(parts), height=600))
|
|
|
|
|
|
def summary(report, output):
|
|
method = report["methodology"]
|
|
lines = [
|
|
"# Lab 3 grade-4 experiment", "",
|
|
f"Generated: {report['environment']['utc_started_at']}.", "",
|
|
"## Method", "",
|
|
f"- concurrency: {method['concurrency']};",
|
|
f"- baseline duration: {method['baseline_seconds']} s;",
|
|
"- load: closed-loop POST messages through Nginx;",
|
|
"- failover: both original API containers stopped and restored in turn;",
|
|
"- rolling update: one surge replica, old replicas replaced one by one;",
|
|
"- percentiles cover successful responses; failures are separate.", "",
|
|
"## Results", "",
|
|
"| Phase | RPS | Errors | p50 ms | p95 ms | p99 ms | Recovery s |",
|
|
"| --- | ---: | ---: | ---: | ---: | ---: | ---: |",
|
|
]
|
|
for phase in report["phases"]:
|
|
lat = phase["successful_latency_ms"]
|
|
recovery = phase["recovery_seconds"]
|
|
lines.append(
|
|
f"| {phase['name']} | {phase['successful_rps']} | "
|
|
f"{phase['failed_requests']} ({phase['error_ratio']*100:.3f}%) | "
|
|
f"{lat['p50']} | {lat['p95']} | {lat['p99']} | "
|
|
f"{recovery if recovery is not None else 'n/a'} |"
|
|
)
|
|
idem = report["idempotency"]
|
|
lines += [
|
|
"", "## Parallel idempotency", "",
|
|
f"{idem['parallel_requests']} requests produced "
|
|
f"{idem['unique_message_ids']} unique message ID across "
|
|
f"{len(idem['observed_instances'])} API instances.", "",
|
|
"## Graphs", "",
|
|
"", "",
|
|
"", "",
|
|
"", "",
|
|
"", "",
|
|
"## Scope", "",
|
|
"Single-host process failure and rolling replacement only. PostgreSQL "
|
|
"and Nginx remain single points of failure.", "",
|
|
]
|
|
output.write_text("\n".join(lines))
|
|
|
|
|
|
def main():
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("results", nargs="?", default="evidence/grade4/results.json")
|
|
args = parser.parse_args()
|
|
source = Path(args.results)
|
|
report = json.loads(source.read_text())
|
|
destination = source.parent
|
|
phases = report["phases"]
|
|
throughput(phases, destination / "throughput-errors.svg")
|
|
latency(phases, destination / "latency.svg")
|
|
timeline(phases, destination / "timeline.svg")
|
|
resources(phases, destination / "resources.svg")
|
|
summary(report, destination / "README.md")
|
|
print(f"rendered grade-4 evidence in {destination}")
|
|
|
|
|
|
if __name__ == "__main__":
|
|
main()
|