代码调整优化

This commit is contained in:
meilin.huang
2021-09-08 17:55:57 +08:00
parent 00f053573e
commit 318005f459
32 changed files with 209 additions and 355 deletions

View File

@@ -30,7 +30,12 @@ type Machine struct {
}
func (m *Machine) Machines(rc *ctx.ReqCtx) {
rc.ResData = m.MachineApp.GetMachineList(new(entity.Machine), ginx.GetPageParam(rc.GinCtx), new([]vo.MachineVO))
res := m.MachineApp.GetMachineList(new(entity.Machine), ginx.GetPageParam(rc.GinCtx), new([]*vo.MachineVO))
list := res.List.(*[]*vo.MachineVO)
for _, mv := range *list {
mv.HasCli = machine.HasCli(*mv.Id)
}
rc.ResData = res
}
func (m *Machine) SaveMachine(rc *ctx.ReqCtx) {
@@ -46,14 +51,14 @@ func (m *Machine) SaveMachine(rc *ctx.ReqCtx) {
}
func (m *Machine) DeleteMachine(rc *ctx.ReqCtx) {
id := uint64(ginx.PathParamInt(rc.GinCtx, "id"))
id := uint64(ginx.PathParamInt(rc.GinCtx, "machineId"))
rc.ReqParam = id
m.MachineApp.Delete(id)
}
// top命令信息
func (m *Machine) Top(rc *ctx.ReqCtx) {
rc.ResData = m.MachineApp.GetCli(GetMachineId(rc.GinCtx)).GetTop()
// 关闭机器客户端
func (m *Machine) CloseCli(rc *ctx.ReqCtx) {
machine.DeleteCli(GetMachineId(rc.GinCtx))
}
func (m *Machine) WsSSH(g *gin.Context) {
@@ -78,9 +83,7 @@ func (m *Machine) WsSSH(g *gin.Context) {
rows := ginx.QueryInt(g, "rows", 40)
sws, err := machine.NewLogicSshWsSession(cols, rows, m.MachineApp.GetCli(GetMachineId(g)), wsConn)
if sws == nil {
panic(biz.NewBizErr("连接失败"))
}
biz.ErrIsNilAppendErr(err, "连接失败:%s")
defer sws.Close()
quitChan := make(chan bool, 3)

View File

@@ -50,7 +50,7 @@ func (r *Redis) RedisInfo(rc *ctx.ReqCtx) {
i := 0
length := len(datas)
parseMap := make(map[string]map[string]string, 0)
parseMap := make(map[string]map[string]string)
for {
if i >= length {
break
@@ -60,7 +60,7 @@ func (r *Redis) RedisInfo(rc *ctx.ReqCtx) {
i++
key = strings.Trim(key, " ")
sectionMap := make(map[string]string, 0)
sectionMap := make(map[string]string)
for {
if i >= length || !strings.Contains(datas[i], ":") {
break
@@ -156,41 +156,6 @@ func (r *Redis) GetSetValue(rc *ctx.ReqCtx) {
rc.ResData = res
}
func (r *Redis) Test(rc *ctx.ReqCtx) {
schema := `{
"$schema": "http://json-schema.org/draft-04/schema#",
"title": "Product",
"description": "A product from Acme's catalog",
"type": "object",
"properties": {
"id": {
"description": "The unique identifier for a product",
"type": "integer"
},
"name": {
"description": "Name of the product",
"type": "string"
},
"price": {
"type": "number",
"minimum": 0,
"exclusiveMinimum": true
}
},
"required": ["id", "name", "price"]
}
`
// 获取请求报文的内容长度
len := rc.GinCtx.Request.ContentLength
// 新建一个字节切片,长度与请求报文的内容长度相同
body := make([]byte, len)
// 读取 r 的请求主体,并将具体内容读入 body 中
rc.GinCtx.Request.Body.Read(body)
err := utils.ValidJsonString(schema, string(body))
biz.ErrIsNilAppendErr(err, "%s")
}
func (r *Redis) SetStringValue(rc *ctx.ReqCtx) {
g := rc.GinCtx
keyValue := new(form.KeyValue)

View File

@@ -15,7 +15,7 @@ type AccountVO struct {
type MachineVO struct {
//models.BaseModel
Id *int64 `json:"id"`
Id *uint64 `json:"id"`
Name *string `json:"name"`
Username *string `json:"username"`
Ip *string `json:"ip"`
@@ -26,6 +26,7 @@ type MachineVO struct {
UpdateTime *time.Time `json:"updateTime"`
Modifier *string `json:"modifier"`
ModifierId *int64 `json:"modifierId"`
HasCli bool `json:"hasCli" gorm:"-"`
}
type MachineScriptVO struct {

View File

@@ -53,7 +53,7 @@ func (m *machineAppImpl) Save(me *entity.Machine) {
biz.IsTrue(oldMachine.Id == me.Id, "该机器信息已存在")
}
// 关闭连接
machine.Close(me.Id)
machine.DeleteCli(me.Id)
m.machineRepo.UpdateById(me)
} else {
biz.IsTrue(err != nil, "该机器信息已存在")
@@ -64,7 +64,7 @@ func (m *machineAppImpl) Save(me *entity.Machine) {
// 根据条件获取机器信息
func (m *machineAppImpl) Delete(id uint64) {
// 关闭连接
machine.Close(id)
machine.DeleteCli(id)
model.Tx(
func(db *gorm.DB) error {
// 删除machine表信息

View File

@@ -154,7 +154,7 @@ func (m *machineFileAppImpl) RemoveFile(fileId uint64, path string) {
sftpCli := m.getSftpCli(machineId)
file, err := sftpCli.Open(path)
biz.ErrIsNilAppendErr(err, "打开文件失败: %s")
fi, err := file.Stat()
fi, _ := file.Stat()
if fi.IsDir() {
err = sftpCli.RemoveDirectory(path)
} else {

View File

@@ -3,7 +3,6 @@ package machine
import (
"errors"
"fmt"
"io"
"mayfly-go/base/biz"
"mayfly-go/base/cache"
"mayfly-go/base/global"
@@ -29,10 +28,22 @@ type Cli struct {
var cliCache = cache.NewTimedCache(30*time.Minute, 5*time.Second).
WithUpdateAccessTime(true).
OnEvicted(func(key interface{}, value interface{}) {
global.Log.Info(fmt.Sprintf("删除机器连接缓存 id: %d", key))
value.(*Cli).Close()
})
// 是否存在指定id的客户端连接
func HasCli(machineId uint64) bool {
if _, ok := cliCache.Get(machineId); ok {
return true
}
return false
}
// 删除指定机器客户端,并关闭客户端连接
func DeleteCli(id uint64) {
cliCache.Delete(id)
}
// 从缓存中获取客户端信息,不存在则回调获取机器信息函数,并新建
func GetCli(machineId uint64, getMachine func(uint64) *entity.Machine) (*Cli, error) {
cli, err := cliCache.ComputeIfAbsent(machineId, func(key interface{}) (interface{}, error) {
@@ -42,6 +53,7 @@ func GetCli(machineId uint64, getMachine func(uint64) *entity.Machine) (*Cli, er
}
return c, nil
})
if cli != nil {
return cli.(*Cli), err
}
@@ -54,7 +66,7 @@ func newClient(machine *entity.Machine) (*Cli, error) {
return nil, errors.New("机器不存在")
}
global.Log.Infof("机器连接:%s:%d", machine.Ip, machine.Port)
global.Log.Infof("[%s]机器连接:%s:%d", machine.Name, machine.Ip, machine.Port)
cli := new(Cli)
cli.machine = machine
err := cli.connect()
@@ -109,11 +121,15 @@ func TestConn(m *entity.Machine) error {
// 关闭client和并从缓存中移除
func (c *Cli) Close() {
m := c.machine
global.Log.Info(fmt.Sprintf("关闭机器客户端连接-> id: %d, name: %s, ip: %s", m.Id, m.Name, m.Ip))
if c.client != nil {
c.client.Close()
c.client = nil
}
if c.sftpClient != nil {
c.sftpClient.Close()
c.sftpClient = nil
}
}
@@ -164,53 +180,3 @@ func (c *Cli) Run(shell string) (*string, error) {
res := string(buf)
return &res, nil
}
//执行带交互的命令
func (c *Cli) RunTerminal(shell string, stdout, stderr io.Writer) error {
session, err := c.GetSession()
if err != nil {
return err
}
//defer session.Close()
// fd := int(os.Stdin.Fd())
// oldState, err := terminal.MakeRaw(fd)
// if err != nil {
// panic(err)
// }
// defer terminal.Restore(fd, oldState)
// writer, err := session.StdinPipe()
biz.ErrIsNilAppendErr(err, "获取session stdin 错误:%s")
session.Stdout = stdout
session.Stderr = stderr
// termWidth, termHeight, err := terminal.GetSize(fd)
// if err != nil {
// panic(err)
// }
// Set up terminal modes
// modes := ssh.TerminalModes{
// ssh.ECHO: 1, // enable echoing
// ssh.TTY_OP_ISPEED: 14400, // input speed = 14.4kbaud
// ssh.TTY_OP_OSPEED: 14400, // output speed = 14.4kbaud
// }
// // Request pseudo terminal
// if err := session.RequestPty("xterm-256color", 400, 800, modes); err != nil {
// return err
// }
session.Shell()
session.Wait()
// writer.Write([]byte(shell))
session.Run(shell)
return nil
}
// 关闭指定机器的连接
func Close(id uint64) {
if cli, ok := cliCache.Get(id); ok {
cli.(*Cli).Close()
}
}

View File

@@ -24,14 +24,15 @@ func InitMachineRouter(router *gin.RouterGroup) {
})
delMachine := ctx.NewLogInfo("删除机器")
db.DELETE("/delete/:id", func(c *gin.Context) {
db.DELETE(":machineId", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).
WithLog(delMachine).
Handle(m.DeleteMachine)
})
db.GET(":machineId/top", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).Handle(m.Top)
closeCli := ctx.NewLogInfo("关闭机器客户端")
db.DELETE(":machineId/close-cli", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).WithLog(closeCli).Handle(m.CloseCli)
})
db.GET(":machineId/terminal", m.WsSSH)

View File

@@ -70,10 +70,5 @@ func InitRedisRouter(router *gin.RouterGroup) {
redis.POST(":id/hash-value", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).Handle(rs.SetStringValue)
})
// 设置hash类型值
redis.POST("test", func(c *gin.Context) {
ctx.NewReqCtxWithGin(c).WithNeedToken(false).Handle(rs.Test)
})
}
}