mirror of
https://github.com/prometheus/node_exporter
synced 2025-04-11 04:01:52 +00:00
loadavg: Use getloadavg() from stdlib.h
This commit is contained in:
parent
0f0daef4e0
commit
f9fa6d05cf
@ -3,18 +3,17 @@
|
|||||||
package collector
|
package collector
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"errors"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io/ioutil"
|
|
||||||
"strconv"
|
|
||||||
"strings"
|
|
||||||
|
|
||||||
"github.com/prometheus/client_golang/prometheus"
|
"github.com/prometheus/client_golang/prometheus"
|
||||||
"github.com/prometheus/log"
|
"github.com/prometheus/log"
|
||||||
)
|
)
|
||||||
|
|
||||||
const (
|
// #include <stdlib.h>
|
||||||
procLoad = "/proc/loadavg"
|
import "C"
|
||||||
)
|
|
||||||
|
var loadavg [1]C.double
|
||||||
|
|
||||||
type loadavgCollector struct {
|
type loadavgCollector struct {
|
||||||
metric prometheus.Gauge
|
metric prometheus.Gauge
|
||||||
@ -22,6 +21,7 @@ type loadavgCollector struct {
|
|||||||
|
|
||||||
func init() {
|
func init() {
|
||||||
Factories["loadavg"] = NewLoadavgCollector
|
Factories["loadavg"] = NewLoadavgCollector
|
||||||
|
loadavg[0] = 0
|
||||||
}
|
}
|
||||||
|
|
||||||
// Takes a prometheus registry and returns a new Collector exposing
|
// 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) {
|
func getLoad1() (float64, error) {
|
||||||
data, err := ioutil.ReadFile(procLoad)
|
samples := C.getloadavg(&loadavg[0], 1)
|
||||||
if err != nil {
|
if samples > 0 {
|
||||||
return 0, err
|
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
|
|
||||||
}
|
}
|
||||||
|
@ -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)
|
|
||||||
}
|
|
||||||
}
|
|
Loading…
Reference in New Issue
Block a user