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