unos/watchdog-go/watchdog/cpu_collector.go

52 lines
996 B
Go

package watchdog
import (
"fmt"
"github.com/shirou/gopsutil/v3/cpu"
"google.golang.org/protobuf/types/known/timestamppb"
"time"
)
type UsedCPU struct {
config Config
}
func NewUsedCpu(config Config) MetricsCollector {
return &UsedCPU{
config: config,
}
}
func (u UsedCPU) Collect() (*Metric, error) {
coreCounts, err := cpu.Counts(false)
if err != nil {
return nil, err
}
threadCounts, err := cpu.Counts(true)
if err != nil {
return nil, err
}
name := u.config.ClientName + " Used CPU"
percent, err := cpu.Percent(100+time.Millisecond, false)
if err != nil {
return nil, err
}
usedCpu := fmt.Sprintf("%g", percent[0])
cpuCore := fmt.Sprintf("%d Core %d Thread", coreCounts, threadCounts)
return &Metric{
Name: name,
ObjectId: toId(name),
Domain: u.config.ClientDomain,
Status: Status_OK,
Value: usedCpu,
Timestamp: timestamppb.Now(),
Message: cpuCore,
}, nil
}
func (u UsedCPU) Timer() time.Duration {
return 1 * time.Minute
}