nezha/model/alertrule.go

78 lines
1.4 KiB
Go
Raw Normal View History

package model
import (
"encoding/json"
"gorm.io/gorm"
)
type AlertRule struct {
Common
Name string
RulesRaw string
Enable *bool
2021-01-16 01:11:51 -05:00
Rules []Rule `gorm:"-" json:"-"`
}
func (r *AlertRule) BeforeSave(tx *gorm.DB) error {
data, err := json.Marshal(r.Rules)
if err != nil {
return err
}
r.RulesRaw = string(data)
return nil
}
func (r *AlertRule) AfterFind(tx *gorm.DB) error {
2020-12-19 23:18:27 -05:00
return json.Unmarshal([]byte(r.RulesRaw), &r.Rules)
}
func (r *AlertRule) Snapshot(server *Server, db *gorm.DB) []interface{} {
2020-12-19 23:18:27 -05:00
var point []interface{}
for i := 0; i < len(r.Rules); i++ {
point = append(point, r.Rules[i].Snapshot(server, db))
2020-12-19 23:18:27 -05:00
}
return point
}
func (r *AlertRule) Check(points [][]interface{}) (int, bool) {
2020-12-19 23:18:27 -05:00
var max int
2020-12-21 09:51:23 -05:00
var count int
2020-12-19 23:18:27 -05:00
for i := 0; i < len(r.Rules); i++ {
if r.Rules[i].IsTransferDurationRule() {
if max < 1 {
max = 1
}
// 循环区间流量报警
for j := len(points[i]) - 1; j >= 0; j-- {
if points[i][j] != nil {
count++
break
}
}
} else {
// 常规报警
total := 0.0
fail := 0.0
num := int(r.Rules[i].Duration)
if num > max {
max = num
}
if len(points) < num {
continue
}
for j := len(points) - 1; j >= 0 && len(points)-num <= j; j-- {
total++
if points[j][i] != nil {
fail++
}
}
if fail/total > 0.7 {
count++
break
2020-12-19 23:18:27 -05:00
}
}
2020-12-21 09:51:23 -05:00
}
return max, count != len(r.Rules)
}