resource_span_record.py 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172
  1. import math
  2. from datetime import datetime as dt
  3. from oteldatareplay.common import gen_span_id, gen_trace_id
  4. def dt2span_time_nano(t):
  5. return str(math.floor(t.timestamp() * 1e9))
  6. def span_start_time(span, key='startTimeUnixNano'):
  7. return dt.fromtimestamp(int(span[key]) / 1e9)
  8. class ResourceSpanRecord:
  9. def __init__(self, record):
  10. self.record = record
  11. self.parse_stats()
  12. self.traces_ids = []
  13. self.span_ids = []
  14. self.span_count = 0
  15. self.first_span_start_time = None
  16. self.parse_stats()
  17. def get_first_span(self):
  18. rs = self.get_first_resource_span()
  19. if not rs:
  20. return None
  21. scope_spans = rs['scopeSpans']
  22. scope_span = scope_spans[0]
  23. spans = scope_span['spans']
  24. return spans[0] if len(spans) > 0 else None
  25. def get_first_resource_span(self):
  26. rss = self.get_resource_spans()
  27. return rss[0] if len(rss) > 0 else None
  28. def get_resource_spans(self):
  29. return self.record['resourceSpans']
  30. def parse_stats(self):
  31. rss = self.get_resource_spans()
  32. scope_spans = [sc for rs in rss for sc in rs['scopeSpans']]
  33. spans = [span for scopeSpan in scope_spans for span in scopeSpan['spans']]
  34. self.traces_ids = set([s['traceId'] for s in spans])
  35. self.span_ids = set([s['spanId'] for s in spans])
  36. self.span_count = len(spans)
  37. self.first_span_start_time = dt.fromtimestamp(int(spans[0]['startTimeUnixNano']) / 1e9)
  38. def iter_spans(self, func):
  39. for rs in self.record['resourceSpans']:
  40. for sc in rs['scopeSpans']:
  41. for span in sc['spans']:
  42. func(span)
  43. def update_span(self, now, first_record_time, trace_id_map):
  44. def update_span_time(span):
  45. span_start_dt = span_start_time(span)
  46. span_end_dt = span_start_time(span, 'endTimeUnixNano')
  47. span_start_dt_sim = (span_start_dt - first_record_time) + now
  48. span_end_dt_sim = (span_end_dt - first_record_time) + now
  49. trace_id = span['traceId']
  50. if trace_id in trace_id_map:
  51. span['traceId'] = trace_id_map[trace_id]
  52. else:
  53. tid = gen_trace_id()
  54. trace_id_map[trace_id] = gen_trace_id()
  55. span['traceId'] = tid
  56. span['startTimeUnixNano'] = dt2span_time_nano(span_start_dt_sim)
  57. span['endTimeUnixNano'] = dt2span_time_nano(span_end_dt_sim)
  58. self.iter_spans(update_span_time)