container_apm.go 12 KB

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