2015-06-23 20:14:52 +00:00
|
|
|
// +build !cpu
|
2015-05-12 07:13:08 +00:00
|
|
|
|
|
|
|
package collector
|
|
|
|
|
|
|
|
import (
|
|
|
|
"errors"
|
2015-05-20 07:52:00 +00:00
|
|
|
"os"
|
2015-05-12 07:13:08 +00:00
|
|
|
"strconv"
|
|
|
|
"unsafe"
|
|
|
|
|
|
|
|
"github.com/prometheus/client_golang/prometheus"
|
|
|
|
)
|
|
|
|
|
|
|
|
/*
|
|
|
|
#cgo LDFLAGS: -lkvm
|
|
|
|
#include <fcntl.h>
|
|
|
|
#include <kvm.h>
|
|
|
|
#include <sys/param.h>
|
|
|
|
#include <sys/pcpu.h>
|
|
|
|
#include <sys/resource.h>
|
|
|
|
*/
|
|
|
|
import "C"
|
|
|
|
|
|
|
|
type statCollector struct {
|
2015-06-23 13:49:18 +00:00
|
|
|
cpu *prometheus.CounterVec
|
2015-05-12 07:13:08 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func init() {
|
|
|
|
Factories["cpu"] = NewStatCollector
|
|
|
|
}
|
|
|
|
|
2015-06-23 20:14:52 +00:00
|
|
|
// Takes a prometheus registry and returns a new Collector exposing
|
|
|
|
// CPU stats.
|
2015-06-23 13:49:18 +00:00
|
|
|
func NewStatCollector() (Collector, error) {
|
2015-05-12 07:13:08 +00:00
|
|
|
return &statCollector{
|
|
|
|
cpu: prometheus.NewCounterVec(
|
|
|
|
prometheus.CounterOpts{
|
|
|
|
Namespace: Namespace,
|
2015-06-23 20:14:52 +00:00
|
|
|
Name: "cpu_seconds_total",
|
|
|
|
Help: "Seconds the CPU spent in each mode.",
|
2015-05-12 07:13:08 +00:00
|
|
|
},
|
|
|
|
[]string{"cpu", "mode"},
|
|
|
|
),
|
|
|
|
}, nil
|
|
|
|
}
|
|
|
|
|
2015-06-23 20:14:52 +00:00
|
|
|
// Expose CPU stats using KVM.
|
2015-05-12 07:13:08 +00:00
|
|
|
func (c *statCollector) Update(ch chan<- prometheus.Metric) (err error) {
|
2015-05-20 07:52:00 +00:00
|
|
|
if os.Geteuid() != 0 && os.Getegid() != 2 {
|
2015-06-23 20:14:52 +00:00
|
|
|
return errors.New("caller should be either root user or kmem group to access /dev/mem")
|
2015-05-20 07:52:00 +00:00
|
|
|
}
|
|
|
|
|
2015-05-12 07:13:08 +00:00
|
|
|
var errbuf *C.char
|
|
|
|
kd := C.kvm_open(nil, nil, nil, C.O_RDONLY, errbuf)
|
|
|
|
if errbuf != nil {
|
2015-06-23 20:14:52 +00:00
|
|
|
return errors.New("failed to call kvm_open().")
|
2015-05-12 07:13:08 +00:00
|
|
|
}
|
|
|
|
defer C.kvm_close(kd)
|
|
|
|
|
|
|
|
ncpus := C.kvm_getncpus(kd)
|
|
|
|
for i := 0; i < int(ncpus); i++ {
|
|
|
|
pcpu := C.kvm_getpcpu(kd, C.int(i))
|
|
|
|
cp_time := ((*C.struct_pcpu)(unsafe.Pointer(pcpu))).pc_cp_time
|
|
|
|
c.cpu.With(prometheus.Labels{"cpu": strconv.Itoa(i), "mode": "user"}).Set(float64(cp_time[C.CP_USER]))
|
|
|
|
c.cpu.With(prometheus.Labels{"cpu": strconv.Itoa(i), "mode": "nice"}).Set(float64(cp_time[C.CP_NICE]))
|
|
|
|
c.cpu.With(prometheus.Labels{"cpu": strconv.Itoa(i), "mode": "system"}).Set(float64(cp_time[C.CP_SYS]))
|
|
|
|
c.cpu.With(prometheus.Labels{"cpu": strconv.Itoa(i), "mode": "interrupt"}).Set(float64(cp_time[C.CP_INTR]))
|
|
|
|
c.cpu.With(prometheus.Labels{"cpu": strconv.Itoa(i), "mode": "idle"}).Set(float64(cp_time[C.CP_IDLE]))
|
|
|
|
}
|
|
|
|
c.cpu.Collect(ch)
|
|
|
|
return err
|
|
|
|
}
|