Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
10 changes: 7 additions & 3 deletions agent/app/api/v2/alert.go
Original file line number Diff line number Diff line change
Expand Up @@ -243,7 +243,11 @@ func (b *BaseApi) GetCronJobs(c *gin.Context) {
// @Security Timestamp
// @Router /alert/config/info [post]
func (b *BaseApi) GetAlertConfig(c *gin.Context) {
config, err := alertService.GetAlertConfig()
var req dto.AlertConfigQuery
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
config, err := alertService.GetAlertConfig(req)
if err != nil {
helper.InternalServer(c, err)
return
Expand All @@ -254,13 +258,13 @@ func (b *BaseApi) GetAlertConfig(c *gin.Context) {
// @Tags Alert
// @Summary Page alert config
// @Accept json
// @Param request body dto.PageInfo true "request"
// @Param request body dto.AlertConfigPageReq true "request"
// @Success 200
// @Security ApiKeyAuth
// @Security Timestamp
// @Router /alert/config/search [post]
func (b *BaseApi) PageAlertConfig(c *gin.Context) {
var req dto.PageInfo
var req dto.AlertConfigPageReq
if err := helper.CheckBindAndValidate(&req, c); err != nil {
return
}
Expand Down
9 changes: 9 additions & 0 deletions agent/app/dto/alert.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,15 @@ type AlertSearch struct {
Method string `json:"method"`
}

type AlertConfigQuery struct {
ExcludeTypes []string `json:"excludeTypes"`
}

type AlertConfigPageReq struct {
PageInfo
ExcludeTypes []string `json:"excludeTypes"`
}

type AlertDTO struct {
ID uint `json:"id"`
Type string `json:"type"`
Expand Down
19 changes: 9 additions & 10 deletions agent/app/service/alert.go
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ import (
type AlertService struct{}

var eeHiddenAlertTypes = []string{"licenseException", "panelUpdate", "panelPwdEndTime"}
var hiddenAlertConfigTypes = []string{"sms"}

type IAlertService interface {
PageAlert(req dto.AlertSearch) (int64, []dto.AlertDTO, error)
Expand All @@ -44,8 +43,8 @@ type IAlertService interface {
GetClams() ([]dto.ClamDTO, error)
GetCronJobs(req dto.CronJobReq) ([]dto.CronJobDTO, error)

GetAlertConfig() ([]model.AlertConfig, error)
PageAlertConfig(req dto.PageInfo) (int64, []model.AlertConfig, error)
GetAlertConfig(req dto.AlertConfigQuery) ([]model.AlertConfig, error)
PageAlertConfig(req dto.AlertConfigPageReq) (int64, []model.AlertConfig, error)
UpdateAlertConfig(req dto.AlertConfigUpdate, operator string) error
DeleteAlertConfig(id uint) error
TestAlertConfig(req dto.AlertConfigTest) (bool, error)
Expand Down Expand Up @@ -469,26 +468,26 @@ func (a AlertService) GetCronJobs(req dto.CronJobReq) ([]dto.CronJobDTO, error)
return cronJobs, err
}

func (a AlertService) GetAlertConfig() ([]model.AlertConfig, error) {
func (a AlertService) GetAlertConfig(req dto.AlertConfigQuery) ([]model.AlertConfig, error) {
var (
opts []repo.DBOption
configs []model.AlertConfig
)
if global.CONF.Base.IsEnterprise || global.CONF.Base.Edition == "intl" {
opts = append(opts, alertRepo.WithByTypeNotIn(hiddenAlertConfigTypes))
if len(req.ExcludeTypes) > 0 {
opts = append(opts, alertRepo.WithByTypeNotIn(req.ExcludeTypes))
}
opts = append(opts, repo.WithByStatus(constant.AlertEnable))
configs, err := alertRepo.AlertConfigList(opts...)
return configs, err
}

func (a AlertService) PageAlertConfig(req dto.PageInfo) (int64, []model.AlertConfig, error) {
func (a AlertService) PageAlertConfig(req dto.AlertConfigPageReq) (int64, []model.AlertConfig, error) {
opts := []repo.DBOption{
alertRepo.WithByTypeNotIn([]string{"common"}),
repo.WithOrderDesc("created_at"),
}
if global.CONF.Base.IsEnterprise || global.CONF.Base.Edition == "intl" {
opts = append(opts, alertRepo.WithByTypeNotIn(hiddenAlertConfigTypes))
if len(req.ExcludeTypes) > 0 {
opts = append(opts, alertRepo.WithByTypeNotIn(req.ExcludeTypes))
}
return alertRepo.PageAlertConfig(req.Page, req.PageSize, opts...)
}
Expand Down Expand Up @@ -585,7 +584,7 @@ func (a AlertService) DeleteAlertConfig(id uint) error {
usedAlerts = append(usedAlerts, legacyAlerts...)
}
if len(usedAlerts) > 0 {
return fmt.Errorf("alert config is in use")
return buserr.New("ErrAlertConfigInUse")
}
return alertRepo.DeleteAlertConfig(repo.WithByID(id))
}
Expand Down
8 changes: 4 additions & 4 deletions agent/app/service/container.go
Original file line number Diff line number Diff line change
Expand Up @@ -297,14 +297,14 @@ func (u *ContainerService) ContainerListStats() ([]dto.ContainerListStats, error
if err != nil {
return nil, err
}
var datas []dto.ContainerListStats
datas := make([]dto.ContainerListStats, len(list))
var wg sync.WaitGroup
wg.Add(len(list))
for i := 0; i < len(list); i++ {
go func(item container.Summary) {
datas = append(datas, loadCpuAndMem(client, item.ID))
go func(index int, item container.Summary) {
datas[index] = loadCpuAndMem(client, item.ID)
wg.Done()
}(list[i])
}(i, list[i])
}
wg.Wait()
return datas, nil
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/en.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ ErrBackupInUsed: 'Backup account is in use by a scheduled task'
ErrBackupCheck: 'Backup account connectivity test failed: {{ .err }}'
ErrBackupLocalDelete: 'Local backup accounts cannot be deleted'
ErrBackupLocalCreate: 'Local backup accounts cannot be created'
ErrAlertConfigInUse: 'Alert configuration is in use and cannot be deleted'

#app
ErrPortInUsed: '{{ .detail }} port is already occupied!'
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/es-ES.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ ErrBackupInUsed: 'Cuenta de respaldo en uso por tarea programada'
ErrBackupCheck: 'Conexión de respaldo falló: {{ .err }}'
ErrBackupLocalDelete: 'No se puede eliminar cuentas de respaldo locales'
ErrBackupLocalCreate: 'No se pueden crear cuentas de respaldo locales'
ErrAlertConfigInUse: 'La configuración de alertas está en uso y no se puede eliminar'
ErrPortInUsed: 'El puerto {{ .detail }} ya está ocupado'
ErrAppLimit: 'El número de aplicaciones instaladas ha superado el límite'
ErrNotInstall: 'Aplicación no instalada'
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/ja.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ ErrBackupInUsed: 'バックアップアカウントがスケジュールで使
ErrBackupCheck: '接続テストに失敗しました: {{ .err }}'
ErrBackupLocalDelete: 'ローカルバックアップは削除できません'
ErrBackupLocalCreate: 'ローカルバックアップは作成できません'
ErrAlertConfigInUse: 'アラート設定は使用中のため削除できません'
ErrPortInUsed: '{{ .detail }} ポートはすでに使用されています'
ErrAppLimit: 'インストールされているアプリケーションの数が制限を超えました'
ErrNotInstall: 'アプリケーションがインストールされていません'
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/ko.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ ErrBackupInUsed: '백업 계정이 예약에 사용 중'
ErrBackupCheck: '연결 테스트 실패: {{ .err }}'
ErrBackupLocalDelete: '로컬 백업은 삭제할 수 없습니다'
ErrBackupLocalCreate: '로컬 백업은 만들 수 없습니다'
ErrAlertConfigInUse: '경고 설정이 사용 중이므로 삭제할 수 없습니다'
ErrPortInUsed: '{{ .detail }} 포트가 이미 사용 중입니다'
ErrAppLimit: '설치된 애플리케이션 수가 한도를 초과했습니다'
ErrNotInstall: '응용 프로그램이 설치되지 않았습니다'
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/ms.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ ErrBackupInUsed: 'Akaun sandaran sedang digunakan oleh tugas'
ErrBackupCheck: 'Ujian sambungan gagal: {{ .err }}'
ErrBackupLocalDelete: 'Tidak boleh padam sandaran tempatan'
ErrBackupLocalCreate: 'Tidak boleh buat sandaran tempatan'
ErrAlertConfigInUse: 'Konfigurasi amaran sedang digunakan dan tidak boleh dipadamkan'
ErrPortInUsed: 'Port {{ .detail }} sudah diduduki'
ErrAppLimit: 'Bilangan aplikasi yang dipasang telah melebihi had'
ErrNotInstall: 'Aplikasi tidak dipasang'
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/pt-BR.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ ErrBackupInUsed: 'Conta de backup em uso por tarefa'
ErrBackupCheck: 'Teste de conexão falhou: {{ .err }}'
ErrBackupLocalDelete: 'Não é permitido excluir contas locais'
ErrBackupLocalCreate: 'Não é permitido criar contas locais'
ErrAlertConfigInUse: 'A configuração de alerta está em uso e não pode ser excluída'
ErrPortInUsed: 'A porta {{ .detail }} já está ocupada'
ErrAppLimit: 'O número de aplicativos instalados excedeu o limite'
ErrNotInstall: 'Aplicativo não instalado'
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/ru.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ ErrBackupInUsed: 'Аккаунт бэкапа занят задачей'
ErrBackupCheck: 'Проверка подключения не удалась: {{ .err }}'
ErrBackupLocalDelete: 'Нельзя удалить локальные бэкапы'
ErrBackupLocalCreate: 'Нельзя создать локальные бэкапы'
ErrAlertConfigInUse: 'Конфигурация оповещений используется и не может быть удалена'
ErrPortInUsed: '{{ .detail }} порт уже занят'
ErrAppLimit: 'Количество установленных приложений превысило лимит'
ErrNotInstall: 'Приложение не установлено'
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/tr.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ ErrBackupInUsed: 'Yedek hesabı görevde kullanılıyor'
ErrBackupCheck: 'Bağlantı testi başarısız: {{ .err }}'
ErrBackupLocalDelete: 'Yerel yedek silme yok'
ErrBackupLocalCreate: 'Yerel yedek oluşturma yok'
ErrAlertConfigInUse: 'Uyarı yapılandırması kullanımda ve silinemez'
ErrPortInUsed: '{{ .detail }} portu zaten kullanılıyor'
ErrAppLimit: 'Yüklenen uygulama sayısı sınırı aştı'
ErrNotInstall: 'Uygulama yüklenmedi'
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/zh-Hant.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -75,6 +75,7 @@ ErrBackupInUsed: '此備份帳號已在排程任務中使用,無法刪除'
ErrBackupCheck: '備份帳號測試連線失敗{{ .err }}'
ErrBackupLocalDelete: '暫時不支援刪除本機伺服器備份帳號'
ErrBackupLocalCreate: '暫時不支援建立本機伺服器備份帳號'
ErrAlertConfigInUse: '告警配置正在使用中,無法刪除'
ErrPortInUsed: '{{ .detail }} 連接埠已被佔用!'
ErrAppLimit: '應用程式超出安裝數量限制'
ErrNotInstall: '應用程式未安裝'
Expand Down
1 change: 1 addition & 0 deletions agent/i18n/lang/zh.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -74,6 +74,7 @@ ErrBackupInUsed: "该备份账号已在计划任务中使用,无法删除"
ErrBackupCheck: "备份账号测试连接失败 {{ .err }}"
ErrBackupLocalDelete: "暂不支持删除本地服务器备份账号"
ErrBackupLocalCreate: "暂不支持创建本地服务器备份账号"
ErrAlertConfigInUse: "告警配置正在使用中,无法删除"

#app
ErrPortInUsed: "{{ .detail }} 端口已被占用!"
Expand Down
10 changes: 9 additions & 1 deletion core/app/auth/api_auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ func isValid1PanelToken(panelToken string, panelTimestamp string, apiKey string)
}

func isIPInWhiteList(clientIP string, ipWhiteString string) bool {
if len(ipWhiteString) == 0 {
if strings.TrimSpace(ipWhiteString) == "" {
global.LOG.Error("IP whitelist is empty")
return false
}
Expand All @@ -136,9 +136,17 @@ func isIPInWhiteList(clientIP string, ipWhiteString string) bool {
iPv4 := clientParsedIP.To4()
iPv6 := clientParsedIP.To16()
for _, cidr := range ipWhiteList {
cidr = strings.TrimSpace(cidr)
if cidr == "" {
continue
}
if (iPv4 != nil && (cidr == "0.0.0.0" || cidr == "0.0.0.0/0" || iPv4.String() == cidr)) || (iPv6 != nil && (cidr == "::/0" || iPv6.String() == cidr)) {
return true
}
whiteIP := net.ParseIP(cidr)
if whiteIP != nil && whiteIP.Equal(clientParsedIP) {
return true
}
_, ipNet, err := net.ParseCIDR(cidr)
if err != nil {
continue
Expand Down
1 change: 1 addition & 0 deletions core/constant/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -201,6 +201,7 @@ var WebUrlMap = map[string]struct{}{
"/enterprise/ops-report/website": {},
"/enterprise/ops-report/resource": {},
"/enterprise/ops-report/cronjob": {},
"/enterprise/ops-report/alert": {},
"/enterprise/ops-report/history": {},
"/enterprise/ops-report/settings": {},
}
Expand Down
1 change: 1 addition & 0 deletions core/utils/common/common.go
Original file line number Diff line number Diff line change
Expand Up @@ -230,6 +230,7 @@ func HandleIPList(content string) ([]string, error) {
ipList := strings.Split(content, "\n")
var res []string
for _, ip := range ipList {
ip = strings.TrimSpace(ip)
if ip == "" {
continue
}
Expand Down
5 changes: 5 additions & 0 deletions frontend/src/api/interface/alert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -147,6 +147,11 @@ export namespace Alert {
export interface AlertConfigPageReq {
page: number;
pageSize: number;
excludeTypes?: string[];
}

export interface AlertConfigFilterReq {
excludeTypes?: string[];
}

export interface AlertConfigUpdateReq {
Expand Down
26 changes: 23 additions & 3 deletions frontend/src/api/modules/alert.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,18 @@ import http from '@/api';
import { ResPage } from '@/api/interface';
import { Alert } from '../interface/alert';
import { deepCopy } from '@/utils/misc';
import { GlobalStore } from '@/store';

const alertConfigHiddenTypes = ['sms'];

const resolveAlertConfigExcludeTypes = (excludeTypes: string[] = []) => {
const globalStore = GlobalStore();
const types = new Set(excludeTypes);
if (!(globalStore.isProductPro && !globalStore.isIntl && !globalStore.isEE)) {
alertConfigHiddenTypes.forEach((type) => types.add(type));
}
return Array.from(types);
};
export const SearchAlerts = (req: Alert.AlertSearch, currentNode?: string) => {
return http.post<ResPage<Alert.AlertInfo>>(
`/alert/search`,
Expand Down Expand Up @@ -53,19 +65,27 @@ export const ListCronJob = (req: Alert.CronJobReq) => {
return http.post<Alert.CronJobDTO[]>(`/alert/cronjob/list`, req);
};

export const ListAlertConfigs = (currentNode?: string) => {
export const ListAlertConfigs = (req: Alert.AlertConfigFilterReq = {}, currentNode?: string) => {
const request = {
...req,
excludeTypes: resolveAlertConfigExcludeTypes(req.excludeTypes),
};
return http.post<Alert.AlertConfigInfo[]>(
`/alert/config/info`,
{},
request,
undefined,
currentNode ? { CurrentNode: currentNode } : undefined,
);
};

export const PageAlertConfigs = (req: Alert.AlertConfigPageReq, currentNode?: string) => {
const request = {
...req,
excludeTypes: resolveAlertConfigExcludeTypes(req.excludeTypes),
};
return http.post<ResPage<Alert.AlertConfigInfo>>(
`/alert/config/search`,
req,
request,
undefined,
currentNode ? { CurrentNode: currentNode } : undefined,
);
Expand Down
8 changes: 6 additions & 2 deletions frontend/src/api/modules/container.ts
Original file line number Diff line number Diff line change
Expand Up @@ -89,8 +89,12 @@ export const containerItemStats = (containerID: string, currentNode?: string) =>
currentNode ? { CurrentNode: currentNode } : undefined,
);
};
export const containerListStats = () => {
return http.get<Array<Container.ContainerListStats>>(`/containers/list/stats`);
export const containerListStats = (currentNode?: string) => {
return http.get<Array<Container.ContainerListStats>>(
`/containers/list/stats`,
{},
currentNode ? { headers: { CurrentNode: currentNode } } : {},
);
};
export const containerStats = (id: string) => {
return http.get<Container.ContainerStats>(`/containers/stats/${id}`);
Expand Down
Loading
Loading