Add simpler collectors for load, mem_used and network

This commit is contained in:
Thomas Roehl 2021-03-25 14:47:35 +01:00
parent a6ac0c5373
commit 73fd59537e
3 changed files with 152 additions and 0 deletions

View File

@ -0,0 +1,36 @@
package collectors
import (
"io/ioutil"
"strconv"
"time"
"strings"
)
const LOADAVGFILE = `/proc/loadavg`
type LoadavgCollector struct {
MetricCollector
}
func (m *LoadavgCollector) Init() {
m.name = "LoadavgCollector"
m.setup()
}
func (m *LoadavgCollector) Read(interval time.Duration){
buffer, err := ioutil.ReadFile(string(LOADAVGFILE))
if err != nil {
return
}
ls := strings.Split(string(buffer), ` `)
loadOne, _ := strconv.ParseFloat(ls[0], 64)
m.node["load_one"] = float64(loadOne)
}
func (m *LoadavgCollector) Close() {
return
}

View File

@ -0,0 +1,57 @@
package collectors
import (
"errors"
"io/ioutil"
"log"
"strconv"
"strings"
"time"
//protocol "github.com/influxdata/line-protocol"
)
const MEMSTATFILE = `/proc/meminfo`
type MemstatCollector struct {
MetricCollector
}
func (m *MemstatCollector) Init() {
m.name = "MemstatCollector"
m.setup()
}
func (m *MemstatCollector) Read(interval time.Duration){
buffer, err := ioutil.ReadFile(string(MEMSTATFILE))
if err != nil {
log.Print(err)
return
}
ll := strings.Split(string(buffer), "\n")
memstats := make(map[string]int64)
for _, line := range ll {
ls := strings.Split(line, `:`)
if len(ls) > 1 {
lv := strings.Fields(ls[1])
memstats[ls[0]], err = strconv.ParseInt(lv[0], 0, 64)
}
}
if _, exists := memstats[`MemTotal`]; !exists {
err = errors.New("Parse error")
log.Print(err)
return
}
memUsed := memstats[`MemTotal`] - (memstats[`MemFree`] + memstats[`Buffers`] + memstats[`Cached`])
m.node["mem_used"] = float64(memUsed) * 1.0e-3
}
func (m *MemstatCollector) Close() {
return
}

View File

@ -0,0 +1,59 @@
package collectors
import (
"io/ioutil"
"strconv"
"strings"
"time"
"log"
)
const NETSTATFILE = `/proc/net/dev`
type NetstatCollector struct {
MetricCollector
}
func (m *NetstatCollector) Init() {
m.name = "NetstatCollector"
m.setup()
}
func (m *NetstatCollector) Read(interval time.Duration){
data, err := ioutil.ReadFile(string(NETSTATFILE))
if err != nil {
log.Print(err.Error())
return
}
var matches = map[int]string{
1: "bytes_in",
9: "bytes_out",
2: "pkts_in",
10: "pkts_out",
}
lines := strings.Split(string(data), "\n")
for _, l := range lines {
if !strings.Contains(l, ":") {
continue
}
f := strings.Fields(l)
dev := f[0][0 : len(f[0])-1]
if dev == "lo" {
continue
}
for i, name := range matches {
v, err := strconv.ParseInt(f[i], 10, 0)
if err == nil {
m.node[name] = float64(v) * 1.0e-3
}
}
}
}
func (m *NetstatCollector) Close() {
return
}