mem_darwin_nocgo.go 1.9 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. // +build darwin
  2. // +build !cgo
  3. package mem
  4. import (
  5. "context"
  6. "os/exec"
  7. "strconv"
  8. "strings"
  9. "golang.org/x/sys/unix"
  10. )
  11. // Runs vm_stat and returns Free and inactive pages
  12. func getVMStat(vms *VirtualMemoryStat) error {
  13. vm_stat, err := exec.LookPath("vm_stat")
  14. if err != nil {
  15. return err
  16. }
  17. out, err := invoke.Command(vm_stat)
  18. if err != nil {
  19. return err
  20. }
  21. return parseVMStat(string(out), vms)
  22. }
  23. func parseVMStat(out string, vms *VirtualMemoryStat) error {
  24. var err error
  25. lines := strings.Split(out, "\n")
  26. pagesize := uint64(unix.Getpagesize())
  27. for _, line := range lines {
  28. fields := strings.Split(line, ":")
  29. if len(fields) < 2 {
  30. continue
  31. }
  32. key := strings.TrimSpace(fields[0])
  33. value := strings.Trim(fields[1], " .")
  34. switch key {
  35. case "Pages free":
  36. free, e := strconv.ParseUint(value, 10, 64)
  37. if e != nil {
  38. err = e
  39. }
  40. vms.Free = free * pagesize
  41. case "Pages inactive":
  42. inactive, e := strconv.ParseUint(value, 10, 64)
  43. if e != nil {
  44. err = e
  45. }
  46. vms.Inactive = inactive * pagesize
  47. case "Pages active":
  48. active, e := strconv.ParseUint(value, 10, 64)
  49. if e != nil {
  50. err = e
  51. }
  52. vms.Active = active * pagesize
  53. case "Pages wired down":
  54. wired, e := strconv.ParseUint(value, 10, 64)
  55. if e != nil {
  56. err = e
  57. }
  58. vms.Wired = wired * pagesize
  59. }
  60. }
  61. return err
  62. }
  63. // VirtualMemory returns VirtualmemoryStat.
  64. func VirtualMemory() (*VirtualMemoryStat, error) {
  65. return VirtualMemoryWithContext(context.Background())
  66. }
  67. func VirtualMemoryWithContext(ctx context.Context) (*VirtualMemoryStat, error) {
  68. ret := &VirtualMemoryStat{}
  69. total, err := getHwMemsize()
  70. if err != nil {
  71. return nil, err
  72. }
  73. err = getVMStat(ret)
  74. if err != nil {
  75. return nil, err
  76. }
  77. ret.Available = ret.Free + ret.Inactive
  78. ret.Total = total
  79. ret.Used = ret.Total - ret.Available
  80. ret.UsedPercent = 100 * float64(ret.Used) / float64(ret.Total)
  81. return ret, nil
  82. }