container_apm.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541
  1. package containers
  2. import (
  3. "bufio"
  4. "bytes"
  5. "debug/elf"
  6. "fmt"
  7. "os"
  8. "sort"
  9. "strconv"
  10. "strings"
  11. "time"
  12. "github.com/coroot/coroot-node-agent/ebpftracer"
  13. "github.com/coroot/coroot-node-agent/ebpftracer/l7"
  14. "github.com/coroot/coroot-node-agent/ebpftracer/tracer"
  15. "github.com/coroot/coroot-node-agent/proc"
  16. "github.com/coroot/coroot-node-agent/tracing"
  17. "github.com/coroot/coroot-node-agent/utils"
  18. . "github.com/coroot/coroot-node-agent/utils/modelse"
  19. "github.com/pkg/errors"
  20. klog "github.com/sirupsen/logrus"
  21. "inet.af/netaddr"
  22. )
  23. const TRACE_STATUS = 1
  24. func (c *Container) getTrace(traceId uint64) (*tracing.Trace, bool) {
  25. trace, ok := c.traceMap[traceId]
  26. return trace, ok
  27. }
  28. func (c *Container) createTraceMap(traceId uint64, trace *tracing.Trace) {
  29. c.traceMap[traceId] = trace
  30. }
  31. // 查询或创建trace信息
  32. func (c *Container) getOrInitTrace(traceId uint64) (*tracing.Trace, error) {
  33. trace, ok := c.getTrace(traceId)
  34. if !ok {
  35. //new trace
  36. trace = tracing.NewTraceFromEvent(string(c.id))
  37. //create TraceMap
  38. c.createTraceMap(traceId, trace)
  39. //create ParentSpan
  40. trace.CreateRootSpan(traceId)
  41. }
  42. return trace, nil
  43. }
  44. func (c *Container) InitTrace(traceId uint64, r *l7.RequestData) error {
  45. method, path, hostIp, port := l7.ParseHttpHost(r.Payload)
  46. ip, err := netaddr.ParseIP(hostIp)
  47. if err != nil {
  48. fmt.Println("host ip error")
  49. hostIp = "127.0.0.1"
  50. }
  51. addr := netaddr.IPPortFrom(ip, port)
  52. trace := tracing.NewTrace(string(c.id), addr)
  53. if trace == nil {
  54. return fmt.Errorf("OTEL_EXPORTER_OTLP_TRACES_ENDPOINT is null")
  55. }
  56. c.traceMap[traceId] = trace
  57. trace.TraceStart(method, path, r.Status, r.Duration)
  58. return nil
  59. }
  60. // 在任意阶段,r.TraceId 不等于0 则创建 traceMap && createParentSpan
  61. // 更新 createTraceSpan 机制,更新触发traceEnd机制,当事件个数满足时,任意event均可触发end
  62. func (c *Container) SendEvent(t *tracing.Trace, traceID uint64) {
  63. if t.AllEventReady(traceID) {
  64. t.SendEvent()
  65. klog.Infof("SendEvent %d", traceID)
  66. //fmt.Println(t.GetSpan())
  67. //fmt.Println("===============")
  68. delete(c.traceMap, traceID)
  69. }
  70. }
  71. func (c *Container) valuableTrace(traceID uint64) bool {
  72. return traceID != 0
  73. }
  74. func (c *Container) onL7RequestApm(pid uint32, fd uint64, timestamp uint64, r *l7.RequestData) map[netaddr.IP]string {
  75. c.lock.Lock()
  76. defer c.lock.Unlock()
  77. if r.Protocol == l7.ProtocolDNS {
  78. ip2fqdn, _type, fqdn := c.onDNSRequest(r)
  79. if c.l7Attach && c.valuableTrace(r.TraceId) {
  80. apmTrace, err := c.getOrInitTrace(r.TraceId)
  81. if err == nil {
  82. apmTrace.DNSTraceQueryEvent(r, _type, fqdn)
  83. c.SendEvent(apmTrace, r.TraceId)
  84. }
  85. }
  86. return ip2fqdn
  87. }
  88. //if !c.valuableTrace(r.TraceId) {
  89. // return nil
  90. //}
  91. // klog.Infof("====ProtocolTrace+++++ start==== %d %d", pid, r.TraceId)
  92. // klog.Infof("====ProtocolTrace===== start==== %d %d", r.Protocol == l7.ProtocolTrace, c.l7Attach)
  93. if r.Protocol == l7.ProtocolTrace && c.valuableTrace(r.TraceId) {
  94. // klog.Infof("====ProtocolTrace---- start==== %d %d", pid, r.TraceId)
  95. if r.TraceStart == TRACE_STATUS {
  96. // klog.Infof("====ProtocolTrace start==== %d %d", pid, r.TraceId)
  97. trace, err := c.getOrInitTrace(r.TraceId)
  98. if err == nil {
  99. method, path, hostIp, port := l7.ParseHttpHost(r.Payload)
  100. ip, _ := netaddr.ParseIP(hostIp)
  101. //codeType := c.GetCodeTypeFromCache(pid)
  102. trace.TraceStartEvent(method, path, r.Status, netaddr.IPPortFrom(ip, port), pid, c.GetAppInfo())
  103. c.SendEvent(trace, r.TraceId)
  104. }
  105. return nil
  106. }
  107. if r.TraceEnd == TRACE_STATUS {
  108. klog.Infof("====ProtocolTrace end==== %d %d", pid, r.TraceId)
  109. trace, err := c.getOrInitTrace(r.TraceId)
  110. if err == nil {
  111. trace.TraceEndEvent(r)
  112. c.SendEvent(trace, r.TraceId)
  113. }
  114. return nil
  115. }
  116. }
  117. if r.Protocol == l7.ProtocolHTTP {
  118. if c.l7Attach && c.valuableTrace(r.TraceId) {
  119. method, path, hostIp, port := l7.ParseHttpHost(r.Payload)
  120. apmTrace, err := c.getOrInitTrace(r.TraceId)
  121. //fmt.Println("ProtocolHTTP-----", r.TraceId, err)
  122. if err == nil {
  123. apmTrace.HttpTraceRequestEvent(method, path, hostIp, port, r)
  124. c.SendEvent(apmTrace, r.TraceId)
  125. }
  126. }
  127. //return nil
  128. }
  129. conn := c.connectionsByPidFd[PidFd{Pid: pid, Fd: fd}]
  130. //fmt.Println("l7.connectionsByPidFd", conn, pid, fd)
  131. if conn == nil {
  132. return nil
  133. }
  134. if timestamp != 0 && conn.Timestamp != timestamp {
  135. return nil
  136. }
  137. stats := c.l7Stats.get(r.Protocol, conn.Dest, conn.ActualDest)
  138. //trace := tracing.NewTrace(string(c.id), conn.ActualDest)
  139. switch r.Protocol {
  140. case l7.ProtocolHTTP:
  141. stats.observe(r.Status.Http(), "", r.Duration)
  142. case l7.ProtocolHTTP2:
  143. if conn.http2Parser == nil {
  144. conn.http2Parser = l7.NewHttp2Parser()
  145. }
  146. requests := conn.http2Parser.Parse(r.Method, r.Payload, uint64(r.Duration))
  147. for _, req := range requests {
  148. stats.observe(req.Status.Http(), "", req.Duration)
  149. //trace.Http2Request(req.Method, req.Path, req.Scheme, req.Status, req.Duration)
  150. }
  151. case l7.ProtocolPostgres:
  152. if r.Method != l7.MethodStatementClose {
  153. stats.observe(r.Status.String(), "", r.Duration)
  154. }
  155. //if conn.postgresParser == nil {
  156. // conn.postgresParser = l7.NewPostgresParser()
  157. //}
  158. //query := conn.postgresParser.Parse(r.Payload)
  159. //trace.PostgresQuery(query, r.Status.Error(), r.Duration)
  160. case l7.ProtocolMysql:
  161. if r.Method != l7.MethodStatementClose {
  162. stats.observe(r.Status.String(), "", r.Duration)
  163. }
  164. if c.l7Attach && c.valuableTrace(r.TraceId) {
  165. if conn.mysqlParser == nil {
  166. conn.mysqlParser = l7.NewMysqlParser()
  167. }
  168. query := conn.mysqlParser.Parse(r.Payload, r.StatementId)
  169. //trace.MysqlQuery(query, r.Status.Error(), r.Duration)
  170. //apmTrace, ok := c.getTrace(r.TraceId)
  171. apmTrace, err := c.getOrInitTrace(r.TraceId)
  172. fmt.Println(err)
  173. //fmt.Println("mysql r.TraceId:", r.TraceId)
  174. //fmt.Println("ok:", ok)
  175. //fmt.Println("traceMap:", len(c.traceMap))
  176. if err == nil {
  177. //apmTrace.MysqlTraceQuery(query, r.Status.Error(), r.Duration, conn.ActualDest)
  178. apmTrace.MysqlTraceQueryEvent(query, r, conn.ActualDest)
  179. c.SendEvent(apmTrace, r.TraceId)
  180. }
  181. }
  182. case l7.ProtocolDM:
  183. fmt.Println("---- onL7RequestApm ProtocolDM start ---->")
  184. fmt.Println("-------dm r.Status :", r.Status)
  185. if conn.dmParser == nil {
  186. conn.dmParser = l7.NewDmParser()
  187. }
  188. query := conn.dmParser.Parse(r.Payload, r.StatementId)
  189. apmTrace, err := c.getOrInitTrace(r.TraceId)
  190. fmt.Println("-------dm r.TraceId:", r.TraceId)
  191. if err == nil {
  192. apmTrace.DmTraceQueryEvent(query, r, conn.ActualDest)
  193. c.SendEvent(apmTrace, r.TraceId)
  194. }
  195. fmt.Println("---- onL7RequestApm ProtocolDM end <----")
  196. case l7.ProtocolMemcached:
  197. stats.observe(r.Status.String(), "", r.Duration)
  198. if c.l7Attach && c.valuableTrace(r.TraceId) {
  199. }
  200. //cmd, items := l7.ParseMemcached(r.Payload)
  201. //trace.MemcachedQuery(cmd, items, r.Status.Error(), r.Duration)
  202. case l7.ProtocolRedis:
  203. stats.observe(r.Status.String(), "", r.Duration)
  204. if c.l7Attach && c.valuableTrace(r.TraceId) {
  205. cmd, args := l7.ParseRedis(r.Payload)
  206. //fmt.Println("cmd", cmd)
  207. //fmt.Println("args", args)
  208. //apmTrace, ok := c.getTrace(r.TraceId)
  209. apmTrace, err := c.getOrInitTrace(r.TraceId)
  210. if err == nil {
  211. //apmTrace.RedisTraceQuery(cmd, args, r.Status.Error(), r.Duration)
  212. apmTrace.RedisTraceQueryEvent(cmd, args, r, conn.ActualDest)
  213. c.SendEvent(apmTrace, r.TraceId)
  214. }
  215. }
  216. //trace.RedisQuery(cmd, args, r.Status.Error(), r.Duration)
  217. case l7.ProtocolMongo:
  218. stats.observe(r.Status.String(), "", r.Duration)
  219. if c.l7Attach && c.valuableTrace(r.TraceId) {
  220. }
  221. //query := l7.ParseMongo(r.Payload)
  222. //trace.MongoQuery(query, r.Status.Error(), r.Duration)
  223. case l7.ProtocolKafka, l7.ProtocolCassandra:
  224. stats.observe(r.Status.String(), "", r.Duration)
  225. if c.l7Attach && c.valuableTrace(r.TraceId) {
  226. }
  227. case l7.ProtocolRabbitmq, l7.ProtocolNats:
  228. stats.observe(r.Status.String(), r.Method.String(), 0)
  229. if c.l7Attach && c.valuableTrace(r.TraceId) {
  230. }
  231. case l7.ProtocolDubbo2:
  232. stats.observe(r.Status.String(), "", r.Duration)
  233. if c.l7Attach && c.valuableTrace(r.TraceId) {
  234. }
  235. }
  236. return nil
  237. }
  238. func (c *Container) buildIDs(pid uint32) bool {
  239. c.lock.Lock()
  240. defer c.lock.Unlock()
  241. p := c.processes[pid]
  242. if p != nil {
  243. p.cmdline = string(proc.GetRealCmdline(pid))
  244. }
  245. for address, val := range c.getListens() {
  246. if val == 1 {
  247. ip := address.IP()
  248. if ip.Is4() && !ip.IsLoopback() {
  249. // 获取端口号
  250. port := address.Port()
  251. //c.instanceID.IntVal, c.instanceID.HashtVal, _ =
  252. c.AppInfo.Sn = ip.String()
  253. c.AppInfo.Sport = int(port)
  254. strInstanceID := utils.BuildInt64ID(fmt.Sprintf("%s:%d", ip.String(), port))
  255. c.AppInfo.InstanceIdHash.IntVal, _ = strInstanceID.ToInt64()
  256. c.AppInfo.InstanceIdHash.HashtVal = strInstanceID.ToHashByte()
  257. //c.AppInfo.InstanceId = c.instanceID.IntVal
  258. strAgentID := utils.BuildInt64ID(fmt.Sprintf("%s:%s", strInstanceID, string(proc.GetExe(pid))))
  259. c.AppInfo.AgentId, _ = strAgentID.ToInt64()
  260. c.AppInfo.CodeType = c.GetCodeTypeFromCache(pid)
  261. return true
  262. }
  263. }
  264. }
  265. return false
  266. }
  267. func (c *Container) StackProcess(event ebpftracer.StackEvent, tracer *ebpftracer.Tracer) {
  268. c.lock.Lock()
  269. defer c.lock.Unlock()
  270. // get the associated uprobe
  271. uprobe, err := c.GetUprobe(event, tracer)
  272. if err != nil {
  273. fmt.Println("GetUprobeGetUprobe errer: %v", err)
  274. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  275. return
  276. }
  277. if event.TraceId <= 0 {
  278. fmt.Println("StackProcess TraceId id 0")
  279. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  280. return
  281. }
  282. // fmt.Printf("StackProcess 函数入口开始处理 fun:TraceId:%lld, Funcname:%s, time: %lld\n", event.TraceId, uprobe.Funcname, event.TimeNsEnd-event.TimeNsStart)
  283. stackFun := ebpftracer.StackFunEvent{}
  284. stackFun.Uprobe = &uprobe
  285. stackFun.StackEvent = event
  286. apmTrace, ok := c.getTrace(event.TraceId)
  287. if ok {
  288. apmTrace.FunAdd(stackFun)
  289. }
  290. }
  291. func byteExtractString(nameString [100]byte) string {
  292. n := bytes.IndexByte(nameString[:], 0)
  293. if n == -1 {
  294. n = len(nameString) // 没找到零值,使用数组长度
  295. }
  296. return string(nameString[:n])
  297. }
  298. func (c *Container) StackProcess2(event ebpftracer.StackEvent, tracer *ebpftracer.Tracer) {
  299. c.lock.Lock()
  300. defer c.lock.Unlock()
  301. // get the associated uprobe
  302. switch event.Location {
  303. case 0: // ret
  304. Funcname := ""
  305. if event.Type != uint64(CodeTypeJava) {
  306. uprobe, err := c.GetUprobe(event, tracer)
  307. if err != nil {
  308. fmt.Println("GetUprobeGetUprobe errer: %v", err)
  309. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  310. return
  311. }
  312. Funcname = uprobe.Funcname
  313. } else {
  314. ClassName := byteExtractString(event.ClassName)
  315. MethedName := byteExtractString(event.MethedName)
  316. Funcname = ClassName + "." + MethedName
  317. }
  318. if event.TraceId <= 0 {
  319. fmt.Println("StackProcess TraceId id 0")
  320. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  321. return
  322. }
  323. //fmt.Printf("StackProcess 函数入口开始处理 fun:TraceId:%lld, Funcname:%s, time: %lld\n", event.TraceId, uprobe.Funcname, event.TimeNsEnd-event.TimeNsStart)
  324. apmTrace, err := c.getOrInitTrace(event.TraceId)
  325. if err == nil {
  326. //fmt.Println("append FuncTraceQuery fun:", event.TraceId, uprobe.Funcname, event.Pid)
  327. duration := event.TimeNsEnd - event.TimeNsStart
  328. apmTrace.FuncTraceQuery(Funcname, time.Duration(duration), event.TimeNsStart, event.TimeNsEnd)
  329. c.SendEvent(apmTrace, event.TraceId)
  330. }
  331. }
  332. }
  333. // ResolveAddress returns the symbol(s) and offset of the given address.
  334. func (c *Container) ResolveAddress(addr uint64, symbols []elf.Symbol) (syms []elf.Symbol, offset uint, err error) {
  335. if addr == 0 {
  336. // err = errors.Wrapf(SymbolNotFoundError, "0")
  337. return
  338. }
  339. // symbols, _, err := e.Symbols()
  340. if err != nil {
  341. return
  342. }
  343. idx := sort.Search(len(symbols), func(i int) bool { return symbols[i].Value > addr })
  344. if idx == 0 {
  345. // err = errors.Wrap(SymbolNotFoundError, fmt.Sprintf("%x", addr))
  346. return
  347. }
  348. // why diff symbol may contains the same addr?
  349. sym := symbols[idx-1]
  350. for i := idx - 1; i >= 0 && symbols[i].Value == sym.Value; i-- {
  351. syms = append(syms, symbols[i])
  352. }
  353. for i := idx; i < len(symbols) && symbols[i].Value == sym.Value; i++ {
  354. syms = append(syms, symbols[i])
  355. }
  356. return syms, uint(addr - sym.Value), nil
  357. }
  358. type MemoryMap struct {
  359. Start, End uint64
  360. }
  361. // ReadFirstLineOfMapsFile reads the first line of /proc/<pid>/maps file and return the memory map as a MemoryMap struct
  362. func ReadFirstLineOfMapsFile(pid string) (*MemoryMap, error) {
  363. file, err := os.Open(fmt.Sprintf("/proc/%s/maps", pid))
  364. if err != nil {
  365. return nil, err
  366. }
  367. defer file.Close()
  368. scanner := bufio.NewScanner(file)
  369. if scanner.Scan() {
  370. fields := strings.Fields(scanner.Text())
  371. addresses := strings.Split(fields[0], "-")
  372. if len(addresses) != 2 {
  373. return nil, errors.New("unexpected format in /proc/<pid>/maps")
  374. }
  375. start, err := strconv.ParseUint(addresses[0], 16, 64)
  376. if err != nil {
  377. return nil, err
  378. }
  379. end, err := strconv.ParseUint(addresses[1], 16, 64)
  380. if err != nil {
  381. return nil, err
  382. }
  383. return &MemoryMap{
  384. Start: start,
  385. End: end,
  386. }, nil
  387. }
  388. if err := scanner.Err(); err != nil {
  389. return nil, err
  390. }
  391. return nil, errors.New("empty /proc/<pid>/maps")
  392. }
  393. func (c *Container) GetUprobe(event ebpftracer.StackEvent, tracer *ebpftracer.Tracer) (uprobe tracer.Uprobe, err error) {
  394. //fmt.Println("GetUprobe entory:")
  395. memoryMap, _ := ReadFirstLineOfMapsFile(strconv.Itoa(int(event.Pid)))
  396. Address := event.Ip - memoryMap.Start
  397. // fmt.Printf("memoryMap.Start: %x, event.Ip: %x, Address: %x\n", memoryMap.Start, event.Ip, Address)
  398. for _, fun := range c.UprobesMap {
  399. funAddress := fun.Address + fun.AbsOffset
  400. // fmt.Printf("GetUprobeGetUprobeGetUprobe:fun.Address %x, fun.AbsOffset: %x\n", fun.Address, fun.AbsOffset)
  401. if funAddress == Address {
  402. // fmt.Printf("---GetUprobeGetUprobeGetUprobe: %x, event.Ip: %x ---- %s--%x\n", memoryMap.Start, event.Ip, fun.Funcname, fun.Address)
  403. return fun, nil
  404. }
  405. }
  406. syms, _, err := c.ResolveAddress(event.Ip, tracer.Symbols)
  407. if err != nil {
  408. return
  409. }
  410. for _, sym := range syms {
  411. //fmt.Println("GetUprobeGetUprobeGetUprobe: %s+%d", sym.Name, offset)
  412. uprobe, ok := tracer.UprobesMap[fmt.Sprintf("%s-%s", sym.Name, sym.Value)]
  413. if ok {
  414. return uprobe, nil
  415. }
  416. }
  417. err = errors.New("uprobe not found")
  418. return
  419. }
  420. func (c *Container) GetAppInfo() AppInfo {
  421. return c.AppInfo
  422. }
  423. // 可注入前置
  424. func (c *Container) checkEventReady() bool {
  425. c.lock.Lock()
  426. defer c.lock.Unlock()
  427. return c.l7EventReady
  428. }
  429. func (c *Container) eventReady() {
  430. c.lock.Lock()
  431. defer c.lock.Unlock()
  432. c.l7EventReady = true
  433. }
  434. // uprobe前置
  435. func (c *Container) checkL7AttachReady() bool {
  436. c.lock.Lock()
  437. defer c.lock.Unlock()
  438. return c.l7Attach
  439. }
  440. func (c *Container) l7AttachSuccess() {
  441. c.lock.Lock()
  442. defer c.lock.Unlock()
  443. c.l7Attach = true
  444. }
  445. func (c *Container) verifyAttachConditions(r *Registry, pid uint32) bool {
  446. p := c.processes[pid]
  447. if p != nil && c.checkEventReady() {
  448. codeType := c.GetCodeTypeFromCache(pid)
  449. if codeType.IsUnknownCode() {
  450. klog.WithField("pid", pid).Infof("[verify] unknown language.")
  451. return false
  452. }
  453. cmdline := p.GetCmdline()
  454. if len(cmdline) == 0 {
  455. return false
  456. }
  457. whiteListByCode := r.getWhiteListByCodeType(codeType)
  458. klog.WithField("pid", pid).WithField("codeType", codeType.String()).
  459. Infof("[verify] white list %v", whiteListByCode)
  460. // 当前语言的白名单规则
  461. for _, setting := range whiteListByCode {
  462. ruleVal := setting.Filters
  463. if ruleVal == "" {
  464. continue
  465. }
  466. // 判断规则
  467. if strings.Contains(cmdline, ruleVal) {
  468. c.WhiteSettingInfo = setting
  469. klog.WithField("pid", pid).
  470. WithField("ruleVal", ruleVal).
  471. WithField("cmdline", cmdline).
  472. Infoln("[verify] check successful.")
  473. return true
  474. }
  475. }
  476. }
  477. return false
  478. }
  479. func (c *Container) detachUprobes(pid uint32) {
  480. c.lock.Lock()
  481. defer c.lock.Unlock()
  482. // close uprobe
  483. if p := c.processes[pid]; p != nil {
  484. if len(p.uprobes) > 0 {
  485. klog.Infof("detachUprobes", pid)
  486. p.DynamicClose()
  487. c.l7Attach = false
  488. c.AppInfo = AppInfo{}
  489. }
  490. }
  491. }