Skip to content

Commit

Permalink
🚀 Optimize rule expr process logic
Browse files Browse the repository at this point in the history
  • Loading branch information
Cairry committed Dec 20, 2024
1 parent 405ea29 commit ca3fa9d
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 7 deletions.
14 changes: 7 additions & 7 deletions alert/eval/query.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,6 @@ package eval
import (
"fmt"
"github.com/zeromicro/go-zero/core/logc"
"regexp"
"strconv"
"strings"
"time"
"watchAlert/alert/process"
Expand Down Expand Up @@ -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)
Expand All @@ -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) {
Expand Down
23 changes: 23 additions & 0 deletions pkg/tools/cmd.go
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ import (
"io"
"math/rand"
"regexp"
"strconv"
"strings"
"time"
)

Expand Down Expand Up @@ -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
}

0 comments on commit ca3fa9d

Please sign in to comment.