3ambench / src /alertforge /data /range2test
openenvforge's picture
3amBench v0.2.0
44084af verified
Raw History Blame Contribute Delete
2.6 kB
#!/usr/bin/env python3
# range2test: turn /api/v1/query_range JSON into a promtool test skeleton so you can
# replay an incident against a rules branch. Written during INC-3920, works on the API's
# JSON (not Grafana CSV). Gaps become `_`. Prometheus would have written stale markers
# for a target that went away, so absent()-style onsets come out a few minutes late
# here; add `stale` by hand if that matters. Step must be a multiple of 1m.
#
# bin/range2test incidents/INC-1234/query-range/*.json > /tmp/replay.test.yml
# promtool test rules /tmp/replay.test.yml (after pointing rule_files at your rules)
#
# Several files are merged into one test; the earliest timestamp across them is minute 0.
# Timestamps are printed as a comment so you can line eval_time up with the timeline.
import json
import sys
import time
def fmt(v):
f = float(v)
return str(int(f)) if f == int(f) else repr(f)
def main(paths):
if not paths:
print(__doc__ or "usage: range2test <query_range.json>...", file=sys.stderr)
return 2
series, t0, step = [], None, None
for p in paths:
with open(p) as fh:
doc = json.load(fh)
for r in doc["data"]["result"]:
ts = [int(float(x[0])) for x in r["values"]]
t0 = min(ts) if t0 is None else min(t0, ts[0])
if len(ts) > 1:
d = min(b - a for a, b in zip(ts, ts[1:]))
step = d if step is None else min(step, d)
series.append(r)
step = step or 60
if step % 60:
print(f"step {step}s is not a multiple of 1m", file=sys.stderr)
return 1
out = ["# generated by bin/range2test from " + ", ".join(paths),
f"# minute 0 = {time.strftime('%Y-%m-%dT%H:%M:%SZ', time.gmtime(t0))}",
"rule_files:", " - ../rules/*.yml", "evaluation_interval: 1m", "tests:",
f" - interval: {step // 60}m", " input_series:"]
for r in series:
m = dict(r["metric"])
name = m.pop("__name__", "")
sel = name + "{" + ",".join(f'{k}="{v}"' for k, v in sorted(m.items())) + "}"
byt = {int(float(t)): v for t, v in r["values"]}
last = max(byt)
vals = []
t = t0
while t <= last:
vals.append(fmt(byt[t]) if t in byt else "_")
t += step
out.append(f" - series: '{sel}'")
out.append(f" values: '{' '.join(vals)}'")
out += [" alert_rule_test: []", " promql_expr_test: []"]
print("\n".join(out))
return 0
if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))