8 / check mem usage (#10)

* 8 / Check Mem Job
* 8 / check mem usage - localization
This commit is contained in:
serogaq 2024-12-08 18:07:56 +03:00 committed by GitHub
parent 07ffa7a525
commit 876045a123
No known key found for this signature in database
GPG key ID: B5690EEEBB952194
18 changed files with 138 additions and 5 deletions

View file

@ -22,6 +22,8 @@ class AllSetting {
this.tgBotBackup = false;
this.tgBotLoginNotify = true;
this.tgCpu = 80;
this.tgMem = 80;
this.restartAtMemThreshold = false;
this.tgLang = "en-US";
this.xrayTemplateConfig = "";
this.secretEnable = false;
@ -43,7 +45,7 @@ class AllSetting {
this.subJsonMux = "";
this.subJsonRules = "";
this.timeLocation = "Asia/Tehran";
this.timeLocation = "Europe/Moscow";
if (data == null) {
return

View file

@ -36,6 +36,8 @@ type AllSetting struct {
TgBotBackup bool `json:"tgBotBackup" form:"tgBotBackup"`
TgBotLoginNotify bool `json:"tgBotLoginNotify" form:"tgBotLoginNotify"`
TgCpu int `json:"tgCpu" form:"tgCpu"`
TgMem int `json:"tgMem" form:"tgMem"`
RestartAtMemThreshold bool `json:"restartAtMemThreshold" form:"restartAtMemThreshold"`
TgLang string `json:"tgLang" form:"tgLang"`
TimeLocation string `json:"timeLocation" form:"timeLocation"`
SecretEnable bool `json:"secretEnable" form:"secretEnable"`
@ -100,6 +102,10 @@ func (s *AllSetting) CheckValid() error {
}
}
if s.TgMem < 0 || s.TgMem > 100 {
return common.NewError("TgMem must be in the range 0-100, passed ", s.TgMem)
}
if !strings.HasPrefix(s.WebBasePath, "/") {
s.WebBasePath = "/" + s.WebBasePath
}

View file

@ -245,6 +245,8 @@
<setting-list-item type="switch" title='{{ i18n "pages.settings.tgNotifyBackup" }}' desc='{{ i18n "pages.settings.tgNotifyBackupDesc" }}' v-model="allSetting.tgBotBackup"></setting-list-item>
<setting-list-item type="switch" title='{{ i18n "pages.settings.tgNotifyLogin" }}' desc='{{ i18n "pages.settings.tgNotifyLoginDesc" }}' v-model="allSetting.tgBotLoginNotify"></setting-list-item>
<setting-list-item type="number" title='{{ i18n "pages.settings.tgNotifyCpu" }}' desc='{{ i18n "pages.settings.tgNotifyCpuDesc" }}' v-model="allSetting.tgCpu" :min="0" :max="100"></setting-list-item>
<setting-list-item type="number" title='{{ i18n "pages.settings.tgNotifyMem" }}' desc='{{ i18n "pages.settings.tgNotifyMemDesc" }}' v-model="allSetting.tgMem" :min="0" :max="100"></setting-list-item>
<setting-list-item type="switch" title='{{ i18n "pages.settings.restartAtMemThreshold" }}' desc='{{ i18n "pages.settings.restartAtMemThresholdDesc" }}' v-model="allSetting.restartAtMemThreshold"></setting-list-item>
<setting-list-item type="text" title='{{ i18n "pages.settings.telegramProxy"}}' desc='{{ i18n "pages.settings.telegramProxyDesc"}}' v-model="allSetting.tgBotProxy" placeholder="socks5://user:pass@host:port"></setting-list-item>
<setting-list-item type="text" title='{{ i18n "pages.settings.telegramAPIServer"}}' desc='{{ i18n "pages.settings.telegramAPIServerDesc"}}' v-model="allSetting.tgBotAPIServer" placeholder="https://api.example.com"></setting-list-item>
<a-list-item>
@ -464,7 +466,7 @@
type: "field",
outboundTag: "direct",
domain: [
"geosite:category-ir"
"geosite:category-ru"
]
},
{
@ -472,7 +474,7 @@
outboundTag: "direct",
ip: [
"geoip:private",
"geoip:ir"
"geoip:ru"
]
},
],
@ -824,7 +826,7 @@
subJsonPath = this.allSetting.subJsonURI.length > 0 ? new URL(this.allSetting.subJsonURI).pathname : this.allSetting.subJsonPath;
if (subJsonPath == '/json/') alerts.push('{{ i18n "secAlertSubJsonURI" }}');
}
return alerts
return alerts;
}
}
},

