From d80b2af492ab3aeeec233af08115799cbb036cc3 Mon Sep 17 00:00:00 2001 From: Siavash Safi Date: Wed, 24 Jun 2015 16:38:43 +0430 Subject: [PATCH] loadavg: Split the collector for linux and other platforms. --- collector/loadavg.go | 3 +- collector/loadavg_linux.go | 65 +++++++++++++++++++++++++++++++++ collector/loadavg_linux_test.go | 14 +++++++ 3 files changed, 81 insertions(+), 1 deletion(-) create mode 100644 collector/loadavg_linux.go create mode 100644 collector/loadavg_linux_test.go diff --git a/collector/loadavg.go b/collector/loadavg.go index 6ecb7edb..7d7611a6 100644 --- a/collector/loadavg.go +++ b/collector/loadavg.go @@ -1,4 +1,4 @@ -// +build !noloadavg +// +build !linux !noloadavg package collector @@ -21,6 +21,7 @@ func init() { Factories["loadavg"] = NewLoadavgCollector } +// Takes a prometheus registry and returns a new Collector exposing // load1 stat. func NewLoadavgCollector() (Collector, error) { return &loadavgCollector{ diff --git a/collector/loadavg_linux.go b/collector/loadavg_linux.go new file mode 100644 index 00000000..bdf72988 --- /dev/null +++ b/collector/loadavg_linux.go @@ -0,0 +1,65 @@ +// +build !noloadavg + +package collector + +import ( + "fmt" + "io/ioutil" + "strconv" + "strings" + + "github.com/prometheus/client_golang/prometheus" + "github.com/prometheus/log" +) + +const ( + procLoad = "/proc/loadavg" +) + +type loadavgCollector struct { + 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. +func NewLoadavgCollector() (Collector, error) { + return &loadavgCollector{ + metric: prometheus.NewGauge(prometheus.GaugeOpts{ + Namespace: Namespace, + Name: "load1", + Help: "1m load average.", + }), + }, nil +} + +func (c *loadavgCollector) Update(ch chan<- prometheus.Metric) (err error) { + load, err := getLoad1() + if err != nil { + return fmt.Errorf("Couldn't get load: %s", err) + } + log.Debugf("Set node_load: %f", load) + c.metric.Set(load) + c.metric.Collect(ch) + return err +} + +func getLoad1() (float64, error) { + data, err := ioutil.ReadFile(procLoad) + if err != nil { + return 0, err + } + return parseLoad(string(data)) +} + +func parseLoad(data string) (float64, error) { + 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) + } + return load, nil +} diff --git a/collector/loadavg_linux_test.go b/collector/loadavg_linux_test.go new file mode 100644 index 00000000..e83822a6 --- /dev/null +++ b/collector/loadavg_linux_test.go @@ -0,0 +1,14 @@ +package collector + +import "testing" + +func TestLoad(t *testing.T) { + load, 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) + } +}