slo-toolkit 0.1.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- slo_toolkit/__init__.py +3 -0
- slo_toolkit/cli.py +94 -0
- slo_toolkit/dashboards.py +128 -0
- slo_toolkit/py.typed +0 -0
- slo_toolkit/rules.py +162 -0
- slo_toolkit/spec.py +126 -0
- slo_toolkit-0.1.1.dist-info/METADATA +195 -0
- slo_toolkit-0.1.1.dist-info/RECORD +11 -0
- slo_toolkit-0.1.1.dist-info/WHEEL +4 -0
- slo_toolkit-0.1.1.dist-info/entry_points.txt +2 -0
- slo_toolkit-0.1.1.dist-info/licenses/LICENSE +21 -0
slo_toolkit/__init__.py
ADDED
slo_toolkit/cli.py
ADDED
|
@@ -0,0 +1,94 @@
|
|
|
1
|
+
"""`slogen` command line: validate specs and generate rules and dashboards."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import json
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
from typing import Annotated, Any
|
|
8
|
+
|
|
9
|
+
import typer
|
|
10
|
+
import yaml
|
|
11
|
+
|
|
12
|
+
from slo_toolkit.dashboards import dashboard
|
|
13
|
+
from slo_toolkit.rules import rule_groups
|
|
14
|
+
from slo_toolkit.spec import ServiceSLOs, SpecError, load_all
|
|
15
|
+
|
|
16
|
+
app = typer.Typer(
|
|
17
|
+
help="SLOs as code: Prometheus rules and Grafana dashboards from YAML.", no_args_is_help=True
|
|
18
|
+
)
|
|
19
|
+
|
|
20
|
+
SpecsArg = Annotated[list[Path], typer.Argument(help="SLO spec files or directories.")]
|
|
21
|
+
|
|
22
|
+
_HEADER = "# Generated by slogen from slos/{service}.yaml. Do not edit; change the spec instead.\n"
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
class _Dumper(yaml.SafeDumper):
|
|
26
|
+
"""Multi-line strings (PromQL) as literal blocks, so generated rules stay readable."""
|
|
27
|
+
|
|
28
|
+
def ignore_aliases(self, data: Any) -> bool: # no &id001 anchors in generated files
|
|
29
|
+
return True
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
def _str(dumper: yaml.SafeDumper, value: str) -> yaml.ScalarNode:
|
|
33
|
+
style = "|" if "\n" in value else None
|
|
34
|
+
return dumper.represent_scalar("tag:yaml.org,2002:str", value, style=style)
|
|
35
|
+
|
|
36
|
+
|
|
37
|
+
_Dumper.add_representer(str, _str)
|
|
38
|
+
|
|
39
|
+
|
|
40
|
+
def render(service: ServiceSLOs) -> dict[str, str]:
|
|
41
|
+
"""Relative path -> file content for one service."""
|
|
42
|
+
rules = _HEADER.format(service=service.service) + yaml.dump(
|
|
43
|
+
{"groups": rule_groups(service)}, Dumper=_Dumper, sort_keys=False, width=1000
|
|
44
|
+
)
|
|
45
|
+
board = json.dumps(dashboard(service), indent=2) + "\n"
|
|
46
|
+
return {
|
|
47
|
+
f"prometheus/{service.service}.rules.yml": rules,
|
|
48
|
+
f"grafana/{service.service}.json": board,
|
|
49
|
+
}
|
|
50
|
+
|
|
51
|
+
|
|
52
|
+
def _load(specs: list[Path]) -> list[ServiceSLOs]:
|
|
53
|
+
try:
|
|
54
|
+
return load_all(specs)
|
|
55
|
+
except SpecError as exc:
|
|
56
|
+
typer.echo(str(exc), err=True)
|
|
57
|
+
raise typer.Exit(code=2) from exc
|
|
58
|
+
|
|
59
|
+
|
|
60
|
+
@app.command()
|
|
61
|
+
def validate(specs: SpecsArg) -> None:
|
|
62
|
+
"""Check spec files."""
|
|
63
|
+
for service in _load(specs):
|
|
64
|
+
objectives = ", ".join(f"{s.name} {s.objective}%" for s in service.slos)
|
|
65
|
+
typer.echo(f"ok {service.service}: {objectives}")
|
|
66
|
+
|
|
67
|
+
|
|
68
|
+
@app.command()
|
|
69
|
+
def generate(
|
|
70
|
+
specs: SpecsArg,
|
|
71
|
+
out: Annotated[Path, typer.Option(help="Output directory.")] = Path("generated"),
|
|
72
|
+
check: Annotated[bool, typer.Option(help="Fail if the files on disk are out of date.")] = False,
|
|
73
|
+
) -> None:
|
|
74
|
+
"""Write Prometheus rule files and Grafana dashboards."""
|
|
75
|
+
stale: list[str] = []
|
|
76
|
+
files: dict[str, Any] = {}
|
|
77
|
+
for service in _load(specs):
|
|
78
|
+
files |= render(service)
|
|
79
|
+
for relative, content in sorted(files.items()):
|
|
80
|
+
path = out / relative
|
|
81
|
+
current = path.read_text() if path.exists() else None
|
|
82
|
+
if current == content:
|
|
83
|
+
continue
|
|
84
|
+
if check:
|
|
85
|
+
stale.append(str(path))
|
|
86
|
+
continue
|
|
87
|
+
path.parent.mkdir(parents=True, exist_ok=True)
|
|
88
|
+
path.write_text(content)
|
|
89
|
+
typer.echo(f"wrote {path}")
|
|
90
|
+
if stale:
|
|
91
|
+
typer.echo("out of date (run `slogen generate slos`):\n " + "\n ".join(stale), err=True)
|
|
92
|
+
raise typer.Exit(code=1)
|
|
93
|
+
if check:
|
|
94
|
+
typer.echo(f"{len(files)} generated files are up to date")
|
|
@@ -0,0 +1,128 @@
|
|
|
1
|
+
"""Grafana dashboard per service: one row per SLO with SLI, budget and burn-rate panels."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
from typing import Any
|
|
6
|
+
|
|
7
|
+
from slo_toolkit.rules import PAGE, _num, selector
|
|
8
|
+
from slo_toolkit.spec import SLO, ServiceSLOs
|
|
9
|
+
|
|
10
|
+
_DATASOURCE = {"type": "prometheus", "uid": "${datasource}"}
|
|
11
|
+
|
|
12
|
+
|
|
13
|
+
def _target(expr: str, legend: str = "") -> dict[str, Any]:
|
|
14
|
+
return {"refId": legend or "A", "expr": expr, "legendFormat": legend, "datasource": _DATASOURCE}
|
|
15
|
+
|
|
16
|
+
|
|
17
|
+
def _stat(
|
|
18
|
+
title: str, expr: str, x: int, y: int, thresholds: list[dict[str, Any]], description: str
|
|
19
|
+
) -> dict[str, Any]:
|
|
20
|
+
return {
|
|
21
|
+
"type": "stat",
|
|
22
|
+
"title": title,
|
|
23
|
+
"description": description,
|
|
24
|
+
"datasource": _DATASOURCE,
|
|
25
|
+
"gridPos": {"h": 6, "w": 6, "x": x, "y": y},
|
|
26
|
+
"targets": [_target(expr)],
|
|
27
|
+
"fieldConfig": {
|
|
28
|
+
"defaults": {
|
|
29
|
+
"unit": "percentunit",
|
|
30
|
+
"decimals": 3,
|
|
31
|
+
"thresholds": {"mode": "absolute", "steps": thresholds},
|
|
32
|
+
}
|
|
33
|
+
},
|
|
34
|
+
"options": {"reduceOptions": {"calcs": ["lastNotNull"]}, "colorMode": "background"},
|
|
35
|
+
}
|
|
36
|
+
|
|
37
|
+
|
|
38
|
+
def _panels(service: ServiceSLOs, slo: SLO, y: int) -> list[dict[str, Any]]:
|
|
39
|
+
sel = selector(service, slo)
|
|
40
|
+
objective = slo.objective / 100
|
|
41
|
+
fast = PAGE[0].burn_rate
|
|
42
|
+
return [
|
|
43
|
+
{
|
|
44
|
+
"type": "row",
|
|
45
|
+
"title": f"{slo.name}: {_num(slo.objective)}% over {slo.window}",
|
|
46
|
+
"collapsed": False,
|
|
47
|
+
"gridPos": {"h": 1, "w": 24, "x": 0, "y": y},
|
|
48
|
+
"panels": [],
|
|
49
|
+
},
|
|
50
|
+
_stat(
|
|
51
|
+
f"SLI ({slo.window})",
|
|
52
|
+
f"1 - slo:sli_error:ratio_rate{slo.window}{{{sel}}}",
|
|
53
|
+
0,
|
|
54
|
+
y + 1,
|
|
55
|
+
[{"color": "red", "value": None}, {"color": "green", "value": objective}],
|
|
56
|
+
slo.description,
|
|
57
|
+
),
|
|
58
|
+
_stat(
|
|
59
|
+
"Error budget remaining",
|
|
60
|
+
f"slo:error_budget_remaining:ratio{{{sel}}}",
|
|
61
|
+
6,
|
|
62
|
+
y + 1,
|
|
63
|
+
[
|
|
64
|
+
{"color": "red", "value": None},
|
|
65
|
+
{"color": "orange", "value": 0},
|
|
66
|
+
{"color": "green", "value": 0.25},
|
|
67
|
+
],
|
|
68
|
+
"Share of this period's error budget still unspent. Below zero, the SLO is missed.",
|
|
69
|
+
),
|
|
70
|
+
{
|
|
71
|
+
"type": "timeseries",
|
|
72
|
+
"title": "Burn rate",
|
|
73
|
+
"description": f"1 = spending the budget exactly over {slo.window}. "
|
|
74
|
+
f"Paging threshold is {_num(fast)} (2% of the budget in one hour).",
|
|
75
|
+
"datasource": _DATASOURCE,
|
|
76
|
+
"gridPos": {"h": 6, "w": 12, "x": 12, "y": y + 1},
|
|
77
|
+
"targets": [
|
|
78
|
+
_target(f"slo:burn_rate:ratio_rate5m{{{sel}}}", "5m"),
|
|
79
|
+
_target(f"slo:burn_rate:ratio_rate1h{{{sel}}}", "1h"),
|
|
80
|
+
_target(f"slo:burn_rate:ratio_rate6h{{{sel}}}", "6h"),
|
|
81
|
+
],
|
|
82
|
+
"fieldConfig": {
|
|
83
|
+
"defaults": {
|
|
84
|
+
"unit": "none",
|
|
85
|
+
"custom": {"thresholdsStyle": {"mode": "line"}},
|
|
86
|
+
"thresholds": {
|
|
87
|
+
"mode": "absolute",
|
|
88
|
+
"steps": [
|
|
89
|
+
{"color": "green", "value": None},
|
|
90
|
+
{"color": "orange", "value": 1},
|
|
91
|
+
{"color": "red", "value": fast},
|
|
92
|
+
],
|
|
93
|
+
},
|
|
94
|
+
}
|
|
95
|
+
},
|
|
96
|
+
},
|
|
97
|
+
]
|
|
98
|
+
|
|
99
|
+
|
|
100
|
+
def dashboard(service: ServiceSLOs) -> dict[str, Any]:
|
|
101
|
+
panels: list[dict[str, Any]] = []
|
|
102
|
+
y = 0
|
|
103
|
+
for slo in service.slos:
|
|
104
|
+
panels += _panels(service, slo, y)
|
|
105
|
+
y += 7
|
|
106
|
+
for index, panel in enumerate(panels, start=1):
|
|
107
|
+
panel["id"] = index
|
|
108
|
+
return {
|
|
109
|
+
"uid": f"slo-{service.service}"[:40],
|
|
110
|
+
"title": f"SLOs: {service.service}",
|
|
111
|
+
"description": service.description
|
|
112
|
+
or f"Service level objectives for {service.service}, owned by {service.owner}.",
|
|
113
|
+
"tags": ["slo", service.service],
|
|
114
|
+
"schemaVersion": 39,
|
|
115
|
+
"time": {"from": "now-6h", "to": "now"},
|
|
116
|
+
"refresh": "30s",
|
|
117
|
+
"templating": {
|
|
118
|
+
"list": [
|
|
119
|
+
{
|
|
120
|
+
"name": "datasource",
|
|
121
|
+
"type": "datasource",
|
|
122
|
+
"query": "prometheus",
|
|
123
|
+
"label": "Prometheus",
|
|
124
|
+
}
|
|
125
|
+
]
|
|
126
|
+
},
|
|
127
|
+
"panels": panels,
|
|
128
|
+
}
|
slo_toolkit/py.typed
ADDED
|
File without changes
|
slo_toolkit/rules.py
ADDED
|
@@ -0,0 +1,162 @@
|
|
|
1
|
+
"""Prometheus rules: SLI recording rules, error-budget metadata and burn-rate alerts.
|
|
2
|
+
|
|
3
|
+
Alerting follows the Google SRE Workbook ("Alerting on SLOs", multiwindow, multi-burn-rate):
|
|
4
|
+
|
|
5
|
+
severity long short burn rate budget consumed when it fires
|
|
6
|
+
page 1h 5m 14.4 2% in one hour
|
|
7
|
+
page 6h 30m 6 5% in six hours
|
|
8
|
+
ticket 1d 2h 3 10% in one day
|
|
9
|
+
ticket 3d 6h 1 on track to spend the whole budget
|
|
10
|
+
|
|
11
|
+
Both windows must be over the threshold: the long one proves the problem is significant,
|
|
12
|
+
the short one makes the alert stop soon after the problem does.
|
|
13
|
+
"""
|
|
14
|
+
|
|
15
|
+
from __future__ import annotations
|
|
16
|
+
|
|
17
|
+
from dataclasses import dataclass
|
|
18
|
+
from typing import Any
|
|
19
|
+
|
|
20
|
+
from slo_toolkit.spec import SLO, ServiceSLOs
|
|
21
|
+
|
|
22
|
+
SLI_WINDOWS = ("5m", "30m", "1h", "2h", "6h", "1d", "3d")
|
|
23
|
+
|
|
24
|
+
|
|
25
|
+
@dataclass(frozen=True)
|
|
26
|
+
class BurnCondition:
|
|
27
|
+
long: str
|
|
28
|
+
short: str
|
|
29
|
+
burn_rate: float
|
|
30
|
+
|
|
31
|
+
|
|
32
|
+
PAGE = (BurnCondition("1h", "5m", 14.4), BurnCondition("6h", "30m", 6.0))
|
|
33
|
+
TICKET = (BurnCondition("1d", "2h", 3.0), BurnCondition("3d", "6h", 1.0))
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
def _num(value: float) -> str:
|
|
37
|
+
"""Stable float formatting for expressions (no 0.07200000000000001)."""
|
|
38
|
+
return f"{value:.10g}"
|
|
39
|
+
|
|
40
|
+
|
|
41
|
+
def _camel(*parts: str) -> str:
|
|
42
|
+
return "".join(
|
|
43
|
+
word.capitalize() for part in parts for word in part.replace("_", "-").split("-")
|
|
44
|
+
)
|
|
45
|
+
|
|
46
|
+
|
|
47
|
+
def slo_labels(service: ServiceSLOs, slo: SLO) -> dict[str, str]:
|
|
48
|
+
return {"slo_service": service.service, "slo_name": slo.name}
|
|
49
|
+
|
|
50
|
+
|
|
51
|
+
def selector(service: ServiceSLOs, slo: SLO) -> str:
|
|
52
|
+
return f'slo_service="{service.service}",slo_name="{slo.name}"'
|
|
53
|
+
|
|
54
|
+
|
|
55
|
+
def error_ratio_expr(slo: SLO, window: str) -> str:
|
|
56
|
+
if slo.sli.ratio is not None:
|
|
57
|
+
errors = slo.sli.ratio.errors.replace("{{window}}", window)
|
|
58
|
+
total = slo.sli.ratio.total.replace("{{window}}", window)
|
|
59
|
+
# No error series yet (no 5xx ever seen) must read as 0 errors, not as missing data;
|
|
60
|
+
# otherwise dashboards show gaps and the period average skips healthy time.
|
|
61
|
+
return f"(\n {errors}\n or vector(0)\n)\n/\n(\n {total}\n)"
|
|
62
|
+
latency = slo.sli.latency
|
|
63
|
+
if latency is None: # unreachable: the SLI validator requires ratio or latency
|
|
64
|
+
raise ValueError(f"SLO {slo.name} has no SLI")
|
|
65
|
+
extra = f"{latency.selector}," if latency.selector else ""
|
|
66
|
+
good = f'sum(rate({latency.histogram}_bucket{{{extra}le="{latency.le}"}}[{window}]))'
|
|
67
|
+
total = f"sum(rate({latency.histogram}_count{{{latency.selector}}}[{window}]))"
|
|
68
|
+
return f"1 - (\n {good}\n /\n {total}\n)"
|
|
69
|
+
|
|
70
|
+
|
|
71
|
+
def _sli_group(service: ServiceSLOs, slo: SLO) -> dict[str, Any]:
|
|
72
|
+
labels = slo_labels(service, slo)
|
|
73
|
+
return {
|
|
74
|
+
"name": f"slo:{service.service}:{slo.name}:sli",
|
|
75
|
+
"rules": [
|
|
76
|
+
{
|
|
77
|
+
"record": f"slo:sli_error:ratio_rate{window}",
|
|
78
|
+
"expr": error_ratio_expr(slo, window),
|
|
79
|
+
"labels": labels,
|
|
80
|
+
}
|
|
81
|
+
for window in SLI_WINDOWS
|
|
82
|
+
],
|
|
83
|
+
}
|
|
84
|
+
|
|
85
|
+
|
|
86
|
+
def _meta_group(service: ServiceSLOs, slo: SLO) -> dict[str, Any]:
|
|
87
|
+
labels = slo_labels(service, slo)
|
|
88
|
+
sel = selector(service, slo)
|
|
89
|
+
budget = _num(slo.error_budget)
|
|
90
|
+
period = slo.window
|
|
91
|
+
return {
|
|
92
|
+
"name": f"slo:{service.service}:{slo.name}:meta",
|
|
93
|
+
"rules": [
|
|
94
|
+
{
|
|
95
|
+
"record": "slo:objective:ratio",
|
|
96
|
+
"expr": f"vector({_num(slo.objective / 100)})",
|
|
97
|
+
"labels": labels,
|
|
98
|
+
},
|
|
99
|
+
{"record": "slo:error_budget:ratio", "expr": f"vector({budget})", "labels": labels},
|
|
100
|
+
{
|
|
101
|
+
# Average of the 5m ratio over the SLO period: cheap, and exact for steady traffic.
|
|
102
|
+
"record": f"slo:sli_error:ratio_rate{period}",
|
|
103
|
+
"expr": (
|
|
104
|
+
f"sum_over_time(slo:sli_error:ratio_rate5m{{{sel}}}[{period}])\n"
|
|
105
|
+
f"/\ncount_over_time(slo:sli_error:ratio_rate5m{{{sel}}}[{period}])"
|
|
106
|
+
),
|
|
107
|
+
"labels": labels,
|
|
108
|
+
},
|
|
109
|
+
{
|
|
110
|
+
"record": "slo:error_budget_remaining:ratio",
|
|
111
|
+
"expr": f"1 - (slo:sli_error:ratio_rate{period}{{{sel}}} / {budget})",
|
|
112
|
+
"labels": labels,
|
|
113
|
+
},
|
|
114
|
+
*(
|
|
115
|
+
{
|
|
116
|
+
"record": f"slo:burn_rate:ratio_rate{window}",
|
|
117
|
+
"expr": f"slo:sli_error:ratio_rate{window}{{{sel}}} / {budget}",
|
|
118
|
+
"labels": labels,
|
|
119
|
+
}
|
|
120
|
+
for window in ("5m", "1h", "6h", "1d")
|
|
121
|
+
),
|
|
122
|
+
],
|
|
123
|
+
}
|
|
124
|
+
|
|
125
|
+
|
|
126
|
+
def _alert(
|
|
127
|
+
service: ServiceSLOs, slo: SLO, severity: str, conditions: tuple[BurnCondition, ...]
|
|
128
|
+
) -> dict[str, Any]:
|
|
129
|
+
sel = selector(service, slo)
|
|
130
|
+
budget = slo.error_budget
|
|
131
|
+
clauses = [
|
|
132
|
+
f"(\n slo:sli_error:ratio_rate{c.long}{{{sel}}} > {_num(c.burn_rate * budget)}\n"
|
|
133
|
+
f" and\n slo:sli_error:ratio_rate{c.short}{{{sel}}} > {_num(c.burn_rate * budget)}\n)"
|
|
134
|
+
for c in conditions
|
|
135
|
+
]
|
|
136
|
+
speed = "fast" if severity == "page" else "slow"
|
|
137
|
+
annotations = {
|
|
138
|
+
"summary": f"{service.service} {slo.name}: error budget burning {speed}",
|
|
139
|
+
"description": f"{slo.description} Objective {_num(slo.objective)}% over {slo.window}.",
|
|
140
|
+
}
|
|
141
|
+
if slo.alerting.runbook_url:
|
|
142
|
+
annotations["runbook_url"] = slo.alerting.runbook_url
|
|
143
|
+
return {
|
|
144
|
+
"alert": _camel(service.service, slo.name, f"{speed}-burn"),
|
|
145
|
+
"expr": "\nor\n".join(clauses),
|
|
146
|
+
"labels": {**slo_labels(service, slo), "severity": severity},
|
|
147
|
+
"annotations": annotations,
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
|
|
151
|
+
def rule_groups(service: ServiceSLOs) -> list[dict[str, Any]]:
|
|
152
|
+
groups: list[dict[str, Any]] = []
|
|
153
|
+
for slo in service.slos:
|
|
154
|
+
groups += [_sli_group(service, slo), _meta_group(service, slo)]
|
|
155
|
+
alerts = []
|
|
156
|
+
if slo.alerting.page:
|
|
157
|
+
alerts.append(_alert(service, slo, "page", PAGE))
|
|
158
|
+
if slo.alerting.ticket:
|
|
159
|
+
alerts.append(_alert(service, slo, "ticket", TICKET))
|
|
160
|
+
if alerts:
|
|
161
|
+
groups.append({"name": f"slo:{service.service}:{slo.name}:alerts", "rules": alerts})
|
|
162
|
+
return groups
|
slo_toolkit/spec.py
ADDED
|
@@ -0,0 +1,126 @@
|
|
|
1
|
+
"""SLO specification: one YAML file per service (see slos/)."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import re
|
|
6
|
+
from pathlib import Path
|
|
7
|
+
|
|
8
|
+
import yaml
|
|
9
|
+
from pydantic import BaseModel, ConfigDict, Field, ValidationError, field_validator, model_validator
|
|
10
|
+
|
|
11
|
+
_WINDOW = re.compile(r"^\d+[mhd]$")
|
|
12
|
+
_METRIC = r"^[a-zA-Z_:][a-zA-Z0-9_:]*$"
|
|
13
|
+
|
|
14
|
+
|
|
15
|
+
class _Strict(BaseModel):
|
|
16
|
+
model_config = ConfigDict(extra="forbid")
|
|
17
|
+
|
|
18
|
+
|
|
19
|
+
class RatioSLI(_Strict):
|
|
20
|
+
"""Error ratio = errors / total. Write ``{{window}}`` where the range goes:
|
|
21
|
+
``sum(rate(http_requests_total{code=~"5.."}[{{window}}]))``."""
|
|
22
|
+
|
|
23
|
+
errors: str
|
|
24
|
+
total: str
|
|
25
|
+
|
|
26
|
+
@field_validator("errors", "total")
|
|
27
|
+
@classmethod
|
|
28
|
+
def _needs_window(cls, value: str) -> str:
|
|
29
|
+
if "{{window}}" not in value:
|
|
30
|
+
raise ValueError(
|
|
31
|
+
"query must use {{window}} as its range, e.g. rate(metric[{{window}}])"
|
|
32
|
+
)
|
|
33
|
+
return value.strip()
|
|
34
|
+
|
|
35
|
+
|
|
36
|
+
class LatencySLI(_Strict):
|
|
37
|
+
"""Good events are requests faster than ``threshold`` seconds, read from a classic
|
|
38
|
+
Prometheus histogram. ``threshold`` must be one of the histogram's bucket bounds."""
|
|
39
|
+
|
|
40
|
+
histogram: str = Field(pattern=_METRIC) # metric name without _bucket / _count
|
|
41
|
+
threshold: float = Field(gt=0)
|
|
42
|
+
selector: str = "" # extra matchers, e.g. job="llm-gateway"
|
|
43
|
+
|
|
44
|
+
@property
|
|
45
|
+
def le(self) -> str:
|
|
46
|
+
"""Bucket label as Prometheus 3 stores it (normalised float: 8 -> "8.0")."""
|
|
47
|
+
return repr(float(self.threshold))
|
|
48
|
+
|
|
49
|
+
|
|
50
|
+
class SLI(_Strict):
|
|
51
|
+
ratio: RatioSLI | None = None
|
|
52
|
+
latency: LatencySLI | None = None
|
|
53
|
+
|
|
54
|
+
@model_validator(mode="after")
|
|
55
|
+
def _exactly_one(self) -> SLI:
|
|
56
|
+
if (self.ratio is None) == (self.latency is None):
|
|
57
|
+
raise ValueError("set exactly one of ratio or latency")
|
|
58
|
+
return self
|
|
59
|
+
|
|
60
|
+
|
|
61
|
+
class Alerting(_Strict):
|
|
62
|
+
page: bool = True
|
|
63
|
+
ticket: bool = True
|
|
64
|
+
runbook_url: str | None = None
|
|
65
|
+
|
|
66
|
+
|
|
67
|
+
class SLO(_Strict):
|
|
68
|
+
name: str = Field(pattern=r"^[a-z0-9][a-z0-9-]*$")
|
|
69
|
+
description: str
|
|
70
|
+
objective: float = Field(gt=0, lt=100, description="Target percentage, e.g. 99.9")
|
|
71
|
+
window: str = "30d"
|
|
72
|
+
sli: SLI
|
|
73
|
+
alerting: Alerting = Field(default_factory=Alerting)
|
|
74
|
+
|
|
75
|
+
@field_validator("window")
|
|
76
|
+
@classmethod
|
|
77
|
+
def _window(cls, value: str) -> str:
|
|
78
|
+
if not _WINDOW.match(value):
|
|
79
|
+
raise ValueError("window must look like 28d, 30d or 7d")
|
|
80
|
+
return value
|
|
81
|
+
|
|
82
|
+
@property
|
|
83
|
+
def error_budget(self) -> float:
|
|
84
|
+
"""Allowed error ratio, e.g. 0.001 for a 99.9% objective."""
|
|
85
|
+
return round(1 - self.objective / 100, 12)
|
|
86
|
+
|
|
87
|
+
|
|
88
|
+
class ServiceSLOs(_Strict):
|
|
89
|
+
service: str = Field(pattern=r"^[a-z0-9][a-z0-9-]*$")
|
|
90
|
+
owner: str
|
|
91
|
+
description: str = ""
|
|
92
|
+
slos: list[SLO] = Field(min_length=1)
|
|
93
|
+
|
|
94
|
+
@model_validator(mode="after")
|
|
95
|
+
def _unique_names(self) -> ServiceSLOs:
|
|
96
|
+
names = [s.name for s in self.slos]
|
|
97
|
+
if duplicates := sorted({n for n in names if names.count(n) > 1}):
|
|
98
|
+
raise ValueError(f"duplicate SLO names: {duplicates}")
|
|
99
|
+
return self
|
|
100
|
+
|
|
101
|
+
|
|
102
|
+
class SpecError(ValueError):
|
|
103
|
+
"""A spec file is missing or invalid."""
|
|
104
|
+
|
|
105
|
+
|
|
106
|
+
def load(path: Path) -> ServiceSLOs:
|
|
107
|
+
try:
|
|
108
|
+
return ServiceSLOs.model_validate(yaml.safe_load(path.read_text()))
|
|
109
|
+
except (OSError, yaml.YAMLError) as exc:
|
|
110
|
+
raise SpecError(f"{path}: {exc}") from exc
|
|
111
|
+
except ValidationError as exc:
|
|
112
|
+
problems = "\n".join(
|
|
113
|
+
f" {'.'.join(map(str, e['loc'])) or '<root>'}: {e['msg']}" for e in exc.errors()
|
|
114
|
+
)
|
|
115
|
+
raise SpecError(f"{path}:\n{problems}") from exc
|
|
116
|
+
|
|
117
|
+
|
|
118
|
+
def load_all(paths: list[Path]) -> list[ServiceSLOs]:
|
|
119
|
+
files: list[Path] = []
|
|
120
|
+
for path in paths:
|
|
121
|
+
files += sorted(path.glob("*.y*ml")) if path.is_dir() else [path]
|
|
122
|
+
specs = [load(f) for f in files]
|
|
123
|
+
services = [s.service for s in specs]
|
|
124
|
+
if duplicates := sorted({s for s in services if services.count(s) > 1}):
|
|
125
|
+
raise SpecError(f"services defined twice: {duplicates}")
|
|
126
|
+
return specs
|
|
@@ -0,0 +1,195 @@
|
|
|
1
|
+
Metadata-Version: 2.5
|
|
2
|
+
Name: slo-toolkit
|
|
3
|
+
Version: 0.1.1
|
|
4
|
+
Summary: SLOs as code: generate Prometheus multi-window, multi-burn-rate alerts and Grafana dashboards from YAML, verified with promtool.
|
|
5
|
+
Project-URL: Homepage, https://github.com/MuhFawad1/monitoring-observability-stack
|
|
6
|
+
Project-URL: Source, https://github.com/MuhFawad1/monitoring-observability-stack
|
|
7
|
+
Project-URL: Issues, https://github.com/MuhFawad1/monitoring-observability-stack/issues
|
|
8
|
+
Project-URL: Changelog, https://github.com/MuhFawad1/monitoring-observability-stack/releases
|
|
9
|
+
Author: Muhammad Fawad
|
|
10
|
+
License-Expression: MIT
|
|
11
|
+
License-File: LICENSE
|
|
12
|
+
Keywords: alerting,error-budget,grafana,prometheus,slo,sre
|
|
13
|
+
Classifier: Development Status :: 3 - Alpha
|
|
14
|
+
Classifier: Intended Audience :: Developers
|
|
15
|
+
Classifier: Intended Audience :: System Administrators
|
|
16
|
+
Classifier: Programming Language :: Python :: 3
|
|
17
|
+
Classifier: Programming Language :: Python :: 3.12
|
|
18
|
+
Classifier: Topic :: System :: Monitoring
|
|
19
|
+
Classifier: Typing :: Typed
|
|
20
|
+
Requires-Python: >=3.12
|
|
21
|
+
Requires-Dist: pydantic>=2.8
|
|
22
|
+
Requires-Dist: pyyaml>=6.0
|
|
23
|
+
Requires-Dist: typer>=0.12
|
|
24
|
+
Description-Content-Type: text/markdown
|
|
25
|
+
|
|
26
|
+
# monitoring-observability-stack: SLOs as code
|
|
27
|
+
|
|
28
|
+
[](https://github.com/MuhFawad1/monitoring-observability-stack/actions/workflows/ci.yml)
|
|
29
|
+

|
|
30
|
+

|
|
31
|
+
[](LICENSE)
|
|
32
|
+
|
|
33
|
+
Define service level objectives in a few lines of YAML; `slogen` generates the
|
|
34
|
+
Prometheus recording rules, error-budget metrics, multi-window multi-burn-rate alerts
|
|
35
|
+
and Grafana dashboards. The alerts are unit-tested with promtool, and a local stack
|
|
36
|
+
runs them against a live service.
|
|
37
|
+
|
|
38
|
+
The example SLOs cover two real services from this portfolio: the
|
|
39
|
+
[llm-gateway](https://github.com/MuhFawad1/llm-gateway) and the scoring API of the
|
|
40
|
+
[mlops-platform](https://github.com/MuhFawad1/mlops-platform). They use the metrics those
|
|
41
|
+
services actually export.
|
|
42
|
+
|
|
43
|
+
## Why
|
|
44
|
+
|
|
45
|
+
Alerting on CPU or on "error rate above 1% for 5 minutes" pages people for blips users
|
|
46
|
+
never notice, and misses slow leaks that blow a monthly objective. Burn-rate alerting
|
|
47
|
+
(Google SRE Workbook) pages only when the error budget is being spent fast enough to
|
|
48
|
+
matter, and resets quickly once the problem stops.
|
|
49
|
+
|
|
50
|
+
```mermaid
|
|
51
|
+
flowchart LR
|
|
52
|
+
S[slos/*.yaml] --> G[slogen generate]
|
|
53
|
+
G --> R[generated/prometheus<br/>recording rules + alerts]
|
|
54
|
+
G --> D[generated/grafana<br/>dashboards]
|
|
55
|
+
R --> T{{promtool unit tests}}
|
|
56
|
+
R --> P[Prometheus] --> A[Alertmanager<br/>page / ticket]
|
|
57
|
+
D --> F[Grafana]
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
## A spec
|
|
61
|
+
|
|
62
|
+
```yaml
|
|
63
|
+
service: llm-gateway
|
|
64
|
+
owner: ai-platform
|
|
65
|
+
slos:
|
|
66
|
+
- name: availability
|
|
67
|
+
description: Chat requests that do not fail on the gateway side.
|
|
68
|
+
objective: 99.5
|
|
69
|
+
window: 30d
|
|
70
|
+
sli:
|
|
71
|
+
ratio:
|
|
72
|
+
errors: sum(rate(llm_gateway_requests_total{status=~"5.."}[{{window}}]))
|
|
73
|
+
total: sum(rate(llm_gateway_requests_total[{{window}}]))
|
|
74
|
+
alerting:
|
|
75
|
+
runbook_url: https://github.com/MuhFawad1/monitoring-observability-stack/blob/main/docs/runbooks/llm-gateway-availability.md
|
|
76
|
+
- name: upstream-latency
|
|
77
|
+
description: Upstream model calls that answer within 8 seconds.
|
|
78
|
+
objective: 95
|
|
79
|
+
sli:
|
|
80
|
+
latency:
|
|
81
|
+
histogram: llm_gateway_upstream_duration_seconds
|
|
82
|
+
threshold: 8
|
|
83
|
+
alerting:
|
|
84
|
+
page: false
|
|
85
|
+
```
|
|
86
|
+
|
|
87
|
+
Each SLO becomes:
|
|
88
|
+
- seven SLI windows (5m through 3d) plus the 30-day SLI
|
|
89
|
+
- objective, budget, budget-remaining and burn-rate series
|
|
90
|
+
- a **page** alert (14.4× over 1h/5m, or 6× over 6h/30m)
|
|
91
|
+
- a **ticket** alert (3× over 1d/2h, or 1× over 3d/6h)
|
|
92
|
+
|
|
93
|
+
The generated page alert, for a 99.5% objective:
|
|
94
|
+
|
|
95
|
+
```yaml
|
|
96
|
+
- alert: LlmGatewayAvailabilityFastBurn
|
|
97
|
+
expr: |-
|
|
98
|
+
(
|
|
99
|
+
slo:sli_error:ratio_rate1h{slo_service="llm-gateway",slo_name="availability"} > 0.072
|
|
100
|
+
and
|
|
101
|
+
slo:sli_error:ratio_rate5m{slo_service="llm-gateway",slo_name="availability"} > 0.072
|
|
102
|
+
)
|
|
103
|
+
or
|
|
104
|
+
(
|
|
105
|
+
slo:sli_error:ratio_rate6h{slo_service="llm-gateway",slo_name="availability"} > 0.03
|
|
106
|
+
and
|
|
107
|
+
slo:sli_error:ratio_rate30m{slo_service="llm-gateway",slo_name="availability"} > 0.03
|
|
108
|
+
)
|
|
109
|
+
labels: {slo_service: llm-gateway, slo_name: availability, severity: page}
|
|
110
|
+
```
|
|
111
|
+
|
|
112
|
+
## Install
|
|
113
|
+
|
|
114
|
+
The generator is published on PyPI as `slo-toolkit`; the command is `slogen`.
|
|
115
|
+
|
|
116
|
+
```bash
|
|
117
|
+
pip install slo-toolkit # or: uv tool install slo-toolkit
|
|
118
|
+
slogen validate slos && slogen generate slos
|
|
119
|
+
```
|
|
120
|
+
|
|
121
|
+
Releases are published from GitHub Actions with trusted publishing, so no PyPI token is
|
|
122
|
+
stored anywhere, and every file carries a signed attestation of the workflow that built it.
|
|
123
|
+
|
|
124
|
+
## Quickstart
|
|
125
|
+
|
|
126
|
+
```bash
|
|
127
|
+
uv sync
|
|
128
|
+
uv run slogen validate slos
|
|
129
|
+
uv run slogen generate slos # writes generated/prometheus/*.rules.yml and generated/grafana/*.json
|
|
130
|
+
make test # pytest, freshness check, promtool check + alert tests
|
|
131
|
+
```
|
|
132
|
+
|
|
133
|
+
## The alerts are tested, not eyeballed
|
|
134
|
+
|
|
135
|
+
[`tests/promtool/`](tests/promtool) feeds synthetic traffic through the generated rules:
|
|
136
|
+
|
|
137
|
+
| Scenario | Expected |
|
|
138
|
+
|---|---|
|
|
139
|
+
| Healthy traffic for 3 hours | no page, no ticket |
|
|
140
|
+
| No 5xx series has ever existed | SLI reads 0, not "no data" |
|
|
141
|
+
| Hard outage (17% errors) after two healthy hours | no page 4 minutes in; page by minute 40 |
|
|
142
|
+
| Steady 2% errors for 25 hours | ticket, never a page |
|
|
143
|
+
| 80% of upstream calls slower than 8s | latency ticket (paging disabled for that SLO) |
|
|
144
|
+
| Scoring API at 99.9%: a 9% error spike | page within the hour |
|
|
145
|
+
|
|
146
|
+
## Run it live
|
|
147
|
+
|
|
148
|
+
```bash
|
|
149
|
+
make up # 2% errors: watch a slow burn
|
|
150
|
+
ERROR_PERCENT=20 make up # an outage: fast burn
|
|
151
|
+
```
|
|
152
|
+
|
|
153
|
+
The stack runs the published `ghcr.io/muhfawad1/llm-gateway:0.1.0` image with mock
|
|
154
|
+
upstreams under synthetic traffic, plus:
|
|
155
|
+
- Prometheus loading the generated rules
|
|
156
|
+
- Alertmanager routing pages and tickets separately, and suppressing a ticket while the
|
|
157
|
+
same SLO is paging
|
|
158
|
+
- Grafana with the generated dashboards: [localhost:3000](http://localhost:3000)
|
|
159
|
+
|
|
160
|
+
CI starts this stack on every change and asserts that the SLI series appear, that no
|
|
161
|
+
rule has an evaluation error, and that the dashboard loads.
|
|
162
|
+
|
|
163
|
+
## Design decisions
|
|
164
|
+
|
|
165
|
+
| ADR | Decision |
|
|
166
|
+
|---|---|
|
|
167
|
+
| [0001](docs/adr/0001-multiwindow-multi-burn-rate-alerts.md) | Alert on budget burn over two windows, not on raw thresholds |
|
|
168
|
+
| [0002](docs/adr/0002-generate-and-test-rules.md) | Generate rules from specs, commit the output, test it with promtool |
|
|
169
|
+
| [0003](docs/adr/0003-what-counts-as-an-error.md) | What counts as an error, and the PromQL edge cases that keep SLIs honest |
|
|
170
|
+
|
|
171
|
+
Runbook referenced by the llm-gateway alerts:
|
|
172
|
+
[docs/runbooks/llm-gateway-availability.md](docs/runbooks/llm-gateway-availability.md).
|
|
173
|
+
|
|
174
|
+
## Layout
|
|
175
|
+
|
|
176
|
+
```text
|
|
177
|
+
slos/ one spec per service
|
|
178
|
+
src/slo_toolkit/ spec model, rule and dashboard generators, CLI (slogen)
|
|
179
|
+
generated/ committed output: Prometheus rules, Grafana dashboards
|
|
180
|
+
tests/ generator unit tests; promtool/ alert tests
|
|
181
|
+
stack/ local Prometheus, Alertmanager, Grafana, llm-gateway, traffic
|
|
182
|
+
docs/ ADRs and runbooks
|
|
183
|
+
```
|
|
184
|
+
|
|
185
|
+
## Roadmap
|
|
186
|
+
|
|
187
|
+
- Emit `PrometheusRule` resources for the Prometheus Operator next to plain rule files.
|
|
188
|
+
- Import OpenSLO v1 specs.
|
|
189
|
+
- Per-tenant SLOs (grouped by a label such as `team`) with per-tenant budgets.
|
|
190
|
+
- A monthly budget report (Markdown) for service reviews.
|
|
191
|
+
- Synthetic-probe SLIs (blackbox exporter) for low-traffic services.
|
|
192
|
+
|
|
193
|
+
## License
|
|
194
|
+
|
|
195
|
+
[MIT](LICENSE)
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
slo_toolkit/__init__.py,sha256=mPy429jDupC_7YWMuZQ_zABqD0yeISDjrYphEHFvs5M,98
|
|
2
|
+
slo_toolkit/cli.py,sha256=aGRydegwxlY6gKrNrGOiajzXm1j7PKaPqvhjaDxIOQQ,3108
|
|
3
|
+
slo_toolkit/dashboards.py,sha256=bKCTfLvnUnboEJ465QNKlwa2r-2RVtof6LlbyGIKyPk,4405
|
|
4
|
+
slo_toolkit/py.typed,sha256=47DEQpj8HBSa-_TImW-5JCeuQeRkm5NMpJWZG3hSuFU,0
|
|
5
|
+
slo_toolkit/rules.py,sha256=pzAczjK6_PkqlcdwvQ0EOkgwz82H4Fu5NDss2XV709k,6094
|
|
6
|
+
slo_toolkit/spec.py,sha256=kx4Mp5nX5BP6HxujwMU9vFzDhJvzW3TNrQcAXUygnDo,3955
|
|
7
|
+
slo_toolkit-0.1.1.dist-info/METADATA,sha256=fGD5ciRjGP3OzW_GAmBUKYXBmE-yIzD2Nw4Z0YKo3ag,7580
|
|
8
|
+
slo_toolkit-0.1.1.dist-info/WHEEL,sha256=2iZrJkDIkeDh0k9SikKMqFuRP-ua6mb4Ir1AsER4BEw,87
|
|
9
|
+
slo_toolkit-0.1.1.dist-info/entry_points.txt,sha256=htJEcb7rxRkLFhB-C1XRYdquzA5yF_lzwHJk8WGDZ4I,47
|
|
10
|
+
slo_toolkit-0.1.1.dist-info/licenses/LICENSE,sha256=f2gypWTehd4xFtc4Ob36PpSOcIE9aa6qEJo9WU5oCAs,1071
|
|
11
|
+
slo_toolkit-0.1.1.dist-info/RECORD,,
|
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
MIT License
|
|
2
|
+
|
|
3
|
+
Copyright (c) 2026 Muhammad Fawad
|
|
4
|
+
|
|
5
|
+
Permission is hereby granted, free of charge, to any person obtaining a copy
|
|
6
|
+
of this software and associated documentation files (the "Software"), to deal
|
|
7
|
+
in the Software without restriction, including without limitation the rights
|
|
8
|
+
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
|
|
9
|
+
copies of the Software, and to permit persons to whom the Software is
|
|
10
|
+
furnished to do so, subject to the following conditions:
|
|
11
|
+
|
|
12
|
+
The above copyright notice and this permission notice shall be included in all
|
|
13
|
+
copies or substantial portions of the Software.
|
|
14
|
+
|
|
15
|
+
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
|
16
|
+
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
|
|
17
|
+
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
|
|
18
|
+
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
|
|
19
|
+
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
|
|
20
|
+
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
|
|
21
|
+
SOFTWARE.
|