View file

@ -0,0 +1,47 @@
package job
import (
"strconv"
"x-ui/web/service"
"x-ui/logger"
"github.com/shirou/gopsutil/v4/mem"
)
type CheckMemJob struct {
tgbotService service.Tgbot
settingService service.SettingService
serverService service.ServerService
}
func NewCheckMemJob() *CheckMemJob {
return new(CheckMemJob)
}
// Here run is a interface method of Job interface
func (j *CheckMemJob) Run() {
threshold, _ := j.settingService.GetTgMem()
needRestart, _ := j.settingService.GetRestartAtMemThreshold()
memInfo, err := mem.VirtualMemory()
if err != nil {
logger.Error("CheckMemJob -- get virtual memory failed:", err)
} else {
currentMem := memInfo.Used
totalMem := memInfo.Total
percentMem := int(currentMem / totalMem * 100)
if percentMem >= int(threshold) && bool(needRestart) == true {
msg := j.tgbotService.I18nBot("tgbot.messages.memThreshold", "Threshold=="+strconv.Itoa(threshold))
j.tgbotService.SendMsgToTgbotAdmins(msg)
err := j.serverService.RestartXrayService()
if err != nil {
logger.Error("CheckMemJob -- RestartXrayService failed:", err)
} else {
logger.Info("CheckMemJob -- RestartXrayService success")
}
}
}
}

View file

