cc-metric-collector/collectors/netstatMetric.go

71 lines
1.3 KiB
Go
Raw Normal View History

package collectors
import (
2021-10-04 15:23:43 +02:00
lp "github.com/influxdata/line-protocol"
"io/ioutil"
2021-03-25 17:47:08 +01:00
"log"
"strconv"
"strings"
"time"
)
const NETSTATFILE = `/proc/net/dev`
type NetstatCollector struct {
MetricCollector
2021-10-04 15:23:43 +02:00
matches map[int]string
tags map[string]string
}
func (m *NetstatCollector) Init() error {
2021-03-25 17:47:08 +01:00
m.name = "NetstatCollector"
m.setup()
2021-10-04 15:23:43 +02:00
m.tags = map[string]string{"type": "node"}
m.matches = map[int]string{
1: "bytes_in",
9: "bytes_out",
2: "pkts_in",
10: "pkts_out",
}
_, err := ioutil.ReadFile(string(NETSTATFILE))
if err == nil {
2021-10-04 15:47:03 +02:00
m.init = true
}
return nil
}
2021-10-04 15:23:43 +02:00
func (m *NetstatCollector) Read(interval time.Duration, out *[]lp.MutableMetric) {
data, err := ioutil.ReadFile(string(NETSTATFILE))
if err != nil {
log.Print(err.Error())
return
}
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
}
2021-10-04 15:23:43 +02:00
for i, name := range m.matches {
v, err := strconv.ParseInt(f[i], 10, 0)
if err == nil {
2021-10-04 15:23:43 +02:00
y, err := lp.New(name, m.tags, map[string]interface{}{"value": int(float64(v) * 1.0e-3)}, time.Now())
if err == nil {
*out = append(*out, y)
}
}
}
}
2021-03-25 17:47:08 +01:00
}
func (m *NetstatCollector) Close() {
2021-10-04 15:47:03 +02:00
m.init = false
2021-03-25 17:47:08 +01:00
return
}