2024-05-13 19:37:27 +00:00
|
|
|
package utils
|
2024-05-11 00:37:40 +00:00
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
2024-05-13 12:41:33 +00:00
|
|
|
"log/slog"
|
2024-05-13 20:12:45 +00:00
|
|
|
"oneuptime-infrastructure-agent/model"
|
2024-05-11 00:37:40 +00:00
|
|
|
"time"
|
2024-05-13 19:28:21 +00:00
|
|
|
|
|
|
|
"github.com/shirou/gopsutil/v3/cpu"
|
2024-05-11 00:37:40 +00:00
|
|
|
)
|
|
|
|
|
2024-05-13 20:12:45 +00:00
|
|
|
func GetCpuMetrics() *model.CPUMetrics {
|
2024-05-11 00:37:40 +00:00
|
|
|
//avg, err := load.Avg()
|
|
|
|
//if err != nil {
|
|
|
|
// slog.Error(err)
|
|
|
|
// return nil
|
|
|
|
//}
|
|
|
|
//
|
|
|
|
//numCpu, err := cpu.Counts(true)
|
|
|
|
//if err != nil {
|
|
|
|
// slog.Error(err)
|
|
|
|
// return nil
|
|
|
|
//}
|
|
|
|
//
|
|
|
|
//// Calculate CPU usage, which is the average load over the last minute divided by the number of CPUs
|
|
|
|
//cpuUsage := (avg.Load1 / float64(numCpu)) * 100
|
|
|
|
|
|
|
|
//trying new calculation method, more accurate
|
|
|
|
// Get CPU times at the start
|
|
|
|
startTimes, err := cpu.Times(false) // false to get the aggregate of all CPUs
|
|
|
|
if err != nil {
|
2024-05-13 12:41:33 +00:00
|
|
|
slog.Error(fmt.Sprintf("error fetching initial CPU times: %v", err))
|
2024-05-11 00:37:40 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Wait for a short interval (e.g., 1000 milliseconds)
|
|
|
|
time.Sleep(1000 * time.Millisecond)
|
|
|
|
|
|
|
|
// Get CPU times after the interval
|
|
|
|
endTimes, err := cpu.Times(false)
|
|
|
|
if err != nil {
|
2024-05-13 12:41:33 +00:00
|
|
|
slog.Error(fmt.Sprintf("error fetching final CPU times: %v", err))
|
2024-05-11 00:37:40 +00:00
|
|
|
return nil
|
|
|
|
}
|
|
|
|
|
|
|
|
// Calculate the difference in total and idle times
|
2024-05-13 20:12:45 +00:00
|
|
|
totalDelta := TotalCPUTime(endTimes[0]) - TotalCPUTime(startTimes[0])
|
2024-05-11 00:37:40 +00:00
|
|
|
idleDelta := endTimes[0].Idle - startTimes[0].Idle
|
|
|
|
|
|
|
|
// Calculate the CPU usage percentage
|
|
|
|
if totalDelta == 0 {
|
|
|
|
slog.Error("totalDelta is 0")
|
|
|
|
return nil
|
|
|
|
}
|
|
|
|
cpuUsagePercent := (1 - idleDelta/totalDelta) * 100
|
|
|
|
|
2024-07-02 12:54:04 +00:00
|
|
|
numberOfCpuCores, err := cpu.Counts(true)
|
|
|
|
|
2024-05-13 20:12:45 +00:00
|
|
|
return &model.CPUMetrics{
|
2024-05-11 00:37:40 +00:00
|
|
|
PercentUsed: cpuUsagePercent,
|
2024-07-02 12:54:04 +00:00
|
|
|
Cores: numberOfCpuCores,
|
2024-05-11 00:37:40 +00:00
|
|
|
}
|
|
|
|
}
|
|
|
|
|
2024-05-13 20:12:45 +00:00
|
|
|
func TotalCPUTime(times cpu.TimesStat) float64 {
|
2024-05-11 00:37:40 +00:00
|
|
|
return times.User + times.System + times.Idle + times.Nice +
|
|
|
|
times.Iowait + times.Irq + times.Softirq + times.Steal +
|
|
|
|
times.Guest + times.GuestNice
|
|
|
|
}
|