container_apm.go 9.6 KB

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