@ -37,7 +37,7 @@ var defaultValueMap = map[string]string{
"expireDiff": "0",
"trafficDiff": "0",
"remarkModel": "-ieo",
"timeLocation": "Asia/Tehran",
"timeLocation": "Europe/Moscow",
"tgBotEnable": "false",
"tgBotToken": "",
"tgBotProxy": "",
@ -47,6 +47,8 @@ var defaultValueMap = map[string]string{
"tgBotBackup": "false",
"tgBotLoginNotify": "true",
"tgCpu": "80",
"tgMem": "80",
"restartAtMemThreshold":"false",
"tgLang": "en-US",
"secretEnable": "false",
"subEnable": "false",
@ -311,6 +313,14 @@ func (s *SettingService) GetTgCpu() (int, error) {
return s.getInt("tgCpu")
}
func (s *SettingService) GetTgMem() (int, error) {
return s.getInt("tgMem")
}
func (s *SettingService) GetRestartAtMemThreshold() (bool, error) {
return s.getBool("restartAtMemThreshold")
}
func (s *SettingService) GetTgLang() (string, error) {
return s.getString("tgLang")
}

View file

@ -282,6 +282,10 @@
"trafficDiffDesc" = "Get notified about traffic cap when reaching this threshold. (unit: GB)"
"tgNotifyCpu" = "CPU Load Notification"
"tgNotifyCpuDesc" = "Get notified if CPU load exceeds this threshold. (unit: %)"
"tgNotifyMem" = "RAM Load Notification"
"tgNotifyMemDesc" = "Get notified if RAM load exceeds this threshold. (unit: %)"
"restartAtMemThreshold" = "Restart Xray when the threshold is reached"
"restartAtMemThresholdDesc" = "When the RAM utilization reaches the specified percentage, Xray will be restarted"
"timeZone" = "Time Zone"
"timeZoneDesc" = "Scheduled tasks will run based on this time zone."
"subSettings" = "Subscription"
@ -493,6 +497,7 @@
[tgbot.messages]
"cpuThreshold" = "🔴 CPU Load {{ .Percent }}% exceeds the threshold of {{ .Threshold }}%"
"memThreshold" = "🔴 RAM Threshold\r\nThe {{ .Threshold }}% threshold has been reached. Reboot performed"
"selectUserFailed" = "❌ Error in user selection!"
"userSaved" = "✅ Telegram User saved."
"loginSuccess" = "✅ Logged in to the panel successfully.\r\n"

View file

@ -282,6 +282,10 @@
"trafficDiffDesc" = "Reciba notificaciones sobre el agotamiento del tráfico antes de alcanzar el umbral (unidad: GB)."
"tgNotifyCpu" = "Umbral de Alerta de Porcentaje de CPU"
"tgNotifyCpuDesc" = "Reciba notificaciones si el uso de la CPU supera este umbral (unidad: %)."
"tgNotifyMem" = "RAM Load Notification"
"tgNotifyMemDesc" = "Get notified if RAM load exceeds this threshold. (unit: %)"
"restartAtMemThreshold" = "Restart Xray when the threshold is reached"
"restartAtMemThresholdDesc" = "When the RAM utilization reaches the specified percentage, Xray will be restarted"
"timeZone" = "Zona Horaria"
"timeZoneDesc" = "Las tareas programadas se ejecutan de acuerdo con la hora en esta zona horaria."
"subSettings" = "Suscripción"
@ -493,6 +497,7 @@
[tgbot.messages]
"cpuThreshold" = "🔴 El uso de CPU {{ .Percent }}% es mayor que el umbral {{ .Threshold }}%"
"memThreshold" = "🔴 RAM Threshold\r\nThe {{ .Threshold }}% threshold has been reached. Reboot performed"
"selectUserFailed" = "❌ ¡Error al seleccionar usuario!"
"userSaved" = "✅ Usuario de Telegram guardado."
"loginSuccess" = "✅ Has iniciado sesión en el panel con éxito.\r\n"

View file

@ -282,6 +282,10 @@
"trafficDiffDesc" = "(فاصله زمانی هشدار تا رسیدن به اتمام ترافیک. (واحد: گیگابایت"
"tgNotifyCpu" = "آستانه هشدار بار پردازنده"
"tgNotifyCpuDesc" = "(اگر بار روی پردازنده ازاین آستانه فراتر رفت، برای شما پیام ارسال می‌شود. (واحد: درصد"
"tgNotifyMem" = "RAM Load Notification"
"tgNotifyMemDesc" = "Get notified if RAM load exceeds this threshold. (unit: %)"
"restartAtMemThreshold" = "Restart Xray when the threshold is reached"
"restartAtMemThresholdDesc" = "When the RAM utilization reaches the specified percentage, Xray will be restarted"
"timeZone" = "منطقه زمانی"
"timeZoneDesc" = "وظایف برنامه ریزی شده بر اساس این منطقه‌زمانی اجرا می‌شود"
"subSettings" = "سابسکریپشن"
@ -493,6 +497,7 @@
[tgbot.messages]
"cpuThreshold" = "🔴 بار ‌پردازنده {{ .Percent }}% بیشتر از آستانه است {{ .Threshold }}%"
"memThreshold" = "🔴 RAM Threshold\r\nThe {{ .Threshold }}% threshold has been reached. Reboot performed"
"selectUserFailed" = "❌ خطا در انتخاب کاربر!"
"userSaved" = "✅ کاربر تلگرام ذخیره شد."
"loginSuccess" = "✅ با موفقیت به پنل وارد شدید.\r\n"

View file

@ -282,6 +282,10 @@
"trafficDiffDesc" = "Dapatkan notifikasi tentang batas traffic saat mencapai ambang batas ini. (unit: GB)"
"tgNotifyCpu" = "Notifikasi Beban CPU"
"tgNotifyCpuDesc" = "Dapatkan notifikasi jika beban CPU melebihi ambang batas ini. (unit: %)"
"tgNotifyMem" = "RAM Load Notification"
"tgNotifyMemDesc" = "Get notified if RAM load exceeds this threshold. (unit: %)"
"restartAtMemThreshold" = "Restart Xray when the threshold is reached"
"restartAtMemThresholdDesc" = "When the RAM utilization reaches the specified percentage, Xray will be restarted"
"timeZone" = "Zone Waktu"
"timeZoneDesc" = "Tugas terjadwal akan berjalan berdasarkan zona waktu ini."
"subSettings" = "Langganan"
@ -493,6 +497,7 @@
[tgbot.messages]
"cpuThreshold" = "🔴 Beban CPU {{ .Percent }}% melebihi batas {{ .Threshold }}%"
"memThreshold" = "🔴 RAM Threshold\r\nThe {{ .Threshold }}% threshold has been reached. Reboot performed"
"selectUserFailed" = "❌ Kesalahan dalam pemilihan pengguna!"
"userSaved" = "✅ Pengguna Telegram tersimpan."
"loginSuccess" = "✅ Berhasil masuk ke panel.\r\n"

View file

@ -282,6 +282,10 @@
"trafficDiffDesc" = "このしきい値に達した場合、トラフィック消耗に関する通知を受け取る単位GB"
"tgNotifyCpu" = "CPU負荷通知しきい値"
"tgNotifyCpuDesc" = "CPU負荷がこのしきい値を超えた場合、通知を受け取る単位%"
"tgNotifyMem" = "RAM Load Notification"
"tgNotifyMemDesc" = "Get notified if RAM load exceeds this threshold. (unit: %)"
"restartAtMemThreshold" = "Restart Xray when the threshold is reached"
"restartAtMemThresholdDesc" = "When the RAM utilization reaches the specified percentage, Xray will be restarted"
"timeZone" = "タイムゾーン"
"timeZoneDesc" = "定時タスクはこのタイムゾーンの時間に従って実行される"
"subSettings" = "サブスクリプション設定"
@ -493,6 +497,7 @@
[tgbot.messages]
"cpuThreshold" = "🔴 CPU使用率は{{ .Percent }}%、しきい値{{ .Threshold }}%を超えました"
"memThreshold" = "🔴 RAM Threshold\r\nThe {{ .Threshold }}% threshold has been reached. Reboot performed"
"selectUserFailed" = "❌ ユーザーの選択に失敗しました!"
"userSaved" = "✅ Telegramユーザーが保存されました。"
"loginSuccess" = "✅ パネルに正常にログインしました。\r\n"

View file

@ -282,6 +282,10 @@
"trafficDiffDesc" = "Receba notificações sobre o limite de tráfego ao atingir esse limite. (unidade: GB)"
"tgNotifyCpu" = "Notificação de Carga da CPU"
"tgNotifyCpuDesc" = "Receba notificações se a carga da CPU ultrapassar esse limite. (unidade: %)"
"tgNotifyMem" = "RAM Load Notification"
"tgNotifyMemDesc" = "Get notified if RAM load exceeds this threshold. (unit: %)"
"restartAtMemThreshold" = "Restart Xray when the threshold is reached"
"restartAtMemThresholdDesc" = "When the RAM utilization reaches the specified percentage, Xray will be restarted"
"timeZone" = "Fuso Horário"
"timeZoneDesc" = "As tarefas agendadas serão executadas com base nesse fuso horário."
"subSettings" = "Assinatura"
@ -493,6 +497,7 @@
[tgbot.messages]
"cpuThreshold" = "🔴 A carga da CPU {{ .Percent }}% excede o limite de {{ .Threshold }}%"
"memThreshold" = "🔴 RAM Threshold\r\nThe {{ .Threshold }}% threshold has been reached. Reboot performed"
"selectUserFailed" = "❌ Erro na seleção do usuário!"
"userSaved" = "✅ Usuário do Telegram salvo."
"loginSuccess" = "✅ Conectado ao painel com sucesso.\r\n"

View file

@ -282,6 +282,10 @@
"trafficDiffDesc" = "Получение уведомления об исчерпании трафика до достижения порога (значение: ГБ)"
"tgNotifyCpu" = "Порог нагрузки на ЦП для уведомления"
"tgNotifyCpuDesc" = "Получение уведомления, если нагрузка на ЦП превышает этот порог (значение: %)"
"tgNotifyMem" = "RAM Load Notification"
"tgNotifyMemDesc" = "Get notified if RAM load exceeds this threshold. (unit: %)"
"restartAtMemThreshold" = "Restart Xray when the threshold is reached"
"restartAtMemThresholdDesc" = "When the RAM utilization reaches the specified percentage, Xray will be restarted"
"timeZone" = "Часовой пояс"
"timeZoneDesc" = "Запланированные задачи выполняются в соответствии со временем в этом часовом поясе"
"subSettings" = "Подписка"
@ -493,6 +497,7 @@
[tgbot.messages]
"cpuThreshold" = "🔴 Загрузка процессора составляет {{ .Percent }}%, что превышает пороговое значение {{ .Threshold }}%"
"memThreshold" = "🔴 RAM Threshold\r\nThe {{ .Threshold }}% threshold has been reached. Reboot performed"
"selectUserFailed" = "❌ Ошибка при выборе пользователя!"
"userSaved" = "✅ Пользователь Telegram сохранен."
"loginSuccess" = "✅ Успешный вход в панель.\r\n"

View file

@ -282,6 +282,10 @@
"trafficDiffDesc" = "Bu eşik seviyesine ulaşıldığında trafik sınırı hakkında bildirim alın. (birim: GB)"
"tgNotifyCpu" = "CPU Yükü Bildirimi"
"tgNotifyCpuDesc" = "CPU yükü bu eşik seviyesini aşarsa bildirim alın. (birim: %)"
"tgNotifyMem" = "RAM Load Notification"
"tgNotifyMemDesc" = "Get notified if RAM load exceeds this threshold. (unit: %)"
"restartAtMemThreshold" = "Restart Xray when the threshold is reached"
"restartAtMemThresholdDesc" = "When the RAM utilization reaches the specified percentage, Xray will be restarted"
"timeZone" = "Saat Dilimi"
"timeZoneDesc" = "Planlanmış görevler bu saat dilimine göre çalışacaktır."
"subSettings" = "Abonelik"
@ -493,6 +497,7 @@
[tgbot.messages]
"cpuThreshold" = "🔴 CPU Yükü {{ .Percent }}% eşiği {{ .Threshold }}%'yi aşıyor"
"memThreshold" = "🔴 RAM Threshold\r\nThe {{ .Threshold }}% threshold has been reached. Reboot performed"
"selectUserFailed" = "❌ Kullanıcı seçiminde hata!"
"userSaved" = "✅ Telegram Kullanıcısı kaydedildi."
"loginSuccess" = "✅ Panele başarıyla giriş yapıldı.\r\n"

View file

@ -282,6 +282,10 @@
"trafficDiffDesc" = "Отримувати сповіщення про обмеження трафіку при досягненні цього порогу. (одиниця: ГБ)"
"tgNotifyCpu" = "Сповіщення про завантаження ЦП"
"tgNotifyCpuDesc" = "Отримувати сповіщення, якщо навантаження ЦП перевищує це порогове значення. (одиниця: %)"
"tgNotifyMem" = "RAM Load Notification"
"tgNotifyMemDesc" = "Get notified if RAM load exceeds this threshold. (unit: %)"
"restartAtMemThreshold" = "Restart Xray when the threshold is reached"
"restartAtMemThresholdDesc" = "When the RAM utilization reaches the specified percentage, Xray will be restarted"
"timeZone" = "Часовий пояс"
"timeZoneDesc" = "Заплановані завдання виконуватимуться на основі цього часового поясу."
"subSettings" = "Підписка"
@ -493,6 +497,7 @@
[tgbot.messages]
"cpuThreshold" = "🔴 Навантаження ЦП {{ .Percent }}% перевищує порогове значення {{ .Threshold }}%"
"memThreshold" = "🔴 RAM Threshold\r\nThe {{ .Threshold }}% threshold has been reached. Reboot performed"
"selectUserFailed" = "❌ Помилка під час вибору користувача!"
"userSaved" = "✅ Користувача Telegram збережено."
"loginSuccess" = "✅ Успішно ввійшли в панель\r\n"

View file

@ -282,6 +282,10 @@
"trafficDiffDesc" = "Nhận thông báo về việc cạn kiệt lưu lượng trước khi đạt đến ngưỡng này (đơn vị: GB)"
"tgNotifyCpu" = "Ngưỡng cảnh báo tỷ lệ CPU"
"tgNotifyCpuDesc" = "Nhận thông báo nếu tỷ lệ sử dụng CPU vượt quá ngưỡng này (đơn vị: %)"
"tgNotifyMem" = "RAM Load Notification"
"tgNotifyMemDesc" = "Get notified if RAM load exceeds this threshold. (unit: %)"
"restartAtMemThreshold" = "Restart Xray when the threshold is reached"
"restartAtMemThresholdDesc" = "When the RAM utilization reaches the specified percentage, Xray will be restarted"
"timeZone" = "Múi giờ"
"timeZoneDesc" = "Các tác vụ được lên lịch chạy theo thời gian trong múi giờ này."
"subSettings" = "Gói đăng ký"
@ -493,6 +497,7 @@
[tgbot.messages]
"cpuThreshold" = "🔴 Sử dụng CPU {{ .Percent }}% vượt quá ngưỡng {{ .Threshold }}%"
"memThreshold" = "🔴 RAM Threshold\r\nThe {{ .Threshold }}% threshold has been reached. Reboot performed"
"selectUserFailed" = "❌ Lỗi khi chọn người dùng!"
"userSaved" = "✅ Người dùng Telegram đã được lưu."
"loginSuccess" = "✅ Đăng nhập thành công vào bảng điều khiển.\r\n"

View file

@ -282,6 +282,10 @@
"trafficDiffDesc" = "达到此阈值时将收到有关流量耗尽的通知单位GB"
"tgNotifyCpu" = "CPU 负载通知阈值"
"tgNotifyCpuDesc" = "CPU 负载超过此阈值时,将收到通知(单位:%"
"tgNotifyMem" = "RAM Load Notification"
"tgNotifyMemDesc" = "Get notified if RAM load exceeds this threshold. (unit: %)"
"restartAtMemThreshold" = "Restart Xray when the threshold is reached"
"restartAtMemThresholdDesc" = "When the RAM utilization reaches the specified percentage, Xray will be restarted"
"timeZone" = "时区"
"timeZoneDesc" = "定时任务将按照该时区的时间运行"
"subSettings" = "订阅设置"
@ -493,6 +497,7 @@
[tgbot.messages]
"cpuThreshold" = "🔴 CPU 使用率为 {{ .Percent }}%,超过阈值 {{ .Threshold }}%"
"memThreshold" = "🔴 RAM Threshold\r\nThe {{ .Threshold }}% threshold has been reached. Reboot performed"
"selectUserFailed" = "❌ 用户选择错误!"
"userSaved" = "✅ 电报用户已保存。"
"loginSuccess" = "✅ 成功登录到面板。\r\n"

View file

@ -282,6 +282,10 @@
"trafficDiffDesc" = "達到此閾值時將收到有關流量耗盡的通知單位GB"
"tgNotifyCpu" = "CPU 負載通知閾值"
"tgNotifyCpuDesc" = "CPU 負載超過此閾值時,將收到通知(單位:%"
"tgNotifyMem" = "RAM Load Notification"
"tgNotifyMemDesc" = "Get notified if RAM load exceeds this threshold. (unit: %)"
"restartAtMemThreshold" = "Restart Xray when the threshold is reached"
"restartAtMemThresholdDesc" = "When the RAM utilization reaches the specified percentage, Xray will be restarted"
"timeZone" = "時區"
"timeZoneDesc" = "定時任務將按照該時區的時間執行"
"subSettings" = "訂閱設定"
@ -493,6 +497,7 @@
[tgbot.messages]
"cpuThreshold" = "🔴 CPU 使用率為 {{ .Percent }}%,超過閾值 {{ .Threshold }}%"
"memThreshold" = "🔴 RAM Threshold\r\nThe {{ .Threshold }}% threshold has been reached. Reboot performed"
"selectUserFailed" = "❌ 使用者選擇錯誤!"
"userSaved" = "✅ 電報使用者已儲存。"
"loginSuccess" = "✅ 成功登入到面板。\r\n"

View file

@ -290,6 +290,12 @@ func (s *Server) startTask() {
if (err == nil) && (cpuThreshold > 0) {
s.cron.AddJob("@every 10s", job.NewCheckCpuJob())
}
// Check RAM and alarm to TgBot if threshold passes
memThreshold, err := s.settingService.GetTgMem()
if (err == nil) && (memThreshold > 0) {
s.cron.AddJob("@every 10s", job.NewCheckMemJob())
}
} else {
s.cron.Remove(entry)
}