|
| 1 | +#!/usr/bin/env python3 |
| 2 | +"""Fetch the latest Jaeger trace for a service and render it as a Mermaid Gantt chart. |
| 3 | +
|
| 4 | +Usage: trace-to-mermaid.py <service_name> [min_ms] |
| 5 | +
|
| 6 | +Arguments: |
| 7 | + service_name Jaeger service name (e.g., "nerdbox") |
| 8 | + min_ms Minimum span duration in ms to include (default: 1) |
| 9 | +
|
| 10 | +Environment: |
| 11 | + JAEGER_URL Jaeger base URL (default: http://localhost:16686) |
| 12 | +""" |
| 13 | +import json |
| 14 | +import sys |
| 15 | +import tempfile |
| 16 | +import urllib.request |
| 17 | + |
| 18 | +if len(sys.argv) < 2: |
| 19 | + print("Usage: trace-to-mermaid.py <service_name> [min_ms]", file=sys.stderr) |
| 20 | + sys.exit(1) |
| 21 | + |
| 22 | +service = sys.argv[1] |
| 23 | +min_ms = int(sys.argv[2]) if len(sys.argv) > 2 else 1 |
| 24 | +jaeger_url = __import__("os").environ.get("JAEGER_URL", "http://localhost:16686") |
| 25 | + |
| 26 | +# Fetch latest trace for the service |
| 27 | +url = f"{jaeger_url}/api/traces?service={service}&limit=1" |
| 28 | +try: |
| 29 | + with urllib.request.urlopen(url) as resp: |
| 30 | + trace_data = json.load(resp) |
| 31 | +except Exception as e: |
| 32 | + print(f"Error: could not fetch traces from {jaeger_url}: {e}", file=sys.stderr) |
| 33 | + print("Is Jaeger running? Try: make jaeger-start", file=sys.stderr) |
| 34 | + sys.exit(1) |
| 35 | + |
| 36 | +if not trace_data.get("data"): |
| 37 | + print(f"Error: no traces found for service '{service}'", file=sys.stderr) |
| 38 | + print("Run some operations first, e.g.:", file=sys.stderr) |
| 39 | + print(" make test-tracing", file=sys.stderr) |
| 40 | + sys.exit(1) |
| 41 | + |
| 42 | +trace = trace_data["data"][0] |
| 43 | +spans = trace["spans"] |
| 44 | +processes = trace["processes"] |
| 45 | + |
| 46 | +if not spans: |
| 47 | + print("Error: trace has no spans", file=sys.stderr) |
| 48 | + sys.exit(1) |
| 49 | + |
| 50 | +# Find trace start time (earliest span) |
| 51 | +trace_start = min(s["startTime"] for s in spans) |
| 52 | + |
| 53 | +# Build span lookup and parent map |
| 54 | +span_map = {} |
| 55 | +children = {} |
| 56 | +for s in spans: |
| 57 | + sid = s["spanID"] |
| 58 | + span_map[sid] = s |
| 59 | + children.setdefault(sid, []) |
| 60 | + for ref in s.get("references", []): |
| 61 | + if ref["refType"] == "CHILD_OF": |
| 62 | + parent_id = ref["spanID"] |
| 63 | + children.setdefault(parent_id, []) |
| 64 | + children[parent_id].append(sid) |
| 65 | + |
| 66 | +# Find root spans (no CHILD_OF reference within this trace) |
| 67 | +all_span_ids = {s["spanID"] for s in spans} |
| 68 | +root_spans = [] |
| 69 | +for s in spans: |
| 70 | + refs = s.get("references", []) |
| 71 | + parent_refs = [r for r in refs if r["refType"] == "CHILD_OF" and r["spanID"] in all_span_ids] |
| 72 | + if not parent_refs: |
| 73 | + root_spans.append(s) |
| 74 | + |
| 75 | +# Sort roots by start time |
| 76 | +root_spans.sort(key=lambda s: s["startTime"]) |
| 77 | + |
| 78 | + |
| 79 | +def span_duration_ms(s): |
| 80 | + return s["duration"] / 1000.0 |
| 81 | + |
| 82 | + |
| 83 | +def span_start_ms(s): |
| 84 | + return (s["startTime"] - trace_start) / 1000.0 |
| 85 | + |
| 86 | + |
| 87 | +def safe_id(name, sid): |
| 88 | + """Create a mermaid-safe task ID.""" |
| 89 | + clean = name.replace(" ", "_").replace(".", "_").replace("/", "_").replace("-", "_") |
| 90 | + # Append short span ID suffix for uniqueness |
| 91 | + return f"{clean}_{sid[:6]}" |
| 92 | + |
| 93 | + |
| 94 | +def collect_spans(span_id, depth=0): |
| 95 | + """Collect span and descendants, depth-first.""" |
| 96 | + s = span_map[span_id] |
| 97 | + result = [(s, depth)] |
| 98 | + kids = children.get(span_id, []) |
| 99 | + kids.sort(key=lambda cid: span_map[cid]["startTime"]) |
| 100 | + for cid in kids: |
| 101 | + result.extend(collect_spans(cid, depth + 1)) |
| 102 | + return result |
| 103 | + |
| 104 | + |
| 105 | +# Build output |
| 106 | +service_name = processes[spans[0]["processID"]]["serviceName"] |
| 107 | +lines = [] |
| 108 | +lines.append("```mermaid") |
| 109 | +lines.append("gantt") |
| 110 | +lines.append(" dateFormat x") |
| 111 | +lines.append(" axisFormat %s.%L s") |
| 112 | +lines.append(f" title Trace for {service_name}") |
| 113 | +lines.append("") |
| 114 | + |
| 115 | +for root in root_spans: |
| 116 | + root_name = root["operationName"] |
| 117 | + |
| 118 | + # Section per root span |
| 119 | + lines.append(f" section {root_name}") |
| 120 | + |
| 121 | + all_spans = collect_spans(root["spanID"]) |
| 122 | + for s, depth in all_spans: |
| 123 | + dur_ms = span_duration_ms(s) |
| 124 | + if dur_ms < min_ms: |
| 125 | + continue |
| 126 | + start_ms = span_start_ms(s) |
| 127 | + end_ms = start_ms + dur_ms |
| 128 | + |
| 129 | + # Indent name by depth for readability |
| 130 | + prefix = ". " * depth |
| 131 | + op = s["operationName"] |
| 132 | + proc = processes[s["processID"]]["serviceName"] |
| 133 | + label = f"{prefix}{op}" |
| 134 | + if proc != service_name: |
| 135 | + label = f"{prefix}{proc}/{op}" |
| 136 | + |
| 137 | + tid = safe_id(op, s["spanID"]) |
| 138 | + # Mermaid gantt uses milliseconds with dateFormat x |
| 139 | + lines.append(f" {label} :{tid}, {int(start_ms)}, {int(end_ms)}") |
| 140 | + |
| 141 | +lines.append("```") |
| 142 | + |
| 143 | +print("\n".join(lines)) |
0 commit comments