gstat/commands/cpu.go

38 lines
1 KiB
Go
Raw Permalink Normal View History

2020-05-30 17:50:20 +02:00
package commands
2020-05-09 14:42:23 +02:00
import (
2020-05-30 20:14:49 +02:00
"encoding/json"
2020-05-09 14:42:23 +02:00
"time"
"github.com/hamburghammer/gstat/args"
"github.com/hamburghammer/gstat/errors"
"github.com/shirou/gopsutil/cpu"
2020-05-09 14:42:23 +02:00
)
// OperationKeyCPUReading represents the key for the Operation field of an CPUReadingError
const OperationKeyCPUReading = "CPUReading"
// CPU holds the config to get the cpu load in percentage
type CPU struct {
TimeInMilSec int
ReadCPUStat func(interval time.Duration, percpu bool) ([]float64, error)
}
// NewCPU creates a new cpu percentage struct
func NewCPU() CPU {
return CPU{TimeInMilSec: 500, ReadCPUStat: cpu.Percent}
2020-05-30 20:14:49 +02:00
}
// Exec gets the cpu value and maps it to the executiondata struct
func (c CPU) Exec(args args.Arguments) ([]byte, error) {
if !args.CPU {
return []byte{}, nil
}
total, err := c.ReadCPUStat(time.Millisecond*time.Duration(c.TimeInMilSec), false)
2020-05-30 20:14:49 +02:00
if err != nil {
2020-06-30 16:36:51 +02:00
return []byte{}, errors.BaseError{Operation: OperationKeyCPUReading, Message: err.Error()}
2020-05-30 20:14:49 +02:00
}
data := struct{ CPU float64 }{CPU: total[0]}
return json.Marshal(data)
}