container_apm.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326
  1. package containers
  2. import (
  3. "debug/elf"
  4. "fmt"
  5. "math/rand"
  6. "sort"
  7. "strconv"
  8. "time"
  9. "github.com/coroot/coroot-node-agent/ebpftracer"
  10. "github.com/coroot/coroot-node-agent/ebpftracer/l7"
  11. "github.com/coroot/coroot-node-agent/ebpftracer/tracer"
  12. "github.com/coroot/coroot-node-agent/tracing"
  13. "github.com/pkg/errors"
  14. "inet.af/netaddr"
  15. )
  16. func (c *Container) getTrace(traceId uint64) (*tracing.Trace, bool) {
  17. trace, ok := c.traceMap[traceId]
  18. return trace, ok
  19. }
  20. func (c *Container) InitTrace(traceId uint64, r *l7.RequestData) error {
  21. method, path, hostIp, port := l7.ParseHttpHost(r.Payload)
  22. ip, err := netaddr.ParseIP(hostIp)
  23. if err != nil {
  24. return fmt.Errorf("host ip error")
  25. }
  26. addr := netaddr.IPPortFrom(ip, port)
  27. trace := tracing.NewTrace(string(c.id), addr)
  28. if trace == nil {
  29. return fmt.Errorf("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT is null")
  30. }
  31. c.traceMap[traceId] = trace
  32. trace.TraceStart(method, path, r.Status, r.Duration)
  33. return nil
  34. }
  35. func (c *Container) onL7RequestApm(pid uint32, fd uint64, timestamp uint64, r *l7.RequestData) map[netaddr.IP]string {
  36. c.lock.Lock()
  37. defer c.lock.Unlock()
  38. if r.Protocol == l7.ProtocolDNS {
  39. return c.onDNSRequest(r)
  40. }
  41. if r.Protocol == l7.ProtocolTrace {
  42. //fmt.Println("r.TraceStart:", r.TraceStart)
  43. //fmt.Println("r.TraceEnd:", r.TraceEnd)
  44. if r.TraceStart == 1 {
  45. //fmt.Println("====ProtocolTrace start1====", r.TraceId)
  46. err := c.InitTrace(r.TraceId, r)
  47. if err != nil {
  48. fmt.Println(err)
  49. }
  50. //fmt.Println("init r.TraceId:", r.TraceId)
  51. //trace, _ := c.getTrace(r.TraceId)
  52. //fmt.Println("init traceId", trace)
  53. //stats.observe(r.Status.Http(), "", r.Duration)
  54. //method, path := l7.ParseHttp(r.Payload)
  55. //fmt.Println("r.Payload:", string(r.Payload))
  56. //fmt.Println("method:", method)
  57. //fmt.Println("path:", path)
  58. //fmt.Println("====ProtocolTrace start2====")
  59. return nil
  60. }
  61. if r.TraceEnd == 1 {
  62. //fmt.Println("r:", r)
  63. //fmt.Println("r.Payload:", string(r.Payload))
  64. //fmt.Println("====ProtocolTrace end2====")
  65. trace, ok := c.getTrace(r.TraceId)
  66. if ok {
  67. trace.TraceEnd(r)
  68. delete(c.traceMap, r.TraceId)
  69. }
  70. //fmt.Println("====ProtocolTrace end1====", ok, r.TraceId)
  71. return nil
  72. }
  73. }
  74. conn := c.connectionsByPidFd[PidFd{Pid: pid, Fd: fd}]
  75. //fmt.Println(conn, pid, fd)
  76. if conn == nil {
  77. return nil
  78. }
  79. if timestamp != 0 && conn.Timestamp != timestamp {
  80. return nil
  81. }
  82. stats := c.l7Stats.get(r.Protocol, conn.Dest, conn.ActualDest)
  83. trace := tracing.NewTrace(string(c.id), conn.ActualDest)
  84. switch r.Protocol {
  85. case l7.ProtocolHTTP:
  86. stats.observe(r.Status.Http(), "", r.Duration)
  87. method, path, hostIp, port := l7.ParseHttpHost(r.Payload)
  88. //trace.HttpRequest(method, path, r.Status, r.Duration)
  89. apmTrace, ok := c.getTrace(r.TraceId)
  90. if ok {
  91. apmTrace.HttpTraceRequest(method, path, hostIp, port, r.Status, r.Duration)
  92. }
  93. case l7.ProtocolHTTP2:
  94. if conn.http2Parser == nil {
  95. conn.http2Parser = l7.NewHttp2Parser()
  96. }
  97. requests := conn.http2Parser.Parse(r.Method, r.Payload, uint64(r.Duration))
  98. for _, req := range requests {
  99. stats.observe(req.Status.Http(), "", req.Duration)
  100. trace.Http2Request(req.Method, req.Path, req.Scheme, req.Status, req.Duration)
  101. }
  102. case l7.ProtocolPostgres:
  103. if r.Method != l7.MethodStatementClose {
  104. stats.observe(r.Status.String(), "", r.Duration)
  105. }
  106. if conn.postgresParser == nil {
  107. conn.postgresParser = l7.NewPostgresParser()
  108. }
  109. query := conn.postgresParser.Parse(r.Payload)
  110. trace.PostgresQuery(query, r.Status.Error(), r.Duration)
  111. case l7.ProtocolMysql:
  112. //fmt.Println("mysql mysql")
  113. //fmt.Println(conn)
  114. if r.Method != l7.MethodStatementClose {
  115. stats.observe(r.Status.String(), "", r.Duration)
  116. }
  117. if conn.mysqlParser == nil {
  118. conn.mysqlParser = l7.NewMysqlParser()
  119. }
  120. query := conn.mysqlParser.Parse(r.Payload, r.StatementId)
  121. //trace.MysqlQuery(query, r.Status.Error(), r.Duration)
  122. apmTrace, ok := c.getTrace(r.TraceId)
  123. //fmt.Println("mysql r.TraceId:", r.TraceId)
  124. //fmt.Println("ok:", ok)
  125. //fmt.Println("traceMap:", len(c.traceMap))
  126. if ok {
  127. apmTrace.MysqlTraceQuery(query, r.Status.Error(), r.Duration, conn.ActualDest)
  128. }
  129. case l7.ProtocolMemcached:
  130. stats.observe(r.Status.String(), "", r.Duration)
  131. cmd, items := l7.ParseMemcached(r.Payload)
  132. trace.MemcachedQuery(cmd, items, r.Status.Error(), r.Duration)
  133. case l7.ProtocolRedis:
  134. fmt.Println("redis redis")
  135. stats.observe(r.Status.String(), "", r.Duration)
  136. cmd, args := l7.ParseRedis(r.Payload)
  137. fmt.Println("cmd", cmd)
  138. fmt.Println("args", args)
  139. apmTrace, ok := c.getTrace(r.TraceId)
  140. fmt.Println("redis r.TraceId:", r.TraceId)
  141. fmt.Println("ok:", ok)
  142. fmt.Println("traceMap:", len(c.traceMap))
  143. if ok {
  144. apmTrace.RedisTraceQuery(cmd, args, r.Status.Error(), r.Duration)
  145. }
  146. //trace.RedisQuery(cmd, args, r.Status.Error(), r.Duration)
  147. case l7.ProtocolMongo:
  148. stats.observe(r.Status.String(), "", r.Duration)
  149. query := l7.ParseMongo(r.Payload)
  150. trace.MongoQuery(query, r.Status.Error(), r.Duration)
  151. case l7.ProtocolKafka, l7.ProtocolCassandra:
  152. stats.observe(r.Status.String(), "", r.Duration)
  153. case l7.ProtocolRabbitmq, l7.ProtocolNats:
  154. stats.observe(r.Status.String(), r.Method.String(), 0)
  155. }
  156. return nil
  157. }
  158. func (c *Container) StackProcess(event ebpftracer.StackEvent, tracer *ebpftracer.Tracer) {
  159. c.lock.Lock()
  160. defer c.lock.Unlock()
  161. // get the associated uprobe
  162. switch event.Location {
  163. case 0: // ret
  164. uprobe, err := c.GetUprobe(event, tracer)
  165. if err != nil {
  166. fmt.Println("GetUprobeGetUprobe errer: %v", err)
  167. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  168. return
  169. }
  170. if event.TraceId <= 0 {
  171. fmt.Println("StackProcess TraceId id 0")
  172. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  173. return
  174. }
  175. fmt.Println("StackProcess 函数入口开始处理 fun:", event.TraceId, uprobe.Funcname, event.TimeNsEnd-event.TimeNsStart)
  176. apmTrace, ok := c.getTrace(event.TraceId)
  177. if ok {
  178. fmt.Println("append FuncTraceQuery fun:", event.TraceId, uprobe.Funcname, event.Pid)
  179. duration := event.TimeNsEnd - event.TimeNsStart
  180. apmTrace.FuncTraceQuery(uprobe.Funcname, time.Duration(duration), int(event.Level), int(event.Fpid), int(event.Nid))
  181. }
  182. case 2: // coroutine
  183. fmt.Println("StackProcess 协程入口开始处理 fun:", event.TraceId, event.Goid, event.TimeNsEnd-event.TimeNsStart)
  184. apmTrace, ok := c.getTrace(event.TraceId)
  185. if ok {
  186. fmt.Println("append FuncTraceQuery fun:", event.TraceId, "coroutine"+strconv.FormatUint(event.Goid, 10), event.Pid, event.Fpid)
  187. duration := event.TimeNsEnd - event.TimeNsStart
  188. apmTrace.FuncTraceQuery("coroutine"+strconv.FormatUint(event.Goid, 10), time.Duration(duration), int(event.Level), int(event.Fpid), int(event.Nid))
  189. }
  190. }
  191. }
  192. func (c *Container) StackProcessBak(event ebpftracer.StackEvent, tracer *ebpftracer.Tracer) {
  193. c.lock.Lock()
  194. defer c.lock.Unlock()
  195. // get the associated uprobe
  196. uprobe, err := c.GetUprobe(event, tracer)
  197. if err != nil {
  198. fmt.Println("GetUprobeGetUprobe errer: %v", err)
  199. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  200. return
  201. }
  202. if event.TraceId <= 0 {
  203. fmt.Println("StackProcess TraceId id 0")
  204. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  205. return
  206. }
  207. length := len(c.goEventStacks[event.TraceId])
  208. if length <= 0 {
  209. c.goEventStacks = map[uint64]map[uint64][]ebpftracer.StackFunEvent{}
  210. c.goEventStacks[event.TraceId] = map[uint64][]ebpftracer.StackFunEvent{}
  211. c.goEventStacks[event.TraceId][event.Goid] = []ebpftracer.StackFunEvent{}
  212. }
  213. switch event.Location {
  214. case 0: // entry
  215. level := 100
  216. pid := 100000 + event.Goid
  217. length := len(c.goEventStacks[event.TraceId][event.Goid])
  218. fmt.Println("StackProcess 函数入口开始处理 fun:", event.TraceId, uprobe.Funcname, length)
  219. if length > 0 {
  220. funEvent := c.goEventStacks[event.TraceId][event.Goid][length-1]
  221. fmt.Println("funEvent goEventStacks fun:", event.TraceId, funEvent.Uprobe.Funcname, funEvent.Nid, funEvent.Level)
  222. lastEvent := funEvent.StackEvent
  223. if lastEvent.Location == event.Location && lastEvent.Ip == event.Ip && lastEvent.Bp != event.CallerBp {
  224. // duplicated entry event due to stack expansion/shrinkage
  225. // log.Debugf("duplicated entry event: %+v", event)
  226. fmt.Println("GetUprobeGetUprobe duplicated entry event: %+v", event)
  227. c.goEventStacks[event.TraceId][event.Goid][length-1].StackEvent = event
  228. return
  229. }
  230. level = int(funEvent.Level)
  231. pid = uint64(funEvent.Nid)
  232. }
  233. rand.Seed(time.Now().UnixNano())
  234. // append new event
  235. fmt.Println("append goEventStacks fun:", event.TraceId, uprobe.Funcname, pid, level+1)
  236. c.goEventStacks[event.TraceId][event.Goid] = append(c.goEventStacks[event.TraceId][event.Goid], ebpftracer.StackFunEvent{
  237. StackEvent: event,
  238. Uprobe: &uprobe,
  239. Level: level + 1,
  240. Pid: int(pid),
  241. Nid: rand.Intn(100000000),
  242. })
  243. length = len(c.goEventStacks[event.TraceId][event.Goid])
  244. fmt.Println("append goEventStacks end:", event.TraceId, uprobe.Funcname, pid, level+1, length)
  245. case 1: // ret
  246. // fmt.Println("StackProcess 函数出口开始处理 fun:", event.TraceId, uprobe.Funcname)
  247. length := len(c.goEventStacks[event.TraceId][event.Goid])
  248. fmt.Println("StackProcess 函数出口开始处理 fun:", event.TraceId, uprobe.Funcname, length)
  249. if length > 0 {
  250. funEvent := c.goEventStacks[event.TraceId][event.Goid][length-1]
  251. entFun := funEvent.StackEvent
  252. apmTrace, ok := c.getTrace(event.TraceId)
  253. fmt.Println("StackProcess 函数出口处理 fun:", event.TraceId, funEvent.Uprobe.Funcname, length)
  254. if ok {
  255. fmt.Println("append FuncTraceQuery fun:", event.TraceId, uprobe.Funcname, funEvent.Pid, funEvent.Level, funEvent.Nid)
  256. duration := event.TimeNsEnd - entFun.TimeNsStart
  257. c.goEventStacks[event.TraceId][event.Goid] = c.goEventStacks[event.TraceId][event.Goid][:length-1]
  258. apmTrace.FuncTraceQuery(funEvent.Uprobe.Funcname, time.Duration(duration), funEvent.Level, funEvent.Pid, funEvent.Nid)
  259. }
  260. }
  261. }
  262. }
  263. // ResolveAddress returns the symbol(s) and offset of the given address.
  264. func (c *Container) ResolveAddress(addr uint64, symbols []elf.Symbol) (syms []elf.Symbol, offset uint, err error) {
  265. if addr == 0 {
  266. // err = errors.Wrapf(SymbolNotFoundError, "0")
  267. return
  268. }
  269. // symbols, _, err := e.Symbols()
  270. if err != nil {
  271. return
  272. }
  273. idx := sort.Search(len(symbols), func(i int) bool { return symbols[i].Value > addr })
  274. if idx == 0 {
  275. // err = errors.Wrap(SymbolNotFoundError, fmt.Sprintf("%x", addr))
  276. return
  277. }
  278. // why diff symbol may contains the same addr?
  279. sym := symbols[idx-1]
  280. for i := idx - 1; i >= 0 && symbols[i].Value == sym.Value; i-- {
  281. syms = append(syms, symbols[i])
  282. }
  283. for i := idx; i < len(symbols) && symbols[i].Value == sym.Value; i++ {
  284. syms = append(syms, symbols[i])
  285. }
  286. return syms, uint(addr - sym.Value), nil
  287. }
  288. func (c *Container) GetUprobe(event ebpftracer.StackEvent, tracer *ebpftracer.Tracer) (uprobe tracer.Uprobe, err error) {
  289. fmt.Println("GetUprobe entory:")
  290. syms, offset, err := c.ResolveAddress(event.Ip, tracer.Symbols)
  291. if err != nil {
  292. return
  293. }
  294. for _, sym := range syms {
  295. fmt.Println("GetUprobeGetUprobeGetUprobe: %s+%d", sym.Name, offset)
  296. uprobe, ok := tracer.UprobesMap[fmt.Sprintf("%s", sym.Name)]
  297. if ok {
  298. return uprobe, nil
  299. }
  300. }
  301. err = errors.New("uprobe not found")
  302. return
  303. }