Newer
Older
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
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
import re
import json
import time
import requests
import numpy as np
from copy import deepcopy
import warnings
import paramiko
from elasticsearch import Elasticsearch, helpers
warnings.filterwarnings("ignore")
es_url = 'http://11.11.11.24:9200'
root_index = 'root'
client = Elasticsearch([es_url])
'''
Query the initial trace data from elasticsearch by scroll(1 min)
:arg
date: format 2020-08-14 or 2020-08-*
start: the timestamp of start time (ms)
end: the timestamp of end time (ms)
:return
all span between start time and end time except jaeger-query service
'''
def get_span(start=None, end=None):
local_time = time.localtime(start/1000)
day = time.strftime('%Y-%m', local_time)
index_name = 'jaeger-span-' + day + '-*'
scroll_api = es_url + "/" + index_name + "/_search?scroll=1m"
based_api = es_url + "/_search/scroll?filter_path=hits.hits._source"
headers = {"Content-Type": "application/json"}
query_data = {
"size": 10000,
"query": {
"bool": {
"must_not": [
{
"terms": {
"process.serviceName": [
"jaeger-query"
]}
}
],
"filter": {
"range": {
"startTimeMillis": {
"lte": str(end),
"gte": str(start)
}
}
}
}
},
"sort": {
"traceID": {
"order": "asc"
},
"startTime": {
"order": "asc"
}
}
}
data = requests.post(scroll_api, json=query_data, headers=headers).json()
for i in range(10):
if '_scroll_id' not in data:
print("query error, restart query scroll")
time.sleep(10)
data = requests.post(
scroll_api, json=query_data, headers=headers).json()
else:
break
scroll_data = {
"scroll": "1m",
"scroll": data['_scroll_id']
}
span_list = []
while 'hits' in data and len(data['hits']['hits']) > 0:
span_list += data['hits']['hits']
data = requests.post(based_api, json=scroll_data,
headers=headers).json()
print('\nSpan Length:', len(span_list))
return span_list
'''
Query all the service_operation from the input span_list
:arg
span_list: should be a long time span_list to get all operation
:return
the operation list and operation list dict
'''
def get_service_operation_list(span_list):
operation_list = []
for doc in span_list:
doc = doc['_source']
operation_name = doc['operationName']
operation_name = operation_name.split('/')[-1]
# Currencyservice_Convert
operation = doc['process']['serviceName'] + '_' + operation_name
if operation not in operation_list:
operation_list.append(operation)
return operation_list
"""
Calculate the mean of duration and variance for each span_list
:arg
operation_list: contains all operation
span_list: should be a long time span_list
:return
operation dict of the mean of and variance
{
# operation: {mean, variance}
"Currencyservice_Convert": [600, 3]}
}
"""
def get_operation_slo(service_operation_list, span_list):
template = {
'parent': '', # parent span
'operation': '', # current servicename_operation
'duration': 0 # duration of current operation
}
traceid = span_list[0]['_source']['traceID']
filter_data = {}
temp = {}
normal_trace = True
def check_filter_data():
for spanid in temp:
if temp[spanid]['parent'] == root_index:
if temp[spanid]['duration'] > 1000000:
print("filter data because duration > 1000ms")
print(temp)
return False
return True
def server_client_determined():
"""
:return span.kind
tags: [{"key": "span.kind",
"type": "string",
"value": "server"}]
"""
for tag in doc['tags']:
if tag['key'] == "span.kind":
return tag['value']
def get_operation_name():
operation_name = doc['operationName']
operation_name = operation_name.split('/')[-1]
operation_name = doc['process']['serviceName'] + '_' + operation_name
return operation_name
for doc in span_list:
doc = doc['_source']
if traceid == doc['traceID']:
spanid = doc['spanID']
temp[spanid] = deepcopy(template)
temp[spanid]['duration'] = doc['duration']
temp[spanid]['operation'] = get_operation_name()
if server_client_determined() == 'server' and doc['process']['serviceName'] == "frontend":
temp[spanid]['parent'] = root_index
else:
"""
"references" : [{"refType" : "CHILD_OF",
"traceID" : "0000658f4e42f8674d2e36630a9ca2b8",
"spanID" : "83438897471cc41a"}],
"""
if len(doc['references']) == 0:
print(doc)
normal_trace = False
else:
parentId = doc['references'][0]['spanID']
temp[spanid]['parent'] = parentId
if parentId in temp:
temp[parentId]['duration'] -= temp[spanid]['duration']
else:
normal_trace = False
elif traceid != doc['traceID'] and len(temp) > 0:
if check_filter_data() and normal_trace:
filter_data[traceid] = temp
traceid = doc['traceID']
normal_trace = True
spanid = doc['spanID']
temp = {}
temp[spanid] = deepcopy(template)
temp[spanid]['duration'] = doc['duration']
temp[spanid]['operation'] = get_operation_name()
if server_client_determined() == 'server' and doc['process']['serviceName'] == "frontend":
temp[spanid]['parent'] = root_index
else:
if len(doc['references']) == 0:
normal_trace = False
print(
"filter data because it is not frontend and its references is null ")
print(traceid)
else:
parentId = doc['references'][0]['spanID']
temp[spanid]['parent'] = parentId
if parentId in temp:
temp[parentId]['duration'] -= temp[spanid]['duration']
else:
normal_trace = False
# The last trace
if len(temp) > 1:
if check_filter_data() and normal_trace:
filter_data[traceid] = temp
duration_dict = {}
"""
{'frontend_Recv.': [1961, 1934, 1316, 1415, 1546, 1670, 1357, 2099, 2789, 1832, 1270, 1242, 2230, 1386],
'recommendationservice_ListProducts': [3576, 7127, 4387, 19657, 5158, 4563, 4167, 8822, 4507],
"""
for operation in service_operation_list:
duration_dict[operation] = []
for traceid in filter_data:
single_trace = filter_data[traceid]
for spanid in single_trace:
duration_dict[single_trace[spanid]['operation']].append(
single_trace[spanid]['duration'])
operation_slo = {}
"""
{'frontend_Recv.': [2.903, 10.0949], 'frontend_GetSupportedCurrencies': [8.1019, 16.2973], }
"""
for operation in service_operation_list:
operation_slo[operation] = []
for operation in service_operation_list:
operation_slo[operation].append(
round(np.mean(duration_dict[operation]) / 1000.0, 4))
#operation_slo[operation].append(round(np.percentile(duration_dict[operation], 90) / 1000.0, 4))
operation_slo[operation].append(
round(np.std(duration_dict[operation]) / 1000.0, 4))
return operation_slo
'''
Query the operation and duration in span_list for anormaly detector
:arg
operation_list: contains all operation
operation_dict: { "operation1": 1, "operation2":2 ... "operationn": 0, "duration": 666}
span_list: all the span_list in one anomaly detection interval (1 min or 30s)
:return
{
traceid: {
operation1: 1
operation2: 2
}
}
'''
def get_operation_duration_data(operation_list, span_list):
operation_dict = {}
trace_id = span_list[0]['_source']['traceID']
def server_client_determined():
for tag in doc['tags']:
if tag['key'] == "span.kind":
return tag['value']
def get_operation_name():
operation_name_tmp = doc['operationName']
operation_name_tmp = operation_name_tmp.split('/')[-1]
operation_name_tmp = doc['process']['serviceName'] + \
'_' + operation_name_tmp
return operation_name_tmp
def init_dict(trace_id):
if trace_id not in operation_dict:
operation_dict[trace_id] = {}
for operation in operation_list:
operation_dict[trace_id][operation] = 0
operation_dict[trace_id]['duration'] = 0
length = 0
for doc in span_list:
doc = doc['_source']
tag = server_client_determined()
operation_name = get_operation_name()
init_dict(doc['traceID'])
if trace_id == doc['traceID']:
operation_dict[trace_id][operation_name] += 1
length += 1
if doc['process']['serviceName'] == "frontend" and tag == "server":
operation_dict[trace_id]['duration'] += doc['duration']
else:
if operation_dict[trace_id]['duration'] == 0:
if length > 45:
operation_dict.pop(trace_id)
else:
operation_dict.pop(trace_id)
trace_id = doc['traceID']
length = 0
operation_dict[trace_id][operation_name] += 1
if doc['process']['serviceName'] == "frontend" and tag == "server":
operation_dict[trace_id]['duration'] += doc['duration']
return operation_dict
'''
Query the pagerank graph
:arg
trace_list: anormaly_traceid_list or normaly_traceid_list
span_list: 异常点前后两分钟 span_list
:return
operation_operation 存储子节点 Call graph
operation_operation[operation_name] = [operation_name1 , operation_name1 ]
operation_trace 存储trace经过了哪些operation, 右上角 coverage graph
operation_trace[traceid] = [operation_name1 , operation_name2]
trace_operation 存储 operation被哪些trace 访问过, 左下角 coverage graph
trace_operation[operation_name] = [traceid1, traceid2]
pr_trace: 存储trace id 经过了哪些operation,不去重
pr_trace[traceid] = [operation_name1 , operation_name2]
'''
def get_pagerank_graph(trace_list, span_list):
template = {
'parent': '', # parent span
'operation': '', # current servicename_operation
}
if len(trace_list) > 0:
traceid = trace_list[0]
else:
traceid = span_list[0]
filter_data = {}
temp = {}
def get_operation_name():
"""
有时pod_name在 tags 中,有时在process的tags中
"process": {"tags": [{"key": "name",
"type": "string",
"value": "frontend-7dbb469cd9-lkv68"}]}
"tags" : [{"key" : "name",
"type" : "string",
"value" : "adservice-7688bd74f6-7qkvl"}]
operation = pod_name + operation_name
:return operation
"""
pod_name = ""
for tag in doc['process']['tags']:
if tag['key'] == "name":
pod_name = tag['value']
for tag in doc['tags']:
if tag['key'] == "name":
pod_name = tag['value']
operation = pod_name + "_" + doc['operationName']
return operation
operation_operation = {}
operation_trace = {}
trace_operation = {}
pr_trace = {}
for doc in span_list:
doc = doc['_source']
operation_name = get_operation_name()
if doc['traceID'] in trace_list:
if traceid == doc['traceID']:
spanid = doc['spanID']
temp[spanid] = deepcopy(template)
temp[spanid]['operation'] = get_operation_name()
if len(doc['references']) > 0:
parentId = doc['references'][0]['spanID']
temp[spanid]['parent'] = parentId
elif traceid != doc['traceID'] and len(temp) > 0:
filter_data[traceid] = temp
traceid = doc['traceID']
spanid = doc['spanID']
temp = {}
temp[spanid] = deepcopy(template)
temp[spanid]['operation'] = get_operation_name()
if len(doc['references']) > 0:
parentId = doc['references'][0]['spanID']
temp[spanid]['parent'] = parentId
if len(temp) > 1:
filter_data[traceid] = temp
"""
operation_operation
operation_operation[operation_name] = [operation_name1 , operation_name1 ]
operation_trace
operation_trace[traceid] = [operation_name1 , operation_name1]
trace_operation
trace_operation[operation_name] = [traceid1, traceid2]
"""
if operation_name not in operation_operation:
operation_operation[operation_name] = []
trace_operation[operation_name] = []
if doc['traceID'] not in operation_trace:
operation_trace[doc['traceID']] = []
pr_trace[doc['traceID']] = []
pr_trace[doc['traceID']].append(operation_name)
if operation_name not in operation_trace[doc['traceID']]:
operation_trace[doc['traceID']].append(operation_name)
if doc['traceID'] not in trace_operation[operation_name]:
trace_operation[operation_name].append(doc['traceID'])
for traceid in filter_data:
single_trace = filter_data[traceid]
if traceid in trace_list:
for spanid in single_trace:
parent_id = single_trace[spanid]["parent"]
if parent_id != "":
if parent_id not in single_trace:
continue
if single_trace[spanid]["operation"] not in operation_operation[
single_trace[parent_id]["operation"]]:
operation_operation[single_trace[parent_id]["operation"]].append(
single_trace[spanid]["operation"])
return operation_operation, operation_trace, trace_operation, pr_trace
if __name__ == '__main__':
def timestamp(datetime):
timeArray = time.strptime(datetime, "%Y-%m-%d %H:%M:%S")
ts = int(time.mktime(timeArray)) * 1000
# print(ts)
return ts
start = '2020-08-28 14:56:43'
end = '2020-08-28 14:57:44'
span_list = get_span(start=timestamp(start), end=timestamp(end))
# print(span_list)
operation_list = get_service_operation_list(span_list)
print(operation_list)
operation_slo = get_operation_slo(
service_operation_list=operation_list, span_list=span_list)
print(operation_slo)