container_apm.go 12 KB

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