Files
aiops/backend/model/alert.go
T
2026-07-09 14:16:56 +08:00

508 lines
24 KiB
Go

package model
import (
"time"
"gorm.io/gorm"
)
// ============================================
// AlertRule 告警规则(增强版 — 合并原V2特性)
// ============================================
// AlertRuleStatus 告警规则状态
type AlertRuleStatus string
const (
AlertRuleEnabled AlertRuleStatus = "enabled"
AlertRuleDisabled AlertRuleStatus = "disabled"
)
// AlertSeverity 告警级别
type AlertSeverity string
const (
AlertSeverityCritical AlertSeverity = "critical"
AlertSeverityWarning AlertSeverity = "warning"
AlertSeverityNotice AlertSeverity = "notice"
AlertSeverityInfo AlertSeverity = "info"
)
// AggFunction 聚合函数
type AggFunction string
const (
AggFunctionAvg AggFunction = "avg"
AggFunctionMin AggFunction = "min"
AggFunctionMax AggFunction = "max"
AggFunctionSum AggFunction = "sum"
AggFunctionCount AggFunction = "count"
AggFunctionLast AggFunction = "last"
AggFunctionP95 AggFunction = "p95"
AggFunctionP99 AggFunction = "p99"
)
// Operator 比较运算符
type Operator string
const (
OperatorGT Operator = ">"
OperatorGTE Operator = ">="
OperatorLT Operator = "<"
OperatorLTE Operator = "<="
OperatorEQ Operator = "=="
OperatorNE Operator = "!="
)
// AlertRule 告警规则(增强版)
type AlertRule struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
Name string `gorm:"type:varchar(128);not null;comment:规则名称" json:"name"`
Description string `gorm:"type:varchar(500);comment:规则描述" json:"description,omitempty"`
// ====== 原 V1 兼容字段 ======
Type string `gorm:"type:varchar(32);comment:规则类型: metric/log/event" json:"type,omitempty"`
Source string `gorm:"type:varchar(64);comment:数据源: prometheus/zabbix/custom/loki/elasticsearch" json:"source,omitempty"`
Expression string `gorm:"type:text;comment:PromQL/Zabbix/LogQL/Lucene表达式" json:"expression,omitempty"`
DatasourceID uint `gorm:"index;comment:日志/指标数据源ID" json:"datasource_id,omitempty"`
Severity string `gorm:"type:varchar(32);default:'warning';comment:告警级别" json:"severity"`
Duration int `gorm:"comment:持续时间(秒)" json:"duration,omitempty"`
Enabled bool `gorm:"default:true;comment:是否启用" json:"enabled"`
// ====== V2 增强字段 ======
Status AlertRuleStatus `gorm:"type:varchar(16);default:'enabled';comment:规则状态" json:"status,omitempty"`
TargetType string `gorm:"type:varchar(32);comment:目标类型" json:"target_type,omitempty"`
TargetID uint `gorm:"index;comment:目标ID(0表示全部)" json:"target_id,omitempty"`
TargetTags string `gorm:"type:varchar(256);comment:目标标签筛选" json:"target_tags,omitempty"`
Conditions string `gorm:"type:text;comment:触发条件JSON数组" json:"conditions,omitempty"`
AggWindow int `gorm:"default:300;comment:聚合窗口(秒)" json:"agg_window,omitempty"`
AggFunction string `gorm:"type:varchar(16);default:'avg';comment:聚合函数" json:"agg_function,omitempty"`
RecoverCount int `gorm:"default:1;comment:恢复次数" json:"recover_count,omitempty"`
RecoverWindow int `gorm:"default:300;comment:恢复检查窗口(秒)" json:"recover_window,omitempty"`
Interval int `gorm:"default:60;comment:评估间隔(秒)" json:"interval,omitempty"`
CheckTimes int `gorm:"default:1;comment:连续触发次数" json:"check_times,omitempty"`
NotifyMode string `gorm:"type:varchar(16);default:'every';comment:通知模式: every/once/upgrade" json:"notify_mode,omitempty"`
ChannelIDs string `gorm:"type:varchar(256);comment:通知渠道ID列表JSON" json:"channel_ids,omitempty"`
NotifyChannels string `gorm:"type:text;comment:通知渠道JSON(兼容V1)" json:"notify_channels,omitempty"`
TemplateID uint `gorm:"comment:通知模板ID" json:"template_id,omitempty"`
UpgradeID uint `gorm:"comment:升级策略ID" json:"upgrade_id,omitempty"`
SilenceID uint `gorm:"comment:静默规则ID" json:"silence_id,omitempty"`
Labels string `gorm:"type:text;comment:标签JSON" json:"labels,omitempty"`
Annotations string `gorm:"type:text;comment:注释JSON" json:"annotations,omitempty"`
CreatedBy uint `gorm:"index;comment:创建人ID" json:"created_by,omitempty"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
}
func (AlertRule) TableName() string {
return "monitor_alert_rules"
}
// ============================================
// AlertEvent 告警事件(增强版 — 合并原V2特性)
// ============================================
// AlertEventStatus 告警事件状态
type AlertEventStatus string
const (
AlertEventFiring AlertEventStatus = "firing"
AlertEventResolved AlertEventStatus = "resolved"
AlertEventSilenced AlertEventStatus = "silenced"
)
// AlertEvent 告警事件(增强版)
type AlertEvent struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
RuleID uint `gorm:"not null;index:idx_rule_time;comment:规则ID" json:"rule_id"`
RuleName string `gorm:"type:varchar(128);comment:规则名称" json:"rule_name,omitempty"`
Severity string `gorm:"type:varchar(32);comment:告警级别" json:"severity,omitempty"`
Status string `gorm:"type:varchar(32);default:'firing';comment:事件状态" json:"status"`
// ====== 原V1兼容字段 ======
Target string `gorm:"type:varchar(255);comment:目标标签" json:"target,omitempty"`
Message string `gorm:"type:text;comment:告警详情" json:"message,omitempty"`
Value float64 `gorm:"comment:触发值" json:"value,omitempty"`
// ====== V2增强字段 ======
TargetID uint `gorm:"index;comment:目标ID" json:"target_id,omitempty"`
TargetName string `gorm:"type:varchar(128);comment:目标名称" json:"target_name,omitempty"`
TargetIP string `gorm:"type:varchar(64);comment:目标IP" json:"target_ip,omitempty"`
Title string `gorm:"type:varchar(256);comment:告警标题" json:"title,omitempty"`
MetricName string `gorm:"type:varchar(64);comment:指标名称" json:"metric_name,omitempty"`
Threshold float64 `gorm:"comment:阈值" json:"threshold,omitempty"`
Operator string `gorm:"type:varchar(8);comment:运算符" json:"operator,omitempty"`
Unit string `gorm:"type:varchar(32);comment:单位" json:"unit,omitempty"`
Labels string `gorm:"type:text;comment:标签JSON" json:"labels,omitempty"`
Annotations string `gorm:"type:text;comment:注释JSON" json:"annotations,omitempty"`
StartedAt time.Time `gorm:"not null;index:idx_rule_time;comment:触发时间" json:"started_at"`
ResolvedAt *time.Time `gorm:"comment:恢复时间" json:"resolved_at,omitempty"`
Duration int `gorm:"comment:持续时间(秒)" json:"duration,omitempty"`
LastEvalAt time.Time `gorm:"comment:最后评估时间" json:"last_eval_at,omitempty"`
NotifyCount int `gorm:"default:0;comment:通知次数" json:"notify_count,omitempty"`
LastNotifyAt *time.Time `gorm:"comment:最近通知时间" json:"last_notify_at,omitempty"`
UpgradeLevel int `gorm:"default:0;comment:当前升级级别" json:"upgrade_level,omitempty"`
Acknowledged bool `gorm:"default:false;comment:是否已确认" json:"acknowledged"`
AcknowledgedBy *uint `gorm:"comment:确认人ID" json:"acknowledged_by,omitempty"`
AcknowledgedAt *time.Time `gorm:"comment:确认时间" json:"acknowledged_at,omitempty"`
AckComment string `gorm:"type:varchar(256);comment:确认备注" json:"ack_comment,omitempty"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
// 关联
Rule *AlertRule `json:"rule,omitempty" gorm:"foreignKey:RuleID"`
}
func (AlertEvent) TableName() string {
return "monitor_alert_events"
}
// ============================================
// AlertCondition 告警条件定义
// ============================================
type AlertCondition struct {
Metric string `json:"metric"`
Operator Operator `json:"operator"`
Threshold float64 `json:"threshold"`
Unit string `json:"unit,omitempty"`
Index string `json:"index,omitempty"`
LogicOp string `json:"logic_op,omitempty"`
AggFunc AggFunction `json:"agg_func,omitempty"`
Window int `json:"window,omitempty"`
}
func (AlertCondition) TableName() string {
return "monitor_alert_conditions"
}
type AlertConditionGroup struct {
Conditions []AlertCondition `json:"conditions"`
LogicOp string `json:"logic_op"`
}
// ============================================
// AlertNotifyTemplate 告警通知模板
// ============================================
type AlertNotifyTemplate struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
Name string `gorm:"type:varchar(128);not null;comment:模板名称" json:"name"`
Description string `gorm:"type:varchar(256);comment:描述" json:"description,omitempty"`
ChannelType string `gorm:"type:varchar(32);not null;comment:适用渠道类型: email/sms/webhook/dingtalk/wecom/feishu" json:"channel_type"`
TitleTemplate string `gorm:"type:varchar(256);comment:标题模板" json:"title_template,omitempty"`
BodyTemplate string `gorm:"type:text;comment:正文模板" json:"body_template,omitempty"`
Variables string `gorm:"type:text;comment:可用变量说明JSON" json:"variables,omitempty"`
RecoverTitleTemplate string `gorm:"type:varchar(256);comment:恢复标题模板" json:"recover_title_template,omitempty"`
RecoverBodyTemplate string `gorm:"type:text;comment:恢复正文模板" json:"recover_body_template,omitempty"`
IsDefault bool `gorm:"default:false;comment:是否默认模板" json:"is_default"`
Status int `gorm:"default:1;comment:状态: 1启用 0禁用" json:"status"`
CreatedBy uint `gorm:"index;comment:创建人ID" json:"created_by"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
}
func (AlertNotifyTemplate) TableName() string {
return "monitor_alert_notify_templates"
}
type TemplateVariable struct {
Name string `json:"name"`
Description string `json:"description"`
Example string `json:"example"`
}
var DefaultTemplateVariables = []TemplateVariable{
{Name: "{{.RuleName}}", Description: "规则名称", Example: "CPU使用率告警"},
{Name: "{{.TargetName}}", Description: "目标名称", Example: "WebServer-01"},
{Name: "{{.TargetIP}}", Description: "目标IP", Example: "192.168.1.10"},
{Name: "{{.Severity}}", Description: "告警级别", Example: "critical"},
{Name: "{{.MetricName}}", Description: "指标名称", Example: "cpu_usage"},
{Name: "{{.Value}}", Description: "当前值", Example: "95.2"},
{Name: "{{.Threshold}}", Description: "阈值", Example: "90"},
{Name: "{{.Operator}}", Description: "运算符", Example: ">"},
{Name: "{{.Time}}", Description: "触发时间", Example: "2024-01-15 10:30:00"},
{Name: "{{.Duration}}", Description: "持续时间", Example: "5m"},
{Name: "{{.Description}}", Description: "规则描述", Example: "CPU使用率超过阈值"},
{Name: "{{.URL}}", Description: "详情链接", Example: "https://ezops.io/alerts/123"},
}
// ============================================
// AlertUpgrade + AlertUpgradeRecord 告警升级
// ============================================
type AlertUpgrade struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
Name string `gorm:"type:varchar(128);not null;comment:策略名称" json:"name"`
Description string `gorm:"type:varchar(256);comment:描述" json:"description,omitempty"`
Rules string `gorm:"type:text;comment:升级规则JSON数组" json:"rules,omitempty"`
MaxLevel int `gorm:"default:3;comment:最大升级级别" json:"max_level"`
IsDefault bool `gorm:"default:false;comment:是否默认策略" json:"is_default"`
Status int `gorm:"default:1;comment:状态: 1启用 0禁用" json:"status"`
CreatedBy uint `gorm:"index;comment:创建人ID" json:"created_by"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
}
func (AlertUpgrade) TableName() string {
return "monitor_alert_upgrades"
}
type AlertUpgradeRule struct {
Level int `json:"level"`
Duration int `json:"duration"`
Severity string `json:"severity"`
ChannelIDs []string `json:"channel_ids"`
NotifyUsers []uint `json:"notify_users"`
RepeatInterval int `json:"repeat_interval"`
}
type AlertUpgradeRecord struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
AlertID uint `gorm:"not null;index;comment:告警ID" json:"alert_id"`
RuleID uint `gorm:"not null;comment:规则ID" json:"rule_id"`
FromLevel int `gorm:"comment:原级别" json:"from_level"`
ToLevel int `gorm:"comment:升级后级别" json:"to_level"`
UpgradedAt time.Time `gorm:"not null;comment:升级时间" json:"upgraded_at"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
}
func (AlertUpgradeRecord) TableName() string {
return "monitor_alert_upgrade_records"
}
// ============================================
// AlertSilence 告警静默规则
// ============================================
type AlertSilenceType string
const (
AlertSilenceOneTime AlertSilenceType = "onetime"
AlertSilenceDaily AlertSilenceType = "daily"
AlertSilenceWeekly AlertSilenceType = "weekly"
)
type AlertSilence struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
Name string `gorm:"type:varchar(128);not null;comment:静默规则名称" json:"name"`
Description string `gorm:"type:varchar(256);comment:描述" json:"description,omitempty"`
RuleIDs string `gorm:"type:varchar(256);comment:匹配的告警规则ID列表JSON" json:"rule_ids,omitempty"`
TargetIDs string `gorm:"type:varchar(256);comment:匹配的目标ID列表JSON" json:"target_ids,omitempty"`
Matchers string `gorm:"type:text;comment:标签匹配条件JSON" json:"matchers,omitempty"`
SilenceType AlertSilenceType `gorm:"type:varchar(16);default:'onetime';comment:静默类型" json:"silence_type"`
StartTime time.Time `gorm:"not null;comment:开始时间" json:"start_time"`
EndTime time.Time `gorm:"not null;comment:结束时间" json:"end_time"`
Timezone string `gorm:"type:varchar(32);default:'Asia/Shanghai';comment:时区" json:"timezone"`
Weekdays string `gorm:"type:varchar(64);comment:生效星期(0-6)JSON数组" json:"weekdays,omitempty"`
Status int `gorm:"default:1;comment:状态: 1启用 0禁用" json:"status"`
CreatedBy uint `gorm:"index;comment:创建人ID" json:"created_by"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
}
func (AlertSilence) TableName() string {
return "monitor_alert_silences"
}
type AlertSilenceMatcher struct {
Name string `json:"name"`
Value string `json:"value"`
IsRegex bool `json:"is_regex"`
}
type AlertSilenceCheckResult struct {
IsSilenced bool `json:"is_silenced"`
SilenceID uint `json:"silence_id,omitempty"`
SilenceName string `json:"silence_name,omitempty"`
ExpiresAt *time.Time `json:"expires_at,omitempty"`
}
// NotifyChannel 通知渠道模型
type NotifyChannel struct {
ID uint `gorm:"primarykey" json:"id"`
Name string `gorm:"size:64;not null" json:"name"`
Type string `gorm:"size:32;not null" json:"type"` // email, sms, webhook, dingtalk, wechat
Config string `gorm:"type:text" json:"config"` // JSON
Enabled bool `gorm:"default:true" json:"enabled"`
TestStatus string `gorm:"size:32" json:"test_status"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
// TableName 表名
func (NotifyChannel) TableName() string {
return "monitor_alert_channels"
}
// MetricData 监控指标数据
type MetricData struct {
ID uint `gorm:"primarykey" json:"id"`
ServerID *uint `json:"server_id"`
ClusterID *uint `json:"cluster_id"`
Name string `gorm:"size:64" json:"name"`
Value float64 `json:"value"`
Labels string `gorm:"type:text" json:"labels"`
Timestamp time.Time `json:"timestamp"`
}
// TableName 表名
func (MetricData) TableName() string {
return "monitor_metric_data"
}
// CreateAlertRuleRequest 创建告警规则请求
type CreateAlertRuleRequest struct {
Name string `json:"name" binding:"required"`
Description string `json:"description"`
Type string `json:"type" binding:"required,oneof=metric log event"`
Source string `json:"source" binding:"required"`
Expression string `json:"expression" binding:"required"`
Severity string `json:"severity" binding:"omitempty,oneof=info warning critical"`
Duration int `json:"duration"`
DatasourceID uint `json:"datasource_id"`
Labels string `json:"labels"`
Annotations string `json:"annotations"`
NotifyChannels []string `json:"notify_channels"`
}
// UpdateAlertRuleRequest 更新告警规则请求
type UpdateAlertRuleRequest struct {
Name string `json:"name"`
Description string `json:"description"`
Expression string `json:"expression"`
Severity string `json:"severity" binding:"omitempty,oneof=info warning critical"`
Duration int `json:"duration"`
DatasourceID uint `json:"datasource_id"`
Enabled *bool `json:"enabled"`
Labels string `json:"labels"`
Annotations string `json:"annotations"`
NotifyChannels []string `json:"notify_channels"`
}
// AlertStats 告警统计
type AlertStats struct {
Total int64 `json:"total"`
Firing int64 `json:"firing"`
Resolved int64 `json:"resolved"`
Critical int64 `json:"critical"`
Warning int64 `json:"warning"`
Info int64 `json:"info"`
TodayCount int64 `json:"today_count"`
WeekCount int64 `json:"week_count"`
}
// AcknowledgeAlertRequest 确认告警请求
type AcknowledgeAlertRequest struct {
Message string `json:"message"`
}
// ============================================
// AlertContact 报警联系人
// ============================================
type AlertContact struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
Name string `gorm:"type:varchar(128);not null;comment:联系人姓名" json:"name"`
Phone string `gorm:"type:varchar(32);comment:手机号" json:"phone,omitempty"`
Email string `gorm:"type:varchar(128);comment:邮箱" json:"email,omitempty"`
ChannelType string `gorm:"type:varchar(32);default:'feishu';comment:渠道类型: feishu/dingtalk/wechat/webhook" json:"channel_type,omitempty"`
WebhookURL string `gorm:"type:varchar(512);comment:Webhook地址" json:"webhook_url,omitempty"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
}
func (AlertContact) TableName() string {
return "monitor_alert_contacts"
}
// ============================================
// AlertContactGroup 报警联系组
// ============================================
type AlertContactGroup struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
GroupName string `gorm:"type:varchar(128);not null;comment:组名称" json:"group_name"`
Notes string `gorm:"type:varchar(500);comment:备注" json:"notes,omitempty"`
ContactIDs string `gorm:"type:text;comment:联系人ID列表JSON" json:"contact_ids,omitempty"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
DeletedAt gorm.DeletedAt `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
}
func (AlertContactGroup) TableName() string {
return "monitor_alert_contact_groups"
}
// CreateContactRequest 创建联系人请求
type CreateContactRequest struct {
Name string `json:"name" binding:"required"`
Phone string `json:"phone,omitempty"`
Email string `json:"email,omitempty"`
ChannelType string `json:"channel_type" binding:"required,oneof=feishu dingtalk wechat webhook"`
WebhookURL string `json:"webhook_url" binding:"required"`
}
// UpdateContactRequest 更新联系人请求
type UpdateContactRequest struct {
Name string `json:"name,omitempty"`
Phone string `json:"phone,omitempty"`
Email string `json:"email,omitempty"`
ChannelType string `json:"channel_type,omitempty" binding:"omitempty,oneof=feishu dingtalk wechat webhook"`
WebhookURL string `json:"webhook_url,omitempty"`
}
// CreateContactGroupRequest 创建联系组请求
type CreateContactGroupRequest struct {
GroupName string `json:"group_name" binding:"required"`
Notes string `json:"notes,omitempty"`
ContactIDs []uint `json:"contact_ids"`
}
// UpdateContactGroupRequest 更新联系组请求
type UpdateContactGroupRequest struct {
GroupName string `json:"group_name,omitempty"`
Notes string `json:"notes,omitempty"`
ContactIDs []uint `json:"contact_ids,omitempty"`
}
// CreateNotifyChannelRequest 创建通知渠道请求
type CreateNotifyChannelRequest struct {
Name string `json:"name" binding:"required"`
Type string `json:"type" binding:"required,oneof=email sms webhook dingtalk wechat feishu"`
Config string `json:"config"`
}
// UpdateNotifyChannelRequest 更新通知渠道请求
type UpdateNotifyChannelRequest struct {
Name string `json:"name"`
Type string `json:"type" binding:"omitempty,oneof=email sms webhook dingtalk wechat feishu"`
Config string `json:"config"`
Enabled *bool `json:"enabled"`
}
// FeishuWebhookConfig 飞书 Webhook 配置
type FeishuWebhookConfig struct {
URL string `json:"url"` // 飞书机器人 webhook 地址
Secret string `json:"secret"` // 可选:签名密钥
}
// FeishuCardMessage 飞书卡片消息
type FeishuCardMessage struct {
MsgType string `json:"msg_type"`
Content FeishuCardContent `json:"content"`
}
type FeishuCardContent struct {
Title string `json:"title"`
Content [][]FeishuCardElement `json:"content"`
}
// FeishuCardElement 飞书卡片元素
type FeishuCardElement struct {
Tag string `json:"tag"`
Text string `json:"text,omitempty"`
}