Serge Bazanski | cc25bdf | 2018-10-25 14:02:58 +0200 | [diff] [blame] | 1 | // +build linux |
| 2 | |
| 3 | package load |
| 4 | |
| 5 | import ( |
| 6 | "context" |
| 7 | "io/ioutil" |
| 8 | "strconv" |
| 9 | "strings" |
| 10 | |
| 11 | "github.com/shirou/gopsutil/internal/common" |
| 12 | ) |
| 13 | |
| 14 | func Avg() (*AvgStat, error) { |
| 15 | return AvgWithContext(context.Background()) |
| 16 | } |
| 17 | |
| 18 | func AvgWithContext(ctx context.Context) (*AvgStat, error) { |
| 19 | filename := common.HostProc("loadavg") |
| 20 | line, err := ioutil.ReadFile(filename) |
| 21 | if err != nil { |
| 22 | return nil, err |
| 23 | } |
| 24 | |
| 25 | values := strings.Fields(string(line)) |
| 26 | |
| 27 | load1, err := strconv.ParseFloat(values[0], 64) |
| 28 | if err != nil { |
| 29 | return nil, err |
| 30 | } |
| 31 | load5, err := strconv.ParseFloat(values[1], 64) |
| 32 | if err != nil { |
| 33 | return nil, err |
| 34 | } |
| 35 | load15, err := strconv.ParseFloat(values[2], 64) |
| 36 | if err != nil { |
| 37 | return nil, err |
| 38 | } |
| 39 | |
| 40 | ret := &AvgStat{ |
| 41 | Load1: load1, |
| 42 | Load5: load5, |
| 43 | Load15: load15, |
| 44 | } |
| 45 | |
| 46 | return ret, nil |
| 47 | } |
| 48 | |
| 49 | // Misc returnes miscellaneous host-wide statistics. |
| 50 | // Note: the name should be changed near future. |
| 51 | func Misc() (*MiscStat, error) { |
| 52 | return MiscWithContext(context.Background()) |
| 53 | } |
| 54 | |
| 55 | func MiscWithContext(ctx context.Context) (*MiscStat, error) { |
| 56 | filename := common.HostProc("stat") |
| 57 | out, err := ioutil.ReadFile(filename) |
| 58 | if err != nil { |
| 59 | return nil, err |
| 60 | } |
| 61 | |
| 62 | ret := &MiscStat{} |
| 63 | lines := strings.Split(string(out), "\n") |
| 64 | for _, line := range lines { |
| 65 | fields := strings.Fields(line) |
| 66 | if len(fields) != 2 { |
| 67 | continue |
| 68 | } |
| 69 | v, err := strconv.ParseInt(fields[1], 10, 64) |
| 70 | if err != nil { |
| 71 | continue |
| 72 | } |
| 73 | switch fields[0] { |
| 74 | case "procs_running": |
| 75 | ret.ProcsRunning = int(v) |
| 76 | case "procs_blocked": |
| 77 | ret.ProcsBlocked = int(v) |
| 78 | case "ctxt": |
| 79 | ret.Ctxt = int(v) |
| 80 | default: |
| 81 | continue |
| 82 | } |
| 83 | |
| 84 | } |
| 85 | |
| 86 | return ret, nil |
| 87 | } |