chore: 统一本地服务器与远程仓库源码
- 合并 main 与 master 历史并以服务器结构为基线 - 保留迁移、数据保留、AWS 账单与部署安全能力 - 建立 SDD 规格和 CI 验证闭环
This commit is contained in:
commit
fd60361d93
460 files changed
+37492
-23871
No files matched your search
@@ -2,7 +2,6 @@ package database
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"log"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
@@ -70,10 +69,9 @@ func New(cfg config.DatabaseConfig) (*gorm.DB, error) {
|
||||
return db, nil
|
||||
}
|
||||
|
||||
// AutoMigrate 自动迁移数据库表
|
||||
// 逐表迁移:单张表的迁移错误(如索引名冲突)不会阻塞其他表,
|
||||
// 避免 GORM + MySQL 8.0 的 "Can't DROP" 索引问题导致整个启动失败
|
||||
func AutoMigrate(db *gorm.DB) error {
|
||||
// BootstrapSchema 为空数据库创建初始基线结构。
|
||||
// 该函数只能由显式的 `aiops migrate up` 调用,服务启动路径禁止调用。 // Logan.Li
|
||||
func BootstrapSchema(db *gorm.DB) error {
|
||||
allModels := []interface{}{
|
||||
&model.User{},
|
||||
&model.Role{},
|
||||
@@ -96,9 +94,9 @@ func AutoMigrate(db *gorm.DB) error {
|
||||
&model.AlertNotifyPolicy{}, // 告警集合通知策略 // Logan.Li
|
||||
&model.AlertNotifySettings{}, // 告警消息模版 // Logan.Li
|
||||
&model.NotifyChannel{},
|
||||
&model.MetricData{},
|
||||
&model.Pipeline{},
|
||||
&model.PipelineRun{},
|
||||
&model.JenkinsConfig{},
|
||||
&model.BuildNode{},
|
||||
&model.AppRelease{},
|
||||
&model.CronJob{},
|
||||
@@ -116,16 +114,16 @@ func AutoMigrate(db *gorm.DB) error {
|
||||
&model.LDAPConfig{},
|
||||
&model.ResourceModel{},
|
||||
&model.CloudBilling{},
|
||||
&model.BillingSettings{}, // 云账单换算设置 // Logan.Li
|
||||
&model.BillingAlertRule{},
|
||||
&model.AgentReport{},
|
||||
&model.AgentTask{},
|
||||
&model.AgentRule{},
|
||||
&model.AgentAlert{},
|
||||
&model.AgentPortPolicy{}, // Agent 端口策略 // Logan.Li
|
||||
&model.AnsiblePlaybook{},
|
||||
&model.AnsibleJob{},
|
||||
&model.AnsibleInventory{},
|
||||
&model.LogSource{},
|
||||
&model.LogEntry{},
|
||||
&model.TopologyLayout{}, // 拓扑布局保存 // Logan.Li
|
||||
&model.TerminalSession{}, // 终端会话录制(终端审计) // Logan.Li
|
||||
&model.RDPSession{}, // RDP 图形会话审计 // Logan.Li
|
||||
@@ -136,7 +134,6 @@ func AutoMigrate(db *gorm.DB) error {
|
||||
&model.MetricsAggregate{}, // 指标时序聚合(Redis → MySQL)// Logan.Li
|
||||
&model.MonitorTarget{}, // 监控目标(主机/中间件/设备/站点) // Logan.Li
|
||||
&model.MonitorMetric{}, // 监控指标定义 // Logan.Li
|
||||
&model.MetricValue{}, // 指标当前值 // Logan.Li
|
||||
&model.MetricHistory{}, // 指标历史时序 // Logan.Li
|
||||
&model.HostGroup{}, // 主机组 // Logan.Li
|
||||
&model.SNMPDevice{}, // SNMP设备 // Logan.Li
|
||||
@@ -152,8 +149,6 @@ func AutoMigrate(db *gorm.DB) error {
|
||||
&model.ZabbixDataSource{}, // Zabbix 数据源配置 // Logan.Li
|
||||
&model.LogDataSource{}, // Loki / ES 日志数据源 // Logan.Li
|
||||
&model.Credential{}, // 凭据管理(SSH密钥/API Token) // Logan.Li
|
||||
&model.PipelineRepo{}, // Git 仓库认证 // Logan.Li
|
||||
&model.PipelineRegistry{}, // 镜像仓库认证 // Logan.Li
|
||||
&model.DeployEnvironment{}, // 发布环境分组 // Logan.Li
|
||||
&model.DeployPipelineMember{}, // 流水线成员 // Logan.Li
|
||||
&model.DeployUserGroup{}, // 用户组 // Logan.Li
|
||||
@@ -172,94 +167,196 @@ func AutoMigrate(db *gorm.DB) error {
|
||||
&model.HealthProbe{}, // 健康探针配置 // Logan.Li
|
||||
&model.ApprovalWorkflow{}, // 审批流程定义 // Logan.Li
|
||||
&model.ApprovalWorkflowStep{}, // 审批流程步骤 // Logan.Li
|
||||
&model.AgentCLISession{}, // Agent CLI 任务会话 // Logan.Li
|
||||
&model.AgentCLIMessage{}, // Agent CLI 推理消息 // Logan.Li
|
||||
&model.CustomDashboard{}, // 自定义监控仪表盘 // Logan.Li
|
||||
&model.AIRun{}, // AI 任务统一运行记录 // Logan.Li
|
||||
&model.AIRunMessage{}, // AI 任务回放消息 // Logan.Li
|
||||
&model.AIRunSpan{}, // AI 工具/LLM/Guardrail Trace Span // Logan.Li
|
||||
&model.AICapability{}, // AI 内置/MCP/技能能力注册 // Logan.Li
|
||||
&model.AICapabilityPolicy{}, // AI 工具能力策略 // Logan.Li
|
||||
&model.OpsSession{}, // 人机统一执行会话 // Logan.Li
|
||||
&model.OpsCommand{}, // 人机统一命令审计 // Logan.Li
|
||||
&model.TraceDataSource{}, // 链路追踪数据源 Jaeger/Tempo // Logan.Li
|
||||
}
|
||||
|
||||
var lastErr error
|
||||
for _, m := range allModels {
|
||||
if err := db.AutoMigrate(m); err != nil {
|
||||
// 记录但不阻塞 — 表和大多数索引已正常创建,
|
||||
// 个别索引 DROP 冲突不影响核心功能
|
||||
lastErr = err
|
||||
return fmt.Errorf("创建初始基线表失败 (%T): %w", m, err)
|
||||
}
|
||||
}
|
||||
// 全部跑完后返回 nil:单张表的索引错误不应阻断服务启动
|
||||
_ = lastErr
|
||||
applySchemaPatches(db)
|
||||
return nil
|
||||
}
|
||||
|
||||
// applySchemaPatches 补全 AutoMigrate 可能遗漏的列(MySQL 索引冲突时 User 表不会自动加列)// Logan.Li
|
||||
func applySchemaPatches(db *gorm.DB) {
|
||||
// ApplyLegacySchemaPatches 为历史数据库执行一次兼容性补丁。
|
||||
// 调用方必须通过版本化迁移显式执行,任一失败都会中止,避免隐式部分成功。 // Logan.Li
|
||||
func ApplyLegacySchemaPatches(db *gorm.DB) error {
|
||||
m := db.Migrator()
|
||||
if !m.HasTable(&model.User{}) {
|
||||
return
|
||||
return fmt.Errorf("缺少 iam_users,不能执行历史结构补丁")
|
||||
}
|
||||
patchUserColumn := func(field string, col string) {
|
||||
patchUserColumn := func(field string, col string) error {
|
||||
if !m.HasColumn(&model.User{}, col) {
|
||||
if err := m.AddColumn(&model.User{}, field); err != nil {
|
||||
log.Printf("[DB] 补列 %s 失败: %v", col, err)
|
||||
return fmt.Errorf("补充 iam_users.%s 失败: %w", col, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, column := range [][2]string{
|
||||
{"ApiAccessKeyExpiresAt", "api_access_key_expires_at"},
|
||||
{"ApiAccessKeyID", "api_access_key_id"},
|
||||
{"ApiAccessKeyDescription", "api_access_key_description"},
|
||||
{"ApiAccessKeyDurationMonths", "api_access_key_duration_months"},
|
||||
{"ApiAccessKeyLastUsedAt", "api_access_key_last_used_at"},
|
||||
} {
|
||||
if err := patchUserColumn(column[0], column[1]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
patchUserColumn("ApiAccessKeyExpiresAt", "api_access_key_expires_at")
|
||||
patchUserColumn("ApiAccessKeyID", "api_access_key_id")
|
||||
patchUserColumn("ApiAccessKeyDescription", "api_access_key_description")
|
||||
patchUserColumn("ApiAccessKeyDurationMonths", "api_access_key_duration_months")
|
||||
patchUserColumn("ApiAccessKeyLastUsedAt", "api_access_key_last_used_at")
|
||||
|
||||
// 补全日志数据源表可能缺失的列(旧表仅有基础字段)// Logan.Li
|
||||
patchLogDSColumn := func(field string, col string) {
|
||||
patchLogDSColumn := func(field string, col string) error {
|
||||
if !m.HasColumn(&model.LogDataSource{}, col) {
|
||||
if err := m.AddColumn(&model.LogDataSource{}, field); err != nil {
|
||||
log.Printf("[DB] 补列 monitor_log_datasources.%s 失败: %v", col, err)
|
||||
return fmt.Errorf("补充 monitor_log_datasources.%s 失败: %w", col, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, column := range [][2]string{{"AuthType", "auth_type"}, {"Token", "token"}, {"Headers", "headers"}} {
|
||||
if err := patchLogDSColumn(column[0], column[1]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
patchLogDSColumn("AuthType", "auth_type")
|
||||
patchLogDSColumn("Token", "token")
|
||||
patchLogDSColumn("Headers", "headers")
|
||||
|
||||
// 日志权限关联表:AutoMigrate 在 MySQL 索引冲突时可能只创建策略表未创建用户关联表 // Logan.Li
|
||||
ensureTable := func(tbl interface{}, name string) {
|
||||
ensureTable := func(tbl interface{}, name string) error {
|
||||
if !m.HasTable(tbl) {
|
||||
if err := db.AutoMigrate(tbl); err != nil {
|
||||
log.Printf("[DB] 补表 %s 失败: %v", name, err)
|
||||
return fmt.Errorf("创建 %s 失败: %w", name, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := ensureTable(&model.LogScopeRole{}, "iam_log_scope_roles"); err != nil {
|
||||
return err
|
||||
}
|
||||
if !m.HasTable("iam_user_log_scope_roles") {
|
||||
if err := createUserLogScopeRolesTable(db); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
ensureTable(&model.LogScopeRole{}, "monitor_log_scope_roles")
|
||||
ensureTable(&model.UserLogScopeRole{}, "monitor_user_log_scope_roles")
|
||||
|
||||
// LDAP 目录类型列(openldap | ad) // Logan.Li
|
||||
if m.HasTable(&model.LDAPConfig{}) && !m.HasColumn(&model.LDAPConfig{}, "server_type") {
|
||||
if err := m.AddColumn(&model.LDAPConfig{}, "ServerType"); err != nil {
|
||||
log.Printf("[DB] 补列 iam_ldap_configs.server_type 失败: %v", err)
|
||||
return fmt.Errorf("补充 iam_ldap_configs.server_type 失败: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 服务器 RDP/协议字段(旧库 AutoMigrate 可能未加列)// Logan.Li
|
||||
patchServerColumn := func(field string, col string) {
|
||||
patchServerColumn := func(field string, col string) error {
|
||||
if !m.HasColumn(&model.Server{}, col) {
|
||||
if err := m.AddColumn(&model.Server{}, field); err != nil {
|
||||
log.Printf("[DB] 补列 asset_servers.%s 失败: %v", col, err)
|
||||
return fmt.Errorf("补充 asset_servers.%s 失败: %w", col, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, column := range [][2]string{
|
||||
{"OSType", "os_type"}, {"Protocol", "protocol"}, {"RDPPort", "rdp_port"},
|
||||
{"Alias", "alias"}, {"CloudInstanceName", "cloud_instance_name"}, {"CloudInstanceID", "cloud_instance_id"},
|
||||
} {
|
||||
if err := patchServerColumn(column[0], column[1]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
patchServerColumn("OSType", "os_type")
|
||||
patchServerColumn("Protocol", "protocol")
|
||||
patchServerColumn("RDPPort", "rdp_port")
|
||||
|
||||
// 将历史仅填 os=windows 的记录补齐协议字段 // Logan.Li
|
||||
if m.HasColumn(&model.Server{}, "os_type") && m.HasColumn(&model.Server{}, "protocol") {
|
||||
_ = db.Exec(`
|
||||
if err := db.Exec(`
|
||||
UPDATE asset_servers
|
||||
SET os_type = 'windows', protocol = 'rdp', rdp_port = IF(rdp_port IS NULL OR rdp_port = 0, 3389, rdp_port)
|
||||
SET os_type = 'windows', protocol = 'rdp', rdp_port = CASE WHEN rdp_port IS NULL OR rdp_port = 0 THEN 3389 ELSE rdp_port END
|
||||
WHERE (os_type IS NULL OR os_type = '' OR protocol IS NULL OR protocol = '')
|
||||
AND LOWER(os) LIKE '%windows%'
|
||||
`).Error
|
||||
`).Error; err != nil {
|
||||
return fmt.Errorf("补全 Windows 服务器协议字段失败: %w", err)
|
||||
}
|
||||
}
|
||||
|
||||
// 兼容早期 GORM 将 CIProvider 误建为 c_iprovider 的流水线表。// Logan.Li
|
||||
if m.HasTable(&model.Pipeline{}) {
|
||||
if !m.HasColumn(&model.Pipeline{}, "ci_provider") {
|
||||
if err := m.AddColumn(&model.Pipeline{}, "CIProvider"); err != nil {
|
||||
return fmt.Errorf("补充 deploy_pipelines.ci_provider 失败: %w", err)
|
||||
}
|
||||
}
|
||||
if m.HasColumn(&model.Pipeline{}, "ci_provider") && m.HasColumn(&model.Pipeline{}, "c_iprovider") {
|
||||
if err := db.Exec(`
|
||||
UPDATE deploy_pipelines
|
||||
SET ci_provider = COALESCE(NULLIF(ci_provider, ''), NULLIF(c_iprovider, ''), 'aiops')
|
||||
WHERE ci_provider IS NULL OR ci_provider = ''
|
||||
`).Error; err != nil {
|
||||
return fmt.Errorf("迁移 deploy_pipelines.ci_provider 失败: %w", err)
|
||||
}
|
||||
}
|
||||
patchPipelineColumn := func(field string, col string) error {
|
||||
if !m.HasColumn(&model.Pipeline{}, col) {
|
||||
if err := m.AddColumn(&model.Pipeline{}, field); err != nil {
|
||||
return fmt.Errorf("补充 deploy_pipelines.%s 失败: %w", col, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
for _, column := range [][2]string{{"JenkinsView", "jenkins_view"}, {"JenkinsViewURL", "jenkins_view_url"}, {"JenkinsViews", "jenkins_views"}, {"JenkinsParams", "jenkins_params"}, {"JenkinsSteps", "jenkins_steps"}} {
|
||||
if err := patchPipelineColumn(column[0], column[1]); err != nil {
|
||||
return err
|
||||
}
|
||||
}
|
||||
}
|
||||
if m.HasTable(&model.JenkinsConfig{}) {
|
||||
patchJenkinsColumn := func(field string, col string) error {
|
||||
if !m.HasColumn(&model.JenkinsConfig{}, col) {
|
||||
if err := m.AddColumn(&model.JenkinsConfig{}, field); err != nil {
|
||||
return fmt.Errorf("补充 deploy_jenkins_configs.%s 失败: %w", col, err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
if err := patchJenkinsColumn("RefMode", "ref_mode"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := patchJenkinsColumn("RefParam", "ref_param"); err != nil {
|
||||
return err
|
||||
}
|
||||
if err := db.Exec("UPDATE deploy_jenkins_configs SET ref_mode = 'both' WHERE ref_mode IS NULL OR ref_mode = ''").Error; err != nil {
|
||||
return fmt.Errorf("补全 deploy_jenkins_configs.ref_mode 失败: %w", err)
|
||||
}
|
||||
if err := db.Exec("UPDATE deploy_jenkins_configs SET ref_param = 'SELECT' WHERE ref_param IS NULL OR ref_param = ''").Error; err != nil {
|
||||
return fmt.Errorf("补全 deploy_jenkins_configs.ref_param 失败: %w", err)
|
||||
}
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func createUserLogScopeRolesTable(db *gorm.DB) error {
|
||||
sql := `CREATE TABLE IF NOT EXISTS iam_user_log_scope_roles (
|
||||
id BIGINT UNSIGNED AUTO_INCREMENT PRIMARY KEY,
|
||||
user_id BIGINT UNSIGNED NOT NULL,
|
||||
log_scope_role_id BIGINT UNSIGNED NOT NULL,
|
||||
created_at DATETIME(3) NULL,
|
||||
UNIQUE KEY idx_iam_user_log_scope_role (user_id, log_scope_role_id),
|
||||
KEY idx_iam_user_log_scope_role_role (log_scope_role_id)
|
||||
)`
|
||||
if db.Dialector.Name() == "sqlite" {
|
||||
sql = `CREATE TABLE IF NOT EXISTS iam_user_log_scope_roles (
|
||||
id INTEGER PRIMARY KEY AUTOINCREMENT,
|
||||
user_id INTEGER NOT NULL,
|
||||
log_scope_role_id INTEGER NOT NULL,
|
||||
created_at DATETIME,
|
||||
UNIQUE(user_id, log_scope_role_id)
|
||||
)`
|
||||
}
|
||||
if err := db.Exec(sql).Error; err != nil {
|
||||
return fmt.Errorf("创建 iam_user_log_scope_roles 失败: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -51,13 +51,13 @@ func CleanupSNMPMetricsSQL(driver string, retentionDays int) string {
|
||||
switch driver {
|
||||
case "sqlite":
|
||||
return fmt.Sprintf(
|
||||
"DELETE FROM ops_snmp_metrics WHERE timestamp < CAST(strftime('%%s', 'now', '-%d days') AS INTEGER)",
|
||||
"DELETE FROM monitor_snmp_samples WHERE timestamp < CAST(strftime('%%s', 'now', '-%d days') AS INTEGER)",
|
||||
retentionDays,
|
||||
)
|
||||
default:
|
||||
return fmt.Sprintf(
|
||||
"DELETE FROM ops_snmp_metrics WHERE timestamp < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL %d DAY))",
|
||||
"DELETE FROM monitor_snmp_samples WHERE timestamp < UNIX_TIMESTAMP(DATE_SUB(NOW(), INTERVAL %d DAY))",
|
||||
retentionDays,
|
||||
)
|
||||
}
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user