Commit a812ce93 authored by 陈子龙's avatar 陈子龙

新增 文件上传接口,优化主机管理

parent 422e5242
...@@ -12,6 +12,8 @@ require ( ...@@ -12,6 +12,8 @@ require (
github.com/google/uuid v1.3.0 github.com/google/uuid v1.3.0
github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible github.com/lestrrat-go/file-rotatelogs v2.4.0+incompatible
github.com/lib/pq v1.10.9 github.com/lib/pq v1.10.9
github.com/minio/minio-go/v7 v7.0.58
github.com/pkg/errors v0.9.1
github.com/spf13/cast v1.5.0 github.com/spf13/cast v1.5.0
github.com/spf13/pflag v1.0.5 github.com/spf13/pflag v1.0.5
github.com/thoas/go-funk v0.9.3 github.com/thoas/go-funk v0.9.3
...@@ -26,6 +28,7 @@ require ( ...@@ -26,6 +28,7 @@ require (
github.com/andybalholm/brotli v1.0.5 // indirect github.com/andybalholm/brotli v1.0.5 // indirect
github.com/bytedance/sonic v1.8.0 // indirect github.com/bytedance/sonic v1.8.0 // indirect
github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect github.com/chenzhuoyu/base64x v0.0.0-20221115062448-fe3a3abad311 // indirect
github.com/dustin/go-humanize v1.0.1 // indirect
github.com/gin-contrib/sse v0.1.0 // indirect github.com/gin-contrib/sse v0.1.0 // indirect
github.com/goccy/go-json v0.10.0 // indirect github.com/goccy/go-json v0.10.0 // indirect
github.com/golang/protobuf v1.5.0 // indirect github.com/golang/protobuf v1.5.0 // indirect
...@@ -33,16 +36,19 @@ require ( ...@@ -33,16 +36,19 @@ require (
github.com/henrylee2cn/ameda v1.5.0 // indirect github.com/henrylee2cn/ameda v1.5.0 // indirect
github.com/henrylee2cn/goutil v0.0.0-20220704075712-42f2ec55fe8d // indirect github.com/henrylee2cn/goutil v0.0.0-20220704075712-42f2ec55fe8d // indirect
github.com/json-iterator/go v1.1.12 // indirect github.com/json-iterator/go v1.1.12 // indirect
github.com/klauspost/compress v1.16.3 // indirect github.com/klauspost/compress v1.16.5 // indirect
github.com/klauspost/cpuid/v2 v2.0.9 // indirect github.com/klauspost/cpuid/v2 v2.2.4 // indirect
github.com/leodido/go-urn v1.2.3 // indirect github.com/leodido/go-urn v1.2.3 // indirect
github.com/lestrrat-go/strftime v1.0.6 // indirect github.com/lestrrat-go/strftime v1.0.6 // indirect
github.com/mattn/go-isatty v0.0.17 // indirect github.com/mattn/go-isatty v0.0.17 // indirect
github.com/minio/md5-simd v1.1.2 // indirect
github.com/minio/sha256-simd v1.0.1 // indirect
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
github.com/modern-go/reflect2 v1.0.2 // indirect github.com/modern-go/reflect2 v1.0.2 // indirect
github.com/nyaruka/phonenumbers v1.1.7 // indirect github.com/nyaruka/phonenumbers v1.1.7 // indirect
github.com/pelletier/go-toml/v2 v2.0.6 // indirect github.com/pelletier/go-toml/v2 v2.0.6 // indirect
github.com/pkg/errors v0.9.1 // indirect github.com/rs/xid v1.5.0 // indirect
github.com/sirupsen/logrus v1.9.2 // indirect
github.com/syndtr/goleveldb v1.0.0 // indirect github.com/syndtr/goleveldb v1.0.0 // indirect
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
github.com/ugorji/go/codec v1.2.9 // indirect github.com/ugorji/go/codec v1.2.9 // indirect
...@@ -50,11 +56,12 @@ require ( ...@@ -50,11 +56,12 @@ require (
go.uber.org/atomic v1.7.0 // indirect go.uber.org/atomic v1.7.0 // indirect
go.uber.org/multierr v1.6.0 // indirect go.uber.org/multierr v1.6.0 // indirect
golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect golang.org/x/arch v0.0.0-20210923205945-b76863e36670 // indirect
golang.org/x/crypto v0.7.0 // indirect golang.org/x/crypto v0.9.0 // indirect
golang.org/x/net v0.8.0 // indirect golang.org/x/net v0.10.0 // indirect
golang.org/x/sys v0.6.0 // indirect golang.org/x/sys v0.8.0 // indirect
golang.org/x/text v0.8.0 // indirect golang.org/x/text v0.9.0 // indirect
google.golang.org/protobuf v1.28.1 // indirect google.golang.org/protobuf v1.28.1 // indirect
gopkg.in/ini.v1 v1.67.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect
xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978 // indirect xorm.io/builder v0.3.11-0.20220531020008-1bd24a7dc978 // indirect
) )
This diff is collapsed.
package entity
import "time"
type HostManage struct {
Id int `json:"id" xorm:"pk autoincr" ` // id
HostName string `json:"hostName" xorm:"host_name"` // 主机分组名称
IsDelete int `json:"isDelete" xorm:"is_delete" ` // 是否删除(0 未删除 1已删除)
CreateUser string `json:"createUser" xorm:"create_user" ` // 创建人
CreateTime time.Time `json:"createTime" xorm:"create_time"` // 创建时间
UpdateUser string `json:"updateUser" xorm:"update_user" ` // 修改人
UpdateTime time.Time `json:"updateTime" xorm:"update_time"` // 修改时间
}
type HostManageList struct {
Id int `json:"id" xorm:"pk autoincr" ` // id
Ip string `json:"ip" xorm:"ip"` // ip
Port string `json:"port" xorm:"port"` // 端口
VoucherType int `json:"voucherType" xorm:"voucher_type"` // 凭证类型(0密码验证 密钥验证)
UserName string `json:"userName" xorm:"user_name"` // 用户名
Password string `json:"password" xorm:"password"` // 密码
HostGroupId int `json:"hostGroupId" xorm:"host_group_id"` // 主机分组id
HostFileUrl string `json:"hostFileUrl" xorm:"host_file_url"` // 主机文件url
IsDelete int `json:"isDelete" xorm:"is_delete" ` // 是否删除(0 未删除 1已删除)
ConnStatus int `json:"connStatus" xorm:"conn_status" ` // 连接状态(0异常 1正常)
}
package request
type AddHostManageReq struct {
HostName string `json:"hostName"` // 主机分组名称
HostFileUrl string `json:"hostFileUrl"` // 主机文件url
HostManageList []HostManageList `json:"hostManageList"` //主机列表
}
type HostManageList struct {
Ip string `json:"ip"` // ip
Port string `json:"port"` // 端口
VoucherType int `json:"voucherType"` // 凭证类型(0密码验证 密钥验证)
UserName string `json:"userName"` // 用户名
Password string `json:"password"` // 密码
}
type EditHostManageReq struct {
Id int `json:"id"` // 主键ID
HostName string `json:"hostName"` // 主机分组名称
HostFileUrl string `json:"hostFileUrl"` // 主机文件url
HostManageList []HostManageList `json:"hostManageList"` //主机列表
}
type DelHostManageReq struct {
Id []int `json:"id" vd:"len($)>0;msg:'请输入id'"` // 主键ID
}
type ListHostManageReq struct {
Search string `json:"search" form:"search"` //关键词
CreateDateFrom string `json:"createDateFrom" form:"createDateFrom"` //创建时间从
CreateDateTo string `json:"createDateTo" form:"createDateTo"` //创建时间至
Pagination
}
type StateHostManageReq struct {
Id int `json:"id" form:"id" binding:"required"` //主键ID
Pagination
}
package response
import "time"
type HostManageRes struct {
Id int `json:"id"` // id
HostName string `json:"hostName"` // 主机分组名称
TaskCnt int `json:"taskCnt"` // 任务数量
IpCnt int `json:"ipCnt"` // ip数量
CreateUser string `json:"createUser"` // 创建人
CreateTime time.Time `json:"createTime"` // 创建时间
UpdateUser string `json:"updateUser"` // 修改人
UpdateTime time.Time `json:"updateTime"` // 修改时间
HostFileUrl string `json:"hostFileUrl"` // 主机文件url
HostList []HostList `json:"hostList"` // 主机列表
TaskList []TaskList `json:"taskList"` // 主机列表
}
type HostManage struct {
Id int `json:"id"` // id
HostName string `json:"hostName"` // 主机分组名称
CreateUser string `json:"createUser"` // 创建人
CreateTime time.Time `json:"createTime"` // 创建时间
UpdateUser string `json:"updateUser"` // 修改人
UpdateTime time.Time `json:"updateTime"` // 修改时间
}
type HostList struct {
Id int `json:"id"` // id
Ip string `json:"ip"` // ip
Port string `json:"port"` // 端口
HostFileUrl string `json:"hostFileUrl"` // 主机文件url
}
type TaskList struct {
Id int `json:"id"` // id
TaskName string `json:"taskName"` // 任务名称
TaskDesc string `json:"taskDesc"` // 任务描述
ExecCnt int `json:"execCnt"` // 执行次数
}
type HostManagesRes struct {
Id int `json:"id"` // id
HostName string `json:"hostName"` // 主机分组名称
CreateUser string `json:"createUser"` // 创建人
CreateTime time.Time `json:"createTime"` // 创建时间
TaskCnt int `json:"taskCnt"` // 任务数量
IpCntErr int `json:"ipCntErr"` // ip数量(异常)
IpCnt int `json:"ipCnt"` // ip数量(全部)
}
type HostManageListRes struct {
Id int `json:"id"` // id
Ip string `json:"ip"` // ip
Port string `json:"port"` // 端口
VoucherType int `json:"voucherType"` // 凭证类型(0密码验证 密钥验证)
UserName string `json:"userName"` // 用户名
Password string `json:"password"` // 密码
}
package client
import (
"fmt"
"github.com/minio/minio-go/v7"
"gitlab.wodcloud.com/smart-operation/so-operation-api/src/common/conf"
"net/url"
"github.com/minio/minio-go/v7/pkg/credentials"
)
var MinioClient *minio.Client
func GetMinioConnect() (*minio.Client, error) {
if MinioClient != nil {
return MinioClient, nil
}
parse, err := url.Parse(conf.Options.MinioServer)
if err != nil {
return MinioClient, err
}
minioClient, err := minio.New(parse.Host, &minio.Options{
Creds: credentials.NewStaticV4(conf.Options.MinioAccessKey, conf.Options.MinioSecretKey, ""),
Secure: false,
})
if err != nil {
return MinioClient, err
}
MinioClient = minioClient
fmt.Printf("connect Minio Server { %s } success!\n", conf.Options.MinioServer)
return MinioClient, err
}
...@@ -25,4 +25,8 @@ type Config struct { ...@@ -25,4 +25,8 @@ type Config struct {
LogMode int LogMode int
ArgBool bool ArgBool bool
ArgInt int ArgInt int
MinioServer string
MinioAccessKey string
MinioSecretKey string
MinioBucket string
} }
package controller
import (
"github.com/gin-gonic/gin"
"gitlab.wodcloud.com/smart-operation/so-operation-api/src/pkg/beagle/resp"
"gitlab.wodcloud.com/smart-operation/so-operation-api/src/service"
)
func AddFile(c *gin.Context) {
docLibSvc := service.DocLibSvc{}
doc, err := docLibSvc.AddFile(c)
if err != nil {
SendJsonResponse(c, resp.FAIL.WithError(err), nil)
return
}
SendJsonResponse(c, resp.OK, doc)
}
//
//func (d *DocLib) Get(c *gin.Context) {
// var req request.DocLibGetReq
// if err := c.ShouldBindUri(&req); err != nil {
// resp.Json(c, resp.InvalidParam.WithTranslate(err))
// return
// }
// user, _ := header.GetUserContext(c)
// svc := new(service.DocLibSvc)
// svc.User = &user
// doc, docUrl, err := svc.Get(c, req)
// if err != nil {
// resp.Json(c, resp.FAIL.WithMsg(err.Error()))
// return
// }
// switch req.Opt {
// case "download":
// //c.Redirect(http.StatusMovedPermanently, docUrl.String())
// docUrlParse, _ := url.Parse(docUrl.String())
// proxy := httputil.ReverseProxy{
// Director: func(req *http.Request) {
// req.Header = c.Request.Header
// req.Host = docUrlParse.Host
// req.URL = docUrlParse
// },
// }
// proxy.ServeHTTP(c.Writer, c.Request)
// case "preview":
// c.Redirect(http.StatusMovedPermanently, docUrl.String())
// case "info":
// resp.Json(c, resp.OK.WithData(doc))
// case "tmp":
// resp.Json(c, resp.OK.WithData(docUrl.String()))
// }
//}
//
//func (d *DocLib) List(c *gin.Context) {
// var req request.DocLibListReq
// if err := c.ShouldBind(&req); err != nil {
// resp.Json(c, resp.InvalidParam.WithTranslate(err))
// return
// }
// user, _ := header.GetUserContext(c)
// svc := new(service.DocLibSvc)
// svc.User = &user
// data, err := svc.List(c, req)
// if err != nil {
// resp.Json(c, resp.FAIL.WithMsg(err.Error()))
// return
// }
// resp.Json(c, resp.OK.WithData(data))
//}
//
//func (d *DocLib) Del(c *gin.Context) {
// var req request.DocLibDelReq
// if err := c.ShouldBind(&req); err != nil {
// resp.Json(c, resp.InvalidParam.WithTranslate(err))
// return
// }
// user, _ := header.GetUserContext(c)
// svc := new(service.DocLibSvc)
// svc.User = &user
// err := svc.Del(c, req)
// if err != nil {
// resp.Json(c, resp.FAIL.WithMsg(err.Error()))
// return
// }
// resp.Json(c, resp.OK)
//}
//
//func (d *DocLib) Exts(c *gin.Context) {
// user, _ := header.GetUserContext(c)
// svc := new(service.DocLibSvc)
// svc.User = &user
// data, err := svc.Exts(c)
// if err != nil {
// resp.Json(c, resp.FAIL.WithMsg(err.Error()))
// return
// }
// resp.Json(c, resp.OK.WithData(data))
//}
//
//func (d *DocLib) Update(c *gin.Context) {
// var req request.DocLibUpdateReq
// if err := c.ShouldBind(&req); err != nil {
// resp.Json(c, resp.InvalidParam.WithTranslate(err))
// return
// }
// user, _ := header.GetUserContext(c)
// svc := new(service.DocLibSvc)
// svc.User = &user
// doc, err := svc.Update(c, req)
// if err != nil {
// resp.Json(c, resp.FAIL.WithMsg(err.Error()))
// return
// }
// resp.Json(c, resp.OK.WithData(doc))
//}
package controller
import (
"errors"
"github.com/gin-gonic/gin"
"github.com/spf13/cast"
"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/service"
"gitlab.wodcloud.com/smart-operation/so-operation-api/src/util"
)
// AddHostManage 新增
func AddHostManage(c *gin.Context) {
var req request.AddHostManageReq
if err := c.ShouldBindJSON(&req); err != nil {
SendJsonResponse(c, resp.InvalidParam.WithError(err), nil)
return
}
//参数校验
if req.HostName == "" {
SendJsonResponse(c, resp.InvalidParam.WithError(errors.New("主机分组名称为空")), nil)
return
}
if req.HostFileUrl == "" {
if len(req.HostManageList) == 0 {
SendJsonResponse(c, resp.InvalidParam.WithError(errors.New("主机分组数量为0")), nil)
return
}
if len(req.HostManageList) > 5 {
SendJsonResponse(c, resp.InvalidParam.WithError(errors.New("主机分组数量超过5条")), nil)
return
}
for _, v := range req.HostManageList {
if v.Ip == "" || v.UserName == "" {
SendJsonResponse(c, resp.InvalidParam.WithError(errors.New("ip或用户名为空")), nil)
return
}
if v.VoucherType == 0 && v.Password == "" {
SendJsonResponse(c, resp.InvalidParam.WithError(errors.New("密码为空")), nil)
return
}
}
}
hostManageSvc := service.HostManageSvc{}
err := hostManageSvc.AddHostManage(req)
if err != nil {
SendJsonResponse(c, err, nil)
return
}
SendJsonResponse(c, resp.OK, nil)
}
// EditHostManage 编辑
func EditHostManage(c *gin.Context) {
var req request.EditHostManageReq
if err := c.ShouldBindJSON(&req); err != nil {
SendJsonResponse(c, resp.InvalidParam.WithError(err), nil)
return
}
//参数校验
if req.HostName == "" || req.Id == 0 {
SendJsonResponse(c, resp.InvalidParam.WithError(errors.New("主机分组ID或名称为空")), nil)
return
}
if req.HostFileUrl == "" {
if len(req.HostManageList) == 0 {
SendJsonResponse(c, resp.InvalidParam.WithError(errors.New("主机分组数量为0")), nil)
return
}
if len(req.HostManageList) > 5 {
SendJsonResponse(c, resp.InvalidParam.WithError(errors.New("主机分组数量超过5条")), nil)
return
}
for _, v := range req.HostManageList {
if v.Ip == "" || v.UserName == "" {
SendJsonResponse(c, resp.InvalidParam.WithError(errors.New("ip或用户名为空")), nil)
return
}
if v.VoucherType == 0 && v.Password == "" {
SendJsonResponse(c, resp.InvalidParam.WithError(errors.New("密码为空")), nil)
return
}
}
}
hostManageSvc := service.HostManageSvc{}
err := hostManageSvc.EditHostManage(req)
if err != nil {
SendJsonResponse(c, err, nil)
return
}
SendJsonResponse(c, resp.OK, nil)
}
// DelHostManage 删除
func DelHostManage(c *gin.Context) {
var req request.DelHostManageReq
if err := c.ShouldBindJSON(&req); err != nil {
SendJsonResponse(c, resp.InvalidParam.WithError(err), nil)
return
}
//参数校验
if err := util.ValidateSimple(req, "Id"); err != nil {
SendJsonResponse(c, resp.InvalidParam.WithError(err), nil)
return
}
hostManageSvc := service.HostManageSvc{}
err := hostManageSvc.DelHostManage(req)
if err != nil {
SendJsonResponse(c, err, nil)
return
}
SendJsonResponse(c, resp.OK, nil)
}
// DetailsHostManage 详情
func DetailsHostManage(c *gin.Context) {
var (
err error
id string
)
if id = c.Query("id"); id == "" {
id = c.Param("id")
}
if id == "" {
SendJsonResponse(c, resp.InvalidParam.WithError(errors.New("id为空")), nil)
return
}
hostManageSvc := service.HostManageSvc{}
data, err := hostManageSvc.DetailsHostManage(cast.ToInt(id))
if err != nil {
SendJsonResponse(c, err, nil)
return
}
SendJsonResponse(c, resp.OK, data)
}
// ListHostManage 列表
func ListHostManage(c *gin.Context) {
var req request.ListHostManageReq
if err := c.ShouldBindJSON(&req); err != nil {
SendJsonResponse(c, resp.InvalidParam.WithError(err), nil)
return
}
hostManageSvc := service.HostManageSvc{}
total, list, err := hostManageSvc.ListHostManage(req)
if err != nil {
SendJsonPageResponse(c, err, nil, 0)
return
}
SendJsonPageResponse(c, resp.OK, list, total)
}
// StateHostManage 状态检测
func StateHostManage(c *gin.Context) {
var req request.StateHostManageReq
if err := c.ShouldBindJSON(&req); err != nil {
SendJsonResponse(c, resp.InvalidParam.WithError(err), nil)
return
}
hostManageSvc := service.HostManageSvc{}
total, list, err := hostManageSvc.StateHostManage(req)
if err != nil {
SendJsonPageResponse(c, err, nil, 0)
return
}
SendJsonPageResponse(c, resp.OK, list, total)
}
...@@ -23,8 +23,8 @@ func AddTaskManage(c *gin.Context) { ...@@ -23,8 +23,8 @@ func AddTaskManage(c *gin.Context) {
return return
} }
taskManageService := service.TaskManageSvc{} taskManageSvc := service.TaskManageSvc{}
err := taskManageService.AddTaskManage(req) err := taskManageSvc.AddTaskManage(req)
if err != nil { if err != nil {
SendJsonResponse(c, err, nil) SendJsonResponse(c, err, nil)
return return
...@@ -45,8 +45,8 @@ func EditTaskManage(c *gin.Context) { ...@@ -45,8 +45,8 @@ func EditTaskManage(c *gin.Context) {
return return
} }
taskManageService := service.TaskManageSvc{} taskManageSvc := service.TaskManageSvc{}
err := taskManageService.EditTaskManage(req) err := taskManageSvc.EditTaskManage(req)
if err != nil { if err != nil {
SendJsonResponse(c, err, nil) SendJsonResponse(c, err, nil)
return return
...@@ -67,8 +67,8 @@ func DelTaskManage(c *gin.Context) { ...@@ -67,8 +67,8 @@ func DelTaskManage(c *gin.Context) {
return return
} }
taskManageService := service.TaskManageSvc{} taskManageSvc := service.TaskManageSvc{}
err := taskManageService.DelTaskManage(req) err := taskManageSvc.DelTaskManage(req)
if err != nil { if err != nil {
SendJsonResponse(c, err, nil) SendJsonResponse(c, err, nil)
return return
...@@ -87,12 +87,12 @@ func DetailsTaskManage(c *gin.Context) { ...@@ -87,12 +87,12 @@ func DetailsTaskManage(c *gin.Context) {
id = c.Param("id") id = c.Param("id")
} }
if id == "" { if id == "" {
SendJsonResponse(c, resp.InvalidParam.WithError(errors.New("规则名称重复")), nil) SendJsonResponse(c, resp.InvalidParam.WithError(errors.New("id为空")), nil)
return return
} }
taskManageService := service.TaskManageSvc{} taskManageSvc := service.TaskManageSvc{}
data, err := taskManageService.DetailsTaskManage(cast.ToInt(id)) data, err := taskManageSvc.DetailsTaskManage(cast.ToInt(id))
if err != nil { if err != nil {
SendJsonResponse(c, err, nil) SendJsonResponse(c, err, nil)
return return
...@@ -108,8 +108,8 @@ func ListTaskManage(c *gin.Context) { ...@@ -108,8 +108,8 @@ func ListTaskManage(c *gin.Context) {
return return
} }
taskManageService := service.TaskManageSvc{} taskManageSvc := service.TaskManageSvc{}
total, list, err := taskManageService.ListTaskManage(req) total, list, err := taskManageSvc.ListTaskManage(req)
if err != nil { if err != nil {
SendJsonPageResponse(c, err, nil, 0) SendJsonPageResponse(c, err, nil, 0)
return return
......
...@@ -57,6 +57,10 @@ func initConfig() { ...@@ -57,6 +57,10 @@ func initConfig() {
LogMode: util.SetEnvInt("LOG_MODE", 1), // 1.标准打印 2.输出文件 LogMode: util.SetEnvInt("LOG_MODE", 1), // 1.标准打印 2.输出文件
ArgBool: util.SetEnvBool("ARG_BOOL", false), // 示例参数 ArgBool: util.SetEnvBool("ARG_BOOL", false), // 示例参数
ArgInt: util.SetEnvInt("ARG_INT", 10), // 示例参数 ArgInt: util.SetEnvInt("ARG_INT", 10), // 示例参数
MinioServer: util.SetEnvStr("MINIO_SERVER", "https://cache.wodcloud.com"), // Minio 服务地址
MinioAccessKey: util.SetEnvStr("MINIO_ACCESS_KEY", "beagleadmin"), // Minio Access Key
MinioSecretKey: util.SetEnvStr("MINIO_SECRET_KEY", "H76cPmwvH7vJ"), // Minio Secret
MinioBucket: util.SetEnvStr("MINIO_BUCKET", "so-operation"), // Minio Bucket
} }
} }
......
...@@ -22,10 +22,11 @@ func InitAutomatedMaintenRouter(e *gin.Engine) { ...@@ -22,10 +22,11 @@ func InitAutomatedMaintenRouter(e *gin.Engine) {
//主机管理 //主机管理
host := so.Group("/hostManage") host := so.Group("/hostManage")
{ {
host.POST("/add") // 新增 host.POST("/add", controller.AddHostManage) // 新增
host.PUT("/edit") // 编辑 host.PUT("/edit", controller.EditHostManage) // 编辑
host.DELETE("/del") // 删除 host.DELETE("/del", controller.DelHostManage) // 删除
host.GET("/details") // 详情 host.GET("/details", controller.DetailsHostManage) // 详情
host.GET("/list") // 列表 host.GET("/list", controller.ListHostManage) // 列表
host.GET("/state", controller.StateHostManage) // 状态检测
} }
} }
...@@ -27,6 +27,18 @@ func Load(r *gin.Engine, middleware ...gin.HandlerFunc) { ...@@ -27,6 +27,18 @@ func Load(r *gin.Engine, middleware ...gin.HandlerFunc) {
base.GET("/example", controller.Example) // 示例 base.GET("/example", controller.Example) // 示例
base.GET("/example/list", controller.GetExampleList) // 示例获取列表 base.GET("/example/list", controller.GetExampleList) // 示例获取列表
} }
//文档库
docLib := base.Group("doc_lib")
{
docLib.POST("addFile", controller.AddFile) //文件上传
//docLib.GET(":id/:opt", docLibController.Get) //预览或下载
//docLib.GET("", docLibController.List) //文档列表
//docLib.DELETE("", docLibController.Del) //删除、移除文档
//docLib.GET("exts", docLibController.Exts) //格式列表
//docLib.PUT("", docLibController.Update) //文档编辑
}
// 初始化自动化运维路由 // 初始化自动化运维路由
InitAutomatedMaintenRouter(r) InitAutomatedMaintenRouter(r)
} }
package service
import (
"fmt"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"github.com/minio/minio-go/v7"
"github.com/pkg/errors"
"gitlab.wodcloud.com/smart-operation/so-operation-api/src/common/client"
"gitlab.wodcloud.com/smart-operation/so-operation-api/src/common/conf"
"mime/multipart"
"net/http"
"path"
)
var maxFileByte int64 = 104857600 //100M
type DocLibSvc struct{}
func GetFileContentType(out multipart.File) (contentType string, err error) {
buffer := make([]byte, 512)
_, err = out.Read(buffer)
if err != nil {
return
}
contentType = http.DetectContentType(buffer)
return
}
func (d *DocLibSvc) AddFile(c *gin.Context) (fileUrl string, err error) {
var (
uploadFile *multipart.FileHeader
uploadFd multipart.File
minioClient *minio.Client
ext string
contentType string
)
uploadFile, err = c.FormFile("upload_file")
if err != nil {
err = errors.Wrap(err, "上传的文件不存在")
return
}
if uploadFile.Size > maxFileByte {
err = errors.New("超过上传最大限制")
return
}
uploadFd, err = uploadFile.Open()
if err != nil {
err = errors.Wrap(err, "打开文件失败")
return
}
defer uploadFd.Close()
ext = path.Ext(uploadFile.Filename)
contentType, err = GetFileContentType(uploadFd)
if err != nil {
err = errors.Wrap(err, "获取ContentType失败")
return
}
uploadFd.Seek(0, 0)
//上传文件到minio
minioClient, err = client.GetMinioConnect()
if err != nil {
err = errors.Wrap(err, "getMinio")
return
}
id := uuid.NewString()
_, err = minioClient.PutObject(c,
conf.Options.MinioBucket,
fmt.Sprintf("%s%s", id, ext),
uploadFd,
uploadFile.Size,
minio.PutObjectOptions{
ContentType: contentType,
UserMetadata: map[string]string{
"name": uploadFile.Filename,
},
})
if err != nil {
err = errors.Wrap(err, "上传文件失败")
return
}
fileUrl = fmt.Sprintf("https://%s/%s/%s%s", conf.Options.MinioServer, conf.Options.MinioBucket, id, ext)
fmt.Printf("https://%s/%s/%s%s", conf.Options.MinioServer, conf.Options.MinioBucket, id, ext)
return
}
package service
import (
"errors"
"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/resp"
"time"
)
type HostManageSvc struct {
User *entity.User
}
// AddHostManage 新增主机
func (h *HostManageSvc) AddHostManage(req request.AddHostManageReq) (err error) {
db, err := client.GetDbClient()
if err != nil {
err = resp.DbConnectError.WithError(err)
return
}
// 开启事务
session := db.NewSession()
defer session.Close()
session.Begin()
// 校验 主机分组名称 是否重复
has, err := session.Table("host_manage").Where("is_delete = 0 AND host_name = ?", req.HostName).Exist()
if has {
err = resp.DbDataCheckError.WithError(errors.New("主机名称重复"))
session.Rollback()
return
}
if err != nil {
err = resp.DbSelectError.WithError(err)
session.Rollback()
return
}
//新增主机分组
hostManage := entity.HostManage{
HostName: req.HostName,
CreateUser: "",
CreateTime: time.Now(),
UpdateUser: "",
UpdateTime: time.Now(),
}
_, err = session.Table("host_manage").Insert(&hostManage)
if err != nil {
err = resp.DbInsertError.WithError(err)
session.Rollback()
return
}
if req.HostFileUrl == "" {
//新增主机分组列表
for _, v := range req.HostManageList {
port := "22"
if v.Port != "" {
port = v.Port
}
hostManageList := entity.HostManageList{
Ip: v.Ip,
Port: port,
VoucherType: v.VoucherType,
UserName: v.UserName,
Password: v.Password,
HostGroupId: hostManage.Id,
}
_, err = session.Table("host_manage_list").Insert(&hostManageList)
if err != nil {
err = resp.DbInsertError.WithError(err)
session.Rollback()
return
}
}
} else {
//读取并解析文件内容--czl
var hostManageLists []entity.HostManageList
//新增主机分组列表--文件形式
for _, v := range hostManageLists {
port := "22"
if v.Port != "" {
port = v.Port
}
hostManageList := entity.HostManageList{
Ip: v.Ip,
Port: port,
VoucherType: v.VoucherType,
UserName: v.UserName,
Password: v.Password,
HostGroupId: hostManage.Id,
HostFileUrl: req.HostFileUrl,
}
_, err = session.Table("host_manage_list").Insert(&hostManageList)
if err != nil {
err = resp.DbInsertError.WithError(err)
session.Rollback()
return
}
}
}
session.Commit()
return
}
// EditHostManage 编辑
func (h *HostManageSvc) EditHostManage(req request.EditHostManageReq) (err error) {
db, err := client.GetDbClient()
if err != nil {
err = resp.DbConnectError.WithError(err)
return
}
// 开启事务
session := db.NewSession()
defer session.Close()
session.Begin()
// 校验 主机分组名称 是否重复
has, err := session.Table("host_manage").Where("is_delete = 0 AND id != ? AND host_name = ?", req.Id, req.HostName).Exist()
if has {
err = resp.DbDataCheckError.WithError(errors.New("主机名称重复"))
session.Rollback()
return
}
if err != nil {
err = resp.DbSelectError.WithError(err)
session.Rollback()
return
}
//修改主机分组信息
hostManage := entity.HostManage{
HostName: req.HostName,
UpdateUser: "",
UpdateTime: time.Now(),
}
_, err = session.Table("host_manage").Where("is_delete = 0 AND id = ?", req.Id).
Cols("host_name,update_user,update_time").Update(&hostManage)
if err != nil {
err = resp.DbUpdateError.WithError(err)
session.Rollback()
return
}
//删除主机列表数据
_, err = session.Table("host_manage_list").Where("host_group_id = ?", req.Id).Cols("is_delete").Update(&entity.TaskManage{
IsDelete: 1,
})
if err != nil {
err = resp.DbDeleteError.WithError(err)
session.Rollback()
return
}
if req.HostFileUrl == "" {
//修改主机分组列表
for _, v := range req.HostManageList {
port := "22"
if v.Port != "" {
port = v.Port
}
hostManageList := entity.HostManageList{
Ip: v.Ip,
Port: port,
VoucherType: v.VoucherType,
UserName: v.UserName,
Password: v.Password,
HostGroupId: hostManage.Id,
}
_, err = session.Table("host_manage_list").Insert(&hostManageList)
if err != nil {
err = resp.DbInsertError.WithError(err)
session.Rollback()
return
}
}
} else {
//读取并解析文件内容--czl
var hostManageLists []entity.HostManageList
//新增主机分组列表--文件形式
for _, v := range hostManageLists {
port := "22"
if v.Port != "" {
port = v.Port
}
hostManageList := entity.HostManageList{
Ip: v.Ip,
Port: port,
VoucherType: v.VoucherType,
UserName: v.UserName,
Password: v.Password,
HostGroupId: hostManage.Id,
HostFileUrl: req.HostFileUrl,
}
_, err = session.Table("host_manage_list").Insert(&hostManageList)
if err != nil {
err = resp.DbInsertError.WithError(err)
session.Rollback()
return
}
}
}
session.Commit()
return
}
// DelHostManage 删除任务
func (h *HostManageSvc) DelHostManage(req request.DelHostManageReq) (err error) {
db, err := client.GetDbClient()
if err != nil {
err = resp.DbConnectError.WithError(err)
return
}
// 开启事务
session := db.NewSession()
defer session.Close()
session.Begin()
//删除主机分组
_, err = session.Table("host_manage").In("id", req.Id).Cols("is_delete").Update(&entity.HostManageList{
IsDelete: 1,
})
if err != nil {
err = resp.DbDeleteError.WithError(err)
session.Rollback()
return
}
//删除主机分组列表
_, err = session.Table("host_manage_list").In("host_group_id", req.Id).Cols("is_delete").Update(&entity.HostManageList{
IsDelete: 1,
})
if err != nil {
err = resp.DbDeleteError.WithError(err)
session.Rollback()
return
}
session.Commit()
return
}
// DetailsHostManage 详情
func (h *HostManageSvc) DetailsHostManage(id int) (hostManageRes response.HostManageRes, err error) {
db, err := client.GetDbClient()
if err != nil {
err = resp.DbConnectError.WithError(err)
return
}
var hostManage response.HostManage
hostList := make([]response.HostList, 0)
taskList := make([]response.TaskList, 0)
//查询主机分组
_, err = db.Table("host_manage").Where("is_delete = 0 AND id = ?", id).Get(&hostManage)
if err != nil {
err = resp.DbSelectError.WithError(err)
return
}
//查询主机列表
err = db.Table("host_manage_list").Where("is_delete = 0 AND host_group_id = ?", id).Find(&hostList)
if err != nil {
err = resp.DbSelectError.WithError(err)
return
}
//查询任务列表
err = db.Table("task_manage").Where("is_delete = 0 AND host_group_id = ?", id).Find(&taskList)
if err != nil {
err = resp.DbSelectError.WithError(err)
return
}
hostManageRes.Id = hostManage.Id
hostManageRes.HostName = hostManage.HostName
hostManageRes.TaskCnt = len(hostManageRes.TaskList)
hostManageRes.IpCnt = len(hostManageRes.HostList)
hostManageRes.CreateUser = hostManage.CreateUser
hostManageRes.CreateTime = hostManage.CreateTime
hostManageRes.UpdateUser = hostManage.UpdateUser
hostManageRes.UpdateTime = hostManage.UpdateTime
for _, v := range hostList {
if v.HostFileUrl != "" {
hostManageRes.HostFileUrl = v.HostFileUrl
break
}
}
hostManageRes.HostList = hostList
hostManageRes.TaskList = taskList
return
}
// ListHostManage 列表
func (h *HostManageSvc) ListHostManage(req request.ListHostManageReq) (total int64, hostManageListRes []response.HostManagesRes, err error) {
db, err := client.GetDbClient()
if err != nil {
err = resp.DbConnectError.WithError(err)
return
}
finder := db.Table("host_manage").Alias("hm").Where("hm.is_delete = 0")
if req.Search != "" {
finder.Where("hm.host_name LIKE ?", "%"+req.Search+"%")
}
if req.CreateDateFrom != "" {
finder.Where("hm.create_time >= ?", req.CreateDateFrom)
}
if req.CreateDateTo != "" {
finder.Where("hm.create_time <= ?", req.CreateDateFrom)
}
finder.OrderBy("hm.id")
//查询任务
total, err = finder.Select("hm.id,hm.host_name,hm.create_user,hm.create_time,(SELECT COUNT(*) FROM "+
"task_manage tm WHERE tm.is_delete = 0 AND tm.host_group_id = hm.ID) AS task_cnt,(SELECT COUNT(*) FROM "+
"host_manage_list hml WHERE hml.is_delete = 0 AND hml.conn_status = 0 AND hml.host_group_id = hm.ID) AS "+
"ip_cnt_err,(SELECT COUNT(*) FROM host_manage_list hml WHERE hml.is_delete = 0 AND hml.host_group_id = hm.ID) AS ip_cnt").
Limit(req.PageSize, (req.Page-1)*req.PageSize).FindAndCount(&hostManageListRes)
if err != nil {
err = resp.DbSelectError.WithError(err)
return
}
return
}
// StateHostManage 状态检测
func (h *HostManageSvc) StateHostManage(req request.StateHostManageReq) (total int64, hostManageListRes []response.HostManageListRes, err error) {
db, err := client.GetDbClient()
if err != nil {
err = resp.DbConnectError.WithError(err)
return
}
//状态检测。。
//查询异常列表
finder := db.Table("host_manage_list").Where("is_delete = 0 AND conn_status = 0 AND host_group_id = ?", req.Id)
finder.OrderBy("id")
//查询任务
total, err = finder.Limit(req.PageSize, (req.Page-1)*req.PageSize).FindAndCount(&hostManageListRes)
if err != nil {
err = resp.DbSelectError.WithError(err)
return
}
return
}
package service package service
import ( import (
"errors"
"fmt" "fmt"
"gitlab.wodcloud.com/smart-operation/so-operation-api/src/bean/entity" "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/request"
...@@ -24,15 +23,15 @@ func (t *TaskManageSvc) AddTaskManage(req request.AddTaskManageReq) (err error) ...@@ -24,15 +23,15 @@ func (t *TaskManageSvc) AddTaskManage(req request.AddTaskManageReq) (err error)
} }
// 校验 任务名称 是否重复 // 校验 任务名称 是否重复
has, err := db.Table("task_manage").Where("is_delete = 0 AND task_name = ?", req.TaskName).Exist() //has, err := db.Table("task_manage").Where("is_delete = 0 AND task_name = ?", req.TaskName).Exist()
if has { //if has {
err = resp.DbDataCheckError.WithError(errors.New("任务名称重复")) // err = resp.DbDataCheckError.WithError(errors.New("任务名称重复"))
return // return
} //}
if err != nil { //if err != nil {
err = resp.DbSelectError.WithError(err) // err = resp.DbSelectError.WithError(err)
return // return
} //}
taskManage := entity.TaskManage{ taskManage := entity.TaskManage{
TaskName: req.TaskName, TaskName: req.TaskName,
......
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