2023-03-17 09:07:49 -07:00
|
|
|
package job
|
|
|
|
|
|
|
|
|
|
import (
|
2023-05-20 16:00:26 -07:00
|
|
|
"strconv"
|
2023-03-17 09:07:49 -07:00
|
|
|
"time"
|
2024-03-10 14:31:24 -07:00
|
|
|
|
2026-05-09 17:13:42 -07:00
|
|
|
"github.com/mhsanaei/3x-ui/v3/web/service"
|
2023-03-17 09:07:49 -07:00
|
|
|
|
2024-06-17 12:48:49 -07:00
|
|
|
"github.com/shirou/gopsutil/v4/cpu"
|
2023-03-17 09:07:49 -07:00
|
|
|
)
|
|
|
|
|
|
2025-09-20 00:35:50 -07:00
|
|
|
// CheckCpuJob monitors CPU usage and sends Telegram notifications when usage exceeds the configured threshold.
|
2023-03-17 09:07:49 -07:00
|
|
|
type CheckCpuJob struct {
|
|
|
|
|
tgbotService service.Tgbot
|
|
|
|
|
settingService service.SettingService
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-20 00:35:50 -07:00
|
|
|
// NewCheckCpuJob creates a new CPU monitoring job instance.
|
2023-03-17 09:07:49 -07:00
|
|
|
func NewCheckCpuJob() *CheckCpuJob {
|
|
|
|
|
return new(CheckCpuJob)
|
|
|
|
|
}
|
|
|
|
|
|
2025-09-20 00:35:50 -07:00
|
|
|
// Run checks CPU usage over the last minute and sends a Telegram alert if it exceeds the threshold.
|
2023-03-17 09:07:49 -07:00
|
|
|
func (j *CheckCpuJob) Run() {
|
2025-12-12 05:29:27 -08:00
|
|
|
threshold, err := j.settingService.GetTgCpu()
|
|
|
|
|
if err != nil || threshold <= 0 {
|
|
|
|
|
// If threshold cannot be retrieved or is not set, skip sending notifications
|
|
|
|
|
return
|
|
|
|
|
}
|
2023-03-17 09:07:49 -07:00
|
|
|
|
|
|
|
|
// get latest status of server
|
2025-03-06 11:38:58 -08:00
|
|
|
percent, err := cpu.Percent(1*time.Minute, false)
|
2023-03-17 09:07:49 -07:00
|
|
|
if err == nil && percent[0] > float64(threshold) {
|
2023-05-20 16:00:26 -07:00
|
|
|
msg := j.tgbotService.I18nBot("tgbot.messages.cpuThreshold",
|
|
|
|
|
"Percent=="+strconv.FormatFloat(percent[0], 'f', 2, 64),
|
|
|
|
|
"Threshold=="+strconv.Itoa(threshold))
|
|
|
|
|
|
2023-03-17 09:07:49 -07:00
|
|
|
j.tgbotService.SendMsgToTgbotAdmins(msg)
|
|
|
|
|
}
|
|
|
|
|
}
|