container_apm.go 12 KB

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