2020-08-27 00:37:32 -07:00
|
|
|
package metrics
|
|
|
|
|
|
|
|
import (
|
|
|
|
"time"
|
|
|
|
|
2024-10-12 03:13:33 +08:00
|
|
|
"github.com/shirou/gopsutil/v4/cpu"
|
|
|
|
"github.com/shirou/gopsutil/v4/disk"
|
|
|
|
"github.com/shirou/gopsutil/v4/mem"
|
2020-12-21 19:42:47 -08:00
|
|
|
|
|
|
|
log "github.com/sirupsen/logrus"
|
2020-08-27 00:37:32 -07:00
|
|
|
)
|
|
|
|
|
|
|
|
// Max number of metrics we want to keep.
|
2022-03-24 23:06:47 -07:00
|
|
|
const maxCollectionValues = 300
|
2020-08-27 00:37:32 -07:00
|
|
|
|
|
|
|
func collectCPUUtilization() {
|
2022-03-16 17:34:44 -07:00
|
|
|
if len(metrics.CPUUtilizations) > maxCollectionValues {
|
|
|
|
metrics.CPUUtilizations = metrics.CPUUtilizations[1:]
|
2020-08-27 00:37:32 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
v, err := cpu.Percent(0, false)
|
|
|
|
if err != nil {
|
2020-12-21 19:42:47 -08:00
|
|
|
log.Errorln(err)
|
|
|
|
return
|
2020-08-27 00:37:32 -07:00
|
|
|
}
|
|
|
|
|
2022-12-09 09:49:17 -08:00
|
|
|
// Default to zero but try to use the cumulative values of all the CPUs
|
|
|
|
// if values exist.
|
|
|
|
value := 0.0
|
|
|
|
if len(v) > 0 {
|
|
|
|
value = v[0]
|
|
|
|
}
|
|
|
|
|
|
|
|
metricValue := TimestampedValue{time.Now(), value}
|
2022-03-16 17:34:44 -07:00
|
|
|
metrics.CPUUtilizations = append(metrics.CPUUtilizations, metricValue)
|
|
|
|
cpuUsage.Set(metricValue.Value)
|
2020-08-27 00:37:32 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
func collectRAMUtilization() {
|
2022-03-16 17:34:44 -07:00
|
|
|
if len(metrics.RAMUtilizations) > maxCollectionValues {
|
|
|
|
metrics.RAMUtilizations = metrics.RAMUtilizations[1:]
|
2020-08-27 00:37:32 -07:00
|
|
|
}
|
|
|
|
|
|
|
|
memoryUsage, _ := mem.VirtualMemory()
|
2022-03-16 17:34:44 -07:00
|
|
|
metricValue := TimestampedValue{time.Now(), memoryUsage.UsedPercent}
|
|
|
|
metrics.RAMUtilizations = append(metrics.RAMUtilizations, metricValue)
|
2020-08-27 00:37:32 -07:00
|
|
|
}
|
2020-10-02 12:18:08 -07:00
|
|
|
|
|
|
|
func collectDiskUtilization() {
|
|
|
|
path := "./"
|
|
|
|
diskUse, _ := disk.Usage(path)
|
|
|
|
|
2022-03-16 17:34:44 -07:00
|
|
|
if len(metrics.DiskUtilizations) > maxCollectionValues {
|
|
|
|
metrics.DiskUtilizations = metrics.DiskUtilizations[1:]
|
2020-10-02 12:18:08 -07:00
|
|
|
}
|
|
|
|
|
2022-03-16 17:34:44 -07:00
|
|
|
metricValue := TimestampedValue{time.Now(), diskUse.UsedPercent}
|
|
|
|
metrics.DiskUtilizations = append(metrics.DiskUtilizations, metricValue)
|
2020-10-02 12:18:08 -07:00
|
|
|
}
|