container_apm.go 10 KB

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