apm_tracing.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440
  1. package tracing
  2. import (
  3. "context"
  4. "fmt"
  5. "github.com/coroot/coroot-node-agent/ebpftracer"
  6. "github.com/coroot/coroot-node-agent/ebpftracer/l7"
  7. "github.com/coroot/coroot-node-agent/utils"
  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. "sync/atomic"
  15. "time"
  16. )
  17. /**
  18. * Trace
  19. */
  20. func (t *Trace) setContext(ctx context.Context) {
  21. t.lock.Lock()
  22. defer t.lock.Unlock()
  23. t.ctx = ctx
  24. }
  25. func (t *Trace) setSpan(span trace.Span) {
  26. t.lock.Lock()
  27. defer t.lock.Unlock()
  28. t.span = span
  29. }
  30. type TimeMap struct {
  31. Time uint64
  32. Type int
  33. Map *ebpftracer.StackFunEvent
  34. }
  35. //func (t *Trace) buildFun() {
  36. // mapSlice := []TimeMap{}
  37. // for i, v := range t.stack {
  38. // timeStartMap := TimeMap{}
  39. // if v.StackEvent.Location == 0 {
  40. // timeStartMap = TimeMap{
  41. // Time: v.StackEvent.TimeNsStart,
  42. // Type: 0,
  43. // Map: &t.stack[i],
  44. // }
  45. // } else {
  46. // timeStartMap = TimeMap{
  47. // Time: v.StackEvent.TimeNsEnd,
  48. // Type: 1,
  49. // Map: &t.stack[i],
  50. // }
  51. // }
  52. // mapSlice = append(mapSlice, timeStartMap)
  53. // }
  54. // sort.Slice(mapSlice, func(i, j int) bool {
  55. // return mapSlice[i].Time < mapSlice[j].Time
  56. // })
  57. //
  58. // funStack := []TimeMap{}
  59. //
  60. // currentfunNum := 1
  61. //
  62. // // for k, v := range mapSlice {
  63. // // fmt.Println("---SliceSliceindex", k, "value", v.Time, v.Type, v.Map.Uprobe.Funcname, v.Map.StackEvent.Nid)
  64. // // }
  65. //
  66. // mapSliceLen := len(mapSlice)
  67. // for k, v := range mapSlice {
  68. // // fmt.Println("SliceSliceindex", k, "value", v.Time, v.Type, v.Map.Uprobe.Funcname, v.Map.StackEvent.Nid)
  69. // if v.Type == 0 {
  70. // // 函数入口
  71. // funStack = append(funStack, v)
  72. // } else if v.Type == 1 {
  73. // // 函数出口
  74. // len := len(funStack)
  75. // if len < 1 {
  76. // fmt.Printf("buildFun ErrorError return before enter: %v\n", v)
  77. // continue
  78. // }
  79. // currnt := funStack[len-1]
  80. // if currnt.Map.StackEvent.Location != 0 {
  81. // fmt.Printf("currnt StackEvent ErrorError is not enter: %v\n", v)
  82. // continue
  83. // }
  84. // if k < mapSliceLen-1 && len >= 2 {
  85. // nextfun := mapSlice[k+1]
  86. // preCurrnt := funStack[len-2]
  87. // // // 处理 .netcore 多次 returun
  88. // // 下一个事件是 return 并且函数名跟当前事件是一样的,且上一个函数不是当前函数
  89. // if nextfun.Map.StackEvent.Location == 1 && nextfun.Map.Uprobe.Funcname == currnt.Map.Uprobe.Funcname && preCurrnt.Map.Uprobe.Funcname != currnt.Map.Uprobe.Funcname {
  90. // currentfunNum++
  91. // continue
  92. // }
  93. // }
  94. // funStack = funStack[:len-1]
  95. // duration := v.Map.StackEvent.TimeNsEnd - currnt.Map.StackEvent.TimeNsStart
  96. // t.FuncTraceQuery(currnt.Map.Uprobe.Funcname, time.Duration(duration), currnt.Map.StackEvent.TimeNsStart, v.Map.StackEvent.TimeNsEnd, currentfunNum)
  97. // currentfunNum = 1
  98. // }
  99. // }
  100. //}
  101. func (t *Trace) startReady() {
  102. t.lock.Lock()
  103. defer t.lock.Unlock()
  104. t.startEventReady = true
  105. }
  106. func (t *Trace) endReadyEvent(needCount uint32) {
  107. t.lock.Lock()
  108. defer t.lock.Unlock()
  109. t.endEventReady = true
  110. t.needEventCount = needCount
  111. }
  112. func (t *Trace) AllEventReady(traceID uint64) bool {
  113. fmt.Printf("[AllEventReady (current/need)|start|end|traceid](%d/%d)%v|%v|%d\n", *t.currenEventCount, t.needEventCount, t.startEventReady, t.endEventReady, traceID)
  114. return t.startEventReady && t.endEventReady && *t.currenEventCount >= t.needEventCount
  115. }
  116. func (t *Trace) TraceStartEvent(method, path string, status l7.Status, addr netaddr.IPPort) {
  117. t.span.SetAttributes(semconv.HTTPURL(fmt.Sprintf("http://%s%s", addr.String(), path)),
  118. semconv.HTTPMethod(method),
  119. attribute.String("http.uri", path))
  120. if status > 399 {
  121. t.span.SetStatus(codes.Error, "")
  122. }
  123. t.destination = addr
  124. t.commonAttrs = []attribute.KeyValue{
  125. semconv.NetPeerName(addr.IP().String()),
  126. semconv.NetPeerPort(int(addr.Port())),
  127. }
  128. t.span.SetAttributes(t.commonAttrs...)
  129. t.startReady()
  130. }
  131. // set context span
  132. func (t *Trace) CreateRootSpan(traceId uint64) {
  133. traceIdStr := strconv.Itoa(int(traceId))
  134. ctx, span := tracer(t.containerId).Start(context.Background(), traceIdStr, trace.WithSpanKind(trace.SpanKindClient))
  135. t.setContext(ctx)
  136. t.setSpan(span)
  137. }
  138. func (t *Trace) TraceStart(method, path string, status l7.Status, duration time.Duration) {
  139. if t == nil || method == "" {
  140. return
  141. }
  142. t.createParentSpan("APPLICATION", duration, status >= 400,
  143. semconv.HTTPURL(fmt.Sprintf("http://%s%s", t.destination.String(), path)),
  144. semconv.HTTPMethod(method),
  145. //semconv.HTTPStatusCode(int(status)),
  146. attribute.String("http.uri", path),
  147. )
  148. }
  149. func (t *Trace) TraceEnd(r *l7.RequestData) {
  150. if t == nil {
  151. return
  152. }
  153. t.span.SetAttributes(
  154. semconv.HTTPStatusCode(int(r.Status)),
  155. attribute.String("server.trace_id_from", r.ParentSpanContext.TraceIdFrom),
  156. )
  157. CalledId, err := strconv.ParseInt(r.ParentSpanContext.CalledId, 10, 64)
  158. if err == nil && CalledId != 0 {
  159. t.span.SetAttributes(attribute.Int64("server.called_id", CalledId))
  160. }
  161. InstanceIdFrom, err := strconv.ParseInt(r.ParentSpanContext.InstanceIdFrom, 10, 64)
  162. if err == nil && InstanceIdFrom != 0 {
  163. t.span.SetAttributes(attribute.Int64("server.instance_id_from", InstanceIdFrom))
  164. }
  165. AppIdFrom, err := strconv.ParseInt(r.ParentSpanContext.AppIdFrom, 10, 64)
  166. if err == nil && AppIdFrom != 0 {
  167. t.span.SetAttributes(attribute.Int64("server.app_id_from", AppIdFrom))
  168. }
  169. if r.ParentSpanContext.SpanIdFrom != "0000000000000000" {
  170. t.span.SetAttributes(attribute.String("server.span_id_from", r.ParentSpanContext.SpanIdFrom))
  171. }
  172. // for _, v := range t.stack {
  173. // fmt.Printf("TraceEndTraceEndTraceEnd%s\n", v)
  174. // }
  175. //t.buildFun()
  176. t.span.End(trace.WithTimestamp(time.Now()))
  177. }
  178. // 新增结束事件
  179. func (t *Trace) TraceEndEvent(r *l7.RequestData) {
  180. if t == nil {
  181. return
  182. }
  183. var attr []attribute.KeyValue
  184. attr = append(attr,
  185. semconv.HTTPStatusCode(int(r.Status)),
  186. attribute.String("server.trace_id_from", r.ParentSpanContext.TraceIdFrom),
  187. )
  188. //t.span.SetAttributes(
  189. // semconv.HTTPStatusCode(int(r.Status)),
  190. // attribute.String("server.trace_id_from", r.ParentSpanContext.TraceIdFrom),
  191. //)
  192. calledId, err := strconv.ParseInt(r.ParentSpanContext.CalledId, 10, 64)
  193. if err == nil && calledId != 0 {
  194. attr = append(attr, attribute.Int64("server.called_id", calledId))
  195. //t.span.SetAttributes(attribute.Int64("server.called_id", CalledId))
  196. }
  197. instanceIdFrom, err := strconv.ParseInt(r.ParentSpanContext.InstanceIdFrom, 10, 64)
  198. if err == nil && instanceIdFrom != 0 {
  199. attr = append(attr, attribute.Int64("server.instance_id_from", instanceIdFrom))
  200. //t.span.SetAttributes(attribute.Int64("server.instance_id_from", InstanceIdFrom))
  201. }
  202. appIdFrom, err := strconv.ParseInt(r.ParentSpanContext.AppIdFrom, 10, 64)
  203. if err == nil && appIdFrom != 0 {
  204. attr = append(attr, attribute.Int64("server.app_id_from", appIdFrom))
  205. //t.span.SetAttributes(attribute.Int64("server.app_id_from", AppIdFrom))
  206. }
  207. if r.ParentSpanContext.SpanIdFrom != "0000000000000000" {
  208. attr = append(attr, attribute.String("server.span_id_from", r.ParentSpanContext.SpanIdFrom))
  209. //t.span.SetAttributes(attribute.String("server.span_id_from", r.ParentSpanContext.SpanIdFrom))
  210. }
  211. t.appendTimestamp(&attr, r.StartAt, r.EndAt, r.Duration.Nanoseconds())
  212. t.span.SetAttributes(attr...)
  213. t.endReadyEvent(r.EventCount)
  214. }
  215. func (t *Trace) appendTimestamp(attr *[]attribute.KeyValue, s, e uint64, d int64) {
  216. *attr = append(*attr,
  217. attribute.Int64("time.start_at", utils.KtimeToTimestamp(s)),
  218. attribute.Int64("time.end_at", utils.KtimeToTimestamp(e)),
  219. attribute.Int64("time.duration", d),
  220. )
  221. }
  222. func (t *Trace) createParentSpan(name string, duration time.Duration, error bool, attrs ...attribute.KeyValue) {
  223. end := time.Now()
  224. start := end.Add(-duration)
  225. ctx, span := tracer(t.containerId).Start(context.Background(), name, trace.WithTimestamp(start), trace.WithSpanKind(trace.SpanKindClient))
  226. span.SetAttributes(attrs...)
  227. span.SetAttributes(t.commonAttrs...)
  228. if error {
  229. span.SetStatus(codes.Error, "")
  230. }
  231. t.setContext(ctx)
  232. t.setSpan(span)
  233. }
  234. func (t *Trace) SendEvent() {
  235. t.span.End()
  236. }
  237. func (t *Trace) GetSpan() trace.Span {
  238. return t.span
  239. }
  240. func (t *Trace) createTraceEvent(name string, eventType int, l7Type int, attrs ...attribute.KeyValue) {
  241. t.span.AddEventApm(name, eventType, l7Type, trace.WithAttributes(attrs...))
  242. atomic.AddUint32(t.currenEventCount, 1)
  243. }
  244. func (t *Trace) createTraceSpan(name string, duration time.Duration, error bool, attrs ...attribute.KeyValue) {
  245. end := time.Now()
  246. start := end.Add(-duration)
  247. //fmt.Println("createTraceSpan:", t.ctx)
  248. _, span := tracer(t.containerId).Start(t.ctx, name, trace.WithTimestamp(start), trace.WithSpanKind(trace.SpanKindClient))
  249. span.SetAttributes(t.commonAttrs...)
  250. span.SetAttributes(attrs...)
  251. if error {
  252. span.SetStatus(codes.Error, "")
  253. }
  254. span.End(trace.WithTimestamp(end))
  255. }
  256. func (t *Trace) MysqlTraceQuery(query string, error bool, duration time.Duration, destination netaddr.IPPort) {
  257. if t == nil || query == "" {
  258. return
  259. }
  260. t.createTraceSpan(l7.ProtocolMysql.String(), duration, error,
  261. semconv.DBSystemMySQL,
  262. semconv.DBStatement(query),
  263. semconv.NetPeerName(destination.IP().String()),
  264. semconv.NetPeerPort(int(destination.Port())),
  265. )
  266. }
  267. func (t *Trace) MysqlTraceQueryEvent(query string, r *l7.RequestData, destination netaddr.IPPort) {
  268. if t == nil || query == "" {
  269. return
  270. }
  271. var attr []attribute.KeyValue
  272. attr = append(attr,
  273. semconv.DBSystemMySQL,
  274. semconv.DBStatement(query),
  275. semconv.NetPeerName(destination.IP().String()),
  276. semconv.NetPeerPort(int(destination.Port())),
  277. )
  278. t.appendTimestamp(&attr, r.StartAt, r.EndAt, r.Duration.Nanoseconds())
  279. t.createTraceEvent(l7.ProtocolHTTP.String(), int(ebpftracer.EventTypeL7Request), int(l7.ProtocolMysql), attr...)
  280. }
  281. func (t *Trace) RedisTraceQuery(cmd, args string, error bool, duration time.Duration) {
  282. if t == nil || cmd == "" {
  283. return
  284. }
  285. statement := cmd
  286. if args != "" {
  287. statement += " " + args
  288. }
  289. t.createTraceSpan(l7.ProtocolRedis.String(), duration, error,
  290. semconv.DBSystemRedis,
  291. semconv.DBOperation(cmd),
  292. semconv.DBStatement(statement),
  293. )
  294. }
  295. func (t *Trace) RedisTraceQueryEvent(cmd, args string, r *l7.RequestData, destination netaddr.IPPort) {
  296. if t == nil || cmd == "" {
  297. return
  298. }
  299. statement := cmd
  300. if args != "" {
  301. statement += " " + args
  302. }
  303. var attr []attribute.KeyValue
  304. attr = append(attr,
  305. semconv.DBSystemRedis,
  306. semconv.DBOperation(cmd),
  307. semconv.DBStatement(statement),
  308. semconv.NetPeerName(destination.IP().String()),
  309. semconv.NetPeerPort(int(destination.Port())),
  310. )
  311. t.appendTimestamp(&attr, r.StartAt, r.EndAt, r.Duration.Nanoseconds())
  312. t.createTraceEvent(l7.ProtocolHTTP.String(), int(ebpftracer.EventTypeL7Request), int(l7.ProtocolRedis), attr...)
  313. }
  314. func (t *Trace) HttpTraceRequest(method, path, ip string, port uint16, r *l7.RequestData) {
  315. if t == nil || method == "" {
  316. return
  317. }
  318. assumedAppID, err := strconv.ParseInt(r.AssumedAppId, 10, 64)
  319. if err != nil {
  320. assumedAppID = 0
  321. }
  322. status := r.Status
  323. duration := r.Duration
  324. t.createTraceSpan(l7.ProtocolHTTP.String(), duration, status >= 400,
  325. semconv.HTTPURL(fmt.Sprintf("http://%s%s", t.destination.String(), path)),
  326. semconv.HTTPMethod(method),
  327. semconv.HTTPStatusCode(int(status)),
  328. attribute.String("http.uri", path),
  329. attribute.String("http.ip", ip),
  330. attribute.Int64("http.assumed_app_id", assumedAppID),
  331. attribute.String("http.span_id", r.SpanId),
  332. attribute.Int("http.port", int(port)),
  333. )
  334. }
  335. // 新增事件处理
  336. func (t *Trace) HttpTraceRequestEvent(method, path, ip string, port uint16, r *l7.RequestData) {
  337. if t == nil || method == "" {
  338. return
  339. }
  340. assumedAppID, err := strconv.ParseInt(r.AssumedAppId, 10, 64)
  341. if err != nil {
  342. assumedAppID = 0
  343. }
  344. status := r.Status
  345. var attr []attribute.KeyValue
  346. attr = append(attr,
  347. semconv.HTTPURL(fmt.Sprintf("http://%s%s", t.destination.String(), path)),
  348. semconv.HTTPMethod(method),
  349. semconv.HTTPStatusCode(int(status)),
  350. attribute.Bool("http.status_error", status > 399),
  351. attribute.String("http.uri", path),
  352. attribute.String("http.ip", ip),
  353. attribute.Int64("http.assumed_app_id", assumedAppID),
  354. attribute.String("http.span_id", r.SpanId),
  355. attribute.Int("http.port", int(port)),
  356. )
  357. t.appendTimestamp(&attr, r.StartAt, r.EndAt, r.Duration.Nanoseconds())
  358. t.createTraceEvent(l7.ProtocolHTTP.String(), int(ebpftracer.EventTypeL7Request), int(l7.ProtocolHTTP), attr...)
  359. }
  360. func (t *Trace) FuncTraceQuery(funcname string, duration time.Duration, start uint64, end uint64) {
  361. if t == nil || funcname == "" {
  362. return
  363. }
  364. t.createTraceSpanNoTime2(funcname, duration, false, start, end)
  365. //t.createTraceSpanNoTime2(funcname, duration, false, start, end, attribute.Int("num", num))
  366. }
  367. func (t *Trace) createTraceSpanNoTime(name string, duration time.Duration, error bool, start uint64, end uint64, attrs ...attribute.KeyValue) {
  368. // end := time.Now()
  369. // start := end.Add(-duration)
  370. startTime := time.Unix(0, int64(start))
  371. endTime := time.Unix(0, int64(end))
  372. //fmt.Println("createTraceSpan:", t.ctx)
  373. _, span := tracer(t.containerId).Start(t.ctx, name, trace.WithTimestamp(startTime), trace.WithSpanKind(trace.SpanKindClient))
  374. span.SetAttributes(t.commonAttrs...)
  375. span.SetAttributes(attrs...)
  376. if error {
  377. span.SetStatus(codes.Error, "")
  378. }
  379. span.End(trace.WithTimestamp(endTime))
  380. }
  381. func (t *Trace) createTraceSpanNoTime2(name string, duration time.Duration, error bool, start uint64, end uint64) {
  382. // end := time.Now()
  383. // start := end.Add(-duration)
  384. //startTime := time.Unix(0, int64(start))
  385. //endTime := time.Unix(0, int64(end))
  386. ////fmt.Println("createTraceSpan:", t.ctx)
  387. //_, span := tracer(t.containerId).Start(t.ctx, name, trace.WithTimestamp(startTime), trace.WithSpanKind(trace.SpanKindClient))
  388. //span.SetAttributes(t.commonAttrs...)
  389. //span.SetAttributes(attrs...)
  390. //if error {
  391. // span.SetStatus(codes.Error, "")
  392. //}
  393. //span.End(trace.WithTimestamp(endTime))
  394. //attrs = append([]attribute.KeyValue{
  395. // attribute.Int64("startAt", int64(start)),
  396. // attribute.Int64("endAt", int64(end)),
  397. //})
  398. var attr []attribute.KeyValue
  399. t.appendTimestamp(&attr, start, end, int64(end-start))
  400. t.createTraceEvent(name, int(ebpftracer.EventTypeFunEnt), 0, attr...)
  401. }