Files
mtusi2026lab6/scripts/plot_observability.py
2026-10-30 21:38:40 +03:00

59 lines
3.8 KiB
Python

"""Publication files from saved observations; never synthesizes measurements."""
from pathlib import Path
import json
import matplotlib
matplotlib.use('Agg')
import matplotlib.pyplot as plt
ROOT=Path(__file__).resolve().parents[1]
E=ROOT/'evidence'
def load(name):return json.loads((E/name).read_text())
def scalar(sample,expression):
rows=sample.get('metrics',{}).get(expression,[])
return float(rows[0]['value'][1]) if rows else float('nan')
def main():
samples=load('slo_samples.json');events=load('slo_events.json')
start=min(s['monotonic'] for s in samples)
x=[(s['monotonic']-start)/60 for s in samples]
plt.rcParams.update({'font.size':10,'axes.spines.top':False,'axes.spines.right':False})
fig,axes=plt.subplots(4,1,figsize=(12,12),sharex=True,layout='constrained')
for expr,label,color in [
('slo:api_error_ratio:30s','API errors / 30 s','#c23b22'),
('slo:api_error_ratio:2m','API errors / 2 min','#1f77b4'),
('slo:api_error_ratio:5m','API errors / 5 min','#689f38')]:
axes[0].plot(x,[100*scalar(s,expr) for s in samples],label=label,color=color)
axes[0].axhline(14.4,color='#c23b22',ls='--',alpha=.5,label='fast burn threshold')
axes[0].axhline(6,color='#689f38',ls=':',alpha=.6,label='slow burn threshold')
axes[0].set_ylabel('HTTP 5xx (%)');axes[0].legend(ncol=3,fontsize=8)
axes[1].plot(x,[scalar(s,'max(queue_oldest_age_seconds)') for s in samples],color='#7b1fa2',label='Oldest unfinished job')
axes[1].axhline(15,color='gray',ls='--',label='Queue lag threshold')
axes[1].set_ylabel('Queue age (s)');axes[1].legend(loc='upper right',fontsize=8)
names=['QueueLagGrowing','ReadyErrorBudgetBurn','APIHighErrorRate','APIErrorBudgetBurnFast','APIErrorBudgetBurnSlow']
for index,name in enumerate(names):
active=[s for s in samples if any(a['labels']['alertname']==name and a['state']=='firing' for a in s.get('alerts',[]))]
axes[2].scatter([(s['monotonic']-start)/60 for s in active],[index]*len(active),s=13,marker='s',label=name)
axes[2].set_yticks(range(len(names)),names,fontsize=8);axes[2].set_ylabel('Firing alert')
axes[2].set_ylim(-.5,len(names)-.5)
axes[3].plot(x,[s.get('windows_c_free_bytes',0)/1024**3 for s in samples],color='#00838f',label='C drive free space')
axes[3].axhline(2,color='#c23b22',ls='--',label='Automatic stop threshold')
axes[3].set_ylabel('Free disk (GiB)');axes[3].set_xlabel('Elapsed monotonic time (minutes)')
axes[3].legend(fontsize=8)
for ax in axes:
ax.grid(alpha=.2)
for event in events:
if event['name'] in ['db_lock_acquired','worker_stopped','tempo_stopped']:
ax.axvline((event['monotonic']-start)/60,color='black',alpha=.2,lw=.8)
fig.suptitle('Lab6: two repetitions of short spike, worker stop and sustained DB degradation',fontsize=13)
fig.savefig(E/'slo_timeline.png',dpi=160);fig.savefig(E/'slo_timeline.svg')
plt.close(fig)
rows=load('slo_requests.json')
groups=[('baseline','Baseline'),('1_short_spike','Short DB 1'),('1_db_degraded','Long DB 1'),
('2_short_spike','Short DB 2'),('2_db_degraded','Long DB 2'),('backend_down','Tempo down')]
data=[[r['seconds']*1000 for r in rows if r['phase']==phase and r['status']==201] for phase,_ in groups]
fig,ax=plt.subplots(figsize=(10,4.8),layout='constrained')
ax.boxplot(data,tick_labels=[name for _,name in groups],showfliers=False)
ax.set_ylabel('Successful HTTP latency (ms), log scale');ax.set_yscale('log')
ax.set_title('Client latency by phase (failures counted separately in slo_result.json)')
ax.grid(axis='y',alpha=.2);fig.savefig(E/'successful_latency.png',dpi=160);plt.close(fig)
print('Saved slo_timeline.png/.svg and successful_latency.png from real evidence')
if __name__=='__main__':main()