shirou_gopsutil/load/load_darwin.go

68 lines
1.5 KiB
Go
Raw Normal View History

2021-12-23 05:54:41 +08:00
//go:build darwin
// +build darwin
2014-12-30 21:09:05 +08:00
package load
import (
2017-12-31 14:25:49 +08:00
"context"
"strings"
"unsafe"
"golang.org/x/sys/unix"
)
func Avg() (*AvgStat, error) {
2017-12-31 14:25:49 +08:00
return AvgWithContext(context.Background())
}
func AvgWithContext(ctx context.Context) (*AvgStat, error) {
// This SysctlRaw method borrowed from
// https://github.com/prometheus/node_exporter/blob/master/collector/loadavg_freebsd.go
// this implementation is common with BSDs
type loadavg struct {
load [3]uint32
scale int
}
b, err := unix.SysctlRaw("vm.loadavg")
if err != nil {
return nil, err
}
load := *(*loadavg)(unsafe.Pointer((&b[0])))
scale := float64(load.scale)
ret := &AvgStat{
Load1: float64(load.load[0]) / scale,
Load5: float64(load.load[1]) / scale,
Load15: float64(load.load[2]) / scale,
}
return ret, nil
}
2022-01-31 04:48:09 +08:00
// Misc returns miscellaneous host-wide statistics.
2016-02-20 22:17:20 +08:00
// darwin use ps command to get process running/blocked count.
// Almost same as FreeBSD implementation, but state is different.
// U means 'Uninterruptible Sleep'.
func Misc() (*MiscStat, error) {
2017-12-31 14:25:49 +08:00
return MiscWithContext(context.Background())
}
func MiscWithContext(ctx context.Context) (*MiscStat, error) {
out, err := invoke.CommandWithContext(ctx, "ps", "axo", "state")
if err != nil {
return nil, err
}
lines := strings.Split(string(out), "\n")
ret := MiscStat{}
for _, l := range lines {
if strings.Contains(l, "R") {
2016-04-01 20:34:39 +08:00
ret.ProcsRunning++
} else if strings.Contains(l, "U") {
// uninterruptible sleep == blocked
2016-04-01 20:34:39 +08:00
ret.ProcsBlocked++
}
}
return &ret, nil
}