...
1
2
3 package load
4
5 import (
6 "context"
7 "os/exec"
8 "strings"
9 "unsafe"
10
11 "golang.org/x/sys/unix"
12 )
13
14 func Avg() (*AvgStat, error) {
15 return AvgWithContext(context.Background())
16 }
17
18 func AvgWithContext(ctx context.Context) (*AvgStat, error) {
19
20
21
22 type loadavg struct {
23 load [3]uint32
24 scale int
25 }
26 b, err := unix.SysctlRaw("vm.loadavg")
27 if err != nil {
28 return nil, err
29 }
30 load := *(*loadavg)(unsafe.Pointer((&b[0])))
31 scale := float64(load.scale)
32 ret := &AvgStat{
33 Load1: float64(load.load[0]) / scale,
34 Load5: float64(load.load[1]) / scale,
35 Load15: float64(load.load[2]) / scale,
36 }
37
38 return ret, nil
39 }
40
41
42
43
44
45 func Misc() (*MiscStat, error) {
46 return MiscWithContext(context.Background())
47 }
48
49 func MiscWithContext(ctx context.Context) (*MiscStat, error) {
50 bin, err := exec.LookPath("ps")
51 if err != nil {
52 return nil, err
53 }
54 out, err := invoke.CommandWithContext(ctx, bin, "axo", "state")
55 if err != nil {
56 return nil, err
57 }
58 lines := strings.Split(string(out), "\n")
59
60 ret := MiscStat{}
61 for _, l := range lines {
62 if strings.Contains(l, "R") {
63 ret.ProcsRunning++
64 } else if strings.Contains(l, "U") {
65
66 ret.ProcsBlocked++
67 }
68 }
69
70 return &ret, nil
71 }
72
View as plain text