gstat/commands/cpu.go
Augusto Dwenger J. f004c93773 refactor: implement single point for json marshal
This implementation still isn't perfect. One of the encoutered problems
is that it does not omit Memory sturcts that are technicly empty.
Resulting in JSON with empty objects. This should be a problem for other
parsers but it doesn't look good.
2021-01-02 18:10:16 +01:00

47 lines
1.2 KiB
Go

package commands
import (
"encoding/json"
"time"
"github.com/hamburghammer/gstat/args"
"github.com/hamburghammer/gstat/errors"
"github.com/shirou/gopsutil/cpu"
)
// 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}
}
// 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)
if err != nil {
return 0, errors.BaseError{Operation: OperationKeyCPUReading, Message: err.Error()}
}
return total[0], nil
}