util.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182
  1. package containers
  2. import (
  3. "debug/elf"
  4. "fmt"
  5. "io/ioutil"
  6. "log"
  7. "os"
  8. "os/exec"
  9. "regexp"
  10. "runtime"
  11. )
  12. var libjvmRegex = regexp.MustCompile(`.*/libjvm\.so`)
  13. func GetExeType(pid uint32) CodeType {
  14. mapsFilePath := fmt.Sprintf("/proc/%d/maps", pid)
  15. data, err := ioutil.ReadFile(mapsFilePath)
  16. if err != nil {
  17. log.Fatalf("Failed to read %s: %s", mapsFilePath, err)
  18. }
  19. content := string(data)
  20. if libjvmRegex.MatchString(content) {
  21. fmt.Println("is java process")
  22. return CodeTypeJava
  23. } else if isGoProcess(pid) {
  24. return CodeTypeGo
  25. fmt.Println("is go process")
  26. }
  27. return CodeTypeUnknown
  28. }
  29. func isGoProcess(pid uint32) bool {
  30. path, err := getProcessPath(pid)
  31. if err != nil {
  32. fmt.Printf("无法获取进程路径:%s\n", err)
  33. return false
  34. }
  35. ef, err := elf.Open(path)
  36. if err != nil {
  37. fmt.Println("failed to open as elf binary", err)
  38. return false
  39. }
  40. defer ef.Close()
  41. gopclntabSection := ef.Section(".gopclntab")
  42. if gopclntabSection != nil {
  43. fmt.Println("is a go process")
  44. return true
  45. }
  46. return false
  47. }
  48. func getProcessPath(pid uint32) (string, error) {
  49. switch runtime.GOOS {
  50. case "linux":
  51. return getLinuxProcessPath(pid)
  52. default:
  53. return "", fmt.Errorf("不支持的操作系统:%s", runtime.GOOS)
  54. }
  55. }
  56. func getLinuxProcessPath(pid uint32) (string, error) {
  57. procPath := fmt.Sprintf("/proc/%d/exe", pid)
  58. path, err := os.Readlink(procPath)
  59. if err != nil {
  60. return "", err
  61. }
  62. return path, nil
  63. }
  64. func executeCommand(name string, args ...string) (string, error) {
  65. cmd := exec.Command(name, args...)
  66. out, err := cmd.Output()
  67. if err != nil {
  68. return "", err
  69. }
  70. return string(out), nil
  71. }