container_apm.go 12 KB

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