diff --git a/alert/eval/query.go b/alert/eval/query.go index 8bd85ca..d098d0f 100644 --- a/alert/eval/query.go +++ b/alert/eval/query.go @@ -3,8 +3,6 @@ package eval import ( "fmt" "github.com/zeromicro/go-zero/core/logc" - "regexp" - "strconv" "strings" "time" "watchAlert/alert/process" @@ -64,9 +62,11 @@ func metrics(ctx *ctx.Context, datasourceId, datasourceType string, rule models. for _, v := range resQuery { for _, ruleExpr := range rule.PrometheusConfig.Rules { - re := regexp.MustCompile(`([^\d]+)(\d+)`) - matches := re.FindStringSubmatch(ruleExpr.Expr) - t, _ := strconv.ParseFloat(matches[2], 64) + operator, value, err := tools.ProcessRuleExpr(ruleExpr.Expr) + if err != nil { + logc.Errorf(ctx.Ctx, err.Error()) + continue + } event := func() models.AlertCurEvent { event := process.BuildEvent(rule) @@ -90,9 +90,9 @@ func metrics(ctx *ctx.Context, datasourceId, datasourceType string, rule models. } option := models.EvalCondition{ - Operator: matches[1], + Operator: operator, QueryValue: v.Value, - ExpectedValue: t, + ExpectedValue: value, } if process.EvalCondition(option) { diff --git a/pkg/tools/cmd.go b/pkg/tools/cmd.go index d01566d..9c7bb5b 100644 --- a/pkg/tools/cmd.go +++ b/pkg/tools/cmd.go @@ -10,6 +10,8 @@ import ( "io" "math/rand" "regexp" + "strconv" + "strings" "time" ) @@ -150,3 +152,24 @@ func IsEndOfWeek(dateStr string) bool { } return date.Weekday() == time.Sunday } + +func ProcessRuleExpr(ruleExpr string) (string, float64, error) { + // 去除空格 + trimmedExpr := strings.ReplaceAll(ruleExpr, " ", "") + + // 正则表达式匹配 + re := regexp.MustCompile(`([^\d]+)(\d+)`) + matches := re.FindStringSubmatch(trimmedExpr) + if len(matches) < 3 { + return "", 0, fmt.Errorf("无效的表达式: %s", ruleExpr) + } + + // 提取操作符和数值 + operator := matches[1] + value, err := strconv.ParseFloat(matches[2], 64) + if err != nil { + return "", 0, fmt.Errorf("无法解析数值: %s", matches[2]) + } + + return operator, value, nil +}