cc-metric-collector/collectors/topprocsMetric.go

79 lines
1.7 KiB
Go
Raw Normal View History

package collectors
import (
2021-11-25 15:11:39 +01:00
"encoding/json"
"errors"
"fmt"
"log"
"os/exec"
"strings"
"time"
lp "github.com/influxdata/line-protocol"
)
const MAX_NUM_PROCS = 10
const DEFAULT_NUM_PROCS = 2
type TopProcsCollectorConfig struct {
Num_procs int `json:"num_procs"`
}
type TopProcsCollector struct {
MetricCollector
2021-11-25 15:11:39 +01:00
tags map[string]string
config TopProcsCollectorConfig
}
func (m *TopProcsCollector) Init(config []byte) error {
2021-11-25 15:11:39 +01:00
var err error
m.name = "TopProcsCollector"
2021-10-04 15:23:43 +02:00
m.tags = map[string]string{"type": "node"}
if len(config) > 0 {
2021-11-25 15:11:39 +01:00
err = json.Unmarshal(config, &m.config)
if err != nil {
return err
}
} else {
m.config.Num_procs = int(DEFAULT_NUM_PROCS)
}
if m.config.Num_procs <= 0 || m.config.Num_procs > MAX_NUM_PROCS {
2021-11-25 15:11:39 +01:00
return errors.New(fmt.Sprintf("num_procs option must be set in 'topprocs' config (range: 1-%d)", MAX_NUM_PROCS))
}
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 {
return errors.New("Failed to execute command")
2021-10-04 15:23:43 +02:00
}
m.init = true
return nil
}
2021-10-04 15:23:43 +02:00
func (m *TopProcsCollector) Read(interval time.Duration, out *[]lp.MutableMetric) {
2021-11-25 15:11:39 +01:00
if !m.init {
return
}
2021-05-18 15:14:37 +02:00
command := exec.Command("ps", "-Ao", "comm", "--sort=-pcpu")
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 < m.config.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)
}
}
}
func (m *TopProcsCollector) Close() {
2021-10-04 15:47:03 +02:00
m.init = false
}