From f9fa6d05cfe7aad84cf2fec561dd39e1ce5807a5 Mon Sep 17 00:00:00 2001 From: Siavash Safi Date: Tue, 12 May 2015 10:16:08 +0430 Subject: [PATCH] loadavg: Use getloadavg() from stdlib.h --- collector/loadavg.go | 29 +++++++++++------------------ collector/loadavg_test.go | 14 -------------- 2 files changed, 11 insertions(+), 32 deletions(-) delete mode 100644 collector/loadavg_test.go diff --git a/collector/loadavg.go b/collector/loadavg.go index bdf72988..d1eab262 100644 --- a/collector/loadavg.go +++ b/collector/loadavg.go @@ -3,18 +3,17 @@ package collector import ( + "errors" "fmt" - "io/ioutil" - "strconv" - "strings" "github.com/prometheus/client_golang/prometheus" "github.com/prometheus/log" ) -const ( - procLoad = "/proc/loadavg" -) +// #include +import "C" + +var loadavg [1]C.double type loadavgCollector struct { metric prometheus.Gauge @@ -22,6 +21,7 @@ type loadavgCollector struct { func init() { Factories["loadavg"] = NewLoadavgCollector + loadavg[0] = 0 } // Takes a prometheus registry and returns a new Collector exposing @@ -48,18 +48,11 @@ func (c *loadavgCollector) Update(ch chan<- prometheus.Metric) (err error) { } func getLoad1() (float64, error) { - data, err := ioutil.ReadFile(procLoad) - if err != nil { - return 0, err + samples := C.getloadavg(&loadavg[0], 1) + if samples > 0 { + return float64(loadavg[0]), nil + } else { + return 0, errors.New("Failed to get load average!") } - 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_test.go b/collector/loadavg_test.go deleted file mode 100644 index e83822a6..00000000 --- a/collector/loadavg_test.go +++ /dev/null @@ -1,14 +0,0 @@ -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) - } -}