feat: 监控架构优化 — 模型层 + Prometheus/Zabbix/SNMP pkg + Dockerfile升级Go1.24

整合 /srv/监控架构优化方案 核心代码:

后端模型(4个新文件):
- monitor.go: MonitorTarget(统一监控目标) + MonitorMetric(指标定义) + MetricValue(时序数据) + MetricHistory
- snmp.go: SNMPDevice + SNMPTemplate + OID模板管理
- site.go: SiteTask(拨测任务) + SiteResult(拨测结果)
- alert_v2.go: 增强告警(多条件规则/模板/升级策略/静默)

后端 pkg(3个包):
- pkg/prometheus/client.go (531行): PromQL查询/Range/Labels/Rules
- pkg/zabbix/client.go: Zabbix API (Host/Item/Trigger/History)
- pkg/snmp/collector.go (621行): gosnmp Walk/BulkWalk/自动发现

基础设施:
- Dockerfile: Go 1.21→1.24 (gosnmp依赖)
- Agent安装弹框: SSH一键安装Tab + server上下文
- 服务器列表操作栏: 安装按钮条件显示/隐藏

Handler层因类型不兼容暂时跳过,模型和客户端包已编译通过。
This commit is contained in:
attacker committed 2026-06-18 11:52:10 +00:00
1 parent f3a9e5e8d0
commit 24fa17c2a8
13 files changed
+3427 -98

No files matched your search

