apm_tracing.go 8.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286
  1. package tracing
  2. import (
  3. "context"
  4. "fmt"
  5. "sync/atomic"
  6. "time"
  7. "github.com/coroot/coroot-node-agent/ebpftracer/l7"
  8. "go.opentelemetry.io/otel/attribute"
  9. "go.opentelemetry.io/otel/codes"
  10. semconv "go.opentelemetry.io/otel/semconv/v1.18.0"
  11. "go.opentelemetry.io/otel/trace"
  12. "inet.af/netaddr"
  13. "strconv"
  14. )
  15. /**
  16. * Trace
  17. */
  18. func (t *Trace) setContext(ctx context.Context) {
  19. t.lock.Lock()
  20. defer t.lock.Unlock()
  21. t.ctx = ctx
  22. }
  23. func (t *Trace) setSpan(span trace.Span) {
  24. t.lock.Lock()
  25. defer t.lock.Unlock()
  26. t.span = span
  27. }
  28. func (t *Trace) setDestination(destination netaddr.IPPort) {
  29. t.lock.Lock()
  30. defer t.lock.Unlock()
  31. t.destination = destination
  32. t.commonAttrs = []attribute.KeyValue{
  33. semconv.NetPeerName(destination.IP().String()),
  34. semconv.NetPeerPort(int(destination.Port())),
  35. }
  36. }
  37. func (t *Trace) startReady() {
  38. t.lock.Lock()
  39. defer t.lock.Unlock()
  40. t.startEventReady = true
  41. }
  42. func (t *Trace) endReadyEvent(needCount uint32) {
  43. t.lock.Lock()
  44. defer t.lock.Unlock()
  45. t.endEventReady = true
  46. t.needEventCount = needCount
  47. }
  48. func (t *Trace) AllEventReady(traceID uint64) bool {
  49. fmt.Printf("id<%d>,needEventCount:%d->%d|start:%v|end:%v\n", traceID, t.needEventCount, *t.currenEventCount, t.startEventReady, t.endEventReady)
  50. return t.startEventReady && t.endEventReady && *t.currenEventCount >= t.needEventCount
  51. }
  52. func (t *Trace) TraceStartEvent(method, path string, status l7.Status, addr netaddr.IPPort) {
  53. t.span.SetAttributes(semconv.HTTPURL(fmt.Sprintf("http://%s%s", addr.String(), path)),
  54. semconv.HTTPMethod(method),
  55. attribute.String("http.uri", path))
  56. if status > 399 {
  57. t.span.SetStatus(codes.Error, "")
  58. }
  59. t.setDestination(addr)
  60. t.startReady()
  61. }
  62. // set context span
  63. func (t *Trace) CreateRootSpan(traceId uint64) {
  64. traceIdStr := strconv.Itoa(int(traceId))
  65. ctx, span := tracer(t.containerId).Start(context.Background(), traceIdStr, trace.WithSpanKind(trace.SpanKindClient))
  66. t.setContext(ctx)
  67. t.setSpan(span)
  68. }
  69. func (t *Trace) TraceStart(method, path string, status l7.Status, duration time.Duration) {
  70. if t == nil || method == "" {
  71. return
  72. }
  73. t.createParentSpan("APPLICATION", duration, status >= 400,
  74. semconv.HTTPURL(fmt.Sprintf("http://%s%s", t.destination.String(), path)),
  75. semconv.HTTPMethod(method),
  76. //semconv.HTTPStatusCode(int(status)),
  77. attribute.String("http.uri", path),
  78. )
  79. }
  80. func (t *Trace) TraceEnd(r *l7.RequestData) {
  81. if t == nil {
  82. return
  83. }
  84. t.span.SetAttributes(
  85. semconv.HTTPStatusCode(int(r.Status)),
  86. attribute.String("server.trace_id_from", r.ParentSpanContext.TraceIdFrom),
  87. )
  88. CalledId, err := strconv.ParseInt(r.ParentSpanContext.CalledId, 10, 64)
  89. if err == nil && CalledId != 0 {
  90. t.span.SetAttributes(attribute.Int64("server.called_id", CalledId))
  91. }
  92. InstanceIdFrom, err := strconv.ParseInt(r.ParentSpanContext.InstanceIdFrom, 10, 64)
  93. if err == nil && InstanceIdFrom != 0 {
  94. t.span.SetAttributes(attribute.Int64("server.instance_id_from", InstanceIdFrom))
  95. }
  96. AppIdFrom, err := strconv.ParseInt(r.ParentSpanContext.AppIdFrom, 10, 64)
  97. if err == nil && AppIdFrom != 0 {
  98. t.span.SetAttributes(attribute.Int64("server.app_id_from", AppIdFrom))
  99. }
  100. if r.ParentSpanContext.SpanIdFrom != "0000000000000000" {
  101. t.span.SetAttributes(attribute.String("server.span_id_from", r.ParentSpanContext.SpanIdFrom))
  102. }
  103. t.span.End(trace.WithTimestamp(time.Now()))
  104. }
  105. // 新增结束事件
  106. func (t *Trace) TraceEndEvent(r *l7.RequestData) {
  107. if t == nil {
  108. return
  109. }
  110. var attr []attribute.KeyValue
  111. attr = append(attr,
  112. semconv.HTTPStatusCode(int(r.Status)),
  113. attribute.String("server.trace_id_from", r.ParentSpanContext.TraceIdFrom),
  114. )
  115. //t.span.SetAttributes(
  116. // semconv.HTTPStatusCode(int(r.Status)),
  117. // attribute.String("server.trace_id_from", r.ParentSpanContext.TraceIdFrom),
  118. //)
  119. calledId, err := strconv.ParseInt(r.ParentSpanContext.CalledId, 10, 64)
  120. if err == nil && calledId != 0 {
  121. attr = append(attr, attribute.Int64("server.called_id", calledId))
  122. //t.span.SetAttributes(attribute.Int64("server.called_id", CalledId))
  123. }
  124. instanceIdFrom, err := strconv.ParseInt(r.ParentSpanContext.InstanceIdFrom, 10, 64)
  125. if err == nil && instanceIdFrom != 0 {
  126. attr = append(attr, attribute.Int64("server.instance_id_from", instanceIdFrom))
  127. //t.span.SetAttributes(attribute.Int64("server.instance_id_from", InstanceIdFrom))
  128. }
  129. appIdFrom, err := strconv.ParseInt(r.ParentSpanContext.AppIdFrom, 10, 64)
  130. if err == nil && appIdFrom != 0 {
  131. attr = append(attr, attribute.Int64("server.app_id_from", appIdFrom))
  132. //t.span.SetAttributes(attribute.Int64("server.app_id_from", AppIdFrom))
  133. }
  134. if r.ParentSpanContext.SpanIdFrom != "0000000000000000" {
  135. attr = append(attr, attribute.String("server.span_id_from", r.ParentSpanContext.SpanIdFrom))
  136. //t.span.SetAttributes(attribute.String("server.span_id_from", r.ParentSpanContext.SpanIdFrom))
  137. }
  138. attr = append(attr, attribute.Int64("duration", r.Duration.Nanoseconds()))
  139. t.span.SetAttributes(attr...)
  140. t.endReadyEvent(r.EventCount)
  141. }
  142. func (t *Trace) createParentSpan(name string, duration time.Duration, error bool, attrs ...attribute.KeyValue) {
  143. end := time.Now()
  144. start := end.Add(-duration)
  145. ctx, span := tracer(t.containerId).Start(context.Background(), name, trace.WithTimestamp(start), trace.WithSpanKind(trace.SpanKindClient))
  146. span.SetAttributes(attrs...)
  147. span.SetAttributes(t.commonAttrs...)
  148. if error {
  149. span.SetStatus(codes.Error, "")
  150. }
  151. t.setContext(ctx)
  152. t.setSpan(span)
  153. }
  154. func (t *Trace) SendEvent() {
  155. t.span.End()
  156. }
  157. func (t *Trace) GetSpan() trace.Span {
  158. return t.span
  159. }
  160. func (t *Trace) createTraceEvent(name string, attrs ...attribute.KeyValue) {
  161. t.span.AddEvent(name, trace.WithAttributes(attrs...))
  162. atomic.AddUint32(t.currenEventCount, 1)
  163. }
  164. func (t *Trace) createTraceSpan(name string, duration time.Duration, error bool, attrs ...attribute.KeyValue) {
  165. end := time.Now()
  166. start := end.Add(-duration)
  167. //fmt.Println("createTraceSpan:", t.ctx)
  168. _, span := tracer(t.containerId).Start(t.ctx, name, trace.WithTimestamp(start), trace.WithSpanKind(trace.SpanKindClient))
  169. span.SetAttributes(t.commonAttrs...)
  170. span.SetAttributes(attrs...)
  171. if error {
  172. span.SetStatus(codes.Error, "")
  173. }
  174. span.End(trace.WithTimestamp(end))
  175. }
  176. func (t *Trace) MysqlTraceQuery(query string, error bool, duration time.Duration, destination netaddr.IPPort) {
  177. if t == nil || query == "" {
  178. return
  179. }
  180. t.createTraceSpan(l7.ProtocolMysql.String(), duration, error,
  181. semconv.DBSystemMySQL,
  182. semconv.DBStatement(query),
  183. semconv.NetPeerName(destination.IP().String()),
  184. semconv.NetPeerPort(int(destination.Port())),
  185. )
  186. }
  187. func (t *Trace) RedisTraceQuery(cmd, args string, error bool, duration time.Duration) {
  188. if t == nil || cmd == "" {
  189. return
  190. }
  191. statement := cmd
  192. if args != "" {
  193. statement += " " + args
  194. }
  195. t.createTraceSpan(l7.ProtocolRedis.String(), duration, error,
  196. semconv.DBSystemRedis,
  197. semconv.DBOperation(cmd),
  198. semconv.DBStatement(statement),
  199. )
  200. }
  201. func (t *Trace) HttpTraceRequest(method, path, ip string, port uint16, r *l7.RequestData) {
  202. if t == nil || method == "" {
  203. return
  204. }
  205. assumedAppID, err := strconv.ParseInt(r.AssumedAppId, 10, 64)
  206. if err != nil {
  207. assumedAppID = 0
  208. }
  209. status := r.Status
  210. duration := r.Duration
  211. t.createTraceSpan(l7.ProtocolHTTP.String(), duration, status >= 400,
  212. semconv.HTTPURL(fmt.Sprintf("http://%s%s", t.destination.String(), path)),
  213. semconv.HTTPMethod(method),
  214. semconv.HTTPStatusCode(int(status)),
  215. attribute.String("http.uri", path),
  216. attribute.String("http.ip", ip),
  217. attribute.Int64("http.assumed_app_id", assumedAppID),
  218. attribute.String("http.span_id", r.SpanId),
  219. attribute.Int("http.port", int(port)),
  220. )
  221. }
  222. // 新增事件处理
  223. func (t *Trace) HttpTraceRequestEvent(method, path, ip string, port uint16, r *l7.RequestData) {
  224. if t == nil || method == "" {
  225. return
  226. }
  227. assumedAppID, err := strconv.ParseInt(r.AssumedAppId, 10, 64)
  228. if err != nil {
  229. assumedAppID = 0
  230. }
  231. status := r.Status
  232. duration := r.Duration
  233. t.createTraceEvent(l7.ProtocolHTTP.String(),
  234. semconv.HTTPURL(fmt.Sprintf("http://%s%s", t.destination.String(), path)),
  235. semconv.HTTPMethod(method),
  236. semconv.HTTPStatusCode(int(status)),
  237. attribute.Bool("http.status_error", status > 399),
  238. attribute.String("http.uri", path),
  239. attribute.String("http.ip", ip),
  240. attribute.Int64("http.assumed_app_id", assumedAppID),
  241. attribute.String("http.span_id", r.SpanId),
  242. attribute.Int("http.port", int(port)),
  243. attribute.Int64("duration", duration.Nanoseconds()),
  244. )
  245. }
  246. func (t *Trace) FuncTraceQuery(funcname string, duration time.Duration, level int, pid int, nid int) {
  247. if t == nil || funcname == "" {
  248. return
  249. }
  250. t.createTraceSpan(funcname, duration, false,
  251. attribute.Int("level", level),
  252. attribute.Int("pid", pid),
  253. attribute.Int("nid", nid),
  254. )
  255. }