container_apm.go 14 KB

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