-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathgraph.py
More file actions
184 lines (149 loc) · 4.82 KB
/
graph.py
File metadata and controls
184 lines (149 loc) · 4.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
import json
import networkx as nx
import matplotlib.pyplot as plt
from dataclasses import dataclass
from typing import List, Dict, Any, Optional
@dataclass
class Span:
source: str
source_pods: List[str]
target: str
target_pods: List[str]
count: int
avg_latency: Optional[float]
max_latency: Optional[float]
avg_threshold: Optional[float]
error_codes: Optional[List[str]] = None
@staticmethod
def from_json(obj: Dict[str, Any]):
span = obj.get("span", {})
msg = obj.get("message", {})
latency = msg.get("latency", {})
return Span(
source=span.get("source"),
source_pods=span.get("source_pods", []),
target=span.get("target"),
target_pods=span.get("target_pods", []),
count=span.get("count", 0),
avg_latency=latency.get("avg_latency_ms"),
max_latency=latency.get("max_latency_ms"),
avg_threshold=latency.get("avg_threshold_ms"),
error_codes=msg.get("error_codes"),
)
def load_spans(path: str) -> List[Span]:
spans = []
with open(path, "r") as f:
for line in f:
if not line.strip():
continue
obj = json.loads(line)
if "span" in obj:
spans.append(Span.from_json(obj))
return spans
def build_graph(spans: List[Span]) -> nx.DiGraph:
g = nx.DiGraph()
for s in spans:
if not g.has_node(s.source):
g.add_node(s.source, pods=set(s.source_pods))
else:
g.nodes[s.source]["pods"].update(s.source_pods)
if not g.has_node(s.target):
g.add_node(s.target, pods=set(s.target_pods))
else:
g.nodes[s.target]["pods"].update(s.target_pods)
record = {
"count": s.count,
"avg_latency": s.avg_latency,
"max_latency": s.max_latency,
"avg_threshold": s.avg_threshold,
"error_codes": s.error_codes,
"source_pods": s.source_pods,
"target_pods": s.target_pods,
}
if not g.has_edge(s.source, s.target):
g.add_edge(s.source, s.target, records=[record])
else:
g[s.source][s.target]["records"].append(record)
for n in g.nodes:
g.nodes[n]["pods"] = list(g.nodes[n]["pods"])
return g
def print_graph_info(g: nx.DiGraph):
print("\nNodes:")
for n, data in g.nodes(data=True):
print(f" {n}: pods={data['pods']}")
print("\nEdges:")
for u, v, data in g.edges(data=True):
print(f" {u} -> {v}")
for idx, rec in enumerate(data["records"], 1):
print(f" record {idx}: {rec}")
# def visualize_graph(g: nx.DiGraph):
# plt.figure(figsize=(12, 8))
# pos = nx.spring_layout(g, seed=42)
# nx.draw(
# g,
# pos,
# with_labels=True,
# node_size=2500,
# font_size=10,
# arrows=True
# )
# edge_labels = {}
# for u, v, data in g.edges(data=True):
# records = data["records"]
# total_count = sum(rec["count"] for rec in records)
# span_count = len(records)
# edge_labels[(u, v)] = f"total_cnt={total_count}, span_cnt={span_count}"
# nx.draw_networkx_edge_labels(g, pos, edge_labels=edge_labels)
# plt.title("Service Call Graph (Aggregated)")
# plt.tight_layout()
# plt.savefig("service_call_graph.png")
def visualize_graph(g: nx.DiGraph):
plt.figure(figsize=(14, 9))
pos = nx.spring_layout(g, seed=42)
node_labels = {}
for n, data in g.nodes(data=True):
pods = data.get("pods", [])
node_labels[n] = f"{n}\npods: {','.join(pods)}"
nx.draw_networkx_nodes(
g, pos,
node_size=2600,
node_color="#A8D1FF"
)
nx.draw_networkx_labels(
g, pos,
labels=node_labels,
font_size=9
)
nx.draw_networkx_edges(
g, pos,
arrows=True,
arrowstyle="-|>",
arrowsize=15,
width=1.8
)
edge_labels = {}
for u, v, data in g.edges(data=True):
records = data["records"]
total_count = sum(rec["count"] for rec in records)
span_count = len(records)
edge_labels[(u, v)] = f"count={total_count}\nspans={span_count}"
nx.draw_networkx_edge_labels(
g, pos,
edge_labels=edge_labels,
font_size=8
)
plt.title("Service Call Graph with Pods and Aggregated Edge Metrics")
plt.tight_layout()
plt.savefig("service_call_graph.png")
def main():
TRACE_FILE = "trace_analysis_report.jsonl"
LOG_FILE = "log_analysis_report.jsonl"
spans = load_spans(TRACE_FILE)
print(f"Loaded {len(spans)} spans.")
g = build_graph(spans)
print_graph_info(g)
visualize_graph(g)
if __name__ == "__main__":
main()
else:
print("Please run this script directly.")