2021-05-12 17:47:12 +02:00
|
|
|
package collectors
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2021-10-04 15:23:43 +02:00
|
|
|
lp "github.com/influxdata/line-protocol"
|
2021-05-12 17:47:12 +02:00
|
|
|
"log"
|
|
|
|
"os/exec"
|
|
|
|
"strings"
|
|
|
|
"time"
|
|
|
|
)
|
|
|
|
|
|
|
|
const NUM_PROCS = 5
|
|
|
|
|
|
|
|
type TopProcsCollector struct {
|
|
|
|
MetricCollector
|
2021-10-04 15:23:43 +02:00
|
|
|
tags map[string]string
|
2021-05-12 17:47:12 +02:00
|
|
|
}
|
|
|
|
|
2021-05-14 19:21:16 +02:00
|
|
|
func (m *TopProcsCollector) Init() error {
|
2021-05-12 17:47:12 +02:00
|
|
|
m.name = "TopProcsCollector"
|
2021-10-04 15:23:43 +02:00
|
|
|
m.tags = map[string]string{"type": "node"}
|
2021-05-12 17:47:12 +02:00
|
|
|
m.setup()
|
2021-10-04 15:23:43 +02:00
|
|
|
command := exec.Command("ps", "-Ao", "comm", "--sort=-pcpu")
|
|
|
|
command.Wait()
|
|
|
|
_, err := command.Output()
|
|
|
|
if err == nil {
|
2021-10-04 15:47:03 +02:00
|
|
|
m.init = true
|
2021-10-04 15:23:43 +02:00
|
|
|
}
|
2021-05-14 19:21:16 +02:00
|
|
|
return nil
|
2021-05-12 17:47:12 +02:00
|
|
|
}
|
|
|
|
|
2021-10-04 15:23:43 +02:00
|
|
|
func (m *TopProcsCollector) Read(interval time.Duration, out *[]lp.MutableMetric) {
|
2021-05-18 15:14:37 +02:00
|
|
|
command := exec.Command("ps", "-Ao", "comm", "--sort=-pcpu")
|
2021-05-12 17:47:12 +02:00
|
|
|
command.Wait()
|
|
|
|
stdout, err := command.Output()
|
|
|
|
if err != nil {
|
|
|
|
log.Print(m.name, err)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
|
|
|
|
lines := strings.Split(string(stdout), "\n")
|
|
|
|
for i := 1; i < NUM_PROCS+1; i++ {
|
2021-10-04 15:23:43 +02:00
|
|
|
name := fmt.Sprintf("topproc%d", i)
|
|
|
|
y, err := lp.New(name, m.tags, map[string]interface{}{"value": string(lines[i])}, time.Now())
|
|
|
|
if err == nil {
|
|
|
|
*out = append(*out, y)
|
|
|
|
}
|
2021-05-12 17:47:12 +02:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func (m *TopProcsCollector) Close() {
|
2021-10-04 15:47:03 +02:00
|
|
|
m.init = false
|
2021-05-12 17:47:12 +02:00
|
|
|
return
|
|
|
|
}
|