diff --git a/src/bean/entity/alert_class.go b/src/bean/entity/alert_class.go index 801f530b924277033533296ff127cd357785a5d8..0e11ad6f05b19ab985ec1ee89ec8bdf208787336 100644 --- a/src/bean/entity/alert_class.go +++ b/src/bean/entity/alert_class.go @@ -3,15 +3,15 @@ package entity import "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/jsontime" type AlertClass struct { - ClassId int `json:"class_id" xorm:"'class_id' pk autoincr" ` // 主键id - ClassName string `json:"class_name" xorm:"'class_name'"` // 分类名称 - ParentId int `json:"parent_id" xorm:"'parent_id'"` // 父级id - SortOrder int `json:"sort_order" xorm:"'sort_order'"` // 排序 - SourceFrom int `json:"source_from" xorm:"source_from"` // 数据来源 1:默认 2:自定义 - CreatedBy string `json:"created_by" xorm:"'created_by'"` // 创建人 - CreatedAt jsontime.Time `json:"created_at" xorm:"'created_at'"` // 创建时间 - UpdatedBy string `json:"updated_by" xorm:"'updated_by'"` // 更新人 - UpdatedAt jsontime.Time `json:"updated_at" xorm:"'updated_at'"` // 更新时间 + ClassId int `json:"class_id" xorm:"'class_id' pk autoincr"` // 主键id + ClassName string `json:"class_name" xorm:"'class_name'"` // 分类名称 + ParentId int `json:"parent_id" xorm:"'parent_id'"` // 父级id + SortOrder int `json:"sort_order" xorm:"'sort_order'"` // 排序 + SourceFrom int `json:"source_from" xorm:"source_from"` // 数据来源 1:默认 2:自定义 + CreatedBy string `json:"created_by" xorm:"'created_by'"` // 创建人 + CreatedAt jsontime.Time `json:"created_at" xorm:"'created_at'"` // 创建时间 + UpdatedBy string `json:"updated_by" xorm:"'updated_by'"` // 更新人 + UpdatedAt jsontime.Time `json:"updated_at" xorm:"'updated_at'"` // 更新时间 } func (m *AlertClass) TableName() string { diff --git a/src/bean/entity/alert_list.go b/src/bean/entity/alert_list.go new file mode 100644 index 0000000000000000000000000000000000000000..0829ffc99c5100397d7c37bb3123182eb3374048 --- /dev/null +++ b/src/bean/entity/alert_list.go @@ -0,0 +1,35 @@ +package entity + +import ( + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/jsontime" +) + +type AlertList struct { + Id int `json:"id"` // 预警列表ID,主键,自增长 + AlertPoint string `json:"alert_point"` // 预警点 + AlertRulesId string `json:"alert_rules_id"` // 告警规则id + RiskLevel int `json:"risk_level"` // 风险等级,1:低风险,2:一般风险,3:较大风险,4:重大风险 + AlertTime jsontime.Time `json:"alert_time"` // 预警时间 + ClassId int `json:"class_id" xorm:"'class_id'"` // 预警对象id(级联:预警分类/预警对象) + ClassParentName string `json:"class_parent_name" xorm:"class_parent_name"` // 预警分类名称 TODO 该字段做关联存储或查询 + ClassName string `json:"class_name" xorm:"class_name"` // 预警对象名称 TODO 该字段做关联存储或查询 + MetricConfigId string `json:"metric_config_id"` // 预警指标id // 预警指标 + MetricConfigName string `json:"metric_config_name" xorm:"metric_config_name"` // 预警指标名称 + AlertRuleType string `json:"alert_rule_type" xorm:"alert_rule_type"` // 预警规则类型 TODO 该字段做关联存储或查询 + CurrentValue float64 `json:"current_value"` // 当前报警值 + AlertCondition string `json:"alert_condition" xorm:"'alert_condition'"` // 预警规则(预警阈值) 字典值 + NotificationCount int `json:"notification_count"` // 通知人数 + PushCount int `json:"push_count"` // 推送次数 + LastPushTime jsontime.Time `json:"last_push_time"` // 最近推送时间 + Status int `json:"status"` // 状态,1:已恢复 2:未恢复 3:已关闭 + IsDisposed int `json:"is_disposed"` // 是否处置(工单管理),1:已处置,2:未处置 + DisposalContent string `json:"disposal_content"` // 处置内容(工单管理,结果反馈) + CreatedBy string `json:"created_by" xorm:"'created_by'"` // 创建人 + CreatedAt jsontime.Time `json:"created_at" xorm:"'created_at'"` // 创建时间 + UpdatedBy string `json:"updated_by" xorm:"'updated_by'"` // 更新人 + UpdatedAt jsontime.Time `json:"updated_at" xorm:"'updated_at'"` // 更新时间 +} + +func (a *AlertList) TableName() string { + return "alert_list" +} diff --git a/src/bean/entity/alert_overview.go b/src/bean/entity/alert_overview.go new file mode 100644 index 0000000000000000000000000000000000000000..af85db31d6455d3e99ed6fde5b65fdb58b7c6b53 --- /dev/null +++ b/src/bean/entity/alert_overview.go @@ -0,0 +1,49 @@ +package entity + +import ( + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/jsontime" +) + +type AlertOverview struct { + RiskLevel int `json:"risk_level"` // 风险等级,1:低风险,2:一般风险,3:较大风险,4:重大风险 + UnresolvedCount int `json:"unresolved_count"` // 未恢复数量 + TotalCount int `json:"total_count"` // 总预警数 + List []AlertArray `json:"list"` // 预警列表 + CreatedBy string `json:"created_by" xorm:"'created_by'"` // 创建人 + CreatedAt jsontime.Time `json:"created_at" xorm:"'created_at'"` // 创建时间 + UpdatedBy string `json:"updated_by" xorm:"'updated_by'"` // 更新人 + UpdatedAt jsontime.Time `json:"updated_at" xorm:"'updated_at'"` // 更新时间 +} + +type AlertArray struct { + MetricName string `json:"metric_name" xorm:"'metric_name'"` // 预警规则名称(指标名称) + UnresolvedCount int `json:"unresolved_count"` // 未恢复数量 + TotalCount int `json:"total_count"` // 总预警数 +} + +type RiskLevelDistribution struct { + Name string `json:"name"` // 名称 + RiskLevel int `json:"risk_level"` // 风险等级,1:低风险,2:一般风险,3:较大风险,4:重大风险 + Percentage string `json:"percentage"` // 百分比 +} + +type AlertStatusDistribution struct { + Name string `json:"name"` // 名称 + Status int `json:"status"` // 状态,1:已恢复 2:未恢复 3:已关闭 + Percentage string `json:"percentage"` // 百分比 +} + +type AlertClassDistribution struct { + Name string `json:"name"` // 名称 + ClassId int `json:"class_id"` // 预警分类id + Percentage string `json:"percentage"` // 百分比 +} + +type AlertFrequencyDistribution struct { + Name string `json:"name"` // 名称 + Count int `json:"count"` // 数量 +} + +func (a *AlertOverview) TableName() string { + return "alert_overview.go" +} diff --git a/src/bean/entity/alert_rules.go b/src/bean/entity/alert_rules.go index 72e096f105cd19a82194bcb028542b198bbd28b4..65960812abeb457439310c4ec8f89d25d15a65f9 100644 --- a/src/bean/entity/alert_rules.go +++ b/src/bean/entity/alert_rules.go @@ -38,7 +38,7 @@ type RulesAlertRange struct { type AlertCondition struct { ThresholdsMax int `json:"thresholds_max" form:"thresholds_max" binding:"required"` ThresholdsMin int `json:"thresholds_min" form:"thresholds_min" binding:"required"` - RiskLevel int `json:"risk_level" form:"risk_level" binding:"required"` + RiskLevel int `json:"risk_level" form:"risk_level" binding:"required,oneof=1 2 3 4"` } type NotifyRecipients struct { diff --git a/src/bean/entity/dictionary.go b/src/bean/entity/dictionary.go index f8016cb085a679c9bc3f729f0de806a17845bc80..a0461856887b57646d4025a2e1a54efeb6986b81 100644 --- a/src/bean/entity/dictionary.go +++ b/src/bean/entity/dictionary.go @@ -37,6 +37,7 @@ type Dict struct { UpdatedAt jsontime.Time `json:"updated_time" xorm:"updated_at"` //修改时间 MinVal string `json:"min_val" xorm:"min_val"` //最大值 MaxVal string `json:"max_val" xorm:"max_val"` //最小值 + Unit string `json:"unit" xorm:"unit"` //单位 Sort int `json:"sort" xorm:"sort autoincr"` //排序字段 降序排列 } diff --git a/src/bean/entity/push_record.go b/src/bean/entity/push_record.go new file mode 100644 index 0000000000000000000000000000000000000000..fafad4ff7395b1ef388c4b4d8ce8b4665c52f49f --- /dev/null +++ b/src/bean/entity/push_record.go @@ -0,0 +1,18 @@ +package entity + +import "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/jsontime" + +type PushRecord struct { + Id int `json:"id" xorm:"'id' pk autoincr"` // 主键id + AlertRulesId string `json:"alert_rules_id" xorm:"'alert_rules_id'"` // 告警规则id + RiskLevel int `json:"risk_level" xorm:"'risk_level'"` // 风险等级,1:低风险,2:一般风险,3:较大风险,4:重大风险 + NotifyMethod string `json:"notify_method" xorm:"'notify_method'"` // 预警通知方式 all dingtalk sms + SystemAccount string `json:"system_account" xorm:"system_account"` // 预警推送用户(NotifyRecipient) // 账号 + PushTime jsontime.Time `json:"push_time" xorm:"'push_time'"` // 推送时间 + PushType int `json:"push_type" xorm:"'push_type'"` // 推送类型,1:自动推送,2:手动推送 + Status int `json:"status" xorm:"'status'"` // 推送状态,1:成功,2:失败 + CreatedBy string `json:"created_by" xorm:"'created_by'"` // 创建人 + CreatedAt jsontime.Time `json:"created_at" xorm:"'created_at'"` // 创建时间 + UpdatedBy string `json:"updated_by" xorm:"'updated_by'"` // 更新人 + UpdatedAt jsontime.Time `json:"updated_at" xorm:"'updated_at'"` // 更新时间 +} diff --git a/src/bean/vo/request/alert_list.go b/src/bean/vo/request/alert_list.go new file mode 100644 index 0000000000000000000000000000000000000000..cd84c796e7fbac83001944edbd68910867364458 --- /dev/null +++ b/src/bean/vo/request/alert_list.go @@ -0,0 +1,20 @@ +package request + +type DetailAlertList struct { + Id int `json:"id" form:"id" binding:"required"` +} + +type UpdateAlertList struct { + RiskLevel int `json:"risk_level" form:"risk_level" binding:"omitempty,oneof=1 2 3 4"` // 风险等级,1:低风险,2:一般风险,3:较大风险,4:重大风险 + Status int `json:"status" form:"status" binding:"omitempty,oneof=1 2 3"` // 状态,1:已恢复 2:未恢复 3:已关闭 + Keyword string `json:"keyword" form:"keyword"` // 预警点/分类/指标 +} + +type ListAlertList struct { + Id int `json:"id" form:"id"` + RiskLevel int `json:"risk_level" form:"risk_level" binding:"omitempty,oneof=1 2 3 4"` // 风险等级,1:低风险,2:一般风险,3:较大风险,4:重大风险 + Status int `json:"status" form:"status" binding:"omitempty,oneof=1 2 3"` // 状态,1:已恢复 2:未恢复 3:已关闭 + Keyword string `json:"keyword" form:"keyword"` // 预警点/分类/指标 + StartTime string `json:"start_time" form:"start_time" binding:"omitempty,datetime=2006-01-02 15:04:05"` + EndTime string `json:"end_time" form:"end_time" binding:"omitempty,datetime=2006-01-02 15:04:05"` +} diff --git a/src/bean/vo/request/alert_overview.go b/src/bean/vo/request/alert_overview.go new file mode 100644 index 0000000000000000000000000000000000000000..aea312e2dac14e79b2e2c45fc797dd329d285c2b --- /dev/null +++ b/src/bean/vo/request/alert_overview.go @@ -0,0 +1,35 @@ +package request + +type AddAlertOverview struct { + ClassName string `json:"class_name" form:"class_name" binding:"required"` + ParentId int `json:"parent_id" form:"parent_id" binding:"omitempty,oneof=0 1"` + SortOrder int `json:"sort_order" form:"sort_order"` + SourceFrom int `json:"source_from" form:"source_from" binding:"omitempty,oneof=1 2"` // 数据来源 1:默认 2:自定义 +} + +type UpdateAlertOverview struct { + ClassId int `json:"class_id" form:"class_id" binding:"required"` + ClassName string `json:"class_name" form:"class_name" binding:"required"` +} + +type DeleteAlertOverview struct { + ClassId int `json:"class_id" form:"class_id"` + ClassIds []int `json:"class_ids" form:"class_ids" binding:"required_without=ClassId"` +} + +type MoveAlertOverview struct { + ClassId int `json:"class_id" form:"class_id" binding:"required"` + Direction string `json:"direction" form:"direction" binding:"oneof=up down"` +} + +type DetailAlertOverview struct { + OverviewTime string `json:"overview_time" form:"overview_time" binding:"omitempty,oneof=today week month year"` + StartTime string `json:"start_time" form:"start_time" binding:"omitempty,datetime=2006-01-02 15:04:05"` + EndTime string `json:"end_time" form:"end_time" binding:"omitempty,datetime=2006-01-02 15:04:05"` +} + +type ListAlertOverview struct { + ClassId int `json:"class_id" form:"class_id"` + ClassName string `json:"class_name" form:"class_name"` + Pagination +} diff --git a/src/bean/vo/request/dict.go b/src/bean/vo/request/dict.go index e59f6148354f327816f3a3ba4529624ea76a142b..632dc6d07919239d9a6ebb8a10a8af93484d801b 100644 --- a/src/bean/vo/request/dict.go +++ b/src/bean/vo/request/dict.go @@ -7,6 +7,8 @@ type DictReq struct { Status int `json:"status" form:"status"` Class int `json:"class" form:"class" binding:"oneof=0 1 2 3 4 5 6 7 8 9 10 11 12 13 14"` //组件分类(1开发语言与版本 2中间件类型与中间件 3云组件类型 4模块类型 5所属区域 6操作系统 7对象类型 8SQL类型 9调研评估结果 10任务阶段 11测试文档类型 12验收问题类型 13Q&A问题类型 14文档类型) ParentId string `json:"parent_id" form:"parent_id"` //父级ID + Search string `json:"search" form:"search"` + Pagination } type DictTreeReq struct { @@ -18,20 +20,22 @@ type AddDictReq struct { Class int `json:"class" form:"class" binding:"required,oneof=1 2 3 4 5 6 7 8 9 10 11 12 13 14"` //组件分类(1开发语言与版本 2中间件类型与中间件 3云组件类型 4模块类型 5所属区域 6操作系统 7对象类型 8SQL类型 9调研评估结果 10任务阶段 11测试文档类型 12验收问题类型 13Q&A问题类型 14文档类型) ParentId string `json:"parent_id" form:"parent_id"` //父级ID Name string `json:"name" form:"name" binding:"required"` //字典标签 - Status int `json:"status" form:"status" binding:"oneof=0 1"` //是否启用(1:启用 2:禁用) + Status int `json:"status" form:"status" binding:"oneof=0 1 2"` //是否启用(1:启用 2:禁用) Description string `json:"description" form:"description" binding:"lte=200"` //描述 MinVal string `json:"min_val" form:"min_val"` //最大值 MaxVal string `json:"max_val" form:"max_val"` //最小值 + Unit string `json:"unit" form:"unit"` //最小值 } type UpdateDictReq struct { Id string `json:"id" form:"id" binding:"required"` //组件ID ParentId string `json:"parent_id" form:"parent_id"` //父级ID Name string `json:"name" form:"name" binding:"required"` //字典标签 - Status int `json:"status" form:"status" binding:"oneof=0 1"` //是否启用(1:启用 2:禁用) + Status int `json:"status" form:"status" binding:"oneof=0 1 2"` //是否启用(1:启用 2:禁用) Description string `json:"description" form:"description" binding:"lte=200"` //描述 MinVal string `json:"min_val" form:"min_val"` //最大值 MaxVal string `json:"max_val" form:"max_val"` //最小值 + Unit string `json:"unit" form:"unit"` //最小值 UpdatedBy int `json:"updated_by" ` //修改人 UpdatedAt jsontime.Time `json:"updated_at"` //修改时间 } @@ -40,7 +44,7 @@ type DictManageListReq struct { Id string `json:"id" form:"id" binding:"required"` //组件ID ParentId string `json:"parent_id" form:"parent_id"` //父级ID Name string `json:"name" form:"name" binding:"required"` //字典标签 - Status int `json:"status" form:"status" binding:"oneof=0 1"` //是否启用(1:启用 2:禁用) + Status int `json:"status" form:"status" binding:"oneof=0 1 2"` //是否启用(1:启用 2:禁用) Description string `json:"description" form:"description" binding:"lte=200"` //描述 MinVal string `json:"min_val" form:"min_val"` //最大值 MaxVal string `json:"max_val" form:"max_val"` //最小值 diff --git a/src/bean/vo/request/log_management.go b/src/bean/vo/request/log_management.go new file mode 100644 index 0000000000000000000000000000000000000000..9d236cc6cad147093be8c63eb43ad5393373810a --- /dev/null +++ b/src/bean/vo/request/log_management.go @@ -0,0 +1,29 @@ +package request + +type LogManagementListReq struct { + Pagination //分页参数 + Search string `json:"search" form:"search"` // 搜素 + //IsAdmin int `json:"is_admin" form:"is_admin"` // 用户类型 (1.业务系统账号 2.组织管理员账号 3.平台用户账号 4.超级管理员) + StartAt string `json:"start_at" form:"start_at"` // 开始时间 + EndAt string `json:"end_at" form:"end_at"` // 结束时间 + Active int `json:"active" form:"active"` // 活跃度 1: 低 2:中 3: 高 + PwdLevel int `json:"pwd_level" form:"pwd_level"` // 密码强度 1低2中3高 +} + +type LogUserBehaviorListReq struct { + Pagination //分页参数 + Search string `json:"search" form:"search"` // 搜素 + //IsAdmin int `json:"is_admin" form:"is_admin"` // 用户类型 (1.业务系统账号 2.组织管理员账号 3.平台用户账号 4.超级管理员) + StartAt string `json:"start_at" form:"start_at"` // 开始时间 + EndAt string `json:"end_at" form:"end_at"` // 结束时间 + OperateType string `json:"operate_type" form:"operate_type"` // 操作类型 + ReqMethod int `json:"req_method" form:"req_method"` // 请求方式 + OperateStatus int `json:"operate_status" form:"operate_status"` // 操作状态 +} + +type SystemLogListReq struct { + Pagination //分页参数 + Search string `json:"search" form:"search"` // 搜素 + Index string `json:"index" form:"index"` //索引名称 + Level string `json:"level" form:"level"` //级别 +} diff --git a/src/bean/vo/request/page.go b/src/bean/vo/request/page.go index c570b08800f861c9ecd816292f0b976434edf371..92a0a702a97dbed149971f85d6c2e92f7404c388 100644 --- a/src/bean/vo/request/page.go +++ b/src/bean/vo/request/page.go @@ -19,3 +19,13 @@ func (p Pagination) GetPageSize() int { } return p.PageSize } + +func (p Pagination) GetOffset() int { + if p.Page == 0 { + p.Page = 1 + } + if p.PageSize == 0 { + p.PageSize = 15 + } + return (p.Page - 1) * p.PageSize +} diff --git a/src/bean/vo/request/work_order.go b/src/bean/vo/request/work_order.go index 7eb26279517db0916e5f6166280c7540dfbaef67..45505722f1b3a3f258b0a356017e738e340485fd 100644 --- a/src/bean/vo/request/work_order.go +++ b/src/bean/vo/request/work_order.go @@ -12,8 +12,8 @@ type AddWorkOrderReq struct { // 推送对象 type PushObj struct { - PushMethod int `json:"push_method" binding:"oneof=1 2 3"` // 推送方式(1钉钉 2短信 3all) - UserObj []UserObj `json:"user_obj" binding:"oneof=1 2 3,dive"` // 用户对象 + PushMethod int `json:"push_method" binding:"oneof=1 2 3"` // 推送方式(1钉钉 2短信 3all) + UserObj []UserObj `json:"user_obj" binding:"dive"` // 用户对象 } type UserObj struct { SystemAccount string `json:"system_account" binding:"required"` // 账号 diff --git a/src/bean/vo/response/alert_list.go b/src/bean/vo/response/alert_list.go new file mode 100644 index 0000000000000000000000000000000000000000..1105cb7d00de643c19384f663f6e8d3689bf8828 --- /dev/null +++ b/src/bean/vo/response/alert_list.go @@ -0,0 +1,15 @@ +package response + +import ( + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/bean/entity" +) + +type AlertListItem struct { + entity.AlertList `xorm:"extends"` + AlertCondition entity.AlertCondition `json:"alert_condition" xorm:"alert_condition"` +} + +type AlertListList struct { + TotalCount int64 `json:"total_count"` + List []AlertListItem `json:"list"` +} diff --git a/src/bean/vo/response/alert_overview.go b/src/bean/vo/response/alert_overview.go new file mode 100644 index 0000000000000000000000000000000000000000..3885be2cd60085b3a1251c4926364d2cfcc04bce --- /dev/null +++ b/src/bean/vo/response/alert_overview.go @@ -0,0 +1,23 @@ +package response + +import ( + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/bean/entity" +) + +type AlertOverviewItem struct { + AlertOverview []entity.AlertOverview `json:"alert_overview"` + RiskLevelDistribution []entity.RiskLevelDistribution `json:"risk_level_distribution"` + AlertStatusDistribution []entity.AlertStatusDistribution `json:"alert_status_distribution"` + AlertClassDistribution []entity.AlertClassDistribution `json:"alert_class_distribution"` + AlertFrequencyDistribution []entity.AlertFrequencyDistribution `json:"alert_frequency_distribution"` +} + +type AlertOverviewList struct { + TotalCount int64 `json:"total_count"` + List []AlertOverviewItem `json:"list"` +} + +type AlertOverviewNode struct { + entity.AlertOverview + Children []*AlertOverviewNode `json:"children"` +} diff --git a/src/bean/vo/response/dict.go b/src/bean/vo/response/dict.go index 15c8f5e05169c659fcff13b639f836354abed0e6..ea3e1acf0c3507f421843560cafed781cbca66ff 100644 --- a/src/bean/vo/response/dict.go +++ b/src/bean/vo/response/dict.go @@ -1,15 +1,21 @@ package response +import "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/jsontime" + type DictListRes struct { - Id string `json:"id" column:"id"` //主键ID - Class int `json:"class" column:"class"` //组件分类(1开发语言与版本 2中间件类型与中间件 3云组件类型 4模块类型 5所属区域 6操作系统 7对象类型 8SQL类型 9调研评估结果 10任务阶段 11测试文档类型 12验收问题类型 13Q&A问题类型 14文档类型) - Name string `json:"name" column:"name"` //组件名称 - ParentId string `json:"parent_id" column:"parent_id"` //父id - Status int `json:"status"` - MinVal string `json:"min_val" ` //最大值 - MaxVal string `json:"max_val"` - Sort int `json:"sort"` - Children []*DictListRes `json:"children,omitempty"` + Id string `json:"id" column:"id"` //主键ID + Class int `json:"class" column:"class"` //组件分类(1开发语言与版本 2中间件类型与中间件 3云组件类型 4模块类型 5所属区域 6操作系统 7对象类型 8SQL类型 9调研评估结果 10任务阶段 11测试文档类型 12验收问题类型 13Q&A问题类型 14文档类型) + Name string `json:"name" column:"name"` //组件名称 + ParentId string `json:"parent_id" column:"parent_id"` //父id + Status int `json:"status"` + Description string `json:"description"` + UpdatedAt jsontime.Time `json:"updated_at"` + MinVal string `json:"min_val" ` //最大值 + MaxVal string `json:"max_val"` + Unit string `json:"unit"` + Sort int `json:"sort"` + BuiltIn int `json:"built_in"` + Children []*DictListRes `json:"children,omitempty"` } //type ComponentDictTreeRes struct { diff --git a/src/bean/vo/response/host_manage.go b/src/bean/vo/response/host_manage.go index 909ed279601fe8795d94fefb6d50049f1fbe9f55..b16046cacfc5075810732e19cc1a34c3039c1455 100644 --- a/src/bean/vo/response/host_manage.go +++ b/src/bean/vo/response/host_manage.go @@ -62,7 +62,7 @@ type HostManageListRes struct { Id int `json:"id"` // id Ip string `json:"ip"` // ip Port string `json:"port"` // 端口 - VoucherType int `json:"voucher_type"` // 凭证类型(0密码验证 密钥验证) + VoucherType int `json:"voucher_type"` // 凭证类型(0密码验证 1密钥验证) UserName string `json:"user_name"` // 用户名 Password string `json:"password"` // 密码 } diff --git a/src/bean/vo/response/log_management.go b/src/bean/vo/response/log_management.go new file mode 100644 index 0000000000000000000000000000000000000000..337e10240bf5ccdb932148865cd269c6b58f1306 --- /dev/null +++ b/src/bean/vo/response/log_management.go @@ -0,0 +1,174 @@ +package response + +import ( + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/jsontime" +) + +type LogManagementRep struct { + Id int32 `json:"id" xorm:"pk autoincr" ` // id + OrganizationId string `json:"organization_id" xorm:"organization_id"` // 所属组织 + Name string `json:"name"` // 所属组织名称 + SystemAccount string `json:"system_account" xorm:"system_account"` // 系统账号 + ContactPhone string `json:"contact_phone" xorm:"contact_phone"` // 联系人电话 + //IsAdmin string `json:"is_admin" xorm:"is_admin"` // 用户类型 (1.业务系统账号 2.组织管理员账号 3.平台用户账号 4.超级管理员) + LastAccessTimes jsontime.Time `json:"-" xorm:"last_access_time"` // 用户最后访问时间 + LastAccessTime jsontime.Time `json:"last_access_time" xorm:"-"` // 用户最后访问时间 + Active string `json:"active"` // 活跃度 高:小于等于7天,中:大于7天小于一个月,低:大于等于一个月 1: 低 2:中 3: 高 + PwdLevel string `json:"pwd_level"` // 密码强度 1低2中3高 + PwdIsUsed int `json:"pwd_is_used"` // 密码使用时长 + CreatedTime jsontime.Time `json:"created_time" xorm:"created_time" ` // 创建时间 +} + +type SystemUserBehaviorList struct { + //Xh int64 `json:"xh" xorm:"id"` + Id int `json:"id" xorm:"id"` // 主键id + UserId int `json:"user_id"` // 系统用户id + OrganizationId string `json:"organization_id"` // 组织uuid + SystemModule string `json:"system_module"` // 系统模块 + OperateType string `json:"operate_type"` // 操作类型 + ReqMethod int `json:"req_method"` // 请求方式 + OperateStatus int `json:"operate_status"` // 操作状态 + OperateIp string `json:"operate_ip"` // 操作ip信息 + OperateAddr string `json:"operate_addr"` // 操作地点 + CreatedTime jsontime.Time `json:"created_time" xorm:"created"` // 操作时间 + IsDeleted int `json:"is_deleted"` // 是否删除 + OperateMethod string `json:"operate_method"` // 操作方法函数名 + ResFields string `json:"res_fields"` // 返回参数 + ReqParam string `json:"req_param"` // 请求参数 + ReqUrl string `json:"req_url"` // 请求地址 + AppId string `json:"app_id"` // appId + SystemAccount string `json:"system_account"` // 系统账号 + Phone string `json:"-" xorm:"phone"` // 手机号 + //IsAdmin int `json:"is_admin"` // 用户类型 + OrgName string `json:"org_name"` // 组织 +} + +type LogUserBehaviorDetailRep struct { + Id int `json:"id" xorm:"pk autoincr"` // 主键id + UserId int `json:"user_id"` // 系统用户id + OrganizationId string `json:"organization_id"` // 组织uuid + SystemModule string `json:"system_module"` // 系统模块 + OperateType string `json:"operate_type"` // 操作类型 + ReqMethod int `json:"req_method"` // 请求方式 + ReqMethodStr string `json:"req_method_str" xorm:"-"` + OperateStatus int `json:"operate_status"` // 操作状态 + OperateStatusStr string `json:"operate_status_str" xorm:"-"` + OperateIp string `json:"operate_ip"` // 操作ip信息 + OperateAddr string `json:"operate_addr"` // 操作地点 + CreatedTime jsontime.Time `json:"created_time" xorm:"created"` // 操作时间 + OperateMethod string `json:"operate_method"` // 操作方法函数名 + ResFields string `json:"res_fields"` // 返回参数 + ReqParam string `json:"req_param"` // 请求参数 + ReqUrl string `json:"req_url"` // 请求地址 + AppId string `json:"app_id"` // appId + SystemAccount string `json:"system_account"` // 系统账号 + Phone string `json:"phone"` // 手机号 + //IsAdmin int `json:"-"` // 用户类型 + //UserType string `json:"user_type" xorm:"-"` + OrgName string `json:"org_name"` // 组织 +} + +type SystemUserBehaviorInfo struct { + Total map[string]interface{} `json:"total"` + Hits []BehaviorSourceData `json:"hits"` +} + +type BehaviorSourceData struct { + Id string `json:"_id"` + Source SystemUserBehaviorEs `json:"_source"` +} + +type SystemUserBehaviorEs struct { + Id string `json:"id"` + Xh int64 `json:"xh"` + UserId int `json:"user_id"` // 系统用户id + OrganizationId string `json:"organization_id"` // 组织uuid + SystemModule string `json:"system_module"` // 系统模块 + OperateType string `json:"operate_type"` // 操作类型 + ReqMethod int `json:"req_method"` // 请求方式 + OperateStatus int `json:"operate_status"` // 操作状态 + OperateIp string `json:"operate_ip"` // 操作ip信息 + OperateAddr string `json:"operate_addr"` // 操作地点 + CreatedTime string `json:"created_time" xorm:"created"` // 操作时间 + CreatedTimeUnix int64 `json:"created_time_unix"` // 操作时间戳(用于排序统计) + IsDeleted int `json:"is_deleted"` // 是否删除 + OperateMethod string `json:"operate_method"` // 操作方法函数名 + ResFields string `json:"res_fields"` // 返回参数 + ReqParam string `json:"req_param"` // 请求参数 + ReqUrl string `json:"req_url"` // 请求地址 + AppId string `json:"app_id"` // appId + SystemAccount string `json:"system_account"` // 系统账号 + Phone string `json:"phone" xorm:"phone"` // 手机号 + IsAdmin int `json:"is_admin"` // 用户类型 + OrgName string `json:"org_name"` // 组织 +} + +type SystemUserBehaviorToEs struct { + UserId int `json:"user_id"` // 系统用户id + OrganizationId string `json:"organization_id"` // 组织uuid + SystemModule string `json:"system_module"` // 系统模块 + OperateType string `json:"operate_type"` // 操作类型 + ReqMethod int `json:"req_method"` // 请求方式 + OperateStatus int `json:"operate_status"` // 操作状态 + OperateIp string `json:"operate_ip"` // 操作ip信息 + OperateAddr string `json:"operate_addr"` // 操作地点 + CreatedTime string `json:"created_time" xorm:"created"` // 操作时间 + CreatedTimeUnix int64 `json:"created_time_unix"` // 操作时间戳(用于排序统计) + IsDeleted int `json:"is_deleted"` // 是否删除 + OperateMethod string `json:"operate_method"` // 操作方法函数名 + ResFields string `json:"res_fields"` // 返回参数 + ReqParam string `json:"req_param"` // 请求参数 + ReqUrl string `json:"req_url"` // 请求地址 + AppId string `json:"app_id"` // appId + SystemAccount string `json:"system_account"` // 系统账号 + Phone string `json:"phone" xorm:"phone"` // 手机号 + //IsAdmin int `json:"is_admin"` // 用户类型 + OrgName string `json:"org_name"` // 组织 +} + +type SystemUserInfoEs struct { + SystemAccount string `json:"system_account"` // 系统账号 + Phone string `json:"-" xorm:"phone"` // 手机号 + //IsAdmin int `json:"is_admin"` // 用户类型 + OrgName string `json:"org_name"` // 组织 +} + +type BehaviorEsListInfo struct { + Total map[string]interface{} `json:"total"` + Hits []SourceData `json:"hits"` +} + +type SourceData struct { + Id string `json:"_id"` + Source SystemUserBehaviorList `json:"_source"` +} + +type SystemLogTree struct { + Id int `json:"id"` + Name string `json:"name"` + Value string `json:"value"` +} + +type SystemLogEsListInfo struct { + Hits []SystemLogSourceData `json:"hits"` +} + +type SystemLogSourceData struct { + Id string `json:"_id"` + Source SystemLogEsList `json:"_source"` +} + +type SystemLogEsList struct { + Level string `json:"level"` + Timestamp string `json:"timestamp"` + Msg string `json:"msg"` + Status int `json:"status"` + Method string `json:"method"` + Path string `json:"path"` + Query string `json:"query"` + Ip string `json:"ip"` + UserAgent string `json:"user-agent"` + Errors string `json:"errors"` + Cost int `json:"cost"` + TimeUnit int64 `json:"time_unit"` +} diff --git a/src/common/conf/options.go b/src/common/conf/options.go index 7e170c597c80e613ddcbddfcaa825f2d1ecd0ce8..3b8fff9d96a5156cdcc9c3075b2b0f1f4e23d98b 100644 --- a/src/common/conf/options.go +++ b/src/common/conf/options.go @@ -35,6 +35,8 @@ type Config struct { AccessRuleModeKey string LocationUrl string LocationKey string + PrivateKeySSH string + PublicKeySSH string } const ( diff --git a/src/common/tools/xlsxSheet.go b/src/common/tools/xlsxSheet.go new file mode 100644 index 0000000000000000000000000000000000000000..0716032c7b673d95e2a038e81ae4f1b953f6d65c --- /dev/null +++ b/src/common/tools/xlsxSheet.go @@ -0,0 +1,44 @@ +/** + * @Author: Y + * @Description: + * @File: xlsxSheet + * @Version: 1.0.0 + * @Date: 2023/2/23 15:34 + */ + +package tools + +import ( + "errors" + "github.com/tealeg/xlsx" +) + +type XlsxRow struct { + Row *xlsx.Row + Data []string +} + +func NewRow(row *xlsx.Row, data []string) *XlsxRow { + return &XlsxRow{ + Row: row, + Data: data, + } +} +func (row *XlsxRow) SetRowTitle() error { + return generateRow(row.Row, row.Data) +} + +func (row *XlsxRow) GenerateRow() error { + return generateRow(row.Row, row.Data) +} + +func generateRow(row *xlsx.Row, rowStr []string) error { + if rowStr == nil { + return errors.New("no data to generate xlsx!") + } + for _, v := range rowStr { + cell := row.AddCell() + cell.SetString(v) + } + return nil +} diff --git a/src/controller/alert_list.go b/src/controller/alert_list.go new file mode 100644 index 0000000000000000000000000000000000000000..aa21524220d60c5b24e647547b5118ff0ba20716 --- /dev/null +++ b/src/controller/alert_list.go @@ -0,0 +1,62 @@ +package controller + +import ( + "github.com/gin-gonic/gin" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/bean/vo/request" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/common/client" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/resp" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/router/middleware/header" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/service" +) + +func UpdateAlertList(c *gin.Context) { + var req request.UpdateAlertList + if err := c.ShouldBind(&req); err != nil { + SendJsonResponse(c, resp.InvalidParam.TranslateError(err), nil) + return + } + + svc := service.AlertListSvc{User: header.GetUser(c)} + db, err := client.GetDbClient() + if err != nil { + SendJsonResponse(c, resp.DbConnectError.WithError(err), nil) + return + } + err = svc.Update(db.NewSession(), req) + if err != nil { + SendJsonResponse(c, resp.FAIL.WithError(err), nil) + return + } + SendJsonResponse(c, resp.OK, nil) +} + +func DetailAlertList(c *gin.Context) { + var req request.DetailAlertList + if err := c.ShouldBind(&req); err != nil { + SendJsonResponse(c, resp.InvalidParam.TranslateError(err), nil) + return + } + + svc := service.AlertListSvc{User: header.GetUser(c)} + data, err := svc.GetDataById(req) + if err != nil { + SendJsonResponse(c, resp.FAIL.WithError(err), nil) + return + } + SendJsonResponse(c, resp.OK, data) +} + +func ListAlertList(c *gin.Context) { + var req request.ListAlertList + if err := c.ShouldBind(&req); err != nil { + SendJsonResponse(c, resp.InvalidParam.TranslateError(err), nil) + return + } + svc := service.AlertListSvc{User: header.GetUser(c)} + data, err := svc.List(req) + if err != nil { + SendJsonResponse(c, resp.FAIL.WithError(err), nil) + return + } + SendJsonResponse(c, resp.OK, data) +} diff --git a/src/controller/alert_overview.go b/src/controller/alert_overview.go new file mode 100644 index 0000000000000000000000000000000000000000..2cb24d07361950d44307ad8e9510c1b81432d5e8 --- /dev/null +++ b/src/controller/alert_overview.go @@ -0,0 +1,107 @@ +package controller + +import ( + "github.com/gin-gonic/gin" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/bean/vo/request" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/common/client" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/resp" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/router/middleware/header" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/service" +) + +// AddAlertOverview 新增任务 +func AddAlertOverview(c *gin.Context) { + var req request.AddAlertOverview + if err := c.ShouldBind(&req); err != nil { + SendJsonResponse(c, resp.InvalidParam.TranslateError(err), nil) + return + } + + svc := service.AlertOverviewSvc{User: header.GetUser(c)} + db, err := client.GetDbClient() + if err != nil { + SendJsonResponse(c, resp.DbConnectError.WithError(err), nil) + return + } + _, err = svc.Add(db.NewSession(), req) + if err != nil { + SendJsonResponse(c, resp.FAIL.WithError(err), nil) + return + } + SendJsonResponse(c, resp.OK, nil) +} + +func UpdateAlertOverview(c *gin.Context) { + var req request.UpdateAlertOverview + if err := c.ShouldBind(&req); err != nil { + SendJsonResponse(c, resp.InvalidParam.TranslateError(err), nil) + return + } + + svc := service.AlertOverviewSvc{User: header.GetUser(c)} + db, err := client.GetDbClient() + if err != nil { + SendJsonResponse(c, resp.DbConnectError.WithError(err), nil) + return + } + err = svc.Update(db.NewSession(), req) + if err != nil { + SendJsonResponse(c, resp.FAIL.WithError(err), nil) + return + } + SendJsonResponse(c, resp.OK, nil) +} + +func DetailAlertOverview(c *gin.Context) { + var req request.DetailAlertOverview + if err := c.ShouldBind(&req); err != nil { + SendJsonResponse(c, resp.InvalidParam.TranslateError(err), nil) + return + } + + svc := service.AlertOverviewSvc{User: header.GetUser(c)} + data, err := svc.Overview(req) + if err != nil { + SendJsonResponse(c, resp.FAIL.WithError(err), nil) + return + } + SendJsonResponse(c, resp.OK, data) +} + +func ListAlertOverview(c *gin.Context) { + var req request.ListAlertOverview + if err := c.ShouldBind(&req); err != nil { + SendJsonResponse(c, resp.InvalidParam.TranslateError(err), nil) + return + } + svc := service.AlertOverviewSvc{User: header.GetUser(c)} + data, err := svc.List(req) + if err != nil { + SendJsonResponse(c, resp.FAIL.WithError(err), nil) + return + } + SendJsonResponse(c, resp.OK, data) +} + +func DeleteAlertOverview(c *gin.Context) { + var req request.DeleteAlertOverview + if err := c.ShouldBind(&req); err != nil { + SendJsonResponse(c, resp.InvalidParam.TranslateError(err), nil) + return + } + var ids []int + switch len(req.ClassIds) { + case 0: + ids = append(ids, req.ClassId) + default: + ids = req.ClassIds + } + + svc := service.AlertOverviewSvc{User: header.GetUser(c)} + err := svc.Delete(ids) + if err != nil { + SendJsonResponse(c, resp.FAIL.WithError(err), nil) + return + } + SendJsonResponse(c, resp.OK, nil) +} diff --git a/src/controller/dict.go b/src/controller/dict.go index 28e2d5bc72fe70d030232c1b81aad333bf225e5d..aeb67a7decfddfdcae5273547700ad8e81a929af 100644 --- a/src/controller/dict.go +++ b/src/controller/dict.go @@ -27,13 +27,13 @@ func (d Dict) List(c *gin.Context) { svc := new(service.Dict) svc.Ctx = c svc.User = header.GetUser(c) - result, err := svc.List(req) + result, count, err := svc.List(req) if err != nil { SendJsonResponse(c, resp.InvalidParam.WithError(err), "") return } - SendJsonResponse(c, resp.OK, result) + SendJsonPageResponse(c, resp.OK, result, count) } // DictTree 字典列表-树结构 @@ -194,6 +194,28 @@ func (d Dict) DictSort(c *gin.Context) { SendJsonResponse(c, resp.OK, "") } +func (d Dict) UpdateStatus(c *gin.Context) { + id := c.Query("id") + status := c.Query("status") + if id == "" || status == "" { + SendJsonResponse(c, resp.InvalidParam.WithData("id 或 status 字段不能为空"), "") + return + } + svc := new(service.Dict) + svc.Ctx = c + svc.User = header.GetUser(c) + total, err := svc.UpdateStatus(id, status) + if err != nil { + SendJsonResponse(c, err, nil) + return + } + if total == 0 { + SendJsonResponse(c, resp.FAIL, nil) + return + } + SendJsonResponse(c, resp.OK, nil) +} + // List 组件列表 //func (d Dict) ManageList(c *gin.Context) { // diff --git a/src/controller/log_management.go b/src/controller/log_management.go new file mode 100644 index 0000000000000000000000000000000000000000..b5add52f29222d04ae1972a9629d473a6e216b6b --- /dev/null +++ b/src/controller/log_management.go @@ -0,0 +1,154 @@ +package controller + +import ( + "fmt" + "github.com/gin-gonic/gin" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/bean/vo/request" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/resp" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/router/middleware/header" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/service" + "strings" +) + +// 系统日志树 +func GetSystemLoggerList(c *gin.Context) { + search := c.Query("logTime") + svc := service.LogManagement{User: header.GetUser(c)} + if dir, err := svc.GetSysLogDir(search); err != nil { + SendJsonResponse(c, err, "") + } else { + SendJsonResponse(c, resp.OK, dir) + } +} + +// 系统日志 +func GetSystemLog(c *gin.Context) { + name := c.Query("name") + search := c.Query("search") + logLevel := c.Query("logLevel") + svc := service.LogManagement{User: header.GetUser(c)} + if logs, err := svc.GetSysLog(logLevel, search, name); err != nil { + SendJsonResponse(c, err, "") + } else { + SendJsonResponse(c, resp.OK, logs) + } +} + +// 用户行为审计列表 +func LogUserBehaviorList(c *gin.Context) { + params := request.LogUserBehaviorListReq{} + // 绑定分页数据 + if err := c.ShouldBindQuery(¶ms); err != nil { + SendJsonResponse(c, resp.InvalidParam.WithError(err), nil) + return + } + + svc := service.LogManagement{User: header.GetUser(c)} + var ( + list interface{} + count int64 + err error + ) + + list, count, err = svc.LogUserBehaviorList(¶ms) + if err != nil { + SendJsonResponse(c, err, nil) + return + + } + SendJsonPageResponse(c, nil, list, count) +} + +// 用户行为审计列表导出 +func LogUserBehaviorListExport(c *gin.Context) { + params := request.LogUserBehaviorListReq{} + // 绑定分页数据 + if err := c.ShouldBindQuery(¶ms); err != nil { + SendJsonResponse(c, resp.InvalidParam.WithError(err), nil) + return + } + // 分页数据初始化 limit page Offset + + svc := service.LogManagement{User: header.GetUser(c)} + file, fileName, err := svc.LogUserBehaviorListExport(¶ms) + if err != nil { + SendJsonResponse(c, err, nil) + return + } + c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileName)) //fmt.Sprintf("attachment; filename=%s", filename)对下载的文件重命名 + c.Writer.Header().Add("Content-Type", "application/octet-stream") + c.Writer.Header().Add("Content-Transfer-Encoding", "binary") + _ = file.Write(c.Writer) +} + +func LogUserBehaviorDetail(c *gin.Context) { + id := c.Param("id") + if id == "" { + SendJsonResponse(c, resp.InvalidParam.WithData("id必填"), nil) + return + } + svc := service.LogManagement{User: header.GetUser(c)} + data, err := svc.LogUserBehaviorDetail(id) + if err != nil { + SendJsonResponse(c, err, nil) + return + } + SendJsonResponse(c, nil, data) +} + +func LogUserBehaviorDelete(c *gin.Context) { + ids := strings.Split(c.Query("ids"), ",") + if len(ids) == 0 { + SendJsonResponse(c, resp.InvalidParam.WithData("id必填"), nil) + return + } + svc := service.LogManagement{User: header.GetUser(c)} + err := svc.LogUserBehaviorDelete(ids) + if err != nil { + SendJsonResponse(c, err, nil) + return + } + SendJsonResponse(c, nil, "删除成功") +} + +//用户账户审计列表 +//func LogUserAccountAuditList(c *gin.Context) { +// params := request.LogManagementListReq{} +// // 绑定分页数据 +// if err := c.ShouldBindQuery(¶ms); err != nil { +// SendJsonResponse(c, res.ParamsParserError.ErrorDetail(err), nil) +// return +// } +// // 分页数据初始化 limit page Offset +// params.PageInfo = params.PageInfo.InitPage() +// svc := service.LogManagement{User: util.GetContextUser(c)} +// list, count, err := svc.LogUserAccountAuditList(¶ms) +// if err != nil { +// SendJsonResponse(c, err, nil) +// return +// } +// SendJsonPageResponse(c, err, list, count) +//} +// +//// 用户账户审计列表导出LogUserAccountAuditExport +//func LogUserAccountAuditExport(c *gin.Context) { +// params := request.LogManagementListReq{} +// // 绑定分页数据 +// if err := c.ShouldBindQuery(¶ms); err != nil { +// SendJsonResponse(c, res.ParamsParserError.ErrorDetail(err), nil) +// return +// } +// // 分页数据初始化 limit page Offset +// params.PageInfo = params.PageInfo.InitPage() +// svc := service.LogManagement{User: util.GetContextUser(c)} +// file, fileName, err := svc.LogUserAccountAuditExport(¶ms) +// if err != nil { +// SendJsonResponse(c, err, nil) +// return +// } +// c.Writer.Header().Add("Content-Disposition", fmt.Sprintf("attachment; filename=%s", fileName)) //fmt.Sprintf("attachment; filename=%s", filename)对下载的文件重命名 +// c.Writer.Header().Add("Content-Type", "application/octet-stream") +// c.Writer.Header().Add("Content-Transfer-Encoding", "binary") +// _ = file.Write(c.Writer) +// +//} diff --git a/src/main.go b/src/main.go index 164dbaa314211809db3f2dd1e6e5982a8b7d7a68..91b4705473b3eebead40fe87edb52d8ff3e896dd 100644 --- a/src/main.go +++ b/src/main.go @@ -32,6 +32,8 @@ func main() { initTempDirPrefix() pflag.Parse() // init start args initConfig() + + initAnsibleSSH() // init log config cfg := initLogConfig() conf.Logger = log.NewLogger(cfg, conf.LoggerLevel) @@ -75,6 +77,8 @@ func initConfig() { AccessRuleModeKey: "accessRuleMode", LocationUrl: util.SetEnvStr("LOCATION_URL", "https://apis.map.qq.com/ws/location/v1/ip"), LocationKey: util.SetEnvStr("LOCATION_KEY", "QKFBZ-PGGWJ-VZQFF-FHPA7-QWT5H-YHF4T"), + PrivateKeySSH: util.SetEnvStr("PRIVATE_KEY_SSH", "-----BEGIN OPENSSH PRIVATE KEY-----\nb3BlbnNzaC1rZXktdjEAAAAABG5vbmUAAAAEbm9uZQAAAAAAAAABAAAAlwAAAAdzc2gtcn\nNhAAAAAwEAAQAAAIEAsOFk9OUB8wg9fd+PDHyX8nEtTSPSZY+tjxq2da1Pf5FkIn+U1da6\nh2eqowF9lnyvlt7uEledTIWQZDGWToGYCZnRommSZEpo/vII+l1P28bJVHfgWFCqmxNfIB\nZFQ4KrOp9rXKidmrd8flhK/NTLJNqryrhhIiDs3CTyAliscIsAAAIQTuM2gU7jNoEAAAAH\nc3NoLXJzYQAAAIEAsOFk9OUB8wg9fd+PDHyX8nEtTSPSZY+tjxq2da1Pf5FkIn+U1da6h2\neqowF9lnyvlt7uEledTIWQZDGWToGYCZnRommSZEpo/vII+l1P28bJVHfgWFCqmxNfIBZF\nQ4KrOp9rXKidmrd8flhK/NTLJNqryrhhIiDs3CTyAliscIsAAAADAQABAAAAgDjcfGPtqq\n7CG2J3l7jf5MjfcTy3I0/a3GSApd82k7PivVoJwYLswJH+1XAJbqIN+zR4/fePitWqqjxL\nZJJgPstuXpBZuJDvGwMqfl7wHRL2Qx34sRG02hG5e3uIfMxe5lHcPba0qsVQt+vOhu9MUb\nsYF/mfuQJKt/Oi8nA1BbrBAAAAQFQPrap7AtYWEoCIY7gtpFMW51iDTAv5GN99DsKNuBby\nwQX2S0Wg/da75m/emJn/2IbmaKApvrx8LbenpyywfBkAAABBAN6xiYQ2j7eRjLV4h4Hbie\nVwlPYP4otKHdF5meObr+2ifYiMktdv/44V1XWKhgavjGFNWx2sHgj7byb51e/bi3MAAABB\nAMtVxa55G0wS9Yw1WK2F4JdYZ65ZAnUuo2rbA2dMDQxsOQxgel5Ox2XmC7e0GKrO9BJKPo\nR2fHEOdm9KOmoB8IkAAAAWY2hlbnppbG9uZ0BleGFtcGxlLmNvbQECAwQF\n-----END OPENSSH PRIVATE KEY-----\n"), + PublicKeySSH: util.SetEnvStr("PUBLIC_KEY_SSH", "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAAAgQCw4WT05QHzCD19348MfJfycS1NI9Jlj62PGrZ1rU9/kWQif5TV1rqHZ6qjAX2WfK+W3u4SV51MhZBkMZZOgZgJmdGiaZJkSmj+8gj6XU/bxslUd+BYUKqbE18gFkVDgqs6n2tcqJ2at3x+WEr81Msk2qvKuGEiIOzcJPICWKxwiw== chenzilong@example.com\n"), } } @@ -140,3 +144,30 @@ func initTempDirPrefix() { fmt.Println("创建目录失败!") } } + +func initAnsibleSSH() { + err := os.Mkdir("/root/.ssh", os.ModePerm) + if err != nil { + fmt.Println("创建目录失败!") + } + f, err := os.Create("/root/.ssh/id_rsa") + defer f.Close() + if err != nil { + fmt.Println(err.Error()) + } else { + _, err := f.Write([]byte(conf.Options.PrivateKeySSH)) + if err != nil { + fmt.Println(err.Error()) + } + } + f2, err := os.Create("/root/.ssh/id_rsa.pub") + defer f2.Close() + if err != nil { + fmt.Println(err.Error()) + } else { + _, err := f.Write([]byte(conf.Options.PublicKeySSH)) + if err != nil { + fmt.Println(err.Error()) + } + } +} diff --git a/src/pkg/beagle/jsontime/jsonTime.go b/src/pkg/beagle/jsontime/jsonTime.go index 1412c815961fe4c37056d6f202d3e35fdd7fbaa7..b6171b921fee8bff40f2464f6ccd127a1c673b6e 100644 --- a/src/pkg/beagle/jsontime/jsonTime.go +++ b/src/pkg/beagle/jsontime/jsonTime.go @@ -12,6 +12,19 @@ import ( var CSTZone = time.FixedZone("CST", 8*3600) // 固定东八区(CST: China Standard Time) +const ( + LocalDateTimeFormat string = "2006-01-02 15:04:05" + LocalDateTimeFormat1 string = "2006/01/02 15:04:05" + LocalDateTimeFormatUTC string = "2006-01-02T15:04:05" + LocalDateTimeFormatUTCZ string = "2006-01-02T15:04:05Z" + LocalDateFormat string = "2006-01-02" + LocalDateFormatEs string = "20060102150405" + LocalDateFormat1 string = `20060102` + LocalMonthFormat string = "2006-01" + LocalMonthFormat1 string = "2006.01" + LocalTimeFormat string = "15:04:05" +) + // Time 自定义时间 // 设置当前时间: jsonDate := Time(time.Now()) type Time time.Time diff --git a/src/router/alertlistrouter.go.go b/src/router/alertlistrouter.go.go new file mode 100644 index 0000000000000000000000000000000000000000..8bc089b3225e2f015f3a0f9f4927b2b3eedbe717 --- /dev/null +++ b/src/router/alertlistrouter.go.go @@ -0,0 +1,18 @@ +package router + +import ( + "fmt" + "github.com/gin-gonic/gin" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/common/conf" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/controller" +) + +// InitAlertListRouter 初始化预警列表配置路由 +func InitAlertListRouter(e *gin.Engine) { + group := e.Group(fmt.Sprintf("%s/alert_list", conf.Options.Prefix)) + { + group.GET("", controller.DetailAlertList) + group.GET("list", controller.ListAlertList) + group.PUT("", controller.UpdateAlertList) + } +} diff --git a/src/router/alertoverviewrouter.go.go b/src/router/alertoverviewrouter.go.go new file mode 100644 index 0000000000000000000000000000000000000000..c4927327e1f3153ef3564f5e2adc387971f61698 --- /dev/null +++ b/src/router/alertoverviewrouter.go.go @@ -0,0 +1,16 @@ +package router + +import ( + "fmt" + "github.com/gin-gonic/gin" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/common/conf" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/controller" +) + +// InitAlertOverviewRouter 初始化预警总览配置路由 +func InitAlertOverviewRouter(e *gin.Engine) { + group := e.Group(fmt.Sprintf("%s/alert_overview", conf.Options.Prefix)) + { + group.GET("", controller.DetailAlertOverview) + } +} diff --git a/src/router/dict.go b/src/router/dict.go index 03b2fcf105c2934d132f0aa806053237317b6a8a..20b6cca0ce27e7c6ed71dec393ce625456cfc5b1 100644 --- a/src/router/dict.go +++ b/src/router/dict.go @@ -22,6 +22,8 @@ func initDictRoute(e *gin.Engine) { base.GET("/tree", dict.DictTree) //字典列表-树结构 base.GET("/classList", dict.ClassList) //字典分类列表 base.PUT("/sort", dict.DictSort) //字典排序 + base.PUT("/status", dict.UpdateStatus) //字典排序 + //base.GET("/manage_list", dict.ManageList) //字典管理列表 } diff --git a/src/router/logmanagementrouter.go b/src/router/logmanagementrouter.go new file mode 100644 index 0000000000000000000000000000000000000000..4aa680ef9f70b1e90521f7da5ce4447b4aadd21d --- /dev/null +++ b/src/router/logmanagementrouter.go @@ -0,0 +1,42 @@ +package router + +import ( + "fmt" + "github.com/gin-gonic/gin" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/common/conf" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/controller" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/constant" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/router/middleware/header" +) + +// 初始化日志管理路由 +func InitLogManagementRouter(e *gin.Engine) { + logger := e.Group(fmt.Sprintf("%s/log", conf.Options.Prefix)) + + { + systemLog := logger.Group("/system", header.SetContext) + { + systemLog.GET("list", controller.GetSystemLoggerList) //系统日志树 + systemLog.GET("log", controller.GetSystemLog) //系统日志 + } + + //userBehavior := logger.Group("userBehavior", header.SetContext) + userBehavior := logger.Group("userBehavior") + { + //用户行为审计: + userBehavior.GET("list", controller.LogUserBehaviorList, header.AddLogMiddleware("用户行为审计", "/list", constant.OpTypeIntMap[constant.Find])) //用户行为审计列表 + userBehavior.GET("list/export", controller.LogUserBehaviorListExport, header.AddLogMiddleware("用户行为审计", "/export", constant.OpTypeIntMap[constant.Export])) //用户行为审计列表导出 + userBehavior.GET("detail/:id", controller.LogUserBehaviorDetail) //用户行为审计详情 + userBehavior.DELETE("delete", controller.LogUserBehaviorDelete) //用户行为审计删除 + } + + //userAccountAudit := logger.Group("/userAccountAudit", header.SetContext) + //{ + // //用户账户审计: + // userAccountAudit.GET("list", controller.LogUserAccountAuditList, header.AddLogMiddleware("用户账户审计", "/list", constant.OpTypeIntMap[constant.Find])) //用户账户审计列表 + // userAccountAudit.GET("list/export", controller.LogUserAccountAuditExport, header.AddLogMiddleware("用户账户审计", "/export", constant.OpTypeIntMap[constant.Export])) //用户账户审计列表导出 + // + //} + + } +} diff --git a/src/router/router.go b/src/router/router.go index 950674253000ee392883d4dbaf2ea84208970a21..0856e5324b3ed53ab024e41df299cbd8441fc7be 100644 --- a/src/router/router.go +++ b/src/router/router.go @@ -49,12 +49,18 @@ func Load(r *gin.Engine, middleware ...gin.HandlerFunc) { InitPreferenceConfigRouter(r) // 初始化访问控制管理路由 InitAccessRuleRouter(r) + // 初始化日志管理 + InitLogManagementRouter(r) // 初始化指标配置路由 InitMetricConfigRouter(r) // 初始化预警规则配置路由 InitAlertRulesRouter(r) + // 初始化预警列表配置路由 + InitAlertListRouter(r) // 初始化prometheus路由 InitPrometheusRouter(r) + // 初始化预警总览配置路由 + InitAlertOverviewRouter(r) // 初始化工单管理路由 InitWorkOrderRouter(r) } diff --git a/src/service/alert_list.go b/src/service/alert_list.go new file mode 100644 index 0000000000000000000000000000000000000000..c597a122015af061868896f2aa108ffd7cab473f --- /dev/null +++ b/src/service/alert_list.go @@ -0,0 +1,134 @@ +package service + +import ( + "github.com/jinzhu/copier" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/bean/entity" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/bean/vo/request" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/bean/vo/response" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/jsontime" + "xorm.io/xorm" +) + +type AlertListSvc struct { + User entity.SystemUserInfo +} + +func (a *AlertListSvc) Update(session *xorm.Session, req request.UpdateAlertList) error { + now := jsontime.Now() + data := entity.AlertList{ + UpdatedBy: a.User.SystemAccount, + UpdatedAt: now, + } + _ = copier.Copy(&data, &req) + _, err := session.Cols("class_name", "updated_by", "updated_at").ID(data.ClassId).Update(&data) + if err != nil { + return err + } + return nil +} + +func (a *AlertListSvc) GetDataById(req request.DetailAlertList) (resp response.AlertListItem, err error) { + now := jsontime.Now() + data := response.AlertListItem{ + AlertList: entity.AlertList{ + Id: 123, + AlertPoint: "容器云/kube-apiserver", + AlertRulesId: "762ed641-6c0e-4c39-bf7c-7463abb0f8a2", + RiskLevel: 4, + AlertTime: now, + ClassId: 14, + ClassParentName: "预警分类", + ClassName: "预警对象", + MetricConfigId: "d773b37b-dbb4-4a7b-be11-ab40f8acc00e", + MetricConfigName: "CPU负载过高", + AlertRuleType: "51a2cc1e-eb24-4b16-b106-3dc9db963a49", + CurrentValue: 85, + NotificationCount: 3, + PushCount: 3, + LastPushTime: now, + Status: 2, + IsDisposed: 1, + DisposalContent: "已处置完毕,已做恢复操作", + CreatedBy: "admin", + CreatedAt: now, + UpdatedBy: "admin", + UpdatedAt: now, + }, + AlertCondition: entity.AlertCondition{ + ThresholdsMax: 100, + ThresholdsMin: 80, + RiskLevel: 4, + }, + } + resp = data + return +} + +func (a *AlertListSvc) List(req request.ListAlertList) (resp response.AlertListList, err error) { + now := jsontime.Now() + data1 := response.AlertListItem{ + AlertList: entity.AlertList{ + Id: 123, + AlertPoint: "容器云/kube-apiserver", + AlertRulesId: "762ed641-6c0e-4c39-bf7c-7463abb0f8a2", + RiskLevel: 4, + AlertTime: now, + ClassId: 14, + ClassParentName: "预警分类", + ClassName: "预警对象", + MetricConfigId: "d773b37b-dbb4-4a7b-be11-ab40f8acc00e", + MetricConfigName: "磁盘空间不足", + AlertRuleType: "51a2cc1e-eb24-4b16-b106-3dc9db963a49", + CurrentValue: 85, + NotificationCount: 3, + PushCount: 3, + LastPushTime: now, + Status: 2, + IsDisposed: 1, + DisposalContent: "处置为未恢复", + CreatedBy: "admin", + CreatedAt: now, + UpdatedBy: "admin", + UpdatedAt: now, + }, + AlertCondition: entity.AlertCondition{ + ThresholdsMax: 100, + ThresholdsMin: 80, + RiskLevel: 4, + }, + } + data2 := response.AlertListItem{ + AlertList: entity.AlertList{ + Id: 125, + AlertPoint: "容器云/apaas", + AlertRulesId: "762ed641-6c0e-4c39-bf7c-7463abb0f8a2", + RiskLevel: 3, + AlertTime: now, + ClassId: 14, + ClassParentName: "预警分类", + ClassName: "预警对象", + MetricConfigId: "d773b37b-dbb4-4a7b-be11-ab40f8acc00e", + MetricConfigName: "响应时间超时", + AlertRuleType: "51a2cc1e-eb24-4b16-b106-3dc9db963a49", + CurrentValue: 85, + NotificationCount: 1, + PushCount: 1, + LastPushTime: now, + Status: 1, + IsDisposed: 1, + DisposalContent: "处置内容为已恢复", + CreatedBy: "admin", + CreatedAt: now, + UpdatedBy: "admin", + UpdatedAt: now, + }, + AlertCondition: entity.AlertCondition{ + ThresholdsMax: 80, + ThresholdsMin: 50, + RiskLevel: 3, + }, + } + resp.List = append(resp.List, data1, data2) + resp.TotalCount = int64(len(resp.List)) + return +} diff --git a/src/service/alert_overview.go b/src/service/alert_overview.go new file mode 100644 index 0000000000000000000000000000000000000000..1d8cc722581daf6a22759222df0d38aac396afdc --- /dev/null +++ b/src/service/alert_overview.go @@ -0,0 +1,309 @@ +package service + +import ( + "github.com/jinzhu/copier" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/bean/entity" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/bean/vo/request" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/bean/vo/response" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/common/client" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/jsontime" + "xorm.io/xorm" +) + +type AlertOverviewSvc struct { + User entity.SystemUserInfo +} + +func (a *AlertOverviewSvc) Add(session *xorm.Session, req request.AddAlertOverview) (classId int, err error) { + now := jsontime.Now() + data := entity.AlertOverview{ + CreatedBy: a.User.SystemAccount, + CreatedAt: now, + UpdatedBy: a.User.SystemAccount, + UpdatedAt: now, + } + _ = copier.Copy(&data, &req) + return +} + +func (a *AlertOverviewSvc) Update(session *xorm.Session, req request.UpdateAlertOverview) error { + now := jsontime.Now() + data := entity.AlertOverview{ + UpdatedBy: a.User.SystemAccount, + UpdatedAt: now, + } + _ = copier.Copy(&data, &req) + return nil +} + +func (a *AlertOverviewSvc) Overview(req request.DetailAlertOverview) (resp response.AlertOverviewItem, err error) { + now := jsontime.Now() + resp = response.AlertOverviewItem{ + AlertOverview: []entity.AlertOverview{ + { + RiskLevel: 4, + UnresolvedCount: 10, + TotalCount: 24, + List: []entity.AlertArray{ + { + MetricName: "CPU使用率过高", + UnresolvedCount: 4, + TotalCount: 8, + }, + { + MetricName: "内存不足", + UnresolvedCount: 1, + TotalCount: 2, + }, + { + MetricName: "磁盘空间不足", + UnresolvedCount: 3, + TotalCount: 4, + }, + { + MetricName: "服务中断", + UnresolvedCount: 1, + TotalCount: 4, + }, + { + MetricName: "响应时间超时", + UnresolvedCount: 2, + TotalCount: 6, + }, + }, + CreatedBy: "admin", + CreatedAt: now, + UpdatedBy: "admin", + UpdatedAt: now, + }, + { + RiskLevel: 3, + UnresolvedCount: 8, + TotalCount: 26, + List: []entity.AlertArray{ + { + MetricName: "CPU使用率过高", + UnresolvedCount: 4, + TotalCount: 12, + }, + { + MetricName: "内存不足", + UnresolvedCount: 1, + TotalCount: 10, + }, + { + MetricName: "磁盘空间不足", + UnresolvedCount: 3, + TotalCount: 8, + }, + { + MetricName: "服务中断", + UnresolvedCount: 1, + TotalCount: 4, + }, + { + MetricName: "响应时间超时", + UnresolvedCount: 2, + TotalCount: 6, + }, + }, + CreatedBy: "admin", + CreatedAt: now, + UpdatedBy: "admin", + UpdatedAt: now, + }, + { + RiskLevel: 2, + UnresolvedCount: 13, + TotalCount: 50, + List: []entity.AlertArray{ + { + MetricName: "CPU使用率过高", + UnresolvedCount: 4, + TotalCount: 12, + }, + { + MetricName: "内存不足", + UnresolvedCount: 1, + TotalCount: 10, + }, + { + MetricName: "磁盘空间不足", + UnresolvedCount: 3, + TotalCount: 8, + }, + { + MetricName: "服务中断", + UnresolvedCount: 1, + TotalCount: 4, + }, + { + MetricName: "响应时间超时", + UnresolvedCount: 2, + TotalCount: 6, + }, + }, + CreatedBy: "admin", + CreatedAt: now, + UpdatedBy: "admin", + UpdatedAt: now, + }, + { + RiskLevel: 1, + UnresolvedCount: 8, + TotalCount: 20, + List: []entity.AlertArray{ + { + MetricName: "CPU使用率过高", + UnresolvedCount: 4, + TotalCount: 12, + }, + { + MetricName: "内存不足", + UnresolvedCount: 1, + TotalCount: 10, + }, + { + MetricName: "磁盘空间不足", + UnresolvedCount: 3, + TotalCount: 8, + }, + { + MetricName: "服务中断", + UnresolvedCount: 1, + TotalCount: 4, + }, + { + MetricName: "响应时间超时", + UnresolvedCount: 2, + TotalCount: 6, + }, + }, + CreatedBy: "admin", + CreatedAt: now, + UpdatedBy: "admin", + UpdatedAt: now, + }, + }, + RiskLevelDistribution: []entity.RiskLevelDistribution{ + { + Name: "重大风险", + RiskLevel: 4, + Percentage: "10%", + }, + { + Name: "较大风险", + RiskLevel: 3, + Percentage: "20%", + }, + { + Name: "一般风险", + RiskLevel: 2, + Percentage: "30%", + }, + { + Name: "低风险", + RiskLevel: 1, + Percentage: "40%", + }, + }, + AlertStatusDistribution: []entity.AlertStatusDistribution{ + { + Name: "未恢复", + Status: 1, + Percentage: "30%", + }, + { + Name: "已恢复", + Status: 2, + Percentage: "70%", + }, + }, + AlertClassDistribution: []entity.AlertClassDistribution{ + { + Name: "容器集群", + ClassId: 1, + Percentage: "30%", + }, + { + Name: "容器节点", + ClassId: 2, + Percentage: "20%", + }, + { + Name: "容器组", + ClassId: 3, + Percentage: "30%", + }, + { + Name: "网关", + ClassId: 4, + Percentage: "20%", + }, + }, + AlertFrequencyDistribution: []entity.AlertFrequencyDistribution{ + { + Name: "0-3时", + Count: 12, + }, + { + Name: "3-6时", + Count: 20, + }, + { + Name: "6-9时", + Count: 11, + }, + { + Name: "9-12时", + Count: 50, + }, + { + Name: "12-15时", + Count: 60, + }, + { + Name: "15-18时", + Count: 30, + }, + { + Name: "18-21时", + Count: 16, + }, + { + Name: "21-24时", + Count: 6, + }, + }, + } + + return +} + +func (a *AlertOverviewSvc) List(req request.ListAlertOverview) (resp response.AlertOverviewList, err error) { + db, err := client.GetDbClient() + if err != nil { + return + } + session := db.NewSession() + defer session.Close() + session.Where("source_from = 1") + if req.ClassId != 0 { + session.Where("class_id = ?", req.ClassId) + } + if req.ClassName != "" { + session.Where("class_name LIKE ?", "%"+req.ClassName+"%") + } + resp.TotalCount, err = session.Limit(req.GetPageSize(), (req.GetPage()-1)*req.GetPageSize()). + OrderBy("sort_order").FindAndCount(&resp.List) + return +} + +func (a *AlertOverviewSvc) Delete(ids []int) (err error) { + db, err := client.GetDbClient() + if err != nil { + return + } + _, err = db.NewSession().In("class_id", ids).Delete(&entity.AlertOverview{}) + return +} diff --git a/src/service/component_dict.go b/src/service/component_dict.go index 710f4afb01f49e1532e0f0a020be954136c97dfe..eb9335548cf97fb79e7909a7d2bce5c7a22ac385 100644 --- a/src/service/component_dict.go +++ b/src/service/component_dict.go @@ -55,16 +55,16 @@ func (c *Dict) Check(id, parentId string, name string) (err error) { return } -func (c *Dict) List(req request.DictReq) (dictListRes []*response.DictListRes, err error) { +func (c *Dict) List(req request.DictReq) (dictListRes []*response.DictListRes, count int64, err error) { db, err := client.GetDbClient() if err != nil { err = resp.DbConnectError.WithError(err) - return dictListRes, err + return dictListRes, 0, err } session := db.NewSession() - session.Select("id,class,name,parent_id,status,min_val,max_val,sort").Table("dict") + session.Select("id,class,name,parent_id,status,min_val,max_val,sort,description,updated_at,unit,built_in").Table("dict") session.Where("is_delete = 0 ") if req.Id != "" { @@ -79,10 +79,15 @@ func (c *Dict) List(req request.DictReq) (dictListRes []*response.DictListRes, e if req.Status != 0 { session.Where("status = ? ", req.Status) } + if req.Search != "" { + keyword := util.SpecialEscape(req.Search) + session.Where("name like ?", "%"+keyword+"%") + } - err = session.OrderBy(" class,sort").Find(&dictListRes) + count, err = session.OrderBy(" class,sort").Limit(req.GetPageSize(), (req.GetPage()-1)*req.GetPageSize()). + FindAndCount(&dictListRes) if err != nil { - return dictListRes, resp.DbSelectError.WithError(err) + return dictListRes, 0, resp.DbSelectError.WithError(err) } return } @@ -90,9 +95,9 @@ func (c *Dict) List(req request.DictReq) (dictListRes []*response.DictListRes, e func (c *Dict) DictTree(req request.DictTreeReq) (componentDictTreeRes []*response.DictListRes, err error) { listReq := request.DictReq{ Class: req.Class, - ParentId: "", + ParentId: req.ParentId, } - componentDictList, err := c.List(listReq) + componentDictList, _, err := c.List(listReq) if err != nil { return } @@ -143,6 +148,7 @@ func (c *Dict) Add(req request.AddDictReq) (err error) { UpdatedAt: jsontime.Time(time.Now()), MinVal: req.MinVal, MaxVal: req.MaxVal, + Unit: req.Unit, } db, err := client.GetDbClient() @@ -180,7 +186,7 @@ func (c *Dict) Update(req request.UpdateDictReq) (err error) { req.UpdatedAt = jsontime.Time(time.Now()) _, err = session.Table("dict"). - Cols("name,status,description,updated_by,updated_at,min_val,max_val"). + Cols("name,status,description,updated_by,updated_at,min_val,max_val,unit"). Where("id = ? and is_delete = 0", req.Id).Update(&req) if err != nil { err = errors.Wrap(err, "修改字典失败!") @@ -263,6 +269,23 @@ func (c *Dict) DictSort(req []request.DictSortInput) error { return err } +func (d *Dict) UpdateStatus(id string, status string) (total int64, err error) { + db, err := client.GetDbClient() + if err != nil { + return 0, resp.DbConnectError.ErrorDetail(err) + } + + total, err = db.Table("dict").Where("id = ? and is_delete = 0 ", id).Update(map[string]interface{}{ + "status": status, + "updated_by": d.User.Id, + }) + if err != nil { + conf.Logger.Error("Update UpdateStatus ", zap.String("erro", err.Error())) + return 0, resp.DbUpdateError.ErrorDetail(err) + } + return +} + //func (c *Dict) ManageList(req request.DictManageListReq) (componentDictTreeRes []*response.DictListRes, err error) { // listReq := request.DictReq{ // Class: req.Class, diff --git a/src/service/host_manage.go b/src/service/host_manage.go index 93a28060b1d513bcd6671fff129c696e4b5da320..6e0ba25fe60876583b37bdf5952a1f51cdb41239 100644 --- a/src/service/host_manage.go +++ b/src/service/host_manage.go @@ -117,8 +117,15 @@ func (h *HostManageSvc) AddHostManage(req request.AddHostManageReq) (err error) return } - hostsIp := fmt.Sprintf("%s ansible_ssh_host=%s ansible_ssh_port=%s ansible_ssh_user=\"%s\" ansible_ssh_pass=\"%s\"", - AnsibleIp+fmt.Sprintf("%d", hostManageList.Id), v.Ip, v.Port, v.UserName, v.Password) + hostsIp := "" + if v.VoucherType == 0 { + hostsIp = fmt.Sprintf("%s ansible_ssh_host=%s ansible_ssh_port=%s ansible_ssh_user=\"%s\" ansible_ssh_pass=\"%s\"", + AnsibleIp+fmt.Sprintf("%d", hostManageList.Id), v.Ip, v.Port, v.UserName, v.Password) + } else { + hostsIp = fmt.Sprintf("%s ansible_ssh_host=%s ansible_ssh_port=%s ansible_ssh_user=\"%s\" ansible_ssh_private_key_file=/root/.ssh/id_rsa", + AnsibleIp+fmt.Sprintf("%d", hostManageList.Id), v.Ip, v.Port, v.UserName) + } + hosts["["+AnsibleGroup+fmt.Sprintf("%d", hostManage.Id)+"]"] = append(hosts["["+AnsibleGroup+fmt.Sprintf("%d", hostManage.Id)+"]"], hostsIp) } @@ -219,8 +226,15 @@ func (h *HostManageSvc) EditHostManage(req request.EditHostManageReq) (err error return } - hostsIp := fmt.Sprintf("%s ansible_ssh_host=%s ansible_ssh_port=%s ansible_ssh_user=\"%s\" ansible_ssh_pass=\"%s\"", - AnsibleIp+fmt.Sprintf("%d", hostManageList.Id), v.Ip, v.Port, v.UserName, v.Password) + hostsIp := "" + if v.VoucherType == 0 { + hostsIp = fmt.Sprintf("%s ansible_ssh_host=%s ansible_ssh_port=%s ansible_ssh_user=\"%s\" ansible_ssh_pass=\"%s\"", + AnsibleIp+fmt.Sprintf("%d", hostManageList.Id), v.Ip, v.Port, v.UserName, v.Password) + } else { + hostsIp = fmt.Sprintf("%s ansible_ssh_host=%s ansible_ssh_port=%s ansible_ssh_user=\"%s\" ansible_ssh_private_key_file=/root/.ssh/id_rsa", + AnsibleIp+fmt.Sprintf("%d", hostManageList.Id), v.Ip, v.Port, v.UserName) + } + hosts["["+AnsibleGroup+fmt.Sprintf("%d", req.Id)+"]"] = append(hosts["["+AnsibleGroup+fmt.Sprintf("%d", req.Id)+"]"], hostsIp) } @@ -396,23 +410,47 @@ func (h *HostManageSvc) ListStateHostManage(req request.StateHostManageReq) (err return } - //往hosts文件中写入主机组ip - //f, err := os.OpenFile("/etc/ansible/hosts", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0777) - //if err != nil { - // err = resp.FileExecError.WithError(err) - // return - //} - //defer f.Close() - //_, err = f.Write([]byte(fmt.Sprintf("%s%d\n", AnsibleGroup, req.Id))) - //if err != nil { - // return resp.FileExecError.WithError(err) - //} - //for _, v := range hostManageList { - // _, err = f.Write([]byte(fmt.Sprintf("%s ansible_ssh_host=%s ansible_ssh_port=%s ansible_ssh_user=\"%s\" ansible_ssh_pass=\"%s\"\n", v.Ip, v.Ip, v.Port, v.UserName, v.Password))) - // if err != nil { - // return resp.FileExecError.WithError(err) - // } - //} + //读取hosts中的主机组 + hosts, err := tools.HostsToJson() + if err != nil { + err = resp.MarshalError.WithError(err) + session.Rollback() + return + } + if _, ok := hosts["["+AnsibleGroup+fmt.Sprintf("%d", req.Id)+"]"]; !ok { + // 不存在 + hosts["["+AnsibleGroup+fmt.Sprintf("%d", req.Id)+"]"] = nil + } + //新增主机分组列表 + for _, v := range hostManageList { + hostsIp := "" + if v.VoucherType == 0 { + hostsIp = fmt.Sprintf("%s ansible_ssh_host=%s ansible_ssh_port=%s ansible_ssh_user=\"%s\" ansible_ssh_pass=\"%s\"", + AnsibleIp+fmt.Sprintf("%d", v.Id), v.Ip, v.Port, v.UserName, v.Password) + } else { + hostsIp = fmt.Sprintf("%s ansible_ssh_host=%s ansible_ssh_port=%s ansible_ssh_user=\"%s\" ansible_ssh_private_key_file=/root/.ssh/id_rsa", + AnsibleIp+fmt.Sprintf("%d", v.Id), v.Ip, v.Port, v.UserName) + } + + flag := 0 + for _, v1 := range hosts["["+AnsibleGroup+fmt.Sprintf("%d", req.Id)+"]"] { + if v1 == hostsIp { + flag = 1 + } + } + if flag == 0 { + hosts["["+AnsibleGroup+fmt.Sprintf("%d", req.Id)+"]"] = append(hosts["["+AnsibleGroup+fmt.Sprintf("%d", req.Id)+"]"], hostsIp) + } + } + + //写入hosts + err = tools.MapToSaveHosts(hosts) + if err != nil { + err = resp.MarshalError.WithError(err) + session.Rollback() + return + } + for _, v := range hostManageList { //修改状态 _, err = session.Table("host_manage_list").Where("is_delete = 0 AND id = ?", v.Id). @@ -473,7 +511,14 @@ func (h *HostManageSvc) SaveStateHostManage(hostManageList []request.HostManageL for _, v := range hostManageListCaches { - hostsIp := fmt.Sprintf("%s ansible_ssh_host=%s ansible_ssh_port=%s ansible_ssh_user=\"%s\" ansible_ssh_pass=\"%s\"", AnsibleIp+v.Ip, v.Ip, v.Port, v.UserName, v.Password) + hostsIp := "" + if v.VoucherType == 0 { + hostsIp = fmt.Sprintf("%s ansible_ssh_host=%s ansible_ssh_port=%s ansible_ssh_user=\"%s\" ansible_ssh_pass=\"%s\"", + AnsibleIp+v.Ip, v.Ip, v.Port, v.UserName, v.Password) + } else { + hostsIp = fmt.Sprintf("%s ansible_ssh_host=%s ansible_ssh_port=%s ansible_ssh_user=\"%s\" ansible_ssh_private_key_file=/root/.ssh/id_rsa", + AnsibleIp+v.Ip, v.Ip, v.Port, v.UserName) + } flag := 0 for _, v1 := range hosts["["+AnsibleGroup+"]"] { if v1 == hostsIp { diff --git a/src/service/log_management.go b/src/service/log_management.go new file mode 100644 index 0000000000000000000000000000000000000000..467f08ce2cf19fd25a77ebb6809854d54e26262f --- /dev/null +++ b/src/service/log_management.go @@ -0,0 +1,459 @@ +package service + +import ( + "bufio" + "errors" + "fmt" + "github.com/spf13/cast" + "github.com/tealeg/xlsx" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/bean/entity" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/bean/vo/request" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/bean/vo/response" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/common/client" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/common/conf" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/common/tools" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/constant" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/jsontime" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/resp" + "gitlab.wodcloud.com/smart-operation/so-operation-api/src/util" + "os" + "sort" + "strconv" + "strings" + "time" + + "go.uber.org/zap" +) + +type LogManagement struct { + User entity.SystemUserInfo +} + +func (s *LogManagement) GetSysLogDir(search string) ([]string, error) { + file, err := os.Open(conf.Options.LogDirPrefix) + if err != nil { + zap.L().Error("open file err:", zap.Error(err)) + return nil, resp.ReadFileError.WithError(err) + } + names, err := file.Readdirnames(0) + if err != nil { + zap.L().Error("read dirnames err:", zap.Error(err)) + return nil, resp.ReadFileError.WithError(err) + } + if search != "" { + var filterdNames []string + for i := range names { + if strings.Index(names[i], search) >= 0 { + filterdNames = append(filterdNames, names[i]) + } + } + sort.Slice(filterdNames, func(i, j int) bool { + st := strings.Index(filterdNames[i], "-") + ed := strings.Index(filterdNames[i], ".") + di, _ := time.Parse("2006-01-02", filterdNames[i][st+1:ed]) + dj, _ := time.Parse("2006-01-02", filterdNames[j][st+1:ed]) + return di.After(dj) + }) + return filterdNames, nil + } + sort.Slice(names, func(i, j int) bool { + st := strings.Index(names[i], "-") + ed := strings.Index(names[i], ".") + di, _ := time.Parse("2006-01-02", names[i][st+1:ed]) + dj, _ := time.Parse("2006-01-02", names[j][st+1:ed]) + return di.After(dj) + }) + return names, nil +} + +func (s *LogManagement) GetSysLog(logLevel, search, logName string) ([]string, error) { + log, err := os.Open(conf.Options.LogDirPrefix + "/" + logName) + if err != nil { + zap.L().Error("open file err", zap.Error(err)) + return nil, resp.ReadFileError.WithError(err) + } + var logArr []string + reader := bufio.NewReader(log) + for { + rawLine, _, _ := reader.ReadLine() + if len(rawLine) == 0 { + break + } + flag1, flag2 := true, true + line := string(rawLine) + if search != "" { + if strings.Index(line, search) < 0 { + flag1 = false + } + } + if logLevel != "" { + if strings.Index(line, fmt.Sprintf(`"level":"%s"`, strings.ToUpper(logLevel))) < 0 { + flag2 = false + } + } + if flag1 && flag2 { + logArr = append(logArr, line) + } + } + return logArr, nil +} + +// 用户行为审计列表 +func (s *LogManagement) LogUserBehaviorList(params *request.LogUserBehaviorListReq) (list []response.SystemUserBehaviorList, total int64, err error) { + db, err := client.GetDbClient() + if err != nil { + err = resp.DbConnectError.ErrorDetail(err) + return nil, 0, err + } + modelObj := db.Table("system_user_behavior").Alias("sub") + modelObj.Join("INNER", []string{"system_user", "su"}, "sub.user_id = su.id") + modelObj.Join("INNER", []string{"system_organization", "so"}, "so.organization_id = so.organization_id") + modelObj.Select("sub.*, su.system_account, su.phone, so.name as org_name") + // 条件查询 + if params.Search != "" { + keyword := util.SpecialEscape(params.Search) + modelObj.Where("system_account like ? or system_module like ? or operate_addr like ?", "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%") + } + // 上次访问时间 + if params.StartAt != "" && params.EndAt != "" { + applyEndTime, timeErr := time.Parse(jsontime.LocalDateFormat, params.EndAt) + if timeErr != nil { + conf.Logger.Error("时间转换错误", zap.Error(timeErr)) + return nil, 0, resp.DbSelectError.ErrorDetail(timeErr) + } + EndAt := applyEndTime.AddDate(0, 0, 1).Format(jsontime.LocalDateFormat) + modelObj.Where("last_access_time >= ? and last_access_time < ?", params.StartAt, EndAt) + } + // 操作类型 + if params.OperateType != "" { + modelObj.Where("operate_type = ?", params.OperateType) + } + // 请求方式 + if params.ReqMethod != 0 { + modelObj.Where("req_method = ?", params.ReqMethod) + } + // 操作状态 + if params.OperateStatus != 0 { + modelObj.Where("operate_status = ?", params.OperateStatus) + } + total, err = modelObj.OrderBy("created_time desc").Limit(params.GetPageSize(), params.GetOffset()).FindAndCount(&list) + if err != nil { + conf.Logger.Error("查询用户行为审计列表失败", zap.Error(err)) + err = resp.DbSelectError.WithError(errors.New("查询用户行为审计列表失败")) + return nil, 0, err + } + return list, total, nil +} + +// 用户行为审计导出 +func (s *LogManagement) LogUserBehaviorListExport(params *request.LogUserBehaviorListReq) (xlFile *xlsx.File, fileName string, err error) { + xlFile = xlsx.NewFile() + sheet, err := xlFile.AddSheet("sheet") + if err != nil { + return nil, "", resp.AddSheetError.ErrorDetail(err) + } + titleRow := sheet.AddRow() + tmp := []string{ + "序号", "账号", "手机号", "所属组织", "系统模块", "操作类型", "请求方式", "操作状态", "操作地址", "操作地点", "请求地址", "请求参数", "操作方法", "返回参数", "操作时间", + } + xlsRow2 := tools.NewRow(titleRow, tmp) + err = xlsRow2.SetRowTitle() + if err != nil { + return + } + var ( + list []response.SystemUserBehaviorList + total int64 + ) + + list, total, err = s.LogUserBehaviorList(params) + + if err != nil { + return nil, "", resp.DbSelectError.ErrorDetail(err) + } + if total == 0 { + return nil, "", resp.DbSelectError.ErrorDetail(errors.New("没有可导出的数据")) + } + fileName = "用户行为审计" + ".xlsx" + id := 0 + for _, detail := range list { + id += 1 + currentRow := sheet.AddRow() + var tmp = []string{ + strconv.Itoa(id), detail.SystemAccount, detail.Phone, detail.OrgName, detail.SystemModule, detail.OperateType, + constant.HttpMethodStrMap[detail.ReqMethod], constant.OperateStatusStrMap[detail.OperateStatus], detail.OperateIp, detail.OperateAddr, + detail.ReqUrl, detail.ReqParam, constant.HttpMethodStrMap[detail.ReqMethod], detail.ResFields, cast.ToString(detail.CreatedTime), + } + newRow := tools.NewRow(currentRow, tmp) + err := newRow.GenerateRow() + if err != nil { + return nil, "", resp.AddSheetError.ErrorDetail(err) + } + } + return +} + +// 用户行为审计详情 +func (s *LogManagement) LogUserBehaviorDetail(id string) (data *response.LogUserBehaviorDetailRep, err error) { + + db, err := client.GetDbClient() + if err != nil { + err = resp.DbConnectError.ErrorDetail(err) + return nil, err + } + data = new(response.LogUserBehaviorDetailRep) + modelObj := db.Table("system_user_behavior").Alias("sub") + modelObj.Join("INNER", []string{"system_user", "su"}, "sub.user_id = su.id") + modelObj.Join("INNER", []string{"system_organization", "so"}, "so.organization_id = su.organization_id") + modelObj.Select("sub.*, su.system_account, su.phone, so.name as org_name") + _, err = modelObj.Where("sub.id = ?", id).And("sub.is_deleted = 0").Get(data) + if err != nil { + conf.Logger.Error("获取用户行为审计详情失败", zap.Error(err)) + return nil, resp.DbSelectError.ErrorDetail(err) + } + data.OperateStatusStr = constant.OperateStatusStrMap[data.OperateStatus] + data.ReqMethodStr = constant.HttpMethodStrMap[data.ReqMethod] + //data.UserType = constant.UserTypeStrMap[data.IsAdmin] + return data, nil + +} + +func (s *LogManagement) LogUserBehaviorDelete(ids []string) (err error) { + + db, err := client.GetDbClient() + if err != nil { + return resp.DbConnectError.ErrorDetail(err) + } + _, err = db.Table("system_user_behavior").In("id", ids).Update(&map[string]interface{}{"is_deleted": 1}) + if err != nil { + return resp.DbDeleteError.ErrorDetail(err) + } + + return nil +} + +//// LogUserAccountAuditList 行为日志列表 +//func (s *LogManagement) LogUserAccountAuditList(params *request.LogManagementListReq) ([]response.LogManagementRep, int64, error) { +// var logManagementRep = []response.LogManagementRep{} +// db, err := client.GetDbClient() +// if err != nil { +// err = res.DbConnectError.ErrorDetail(err) +// return nil, 0, err +// } +// +// modelObj := db.Table("system_user as u") +// modelObj.Join("left", "system_organization as org", "u.organization_id = org.organization_id"). +// Select(`u.ID, +// system_account, +// contact_phone, +// case is_admin when 1 then '业务系统账号' when 2 then '组织管理员账号' when 3 then '平台用户账号' when 4 then '超级管理员' end as is_admin, +// NAME, +// u.organization_id, +// last_access_time, +// case pwd_level when 1 then '弱' when 2 then '中' when 3 then '强' end as pwd_level, +// pwd_updated_time, +// date_part('day', now()-pwd_updated_time)as pwd_is_used , +// u.created_time `) +// +// // 条件查询 +// if params.Search != "" { +// keyword := util.SpecialEscape(params.Search) +// modelObj.Where("system_account ilike ? or contact_phone ilike ? or NAME ilike ?", "%"+keyword+"%", "%"+keyword+"%", "%"+keyword+"%") +// } +// // 用户类型 +// if params.IsAdmin != 0 { +// modelObj.Where("is_admin = ?", params.IsAdmin) +// } +// // 上次访问时间 +// if params.StartAt != "" && params.EndAt != "" { +// applyEndTime, timeErr := time.Parse(jsonTime.LocalDateFormat, params.EndAt) +// if timeErr != nil { +// conf.Logger.Error("时间转换错误", zap.Error(timeErr)) +// return nil, 0, res.DataFailError.ErrorDetail(timeErr) +// } +// EndAt := applyEndTime.AddDate(0, 0, 1).Format(jsonTime.LocalDateFormat) +// modelObj.Where("last_access_time >= ? and last_access_time < ?", params.StartAt, EndAt) +// } +// // 活跃度 1: 低 2:中 3: 高 +// if params.Active != 0 { +// switch params.Active { +// case 1: +// modelObj.Where("last_access_time <= now()-interval '1 month'") +// case 2: +// modelObj.Where("last_access_time < now()-interval '1 week'").And("last_access_time > now()-interval '1 month'") +// case 3: +// modelObj.Where("last_access_time >= now()-interval '1 week'") +// } +// } +// // 密码强度 +// if params.PwdLevel != 0 { +// modelObj.Where("pwd_level = ? ", params.PwdLevel) +// } +// count, err := modelObj.OrderBy("last_access_time desc").Limit(int(params.Limit), int(params.Offset)).FindAndCount(&logManagementRep) +// if err != nil { +// conf.Logger.Error("查询用户账户审计列表失败", zap.Error(err)) +// err = res.DbSelectError.ErrorDetail(errors.New("查询用户账户审计列表失败")) +// return nil, 0, err +// } +// for k := range logManagementRep { +// // lastAccessTime := cast.ToTime(logManagementRep[k].LastAccessTimes) +// active := getActivity(logManagementRep[k].LastAccessTimes) +// logManagementRep[k].Active = active +// logManagementRep[k].LastAccessTime = jsonTime.JsonTime(logManagementRep[k].LastAccessTimes) +// } +// +// return logManagementRep, count, nil +//} +// +//func getActivity(date time.Time) string { +// // dates := cast.ToTime(date) +// var ( +// lastAccess = date.Unix() +// pastWeek = time.Now().AddDate(0, 0, -7).Unix() +// pastMonth = time.Now().AddDate(0, -1, 0).Unix() +// ) +// if lastAccess >= pastWeek { +// return "高" +// } +// if lastAccess < pastWeek && lastAccess > pastMonth { +// return "中" +// } +// if lastAccess <= pastMonth { +// return "低" +// } +// return "不活跃" +//} +// +//// LogUserAccountAuditExport 行为日志导出 +//func (s *LogManagement) LogUserAccountAuditExport(params *request.LogManagementListReq) (xlFile *xlsx.File, fileName string, err error) { +// xlFile = xlsx.NewFile() +// sheet, err := xlFile.AddSheet("sheet") +// if err != nil { +// conf.Logger.Error("xlFile.AddSheet err", zap.Error(err)) +// return +// } +// titleRow := sheet.AddRow() +// tmp := []string{ +// "序号", "账号", "手机号", "用户类型", "所属组织", "上次访问时间", "活跃度", "密码强度", "密码使用时长/天", "创建时间", +// } +// xlsRow2 := tools.NewRow(titleRow, tmp) +// err = xlsRow2.SetRowTitle() +// if err != nil { +// return +// } +// params.Page = 0 +// params.Limit = 20000 +// list, total, err := s.LogUserAccountAuditList(params) +// if total == 0 { +// err = errors.New("没有可导出的数据") +// return +// } else { +// fileName = "用户账号审计" + ".xlsx" +// } +// id := 0 +// for _, detail := range list { +// id += 1 +// currentRow := sheet.AddRow() +// var tmp = []string{ +// strconv.Itoa(id), detail.SystemAccount, detail.ContactPhone, detail.IsAdmin, detail.Name, cast.ToString(detail.LastAccessTime), +// detail.Active, detail.PwdLevel, strconv.Itoa(detail.PwdIsUsed), cast.ToString(detail.CreatedTime), +// } +// newRow := tools.NewRow(currentRow, tmp) +// err := newRow.GenerateRow() +// if err != nil { +// return nil, "", err +// } +// } +// return +//} +// +//// 用户行为审计列表 +//func (s *LogManagement) LogUserBehaviorListEs(params *request.LogUserBehaviorListReq) (list []response.SystemUserBehaviorList, total int64, err error) { +// es, err := client.GetEsConnection(conf.EsDoc.Index) +// if err != nil { +// return nil, 0, res.DbConnectError.ErrorDetail(err) +// } +// // boolQuery 可用于组合查询 +// boolQuery := elastic.NewBoolQuery() +// // 条件查询 +// if params.Search != "" { +// keyword := util.SpecialEscape(params.Search) +// boolQuery.Filter( +// elastic.NewBoolQuery().Should( +// elastic.NewWildcardQuery("system_account.keyword", fmt.Sprintf("*%s*", keyword)), +// elastic.NewWildcardQuery("system_module.keyword", fmt.Sprintf("*%s*", keyword)), +// elastic.NewWildcardQuery("operate_addr.keyword", fmt.Sprintf("*%s*", keyword)), +// )) +// } +// // 用户类型 +// if params.IsAdmin != 0 { +// boolQuery.Filter(elastic.NewMatchQuery("is_admin", params.IsAdmin)) +// } +// // 上次访问时间 +// if params.StartAt != "" && params.EndAt != "" { +// applyEndTime, timeErr := time.Parse(jsonTime.LocalDateFormatEs, params.EndAt) +// if timeErr != nil { +// conf.Logger.Error("时间转换错误", zap.Error(timeErr)) +// return nil, 0, res.DataFailError.ErrorDetail(timeErr) +// } +// EndAt := applyEndTime.AddDate(0, 0, 1).Format(jsonTime.LocalDateFormatEs) +// boolQuery.Filter(elastic.NewRangeQuery("created_time").Gte(params.StartAt)) +// boolQuery.Filter(elastic.NewRangeQuery("created_time").Lt(EndAt)) +// } +// // 操作类型 +// if params.OperateType != "" { +// boolQuery.Filter(elastic.NewMatchQuery("operate_type", params.OperateType)) +// } +// // 请求方式 +// if params.ReqMethod != 0 { +// boolQuery.Filter(elastic.NewMatchQuery("req_method", params.ReqMethod)) +// } +// // 操作状态 +// if params.OperateStatus != 0 { +// boolQuery.Filter(elastic.NewMatchQuery("operate_status", params.OperateStatus)) +// } +// searchResult, err := es.Conn.Search(). +// Index(conf.EsDoc.Index). +// Query(boolQuery). +// SortWithInfo(elastic.SortInfo{Field: "created_time_unix", Ascending: false, UnmappedType: "keyword"}). +// From(int((params.Page - 1) * params.Limit)).Size(cast.ToInt(params.Limit)). +// Pretty(true). +// Do(context.Background()) +// if err != nil { +// conf.Logger.Error("查询用户行为审计列表失败", zap.Error(err)) +// return nil, 0, res.DbSelectError.ErrorDetail(err) +// } +// bytes, err := json.Marshal(searchResult) +// if err != nil { +// conf.Logger.Error("json.Marshal序列化用户行为信息失败", zap.Error(err)) +// return nil, 0, res.JsonMarshalError.ErrorDetail(err) +// } +// resultMap := map[string]interface{}{} +// err = json.Unmarshal(bytes, &resultMap) +// if err != nil { +// conf.Logger.Error("序列化用户行为信息失败", zap.Error(err)) +// return nil, 0, res.JsonMarshalError.ErrorDetail(err) +// } +// data, has := resultMap["hits"] +// esData := response.BehaviorEsListInfo{} +// if has { +// bytes, err := json.Marshal(data) +// if err != nil { +// conf.Logger.Error("序列化用户行为信息失败", zap.Error(err)) +// return nil, 0, err +// } +// err = json.Unmarshal(bytes, &esData) +// if err != nil { +// conf.Logger.Error("序列化用户行为信息失败", zap.Error(err)) +// return nil, 0, err +// } +// for k, v := range esData.Hits { +// esData.Hits[k].Source.Id = v.Id +// esData.Hits[k].Source.Xh = (params.Page) * int64(k+1) +// list = append(list, esData.Hits[k].Source) +// } +// } +// total = cast.ToInt64(esData.Total["value"]) +// return list, total, nil +//} +// diff --git a/src/service/task_manage.go b/src/service/task_manage.go index c22ea385d736037731ea002fe317961233d4b785..f64e1542e535bd01b6c1a0ae1ea5fe31385de010 100644 --- a/src/service/task_manage.go +++ b/src/service/task_manage.go @@ -163,7 +163,7 @@ func (t *TaskManageSvc) ListTaskManage(req request.ListTaskManageReq) (total int finder := db.Table("task_manage").Alias("tm").Where("tm.is_delete = 0") if req.Search != "" { - finder.Where(fmt.Sprintf("(tm.task_name LIKE %s OR tm.task_desc LIKE %s OR tm.create_user LIKE %s)", + finder.Where(fmt.Sprintf("(tm.task_name LIKE '%s' OR tm.task_desc LIKE '%s' OR tm.create_user LIKE '%s')", "%"+req.Search+"%", "%"+req.Search+"%", "%"+req.Search+"%")) } if req.CreateDateFrom != "" { diff --git a/src/service/work_order.go b/src/service/work_order.go index 6a9817fc8f237d44ba6c8d7980f1ff3561528003..9d8abf0134fe77e49b9be0da50c40a2612b81b03 100644 --- a/src/service/work_order.go +++ b/src/service/work_order.go @@ -160,7 +160,7 @@ func (w *WorkOrderManageSvc) DelWorkOrderManage(req request.DelWorkOrderReq) (er } // DetailsWorkOrderManage 详情 -func (w *WorkOrderManageSvc) DetailsWorkOrderManage(id int) (taskManageRes response.WorkOrderRes, err error) { +func (w *WorkOrderManageSvc) DetailsWorkOrderManage(id int) (workOrderRes response.WorkOrderRes, err error) { db, err := client.GetDbClient() if err != nil { err = resp.DbConnectError.WithError(err) @@ -170,33 +170,50 @@ func (w *WorkOrderManageSvc) DetailsWorkOrderManage(id int) (taskManageRes respo //查询任务详情 var workOrder entity.WorkOrder finder := db.Table("work_order_manage").Where("id = ?", id) - _, err = finder.Get(&workOrder) + has, err := finder.Get(&workOrder) if err != nil { err = resp.DbSelectError.WithError(err) return } - - err = json.Unmarshal([]byte(workOrder.PushObj), &taskManageRes.PushObj) - if err != nil { - err = resp.FAIL.WithError(err) + if !has { + err = resp.DbSelectError.WithError(errors.New("查询为空")) return } - err = json.Unmarshal([]byte(workOrder.TimingRule), &taskManageRes.TimingRule) + + err = json.Unmarshal([]byte(workOrder.PushObj), &workOrderRes.PushObj) if err != nil { err = resp.FAIL.WithError(err) return } - taskManageRes.Id = workOrder.Id - taskManageRes.OrderName = workOrder.OrderName - taskManageRes.OrderLevel = workOrder.OrderLevel - taskManageRes.OrderDesc = workOrder.OrderDesc - taskManageRes.TimingState = workOrder.TimingState - taskManageRes.TimingType = workOrder.TimingType - taskManageRes.CreateUser = workOrder.CreateUser - taskManageRes.CreateTime = workOrder.CreateTime - taskManageRes.UpdateUser = workOrder.UpdateUser - taskManageRes.UpdateUser = workOrder.UpdateUser - taskManageRes.UpdateTime = workOrder.UpdateTime + if workOrder.TimingType == 2 { + var timingWeekly request.TimingWeekly + err = json.Unmarshal([]byte(workOrder.TimingRule), &timingWeekly) + if err != nil { + err = resp.FAIL.WithError(err) + return + } + workOrderRes.TimingRule = timingWeekly + } else if workOrder.TimingType == 3 { + var timingCustom []request.TimingCustom + err = json.Unmarshal([]byte(workOrder.TimingRule), &timingCustom) + if err != nil { + err = resp.FAIL.WithError(err) + return + } + workOrderRes.TimingRule = timingCustom + } + + workOrderRes.Id = workOrder.Id + workOrderRes.OrderName = workOrder.OrderName + workOrderRes.OrderLevel = workOrder.OrderLevel + workOrderRes.OrderDesc = workOrder.OrderDesc + workOrderRes.TimingState = workOrder.TimingState + workOrderRes.TimingType = workOrder.TimingType + workOrderRes.CreateUser = workOrder.CreateUser + workOrderRes.CreateTime = workOrder.CreateTime + workOrderRes.UpdateUser = workOrder.UpdateUser + workOrderRes.UpdateUser = workOrder.UpdateUser + workOrderRes.UpdateTime = workOrder.UpdateTime return } @@ -211,7 +228,7 @@ func (w *WorkOrderManageSvc) ListWorkOrderManage(req request.ListWorkOrderManage finder := db.Table("work_order_manage") if req.Search != "" { - finder.Where(fmt.Sprintf("order_name LIKE %s", "%"+req.Search+"%")) + finder.Where(fmt.Sprintf("order_name LIKE '%s'", "%"+req.Search+"%")) } if req.OrderLevel != 0 { finder.Where("order_level = ?", req.OrderLevel) @@ -364,7 +381,7 @@ func (w *WorkOrderManageSvc) ListWorkOrderIssuance(req request.ListWorkOrderReq) Join("INNER", "work_order_manage wom", "woi.order_id = wom.id") if req.Search != "" { - finder.Where(fmt.Sprintf("wom.order_name LIKE %s", "%"+req.Search+"%")) + finder.Where(fmt.Sprintf("wom.order_name LIKE '%s'", "%"+req.Search+"%")) } if req.OrderLevel != 0 { finder.Where("wom.order_level = ?", req.OrderLevel) @@ -379,7 +396,7 @@ func (w *WorkOrderManageSvc) ListWorkOrderIssuance(req request.ListWorkOrderReq) finder.Where("woi.create_time <= ?", req.CreateDateTo) } if req.CompleteTimeFrom != "" { - finder.Where("woi.complete_time <= ?", req.CompleteTimeFrom) + finder.Where("woi.complete_time >= ?", req.CompleteTimeFrom) } if req.CompleteTimeTo != "" { finder.Where("woi.complete_time <= ?", req.CompleteTimeTo) @@ -424,12 +441,15 @@ func (w *WorkOrderManageSvc) DetailsWorkOrderIssuance(id int) (workOrderIssuance var workOrderIssuance response.WorkOrderIssuance finder := db.Table("work_order_issuance").Alias("woi"). Join("INNER", "work_order_manage wom", "woi.order_id = wom.ID").Where("woi.id = ?", id) - _, err = finder.Select("woi.\"id\",woi.order_id,wom.order_name,wom.order_level,wom.order_desc,woi.order_state,woi.push_obj,woi.create_user,woi.create_time,woi.complete_time"). + has, err := finder.Select("woi.\"id\",woi.order_id,wom.order_name,wom.order_level,wom.order_desc,woi.order_state,woi.push_obj,woi.create_user,woi.create_time,woi.complete_time"). Get(&workOrderIssuance) if err != nil { err = resp.DbSelectError.WithError(err) return } + if !has { + return + } //var workOrderMe entity.WorkOrderMe finder1 := db.Table("work_order_me").Where("order_issuance_id = ?", id) @@ -521,7 +541,7 @@ func (w *WorkOrderManageSvc) ListWorkOrderMe(req request.ListWorkOrderReq) (tota Join("INNER", "work_order_manage wom", "woi.order_id = wom.id") if req.Search != "" { - finder.Where(fmt.Sprintf("wom.order_name LIKE %s", "%"+req.Search+"%")) + finder.Where(fmt.Sprintf("wom.order_name LIKE '%s'", "%"+req.Search+"%")) } if req.OrderLevel != 0 { finder.Where("wom.order_level = ?", req.OrderLevel) @@ -536,7 +556,7 @@ func (w *WorkOrderManageSvc) ListWorkOrderMe(req request.ListWorkOrderReq) (tota finder.Where("woi.create_time <= ?", req.CreateDateTo) } if req.CompleteTimeFrom != "" { - finder.Where("wome.complete_time <= ?", req.CompleteTimeFrom) + finder.Where("wome.complete_time >= ?", req.CompleteTimeFrom) } if req.CompleteTimeTo != "" { finder.Where("wome.complete_time <= ?", req.CompleteTimeTo)