3x-ui/web/job/check_cpu_usage.go
Борисов Семён f000322a06
Some checks failed
Release 3X-UI / build (386) (push) Has been cancelled
Release 3X-UI / build (amd64) (push) Has been cancelled
Release 3X-UI / build (arm64) (push) Has been cancelled
Release 3X-UI / build (armv5) (push) Has been cancelled
Release 3X-UI / build (armv6) (push) Has been cancelled
Release 3X-UI / build (armv7) (push) Has been cancelled
Release 3X-UI / build (s390x) (push) Has been cancelled
Release 3X-UI / Build for Windows (push) Has been cancelled
fix: handle CPU threshold error to prevent false notifications (#3603)
Previously, when GetTgCpu() failed, the error was ignored and threshold
defaulted to 0, causing notifications to be sent for any CPU usage.

Now the job properly checks for errors and skips notifications if:
- The threshold cannot be retrieved (error)
- The threshold is not set or is 0

This ensures notifications are only sent when CPU usage exceeds the
configured threshold value from settings.
2025-12-12 14:29:27 +01:00

40 lines
1.1 KiB
Go

package job
import (
"strconv"
"time"
"github.com/mhsanaei/3x-ui/v2/web/service"
"github.com/shirou/gopsutil/v4/cpu"
)
// CheckCpuJob monitors CPU usage and sends Telegram notifications when usage exceeds the configured threshold.
type CheckCpuJob struct {
tgbotService service.Tgbot
settingService service.SettingService
}
// NewCheckCpuJob creates a new CPU monitoring job instance.
func NewCheckCpuJob() *CheckCpuJob {
return new(CheckCpuJob)
}
// Run checks CPU usage over the last minute and sends a Telegram alert if it exceeds the threshold.
func (j *CheckCpuJob) Run() {
threshold, err := j.settingService.GetTgCpu()
if err != nil || threshold <= 0 {
// If threshold cannot be retrieved or is not set, skip sending notifications
return
}
// get latest status of server
percent, err := cpu.Percent(1*time.Minute, false)
if err == nil && percent[0] > float64(threshold) {
msg := j.tgbotService.I18nBot("tgbot.messages.cpuThreshold",
"Percent=="+strconv.FormatFloat(percent[0], 'f', 2, 64),
"Threshold=="+strconv.Itoa(threshold))
j.tgbotService.SendMsgToTgbotAdmins(msg)
}
}