Commit fbd6e370 authored by 魏灿's avatar 魏灿

Merge remote-tracking branch 'origin/dev' into dev

parents 82d16aba 58190720
...@@ -3,15 +3,15 @@ package entity ...@@ -3,15 +3,15 @@ package entity
import "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/jsontime" import "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/jsontime"
type AlertClass struct { type AlertClass struct {
ClassId int `json:"class_id" xorm:"'class_id' pk autoincr" ` // 主键id ClassId int `json:"class_id" xorm:"'class_id' pk autoincr"` // 主键id
ClassName string `json:"class_name" xorm:"'class_name'"` // 分类名称 ClassName string `json:"class_name" xorm:"'class_name'"` // 分类名称
ParentId int `json:"parent_id" xorm:"'parent_id'"` // 父级id ParentId int `json:"parent_id" xorm:"'parent_id'"` // 父级id
SortOrder int `json:"sort_order" xorm:"'sort_order'"` // 排序 SortOrder int `json:"sort_order" xorm:"'sort_order'"` // 排序
SourceFrom int `json:"source_from" xorm:"source_from"` // 数据来源 1:默认 2:自定义 SourceFrom int `json:"source_from" xorm:"source_from"` // 数据来源 1:默认 2:自定义
CreatedBy string `json:"created_by" xorm:"'created_by'"` // 创建人 CreatedBy string `json:"created_by" xorm:"'created_by'"` // 创建人
CreatedAt jsontime.Time `json:"created_at" xorm:"'created_at'"` // 创建时间 CreatedAt jsontime.Time `json:"created_at" xorm:"'created_at'"` // 创建时间
UpdatedBy string `json:"updated_by" xorm:"'updated_by'"` // 更新人 UpdatedBy string `json:"updated_by" xorm:"'updated_by'"` // 更新人
UpdatedAt jsontime.Time `json:"updated_at" xorm:"'updated_at'"` // 更新时间 UpdatedAt jsontime.Time `json:"updated_at" xorm:"'updated_at'"` // 更新时间
} }
func (m *AlertClass) TableName() string { func (m *AlertClass) TableName() string {
......
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"
}
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"
}
...@@ -38,7 +38,7 @@ type RulesAlertRange struct { ...@@ -38,7 +38,7 @@ type RulesAlertRange struct {
type AlertCondition struct { type AlertCondition struct {
ThresholdsMax int `json:"thresholds_max" form:"thresholds_max" binding:"required"` ThresholdsMax int `json:"thresholds_max" form:"thresholds_max" binding:"required"`
ThresholdsMin int `json:"thresholds_min" form:"thresholds_min" 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 { type NotifyRecipients struct {
......
...@@ -37,6 +37,7 @@ type Dict struct { ...@@ -37,6 +37,7 @@ type Dict struct {
UpdatedAt jsontime.Time `json:"updated_time" xorm:"updated_at"` //修改时间 UpdatedAt jsontime.Time `json:"updated_time" xorm:"updated_at"` //修改时间
MinVal string `json:"min_val" xorm:"min_val"` //最大值 MinVal string `json:"min_val" xorm:"min_val"` //最大值
MaxVal string `json:"max_val" xorm:"max_val"` //最小值 MaxVal string `json:"max_val" xorm:"max_val"` //最小值
Unit string `json:"unit" xorm:"unit"` //单位
Sort int `json:"sort" xorm:"sort autoincr"` //排序字段 降序排列 Sort int `json:"sort" xorm:"sort autoincr"` //排序字段 降序排列
} }
......
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'"` // 更新时间
}
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"`
}
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
}
...@@ -7,6 +7,8 @@ type DictReq struct { ...@@ -7,6 +7,8 @@ type DictReq struct {
Status int `json:"status" form:"status"` 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文档类型) 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 ParentId string `json:"parent_id" form:"parent_id"` //父级ID
Search string `json:"search" form:"search"`
Pagination
} }
type DictTreeReq struct { type DictTreeReq struct {
...@@ -18,20 +20,22 @@ type AddDictReq 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文档类型) 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 ParentId string `json:"parent_id" form:"parent_id"` //父级ID
Name string `json:"name" form:"name" binding:"required"` //字典标签 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"` //描述 Description string `json:"description" form:"description" binding:"lte=200"` //描述
MinVal string `json:"min_val" form:"min_val"` //最大值 MinVal string `json:"min_val" form:"min_val"` //最大值
MaxVal string `json:"max_val" form:"max_val"` //最小值 MaxVal string `json:"max_val" form:"max_val"` //最小值
Unit string `json:"unit" form:"unit"` //最小值
} }
type UpdateDictReq struct { type UpdateDictReq struct {
Id string `json:"id" form:"id" binding:"required"` //组件ID Id string `json:"id" form:"id" binding:"required"` //组件ID
ParentId string `json:"parent_id" form:"parent_id"` //父级ID ParentId string `json:"parent_id" form:"parent_id"` //父级ID
Name string `json:"name" form:"name" binding:"required"` //字典标签 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"` //描述 Description string `json:"description" form:"description" binding:"lte=200"` //描述
MinVal string `json:"min_val" form:"min_val"` //最大值 MinVal string `json:"min_val" form:"min_val"` //最大值
MaxVal string `json:"max_val" form:"max_val"` //最小值 MaxVal string `json:"max_val" form:"max_val"` //最小值
Unit string `json:"unit" form:"unit"` //最小值
UpdatedBy int `json:"updated_by" ` //修改人 UpdatedBy int `json:"updated_by" ` //修改人
UpdatedAt jsontime.Time `json:"updated_at"` //修改时间 UpdatedAt jsontime.Time `json:"updated_at"` //修改时间
} }
...@@ -40,7 +44,7 @@ type DictManageListReq struct { ...@@ -40,7 +44,7 @@ type DictManageListReq struct {
Id string `json:"id" form:"id" binding:"required"` //组件ID Id string `json:"id" form:"id" binding:"required"` //组件ID
ParentId string `json:"parent_id" form:"parent_id"` //父级ID ParentId string `json:"parent_id" form:"parent_id"` //父级ID
Name string `json:"name" form:"name" binding:"required"` //字典标签 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"` //描述 Description string `json:"description" form:"description" binding:"lte=200"` //描述
MinVal string `json:"min_val" form:"min_val"` //最大值 MinVal string `json:"min_val" form:"min_val"` //最大值
MaxVal string `json:"max_val" form:"max_val"` //最小值 MaxVal string `json:"max_val" form:"max_val"` //最小值
......
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"` //级别
}
...@@ -19,3 +19,13 @@ func (p Pagination) GetPageSize() int { ...@@ -19,3 +19,13 @@ func (p Pagination) GetPageSize() int {
} }
return p.PageSize 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
}
...@@ -12,8 +12,8 @@ type AddWorkOrderReq struct { ...@@ -12,8 +12,8 @@ type AddWorkOrderReq struct {
// 推送对象 // 推送对象
type PushObj struct { type PushObj struct {
PushMethod int `json:"push_method" binding:"oneof=1 2 3"` // 推送方式(1钉钉 2短信 3all) PushMethod int `json:"push_method" binding:"oneof=1 2 3"` // 推送方式(1钉钉 2短信 3all)
UserObj []UserObj `json:"user_obj" binding:"oneof=1 2 3,dive"` // 用户对象 UserObj []UserObj `json:"user_obj" binding:"dive"` // 用户对象
} }
type UserObj struct { type UserObj struct {
SystemAccount string `json:"system_account" binding:"required"` // 账号 SystemAccount string `json:"system_account" binding:"required"` // 账号
......
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"`
}
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"`
}
package response package response
import "gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/jsontime"
type DictListRes struct { type DictListRes struct {
Id string `json:"id" column:"id"` //主键ID 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文档类型) 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"` //组件名称 Name string `json:"name" column:"name"` //组件名称
ParentId string `json:"parent_id" column:"parent_id"` //父id ParentId string `json:"parent_id" column:"parent_id"` //父id
Status int `json:"status"` Status int `json:"status"`
MinVal string `json:"min_val" ` //最大值 Description string `json:"description"`
MaxVal string `json:"max_val"` UpdatedAt jsontime.Time `json:"updated_at"`
Sort int `json:"sort"` MinVal string `json:"min_val" ` //最大值
Children []*DictListRes `json:"children,omitempty"` 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 { //type ComponentDictTreeRes struct {
......
...@@ -62,7 +62,7 @@ type HostManageListRes struct { ...@@ -62,7 +62,7 @@ type HostManageListRes struct {
Id int `json:"id"` // id Id int `json:"id"` // id
Ip string `json:"ip"` // ip Ip string `json:"ip"` // ip
Port string `json:"port"` // 端口 Port string `json:"port"` // 端口
VoucherType int `json:"voucher_type"` // 凭证类型(0密码验证 密钥验证) VoucherType int `json:"voucher_type"` // 凭证类型(0密码验证 1密钥验证)
UserName string `json:"user_name"` // 用户名 UserName string `json:"user_name"` // 用户名
Password string `json:"password"` // 密码 Password string `json:"password"` // 密码
} }
......
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"`
}
...@@ -35,6 +35,8 @@ type Config struct { ...@@ -35,6 +35,8 @@ type Config struct {
AccessRuleModeKey string AccessRuleModeKey string
LocationUrl string LocationUrl string
LocationKey string LocationKey string
PrivateKeySSH string
PublicKeySSH string
} }
const ( const (
......
/**
* @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
}
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)
}
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)
}
...@@ -27,13 +27,13 @@ func (d Dict) List(c *gin.Context) { ...@@ -27,13 +27,13 @@ func (d Dict) List(c *gin.Context) {
svc := new(service.Dict) svc := new(service.Dict)
svc.Ctx = c svc.Ctx = c
svc.User = header.GetUser(c) svc.User = header.GetUser(c)
result, err := svc.List(req) result, count, err := svc.List(req)
if err != nil { if err != nil {
SendJsonResponse(c, resp.InvalidParam.WithError(err), "") SendJsonResponse(c, resp.InvalidParam.WithError(err), "")
return return
} }
SendJsonResponse(c, resp.OK, result) SendJsonPageResponse(c, resp.OK, result, count)
} }
// DictTree 字典列表-树结构 // DictTree 字典列表-树结构
...@@ -194,6 +194,28 @@ func (d Dict) DictSort(c *gin.Context) { ...@@ -194,6 +194,28 @@ func (d Dict) DictSort(c *gin.Context) {
SendJsonResponse(c, resp.OK, "") 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 组件列表 // List 组件列表
//func (d Dict) ManageList(c *gin.Context) { //func (d Dict) ManageList(c *gin.Context) {
// //
......
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(&params); 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(&params)
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(&params); 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(&params)
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(&params); 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(&params)
// 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(&params); 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(&params)
// 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)
//
//}
...@@ -32,6 +32,8 @@ func main() { ...@@ -32,6 +32,8 @@ func main() {
initTempDirPrefix() initTempDirPrefix()
pflag.Parse() // init start args pflag.Parse() // init start args
initConfig() initConfig()
initAnsibleSSH()
// init log config // init log config
cfg := initLogConfig() cfg := initLogConfig()
conf.Logger = log.NewLogger(cfg, conf.LoggerLevel) conf.Logger = log.NewLogger(cfg, conf.LoggerLevel)
...@@ -75,6 +77,8 @@ func initConfig() { ...@@ -75,6 +77,8 @@ func initConfig() {
AccessRuleModeKey: "accessRuleMode", AccessRuleModeKey: "accessRuleMode",
LocationUrl: util.SetEnvStr("LOCATION_URL", "https://apis.map.qq.com/ws/location/v1/ip"), 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"), 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() { ...@@ -140,3 +144,30 @@ func initTempDirPrefix() {
fmt.Println("创建目录失败!") 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())
}
}
}
...@@ -12,6 +12,19 @@ import ( ...@@ -12,6 +12,19 @@ import (
var CSTZone = time.FixedZone("CST", 8*3600) // 固定东八区(CST: China Standard Time) 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 自定义时间 // Time 自定义时间
// 设置当前时间: jsonDate := Time(time.Now()) // 设置当前时间: jsonDate := Time(time.Now())
type Time time.Time type Time time.Time
......
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)
}
}
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)
}
}
...@@ -22,6 +22,8 @@ func initDictRoute(e *gin.Engine) { ...@@ -22,6 +22,8 @@ func initDictRoute(e *gin.Engine) {
base.GET("/tree", dict.DictTree) //字典列表-树结构 base.GET("/tree", dict.DictTree) //字典列表-树结构
base.GET("/classList", dict.ClassList) //字典分类列表 base.GET("/classList", dict.ClassList) //字典分类列表
base.PUT("/sort", dict.DictSort) //字典排序 base.PUT("/sort", dict.DictSort) //字典排序
base.PUT("/status", dict.UpdateStatus) //字典排序
//base.GET("/manage_list", dict.ManageList) //字典管理列表 //base.GET("/manage_list", dict.ManageList) //字典管理列表
} }
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])) //用户账户审计列表导出
//
//}
}
}
...@@ -49,12 +49,18 @@ func Load(r *gin.Engine, middleware ...gin.HandlerFunc) { ...@@ -49,12 +49,18 @@ func Load(r *gin.Engine, middleware ...gin.HandlerFunc) {
InitPreferenceConfigRouter(r) InitPreferenceConfigRouter(r)
// 初始化访问控制管理路由 // 初始化访问控制管理路由
InitAccessRuleRouter(r) InitAccessRuleRouter(r)
// 初始化日志管理
InitLogManagementRouter(r)
// 初始化指标配置路由 // 初始化指标配置路由
InitMetricConfigRouter(r) InitMetricConfigRouter(r)
// 初始化预警规则配置路由 // 初始化预警规则配置路由
InitAlertRulesRouter(r) InitAlertRulesRouter(r)
// 初始化预警列表配置路由
InitAlertListRouter(r)
// 初始化prometheus路由 // 初始化prometheus路由
InitPrometheusRouter(r) InitPrometheusRouter(r)
// 初始化预警总览配置路由
InitAlertOverviewRouter(r)
// 初始化工单管理路由 // 初始化工单管理路由
InitWorkOrderRouter(r) InitWorkOrderRouter(r)
} }
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
}
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
}
...@@ -55,16 +55,16 @@ func (c *Dict) Check(id, parentId string, name string) (err error) { ...@@ -55,16 +55,16 @@ func (c *Dict) Check(id, parentId string, name string) (err error) {
return 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() db, err := client.GetDbClient()
if err != nil { if err != nil {
err = resp.DbConnectError.WithError(err) err = resp.DbConnectError.WithError(err)
return dictListRes, err return dictListRes, 0, err
} }
session := db.NewSession() 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 ") session.Where("is_delete = 0 ")
if req.Id != "" { if req.Id != "" {
...@@ -79,10 +79,15 @@ func (c *Dict) List(req request.DictReq) (dictListRes []*response.DictListRes, e ...@@ -79,10 +79,15 @@ func (c *Dict) List(req request.DictReq) (dictListRes []*response.DictListRes, e
if req.Status != 0 { if req.Status != 0 {
session.Where("status = ? ", req.Status) 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 { if err != nil {
return dictListRes, resp.DbSelectError.WithError(err) return dictListRes, 0, resp.DbSelectError.WithError(err)
} }
return return
} }
...@@ -90,9 +95,9 @@ func (c *Dict) List(req request.DictReq) (dictListRes []*response.DictListRes, e ...@@ -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) { func (c *Dict) DictTree(req request.DictTreeReq) (componentDictTreeRes []*response.DictListRes, err error) {
listReq := request.DictReq{ listReq := request.DictReq{
Class: req.Class, Class: req.Class,
ParentId: "", ParentId: req.ParentId,
} }
componentDictList, err := c.List(listReq) componentDictList, _, err := c.List(listReq)
if err != nil { if err != nil {
return return
} }
...@@ -143,6 +148,7 @@ func (c *Dict) Add(req request.AddDictReq) (err error) { ...@@ -143,6 +148,7 @@ func (c *Dict) Add(req request.AddDictReq) (err error) {
UpdatedAt: jsontime.Time(time.Now()), UpdatedAt: jsontime.Time(time.Now()),
MinVal: req.MinVal, MinVal: req.MinVal,
MaxVal: req.MaxVal, MaxVal: req.MaxVal,
Unit: req.Unit,
} }
db, err := client.GetDbClient() db, err := client.GetDbClient()
...@@ -180,7 +186,7 @@ func (c *Dict) Update(req request.UpdateDictReq) (err error) { ...@@ -180,7 +186,7 @@ func (c *Dict) Update(req request.UpdateDictReq) (err error) {
req.UpdatedAt = jsontime.Time(time.Now()) req.UpdatedAt = jsontime.Time(time.Now())
_, err = session.Table("dict"). _, 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) Where("id = ? and is_delete = 0", req.Id).Update(&req)
if err != nil { if err != nil {
err = errors.Wrap(err, "修改字典失败!") err = errors.Wrap(err, "修改字典失败!")
...@@ -263,6 +269,23 @@ func (c *Dict) DictSort(req []request.DictSortInput) error { ...@@ -263,6 +269,23 @@ func (c *Dict) DictSort(req []request.DictSortInput) error {
return err 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) { //func (c *Dict) ManageList(req request.DictManageListReq) (componentDictTreeRes []*response.DictListRes, err error) {
// listReq := request.DictReq{ // listReq := request.DictReq{
// Class: req.Class, // Class: req.Class,
......
...@@ -117,8 +117,15 @@ func (h *HostManageSvc) AddHostManage(req request.AddHostManageReq) (err error) ...@@ -117,8 +117,15 @@ func (h *HostManageSvc) AddHostManage(req request.AddHostManageReq) (err error)
return return
} }
hostsIp := fmt.Sprintf("%s ansible_ssh_host=%s ansible_ssh_port=%s ansible_ssh_user=\"%s\" ansible_ssh_pass=\"%s\"", hostsIp := ""
AnsibleIp+fmt.Sprintf("%d", hostManageList.Id), v.Ip, v.Port, v.UserName, v.Password) 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) 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 ...@@ -219,8 +226,15 @@ func (h *HostManageSvc) EditHostManage(req request.EditHostManageReq) (err error
return return
} }
hostsIp := fmt.Sprintf("%s ansible_ssh_host=%s ansible_ssh_port=%s ansible_ssh_user=\"%s\" ansible_ssh_pass=\"%s\"", hostsIp := ""
AnsibleIp+fmt.Sprintf("%d", hostManageList.Id), v.Ip, v.Port, v.UserName, v.Password) 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) 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 ...@@ -396,23 +410,47 @@ func (h *HostManageSvc) ListStateHostManage(req request.StateHostManageReq) (err
return return
} }
//往hosts文件中写入主机组ip //读取hosts中的主机组
//f, err := os.OpenFile("/etc/ansible/hosts", os.O_APPEND|os.O_CREATE|os.O_RDWR, 0777) hosts, err := tools.HostsToJson()
//if err != nil { if err != nil {
// err = resp.FileExecError.WithError(err) err = resp.MarshalError.WithError(err)
// return session.Rollback()
//} return
//defer f.Close() }
//_, err = f.Write([]byte(fmt.Sprintf("%s%d\n", AnsibleGroup, req.Id))) if _, ok := hosts["["+AnsibleGroup+fmt.Sprintf("%d", req.Id)+"]"]; !ok {
//if err != nil { // 不存在
// return resp.FileExecError.WithError(err) hosts["["+AnsibleGroup+fmt.Sprintf("%d", req.Id)+"]"] = nil
//} }
//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))) for _, v := range hostManageList {
// if err != nil { hostsIp := ""
// return resp.FileExecError.WithError(err) 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 { for _, v := range hostManageList {
//修改状态 //修改状态
_, err = session.Table("host_manage_list").Where("is_delete = 0 AND id = ?", v.Id). _, 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 ...@@ -473,7 +511,14 @@ func (h *HostManageSvc) SaveStateHostManage(hostManageList []request.HostManageL
for _, v := range hostManageListCaches { 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 flag := 0
for _, v1 := range hosts["["+AnsibleGroup+"]"] { for _, v1 := range hosts["["+AnsibleGroup+"]"] {
if v1 == hostsIp { if v1 == hostsIp {
......
This diff is collapsed.
...@@ -163,7 +163,7 @@ func (t *TaskManageSvc) ListTaskManage(req request.ListTaskManageReq) (total int ...@@ -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") finder := db.Table("task_manage").Alias("tm").Where("tm.is_delete = 0")
if req.Search != "" { 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+"%")) "%"+req.Search+"%", "%"+req.Search+"%", "%"+req.Search+"%"))
} }
if req.CreateDateFrom != "" { if req.CreateDateFrom != "" {
......
...@@ -160,7 +160,7 @@ func (w *WorkOrderManageSvc) DelWorkOrderManage(req request.DelWorkOrderReq) (er ...@@ -160,7 +160,7 @@ func (w *WorkOrderManageSvc) DelWorkOrderManage(req request.DelWorkOrderReq) (er
} }
// DetailsWorkOrderManage 详情 // 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() db, err := client.GetDbClient()
if err != nil { if err != nil {
err = resp.DbConnectError.WithError(err) err = resp.DbConnectError.WithError(err)
...@@ -170,33 +170,50 @@ func (w *WorkOrderManageSvc) DetailsWorkOrderManage(id int) (taskManageRes respo ...@@ -170,33 +170,50 @@ func (w *WorkOrderManageSvc) DetailsWorkOrderManage(id int) (taskManageRes respo
//查询任务详情 //查询任务详情
var workOrder entity.WorkOrder var workOrder entity.WorkOrder
finder := db.Table("work_order_manage").Where("id = ?", id) finder := db.Table("work_order_manage").Where("id = ?", id)
_, err = finder.Get(&workOrder) has, err := finder.Get(&workOrder)
if err != nil { if err != nil {
err = resp.DbSelectError.WithError(err) err = resp.DbSelectError.WithError(err)
return return
} }
if !has {
err = json.Unmarshal([]byte(workOrder.PushObj), &taskManageRes.PushObj) err = resp.DbSelectError.WithError(errors.New("查询为空"))
if err != nil {
err = resp.FAIL.WithError(err)
return return
} }
err = json.Unmarshal([]byte(workOrder.TimingRule), &taskManageRes.TimingRule)
err = json.Unmarshal([]byte(workOrder.PushObj), &workOrderRes.PushObj)
if err != nil { if err != nil {
err = resp.FAIL.WithError(err) err = resp.FAIL.WithError(err)
return return
} }
taskManageRes.Id = workOrder.Id if workOrder.TimingType == 2 {
taskManageRes.OrderName = workOrder.OrderName var timingWeekly request.TimingWeekly
taskManageRes.OrderLevel = workOrder.OrderLevel err = json.Unmarshal([]byte(workOrder.TimingRule), &timingWeekly)
taskManageRes.OrderDesc = workOrder.OrderDesc if err != nil {
taskManageRes.TimingState = workOrder.TimingState err = resp.FAIL.WithError(err)
taskManageRes.TimingType = workOrder.TimingType return
taskManageRes.CreateUser = workOrder.CreateUser }
taskManageRes.CreateTime = workOrder.CreateTime workOrderRes.TimingRule = timingWeekly
taskManageRes.UpdateUser = workOrder.UpdateUser } else if workOrder.TimingType == 3 {
taskManageRes.UpdateUser = workOrder.UpdateUser var timingCustom []request.TimingCustom
taskManageRes.UpdateTime = workOrder.UpdateTime 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 return
} }
...@@ -211,7 +228,7 @@ func (w *WorkOrderManageSvc) ListWorkOrderManage(req request.ListWorkOrderManage ...@@ -211,7 +228,7 @@ func (w *WorkOrderManageSvc) ListWorkOrderManage(req request.ListWorkOrderManage
finder := db.Table("work_order_manage") finder := db.Table("work_order_manage")
if req.Search != "" { 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 { if req.OrderLevel != 0 {
finder.Where("order_level = ?", req.OrderLevel) finder.Where("order_level = ?", req.OrderLevel)
...@@ -364,7 +381,7 @@ func (w *WorkOrderManageSvc) ListWorkOrderIssuance(req request.ListWorkOrderReq) ...@@ -364,7 +381,7 @@ func (w *WorkOrderManageSvc) ListWorkOrderIssuance(req request.ListWorkOrderReq)
Join("INNER", "work_order_manage wom", "woi.order_id = wom.id") Join("INNER", "work_order_manage wom", "woi.order_id = wom.id")
if req.Search != "" { 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 { if req.OrderLevel != 0 {
finder.Where("wom.order_level = ?", req.OrderLevel) finder.Where("wom.order_level = ?", req.OrderLevel)
...@@ -379,7 +396,7 @@ func (w *WorkOrderManageSvc) ListWorkOrderIssuance(req request.ListWorkOrderReq) ...@@ -379,7 +396,7 @@ func (w *WorkOrderManageSvc) ListWorkOrderIssuance(req request.ListWorkOrderReq)
finder.Where("woi.create_time <= ?", req.CreateDateTo) finder.Where("woi.create_time <= ?", req.CreateDateTo)
} }
if req.CompleteTimeFrom != "" { if req.CompleteTimeFrom != "" {
finder.Where("woi.complete_time <= ?", req.CompleteTimeFrom) finder.Where("woi.complete_time >= ?", req.CompleteTimeFrom)
} }
if req.CompleteTimeTo != "" { if req.CompleteTimeTo != "" {
finder.Where("woi.complete_time <= ?", req.CompleteTimeTo) finder.Where("woi.complete_time <= ?", req.CompleteTimeTo)
...@@ -424,12 +441,15 @@ func (w *WorkOrderManageSvc) DetailsWorkOrderIssuance(id int) (workOrderIssuance ...@@ -424,12 +441,15 @@ func (w *WorkOrderManageSvc) DetailsWorkOrderIssuance(id int) (workOrderIssuance
var workOrderIssuance response.WorkOrderIssuance var workOrderIssuance response.WorkOrderIssuance
finder := db.Table("work_order_issuance").Alias("woi"). finder := db.Table("work_order_issuance").Alias("woi").
Join("INNER", "work_order_manage wom", "woi.order_id = wom.ID").Where("woi.id = ?", id) 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) Get(&workOrderIssuance)
if err != nil { if err != nil {
err = resp.DbSelectError.WithError(err) err = resp.DbSelectError.WithError(err)
return return
} }
if !has {
return
}
//var workOrderMe entity.WorkOrderMe //var workOrderMe entity.WorkOrderMe
finder1 := db.Table("work_order_me").Where("order_issuance_id = ?", id) finder1 := db.Table("work_order_me").Where("order_issuance_id = ?", id)
...@@ -521,7 +541,7 @@ func (w *WorkOrderManageSvc) ListWorkOrderMe(req request.ListWorkOrderReq) (tota ...@@ -521,7 +541,7 @@ func (w *WorkOrderManageSvc) ListWorkOrderMe(req request.ListWorkOrderReq) (tota
Join("INNER", "work_order_manage wom", "woi.order_id = wom.id") Join("INNER", "work_order_manage wom", "woi.order_id = wom.id")
if req.Search != "" { 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 { if req.OrderLevel != 0 {
finder.Where("wom.order_level = ?", req.OrderLevel) finder.Where("wom.order_level = ?", req.OrderLevel)
...@@ -536,7 +556,7 @@ func (w *WorkOrderManageSvc) ListWorkOrderMe(req request.ListWorkOrderReq) (tota ...@@ -536,7 +556,7 @@ func (w *WorkOrderManageSvc) ListWorkOrderMe(req request.ListWorkOrderReq) (tota
finder.Where("woi.create_time <= ?", req.CreateDateTo) finder.Where("woi.create_time <= ?", req.CreateDateTo)
} }
if req.CompleteTimeFrom != "" { if req.CompleteTimeFrom != "" {
finder.Where("wome.complete_time <= ?", req.CompleteTimeFrom) finder.Where("wome.complete_time >= ?", req.CompleteTimeFrom)
} }
if req.CompleteTimeTo != "" { if req.CompleteTimeTo != "" {
finder.Where("wome.complete_time <= ?", req.CompleteTimeTo) finder.Where("wome.complete_time <= ?", req.CompleteTimeTo)
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment