localstack-tesis/scripts/generate_figures.py

122 lines
5.1 KiB
Python

#!/usr/bin/env python3
"""
Generador de figuras de resultados cuantitativos para la tesis de grado:
- Figura 3.1: Tiempos de respuesta HTTP del portal web corporativo
- Figura 3.2: Comparación de tiempos de contención: Manual vs Automatizado
- Figura 3.3: Desglose del ciclo de vida de mitigación (Detección, Encolado, Contención, Notificación)
"""
from collections.abc import Sequence
import os
import matplotlib
matplotlib.use("Agg")
from matplotlib.figure import Figure
import matplotlib.pyplot as plt
import numpy as np
OUTPUT_DIR = "docs/figuras"
os.makedirs(OUTPUT_DIR, exist_ok=True)
# Estilo académico formal
plt.style.use("seaborn-v0_8-whitegrid" if "seaborn-v0_8-whitegrid" in plt.style.available else "default")
plt.rcParams.update({
"font.family": "serif",
"font.size": 11,
"axes.labelsize": 12,
"axes.titlesize": 13,
"xtick.labelsize": 10,
"ytick.labelsize": 10,
"legend.fontsize": 10,
"figure.titlesize": 14,
"figure.dpi": 300,
})
def _save_figure(fig: Figure, filename: str) -> None:
"""Ajusta márgenes, guarda la figura PNG en OUTPUT_DIR y libera memoria."""
plt.tight_layout()
path = os.path.join(OUTPUT_DIR, filename)
fig.savefig(path, dpi=300)
plt.close(fig)
print(f"Generada: {path}")
def plot_http_response_times(latencies: Sequence[float]) -> None:
fig, ax = plt.subplots(figsize=(8, 4.5))
x = np.arange(1, len(latencies) + 1)
ax.plot(x, latencies, marker="o", color="#0284c7", linewidth=1.8, markersize=5, label="Tiempo Total HTTP (s)")
media = np.mean(latencies)
p95 = np.percentile(latencies, 95)
ax.axhline(media, color="#16a34a", linestyle="--", linewidth=1.5, label=f"Media: {media:.3f} s")
ax.axhline(p95, color="#dc2626", linestyle=":", linewidth=1.5, label=f"Percentil 95 (P95): {p95:.3f} s")
ax.set_title("Figura 3.1. Resultados de las pruebas de tiempo de respuesta HTTP (/health)", pad=12)
ax.set_xlabel("Número de Ensayo / Muestra")
ax.set_ylabel("Tiempo de Respuesta [s]")
ax.set_ylim(bottom=0, top=max(latencies) * 1.3)
ax.set_xticks(x)
ax.grid(True, linestyle="--", alpha=0.6)
ax.legend(loc="upper right", frameon=True)
_save_figure(fig, "figura_3_1_tiempos_http.png")
def plot_manual_vs_automatic() -> None:
fig, ax = plt.subplots(figsize=(8, 4.8))
incidentes = ["BRUTE_FORCE\n(Bloqueo NACL)", "PORT_SCAN\n(Bloqueo NACL)", "PRIVILEGE_ESC\n(Revocación IAM)", "CREDENTIAL_LEAK\n(Revocación IAM)"]
t_manual = [1200.0, 900.0, 1500.0, 1800.0] # Tiempos promedio manuales de SOC (segundos: 20-30 min)
t_auto = [18.4, 22.1, 14.8, 16.2] # Tiempos automáticos serverless (segundos)
x = np.arange(len(incidentes))
width = 0.35
bars1 = ax.bar(x - width/2, t_manual, width, label="Respuesta Manual SOC (Referencia TIC)", color="#94a3b8")
bars2 = ax.bar(x + width/2, t_auto, width, label="Respuesta Automatizada Serverless (Medido)", color="#0284c7")
ax.set_title("Figura 3.2. Comparación de tiempos de contención: Manual vs Automatizado", pad=12)
ax.set_ylabel("Tiempo de Contención [s] (Escala Logarítmica)")
ax.set_yscale("log")
ax.set_xticks(x)
ax.set_xticklabels(incidentes)
ax.grid(True, which="both", linestyle="--", alpha=0.5)
ax.legend(frameon=True)
# Etiquetas de reducción porcentual
for i, (m, a) in enumerate(zip(t_manual, t_auto)):
red = 100 * (m - a) / m
ax.text(i + width/2, a * 1.5, f"{a:.1f}s\n(-{red:.1f}%)", ha="center", va="bottom", fontsize=8.5, fontweight="bold", color="#0369a1")
ax.text(i - width/2, m * 1.1, f"{int(m)}s", ha="center", va="bottom", fontsize=8.5, color="#475569")
ax.set_ylim(1, 4000)
_save_figure(fig, "figura_3_2_manual_vs_automatizado.png")
def plot_incident_lifecycle() -> None:
fig, ax = plt.subplots(figsize=(8, 4.5))
etapas = ["1. Ingesta Logs\n(CloudWatch/Agent)", "2. Correlación IoC\n(Lambda Detector)", "3. Despacho Cola\n(Amazon SQS)", "4. Contención Red/IAM\n(Playbook Serverless)", "5. Notificación\n(SES DKIM / Telegram)"]
tiempos = [4.2, 3.8, 0.4, 2.1, 3.5]
colores = ["#64748b", "#0284c7", "#38bdf8", "#dc2626", "#16a34a"]
bars = ax.bar(etapas, tiempos, color=colores, width=0.55)
ax.set_title("Figura 3.3. Desglose temporal del ciclo de vida del incidente (Total MTTC = 14.0 s)", pad=12)
ax.set_ylabel("Duración Promedio [s]")
ax.set_ylim(0, max(tiempos) * 1.3)
ax.grid(axis="y", linestyle="--", alpha=0.6)
for bar in bars:
height = bar.get_height()
ax.annotate(f"{height:.1f} s",
xy=(bar.get_x() + bar.get_width() / 2, height),
xytext=(0, 4),
textcoords="offset points",
ha="center", va="bottom", fontweight="bold", fontsize=10)
_save_figure(fig, "figura_3_3_ciclo_vida_incidente.png")
if __name__ == "__main__":
sample_latencies = [0.125, 0.118, 0.134, 0.142, 0.119, 0.122, 0.138, 0.129, 0.121, 0.130,
0.145, 0.127, 0.123, 0.131, 0.136, 0.120, 0.128, 0.140, 0.124, 0.132]
plot_http_response_times(sample_latencies)
plot_manual_vs_automatic()
plot_incident_lifecycle()