stack.go 6.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213
  1. package ebpftracer
  2. import (
  3. "bufio"
  4. "fmt"
  5. "github.com/cilium/ebpf"
  6. "github.com/cilium/ebpf/link"
  7. "github.com/coroot/coroot-node-agent/ebpftracer/tracer"
  8. "github.com/coroot/coroot-node-agent/ebpftracer/tracer/jattach"
  9. "github.com/coroot/coroot-node-agent/utils"
  10. . "github.com/coroot/coroot-node-agent/utils/modelse"
  11. klog "github.com/sirupsen/logrus"
  12. "os"
  13. "path/filepath"
  14. "strconv"
  15. "strings"
  16. "syscall"
  17. )
  18. // AttachStackUprobes
  19. // default process stack
  20. func (t *Tracer) AttachStackUprobes(path string, uprobes []tracer.Uprobe) []link.Link {
  21. var links []link.Link
  22. ex, err := link.OpenExecutable(path)
  23. if err != nil {
  24. return nil
  25. }
  26. klog.Infoln("[stack] Attach Start", path)
  27. for i, up := range uprobes {
  28. klog.Debugf("[stack] attaching %d -> %d -> %s -> 0x%x -> 0x%x -> 0x%x", i, len(uprobes), up.Funcname, up.AbsOffset, up.Address, up.AbsOffset+up.Address)
  29. var prog *ebpf.Program
  30. switch up.Location {
  31. case tracer.AtEntry:
  32. prog = t.uprobes["ent"]
  33. case tracer.AtRet:
  34. prog = t.uprobes["ret"]
  35. case tracer.AtDotNetEntry:
  36. prog = t.uprobes["dotnetent"]
  37. }
  38. uplink, err := ex.Uprobe(up.Funcname, prog, &link.UprobeOptions{Address: up.Address, Offset: up.AbsOffset})
  39. if err != nil {
  40. klog.Errorf("[stack] attachingERROR:%v, %v, %v", err, up, uplink)
  41. // return nil
  42. } else {
  43. links = append(links, uplink)
  44. }
  45. }
  46. return links
  47. }
  48. // JVM process stack
  49. func (t *Tracer) JattachJvm(pid uint32, appInfo AppInfo, whiteList, blackList string) error {
  50. klog.Infoln("[Jvm stack uprobe] Attach Start AttachJVMStackUprobes", pid)
  51. // TODO tiny Agent 注入
  52. // TODO copy agent到 jre conf/lib/plugins
  53. //argkv := "/opt/github/euspace/dist/package_dir/agents/NativeAgent/lib/apmAgent.jar=/opt/github/euspace/dist/package_dir/agents/NativeAgent"
  54. if whiteList == "" && blackList == "" {
  55. return fmt.Errorf("no stack rule")
  56. }
  57. whiteList = strings.ReplaceAll(whiteList, ",", "")
  58. blackList = strings.ReplaceAll(blackList, ",", "")
  59. var stackRule string
  60. if whiteList == "" {
  61. stackRule = fmt.Sprintf("blackStack=%s", blackList) // 仅保留黑名单
  62. } else if blackList == "" {
  63. stackRule = fmt.Sprintf("whiteStack=%s", whiteList) // 仅保留白名单
  64. } else {
  65. stackRule = fmt.Sprintf("whiteStack=%s,blackStack=%s", whiteList, blackList)
  66. }
  67. nativeBasePath := utils.GetDefaultAgentsPath("NativeAgent")
  68. kvPairs := []string{
  69. fmt.Sprintf("%s=%s", filepath.Join(nativeBasePath, "lib", "apmAgent.jar"), nativeBasePath),
  70. fmt.Sprintf("%s=%d", "appId", appInfo.AppIdHash.IntVal),
  71. fmt.Sprintf("%s=%d", "agentId", appInfo.AgentId),
  72. fmt.Sprintf("%s=%d", "hostId", utils.GetHostID()),
  73. fmt.Sprintf("%s=%d", "accountId", utils.GetAccountID()),
  74. stackRule,
  75. }
  76. argkv := strings.Join(kvPairs, ",")
  77. klog.Infof("[Jvm stack uprobe] params:[%s]", argkv)
  78. args := []string{"load", "instrument", "false", argkv}
  79. jattacher := jattach.JvmJattacher{
  80. Pid: pid,
  81. Args: args,
  82. PrintOutput: 1,
  83. }
  84. res, err := jattacher.JAttach()
  85. klog.Infof("[Jvm stack uprobe] JAttach Result: %d", res)
  86. if err != nil {
  87. return err
  88. }
  89. return nil
  90. }
  91. func (t *Tracer) AttachJVMStackUprobes(pid uint32, appInfo AppInfo) ([]link.Link, error) {
  92. //path = utils.GetDefaultAgentsPath("NativeAgent", "libnativeAgent.so")
  93. //tmp/NativeAgentSo2297066477572820801.tmp
  94. path, err := FindNativeSoFromMapped(pid, "NativeAgentSo", ".tmp")
  95. if err != nil {
  96. klog.Error(err)
  97. return nil, err
  98. }
  99. setNodeEnter := "Java_com_cloudwise_agent_common_natives_TraceNative_setNodeEnter"
  100. setNodeReturn := "Java_com_cloudwise_agent_common_natives_TraceNative_setNodeReturn"
  101. klog.Infoln("[Jvm stack uprobe] Attach Start AttachJVMStackUprobes", path)
  102. var links []link.Link
  103. ex, err := link.OpenExecutable(path)
  104. if err != nil {
  105. klog.Error(err)
  106. return nil, err
  107. }
  108. klog.Infof("[Jvm stack uprobe] Attach Start [%s] [%s] ", setNodeEnter, setNodeReturn)
  109. uplink, err := ex.Uprobe(setNodeEnter, t.uprobes["setNodeEnter"], &link.UprobeOptions{Offset: 0x0, PID: int(pid)})
  110. if err != nil {
  111. klog.Errorf("[Jvm stack uprobe] Attaching ERROR: %v, %v, %v\n", err, setNodeEnter, uplink)
  112. return nil, err
  113. } else {
  114. links = append(links, uplink)
  115. }
  116. klog.Infoln("Attach Start " + setNodeReturn)
  117. uplink, err = ex.Uprobe(setNodeReturn, t.uprobes["setNodeReturn"], &link.UprobeOptions{Offset: 0x0})
  118. if err != nil {
  119. klog.Errorf("[Jvm stack uprobe] Attaching ERROR: %v, %v, %v\n", err, setNodeReturn, uplink)
  120. return nil, err
  121. } else {
  122. links = append(links, uplink)
  123. }
  124. return links, nil
  125. }
  126. func FindNativeSoFromMapped(pid uint32, prefix, suffix string) (string, error) {
  127. mapsFile := fmt.Sprintf("/proc/%d/maps", pid)
  128. tmpFile, err := os.Open(mapsFile)
  129. if err != nil {
  130. return "", fmt.Errorf("error opening maps file: %v", err)
  131. }
  132. defer tmpFile.Close()
  133. var selectedPath string
  134. var maxTimestamp int64
  135. fallbackPaths := make(map[string]struct{}) // 使用 map 去重
  136. scanner := bufio.NewScanner(tmpFile)
  137. for scanner.Scan() {
  138. line := scanner.Text()
  139. if strings.Contains(line, prefix) && strings.HasSuffix(line, suffix) {
  140. parts := strings.Fields(line)
  141. if len(parts) > 5 {
  142. path := parts[len(parts)-1]
  143. baseName := filepath.Base(path)
  144. if strings.HasPrefix(baseName, prefix) && strings.HasSuffix(baseName, suffix) {
  145. middle := strings.TrimSuffix(strings.TrimPrefix(baseName, prefix), suffix)
  146. segments := strings.Split(middle, ".")
  147. if len(segments) >= 2 {
  148. timestampStr := segments[len(segments)-1]
  149. timestamp, err := strconv.ParseInt(timestampStr, 10, 64)
  150. if err == nil && timestamp > maxTimestamp {
  151. maxTimestamp = timestamp
  152. selectedPath = path
  153. }
  154. } else {
  155. fallbackPaths[path] = struct{}{}
  156. }
  157. }
  158. }
  159. }
  160. }
  161. if err = scanner.Err(); err != nil {
  162. return "", fmt.Errorf("error reading maps file: %v", err)
  163. }
  164. if selectedPath != "" {
  165. return selectedPath, nil
  166. }
  167. var latestPath string
  168. var latestModTime int64
  169. for path := range fallbackPaths {
  170. info, err := os.Stat(path)
  171. if err != nil {
  172. continue
  173. }
  174. stat, ok := info.Sys().(*syscall.Stat_t)
  175. if !ok {
  176. continue
  177. }
  178. modTime := stat.Mtim.Sec
  179. if modTime > latestModTime {
  180. latestModTime = modTime
  181. latestPath = path
  182. }
  183. }
  184. if latestPath != "" {
  185. return latestPath, nil
  186. }
  187. return "", fmt.Errorf("no matching path found")
  188. }