container_apm.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539
  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. if r.Protocol == l7.ProtocolTrace && c.l7Attach && c.valuableTrace(r.TraceId) {
  92. if r.TraceStart == TRACE_STATUS {
  93. klog.Infof("====ProtocolTrace start==== %d %d", pid, r.TraceId)
  94. trace, err := c.getOrInitTrace(r.TraceId)
  95. if err == nil {
  96. method, path, hostIp, port := l7.ParseHttpHost(r.Payload)
  97. ip, _ := netaddr.ParseIP(hostIp)
  98. //codeType := c.GetCodeTypeFromCache(pid)
  99. trace.TraceStartEvent(method, path, r.Status, netaddr.IPPortFrom(ip, port), pid, c.GetAppInfo())
  100. c.SendEvent(trace, r.TraceId)
  101. }
  102. return nil
  103. }
  104. if r.TraceEnd == TRACE_STATUS {
  105. klog.Infof("====ProtocolTrace end==== %d %d", pid, r.TraceId)
  106. trace, err := c.getOrInitTrace(r.TraceId)
  107. if err == nil {
  108. trace.TraceEndEvent(r)
  109. c.SendEvent(trace, r.TraceId)
  110. }
  111. return nil
  112. }
  113. }
  114. if r.Protocol == l7.ProtocolHTTP {
  115. if c.l7Attach && c.valuableTrace(r.TraceId) {
  116. method, path, hostIp, port := l7.ParseHttpHost(r.Payload)
  117. apmTrace, err := c.getOrInitTrace(r.TraceId)
  118. //fmt.Println("ProtocolHTTP-----", r.TraceId, err)
  119. if err == nil {
  120. apmTrace.HttpTraceRequestEvent(method, path, hostIp, port, r)
  121. c.SendEvent(apmTrace, r.TraceId)
  122. }
  123. }
  124. //return nil
  125. }
  126. conn := c.connectionsByPidFd[PidFd{Pid: pid, Fd: fd}]
  127. //fmt.Println("l7.connectionsByPidFd", conn, pid, fd)
  128. if conn == nil {
  129. return nil
  130. }
  131. if timestamp != 0 && conn.Timestamp != timestamp {
  132. return nil
  133. }
  134. stats := c.l7Stats.get(r.Protocol, conn.Dest, conn.ActualDest)
  135. //trace := tracing.NewTrace(string(c.id), conn.ActualDest)
  136. switch r.Protocol {
  137. case l7.ProtocolHTTP:
  138. stats.observe(r.Status.Http(), "", r.Duration)
  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. if r.Method != l7.MethodStatementClose {
  159. stats.observe(r.Status.String(), "", r.Duration)
  160. }
  161. if c.l7Attach && c.valuableTrace(r.TraceId) {
  162. if conn.mysqlParser == nil {
  163. conn.mysqlParser = l7.NewMysqlParser()
  164. }
  165. query := conn.mysqlParser.Parse(r.Payload, r.StatementId)
  166. //trace.MysqlQuery(query, r.Status.Error(), r.Duration)
  167. //apmTrace, ok := c.getTrace(r.TraceId)
  168. apmTrace, err := c.getOrInitTrace(r.TraceId)
  169. fmt.Println(err)
  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. }
  179. case l7.ProtocolDM:
  180. fmt.Println("---- onL7RequestApm ProtocolDM start ---->")
  181. fmt.Println("-------dm r.Status :", r.Status)
  182. if conn.dmParser == nil {
  183. conn.dmParser = l7.NewDmParser()
  184. }
  185. query := conn.dmParser.Parse(r.Payload, r.StatementId)
  186. apmTrace, err := c.getOrInitTrace(r.TraceId)
  187. fmt.Println("-------dm r.TraceId:", r.TraceId)
  188. if err == nil {
  189. apmTrace.DmTraceQueryEvent(query, r, conn.ActualDest)
  190. c.SendEvent(apmTrace, r.TraceId)
  191. }
  192. fmt.Println("---- onL7RequestApm ProtocolDM end <----")
  193. case l7.ProtocolMemcached:
  194. stats.observe(r.Status.String(), "", r.Duration)
  195. if c.l7Attach && c.valuableTrace(r.TraceId) {
  196. }
  197. //cmd, items := l7.ParseMemcached(r.Payload)
  198. //trace.MemcachedQuery(cmd, items, r.Status.Error(), r.Duration)
  199. case l7.ProtocolRedis:
  200. stats.observe(r.Status.String(), "", r.Duration)
  201. if c.l7Attach && c.valuableTrace(r.TraceId) {
  202. cmd, args := l7.ParseRedis(r.Payload)
  203. //fmt.Println("cmd", cmd)
  204. //fmt.Println("args", args)
  205. //apmTrace, ok := c.getTrace(r.TraceId)
  206. apmTrace, err := c.getOrInitTrace(r.TraceId)
  207. if err == nil {
  208. //apmTrace.RedisTraceQuery(cmd, args, r.Status.Error(), r.Duration)
  209. apmTrace.RedisTraceQueryEvent(cmd, args, r, conn.ActualDest)
  210. c.SendEvent(apmTrace, r.TraceId)
  211. }
  212. }
  213. //trace.RedisQuery(cmd, args, r.Status.Error(), r.Duration)
  214. case l7.ProtocolMongo:
  215. stats.observe(r.Status.String(), "", r.Duration)
  216. if c.l7Attach && c.valuableTrace(r.TraceId) {
  217. }
  218. //query := l7.ParseMongo(r.Payload)
  219. //trace.MongoQuery(query, r.Status.Error(), r.Duration)
  220. case l7.ProtocolKafka, l7.ProtocolCassandra:
  221. stats.observe(r.Status.String(), "", r.Duration)
  222. if c.l7Attach && c.valuableTrace(r.TraceId) {
  223. }
  224. case l7.ProtocolRabbitmq, l7.ProtocolNats:
  225. stats.observe(r.Status.String(), r.Method.String(), 0)
  226. if c.l7Attach && c.valuableTrace(r.TraceId) {
  227. }
  228. case l7.ProtocolDubbo2:
  229. stats.observe(r.Status.String(), "", r.Duration)
  230. if c.l7Attach && c.valuableTrace(r.TraceId) {
  231. }
  232. }
  233. return nil
  234. }
  235. func (c *Container) buildIDs(pid uint32) bool {
  236. c.lock.Lock()
  237. defer c.lock.Unlock()
  238. p := c.processes[pid]
  239. if p != nil {
  240. p.cmdline = string(proc.GetRealCmdline(pid))
  241. }
  242. for address, val := range c.getListens() {
  243. if val == 1 {
  244. ip := address.IP()
  245. if ip.Is4() && !ip.IsLoopback() {
  246. // 获取端口号
  247. port := address.Port()
  248. //c.instanceID.IntVal, c.instanceID.HashtVal, _ =
  249. c.AppInfo.Sn = ip.String()
  250. c.AppInfo.Sport = int(port)
  251. strInstanceID := utils.BuildInt64ID(fmt.Sprintf("%s:%d", ip.String(), port))
  252. c.AppInfo.InstanceIdHash.IntVal, _ = strInstanceID.ToInt64()
  253. c.AppInfo.InstanceIdHash.HashtVal = strInstanceID.ToHashByte()
  254. //c.AppInfo.InstanceId = c.instanceID.IntVal
  255. strAgentID := utils.BuildInt64ID(fmt.Sprintf("%s:%s", strInstanceID, string(proc.GetExe(pid))))
  256. c.AppInfo.AgentId, _ = strAgentID.ToInt64()
  257. c.AppInfo.CodeType = c.GetCodeTypeFromCache(pid)
  258. return true
  259. }
  260. }
  261. }
  262. return false
  263. }
  264. func (c *Container) StackProcess(event ebpftracer.StackEvent, tracer *ebpftracer.Tracer) {
  265. c.lock.Lock()
  266. defer c.lock.Unlock()
  267. // get the associated uprobe
  268. uprobe, err := c.GetUprobe(event, tracer)
  269. if err != nil {
  270. fmt.Println("GetUprobeGetUprobe errer: %v", err)
  271. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  272. return
  273. }
  274. if event.TraceId <= 0 {
  275. fmt.Println("StackProcess TraceId id 0")
  276. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  277. return
  278. }
  279. // fmt.Printf("StackProcess 函数入口开始处理 fun:TraceId:%lld, Funcname:%s, time: %lld\n", event.TraceId, uprobe.Funcname, event.TimeNsEnd-event.TimeNsStart)
  280. stackFun := ebpftracer.StackFunEvent{}
  281. stackFun.Uprobe = &uprobe
  282. stackFun.StackEvent = event
  283. apmTrace, ok := c.getTrace(event.TraceId)
  284. if ok {
  285. apmTrace.FunAdd(stackFun)
  286. }
  287. }
  288. func byteExtractString(nameString [100]byte) string {
  289. n := bytes.IndexByte(nameString[:], 0)
  290. if n == -1 {
  291. n = len(nameString) // 没找到零值,使用数组长度
  292. }
  293. return string(nameString[:n])
  294. }
  295. func (c *Container) StackProcess2(event ebpftracer.StackEvent, tracer *ebpftracer.Tracer) {
  296. c.lock.Lock()
  297. defer c.lock.Unlock()
  298. // get the associated uprobe
  299. switch event.Location {
  300. case 0: // ret
  301. Funcname := ""
  302. if event.Type != uint64(CodeTypeJava) {
  303. uprobe, err := c.GetUprobe(event, tracer)
  304. if err != nil {
  305. fmt.Println("GetUprobeGetUprobe errer: %v", err)
  306. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  307. return
  308. }
  309. Funcname = uprobe.Funcname
  310. } else {
  311. ClassName := byteExtractString(event.ClassName)
  312. MethedName := byteExtractString(event.MethedName)
  313. Funcname = ClassName + "." + MethedName
  314. }
  315. if event.TraceId <= 0 {
  316. fmt.Println("StackProcess TraceId id 0")
  317. // log.Errorf("failed to get uprobe for event %+v: %+v", event, err)
  318. return
  319. }
  320. //fmt.Printf("StackProcess 函数入口开始处理 fun:TraceId:%lld, Funcname:%s, time: %lld\n", event.TraceId, uprobe.Funcname, event.TimeNsEnd-event.TimeNsStart)
  321. apmTrace, err := c.getOrInitTrace(event.TraceId)
  322. if err == nil {
  323. //fmt.Println("append FuncTraceQuery fun:", event.TraceId, uprobe.Funcname, event.Pid)
  324. duration := event.TimeNsEnd - event.TimeNsStart
  325. apmTrace.FuncTraceQuery(Funcname, time.Duration(duration), event.TimeNsStart, event.TimeNsEnd)
  326. c.SendEvent(apmTrace, event.TraceId)
  327. }
  328. }
  329. }
  330. // ResolveAddress returns the symbol(s) and offset of the given address.
  331. func (c *Container) ResolveAddress(addr uint64, symbols []elf.Symbol) (syms []elf.Symbol, offset uint, err error) {
  332. if addr == 0 {
  333. // err = errors.Wrapf(SymbolNotFoundError, "0")
  334. return
  335. }
  336. // symbols, _, err := e.Symbols()
  337. if err != nil {
  338. return
  339. }
  340. idx := sort.Search(len(symbols), func(i int) bool { return symbols[i].Value > addr })
  341. if idx == 0 {
  342. // err = errors.Wrap(SymbolNotFoundError, fmt.Sprintf("%x", addr))
  343. return
  344. }
  345. // why diff symbol may contains the same addr?
  346. sym := symbols[idx-1]
  347. for i := idx - 1; i >= 0 && symbols[i].Value == sym.Value; i-- {
  348. syms = append(syms, symbols[i])
  349. }
  350. for i := idx; i < len(symbols) && symbols[i].Value == sym.Value; i++ {
  351. syms = append(syms, symbols[i])
  352. }
  353. return syms, uint(addr - sym.Value), nil
  354. }
  355. type MemoryMap struct {
  356. Start, End uint64
  357. }
  358. // ReadFirstLineOfMapsFile reads the first line of /proc/<pid>/maps file and return the memory map as a MemoryMap struct
  359. func ReadFirstLineOfMapsFile(pid string) (*MemoryMap, error) {
  360. file, err := os.Open(fmt.Sprintf("/proc/%s/maps", pid))
  361. if err != nil {
  362. return nil, err
  363. }
  364. defer file.Close()
  365. scanner := bufio.NewScanner(file)
  366. if scanner.Scan() {
  367. fields := strings.Fields(scanner.Text())
  368. addresses := strings.Split(fields[0], "-")
  369. if len(addresses) != 2 {
  370. return nil, errors.New("unexpected format in /proc/<pid>/maps")
  371. }
  372. start, err := strconv.ParseUint(addresses[0], 16, 64)
  373. if err != nil {
  374. return nil, err
  375. }
  376. end, err := strconv.ParseUint(addresses[1], 16, 64)
  377. if err != nil {
  378. return nil, err
  379. }
  380. return &MemoryMap{
  381. Start: start,
  382. End: end,
  383. }, nil
  384. }
  385. if err := scanner.Err(); err != nil {
  386. return nil, err
  387. }
  388. return nil, errors.New("empty /proc/<pid>/maps")
  389. }
  390. func (c *Container) GetUprobe(event ebpftracer.StackEvent, tracer *ebpftracer.Tracer) (uprobe tracer.Uprobe, err error) {
  391. //fmt.Println("GetUprobe entory:")
  392. memoryMap, _ := ReadFirstLineOfMapsFile(strconv.Itoa(int(event.Pid)))
  393. Address := event.Ip - memoryMap.Start
  394. // fmt.Printf("memoryMap.Start: %x, event.Ip: %x, Address: %x\n", memoryMap.Start, event.Ip, Address)
  395. for _, fun := range c.UprobesMap {
  396. funAddress := fun.Address + fun.AbsOffset
  397. // fmt.Printf("GetUprobeGetUprobeGetUprobe:fun.Address %x, fun.AbsOffset: %x\n", fun.Address, fun.AbsOffset)
  398. if funAddress == Address {
  399. // fmt.Printf("---GetUprobeGetUprobeGetUprobe: %x, event.Ip: %x ---- %s--%x\n", memoryMap.Start, event.Ip, fun.Funcname, fun.Address)
  400. return fun, nil
  401. }
  402. }
  403. syms, _, err := c.ResolveAddress(event.Ip, tracer.Symbols)
  404. if err != nil {
  405. return
  406. }
  407. for _, sym := range syms {
  408. //fmt.Println("GetUprobeGetUprobeGetUprobe: %s+%d", sym.Name, offset)
  409. uprobe, ok := tracer.UprobesMap[fmt.Sprintf("%s-%s", sym.Name, sym.Value)]
  410. if ok {
  411. return uprobe, nil
  412. }
  413. }
  414. err = errors.New("uprobe not found")
  415. return
  416. }
  417. func (c *Container) GetAppInfo() AppInfo {
  418. return c.AppInfo
  419. }
  420. // 可注入前置
  421. func (c *Container) checkEventReady() bool {
  422. c.lock.Lock()
  423. defer c.lock.Unlock()
  424. return c.l7EventReady
  425. }
  426. func (c *Container) eventReady() {
  427. c.lock.Lock()
  428. defer c.lock.Unlock()
  429. c.l7EventReady = true
  430. }
  431. // uprobe前置
  432. func (c *Container) checkL7AttachReady() bool {
  433. c.lock.Lock()
  434. defer c.lock.Unlock()
  435. return c.l7Attach
  436. }
  437. func (c *Container) l7AttachSuccess() {
  438. c.lock.Lock()
  439. defer c.lock.Unlock()
  440. c.l7Attach = true
  441. }
  442. func (c *Container) verifyAttachConditions(r *Registry, pid uint32) bool {
  443. p := c.processes[pid]
  444. if p != nil && c.checkEventReady() {
  445. codeType := c.GetCodeTypeFromCache(pid)
  446. if codeType.IsUnknownCode() {
  447. klog.WithField("pid", pid).Infof("[verify] unknown language.")
  448. return false
  449. }
  450. cmdline := p.GetCmdline()
  451. if len(cmdline) == 0 {
  452. return false
  453. }
  454. whiteListByCode := r.getWhiteListByCodeType(codeType)
  455. klog.WithField("pid", pid).WithField("codeType", codeType.String()).
  456. Infof("[verify] white list %v", whiteListByCode)
  457. // 当前语言的白名单规则
  458. for _, setting := range whiteListByCode {
  459. ruleVal := setting.Filters
  460. if ruleVal == "" {
  461. continue
  462. }
  463. // 判断规则
  464. if strings.Contains(cmdline, ruleVal) {
  465. c.WhiteSettingInfo = setting
  466. klog.WithField("pid", pid).
  467. WithField("ruleVal", ruleVal).
  468. WithField("cmdline", cmdline).
  469. Infoln("[verify] check successful.")
  470. return true
  471. }
  472. }
  473. }
  474. return false
  475. }
  476. func (c *Container) detachUprobes(pid uint32) {
  477. c.lock.Lock()
  478. defer c.lock.Unlock()
  479. // close uprobe
  480. if p := c.processes[pid]; p != nil {
  481. if len(p.uprobes) > 0 {
  482. klog.Infof("detachUprobes", pid)
  483. p.DynamicClose()
  484. c.l7Attach = false
  485. c.AppInfo = AppInfo{}
  486. }
  487. }
  488. }