gstat/commands/cpu.go

47 lines
1.2 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) {
total, err := c.PureExec(args)
if err != nil {
return []byte{}, err
}
data := struct{ CPU float64 }{CPU: total}
return json.Marshal(data)
}
func (c CPU) PureExec(args args.Arguments) (float64, error) {
if !args.CPU {
return 0, nil
}
total, err := c.ReadCPUStat(time.Millisecond*time.Duration(c.TimeInMilSec), false)
2020-05-30 20:14:49 +02:00
if err != nil {
return 0, errors.BaseError{Operation: OperationKeyCPUReading, Message: err.Error()}
2020-05-30 20:14:49 +02:00
}
return total[0], nil
}