Files
mtusi2026lab6/research/trace_demo.py

84 lines
4.2 KiB
Python
Raw Permalink Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
#!/usr/bin/env python3
"""Демонстрация на защите: один upload → trace от HTTP до worker/S3/DB, логи API и worker того же trace,
ссылка для Grafana Explore. С --retry имя файла содержит fault-transient-1 (FAULT_HOOKS=lab): первая попытка
падает «временно», вторая проходит — обе в одном trace.
python3 research/trace_demo.py [--retry]
"""
import argparse
import json
import sys
import time
import urllib.parse
from pathlib import Path
sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "student-tests"))
from common import BASE_URL, Client, login, new_user, upload, wait_status # noqa: E402
from obs import GRAFANA_URL, Grafana, wait_for # noqa: E402
def explore_link(trace_id):
panes = {"a": {"datasource": "tempo", "queries": [{"refId": "A", "datasource": {"type": "tempo", "uid": "tempo"},
"queryType": "traceql", "query": trace_id}],
"range": {"from": "now-6h", "to": "now"}}}
return GRAFANA_URL + "/explore?schemaVersion=1&orgId=1&panes=" + urllib.parse.quote(json.dumps(panes, separators=(",", ":")))
def tree(spans):
kids = {}
for s in spans:
kids.setdefault(s["parent"], []).append(s)
ids = {s["span_id"] for s in spans}
lines = []
def walk(pid, d):
for s in sorted(kids.get(pid, []), key=lambda x: x["start"]):
extra = []
for k in ("messenger.job.attempt", "messenger.job.outcome", "error.type", "http.response.status_code"):
if k in s["attrs"]:
extra.append("%s=%s" % (k.split(".")[-1], s["attrs"][k]))
lines.append("%s%-40s %-17s %-8s %8.1f мс %s" % (" " * d, s["name"][:40], s["service"], s["kind"],
(s["end"] - s["start"]) * 1000, " ".join(extra)))
walk(s["span_id"], d + 1)
for root in [p for p in kids if p not in ids]:
walk(root, 0)
return lines
def main():
ap = argparse.ArgumentParser()
ap.add_argument("--retry", action="store_true")
a = ap.parse_args()
c, g = Client(BASE_URL), Grafana()
u = new_user(c, "demo")
login(c, u)
chat = c.call("POST", "/api/v1/chats", 201, actor=u, schema="Chat", body={"title": "demo", "member_ids": [u["id"]]})["json"]
t0 = time.time()
att, _ = upload(c, u, chat, filename="demo-fault-transient-1.png" if a.retry else "demo.png")
print("upload: 202, attachment_id=%s, status=%s" % (att["id"], att["status"]))
ready = wait_status(c, u, att["id"], "ready", timeout=90)
print("ready через %.1f с, варианты: %s" % (time.time() - t0, [v["name"] for v in ready["variants"]]))
def find():
tr = g.search('{ span.messenger.attachment.id = "%s" }' % att["id"], since=900)
spans = g.trace(tr[0]["traceID"]) if tr else None
return spans if spans and any(s["attrs"].get("messenger.job.outcome") == "ready" for s in spans) else None
spans = wait_for(find, 60, what="trace")
tid = spans[0]["trace_id"]
print("\nTraceQL: { span.messenger.attachment.id = \"%s\" }\ntrace_id: %s (%d spans)\n" % (att["id"], tid, len(spans)))
print("\n".join(tree(spans)))
print("\nЛоги того же trace (Loki: {service_name=~\"messenger-.*\"} | trace_id=\"%s\"):" % tid)
q = '{service_name=~"messenger-api|messenger-worker"} | trace_id="%s"' % tid
# логи доходят батчами (SDK 1 с + Collector 2 с): ждём записи обоих сервисов, не дольше 20 с
recs = wait_for(lambda: (lambda rs: rs if {r["service_name"] for r in rs} >= {"messenger-api", "messenger-worker"}
else None)(g.loki(q, since=900)), 20, what="logs of both services")
for r in recs:
fields = {k: r[k] for k in ("event", "attempt", "outcome", "error_code", "route", "status") if k in r}
print(" %s %-16s %-5s %s" % (time.strftime("%H:%M:%S", time.localtime(r["ts"])), r["service_name"],
r.get("severity_text", ""), json.dumps(fields, ensure_ascii=False)))
print("\nGrafana Explore (после входа admin):\n" + explore_link(tid))
if __name__ == "__main__":
main()