load_darwin.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. // +build darwin
  2. package load
  3. import (
  4. "context"
  5. "os/exec"
  6. "strconv"
  7. "strings"
  8. "github.com/shirou/gopsutil/internal/common"
  9. )
  10. func Avg() (*AvgStat, error) {
  11. return AvgWithContext(context.Background())
  12. }
  13. func AvgWithContext(ctx context.Context) (*AvgStat, error) {
  14. values, err := common.DoSysctrlWithContext(ctx, "vm.loadavg")
  15. if err != nil {
  16. return nil, err
  17. }
  18. load1, err := strconv.ParseFloat(values[0], 64)
  19. if err != nil {
  20. return nil, err
  21. }
  22. load5, err := strconv.ParseFloat(values[1], 64)
  23. if err != nil {
  24. return nil, err
  25. }
  26. load15, err := strconv.ParseFloat(values[2], 64)
  27. if err != nil {
  28. return nil, err
  29. }
  30. ret := &AvgStat{
  31. Load1: float64(load1),
  32. Load5: float64(load5),
  33. Load15: float64(load15),
  34. }
  35. return ret, nil
  36. }
  37. // Misc returnes miscellaneous host-wide statistics.
  38. // darwin use ps command to get process running/blocked count.
  39. // Almost same as FreeBSD implementation, but state is different.
  40. // U means 'Uninterruptible Sleep'.
  41. func Misc() (*MiscStat, error) {
  42. return MiscWithContext(context.Background())
  43. }
  44. func MiscWithContext(ctx context.Context) (*MiscStat, error) {
  45. bin, err := exec.LookPath("ps")
  46. if err != nil {
  47. return nil, err
  48. }
  49. out, err := invoke.CommandWithContext(ctx, bin, "axo", "state")
  50. if err != nil {
  51. return nil, err
  52. }
  53. lines := strings.Split(string(out), "\n")
  54. ret := MiscStat{}
  55. for _, l := range lines {
  56. if strings.Contains(l, "R") {
  57. ret.ProcsRunning++
  58. } else if strings.Contains(l, "U") {
  59. // uninterruptible sleep == blocked
  60. ret.ProcsBlocked++
  61. }
  62. }
  63. return &ret, nil
  64. }