From e35a9f6b86a65631caa058eafec969ee93d525f2 Mon Sep 17 00:00:00 2001 From: Thomas Roehl Date: Wed, 12 May 2021 16:57:18 +0200 Subject: [PATCH] Add Cpustat collector for /proc/stat --- collectors/cpustatMetric.go | 70 +++++++++++++++++++++++++++++++++++++ config.json | 3 +- metric-collector.go | 1 + 3 files changed, 73 insertions(+), 1 deletion(-) create mode 100644 collectors/cpustatMetric.go diff --git a/collectors/cpustatMetric.go b/collectors/cpustatMetric.go new file mode 100644 index 0000000..ea498d9 --- /dev/null +++ b/collectors/cpustatMetric.go @@ -0,0 +1,70 @@ +package collectors + +import ( + "io/ioutil" + "strconv" + "strings" + "time" +) + +const CPUSTATFILE = `/proc/stat` + +type CpustatCollector struct { + MetricCollector +} + +func (m *CpustatCollector) Init() { + m.name = "CpustatCollector" + m.setup() +} + +func ParseStatLine(line string, out map[string]interface{}) { + ls := strings.Fields(line) + user, _ := strconv.ParseInt(ls[1], 0, 64) + out["cpu_user"] = float64(user) + nice, _ := strconv.ParseInt(ls[2], 0, 64) + out["cpu_nice"] = float64(nice) + system, _ := strconv.ParseInt(ls[3], 0, 64) + out["cpu_system"] = float64(system) + idle, _ := strconv.ParseInt(ls[4], 0, 64) + out["cpu_idle"] = float64(idle) + iowait, _ := strconv.ParseInt(ls[5], 0, 64) + out["cpu_iowait"] = float64(iowait) + irq, _ := strconv.ParseInt(ls[6], 0, 64) + out["cpu_irq"] = float64(irq) + softirq, _ := strconv.ParseInt(ls[7], 0, 64) + out["cpu_softirq"] = float64(softirq) + steal, _ := strconv.ParseInt(ls[8], 0, 64) + out["cpu_steal"] = float64(steal) + guest, _ := strconv.ParseInt(ls[9], 0, 64) + out["cpu_guest"] = float64(guest) + guest_nice, _ := strconv.ParseInt(ls[10], 0, 64) + out["cpu_guest_nice"] = float64(guest_nice) +} + +func (m *CpustatCollector) Read(interval time.Duration) { + buffer, err := ioutil.ReadFile(string(CPUSTATFILE)) + + if err != nil { + return + } + + ll := strings.Split(string(buffer), "\n") + for _, line := range ll { + if (len(line) == 0) { + continue + } + ls := strings.Fields(line) + if (strings.Compare(ls[0], "cpu") == 0) { + ParseStatLine(line, m.node) + } else if (strings.HasPrefix(ls[0], "cpu")) { + cpustr := strings.TrimLeft(ls[0], "cpu") + cpu, _ := strconv.Atoi(cpustr) + ParseStatLine(line, m.cpus[cpu]) + } + } +} + +func (m *CpustatCollector) Close() { + return +} diff --git a/config.json b/config.json index f2bba58..2bd044e 100644 --- a/config.json +++ b/config.json @@ -15,6 +15,7 @@ "loadavg", "netstat", "ibstat", - "lustrestat" + "lustrestat", + "cpustat" ] } diff --git a/metric-collector.go b/metric-collector.go index dd5376c..aeaffd1 100644 --- a/metric-collector.go +++ b/metric-collector.go @@ -23,6 +23,7 @@ var Collectors = map[string]collectors.MetricGetter{ "netstat": &collectors.NetstatCollector{}, "ibstat": &collectors.InfinibandCollector{}, "lustrestat": &collectors.LustreCollector{}, + "cpustat": &collectors.CpustatCollector{}, } var Sinks = map[string]sinks.SinkFuncs{