+400
View File
@@ -0,0 +1,400 @@
package models
import (
"time"
)
// ============================================
// AlertRuleV2 增强告警规则
// ============================================
// AlertRuleV2Status 告警规则状态
type AlertRuleV2Status string
const (
AlertRuleV2Enabled AlertRuleV2Status = "enabled" // 启用
AlertRuleV2Disabled AlertRuleV2Status = "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" // 95分位
AggFunctionP99 AggFunction = "p99" // 99分位
)
// Operator 比较运算符
type Operator string
const (
OperatorGT Operator = ">" // 大于
OperatorGTE Operator = ">=" // 大于等于
OperatorLT Operator = "<" // 小于
OperatorLTE Operator = "<=" // 小于等于
OperatorEQ Operator = "==" // 等于
OperatorNE Operator = "!=" // 不等于
)
// AlertRuleV2 增强告警规则表
// 支持多条件组合、聚合函数、静默期等高级特性
type AlertRuleV2 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"`
Severity AlertSeverity `gorm:"type:varchar(16);not null;comment:告警级别" json:"severity"`
Status AlertRuleV2Status `gorm:"type:varchar(16);default:'enabled';comment:规则状态" json:"status"`
// 关联目标
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"`
// 触发条件(JSON存储支持多条件)
Conditions string `gorm:"type:text;comment:触发条件JSON数组" json:"conditions,omitempty"`
// 聚合配置
AggWindow int `gorm:"default:300;comment:聚合窗口(秒)" json:"agg_window"`
AggFunction AggFunction `gorm:"type:varchar(16);default:'avg';comment:聚合函数" json:"agg_function"`
// 恢复配置
RecoverCount int `gorm:"default:1;comment:恢复次数(连续N次低于阈值触发恢复)" json:"recover_count"`
RecoverWindow int `gorm:"default:300;comment:恢复检查窗口(秒)" json:"recover_window"`
// 执行配置
Interval int `gorm:"default:60;comment:评估间隔(秒)" json:"interval"`
CheckTimes int `gorm:"default:1;comment:连续触发次数" json:"check_times"`
NotifyMode string `gorm:"type:varchar(16);default:'every';comment:通知模式: every/once/upgrade" json:"notify_mode"`
// 通知渠道
ChannelIDs string `gorm:"type:varchar(256);comment:通知渠道ID列表JSON" json:"channel_ids,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:varchar(512);comment:标签JSON" json:"labels,omitempty"`
Annotations string `gorm:"type:text;comment:注释JSON(用于通知内容模板)" json:"annotations,omitempty"`
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 *time.Time `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
}
// TableName 指定表名
func (AlertRuleV2) TableName() string {
return "alert_rules_v2"
}
// AlertCondition 告警条件定义
type AlertCondition struct {
Metric string `json:"metric"` // 指标名称
Operator Operator `json:"operator"` // 比较运算符
Threshold float64 `json:"threshold"` // 阈值
Unit string `json:"unit"` // 单位
Index string `json:"index"` // 实例索引
LogicOp string `json:"logic_op"` // 逻辑关系: AND/OR
AggFunc AggFunction `json:"agg_func"` // 条件级聚合函数
Window int `json:"window"` // 条件级聚合窗口
}
// AlertConditionGroup 告警条件组
type AlertConditionGroup struct {
Conditions []AlertCondition `json:"conditions"` // 条件列表
LogicOp string `json:"logic_op"` // 组间逻辑: AND/OR
}
// RecoverConfig 告警恢复配置
type RecoverConfig struct {
Count int `json:"count"` // 连续恢复次数
Window int `json:"window"` // 恢复检查窗口(秒)
}
// NotifyMode 通知模式
type NotifyMode string
const (
NotifyModeEvery NotifyMode = "every" // 每次都通知
NotifyModeOnce NotifyMode = "once" // 仅通知一次
NotifyModeUpgrade NotifyMode = "upgrade" // 升级通知
)
// ============================================
// AlertNotifyTemplate 告警通知模板
// ============================================
// 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 *time.Time `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
}
// TableName 指定表名
func (AlertNotifyTemplate) TableName() string {
return "alert_notify_templates"
}
// TemplateVariable 模板变量定义
type TemplateVariable struct {
Name string `json:"name"` // 变量名
Description string `json:"description"` // 描述
Example string `json:"example"` // 示例
}
// DefaultTemplateVariables 默认模板变量
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 告警升级策略
// ============================================
// AlertUpgrade 告警升级策略表
// 定义告警在不同阶段的升级策略
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"`
// 升级规则(JSON存储支持多级升级)
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 *time.Time `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
}
// TableName 指定表名
func (AlertUpgrade) TableName() string {
return "alert_upgrades"
}
// AlertUpgradeRule 告警升级规则
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"` // 重复通知间隔(秒)
}
// AlertUpgradeRecord 告警升级记录
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"`
}
// TableName 指定表名
func (AlertUpgradeRecord) TableName() string {
return "alert_upgrade_records"
}
// ============================================
// AlertSilence 告警静默规则
// ============================================
// AlertSilenceType 静默类型
type AlertSilenceType string
const (
AlertSilenceOneTime AlertSilenceType = "onetime" // 一次性静默
AlertSilenceDaily AlertSilenceType = "daily" // 每日重复
AlertSilenceWeekly AlertSilenceType = "weekly" // 每周重复
)
// AlertSilence 告警静默规则表
// 定义告警静默策略,支持一次性、周期性静默
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 *time.Time `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
}
// TableName 指定表名
func (AlertSilence) TableName() string {
return "alert_silences"
}
// AlertSilenceMatcher 静默匹配条件
type AlertSilenceMatcher struct {
Name string `json:"name"` // 标签名
Value string `json:"value"` // 标签值
IsRegex bool `json:"is_regex"` // 是否正则匹配
}
// AlertSilenceCheckResult 静默检查结果
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"`
}
// ============================================
// AlertEventV2 增强告警事件
// ============================================
// AlertEventV2Status 告警事件状态
type AlertEventV2Status string
const (
AlertEventV2Firing AlertEventV2Status = "firing" // 触发中
AlertEventV2Resolved AlertEventV2Status = "resolved" // 已恢复
AlertEventV2Silenced AlertEventV2Status = "silenced" // 已静默
)
// AlertEventV2 增强告警事件表
// 记录告警触发和恢复的全过程
type AlertEventV2 struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
RuleID uint `gorm:"not null;index:idx_rule_time;comment:规则ID" json:"rule_id"`
TargetID uint `gorm:"not null;index;comment:目标ID" json:"target_id"`
TargetName string `gorm:"type:varchar(128);comment:目标名称" json:"target_name,omitempty"`
TargetIP string `gorm:"type:varchar(64);comment:目标IP" json:"target_ip,omitempty"`
Severity AlertSeverity `gorm:"type:varchar(16);not null;index;comment:告警级别" json:"severity"`
Status AlertEventV2Status `gorm:"type:varchar(16);default:'firing';index;comment:事件状态" json:"status"`
Title string `gorm:"type:varchar(256);not null;comment:告警标题" json:"title"`
Message string `gorm:"type:text;comment:告警详情" json:"message,omitempty"`
// 触发值信息
MetricName string `gorm:"type:varchar(64);comment:指标名称" json:"metric_name,omitempty"`
Value float64 `gorm:"comment:触发值" json:"value,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:varchar(512);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"`
LastNotifyAt *time.Time `gorm:"comment:最近通知时间" json:"last_notify_at,omitempty"`
UpgradeLevel int `gorm:"default:0;comment:当前升级级别" json:"upgrade_level"`
// 确认信息
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"`
}
// TableName 指定表名
func (AlertEventV2) TableName() string {
return "alert_events_v2"
}
// AlertRuleV2CreateRequest 告警规则创建请求
type AlertRuleV2CreateRequest struct {
Name string `json:"name" binding:"required,max=128"`
Description string `json:"description"`
Severity AlertSeverity `json:"severity" binding:"required"`
TargetType string `json:"target_type"`
TargetID uint `json:"target_id"`
TargetTags string `json:"target_tags"`
Conditions []AlertCondition `json:"conditions" binding:"required,min=1"`
AggWindow int `json:"agg_window"`
AggFunction AggFunction `json:"agg_function"`
RecoverCount int `json:"recover_count"`
Interval int `json:"interval"`
CheckTimes int `json:"check_times"`
NotifyMode string `json:"notify_mode"`
ChannelIDs []string `json:"channel_ids"`
TemplateID uint `json:"template_id"`
UpgradeID uint `json:"upgrade_id"`
SilenceID uint `json:"silence_id"`
Labels map[string]string `json:"labels"`
Annotations map[string]string `json:"annotations"`
}
// AlertRuleV2UpdateRequest 告警规则更新请求
type AlertRuleV2UpdateRequest struct {
Name string `json:"name" binding:"max=128"`
Description string `json:"description"`
Severity AlertSeverity `json:"severity"`
Status AlertRuleV2Status `json:"status"`
TargetType string `json:"target_type"`
TargetID uint `json:"target_id"`
TargetTags string `json:"target_tags"`
Conditions []AlertCondition `json:"conditions"`
AggWindow int `json:"agg_window"`
AggFunction AggFunction `json:"agg_function"`
RecoverCount int `json:"recover_count"`
Interval int `json:"interval"`
CheckTimes int `json:"check_times"`
NotifyMode string `json:"notify_mode"`
ChannelIDs []string `json:"channel_ids"`
TemplateID uint `json:"template_id"`
UpgradeID uint `json:"upgrade_id"`
SilenceID uint `json:"silence_id"`
Labels map[string]string `json:"labels"`
Annotations map[string]string `json:"annotations"`
}
+355
View File
@@ -0,0 +1,355 @@
package models
import (
"time"
)
// ============================================
// MonitorTarget 监控目标(主机/中间件/设备/站点)
// ============================================
// TargetType 监控目标类型
type TargetType string
const (
TargetTypeHost TargetType = "host" // 主机
TargetTypeMiddleware TargetType = "middleware" // 中间件
TargetTypeDevice TargetType = "device" // 网络设备
TargetTypeSite TargetType = "site" // 站点
TargetTypeDatabase TargetType = "database" // 数据库
TargetTypeContainer TargetType = "container" // 容器
)
// TargetStatus 监控目标状态
type TargetStatus string
const (
TargetStatusOnline TargetStatus = "online" // 在线
TargetStatusOffline TargetStatus = "offline" // 离线
TargetStatusUnknown TargetStatus = "unknown" // 未知
)
// MonitorTarget 监控目标表
// 存储所有被监控的对象,包括主机、中间件、网络设备、站点等
type MonitorTarget struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
Name string `gorm:"type:varchar(128);not null;index;comment:目标名称" json:"name"`
Type TargetType `gorm:"type:varchar(32);not null;index;comment:目标类型" json:"type"`
Status TargetStatus `gorm:"type:varchar(16);default:'unknown';index;comment:状态" json:"status"`
IP string `gorm:"type:varchar(64);comment:IP地址" json:"ip,omitempty"`
Port int `gorm:"default:0;comment:端口" json:"port,omitempty"`
AgentID string `gorm:"type:varchar(64);index;comment:Agent标识" json:"agent_id,omitempty"`
OS string `gorm:"type:varchar(64);comment:操作系统" json:"os,omitempty"`
OSVersion string `gorm:"type:varchar(64);comment:OS版本" json:"os_version,omitempty"`
Arch string `gorm:"type:varchar(16);comment:系统架构" json:"arch,omitempty"`
Kernel string `gorm:"type:varchar(64);comment:内核版本" json:"kernel,omitempty"`
HostGroupID uint `gorm:"index;comment:主机组ID" json:"host_group_id,omitempty"`
Tags string `gorm:"type:varchar(512);comment:标签JSON" json:"tags,omitempty"`
CollectMode string `gorm:"type:varchar(16);default:'agent';comment:采集模式:agent/snmp/api" json:"collect_mode"`
SNMPConfig string `gorm:"type:text;comment:SNMP配置JSON" json:"snmp_config,omitempty"`
APIConfig string `gorm:"type:text;comment:API配置JSON" json:"api_config,omitempty"`
Address string `gorm:"type:varchar(255);comment:监控地址(IP或域名)" json:"address,omitempty"`
Protocol string `gorm:"type:varchar(32);comment:协议类型(http/https/tcp/udp/icmp/snmp)" json:"protocol,omitempty"`
Timeout int `gorm:"default:30;comment:超时时间(秒)" json:"timeout,omitempty"`
Config string `gorm:"type:text;comment:通用配置JSON" json:"config,omitempty"`
Interval int `gorm:"default:60;comment:采集间隔(秒)" json:"interval"`
Labels string `gorm:"type:varchar(512);comment:标签JSON" json:"labels,omitempty"`
Description string `gorm:"type:varchar(256);comment:描述" json:"description,omitempty"`
CreatedAt time.Time `gorm:"not null;index;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
DeletedAt *time.Time `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
LastSeenAt *time.Time `gorm:"index;comment:最后在线时间" json:"last_seen_at,omitempty"`
// 关联关系
HostGroup *HostGroup `gorm:"foreignKey:HostGroupID" json:"host_group,omitempty"`
}
// TableName 指定表名
func (MonitorTarget) TableName() string {
return "monitor_targets"
}
// ============================================
// MonitorMetric 监控指标定义
// ============================================
// MetricType 指标类型
type MetricType string
const (
MetricTypeGauge MetricType = "gauge" // 瞬时值
MetricTypeCounter MetricType = "counter" // 计数器
MetricTypeSummary MetricType = "summary" // 摘要
)
// DataSourceType 数据来源类型
type DataSourceType string
const (
DataSourceAgent DataSourceType = "agent" // Agent采集
DataSourceSNMP DataSourceType = "snmp" // SNMP采集
DataSourceAPI DataSourceType = "api" // API采集
DataSourcePrometheus DataSourceType = "prometheus" // Prometheus
DataSourceZabbix DataSourceType = "zabbix" // Zabbix
)
// MonitorMetric 监控指标定义表
// 定义系统中所有可采集的监控指标元数据
type MonitorMetric struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
Name string `gorm:"type:varchar(128);not null;uniqueIndex:uk_metric_name;comment:指标名称" json:"name"`
DisplayName string `gorm:"type:varchar(128);not null;comment:显示名称" json:"display_name"`
Description string `gorm:"type:varchar(256);comment:指标描述" json:"description,omitempty"`
MetricType MetricType `gorm:"type:varchar(16);not null;comment:指标类型: gauge/counter/summary" json:"metric_type"`
Unit string `gorm:"type:varchar(32);comment:单位" json:"unit,omitempty"`
DataSource DataSourceType `gorm:"type:varchar(16);not null;comment:数据来源" json:"data_source"`
CollectExpr string `gorm:"type:varchar(256);comment:采集表达式/OID/PromQL" json:"collect_expr,omitempty"`
Interval int `gorm:"default:60;comment:采集间隔(秒)" json:"interval"`
Labels string `gorm:"type:varchar(512);comment:指标标签定义JSON" json:"labels,omitempty"`
ValueType string `gorm:"type:varchar(16);default:'float64';comment:值类型" json:"value_type"`
Category string `gorm:"type:varchar(64);comment:指标分类" json:"category,omitempty"`
IsDefault bool `gorm:"default:true;comment:是否默认启用" json:"is_default"`
IsInternal bool `gorm:"default:false;comment:是否内置指标" json:"is_internal"`
Status int `gorm:"default:1;comment:状态: 1启用 0禁用" json:"status"`
Icon string `gorm:"type:varchar(64);comment:图标" json:"icon,omitempty"`
SortOrder int `gorm:"default:0;comment:排序" json:"sort_order"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
DeletedAt *time.Time `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
}
// TableName 指定表名
func (MonitorMetric) TableName() string {
return "monitor_metrics"
}
// ============================================
// MetricValue 指标值(时序数据)
// ============================================
// MetricValue 指标值表(按时间分区的时序数据)
// 存储采集到的实际指标数值,支持高并发写入和时序查询
type MetricValue struct {
ID uint64 `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
MetricID uint `gorm:"not null;index:idx_metric_time;comment:指标ID" json:"metric_id"`
TargetID uint `gorm:"not null;index:idx_target_metric;comment:目标ID" json:"target_id"`
Instance string `gorm:"type:varchar(128);index;comment:实例标识" json:"instance,omitempty"`
Value float64 `gorm:"not null;comment:指标值" json:"value"`
RawValue string `gorm:"type:text;comment:原始值(用于字符串类型)" json:"raw_value,omitempty"`
Labels string `gorm:"type:varchar(512);index;comment:标签JSON" json:"labels,omitempty"`
Timestamp int64 `gorm:"not null;index:idx_metric_time;comment:时间戳(秒)" json:"timestamp"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
// 关联关系
Metric *MonitorMetric `gorm:"foreignKey:MetricID" json:"metric,omitempty"`
Target *MonitorTarget `gorm:"foreignKey:TargetID" json:"target,omitempty"`
}
// TableName 指定表名
func (MetricValue) TableName() string {
return "metric_values"
}
// MetricHistory 指标历史数据(简化版,供监控查询使用)
type MetricHistory struct {
ID uint64 `gorm:"primaryKey;autoIncrement" json:"id"`
TargetID uint `gorm:"index;not null" json:"target_id"`
MetricName string `gorm:"type:varchar(128);index" json:"metric_name"`
Value float64 `json:"value"`
Timestamp int64 `gorm:"index;not null" json:"timestamp"`
}
func (MetricHistory) TableName() string {
return "metric_histories"
}
// MetricValueQuery 指标值查询参数
type MetricValueQuery struct {
MetricID uint `json:"metric_id" form:"metric_id"`
TargetID uint `json:"target_id" form:"target_id"`
Instance string `json:"instance" form:"instance"`
StartTime int64 `json:"start_time" form:"start_time"`
EndTime int64 `json:"end_time" form:"end_time"`
Step int `json:"step" form:"step"` // 聚合步长(秒)
Limit int `json:"limit" form:"limit"`
}
// MetricAggResult 指标聚合结果
type MetricAggResult struct {
Timestamp int64 `json:"timestamp"`
Value float64 `json:"value"`
Count int64 `json:"count,omitempty"`
Min float64 `json:"min,omitempty"`
Max float64 `json:"max,omitempty"`
Avg float64 `json:"avg,omitempty"`
}
// ============================================
// MetricTag 指标标签
// ============================================
// MetricTag 指标标签定义表
// 定义指标维度标签,用于多维数据分析和过滤
type MetricTag struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
MetricID uint `gorm:"not null;index:idx_metric_tag;comment:指标ID" json:"metric_id"`
TagKey string `gorm:"type:varchar(64);not null;index:idx_metric_tag;comment:标签键" json:"tag_key"`
TagValue string `gorm:"type:varchar(128);index;comment:标签值" json:"tag_value"`
Description string `gorm:"type:varchar(128);comment:描述" json:"description,omitempty"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
}
// TableName 指定表名
func (MetricTag) TableName() string {
return "metric_tags"
}
// ============================================
// MonitorDashboard 监控大屏配置
// ============================================
// DashboardType 大屏类型
type DashboardType string
const (
DashboardTypeSystem DashboardType = "system" // 系统内置
DashboardTypeCustom DashboardType = "custom" // 自定义
DashboardTypeShared DashboardType = "shared" // 共享
)
// MonitorDashboard 监控大屏配置表
// 定义监控大屏的元数据配置
type MonitorDashboard struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
Name string `gorm:"type:varchar(128);not null;comment:大屏名称" json:"name"`
Type DashboardType `gorm:"type:varchar(16);default:'custom';comment:大屏类型" json:"type"`
Description string `gorm:"type:varchar(256);comment:描述" json:"description,omitempty"`
Layout string `gorm:"type:text;comment:布局配置JSON" json:"layout,omitempty"`
Theme string `gorm:"type:varchar(32);default:'dark';comment:主题: dark/light" json:"theme"`
RefreshRate int `gorm:"default:30;comment:自动刷新间隔(秒)" json:"refresh_rate"`
IsDefault bool `gorm:"default:false;comment:是否默认大屏" json:"is_default"`
IsPublic bool `gorm:"default:false;comment:是否公开" json:"is_public"`
CreatedBy uint `gorm:"index;comment:创建人ID" json:"created_by"`
Status int `gorm:"default:1;comment:状态: 1启用 0禁用" json:"status"`
SortOrder int `gorm:"default:0;comment:排序" json:"sort_order"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
DeletedAt *time.Time `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
// 关联关系
Panels []DashboardPanel `gorm:"foreignKey:DashboardID" json:"panels,omitempty"`
}
// TableName 指定表名
func (MonitorDashboard) TableName() string {
return "monitor_dashboards"
}
// ============================================
// DashboardPanel 大屏面板
// ============================================
// PanelType 面板类型
type PanelType string
const (
PanelTypeChart PanelType = "chart" // 图表
PanelTypeGauge PanelType = "gauge" // 仪表盘
PanelTypeCounter PanelType = "counter" // 计数器
PanelTypeTable PanelType = "table" // 表格
PanelTypeStatus PanelType = "status" // 状态
PanelTypeTopology PanelType = "topology" // 拓扑
PanelTypeLog PanelType = "log" // 日志
PanelTypeAlertList PanelType = "alert_list" // 告警列表
PanelTypeHeatmap PanelType = "heatmap" // 热力图
PanelTypeText PanelType = "text" // 文本
)
// ChartType 图表类型
type ChartType string
const (
ChartTypeLine ChartType = "line" // 折线
ChartTypeBar ChartType = "bar" // 柱状
ChartTypeArea ChartType = "area" // 面积
ChartTypePie ChartType = "pie" // 饼图
ChartTypeScatter ChartType = "scatter" // 散点
)
// DashboardPanel 大屏面板配置表
// 定义监控大屏中的各个面板配置
type DashboardPanel struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
DashboardID uint `gorm:"not null;index;comment:大屏ID" json:"dashboard_id"`
Title string `gorm:"type:varchar(128);not null;comment:面板标题" json:"title"`
Description string `gorm:"type:varchar(256);comment:描述" json:"description,omitempty"`
PanelType PanelType `gorm:"type:varchar(16);not null;comment:面板类型" json:"panel_type"`
ChartType ChartType `gorm:"type:varchar(16);comment:图表类型" json:"chart_type,omitempty"`
// 位置布局配置
X int `gorm:"default:0;comment:网格X坐标" json:"x"`
Y int `gorm:"default:0;comment:网格Y坐标" json:"y"`
Width int `gorm:"default:6;comment:宽度(网格列数)" json:"width"`
Height int `gorm:"default:4;comment:高度(网格行数)" json:"height"`
// 数据源配置
DataSource string `gorm:"type:varchar(16);comment:数据源类型" json:"data_source,omitempty"`
MetricID uint `gorm:"comment:关联指标ID" json:"metric_id,omitempty"`
TargetID uint `gorm:"comment:关联目标ID" json:"target_id,omitempty"`
QueryExpr string `gorm:"type:text;comment:查询表达式" json:"query_expr,omitempty"`
QueryConfig string `gorm:"type:text;comment:查询配置JSON" json:"query_config,omitempty"`
// 展示配置
TimeRange string `gorm:"type:varchar(16);default:'1h';comment:时间范围" json:"time_range"`
RefreshRate int `gorm:"default:0;comment:刷新间隔(秒),0表示继承大屏" json:"refresh_rate"`
Thresholds string `gorm:"type:text;comment:阈值配置JSON" json:"thresholds,omitempty"`
Colors string `gorm:"type:text;comment:颜色配置JSON" json:"colors,omitempty"`
Legend string `gorm:"type:varchar(64);comment:图例配置" json:"legend,omitempty"`
Unit string `gorm:"type:varchar(32);comment:显示单位" json:"unit,omitempty"`
Decimals int `gorm:"default:2;comment:小数位数" json:"decimals"`
// 状态
Status int `gorm:"default:1;comment:状态: 1启用 0禁用" json:"status"`
SortOrder int `gorm:"default:0;comment:排序" json:"sort_order"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
}
// TableName 指定表名
func (DashboardPanel) TableName() string {
return "dashboard_panels"
}
// PanelQueryConfig 面板查询配置
type PanelQueryConfig struct {
Metrics []string `json:"metrics"` // 指标名称列表
Targets []uint `json:"targets"` // 目标ID列表
Instances []string `json:"instances"` // 实例列表
Aggregations []string `json:"aggregations"` // 聚合函数
GroupBy []string `json:"group_by"` // 分组标签
Filters map[string]string `json:"filters"` // 过滤条件
Step int `json:"step"` // 步长
LegendFormat string `json:"legend_format"` // 图例格式
}
// ThresholdConfig 阈值配置
type ThresholdConfig struct {
Critical float64 `json:"critical"` // 严重
Warning float64 `json:"warning"` // 警告
Info float64 `json:"info"` // 提示
Unit string `json:"unit"` // 单位
}
// HostGroup 主机组
type HostGroup struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
Name string `gorm:"type:varchar(128);not null;uniqueIndex;comment:组名称" json:"name"`
Description string `gorm:"type:varchar(256);comment:描述" json:"description,omitempty"`
ParentID uint `gorm:"index;comment:父组ID" json:"parent_id,omitempty"`
SortOrder int `gorm:"default:0;comment:排序" json:"sort_order"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
DeletedAt *time.Time `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
}
// TableName 指定表名
func (HostGroup) TableName() string {
return "host_groups"
}
+266
View File
@@ -0,0 +1,266 @@
package models
import (
"time"
)
// ============================================
// SiteTask 拨测任务
// ============================================
// SiteTaskType 拨测任务类型
type SiteTaskType string
const (
SiteTaskTypeHTTP SiteTaskType = "http" // HTTP/HTTPS拨测
SiteTaskTypeTCP SiteTaskType = "tcp" // TCP拨测
SiteTaskTypePing SiteTaskType = "ping" // ICMP Ping拨测
SiteTaskTypeDNS SiteTaskType = "dns" // DNS拨测
SiteTaskTypeUDP SiteTaskType = "udp" // UDP拨测
SiteTaskTypeFTP SiteTaskType = "ftp" // FTP拨测
SiteTaskTypeSMTP SiteTaskType = "smtp" // SMTP拨测
SiteTaskTypeTraceroute SiteTaskType = "traceroute" // 路由追踪
)
// SiteTaskMethod HTTP请求方法
type SiteTaskMethod string
const (
SiteTaskMethodGET SiteTaskMethod = "GET"
SiteTaskMethodPOST SiteTaskMethod = "POST"
SiteTaskMethodHEAD SiteTaskMethod = "HEAD"
)
// SiteTaskStatus 拨测任务状态
type SiteTaskStatus string
const (
SiteTaskStatusRunning SiteTaskStatus = "running" // 运行中
SiteTaskStatusPaused SiteTaskStatus = "paused" // 已暂停
SiteTaskStatusError SiteTaskStatus = "error" // 异常
)
// SiteTask 站点拨测任务表
// 定义对网站、服务等进行主动拨测的任务配置
type SiteTask struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
Name string `gorm:"type:varchar(128);not null;comment:任务名称" json:"name"`
URL string `gorm:"type:varchar(512);not null;comment:拨测URL/地址" json:"url"`
TaskType SiteTaskType `gorm:"type:varchar(16);not null;comment:拨测类型" json:"task_type"`
Method SiteTaskMethod `gorm:"type:varchar(8);default:'GET';comment:HTTP方法" json:"method"`
// HTTP 拨测配置
Headers string `gorm:"type:text;comment:请求头JSON" json:"headers,omitempty"`
Body string `gorm:"type:text;comment:请求体" json:"body,omitempty"`
Timeout int `gorm:"default:10;comment:超时时间(秒)" json:"timeout"`
FollowRedirect bool `gorm:"default:true;comment:是否跟随重定向" json:"follow_redirect"`
VerifySSL bool `gorm:"default:true;comment:是否验证SSL证书" json:"verify_ssl"`
// 期望响应配置
ExpectedStatus int `gorm:"default:200;comment:期望状态码" json:"expected_status"`
ExpectedContent string `gorm:"type:text;comment:期望响应内容(支持正则)" json:"expected_content,omitempty"`
ExpectedLength int `gorm:"default:0;comment:期望响应长度(0表示不检查)" json:"expected_length"`
// 执行配置
Frequency int `gorm:"default:60;comment:拨测频率(秒)" json:"frequency"`
Nodes string `gorm:"type:varchar(256);comment:执行节点列表JSON" json:"nodes,omitempty"`
// DNS 配置
DNSResolver string `gorm:"type:varchar(64);comment:DNS解析服务器" json:"dns_resolver,omitempty"`
// 状态
Status SiteTaskStatus `gorm:"type:varchar(16);default:'running';comment:任务状态" json:"status"`
LastResult string `gorm:"type:varchar(16);comment:最近结果: success/fail" json:"last_result,omitempty"`
LastCheckAt *time.Time `gorm:"comment:最近检查时间" json:"last_check_at,omitempty"`
SuccessRate float64 `gorm:"type:decimal(5,2);default:100.00;comment:成功率(%)" json:"success_rate"`
AvgResponse float64 `gorm:"comment:平均响应时间(ms)" json:"avg_response,omitempty"`
Description string `gorm:"type:varchar(256);comment:描述" json:"description,omitempty"`
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 *time.Time `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
// 关联关系
Results []SiteResult `gorm:"foreignKey:TaskID" json:"results,omitempty"`
Alerts []SiteAlert `gorm:"foreignKey:TaskID" json:"alerts,omitempty"`
}
// TableName 指定表名
func (SiteTask) TableName() string {
return "site_tasks"
}
// ============================================
// SiteResult 拨测结果
// ============================================
// SiteResultStatus 拨测结果状态
type SiteResultStatus string
const (
SiteResultSuccess SiteResultStatus = "success" // 成功
SiteResultFail SiteResultStatus = "fail" // 失败
SiteResultTimeout SiteResultStatus = "timeout" // 超时
)
// SiteResult 拨测结果表
// 存储每次拨测的详细结果数据
type SiteResult struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
TaskID uint `gorm:"not null;index:idx_task_time;comment:任务ID" json:"task_id"`
Status SiteResultStatus `gorm:"type:varchar(16);not null;comment:结果状态" json:"status"`
HTTPStatusCode int `gorm:"comment:HTTP状态码" json:"http_status_code,omitempty"`
// 时间指标
DNSTime float64 `gorm:"comment:DNS解析时间(ms)" json:"dns_time,omitempty"`
ConnectTime float64 `gorm:"comment:连接时间(ms)" json:"connect_time,omitempty"`
TLSTime float64 `gorm:"comment:TLS握手时间(ms)" json:"tls_time,omitempty"`
TTFB float64 `gorm:"comment:首字节时间(ms)" json:"ttfb,omitempty"`
ResponseTime float64 `gorm:"comment:响应时间(ms)" json:"response_time,omitempty"`
TotalTime float64 `gorm:"not null;comment:总耗时(ms)" json:"total_time"`
// 响应信息
ResponseSize int `gorm:"comment:响应大小(bytes)" json:"response_size,omitempty"`
ResponseBody string `gorm:"type:text;comment:响应内容摘要" json:"response_body,omitempty"`
// 网络信息
RemoteIP string `gorm:"type:varchar(64);comment:远端IP" json:"remote_ip,omitempty"`
LocalNode string `gorm:"type:varchar(64);comment:执行节点" json:"local_node,omitempty"`
// 错误信息
ErrorMessage string `gorm:"type:text;comment:错误信息" json:"error_message,omitempty"`
ErrorDetail string `gorm:"type:text;comment:错误详情" json:"error_detail,omitempty"`
// SSL 证书信息
SSLCertExpiry *time.Time `gorm:"comment:SSL证书过期时间" json:"ssl_cert_expiry,omitempty"`
SSLCertIssuer string `gorm:"type:varchar(256);comment:SSL证书签发者" json:"ssl_cert_issuer,omitempty"`
SSLCertSubject string `gorm:"type:varchar(256);comment:SSL证书主题" json:"ssl_cert_subject,omitempty"`
SSLDaysRemaining int `gorm:"comment:SSL证书剩余天数" json:"ssl_days_remaining,omitempty"`
// 检查内容匹配
ContentMatch bool `gorm:"comment:内容匹配结果" json:"content_match,omitempty"`
// 时间戳
CheckedAt time.Time `gorm:"not null;index:idx_task_time;comment:拨测时间" json:"checked_at"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
// 关联关系
Task *SiteTask `gorm:"foreignKey:TaskID" json:"task,omitempty"`
}
// TableName 指定表名
func (SiteResult) TableName() string {
return "site_results"
}
// ============================================
// SiteAlert 拨测告警
// ============================================
// SiteAlertStatus 拨测告警状态
type SiteAlertStatus string
const (
SiteAlertStatusActive SiteAlertStatus = "active" // 活跃
SiteAlertStatusResolved SiteAlertStatus = "resolved" // 已恢复
SiteAlertStatusMuted SiteAlertStatus = "muted" // 已静默
)
// SiteAlertSeverity 拨测告警级别
type SiteAlertSeverity string
const (
SiteAlertCritical SiteAlertSeverity = "critical" // 严重
SiteAlertWarning SiteAlertSeverity = "warning" // 警告
SiteAlertInfo SiteAlertSeverity = "info" // 通知
)
// SiteAlert 拨测告警表
// 记录拨测任务触发的告警事件
type SiteAlert struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
TaskID uint `gorm:"not null;index;comment:任务ID" json:"task_id"`
Severity SiteAlertSeverity `gorm:"type:varchar(16);not null;comment:告警级别" json:"severity"`
Status SiteAlertStatus `gorm:"type:varchar(16);default:'active';index;comment:告警状态" json:"status"`
Title string `gorm:"type:varchar(256);not null;comment:告警标题" json:"title"`
Message string `gorm:"type:text;comment:告警详情" json:"message,omitempty"`
// 触发条件
TriggerType string `gorm:"type:varchar(32);comment:触发类型: timeout/status_error/response_time/ssl_expiry" json:"trigger_type"`
TriggerValue string `gorm:"type:varchar(128);comment:触发值" json:"trigger_value,omitempty"`
Threshold float64 `gorm:"comment:阈值" json:"threshold,omitempty"`
// 响应信息
ResponseTime float64 `gorm:"comment:响应时间(ms)" json:"response_time,omitempty"`
HTTPStatus int `gorm:"comment:HTTP状态码" json:"http_status,omitempty"`
ErrorMessage string `gorm:"type:text;comment:错误信息" json:"error_message,omitempty"`
// 状态变化
StartedAt time.Time `gorm:"not null;comment:告警开始时间" json:"started_at"`
ResolvedAt *time.Time `gorm:"comment:告警恢复时间" json:"resolved_at,omitempty"`
Duration int `gorm:"comment:持续时间(秒)" json:"duration,omitempty"`
NotifyCount int `gorm:"default:0;comment:通知次数" json:"notify_count"`
LastNotifyAt *time.Time `gorm:"comment:最近通知时间" json:"last_notify_at,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"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
// 关联关系
Task *SiteTask `gorm:"foreignKey:TaskID" json:"task,omitempty"`
}
// TableName 指定表名
func (SiteAlert) TableName() string {
return "site_alerts"
}
// SiteTaskCreateRequest 拨测任务创建请求
type SiteTaskCreateRequest struct {
Name string `json:"name" binding:"required,max=128"`
URL string `json:"url" binding:"required,max=512,url"`
TaskType SiteTaskType `json:"task_type" binding:"required"`
Method SiteTaskMethod `json:"method"`
Headers string `json:"headers"`
Body string `json:"body"`
Timeout int `json:"timeout"`
FollowRedirect bool `json:"follow_redirect"`
VerifySSL bool `json:"verify_ssl"`
ExpectedStatus int `json:"expected_status"`
ExpectedContent string `json:"expected_content"`
ExpectedLength int `json:"expected_length"`
Frequency int `json:"frequency"`
Nodes []string `json:"nodes"`
DNSResolver string `json:"dns_resolver"`
Description string `json:"description"`
}
// SiteTaskUpdateRequest 拨测任务更新请求
type SiteTaskUpdateRequest struct {
Name string `json:"name" binding:"max=128"`
URL string `json:"url" binding:"max=512,url"`
Method SiteTaskMethod `json:"method"`
Headers string `json:"headers"`
Body string `json:"body"`
Timeout int `json:"timeout"`
FollowRedirect bool `json:"follow_redirect"`
VerifySSL bool `json:"verify_ssl"`
ExpectedStatus int `json:"expected_status"`
ExpectedContent string `json:"expected_content"`
Frequency int `json:"frequency"`
Nodes []string `json:"nodes"`
Status SiteTaskStatus `json:"status"`
Description string `json:"description"`
}
// SiteTaskStatistics 拨测任务统计
type SiteTaskStatistics struct {
TaskID uint `json:"task_id"`
TotalChecks int64 `json:"total_checks"`
SuccessCount int64 `json:"success_count"`
FailCount int64 `json:"fail_count"`
TimeoutCount int64 `json:"timeout_count"`
SuccessRate float64 `json:"success_rate"`
AvgResponseTime float64 `json:"avg_response_time"`
MinResponseTime float64 `json:"min_response_time"`
MaxResponseTime float64 `json:"max_response_time"`
Last24hUptime float64 `json:"last_24h_uptime"`
Last7dUptime float64 `json:"last_7d_uptime"`
Last30dUptime float64 `json:"last_30d_uptime"`
}
// SiteResultQuery 拨测结果查询参数
type SiteResultQuery struct {
TaskID uint `json:"task_id" form:"task_id"`
Status string `json:"status" form:"status"`
StartTime int64 `json:"start_time" form:"start_time"`
EndTime int64 `json:"end_time" form:"end_time"`
Limit int `json:"limit" form:"limit"`
Offset int `json:"offset" form:"offset"`
}
+252
View File
@@ -0,0 +1,252 @@
package models
import (
"time"
)
// ============================================
// SNMPDevice SNMP设备
// ============================================
// SNMPVersion SNMP协议版本
type SNMPVersion string
const (
SNMPVersionV1 SNMPVersion = "v1" // SNMP v1
SNMPVersionV2c SNMPVersion = "v2c" // SNMP v2c
SNMPVersionV3 SNMPVersion = "v3" // SNMP v3
)
// SNMPAuthProtocol SNMP v3 认证协议
type SNMPAuthProtocol string
const (
SNMPAuthMD5 SNMPAuthProtocol = "MD5" // MD5认证
SNMPAuthSHA SNMPAuthProtocol = "SHA" // SHA认证
SNMPAuthSHAAES SNMPAuthProtocol = "SHA-AES" // SHA+AES
)
// SNMPPrivProtocol SNMP v3 加密协议
type SNMPPrivProtocol string
const (
SNMPPrivDES SNMPPrivProtocol = "DES" // DES加密
SNMPPrivAES SNMPPrivProtocol = "AES" // AES加密
SNMPPrivAES256 SNMPPrivProtocol = "AES256" // AES256加密
)
// SNMPDeviceStatus SNMP设备状态
type SNMPDeviceStatus string
const (
SNMPDeviceOnline SNMPDeviceStatus = "online" // 在线
SNMPDeviceOffline SNMPDeviceStatus = "offline" // 离线
SNMPDeviceError SNMPDeviceStatus = "error" // 错误
)
// SNMPDevice SNMP设备表
// 存储通过SNMP协议监控的网络设备信息
type SNMPDevice struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
Name string `gorm:"type:varchar(128);not null;comment:设备名称" json:"name"`
IP string `gorm:"type:varchar(64);not null;index;comment:设备IP地址" json:"ip"`
Port int `gorm:"default:161;comment:SNMP端口" json:"port"`
Version SNMPVersion `gorm:"type:varchar(4);default:'v2c';comment:SNMP版本: v1/v2c/v3" json:"version"`
Community string `gorm:"type:varchar(64);comment:共同体字符串(v1/v2c)" json:"community,omitempty"`
// SNMP v3 安全参数
Username string `gorm:"type:varchar(64);comment:v3用户名" json:"username,omitempty"`
AuthProtocol SNMPAuthProtocol `gorm:"type:varchar(16);comment:v3认证协议" json:"auth_protocol,omitempty"`
AuthPassword string `gorm:"type:varchar(128);comment:v3认证密码" json:"auth_password,omitempty"`
PrivProtocol SNMPPrivProtocol `gorm:"type:varchar(16);comment:v3加密协议" json:"priv_protocol,omitempty"`
PrivPassword string `gorm:"type:varchar(128);comment:v3加密密码" json:"priv_password,omitempty"`
SecurityLevel string `gorm:"type:varchar(16);comment:v3安全级别: noAuthNoPriv/authNoPriv/authPriv" json:"security_level,omitempty"`
// 设备信息
DeviceType string `gorm:"type:varchar(64);comment:设备类型: switch/router/firewall/printer/server" json:"device_type"`
Vendor string `gorm:"type:varchar(64);comment:厂商" json:"vendor,omitempty"`
Model string `gorm:"type:varchar(64);comment:型号" json:"model,omitempty"`
SysDescr string `gorm:"type:text;comment:系统描述" json:"sys_descr,omitempty"`
SysObjectID string `gorm:"type:varchar(128);comment:系统OID" json:"sys_object_id,omitempty"`
SysUptime uint64 `gorm:"comment:系统运行时间(百分之一秒)" json:"sys_uptime,omitempty"`
SysContact string `gorm:"type:varchar(128);comment:系统联系人" json:"sys_contact,omitempty"`
SysName string `gorm:"type:varchar(128);comment:系统名称" json:"sys_name,omitempty"`
SysLocation string `gorm:"type:varchar(128);comment:系统位置" json:"sys_location,omitempty"`
// 采集配置
TemplateID uint `gorm:"index;comment:OID模板ID" json:"template_id,omitempty"`
CollectInterval int `gorm:"default:300;comment:采集间隔(秒)" json:"collect_interval"`
Timeout int `gorm:"default:10;comment:超时时间(秒)" json:"timeout"`
Retries int `gorm:"default:3;comment:重试次数" json:"retries"`
MaxRepetitions uint32 `gorm:"default:25;comment:BulkWalk最大重复数" json:"max_repetitions"`
// 状态
Status SNMPDeviceStatus `gorm:"type:varchar(16);default:'offline';index;comment:状态" json:"status"`
LastCollectAt *time.Time `gorm:"comment:最后采集时间" json:"last_collect_at,omitempty"`
LastError string `gorm:"type:text;comment:最后错误信息" json:"last_error,omitempty"`
Description string `gorm:"type:varchar(256);comment:描述" json:"description,omitempty"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
DeletedAt *time.Time `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
// 关联关系
Template *SNMPTemplate `gorm:"foreignKey:TemplateID" json:"template,omitempty"`
Metrics []SNMPMetric `gorm:"foreignKey:DeviceID" json:"metrics,omitempty"`
}
// TableName 指定表名
func (SNMPDevice) TableName() string {
return "snmp_devices"
}
// ============================================
// SNMPTemplate OID模板
// ============================================
// SNMPTemplate OID模板表
// 预定义的OID模板,用于快速配置同类设备的监控
type SNMPTemplate 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"`
DeviceType string `gorm:"type:varchar(64);comment:适用设备类型" json:"device_type,omitempty"`
Vendor string `gorm:"type:varchar(64);comment:适用厂商" json:"vendor,omitempty"`
IsDefault bool `gorm:"default:false;comment:是否默认模板" json:"is_default"`
IsSystem bool `gorm:"default:false;comment:是否系统模板" json:"is_system"`
Status int `gorm:"default:1;comment:状态: 1启用 0禁用" json:"status"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
DeletedAt *time.Time `gorm:"index;comment:删除时间" json:"deleted_at,omitempty"`
// 关联关系
OIDs []SNMPTemplateOID `gorm:"foreignKey:TemplateID" json:"oids,omitempty"`
}
// TableName 指定表名
func (SNMPTemplate) TableName() string {
return "snmp_templates"
}
// SNMPTemplateOID OID模板条目表
// 模板中具体的OID定义
type SNMPTemplateOID struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
TemplateID uint `gorm:"not null;index;comment:模板ID" json:"template_id"`
Name string `gorm:"type:varchar(64);not null;comment:OID名称" json:"name"`
OID string `gorm:"type:varchar(256);not null;comment:OID字符串" json:"oid"`
Description string `gorm:"type:varchar(128);comment:描述" json:"description,omitempty"`
DataType string `gorm:"type:varchar(16);comment:数据类型: integer/counter/gauge/string" json:"data_type"`
Unit string `gorm:"type:varchar(32);comment:单位" json:"unit,omitempty"`
IsIndex bool `gorm:"default:false;comment:是否索引OID" json:"is_index"`
Conversion string `gorm:"type:varchar(64);comment:转换公式" json:"conversion,omitempty"`
SortOrder int `gorm:"default:0;comment:排序" json:"sort_order"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
}
// TableName 指定表名
func (SNMPTemplateOID) TableName() string {
return "snmp_template_oids"
}
// ============================================
// SNMPMetric SNMP采集指标
// ============================================
// SNMPMetric SNMP采集指标表
// 存储从SNMP设备采集到的指标数据
type SNMPMetric struct {
ID uint64 `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
DeviceID uint `gorm:"not null;index:idx_device_metric;comment:设备ID" json:"device_id"`
Name string `gorm:"type:varchar(64);not null;index;comment:指标名称" json:"name"`
OID string `gorm:"type:varchar(256);not null;comment:OID" json:"oid"`
Index string `gorm:"type:varchar(128);index;comment:索引值(如接口名)" json:"index,omitempty"`
Value float64 `gorm:"comment:数值" json:"value"`
RawValue string `gorm:"type:text;comment:原始字符串值" json:"raw_value,omitempty"`
Unit string `gorm:"type:varchar(32);comment:单位" json:"unit,omitempty"`
DataType string `gorm:"type:varchar(16);comment:数据类型" json:"data_type"`
Timestamp int64 `gorm:"not null;index:idx_device_metric;comment:采集时间戳" json:"timestamp"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
// 关联关系
Device *SNMPDevice `gorm:"foreignKey:DeviceID" json:"device,omitempty"`
}
// TableName 指定表名
func (SNMPMetric) TableName() string {
return "snmp_metrics"
}
// ============================================
// SNMPInterface 网络接口信息
// ============================================
// SNMPInterface SNMP接口信息表
// 存储网络设备的接口详细信息
type SNMPInterface struct {
ID uint `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
DeviceID uint `gorm:"not null;index;comment:设备ID" json:"device_id"`
IfIndex int `gorm:"not null;comment:接口索引" json:"if_index"`
IfDescr string `gorm:"type:varchar(128);comment:接口描述" json:"if_descr,omitempty"`
IfName string `gorm:"type:varchar(64);comment:接口名称" json:"if_name,omitempty"`
IfAlias string `gorm:"type:varchar(128);comment:接口别名" json:"if_alias,omitempty"`
IfType int `gorm:"comment:接口类型" json:"if_type,omitempty"`
IfSpeed uint64 `gorm:"comment:接口速率(bps)" json:"if_speed,omitempty"`
IfPhysAddr string `gorm:"type:varchar(32);comment:物理地址(MAC)" json:"if_phys_addr,omitempty"`
IfAdminStatus int `gorm:"comment:管理状态: 1=up 2=down 3=testing" json:"if_admin_status,omitempty"`
IfOperStatus int `gorm:"comment:操作状态: 1=up 2=down 3=testing" json:"if_oper_status,omitempty"`
IfHighSpeed uint32 `gorm:"comment:高速接口速率(Mbps)" json:"if_high_speed,omitempty"`
Status int `gorm:"default:1;comment:状态" json:"status"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
UpdatedAt time.Time `gorm:"not null;comment:更新时间" json:"updated_at"`
}
// TableName 指定表名
func (SNMPInterface) TableName() string {
return "snmp_interfaces"
}
// ============================================
// SNMPHistory SNMP采集历史
// ============================================
// SNMPHistory SNMP采集历史表(按时间分区)
// 存储SNMP指标的时序历史数据,用于趋势分析和报表
type SNMPHistory struct {
ID uint64 `gorm:"primaryKey;autoIncrement;comment:主键ID" json:"id"`
DeviceID uint `gorm:"not null;index:idx_snmp_history;comment:设备ID" json:"device_id"`
MetricID uint `gorm:"not null;index;comment:指标定义ID" json:"metric_id"`
Name string `gorm:"type:varchar(64);not null;comment:指标名称" json:"name"`
Index string `gorm:"type:varchar(128);index;comment:索引值" json:"index,omitempty"`
Value float64 `gorm:"not null;comment:采集值" json:"value"`
Unit string `gorm:"type:varchar(32);comment:单位" json:"unit,omitempty"`
Timestamp int64 `gorm:"not null;index:idx_snmp_history;comment:时间戳" json:"timestamp"`
CreatedAt time.Time `gorm:"not null;comment:创建时间" json:"created_at"`
}
// TableName 指定表名
func (SNMPHistory) TableName() string {
return "snmp_history"
}
// SNMPWalkResult SNMP Walk 结果
type SNMPWalkResult struct {
OID string `json:"oid"`
Type string `json:"type"`
Value string `json:"value"`
Index string `json:"index,omitempty"`
Timestamp int64 `json:"timestamp"`
}
// SNMPConnectionConfig SNMP连接配置
type SNMPConnectionConfig struct {
IP string `json:"ip"`
Port int `json:"port"`
Version SNMPVersion `json:"version"`
Community string `json:"community,omitempty"`
Username string `json:"username,omitempty"`
AuthProtocol SNMPAuthProtocol `json:"auth_protocol,omitempty"`
AuthPassword string `json:"auth_password,omitempty"`
PrivProtocol SNMPPrivProtocol `json:"priv_protocol,omitempty"`
PrivPassword string `json:"priv_password,omitempty"`
SecurityLevel string `json:"security_level,omitempty"`
Timeout int `json:"timeout"`
Retries int `json:"retries"`
MaxRepetitions uint32 `json:"max_repetitions"`
}