// Package metrics is the pure half of host-process monitoring: every // function here parses a string or a pair of prior readings and MUST fail // toward nil, never a guessed zero. A zero CPU fraction and "we couldn't // read /proc/stat" are different facts, and a caller several layers up // (status pages, alerting) cannot tell them apart once a parser has already // collapsed one into the other — so a garbled line, a missing field, or a // counter that has gone backwards (reboot, cgroup recreated) all return nil // rather than 0 or the previous value. Nothing in this package touches the // filesystem or the OS: callers own reading /proc/stat, /proc/loadavg, and // cgroup v2 files, and pass the resulting text or prior/current readings in. package metrics import ( "strconv" "strings" "time" ) // CPUCounters is a monotonic reading of /proc/stat's aggregate cpu line. type CPUCounters struct{ Busy, Total uint64 } // ParseProcStat parses the aggregate "cpu" line of /proc/stat (fields after // "cpu" are user nice system idle iowait irq softirq steal, with optional // guest/guest_nice columns already folded into user/nice by the kernel on // modern systems). Total is the sum of the first 8 fields; Busy is Total // minus idle and iowait — deliberately only the first 8, so a kernel that // adds guest columns is never double-counted. Any missing "cpu" prefix, too // few fields, or a non-numeric field -> nil. func ParseProcStat(text string) *CPUCounters { for _, line := range strings.Split(text, "\n") { fields := strings.Fields(line) if len(fields) < 9 || fields[0] != "cpu" { continue } var vals [8]uint64 ok := true for i := 0; i < 8; i++ { v, err := strconv.ParseUint(fields[i+1], 10, 64) if err != nil { ok = false break } vals[i] = v } if !ok { continue } var total uint64 for _, v := range vals { total += v } idle, iowait := vals[3], vals[4] return &CPUCounters{Busy: total - idle - iowait, Total: total} } return nil } // CPUFrac turns two /proc/stat readings into a fraction of CPU busy over the // interval between them. Both readings must be non-nil, cur.Total must // exceed prev.Total, and cur.Busy must not be behind prev.Busy — counters // that went backwards mean the box rebooted or the reading is otherwise // invalid, and reporting a fraction from that would be a guess dressed up as // a measurement, so it's nil instead. The Busy check matters on its own: // Total can still advance while Busy alone regresses, and since both are // unsigned, cur.Busy-prev.Busy would silently wrap into a huge garbage // value rather than go negative. func CPUFrac(prev, cur *CPUCounters) *float64 { if prev == nil || cur == nil || cur.Total <= prev.Total || cur.Busy < prev.Busy { return nil } frac := float64(cur.Busy-prev.Busy) / float64(cur.Total-prev.Total) return &frac } // ParseLoadAvg parses /proc/loadavg's first three whitespace-separated // fields (1/5/15-minute load averages). Any missing or non-numeric field // fails the whole reading -> all three results nil, since a partial load // average (e.g. l1 present but l5 garbled) is not a value worth publishing // on its own. func ParseLoadAvg(text string) (l1, l5, l15 *float64) { fields := strings.Fields(text) if len(fields) < 3 { return nil, nil, nil } v1, err1 := strconv.ParseFloat(fields[0], 64) v5, err5 := strconv.ParseFloat(fields[1], 64) v15, err15 := strconv.ParseFloat(fields[2], 64) if err1 != nil || err5 != nil || err15 != nil { return nil, nil, nil } return &v1, &v5, &v15 } // ParseCgroupCPUUsec parses cpu.stat's usage_usec line. Missing key or a // non-numeric value -> nil. func ParseCgroupCPUUsec(text string) *int64 { for _, line := range strings.Split(text, "\n") { fields := strings.Fields(line) if len(fields) != 2 || fields[0] != "usage_usec" { continue } v, err := strconv.ParseInt(fields[1], 10, 64) if err != nil { return nil } return &v } return nil } // ParseCgroupInt parses a single cgroup v2 scalar file such as // memory.current or memory.peak. cgroup v2 uses the literal string "max" to // mean "no limit set" — a real value, but not a number, so it maps to nil // exactly like a parse failure would, since callers only want a byte count // or nothing. func ParseCgroupInt(text string) *int64 { s := strings.TrimSpace(text) if s == "" || s == "max" { return nil } v, err := strconv.ParseInt(s, 10, 64) if err != nil { return nil } return &v } // ParseCgroupIO parses io.stat, summing rbytes and wbytes across every // per-device line (a cgroup can have I/O against several block devices at // once, and the caller wants one whole-cgroup total). A line missing both // keys is simply skipped rather than failing the whole parse — io.stat's // per-device format is otherwise stable — but if no line anywhere yields // either key, both results are nil rather than a false zero. func ParseCgroupIO(text string) (rbytes, wbytes *int64) { var rsum, wsum int64 found := false for _, line := range strings.Split(text, "\n") { for _, field := range strings.Fields(line) { key, val, ok := strings.Cut(field, "=") if !ok { continue } switch key { case "rbytes": if v, err := strconv.ParseInt(val, 10, 64); err == nil { rsum += v found = true } case "wbytes": if v, err := strconv.ParseInt(val, 10, 64); err == nil { wsum += v found = true } } } } if !found { return nil, nil } return &rsum, &wsum } // UnitCPUFrac turns two cgroup cpu.stat usage_usec readings and the elapsed // wall time between them into a fraction of a CPU core busy. Both readings // must be non-nil, cur must not be behind prev (cgroup recreated, counter // reset), and elapsed must be strictly positive — any of those failing // would turn a division into either a guess or a crash, so it's nil instead. func UnitCPUFrac(prevUsec, curUsec *int64, elapsed time.Duration) *float64 { if prevUsec == nil || curUsec == nil || *curUsec < *prevUsec || elapsed <= 0 { return nil } frac := float64(*curUsec-*prevUsec) / 1e6 / elapsed.Seconds() return &frac }