Add load5 and load15 to linux load metric

This commit is contained in:
Matteo Bigoi 2015-10-17 13:07:39 +00:00
parent eee6298266
commit 832ba9cc1d
2 changed files with 49 additions and 24 deletions

View file

@ -26,49 +26,71 @@ import (
)
type loadavgCollector struct {
metric prometheus.Gauge
metric []prometheus.Gauge
}
func init() {
Factories["loadavg"] = NewLoadavgCollector
}
// Takes a prometheus registry and returns a new Collector exposing
// load, seconds since last login and a list of tags as specified by config.
// Takes a prometheus registry and returns a new Collector exposing load average
func NewLoadavgCollector() (Collector, error) {
return &loadavgCollector{
metric: prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: Namespace,
Name: "load1",
Help: "1m load average.",
}),
metric: []prometheus.Gauge{
prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: Namespace,
Name: "load1",
Help: "1m load average.",
}),
prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: Namespace,
Name: "load5",
Help: "5m load average.",
}),
prometheus.NewGauge(prometheus.GaugeOpts{
Namespace: Namespace,
Name: "load15",
Help: "15m load average.",
}),
},
}, nil
}
func (c *loadavgCollector) Update(ch chan<- prometheus.Metric) (err error) {
load, err := getLoad1()
loads, err := getLoad()
if err != nil {
return fmt.Errorf("couldn't get load: %s", err)
return fmt.Errorf("Couldn't get load: %s", err)
}
for i, load := range loads {
log.Debugf("Set load %d: %f", i, load)
c.metric[i].Set(load)
c.metric[i].Collect(ch)
}
log.Debugf("Set node_load: %f", load)
c.metric.Set(load)
c.metric.Collect(ch)
return err
}
func getLoad1() (float64, error) {
// Read loadavg from /proc
func getLoad() (loads []float64, err error) {
data, err := ioutil.ReadFile(procFilePath("loadavg"))
if err != nil {
return 0, err
return loads, err
}
return parseLoad(string(data))
loads, err = parseLoad(string(data))
if err != nil {
return loads, err
}
return loads, nil
}
func parseLoad(data string) (float64, error) {
// Parse /proc loadavg and return 1m, 5m and 15m
func parseLoad(data string) (loads []float64, err error) {
loads = make([]float64, 3)
parts := strings.Fields(data)
load, err := strconv.ParseFloat(parts[0], 64)
if err != nil {
return 0, fmt.Errorf("could not parse load '%s': %s", parts[0], err)
for i, load := range parts[0:3] {
loads[i], err = strconv.ParseFloat(load, 64)
if err != nil {
return loads, fmt.Errorf("Could not parse load '%s': %s", load, err)
}
}
return load, nil
return loads, nil
}

View file

@ -16,12 +16,15 @@ package collector
import "testing"
func TestLoad(t *testing.T) {
load, err := parseLoad("0.21 0.37 0.39 1/719 19737")
want := []float64{0.21, 0.37, 0.39}
loads, err := parseLoad("0.21 0.37 0.39 1/719 19737")
if err != nil {
t.Fatal(err)
}
if want := 0.21; want != load {
t.Fatalf("want load %f, got %f", want, load)
for i, load := range loads {
if want[i] != load {
t.Fatalf("want load %f, got %f", want[i], load)
}
}
}