feat: 更新多个模块以支持新的数据结构和日志格式

This commit is contained in:
TsMask
2025-02-20 10:08:27 +08:00
parent 045a2b6b01
commit f3c33b31ac
272 changed files with 13246 additions and 15885 deletions

View File

@@ -10,11 +10,11 @@ import (
"github.com/gin-gonic/gin"
"be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx"
"be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/ssh"
"be.ems/src/framework/utils/file"
"be.ems/src/framework/utils/generate"
"be.ems/src/framework/utils/ssh"
"be.ems/src/framework/vo/result"
neService "be.ems/src/modules/network_element/service"
)
@@ -45,7 +45,7 @@ type NeActionController struct {
// @Description Sending files from local to network elements
// @Router /ne/action/pushFile [post]
func (s *NeActionController) PushFile(c *gin.Context) {
language := ctx.AcceptLanguage(c)
language := reqctx.AcceptLanguage(c)
var body struct {
NeType string `json:"neType" binding:"required"`
NeID string `json:"neId" binding:"required"`
@@ -53,40 +53,41 @@ func (s *NeActionController) PushFile(c *gin.Context) {
DelTemp bool `json:"delTemp"` // 删除本地临时文件
}
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(body.NeType, body.NeID)
neInfo := s.neInfoService.FindByNeTypeAndNeID(body.NeType, body.NeID)
if neInfo.NeId != body.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
// 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP()
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
defer sftpClient.Close()
// 本地文件
localFilePath := file.ParseUploadFilePath(body.UploadPath)
localFilePath := file.ParseUploadFileAbsPath(body.UploadPath)
// 网元端临时目录
sshClient.RunCMD("mkdir -p /tmp/omc/push && sudo chmod 777 -R /tmp/omc")
neFilePath := filepath.ToSlash(filepath.Join("/tmp/omc/push", filepath.Base(localFilePath)))
// 复制到远程
if err = sftpClient.CopyFileLocalToRemote(localFilePath, neFilePath); err != nil {
c.JSON(200, result.ErrMsg("Please check if the file exists or if scp is allowed to copy remotely"))
c.JSON(200, resp.ErrMsg("Please check if the file exists or if scp is allowed to copy remotely"))
return
}
@@ -95,7 +96,7 @@ func (s *NeActionController) PushFile(c *gin.Context) {
_ = os.Remove(localFilePath)
}
}()
c.JSON(200, result.OkData(filepath.ToSlash(neFilePath)))
c.JSON(200, resp.OkData(filepath.ToSlash(neFilePath)))
}
// 从网元到本地获取文件
@@ -105,7 +106,7 @@ func (s *NeActionController) PushFile(c *gin.Context) {
// @Tags network_element/action
// @Accept json
// @Produce json
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC) default(UPF)
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC) default(UPF)
// @Param neId query string true "NE ID" default(001)
// @Param path query string true "dir path" default(/var/log)
// @Param fileName query string true "file name"
@@ -116,7 +117,7 @@ func (s *NeActionController) PushFile(c *gin.Context) {
// @Description Getting files from the network element to the local
// @Router /ne/action/pullFile [get]
func (s *NeActionController) PullFile(c *gin.Context) {
language := ctx.AcceptLanguage(c)
language := reqctx.AcceptLanguage(c)
var querys struct {
NeType string `form:"neType" binding:"required"`
NeID string `form:"neId" binding:"required"`
@@ -125,28 +126,29 @@ func (s *NeActionController) PullFile(c *gin.Context) {
DelTemp bool `form:"delTemp"` // 删除本地临时文件
}
if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID)
neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
// 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP()
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
defer sftpClient.Close()
@@ -159,7 +161,7 @@ func (s *NeActionController) PullFile(c *gin.Context) {
}
// 复制到本地
if err = sftpClient.CopyFileRemoteToLocal(nePath, localFilePath); err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
@@ -178,7 +180,7 @@ func (s *NeActionController) PullFile(c *gin.Context) {
// @Tags network_element/action
// @Accept json
// @Produce json
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC) default(UPF)
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC) default(UPF)
// @Param neId query string true "NE ID" default(001)
// @Param path query string true "dir path" default(/var/log)
// @Param delTemp query boolean false "Delete Temp File" default(false)
@@ -188,7 +190,7 @@ func (s *NeActionController) PullFile(c *gin.Context) {
// @Description Get directories compressed to ZIP from the network element to the local area
// @Router /ne/action/pullDirZip [get]
func (s *NeActionController) PullDirZip(c *gin.Context) {
language := ctx.AcceptLanguage(c)
language := reqctx.AcceptLanguage(c)
var querys struct {
NeType string `form:"neType" binding:"required"`
NeID string `form:"neId" binding:"required"`
@@ -196,28 +198,29 @@ func (s *NeActionController) PullDirZip(c *gin.Context) {
DelTemp bool `form:"delTemp"` // 删除本地临时文件
}
if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID)
neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
// 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
defer sshClient.Close()
// 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP()
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
defer sftpClient.Close()
@@ -231,7 +234,7 @@ func (s *NeActionController) PullDirZip(c *gin.Context) {
// 复制到本地
localDirFilePath := filepath.Join(localFilePath, "zip")
if err = sftpClient.CopyDirRemoteToLocal(nePath, localDirFilePath); err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
@@ -239,7 +242,7 @@ func (s *NeActionController) PullDirZip(c *gin.Context) {
zipFileName := fmt.Sprintf("%s-%s-%s.zip", neInfo.NeType, neInfo.NeId, dirName)
zipFilePath := filepath.Join(localFilePath, zipFileName)
if err := file.CompressZipByDir(zipFilePath, localDirFilePath); err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
@@ -258,7 +261,7 @@ func (s *NeActionController) PullDirZip(c *gin.Context) {
// @Tags network_element/action
// @Accept json
// @Produce json
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC) default(UPF)
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC) default(UPF)
// @Param neId query string true "NE ID" default(001)
// @Param path query string true "file path" default(/var/log)
// @Param fileName query string true "file name"
@@ -268,7 +271,7 @@ func (s *NeActionController) PullDirZip(c *gin.Context) {
// @Description Viewing the contents of a file on the network element side
// @Router /ne/action/viewFile [get]
func (s *NeActionController) ViewFile(c *gin.Context) {
language := ctx.AcceptLanguage(c)
language := reqctx.AcceptLanguage(c)
var querys struct {
NeType string `form:"neType" binding:"required"`
NeID string `form:"neId" binding:"required"`
@@ -276,21 +279,22 @@ func (s *NeActionController) ViewFile(c *gin.Context) {
FileName string `form:"fileName" binding:"required"`
}
if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID)
neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
// 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
defer sshClient.Close()
@@ -301,10 +305,10 @@ func (s *NeActionController) ViewFile(c *gin.Context) {
output, err := sshClient.RunCMD(fmt.Sprintf("cat %s", nePath))
output = strings.TrimSpace(output)
if err != nil || strings.HasPrefix(output, "ls: ") {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "file view cat error")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "file view cat error")))
return
}
c.JSON(200, result.OkData(output))
c.JSON(200, resp.OkData(output))
}
// 网元端文件列表
@@ -314,7 +318,7 @@ func (s *NeActionController) ViewFile(c *gin.Context) {
// @Tags network_element/action
// @Accept json
// @Produce json
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC) default(UPF)
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC) default(UPF)
// @Param neId query string true "NE ID" default(001)
// @Param path query string true "file path" default(/var/log)
// @Param pageNum query number true "pageNum" default(1)
@@ -326,7 +330,7 @@ func (s *NeActionController) ViewFile(c *gin.Context) {
// @Description List of files on the network element side
// @Router /ne/action/files [get]
func (s *NeActionController) Files(c *gin.Context) {
language := ctx.AcceptLanguage(c)
language := reqctx.AcceptLanguage(c)
var querys struct {
NeType string `form:"neType" binding:"required"`
NeID string `form:"neId" binding:"required"`
@@ -336,21 +340,22 @@ func (s *NeActionController) Files(c *gin.Context) {
Search string `form:"search"`
}
if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID)
neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
// 网元主机的SSH客户端
sshClient, err := s.neInfoService.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
defer sshClient.Close()
@@ -358,7 +363,7 @@ func (s *NeActionController) Files(c *gin.Context) {
// 获取文件列表
rows, err := ssh.FileList(sshClient, querys.Path, querys.Search)
if err != nil {
c.JSON(200, result.Ok(map[string]any{
c.JSON(200, resp.OkData(map[string]any{
"path": querys.Path,
"total": len(rows),
"rows": []ssh.FileListRow{},
@@ -379,7 +384,7 @@ func (s *NeActionController) Files(c *gin.Context) {
splitRows = rows[start:end]
}
c.JSON(200, result.Ok(map[string]any{
c.JSON(200, resp.OkData(map[string]any{
"path": querys.Path,
"total": lenNum,
"rows": splitRows,
@@ -400,21 +405,22 @@ func (s *NeActionController) Files(c *gin.Context) {
// @Description Network element service operation
// @Router /ne/action/service [put]
func (s *NeActionController) Service(c *gin.Context) {
language := ctx.AcceptLanguage(c)
language := reqctx.AcceptLanguage(c)
var body struct {
NeType string `json:"neType" binding:"required"`
NeID string `json:"neId" binding:"required"`
Action string `json:"action" binding:"required,oneof=start restart stop reboot poweroff"` // 操作行为
}
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(body.NeType, body.NeID)
neInfo := s.neInfoService.FindByNeTypeAndNeID(body.NeType, body.NeID)
if neInfo.NeId != body.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
@@ -439,8 +445,8 @@ func (s *NeActionController) Service(c *gin.Context) {
_, err := s.neInfoService.NeRunSSHCmd(body.NeType, body.NeID, cmdStr)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, result.Ok(nil))
c.JSON(200, resp.Ok(nil))
}

View File

@@ -2,18 +2,18 @@ package controller
import (
"encoding/json"
"strings"
"fmt"
cm_omc "be.ems/features/cm/omc"
"be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx"
"be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
neFetchlink "be.ems/src/modules/network_element/fetch_link"
"be.ems/src/modules/network_element/model"
neService "be.ems/src/modules/network_element/service"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
// NewNeConfig 网元参数配置 实例化控制层
@@ -33,125 +33,127 @@ type NeConfigController struct {
// 网元参数配置可用属性值列表
//
// GET /list
func (s *NeConfigController) List(c *gin.Context) {
querys := ctx.QueryMapString(c)
rows, total := s.neConfigService.SelectPage(querys)
c.JSON(200, result.Ok(map[string]any{"total": total, "rows": rows}))
func (s NeConfigController) List(c *gin.Context) {
query := reqctx.QueryMap(c)
rows, total := s.neConfigService.FindByPage(query)
c.JSON(200, resp.OkData(map[string]any{"total": total, "rows": rows}))
}
// 网元参数配置可用属性值信息
//
// GET /info/:id
func (s *NeConfigController) Info(c *gin.Context) {
language := ctx.AcceptLanguage(c)
id := c.Param("id")
if id == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
func (s NeConfigController) Info(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
id := parse.Number(c.Query("id"))
if id <= 0 {
c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return
}
data := s.neConfigService.SelectById(id)
data := s.neConfigService.FindById(id)
if data.ID != id {
// 没有可访问参数配置数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neConfig.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neConfig.noData")))
return
}
// 将字符串转json数据
if err := json.Unmarshal([]byte(data.ParamJson), &data.ParamData); err != nil {
c.JSON(400, result.CodeMsg(400, err.Error()))
c.JSON(400, resp.CodeMsg(400, err.Error()))
return
}
c.JSON(200, result.OkData(data))
c.JSON(200, resp.OkData(data))
}
// 网元参数配置可用属性值新增
//
// POST /
func (s *NeConfigController) Add(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeConfigController) Add(c *gin.Context) {
var body model.NeConfig
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 将json数据转字符串存储
paramDataByte, err := json.Marshal(body.ParamData)
if err != nil {
c.JSON(400, result.CodeMsg(400, err.Error()))
c.JSON(400, resp.CodeMsg(400, err.Error()))
return
}
body.ParamJson = string(paramDataByte)
insertId := s.neConfigService.Insert(body)
if insertId != "" {
c.JSON(200, result.Ok(nil))
if insertId > 0 {
c.JSON(200, resp.Ok(nil))
return
}
c.JSON(200, result.Err(nil))
c.JSON(200, resp.Err(nil))
}
// 网元参数配置可用属性值修改
//
// PUT /
func (s *NeConfigController) Edit(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeConfigController) Edit(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body model.NeConfig
err := c.ShouldBindBodyWith(&body, binding.JSON)
if err != nil || body.ID == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 检查是否存在
data := s.neConfigService.SelectById(body.ID)
data := s.neConfigService.FindById(body.ID)
if data.ID != body.ID {
// 没有可访问主机命令数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neConfig.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neConfig.noData")))
return
}
// 将json数据转字符串存储
paramDataByte, err := json.Marshal(body.ParamData)
if err != nil {
c.JSON(400, result.CodeMsg(400, err.Error()))
c.JSON(400, resp.CodeMsg(400, err.Error()))
return
}
body.ParamJson = string(paramDataByte)
rows := s.neConfigService.Update(body)
if rows > 0 {
c.JSON(200, result.Ok(nil))
c.JSON(200, resp.Ok(nil))
return
}
c.JSON(200, result.Err(nil))
c.JSON(200, resp.Err(nil))
}
// 网元参数配置可用属性值删除
//
// DELETE /
func (s *NeConfigController) Remove(c *gin.Context) {
language := ctx.AcceptLanguage(c)
id, okId := c.GetQuery("id")
if id == "" || !okId {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
func (s NeConfigController) Remove(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
id := c.Query("id")
if id == "" {
c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return
}
// 处理字符转id数组后去重
idsArr := strings.Split(id, ",")
uniqueIDs := parse.RemoveDuplicates(idsArr)
if len(uniqueIDs) <= 0 {
c.JSON(200, result.Err(nil))
return
uniqueIDs := parse.RemoveDuplicatesToArray(id, ",")
// 转换成int64数组类型
ids := make([]int64, 0)
for _, v := range uniqueIDs {
ids = append(ids, parse.Number(v))
}
rows, err := s.neConfigService.DeleteByIds(uniqueIDs)
rows, err := s.neConfigService.DeleteByIds(ids)
if err != nil {
c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error())))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
return
}
msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
c.JSON(200, result.OkMsg(msg))
c.JSON(200, resp.OkMsg(msg))
}
// 网元参数配置可用属性值列表指定网元类型全部无分页
@@ -161,21 +163,21 @@ func (s *NeConfigController) Remove(c *gin.Context) {
// @Tags network_element/config
// @Accept json
// @Produce json
// @Param neType path string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC)
// @Param neType path string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC)
// @Success 200 {object} object "Response Results"
// @Security TokenAuth
// @Summary Network Element Parameter Configuration Available Attribute Values List Specify Network Element Type All Unpaged
// @Description Network Element Parameter Configuration Available Attribute Values List Specify Network Element Type All Unpaged
// @Router /ne/config/list/{neType} [get]
func (s *NeConfigController) ListByNeType(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeConfigController) ListByNeType(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
neType := c.Param("neType")
if neType == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return
}
data := s.neConfigService.SelectNeConfigByNeType(neType)
c.JSON(200, result.OkData(data))
data := s.neConfigService.FindByNeType(neType)
c.JSON(200, resp.OkData(data))
}
// 网元参数配置数据信息
@@ -185,7 +187,7 @@ func (s *NeConfigController) ListByNeType(c *gin.Context) {
// @Tags network_element/config
// @Accept json
// @Produce json
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC)
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC)
// @Param neId query string true "NE ID" default(001)
// @Param paramName query string true "Available attributes, based on querying the list of attributes"
// @Success 200 {object} object "Response Results"
@@ -193,21 +195,22 @@ func (s *NeConfigController) ListByNeType(c *gin.Context) {
// @Summary Network Element Parameter Configuration Data Information
// @Description Network Element Parameter Configuration Data Information
// @Router /ne/config/data [get]
func (s *NeConfigController) DataInfo(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeConfigController) DataInfo(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var query struct {
NeType string `form:"neType" binding:"required"` // 网元类型
NeId string `form:"neId" binding:"required"` // 网元ID
ParamName string `form:"paramName" binding:"required"` // 可用属性
}
if err := c.ShouldBindQuery(&query); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(query.NeType, query.NeId)
neInfo := s.neInfoService.FindByNeTypeAndNeID(query.NeType, query.NeId)
if neInfo.NeId != query.NeId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
@@ -215,21 +218,21 @@ func (s *NeConfigController) DataInfo(c *gin.Context) {
var o *cm_omc.ConfigOMC
resData, err := o.Query(query.ParamName)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, result.OkData(resData))
c.JSON(200, resp.OkData(resData))
return
}
// 网元直连
resData, err := neFetchlink.NeConfigInfo(neInfo, query.ParamName)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, result.Ok(resData))
c.JSON(200, resp.Ok(resData))
}
// 网元参数配置数据修改
@@ -245,8 +248,8 @@ func (s *NeConfigController) DataInfo(c *gin.Context) {
// @Summary Network element parameter configuration data modification
// @Description Network element parameter configuration data modification
// @Router /ne/config/data [put]
func (s *NeConfigController) DataEdit(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeConfigController) DataEdit(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body struct {
NeType string `json:"neType" binding:"required"` // 网元类型
NeId string `json:"neId" binding:"required"` // 网元ID
@@ -254,34 +257,35 @@ func (s *NeConfigController) DataEdit(c *gin.Context) {
ParamData map[string]any `json:"paramData" binding:"required"`
Loc string `json:"loc"` // 仅array使用与数据对象内index一致,有多层时划分嵌套层(index/subParamName/index)
}
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(body.NeType, body.NeId)
neInfo := s.neInfoService.FindByNeTypeAndNeID(body.NeType, body.NeId)
if neInfo.NeId != body.NeId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
if body.NeType == "OMC" {
var o *cm_omc.ConfigOMC
resData, err := o.Modify(body.ParamName, body.ParamData)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, result.OkData(resData))
c.JSON(200, resp.OkData(resData))
return
}
// 网元直连
resData, err := neFetchlink.NeConfigUpdate(neInfo, body.ParamName, body.Loc, body.ParamData)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, result.OkData(resData))
c.JSON(200, resp.OkData(resData))
}
// 网元参数配置数据新增array
@@ -297,8 +301,8 @@ func (s *NeConfigController) DataEdit(c *gin.Context) {
// @Summary Network element parameter configuration data added (array)
// @Description Network element parameter configuration data added (array)
// @Router /ne/config/data [post]
func (s *NeConfigController) DataAdd(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeConfigController) DataAdd(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body struct {
NeType string `json:"neType" binding:"required"` // 网元类型
NeId string `json:"neId" binding:"required"` // 网元ID
@@ -306,37 +310,38 @@ func (s *NeConfigController) DataAdd(c *gin.Context) {
ParamData map[string]any `json:"paramData" binding:"required"` // 数据对象
Loc string `json:"loc" binding:"required"` // 与数据对象内index一致,有多层时划分嵌套层(index/subParamName/index)
}
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 检查是否array
info := s.neConfigService.SelectNeConfigByNeTypeAndParamName(body.NeType, body.ParamName)
info := s.neConfigService.FindByNeTypeAndParamName(body.NeType, body.ParamName)
if info.ParamType != "array" {
c.JSON(400, result.CodeMsg(400, "this attribute does not support adding"))
c.JSON(400, resp.CodeMsg(400, "this attribute does not support adding"))
return
}
// 必须含有index
_, idxOk := body.ParamData["index"]
if info.ParamType == "array" && !idxOk {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return
}
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(body.NeType, body.NeId)
neInfo := s.neInfoService.FindByNeTypeAndNeID(body.NeType, body.NeId)
if neInfo.NeId != body.NeId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
// 网元直连
resData, err := neFetchlink.NeConfigInstall(neInfo, body.ParamName, body.Loc, body.ParamData)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, result.OkData(resData))
c.JSON(200, resp.OkData(resData))
}
// 网元参数配置数据删除array
@@ -346,7 +351,7 @@ func (s *NeConfigController) DataAdd(c *gin.Context) {
// @Tags network_element/config
// @Accept json
// @Produce json
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC)
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC)
// @Param neId query string true "NE ID" default(001)
// @Param paramName query string true "Available attributes, based on querying the list of attributes"
// @Param loc query string true "Array index"
@@ -355,8 +360,8 @@ func (s *NeConfigController) DataAdd(c *gin.Context) {
// @Summary Network element parameter configuration data deletion (array)
// @Description Network element parameter configuration data deletion (array)
// @Router /ne/config/data [delete]
func (s *NeConfigController) DataRemove(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeConfigController) DataRemove(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var query struct {
NeType string `form:"neType" binding:"required"` // 网元类型
NeId string `form:"neId" binding:"required"` // 网元ID
@@ -364,28 +369,28 @@ func (s *NeConfigController) DataRemove(c *gin.Context) {
Loc string `form:"loc" binding:"required"` // 与数据对象内index一致,有多层时划分嵌套层(index/subParamName/index)
}
if err := c.ShouldBindQuery(&query); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return
}
// 检查是否array
info := s.neConfigService.SelectNeConfigByNeTypeAndParamName(query.NeType, query.ParamName)
info := s.neConfigService.FindByNeTypeAndParamName(query.NeType, query.ParamName)
if info.ParamType != "array" {
c.JSON(400, result.CodeMsg(400, "this attribute does not support adding"))
c.JSON(400, resp.CodeMsg(400, "this attribute does not support adding"))
return
}
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(query.NeType, query.NeId)
neInfo := s.neInfoService.FindByNeTypeAndNeID(query.NeType, query.NeId)
if neInfo.NeId != query.NeId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
// 网元直连
resData, err := neFetchlink.NeConfigDelete(neInfo, query.ParamName, query.Loc)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, result.OkData(resData))
c.JSON(200, resp.OkData(resData))
}

View File

@@ -1,19 +1,20 @@
package controller
import (
"fmt"
"os"
"path/filepath"
"strings"
"be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx"
"be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/file"
"be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
"be.ems/src/modules/network_element/model"
neService "be.ems/src/modules/network_element/service"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
// NewNeConfigBackup 实例化控制层 NeConfigBackupController 结构体
@@ -33,33 +34,32 @@ type NeConfigBackupController struct {
// 网元配置文件备份记录列表
//
// GET /list
func (s *NeConfigBackupController) List(c *gin.Context) {
querys := ctx.QueryMap(c)
data := s.neConfigBackupService.SelectPage(querys)
c.JSON(200, result.Ok(data))
func (s NeConfigBackupController) List(c *gin.Context) {
query := reqctx.QueryMap(c)
rows, total := s.neConfigBackupService.FindByPage(query)
c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
}
// 网元配置文件备份记录信息
//
// GET /download?id=xx
func (s *NeConfigBackupController) Download(c *gin.Context) {
language := ctx.AcceptLanguage(c)
id, ok := c.GetQuery("id")
if !ok || id == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
func (s NeConfigBackupController) Download(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
id := parse.Number(c.Query("id"))
if id <= 0 {
c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return
}
item := s.neConfigBackupService.SelectById(id)
item := s.neConfigBackupService.FindById(id)
if item.ID != id {
// 没有可访问主机命令数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neConfigBackup.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neConfigBackup.noData")))
return
}
if _, err := os.Stat(item.Path); err != nil {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neConfigBackup.notFoundFile")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neConfigBackup.notFoundFile")))
return
}
c.FileAttachment(item.Path, item.Name)
@@ -68,125 +68,129 @@ func (s *NeConfigBackupController) Download(c *gin.Context) {
// 网元配置文件备份记录修改
//
// PUT /
func (s *NeConfigBackupController) Edit(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeConfigBackupController) Edit(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body struct {
ID string `json:"id" binding:"required"` // 记录ID
ID int64 `json:"id" binding:"required"` // 记录ID
Name string `json:"name" binding:"required"` // 名称
Remark string `json:"remark" binding:"required"` // 备注
}
err := c.ShouldBindBodyWith(&body, binding.JSON)
if err != nil || body.ID == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 检查是否存在
data := s.neConfigBackupService.SelectById(body.ID)
data := s.neConfigBackupService.FindById(body.ID)
if data.ID != body.ID {
// 没有可访问主机命令数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neConfig.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neConfig.noData")))
return
}
data.Name = body.Name
data.Remark = body.Remark
data.UpdateBy = ctx.LoginUserToUserName(c)
data.UpdateBy = reqctx.LoginUserToUserName(c)
rows := s.neConfigBackupService.Update(data)
if rows > 0 {
c.JSON(200, result.Ok(nil))
c.JSON(200, resp.Ok(nil))
return
}
c.JSON(200, result.Err(nil))
c.JSON(200, resp.Err(nil))
}
// 网元配置文件备份记录删除
//
// DELETE /?id=xx
func (s *NeConfigBackupController) Remove(c *gin.Context) {
language := ctx.AcceptLanguage(c)
id, ok := c.GetQuery("id")
if !ok || id == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
func (s NeConfigBackupController) Remove(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
id := c.Query("id")
if id == "" {
c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return
}
// 处理字符转id数组后去重
ids := strings.Split(id, ",")
uniqueIDs := parse.RemoveDuplicates(ids)
if len(uniqueIDs) <= 0 {
c.JSON(200, result.Err(nil))
return
uniqueIDs := parse.RemoveDuplicatesToArray(id, ",")
// 转换成int64数组类型
ids := make([]int64, 0)
for _, v := range uniqueIDs {
ids = append(ids, parse.Number(v))
}
rows, err := s.neConfigBackupService.DeleteByIds(uniqueIDs)
rows, err := s.neConfigBackupService.DeleteByIds(ids)
if err != nil {
c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error())))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
return
}
msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
c.JSON(200, result.OkMsg(msg))
c.JSON(200, resp.OkMsg(msg))
}
// 网元配置文件备份导入
//
// POST /import
func (s *NeConfigBackupController) Import(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeConfigBackupController) Import(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body struct {
NeType string `json:"neType" binding:"required"`
NeId string `json:"neId" binding:"required"`
Type string `json:"type" binding:"required,oneof=backup upload"` // 导入类型
Path string `json:"path" binding:"required"` // 文件路径
}
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
if !strings.HasSuffix(body.Path, ".zip") {
c.JSON(200, result.ErrMsg("Only supports decompression of zip files"))
c.JSON(200, resp.ErrMsg("Only supports decompression of zip files"))
return
}
// 查网元
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(body.NeType, body.NeId)
neInfo := s.neInfoService.FindByNeTypeAndNeID(body.NeType, body.NeId)
if neInfo.NeId != body.NeId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
// 将zip文件解压到本地后复制到网元端
localFilePath := body.Path
if body.Type == "upload" {
localFilePath = file.ParseUploadFilePath(body.Path)
localFilePath = file.ParseUploadFileAbsPath(body.Path)
}
if err := s.neConfigBackupService.NeConfigLocalToNe(neInfo, localFilePath); err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
if err := s.neConfigBackupService.FileLocalToNe(neInfo, localFilePath); err != nil {
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, result.Ok(nil))
c.JSON(200, resp.Ok(nil))
}
// 网元配置文件备份导出
//
// POST /export
func (s *NeConfigBackupController) Export(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeConfigBackupController) Export(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body struct {
NeType string `json:"neType" binding:"required"`
NeId string `json:"neId" binding:"required"`
}
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 查网元
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(body.NeType, body.NeId)
neInfo := s.neInfoService.FindByNeTypeAndNeID(body.NeType, body.NeId)
if neInfo.NeId != body.NeId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
// 将网元文件备份到本地
zipFilePath, err := s.neConfigBackupService.NeConfigNeToLocal(neInfo)
zipFilePath, err := s.neConfigBackupService.FileNeToLocal(neInfo)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
// 新增备份记录
@@ -195,7 +199,7 @@ func (s *NeConfigBackupController) Export(c *gin.Context) {
NeId: neInfo.NeId,
Name: filepath.Base(zipFilePath),
Path: zipFilePath,
CreateBy: ctx.LoginUserToUserName(c),
CreateBy: reqctx.LoginUserToUserName(c),
}
s.neConfigBackupService.Insert(item)
c.FileAttachment(item.Path, item.Name)

View File

@@ -1,19 +1,20 @@
package controller
import (
"fmt"
"strings"
"be.ems/src/framework/database/redis"
"be.ems/src/framework/i18n"
"be.ems/src/framework/redis"
"be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/ssh"
"be.ems/src/framework/telnet"
"be.ems/src/framework/utils/ctx"
"be.ems/src/framework/utils/parse"
"be.ems/src/framework/utils/ssh"
"be.ems/src/framework/vo/result"
"be.ems/src/modules/network_element/model"
neService "be.ems/src/modules/network_element/service"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
// 实例化控制层 NeHostController 结构体
@@ -31,11 +32,10 @@ type NeHostController struct {
// 网元主机列表
//
// GET /list
func (s *NeHostController) List(c *gin.Context) {
querys := ctx.QueryMap(c)
data := s.neHostService.SelectPage(querys)
func (s NeHostController) List(c *gin.Context) {
query := reqctx.QueryMap(c)
rows, total := s.neHostService.FindByPage(query)
rows := data["rows"].([]model.NeHost)
arr := &rows
for i := range *arr {
(*arr)[i].Password = "-"
@@ -43,129 +43,139 @@ func (s *NeHostController) List(c *gin.Context) {
(*arr)[i].PassPhrase = "-"
}
c.JSON(200, result.Ok(data))
c.JSON(200, resp.OkData(map[string]any{"total": total, "rows": rows}))
}
// 网元主机信息
//
// GET /:hostId
func (s *NeHostController) Info(c *gin.Context) {
language := ctx.AcceptLanguage(c)
hostId := c.Param("hostId")
if hostId == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
// GET /:id
func (s NeHostController) Info(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
id := parse.Number(c.Param("id"))
if id <= 0 {
c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return
}
neHost := s.neHostService.SelectById(hostId)
if neHost.HostID != hostId {
neHost := s.neHostService.FindById(id)
if neHost.ID != id {
// 没有可访问主机信息数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neHost.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.noData")))
return
}
c.JSON(200, result.OkData(neHost))
c.JSON(200, resp.OkData(neHost))
}
// 网元主机新增
//
// POST /
func (s *NeHostController) Add(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeHostController) Add(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body model.NeHost
err := c.ShouldBindBodyWith(&body, binding.JSON)
if err != nil || body.HostID != "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
if body.ID == 0 {
c.JSON(400, resp.CodeMsg(40010, "bind err: id not is empty"))
return
}
if body.GroupID == "1" {
// 主机信息操作【%s】失败禁止操作网元
msg := i18n.TKey(language, "neHost.banNE")
c.JSON(200, result.ErrMsg(msg))
c.JSON(200, resp.ErrMsg(msg))
return
}
// 检查属性值唯一
uniqueHost := s.neHostService.CheckUniqueHostTitle(body.GroupID, body.Title, body.HostType, "")
uniqueHost := s.neHostService.CheckUniqueHostTitle(body.GroupID, body.Title, body.HostType, 0)
if !uniqueHost {
// 主机信息操作【%s】失败同组内名称已存在
msg := i18n.TTemplate(language, "neHost.errKeyExists", map[string]any{"name": body.Title})
c.JSON(200, result.ErrMsg(msg))
c.JSON(200, resp.ErrMsg(msg))
return
}
body.CreateBy = ctx.LoginUserToUserName(c)
body.CreateBy = reqctx.LoginUserToUserName(c)
insertId := s.neHostService.Insert(body)
if insertId != "" {
c.JSON(200, result.Ok(nil))
if insertId > 0 {
c.JSON(200, resp.Ok(nil))
return
}
c.JSON(200, result.Err(nil))
c.JSON(200, resp.Err(nil))
}
// 网元主机修改
//
// PUT /
func (s *NeHostController) Edit(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeHostController) Edit(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body model.NeHost
err := c.ShouldBindBodyWith(&body, binding.JSON)
if err != nil || body.HostID == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
if body.ID <= 0 {
c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return
}
// 检查属性值唯一
uniqueHost := s.neHostService.CheckUniqueHostTitle(body.GroupID, body.Title, body.HostType, body.HostID)
uniqueHost := s.neHostService.CheckUniqueHostTitle(body.GroupID, body.Title, body.HostType, body.ID)
if !uniqueHost {
// 主机信息操作【%s】失败同组内名称已存在
msg := i18n.TTemplate(language, "neHost.errKeyExists", map[string]any{"name": body.Title})
c.JSON(200, result.ErrMsg(msg))
c.JSON(200, resp.ErrMsg(msg))
return
}
// 检查是否存在
neHost := s.neHostService.SelectById(body.HostID)
if neHost.HostID != body.HostID {
neHost := s.neHostService.FindById(body.ID)
if neHost.ID != body.ID {
// 没有可访问主机信息数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neHost.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.noData")))
return
}
body.UpdateBy = ctx.LoginUserToUserName(c)
body.UpdateBy = reqctx.LoginUserToUserName(c)
rows := s.neHostService.Update(body)
if rows > 0 {
c.JSON(200, result.Ok(nil))
c.JSON(200, resp.Ok(nil))
return
}
c.JSON(200, result.Err(nil))
c.JSON(200, resp.Err(nil))
}
// 网元主机删除
//
// DELETE /:hostIds
func (s *NeHostController) Remove(c *gin.Context) {
language := ctx.AcceptLanguage(c)
hostIds := c.Param("hostIds")
if hostIds == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
// DELETE /:id
func (s NeHostController) Remove(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
id := c.Param("id")
if id == "" {
c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return
}
// 处理字符转id数组后去重
ids := strings.Split(hostIds, ",")
uniqueIDs := parse.RemoveDuplicates(ids)
if len(uniqueIDs) <= 0 {
c.JSON(200, result.Err(nil))
return
uniqueIDs := parse.RemoveDuplicatesToArray(id, ",")
// 转换成int64数组类型
ids := make([]int64, 0)
for _, v := range uniqueIDs {
ids = append(ids, parse.Number(v))
}
rows, err := s.neHostService.DeleteByIds(uniqueIDs)
rows, err := s.neHostService.DeleteByIds(ids)
if err != nil {
c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error())))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
return
}
msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
c.JSON(200, result.OkMsg(msg))
c.JSON(200, resp.OkMsg(msg))
}
// 网元主机测试连接
@@ -181,11 +191,12 @@ func (s *NeHostController) Remove(c *gin.Context) {
// @Summary Network element host test connection
// @Description Network element host test connection
// @Router /ne/host/test [post]
func (s *NeHostController) Test(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeHostController) Test(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body model.NeHost
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
@@ -201,11 +212,11 @@ func (s *NeHostController) Test(c *gin.Context) {
}
if err != nil {
// 连接主机失败,请检查连接参数后重试
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
return
}
defer client.Close()
c.JSON(200, result.Ok(nil))
c.JSON(200, resp.Ok(nil))
return
}
@@ -216,16 +227,16 @@ func (s *NeHostController) Test(c *gin.Context) {
client, err := connTelnet.NewClient()
if err != nil {
// 连接主机失败,请检查连接参数后重试
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
return
}
defer client.Close()
// 是否有终止符
if strings.HasSuffix(client.LastResult, ">") || strings.HasSuffix(client.LastResult, "> ") || strings.HasSuffix(client.LastResult, "# ") {
c.JSON(200, result.Ok(nil))
c.JSON(200, resp.Ok(nil))
} else {
// 连接主机失败,请检查连接参数后重试
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
}
return
}
@@ -237,11 +248,11 @@ func (s *NeHostController) Test(c *gin.Context) {
client, err := connRedis.NewClient()
if err != nil {
// 连接主机失败,请检查连接参数后重试
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
return
}
defer client.Close()
c.JSON(200, result.Ok(nil))
c.JSON(200, resp.Ok(nil))
return
}
}
@@ -259,22 +270,23 @@ func (s *NeHostController) Test(c *gin.Context) {
// @Summary The network element host sends the command
// @Description The network element host sends the command
// @Router /ne/host/cmd [post]
func (s *NeHostController) Cmd(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeHostController) Cmd(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body struct {
HostID string `json:"hostId" binding:"required"` // 主机ID
Cmd string `json:"cmd" binding:"required"` // 执行命令
ID int64 `json:"id" binding:"required"` // 主机ID
Cmd string `json:"cmd" binding:"required"` // 执行命令
}
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 检查是否存在
neHost := s.neHostService.SelectById(body.HostID)
if neHost.HostID != body.HostID {
neHost := s.neHostService.FindById(body.ID)
if neHost.ID != body.ID {
// 没有可访问主机信息数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neHost.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.noData")))
return
}
@@ -290,7 +302,7 @@ func (s *NeHostController) Cmd(c *gin.Context) {
}
if err != nil {
// 连接主机失败,请检查连接参数后重试
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
return
}
defer client.Close()
@@ -298,10 +310,10 @@ func (s *NeHostController) Cmd(c *gin.Context) {
// 执行命令
output, err := client.RunCMD(body.Cmd)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, result.OkData(output))
c.JSON(200, resp.OkData(output))
return
}
@@ -312,7 +324,7 @@ func (s *NeHostController) Cmd(c *gin.Context) {
client, err := connTelnet.NewClient()
if err != nil {
// 连接主机失败,请检查连接参数后重试
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
return
}
defer client.Close()
@@ -320,10 +332,10 @@ func (s *NeHostController) Cmd(c *gin.Context) {
// 执行命令
output, err := client.RunCMD(body.Cmd)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, result.OkData(output))
c.JSON(200, resp.OkData(output))
return
}
}
@@ -341,11 +353,12 @@ func (s *NeHostController) Cmd(c *gin.Context) {
// @Summary Checking the server environment by SSH method of Net Element Hosting
// @Description Checking the server environment by SSH method of Net Element Hosting
// @Router /ne/host/checkBySSH [post]
func (s *NeHostController) CheckBySSH(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeHostController) CheckBySSH(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body model.NeHost
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
@@ -361,7 +374,7 @@ func (s *NeHostController) CheckBySSH(c *gin.Context) {
}
if err != nil {
// 连接主机失败,请检查连接参数后重试
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
return
}
defer client.Close()
@@ -381,7 +394,7 @@ func (s *NeHostController) CheckBySSH(c *gin.Context) {
// 执行命令 检查系统环境
output, err := client.RunCMD("uname -snrm && cat /etc/os-release | grep PRETTY_NAME")
if err != nil {
c.JSON(200, result.OkData(data))
c.JSON(200, resp.OkData(data))
return
}
output = strings.TrimSuffix(output, "\n")
@@ -426,7 +439,7 @@ func (s *NeHostController) CheckBySSH(c *gin.Context) {
}
}
c.JSON(200, result.OkData(data))
c.JSON(200, resp.OkData(data))
}
// 网元主机SSH方式授权免密发送
@@ -442,11 +455,16 @@ func (s *NeHostController) CheckBySSH(c *gin.Context) {
// @Summary Network element host SSH method of authorization for password-free sending
// @Description Network element host SSH method of authorization for password-free sending
// @Router /ne/host/authorizedBySSH [post]
func (s *NeHostController) AuthorizedBySSH(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeHostController) AuthorizedBySSH(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body model.NeHost
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil || body.AuthMode == "2" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
if body.AuthMode == "2" {
c.JSON(400, resp.CodeMsg(40010, "bind err: auth mode not equals 2"))
return
}
@@ -464,7 +482,7 @@ func (s *NeHostController) AuthorizedBySSH(c *gin.Context) {
}
if sshLink {
// 连接主机成功,无需重复免密授权认证
c.JSON(200, result.OkMsg(i18n.TKey(language, "neHost.okBySSHLink")))
c.JSON(200, resp.OkMsg(i18n.TKey(language, "neHost.okBySSHLink")))
return
}
@@ -474,7 +492,7 @@ func (s *NeHostController) AuthorizedBySSH(c *gin.Context) {
client, err := connSSH.NewClient()
if err != nil {
// 连接主机失败,请检查连接参数后重试
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHost.errByHostInfo")))
return
}
defer client.Close()
@@ -482,8 +500,8 @@ func (s *NeHostController) AuthorizedBySSH(c *gin.Context) {
// 发送密钥
err = client.SendToAuthorizedKeys()
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, result.Ok(nil))
c.JSON(200, resp.Ok(nil))
}

View File

@@ -1,16 +1,16 @@
package controller
import (
"strings"
"fmt"
"be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx"
"be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
"be.ems/src/modules/network_element/model"
neService "be.ems/src/modules/network_element/service"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
// 实例化控制层 NeHostCmdController 结构体
@@ -28,124 +28,125 @@ type NeHostCmdController struct {
// 网元主机命令列表
//
// GET /list
func (s *NeHostCmdController) List(c *gin.Context) {
querys := ctx.QueryMap(c)
data := s.neHostCmdService.SelectPage(querys)
c.JSON(200, result.Ok(data))
func (s NeHostCmdController) List(c *gin.Context) {
query := reqctx.QueryMap(c)
rows, total := s.neHostCmdService.FindByPage(query)
c.JSON(200, resp.OkData(map[string]any{"total": total, "rows": rows}))
}
// 网元主机命令信息
//
// GET /:cmdId
func (s *NeHostCmdController) Info(c *gin.Context) {
language := ctx.AcceptLanguage(c)
cmdId := c.Param("cmdId")
if cmdId == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
// GET /:id
func (s NeHostCmdController) Info(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
id := parse.Number(c.Param("id"))
if id <= 0 {
c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return
}
neHost := s.neHostCmdService.SelectById(cmdId)
if neHost.CmdID != cmdId {
neHost := s.neHostCmdService.FindById(id)
if neHost.ID != id {
// 没有可访问主机命令数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neHostCmd.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHostCmd.noData")))
return
}
c.JSON(200, result.OkData(neHost))
c.JSON(200, resp.OkData(neHost))
}
// 网元主机命令新增
//
// POST /
func (s *NeHostCmdController) Add(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeHostCmdController) Add(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body model.NeHostCmd
err := c.ShouldBindBodyWith(&body, binding.JSON)
if err != nil || body.CmdID != "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 检查属性值唯一
uniqueHostCmd := s.neHostCmdService.CheckUniqueGroupTitle(body.GroupID, body.Title, body.CmdType, "")
uniqueHostCmd := s.neHostCmdService.CheckUniqueGroupTitle(body.GroupID, body.Title, body.CmdType, 0)
if !uniqueHostCmd {
// 主机命令操作【%s】失败同组内名称已存在
msg := i18n.TTemplate(language, "neHostCmd.errKeyExists", map[string]any{"name": body.Title})
c.JSON(200, result.ErrMsg(msg))
c.JSON(200, resp.ErrMsg(msg))
return
}
body.CreateBy = ctx.LoginUserToUserName(c)
body.CreateBy = reqctx.LoginUserToUserName(c)
insertId := s.neHostCmdService.Insert(body)
if insertId != "" {
c.JSON(200, result.Ok(nil))
if insertId > 0 {
c.JSON(200, resp.Ok(nil))
return
}
c.JSON(200, result.Err(nil))
c.JSON(200, resp.Err(nil))
}
// 网元主机命令修改
//
// PUT /
func (s *NeHostCmdController) Edit(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeHostCmdController) Edit(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body model.NeHostCmd
err := c.ShouldBindBodyWith(&body, binding.JSON)
if err != nil || body.CmdID == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 检查属性值唯一
uniqueHostCmd := s.neHostCmdService.CheckUniqueGroupTitle(body.GroupID, body.Title, body.CmdType, body.CmdID)
uniqueHostCmd := s.neHostCmdService.CheckUniqueGroupTitle(body.GroupID, body.Title, body.CmdType, body.ID)
if !uniqueHostCmd {
// 主机命令操作【%s】失败同组内名称已存在
msg := i18n.TTemplate(language, "neHostCmd.errKeyExists", map[string]any{"name": body.Title})
c.JSON(200, result.ErrMsg(msg))
c.JSON(200, resp.ErrMsg(msg))
return
}
// 检查是否存在
neHost := s.neHostCmdService.SelectById(body.CmdID)
if neHost.CmdID != body.CmdID {
neHost := s.neHostCmdService.FindById(body.ID)
if neHost.ID != body.ID {
// 没有可访问主机命令数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neHostCmd.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neHostCmd.noData")))
return
}
body.UpdateBy = ctx.LoginUserToUserName(c)
body.UpdateBy = reqctx.LoginUserToUserName(c)
rows := s.neHostCmdService.Update(body)
if rows > 0 {
c.JSON(200, result.Ok(nil))
c.JSON(200, resp.Ok(nil))
return
}
c.JSON(200, result.Err(nil))
c.JSON(200, resp.Err(nil))
}
// 网元主机命令删除
//
// DELETE /:cmdIds
func (s *NeHostCmdController) Remove(c *gin.Context) {
language := ctx.AcceptLanguage(c)
cmdIds := c.Param("cmdIds")
if cmdIds == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
// DELETE /:id
func (s NeHostCmdController) Remove(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
id := c.Param("id")
if id == "" {
c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return
}
// 处理字符转id数组后去重
ids := strings.Split(cmdIds, ",")
uniqueIDs := parse.RemoveDuplicates(ids)
if len(uniqueIDs) <= 0 {
c.JSON(200, result.Err(nil))
return
uniqueIDs := parse.RemoveDuplicatesToArray(id, ",")
// 转换成int64数组类型
ids := make([]int64, 0)
for _, v := range uniqueIDs {
ids = append(ids, parse.Number(v))
}
rows, err := s.neHostCmdService.DeleteByIds(uniqueIDs)
rows, err := s.neHostCmdService.DeleteByIds(ids)
if err != nil {
c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error())))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
return
}
msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
c.JSON(200, result.OkMsg(msg))
c.JSON(200, resp.OkMsg(msg))
}

View File

@@ -6,9 +6,9 @@ import (
"sync"
"be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx"
"be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
neFetchlink "be.ems/src/modules/network_element/fetch_link"
"be.ems/src/modules/network_element/model"
neService "be.ems/src/modules/network_element/service"
@@ -43,27 +43,28 @@ var mutex sync.Mutex
// @Tags network_element/info
// @Accept json
// @Produce json
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC)
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC)
// @Param neId query string true "NE ID" default(001)
// @Success 200 {object} object "Response Results"
// @Security TokenAuth
// @Summary Network element information state
// @Description Network element information state
// @Router /ne/info/state [get]
func (s *NeInfoController) State(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeInfoController) State(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var querys struct {
NeType string `form:"neType" binding:"required"`
NeId string `form:"neId" binding:"required"`
}
if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeId)
neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeId)
if neInfo.NeId != querys.NeId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
neKey := fmt.Sprintf("%s_%s", neInfo.NeType, neInfo.NeId)
@@ -87,7 +88,7 @@ func (s *NeInfoController) State(c *gin.Context) {
}
neStateCacheMap.Store(neKey, resDataCache)
mutex.Unlock()
c.JSON(200, result.OkData(resDataCache))
c.JSON(200, resp.OkData(resDataCache))
return
}
@@ -96,7 +97,7 @@ func (s *NeInfoController) State(c *gin.Context) {
mutex.Lock()
neStateCacheMap.Store(neKey, resData)
mutex.Unlock()
c.JSON(200, result.OkData(resData))
c.JSON(200, resp.OkData(resData))
}
// 网元neType和neID查询
@@ -106,30 +107,31 @@ func (s *NeInfoController) State(c *gin.Context) {
// @Tags network_element/info
// @Accept json
// @Produce json
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC)
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC)
// @Param neId query string true "NE ID" default(001)
// @Success 200 {object} object "Response Results"
// @Security TokenAuth
// @Summary Network element neType and neID queries
// @Description Network element neType and neID queries
// @Router /ne/info/byTypeAndID [get]
func (s *NeInfoController) NeTypeAndID(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeInfoController) NeTypeAndID(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var querys struct {
NeType string `form:"neType" binding:"required"`
NeID string `form:"neId" binding:"required"`
}
if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(querys.NeType, querys.NeID)
neInfo := s.neInfoService.FindByNeTypeAndNeID(querys.NeType, querys.NeID)
if neInfo.NeId != querys.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
c.JSON(200, result.OkData(neInfo))
c.JSON(200, resp.OkData(neInfo))
}
// 网元信息列表全部无分页
@@ -148,8 +150,8 @@ func (s *NeInfoController) NeTypeAndID(c *gin.Context) {
// @Summary The list of network element information is all unpaginated
// @Description The list of network element information is all unpaginated
// @Router /ne/info/listAll [get]
func (s *NeInfoController) ListAll(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeInfoController) ListAll(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var querys struct {
NeType string `form:"neType"`
NeId string `form:"neId"`
@@ -157,7 +159,8 @@ func (s *NeInfoController) ListAll(c *gin.Context) {
BandHost bool `form:"bandHost"`
}
if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
@@ -169,75 +172,75 @@ func (s *NeInfoController) ListAll(c *gin.Context) {
if querys.NeId != "" {
ne.NeId = querys.NeId
}
neList := s.neInfoService.SelectList(ne, querys.BandStatus, querys.BandHost)
neList := s.neInfoService.Find(ne, querys.BandStatus, querys.BandHost)
if len(neList) == 0 {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
c.JSON(200, result.OkData(neList))
c.JSON(200, resp.OkData(neList))
}
// 网元端Para5G配置文件读取
//
// GET /para5GFile
func (s *NeInfoController) Para5GFileRead(c *gin.Context) {
func (s NeInfoController) Para5GFileRead(c *gin.Context) {
data, err := s.neInfoService.NeConfPara5GRead()
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, result.OkData(data))
c.JSON(200, resp.OkData(data))
}
// 网元端Para5G配置文件写入
//
// PUT /para5GFile
func (s *NeInfoController) Para5GFileWrite(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeInfoController) Para5GFileWrite(c *gin.Context) {
var body struct {
Content map[string]any `json:"content" binding:"required"` // 内容
SyncNE []string `json:"syncNe"` // 同步到网元
}
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
err := s.neInfoService.NeConfPara5GWirte(body.Content, body.SyncNE)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, result.Ok(nil))
c.JSON(200, resp.Ok(nil))
}
// 网元端OAM配置文件读取
//
// GET /oamFile
func (s *NeInfoController) OAMFileRead(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeInfoController) OAMFileRead(c *gin.Context) {
var querys struct {
NeType string `form:"neType" binding:"required"`
NeID string `form:"neId" binding:"required"`
}
if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
data, err := s.neInfoService.NeConfOAMReadSync(querys.NeType, querys.NeID)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, result.OkData(data))
c.JSON(200, resp.OkData(data))
}
// 网元端OAM配置文件写入
//
// PUT /oamFile
func (s *NeInfoController) OAMFileWrite(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeInfoController) OAMFileWrite(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body struct {
NeType string `json:"neType" binding:"required"`
NeID string `json:"neId" binding:"required"`
@@ -245,23 +248,24 @@ func (s *NeInfoController) OAMFileWrite(c *gin.Context) {
Sync bool `json:"sync"` // 同步到网元
}
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 查询网元获取IP
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(body.NeType, body.NeID)
neInfo := s.neInfoService.FindByNeTypeAndNeID(body.NeType, body.NeID)
if neInfo.NeId != body.NeID || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
err := s.neInfoService.NeConfOAMWirteSync(neInfo, body.Content, body.Sync)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, result.Ok(nil))
c.JSON(200, resp.Ok(nil))
}
// 网元信息列表
@@ -281,19 +285,19 @@ func (s *NeInfoController) OAMFileWrite(c *gin.Context) {
// @Summary Network element information list
// @Description Network element information list
// @Router /ne/info/list [get]
func (s *NeInfoController) List(c *gin.Context) {
query := ctx.QueryMapString(c)
func (s NeInfoController) List(c *gin.Context) {
query := reqctx.QueryMap(c)
bandStatus := false
if v, ok := query["bandStatus"]; ok {
bandStatus = parse.Boolean(v)
}
rows, total := s.neInfoService.SelectPage(query, bandStatus)
c.JSON(200, result.Ok(map[string]any{"rows": rows, "total": total}))
rows, total := s.neInfoService.FindByPage(query, bandStatus)
c.JSON(200, resp.OkData(map[string]any{"rows": rows, "total": total}))
}
// 网元信息
//
// GET /:infoId
// GET /:id
//
// @Tags network_element/info
// @Accept json
@@ -304,22 +308,22 @@ func (s *NeInfoController) List(c *gin.Context) {
// @Summary Network element information
// @Description Network element information
// @Router /ne/info/{value} [get]
func (s *NeInfoController) Info(c *gin.Context) {
language := ctx.AcceptLanguage(c)
infoId := c.Param("infoId")
if infoId == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
func (s NeInfoController) Info(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
id := parse.Number(c.Param("id"))
if id <= 0 {
c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return
}
neHost := s.neInfoService.SelectById(infoId, true)
if neHost.ID != infoId {
neHost := s.neInfoService.FindById(id, true)
if neHost.ID != id {
// 没有可访问网元信息数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neInfo.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neInfo.noData")))
return
}
c.JSON(200, result.OkData(neHost))
c.JSON(200, resp.OkData(neHost))
}
// 网元信息新增
@@ -335,41 +339,46 @@ func (s *NeInfoController) Info(c *gin.Context) {
// @Summary Network element information addition
// @Description Network element information addition
// @Router /ne/info [post]
func (s *NeInfoController) Add(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeInfoController) Add(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body model.NeInfo
err := c.ShouldBindBodyWithJSON(&body)
if err != nil || body.ID != "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
if body.ID != 0 {
c.JSON(400, resp.CodeMsg(40010, "bind err: id not is empty"))
return
}
// 检查属性值唯一
uniqueInfo := s.neInfoService.CheckUniqueNeTypeAndNeId(body.NeType, body.NeId, "")
uniqueInfo := s.neInfoService.CheckUniqueNeTypeAndNeId(body.NeType, body.NeId, 0)
if !uniqueInfo {
// 网元信息操作【%s】失败同类型下标识已存在
msg := i18n.TTemplate(language, "neInfo.errKeyExists", map[string]any{"key": body.NeId})
c.JSON(200, result.ErrMsg(msg))
c.JSON(200, resp.ErrMsg(msg))
return
}
// 获取网元状态是否正常
body.ServerState, err = neFetchlink.NeState(body)
if err != nil {
body.Status = "0"
body.Status = 0
} else {
// 网元状态设置为在线
body.Status = "1"
body.Status = 1
if parse.Boolean(body.ServerState["standby"]) {
body.Status = "3"
body.Status = 3
}
// 下发网管配置信息给网元
if _, err = neFetchlink.NeConfigOMC(body); err != nil {
body.Status = "2"
body.Status = 2
}
}
loginUserName := ctx.LoginUserToUserName(c)
loginUserName := reqctx.LoginUserToUserName(c)
// 新增Version信息
neVersion := model.NeVersion{
NeType: body.NeType,
@@ -403,11 +412,11 @@ func (s *NeInfoController) Add(c *gin.Context) {
s.neLicenseService.Insert(neLicense)
body.CreateBy = loginUserName
insertId := s.neInfoService.Insert(body)
if insertId != "" {
c.JSON(200, result.OkData(insertId))
if insertId > 0 {
c.JSON(200, resp.OkData(insertId))
return
}
c.JSON(200, result.Err(nil))
c.JSON(200, resp.Err(nil))
}
// 网元信息修改
@@ -423,12 +432,17 @@ func (s *NeInfoController) Add(c *gin.Context) {
// @Summary Network element information modification
// @Description Network element information modification
// @Router /ne/info [put]
func (s *NeInfoController) Edit(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeInfoController) Edit(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body model.NeInfo
err := c.ShouldBindBodyWithJSON(&body)
if err != nil || body.ID == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
if body.ID <= 0 {
c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return
}
@@ -437,44 +451,44 @@ func (s *NeInfoController) Edit(c *gin.Context) {
if !uniqueInfo {
// 网元信息操作【%s】失败同类型下标识已存在
msg := i18n.TTemplate(language, "neInfo.errKeyExists", map[string]any{"key": body.NeId})
c.JSON(200, result.ErrMsg(msg))
c.JSON(200, resp.ErrMsg(msg))
return
}
// 检查是否存在
neInfo := s.neInfoService.SelectById(body.ID, false)
neInfo := s.neInfoService.FindById(body.ID, false)
if neInfo.ID != body.ID {
// 没有可访问网元信息数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neInfo.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neInfo.noData")))
return
}
// 赋予主机ID
if neInfo.HostIDs != "" && len(body.Hosts) > 0 {
hostIDs := strings.Split(neInfo.HostIDs, ",")
for index, id := range hostIDs {
body.Hosts[index].HostID = id
body.Hosts[index].ID = parse.Number(id)
}
}
// 获取网元状态是否正常
body.ServerState, err = neFetchlink.NeState(body)
body.ServerState, err = neFetchlink.NeState(neInfo)
if err != nil {
body.Status = "0"
body.Status = 0
} else {
// 网元状态设置为在线
body.Status = "1"
body.Status = 1
if parse.Boolean(body.ServerState["standby"]) {
body.Status = "3"
body.Status = 3
}
// 下发网管配置信息给网元
if _, err = neFetchlink.NeConfigOMC(body); err != nil {
body.Status = "2"
body.Status = 2
}
}
loginUserName := ctx.LoginUserToUserName(c)
neLicense := s.neLicenseService.SelectByNeTypeAndNeID(neInfo.NeType, neInfo.NeId)
neVersion := s.neVersionService.SelectByNeTypeAndNeID(neInfo.NeType, neInfo.NeId)
loginUserName := reqctx.LoginUserToUserName(c)
neLicense := s.neLicenseService.FindByNeTypeAndNeID(neInfo.NeType, neInfo.NeId)
neVersion := s.neVersionService.FindByNeTypeAndNeID(neInfo.NeType, neInfo.NeId)
// 已有网元可获取的信息
if body.ServerState != nil {
@@ -494,14 +508,14 @@ func (s *NeInfoController) Edit(c *gin.Context) {
}
}
if neVersion.ID != "" {
if neVersion.ID <= 0 {
if neVersion.NeType != body.NeType || neVersion.NeId != body.NeId {
neVersion.NeType = body.NeType
neVersion.NeId = body.NeId
}
s.neVersionService.Update(neVersion)
}
if neLicense.ID != "" {
if neLicense.ID <= 0 {
if neLicense.NeType != body.NeType || neLicense.NeId != body.NeId {
neLicense.NeType = body.NeType
neLicense.NeId = body.NeId
@@ -512,44 +526,46 @@ func (s *NeInfoController) Edit(c *gin.Context) {
body.UpdateBy = loginUserName
rows := s.neInfoService.Update(body)
if rows > 0 {
c.JSON(200, result.Ok(nil))
c.JSON(200, resp.Ok(nil))
return
}
c.JSON(200, result.Err(nil))
c.JSON(200, resp.Err(nil))
}
// 网元信息删除
//
// DELETE /:infoIds
// DELETE /:id
//
// @Tags network_element/info
// @Accept json
// @Produce json
// @Param value path string true "Row ID, multiple separated by a , sign"
// @Param value path string true "Row ID"
// @Success 200 {object} object "Response Results"
// @Security TokenAuth
// @Summary Network element information deletion
// @Description Network element information deletion
// @Router /ne/info/{value} [delete]
func (s *NeInfoController) Remove(c *gin.Context) {
language := ctx.AcceptLanguage(c)
infoIds := c.Param("infoIds")
if infoIds == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
// @Router /ne/info [delete]
func (s NeInfoController) Remove(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
id := c.Param("id")
if id == "" {
c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return
}
// 处理字符转id数组后去重
ids := strings.Split(infoIds, ",")
uniqueIDs := parse.RemoveDuplicates(ids)
if len(uniqueIDs) <= 0 {
c.JSON(200, result.Err(nil))
return
uniqueIDs := parse.RemoveDuplicatesToArray(id, ",")
// 转换成int64数组类型
ids := make([]int64, 0)
for _, v := range uniqueIDs {
ids = append(ids, parse.Number(v))
}
rows, err := s.neInfoService.DeleteByIds(uniqueIDs)
rows, err := s.neInfoService.DeleteByIds(ids)
if err != nil {
c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error())))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
return
}
msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
c.JSON(200, result.OkMsg(msg))
c.JSON(200, resp.OkMsg(msg))
}

View File

@@ -6,8 +6,9 @@ import (
"github.com/gin-gonic/gin"
"be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx"
"be.ems/src/framework/vo/result"
"be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/parse"
neFetchlink "be.ems/src/modules/network_element/fetch_link"
"be.ems/src/modules/network_element/model"
neService "be.ems/src/modules/network_element/service"
@@ -34,47 +35,49 @@ type NeLicenseController struct {
// @Tags network_element/license
// @Accept json
// @Produce json
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC)
// @Param neId query string true "NE ID" default(001)
// @Success 200 {object} object "Response Results"
// @Param neType query string false "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC)
// @Param neId query string false "NE ID"
// @Param expiryDate query string false "ExpiryDate"
// @Param pageNum query number true "pageNum" default(1)
// @Param pageSize query number true "pageSize" default(10)
// @Success 200 {object} object "Response Results"
// @Security TokenAuth
// @Summary Net Element License Activation List
// @Description Net Element License Activation List
// @Router /ne/license/list [get]
func (s *NeLicenseController) List(c *gin.Context) {
querys := ctx.QueryMap(c)
data := s.neLicenseService.SelectPage(querys)
query := reqctx.QueryMap(c)
rows, total := s.neLicenseService.FindByPage(query)
// 过滤屏蔽授权文件
rows := data["rows"].([]model.NeLicense)
arr := &rows
for i := range *arr {
(*arr)[i].ActivationRequestCode = "-"
(*arr)[i].LicensePath = "-"
}
c.JSON(200, result.Ok(data))
c.JSON(200, resp.OkData(map[string]any{"total": total, "rows": rows}))
}
// 网元授权激活信息
//
// GET /:licenseId
// GET /:id
func (s *NeLicenseController) Info(c *gin.Context) {
language := ctx.AcceptLanguage(c)
licenseId := c.Param("licenseId")
if licenseId == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
language := reqctx.AcceptLanguage(c)
id := parse.Number(c.Param("id"))
if id <= 0 {
c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return
}
neLicense := s.neLicenseService.SelectById(licenseId)
if neLicense.ID != licenseId {
neLicense := s.neLicenseService.FindById(id)
if neLicense.ID != id {
// 没有可访问网元授权激活数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neLicense.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neLicense.noData")))
return
}
c.JSON(200, result.OkData(neLicense))
c.JSON(200, resp.OkData(neLicense))
}
// 网元neType和neID查询
@@ -84,7 +87,7 @@ func (s *NeLicenseController) Info(c *gin.Context) {
// @Tags network_element/license
// @Accept json
// @Produce json
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC)
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC)
// @Param neId query string true "NE ID" default(001)
// @Success 200 {object} object "Response Results"
// @Security TokenAuth
@@ -92,24 +95,25 @@ func (s *NeLicenseController) Info(c *gin.Context) {
// @Description Network element neType and neID queries
// @Router /ne/license/byTypeAndID [get]
func (s *NeLicenseController) NeTypeAndID(c *gin.Context) {
language := ctx.AcceptLanguage(c)
language := reqctx.AcceptLanguage(c)
var querys struct {
NeType string `form:"neType" binding:"required"`
NeId string `form:"neId" binding:"required"`
}
if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
neLicense := s.neLicenseService.SelectByNeTypeAndNeID(querys.NeType, querys.NeId)
neLicense := s.neLicenseService.FindByNeTypeAndNeID(querys.NeType, querys.NeId)
if neLicense.NeId != querys.NeId {
// 没有可访问网元授权激活数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neLicense.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neLicense.noData")))
return
}
c.JSON(200, result.OkData(neLicense))
c.JSON(200, resp.OkData(neLicense))
}
// 网元授权激活授权申请码
@@ -119,7 +123,7 @@ func (s *NeLicenseController) NeTypeAndID(c *gin.Context) {
// @Tags network_element/license
// @Accept json
// @Produce json
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC)
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC)
// @Param neId query string true "NE ID" default(001)
// @Success 200 {object} object "Response Results"
// @Security TokenAuth
@@ -127,21 +131,21 @@ func (s *NeLicenseController) NeTypeAndID(c *gin.Context) {
// @Description Network Element License Activation License Application Code
// @Router /ne/license/code [get]
func (s *NeLicenseController) Code(c *gin.Context) {
language := ctx.AcceptLanguage(c)
language := reqctx.AcceptLanguage(c)
var querys struct {
NeType string `form:"neType" binding:"required"`
NeId string `form:"neId" binding:"required"`
}
if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return
}
// 检查是否存在授权记录
neLicense := s.neLicenseService.SelectByNeTypeAndNeID(querys.NeType, querys.NeId)
neLicense := s.neLicenseService.FindByNeTypeAndNeID(querys.NeType, querys.NeId)
if neLicense.NeId != querys.NeId {
// 没有可访问网元授权激活数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neLicense.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neLicense.noData")))
return
}
@@ -155,10 +159,10 @@ func (s *NeLicenseController) Code(c *gin.Context) {
neLicense.ExpiryDate = ""
neLicense.Status = "0"
}
neLicense.UpdateBy = ctx.LoginUserToUserName(c)
neLicense.UpdateBy = reqctx.LoginUserToUserName(c)
s.neLicenseService.Update(neLicense)
c.JSON(200, result.OkData(code))
c.JSON(200, resp.OkData(code))
}
// 网元授权激活授权文件替换
@@ -175,19 +179,19 @@ func (s *NeLicenseController) Code(c *gin.Context) {
// @Description Network element authorization activation status
// @Router /ne/license/change [post]
func (s *NeLicenseController) Change(c *gin.Context) {
language := ctx.AcceptLanguage(c)
language := reqctx.AcceptLanguage(c)
var body model.NeLicense
err := c.ShouldBindBodyWithJSON(&body)
if err != nil || body.LicensePath == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return
}
// 检查是否存在授权记录
neLicense := s.neLicenseService.SelectByNeTypeAndNeID(body.NeType, body.NeId)
neLicense := s.neLicenseService.FindByNeTypeAndNeID(body.NeType, body.NeId)
if neLicense.NeId != body.NeId {
// 没有可访问网元授权激活数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neLicense.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neLicense.noData")))
return
}
@@ -197,19 +201,19 @@ func (s *NeLicenseController) Change(c *gin.Context) {
}
neLicense.LicensePath = body.LicensePath
neLicense.Status = "0"
neLicense.UpdateBy = ctx.LoginUserToUserName(c)
neLicense.UpdateBy = reqctx.LoginUserToUserName(c)
upRows := s.neLicenseService.Update(neLicense)
if upRows > 0 {
// 进行上传替换
err = s.neLicenseService.UploadLicense(body)
if err != nil {
c.JSON(200, result.ErrMsg(err.Error()))
c.JSON(200, resp.ErrMsg(err.Error()))
return
}
c.JSON(200, result.Ok(nil))
c.JSON(200, resp.Ok(nil))
return
}
c.JSON(200, result.Err(nil))
c.JSON(200, resp.Err(nil))
}
// 网元授权激活状态
@@ -219,7 +223,7 @@ func (s *NeLicenseController) Change(c *gin.Context) {
// @Tags network_element/license
// @Accept json
// @Produce json
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC)
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC)
// @Param neId query string true "NE ID" default(001)
// @Success 200 {object} object "Response Results"
// @Security TokenAuth
@@ -227,28 +231,28 @@ func (s *NeLicenseController) Change(c *gin.Context) {
// @Description Network element authorization activation status
// @Router /ne/license/state [get]
func (s *NeLicenseController) State(c *gin.Context) {
language := ctx.AcceptLanguage(c)
language := reqctx.AcceptLanguage(c)
var querys struct {
NeType string `form:"neType" binding:"required"`
NeId string `form:"neId" binding:"required"`
}
if err := c.ShouldBindQuery(&querys); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
c.JSON(400, resp.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return
}
// 检查是否存在授权记录
neLicense := s.neLicenseService.SelectByNeTypeAndNeID(querys.NeType, querys.NeId)
neLicense := s.neLicenseService.FindByNeTypeAndNeID(querys.NeType, querys.NeId)
if neLicense.NeId != querys.NeId {
// 没有可访问网元授权激活数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neLicense.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neLicense.noData")))
return
}
// 查询网元获取IP获取网元状态
neInfo := s.neInfoService.SelectNeInfoByNeTypeAndNeID(neLicense.NeType, neLicense.NeId)
neInfo := s.neInfoService.FindByNeTypeAndNeID(neLicense.NeType, neLicense.NeId)
if neInfo.NeId != neLicense.NeId || neInfo.IP == "" {
c.JSON(200, result.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "app.common.noNEInfo")))
return
}
if neState, err := neFetchlink.NeState(neInfo); err == nil && neState["sn"] != nil {
@@ -263,15 +267,15 @@ func (s *NeLicenseController) State(c *gin.Context) {
}
// 更新授权信息
neLicense.UpdateBy = ctx.LoginUserToUserName(c)
neLicense.UpdateBy = reqctx.LoginUserToUserName(c)
s.neLicenseService.Update(neLicense)
if neLicense.Status == "1" {
c.JSON(200, result.OkData(map[string]string{
c.JSON(200, resp.OkData(map[string]string{
"sn": neLicense.SerialNum,
"expire": neLicense.ExpiryDate,
}))
return
}
c.JSON(200, result.ErrMsg(fmt.Sprintf("%s service status exception", neLicense.NeType)))
c.JSON(200, resp.ErrMsg(fmt.Sprintf("%s service status exception", neLicense.NeType)))
}

View File

@@ -1,16 +1,16 @@
package controller
import (
"strings"
"fmt"
"be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx"
"be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/parse"
"be.ems/src/framework/vo/result"
"be.ems/src/modules/network_element/model"
neService "be.ems/src/modules/network_element/service"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
// 实例化控制层 NeSoftwareController 结构体
@@ -32,62 +32,76 @@ type NeSoftwareController struct {
// @Tags network_element/software
// @Accept json
// @Produce json
// @Param neType query string true "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC)
// @Param neId query string true "NE ID" default(001)
// @Success 200 {object} object "Response Results"
// @Param neType query string false "NE Type" Enums(IMS,AMF,AUSF,UDM,SMF,PCF,NSSF,NRF,UPF,MME,CBC,OMC,SGWC,SMSC)
// @Param name query string false "Name"
// @Param version query string false "Version"
// @Param pageNum query number true "pageNum" default(1)
// @Param pageSize query number true "pageSize" default(10)
// @Success 200 {object} object "Response Results"
// @Security TokenAuth
// @Summary List of Network Element Software Packages
// @Description List of Network Element Software Packages
// @Router /ne/software/list [get]
func (s *NeSoftwareController) List(c *gin.Context) {
querys := ctx.QueryMap(c)
data := s.neSoftwareService.SelectPage(querys)
c.JSON(200, result.Ok(data))
func (s NeSoftwareController) List(c *gin.Context) {
query := reqctx.QueryMap(c)
rows, total := s.neSoftwareService.FindByPage(query)
c.JSON(200, resp.OkData(map[string]any{"total": total, "rows": rows}))
}
// 网元软件包信息
//
// GET /:softwareId
func (s *NeSoftwareController) Info(c *gin.Context) {
language := ctx.AcceptLanguage(c)
softwareId := c.Param("softwareId")
if softwareId == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
// GET /:id
func (s NeSoftwareController) Info(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
id := parse.Number(c.Param("id"))
if id <= 0 {
c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return
}
neSoftware := s.neSoftwareService.SelectById(softwareId)
if neSoftware.ID != softwareId {
neSoftware := s.neSoftwareService.FindById(id)
if neSoftware.ID != id {
// 没有可访问网元包信息数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neSoftware.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neSoftware.noData")))
return
}
c.JSON(200, result.OkData(neSoftware))
c.JSON(200, resp.OkData(neSoftware))
}
// 网元软件包新增
//
// POST /
func (s *NeSoftwareController) Add(c *gin.Context) {
language := ctx.AcceptLanguage(c)
//
// @Tags network_element/software
// @Accept json
// @Produce json
// @Param data body object true "Request Param"
// @Success 200 {object} object "Response Results"
// @Security TokenAuth
// @Summary Additions to the Net Element package
// @Description Additions to the Net Element package
// @Router /ne/software [post]
func (s NeSoftwareController) Add(c *gin.Context) {
var body model.NeSoftware
err := c.ShouldBindBodyWith(&body, binding.JSON)
if err != nil || body.Path == "" || body.ID != "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
if body.Path == "" || body.ID > 0 {
c.JSON(400, resp.CodeMsg(40010, "bind err: path is empty or id is not empty"))
return
}
// 找到已存在的删除后重新添加
neSoftwares := s.neSoftwareService.SelectList(model.NeSoftware{
neSoftwares := s.neSoftwareService.Find(model.NeSoftware{
NeType: body.NeType,
Name: body.Name,
Version: body.Version,
})
if len(neSoftwares) > 0 {
neSoftware := neSoftwares[0]
s.neSoftwareService.DeleteByIds([]string{neSoftware.ID})
s.neSoftwareService.DeleteByIds([]int64{neSoftware.ID})
}
// 检查属性值唯一
@@ -95,28 +109,32 @@ func (s *NeSoftwareController) Add(c *gin.Context) {
// if !uniqueSoftware {
// // 网元软件包操作【%s】失败网元类型与文件名版本已存在
// msg := i18n.TTemplate(language, "neSoftware.errKeyExists", map[string]any{"name": body.Name})
// c.JSON(200, result.ErrMsg(msg))
// c.JSON(200, resp.ErrMsg(msg))
// return
// }
body.CreateBy = ctx.LoginUserToUserName(c)
body.CreateBy = reqctx.LoginUserToUserName(c)
insertId := s.neSoftwareService.Insert(body)
if insertId != "" {
c.JSON(200, result.Ok(nil))
if insertId > 0 {
c.JSON(200, resp.Ok(nil))
return
}
c.JSON(200, result.Err(nil))
c.JSON(200, resp.Err(nil))
}
// 网元软件包修改
//
// PUT /
func (s *NeSoftwareController) Edit(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeSoftwareController) Edit(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
var body model.NeSoftware
err := c.ShouldBindBodyWith(&body, binding.JSON)
if err != nil || body.Path == "" || body.ID == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
if body.Path == "" || body.ID == 0 {
c.JSON(400, resp.CodeMsg(40010, "bind err: path or id is empty"))
return
}
@@ -125,51 +143,53 @@ func (s *NeSoftwareController) Edit(c *gin.Context) {
if !uniqueSoftware {
// 网元软件包操作【%s】失败网元类型与文件名版本已存在
msg := i18n.TTemplate(language, "neSoftware.errKeyExists", map[string]any{"name": body.Name})
c.JSON(200, result.ErrMsg(msg))
c.JSON(200, resp.ErrMsg(msg))
return
}
// 检查是否存在
neSoftware := s.neSoftwareService.SelectById(body.ID)
neSoftware := s.neSoftwareService.FindById(body.ID)
if neSoftware.ID != body.ID {
// 没有可访问网元包信息数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neSoftware.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neSoftware.noData")))
return
}
body.UpdateBy = ctx.LoginUserToUserName(c)
body.UpdateBy = reqctx.LoginUserToUserName(c)
rows := s.neSoftwareService.Update(body)
if rows > 0 {
c.JSON(200, result.Ok(nil))
c.JSON(200, resp.Ok(nil))
return
}
c.JSON(200, result.Err(nil))
c.JSON(200, resp.Err(nil))
}
// 网元软件包删除
//
// DELETE /:softwareIds
func (s *NeSoftwareController) Remove(c *gin.Context) {
language := ctx.AcceptLanguage(c)
softwareIds := c.Param("softwareIds")
if softwareIds == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
// DELETE /:id
func (s NeSoftwareController) Remove(c *gin.Context) {
language := reqctx.AcceptLanguage(c)
id := c.Param("id")
if id == "" {
c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return
}
// 处理字符转id数组后去重
ids := strings.Split(softwareIds, ",")
uniqueIDs := parse.RemoveDuplicates(ids)
if len(uniqueIDs) <= 0 {
c.JSON(200, result.Err(nil))
return
uniqueIDs := parse.RemoveDuplicatesToArray(id, ",")
// 转换成int64数组类型
ids := make([]int64, 0)
for _, v := range uniqueIDs {
ids = append(ids, parse.Number(v))
}
rows, err := s.neSoftwareService.DeleteByIds(uniqueIDs)
rows, err := s.neSoftwareService.DeleteByIds(ids)
if err != nil {
c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error())))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
return
}
msg := i18n.TTemplate(language, "app.common.deleteSuccess", map[string]any{"num": rows})
c.JSON(200, result.OkMsg(msg))
c.JSON(200, resp.OkMsg(msg))
}
// 网元软件包设为网元新版本
@@ -185,17 +205,16 @@ func (s *NeSoftwareController) Remove(c *gin.Context) {
// @Summary Net Element package set to Net Element new version
// @Description Net Element package set to Net Element new version
// @Router /ne/software/newNeVersion [post]
func (s *NeSoftwareController) NewNeVersion(c *gin.Context) {
language := ctx.AcceptLanguage(c)
func (s NeSoftwareController) NewNeVersion(c *gin.Context) {
var body model.NeSoftware
err := c.ShouldBindBodyWith(&body, binding.JSON)
if err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
// 找到已存在的软件包信息
neSoftwares := s.neSoftwareService.SelectList(model.NeSoftware{
neSoftwares := s.neSoftwareService.Find(model.NeSoftware{
NeType: body.NeType,
Name: body.Name,
Version: body.Version,
@@ -204,10 +223,10 @@ func (s *NeSoftwareController) NewNeVersion(c *gin.Context) {
neSoftware := neSoftwares[0]
s.neSoftwareService.UpdateVersions(neSoftware, model.NeVersion{
NeType: neSoftware.NeType,
UpdateBy: ctx.LoginUserToUserName(c),
UpdateBy: reqctx.LoginUserToUserName(c),
})
c.JSON(200, result.Ok(nil))
c.JSON(200, resp.Ok(nil))
return
}
c.JSON(200, result.Err(nil))
c.JSON(200, resp.Err(nil))
}

View File

@@ -1,12 +1,15 @@
package controller
import (
"fmt"
"be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx"
"be.ems/src/framework/vo/result"
"be.ems/src/framework/reqctx"
"be.ems/src/framework/resp"
"be.ems/src/framework/utils/parse"
neService "be.ems/src/modules/network_element/service"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
// 实例化控制层 NeVersionController 结构体
@@ -25,31 +28,30 @@ type NeVersionController struct {
//
// GET /list
func (s *NeVersionController) List(c *gin.Context) {
querys := ctx.QueryMap(c)
data := s.neVersionService.SelectPage(querys, true)
c.JSON(200, result.Ok(data))
query := reqctx.QueryMap(c)
rows, total := s.neVersionService.FindByPage(query, true)
c.JSON(200, resp.OkData(map[string]any{"total": total, "rows": rows}))
}
// 网元版本信息
//
// GET /:versionId
// GET /:id
func (s *NeVersionController) Info(c *gin.Context) {
language := ctx.AcceptLanguage(c)
versionId := c.Param("versionId")
if versionId == "" {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
language := reqctx.AcceptLanguage(c)
id := parse.Number(c.Param("id"))
if id <= 0 {
c.JSON(400, resp.CodeMsg(40010, "bind err: id is empty"))
return
}
neVersion := s.neVersionService.SelectById(versionId)
if neVersion.ID != versionId {
neVersion := s.neVersionService.FindById(id)
if neVersion.ID != id {
// 没有可访问网元版本数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neVersion.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neVersion.noData")))
return
}
c.JSON(200, result.OkData(neVersion))
c.JSON(200, resp.OkData(neVersion))
}
// 网元版本操作
@@ -66,30 +68,31 @@ func (s *NeVersionController) Info(c *gin.Context) {
// @Description Network element version operation
// @Router /ne/version/operate [post]
func (s *NeVersionController) Operate(c *gin.Context) {
language := ctx.AcceptLanguage(c)
language := reqctx.AcceptLanguage(c)
var body struct {
Action string `json:"action" binding:"required,oneof=install upgrade rollback"` // 操作行为
NeType string `json:"neType" gorm:"ne_type" binding:"required"` // 网元类型
NeId string `json:"neId" gorm:"ne_id" binding:"required"` // 网元ID
Preinput map[string]string `json:"preinput" ` // 预先输入参数
}
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
errMsgs := fmt.Sprintf("bind err: %s", resp.FormatBindError(err))
c.JSON(422, resp.CodeMsg(40422, errMsgs))
return
}
neVersion := s.neVersionService.SelectByNeTypeAndNeID(body.NeType, body.NeId)
neVersion := s.neVersionService.FindByNeTypeAndNeID(body.NeType, body.NeId)
if neVersion.NeId != body.NeId {
// 没有可访问网元版本数据!
c.JSON(200, result.ErrMsg(i18n.TKey(language, "neVersion.noData")))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, "neVersion.noData")))
return
}
// 进行相关命令操作
output, err := s.neVersionService.Operate(body.Action, neVersion, body.Preinput)
if err != nil {
c.JSON(200, result.ErrMsg(i18n.TKey(language, err.Error())))
c.JSON(200, resp.ErrMsg(i18n.TKey(language, err.Error())))
return
}
c.JSON(200, result.OkData(output))
c.JSON(200, resp.OkData(output))
}

View File

@@ -0,0 +1,35 @@
package fetchlink
import (
"encoding/json"
"fmt"
"strings"
"be.ems/src/framework/logger"
"be.ems/src/framework/utils/fetch"
"be.ems/src/modules/network_element/model"
)
// AlarmHistory 告警历史记录
func AlarmHistory(neInfo model.NeInfo) ([]map[string]any, error) {
// 网元参数配置信息
neUrl := fmt.Sprintf("http://%s:%d/api/rest/faultManagement/v1/elementType/%s/objectType/alarms", neInfo.IP, neInfo.Port, strings.ToLower(neInfo.NeType))
resBytes, err := fetch.Get(neUrl, nil, 60_000)
if err != nil {
errStr := err.Error()
logger.Warnf("AlarmHistory Get \"%s\"", neUrl)
if !(strings.HasPrefix(errStr, "201") || strings.HasPrefix(errStr, "202") || strings.HasPrefix(errStr, "204")) {
logger.Errorf("AlarmHistory %s", err.Error())
return nil, fmt.Errorf("NeService Alarm History Info API Error")
}
}
// 序列化结果
var resData []map[string]any
err = json.Unmarshal(resBytes, &resData)
if err != nil {
logger.Errorf("AlarmHistory Unmarshal %s", err.Error())
return nil, err
}
return resData, nil
}

View File

@@ -2,7 +2,7 @@ package model
// NeConfig 网元_参数配置可用属性值
type NeConfig struct {
ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" binding:"required" gorm:"column:ne_type"` // 网元类型
ParamName string `json:"paramName" binding:"required" gorm:"column:param_name"` // 参数名
ParamDisplay string `json:"paramDisplay" binding:"required" gorm:"column:param_display"` // 参数显示名

View File

@@ -2,16 +2,16 @@ package model
// NeConfigBackup 网元配置文件备份记录 ne_config_backup
type NeConfigBackup struct {
ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"ne_type"` // 网元类型
NeId string `json:"neId" gorm:"ne_id"` // 网元ID
Name string `json:"name" gorm:"name"` // 压缩包名称
Path string `json:"path" gorm:"path"` // 压缩包位置
Remark string `json:"remark" gorm:"remark"` // 备注
CreateBy string `json:"createBy" gorm:"create_by"` // 创建者
CreateTime int64 `json:"createTime" gorm:"create_time"` // 创建时间
UpdateBy string `json:"updateBy" gorm:"update_by"` // 更新者
UpdateTime int64 `json:"updateTime" gorm:"update_time"` // 更新时间
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type"` // 网元类型
NeId string `json:"neId" gorm:"column:ne_id"` // 网元ID
Name string `json:"name" gorm:"column:name"` // 压缩包名称
Path string `json:"path" gorm:"column:path"` // 压缩包位置
Remark string `json:"remark" gorm:"column:remark"` // 备注
CreateBy string `json:"createBy" gorm:"column:create_by"` // 创建者
CreateTime int64 `json:"createTime" gorm:"column:create_time"` // 创建时间
UpdateBy string `json:"updateBy" gorm:"column:update_by"` // 更新者
UpdateTime int64 `json:"updateTime" gorm:"column:update_time"` // 更新时间
// ====== 非数据库字段属性 ======

View File

@@ -4,7 +4,7 @@ import "encoding/json"
// NeHost 网元主机表 ne_host
type NeHost struct {
HostID string `json:"hostId" gorm:"column:host_id"` // 主机主键
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
HostType string `json:"hostType" gorm:"column:host_type" binding:"oneof=ssh telnet redis"` // 连接类型 ssh telnet redis
GroupID string `json:"groupId" gorm:"column:group_id"` // 分组0默认 1网元 2系统
Title string `json:"title" gorm:"column:title"` // 标题名称

View File

@@ -2,7 +2,7 @@ package model
// NeHostCmd 网元主机命令表 ne_host_cmd
type NeHostCmd struct {
CmdID string `json:"cmdId" gorm:"column:cmd_id"` // 命令主键
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
CmdType string `json:"cmdType" gorm:"column:cmd_type"` // 命令类型
GroupID string `json:"groupId" gorm:"column:group_id"` // 分组0默认 1快速命令
Title string `json:"title" gorm:"column:title" binding:"required"` // 标题名称

View File

@@ -2,25 +2,25 @@ package model
// NeInfo 网元信息对象 ne_info
type NeInfo struct {
ID string `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type" binding:"required"`
NeId string `json:"neId" gorm:"column:ne_id" binding:"required"`
RmUID string `json:"rmUid" gorm:"column:rm_uid"`
NeName string `json:"neName" gorm:"column:ne_name"`
IP string `json:"ip" gorm:"column:ip" binding:"required"`
Port int64 `json:"port" gorm:"column:port" binding:"required,number,max=65535,min=1"`
PvFlag string `json:"pvFlag" gorm:"column:pv_flag" binding:"oneof=PNF VNF"` // ''PNF'',''VNF''
Province string `json:"province" gorm:"column:province"` // 省份地域
VendorName string `json:"vendorName" gorm:"column:vendor_name"`
Dn string `json:"dn" gorm:"column:dn"`
NeAddress string `json:"neAddress" gorm:"column:ne_address"` // MAC地址
HostIDs string `json:"hostIds" gorm:"column:host_ids"` // 网元主机ID组 数据格式(ssh,telnet) UDM(ssh,telnet,redis) UPF(ssh,telnet,telnet)
Status string `json:"status" gorm:"column:status"` // 0离线 1在线 2配置待下发 3备用模式
Remark string `json:"remark" gorm:"column:remark"` // 备注
CreateBy string `json:"createBy" gorm:"column:create_by"` // 创建者
CreateTime int64 `json:"createTime" gorm:"column:create_time"` // 创建时间
UpdateBy string `json:"updateBy" gorm:"column:update_by"` // 更新者
UpdateTime int64 `json:"updateTime" gorm:"column:update_time"` // 更新时间
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type" binding:"required"` // 网元类型
NeId string `json:"neId" gorm:"column:ne_id" binding:"required"` // 网元ID
RmUID string `json:"rmUid" gorm:"column:rm_uid"` // 网元资源唯一标识
NeName string `json:"neName" gorm:"column:ne_name"` // 网元名称
IP string `json:"ip" gorm:"column:ip" binding:"required"` // 网元服务IP
Port int64 `json:"port" gorm:"column:port" binding:"required,number,max=65535,min=1"` // 端口
PvFlag string `json:"pvFlag" gorm:"column:pv_flag" binding:"omitempty,oneof=PNF VNF"` // 网元虚拟化标识 物理PNF 虚拟VNF
Province string `json:"province" gorm:"column:province"` // 省份地域
VendorName string `json:"vendorName" gorm:"column:vendor_name"` // 厂商名称
Dn string `json:"dn" gorm:"column:dn"` // 网络标识
NeAddress string `json:"neAddress" gorm:"column:ne_address"` // MAC地址
HostIDs string `json:"hostIds" gorm:"column:host_ids"` // 网元主机ID组 数据格式(ssh,telnet) UDM(ssh,telnet,redis) UPF(ssh,telnet,telnet)
Status int64 `json:"status" gorm:"column:status"` // 网元状态 0离线 1在线 2配置待下发 3备用模式
Remark string `json:"remark" gorm:"column:remark"` // 备注
CreateBy string `json:"createBy" gorm:"column:create_by"` // 创建者
CreateTime int64 `json:"createTime" gorm:"column:create_time"` // 创建时间
UpdateBy string `json:"updateBy" gorm:"column:update_by"` // 更新者
UpdateTime int64 `json:"updateTime" gorm:"column:update_time"` // 更新时间
// ====== 非数据库字段属性 ======

View File

@@ -2,19 +2,19 @@ package model
// NeLicense 网元授权激活信息 ne_license
type NeLicense struct {
ID string `json:"id" gorm:"id"`
NeType string `json:"neType" gorm:"ne_type" binding:"required"` // 网元类型
NeId string `json:"neId" gorm:"ne_id" binding:"required"` // 网元ID
ActivationRequestCode string `json:"activationRequestCode" gorm:"activation_request_code"` // 激活申请代码
LicensePath string `json:"licensePath" gorm:"license_path"` // 激活授权文件
SerialNum string `json:"serialNum" gorm:"serial_num"` // 序列号
ExpiryDate string `json:"expiryDate" gorm:"expiry_date"` // 许可证到期日期
Status string `json:"status" gorm:"status"` // 状态 0无效 1有效
Remark string `json:"remark" gorm:"remark"` // 备注
CreateBy string `json:"createBy" gorm:"create_by"` // 创建者
CreateTime int64 `json:"createTime" gorm:"create_time"` // 创建时间
UpdateBy string `json:"updateBy" gorm:"update_by"` // 更新者
UpdateTime int64 `json:"updateTime" gorm:"update_time"` // 更新时间
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type" binding:"required"` // 网元类型
NeId string `json:"neId" gorm:"column:ne_id" binding:"required"` // 网元ID
ActivationRequestCode string `json:"activationRequestCode" gorm:"column:activation_request_code"` // 激活申请代码
LicensePath string `json:"licensePath" gorm:"column:license_path"` // 激活授权文件
SerialNum string `json:"serialNum" gorm:"column:serial_num"` // 序列号
ExpiryDate string `json:"expiryDate" gorm:"column:expiry_date"` // 许可证到期日期
Status string `json:"status" gorm:"column:status"` // 状态 0无效 1有效
Remark string `json:"remark" gorm:"column:remark"` // 备注
CreateBy string `json:"createBy" gorm:"column:create_by"` // 创建者
CreateTime int64 `json:"createTime" gorm:"column:create_time"` // 创建时间
UpdateBy string `json:"updateBy" gorm:"column:update_by"` // 更新者
UpdateTime int64 `json:"updateTime" gorm:"column:update_time"` // 更新时间
// ====== 非数据库字段属性 ======

View File

@@ -2,16 +2,16 @@ package model
// NeSoftware 网元软件包 ne_software
type NeSoftware struct {
ID string `json:"id" gorm:"id"`
NeType string `json:"neType" gorm:"ne_type" binding:"required"` // 网元类型
Name string `json:"name" gorm:"name" binding:"required"` // 包名称
Path string `json:"path" gorm:"path"` // 包路径
Version string `json:"version" gorm:"version" binding:"required"` // 包版本
Description string `json:"description" gorm:"description"` // 包说明
CreateBy string `json:"createBy" gorm:"column:create_by"` // 创建者
CreateTime int64 `json:"createTime" gorm:"column:create_time"` // 创建时间
UpdateBy string `json:"updateBy" gorm:"column:update_by"` // 更新者
UpdateTime int64 `json:"updateTime" gorm:"column:update_time"` // 更新时间
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type" binding:"required"` // 网元类型
Name string `json:"name" gorm:"column:name" binding:"required"` // 包名称
Path string `json:"path" gorm:"column:path"` // 包路径
Version string `json:"version" gorm:"column:version" binding:"required"` // 包版本
Description string `json:"description" gorm:"column:description"` // 包说明
CreateBy string `json:"createBy" gorm:"column:create_by"` // 创建者
CreateTime int64 `json:"createTime" gorm:"column:create_time"` // 创建时间
UpdateBy string `json:"updateBy" gorm:"column:update_by"` // 更新者
UpdateTime int64 `json:"updateTime" gorm:"column:update_time"` // 更新时间
// ====== 非数据库字段属性 ======

View File

@@ -2,23 +2,23 @@ package model
// NeVersion 网元版本信息 ne_version
type NeVersion struct {
ID string `json:"id" gorm:"id"`
NeType string `json:"neType" gorm:"ne_type" binding:"required"` // 网元类型
NeId string `json:"neId" gorm:"ne_id" binding:"required"` // 网元ID
Name string `json:"name" gorm:"name"` // 当前包名
Version string `json:"version" gorm:"version" binding:"required"` // 当前版本
Path string `json:"path" gorm:"path" binding:"required"` // 当前软件包
PreName string `json:"preName" gorm:"pre_name"` // 上一版本包名
PreVersion string `json:"preVersion" gorm:"pre_version"` // 上一版本
PrePath string `json:"prePath" gorm:"pre_path"` // 上一版本软件包
NewName string `json:"newName" gorm:"new_name"` // 新版本包名
NewVersion string `json:"newVersion" gorm:"new_version"` // 新版本
NewPath string `json:"newPath" gorm:"new_path"` // 新版本软件包
Status string `json:"status" gorm:"status"` // 当前状态 1当前版本 2上一版本 3有新版本
CreateBy string `json:"createBy" gorm:"column:create_by"` // 创建者
CreateTime int64 `json:"createTime" gorm:"column:create_time"` // 创建时间
UpdateBy string `json:"updateBy" gorm:"column:update_by"` // 更新者
UpdateTime int64 `json:"updateTime" gorm:"column:update_time"` // 更新时间
ID int64 `json:"id" gorm:"column:id;primaryKey;autoIncrement"`
NeType string `json:"neType" gorm:"column:ne_type" binding:"required"` // 网元类型
NeId string `json:"neId" gorm:"column:ne_id" binding:"required"` // 网元ID
Name string `json:"name" gorm:"column:name"` // 当前包名
Version string `json:"version" gorm:"column:version" binding:"required"` // 当前版本
Path string `json:"path" gorm:"column:path" binding:"required"` // 当前软件包
PreName string `json:"preName" gorm:"column:pre_name"` // 上一版本包名
PreVersion string `json:"preVersion" gorm:"column:pre_version"` // 上一版本
PrePath string `json:"prePath" gorm:"column:pre_path"` // 上一版本软件包
NewName string `json:"newName" gorm:"column:new_name"` // 新版本包名
NewVersion string `json:"newVersion" gorm:"column:new_version"` // 新版本
NewPath string `json:"newPath" gorm:"column:new_path"` // 新版本软件包
Status string `json:"status" gorm:"column:status"` // 当前状态 1当前版本 2上一版本 3有新版本
CreateBy string `json:"createBy" gorm:"column:create_by"` // 创建者
CreateTime int64 `json:"createTime" gorm:"column:create_time"` // 创建时间
UpdateBy string `json:"updateBy" gorm:"column:update_by"` // 更新者
UpdateTime int64 `json:"updateTime" gorm:"column:update_time"` // 更新时间
}
// TableName 表名称

View File

@@ -153,14 +153,14 @@ func connDB() *gorm.DB {
}
// saveDB 表插入或更新
func saveDB(s model.NeConfig) string {
func saveDB(s model.NeConfig) int64 {
db := connDB()
// 检查是否存在
var id string
var id int64
db.Raw("SELECT id FROM ne_config WHERE ne_type = ? AND param_name = ?", s.NeType, s.ParamName).Scan(&id)
// 更新时间
s.UpdateTime = time.Now().UnixMilli()
if id != "" {
if id > 0 {
s.ID = id
db.Save(&s)
} else {

View File

@@ -85,7 +85,7 @@ func Setup(router *gin.Engine) {
middleware.PreAuthorize(nil),
controller.NewNeInfo.List,
)
neInfoGroup.GET("/:infoId",
neInfoGroup.GET("/:id",
middleware.CryptoApi(false, true),
middleware.PreAuthorize(nil),
controller.NewNeInfo.Info,
@@ -102,7 +102,7 @@ func Setup(router *gin.Engine) {
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.neInfo", collectlogs.BUSINESS_TYPE_UPDATE)),
controller.NewNeInfo.Edit,
)
neInfoGroup.DELETE("/:infoIds",
neInfoGroup.DELETE(":id",
middleware.PreAuthorize(nil),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.neInfo", collectlogs.BUSINESS_TYPE_DELETE)),
controller.NewNeInfo.Remove,
@@ -116,7 +116,7 @@ func Setup(router *gin.Engine) {
middleware.PreAuthorize(nil),
controller.NewNeHost.List,
)
neHostGroup.GET("/:hostId",
neHostGroup.GET("/:id",
middleware.CryptoApi(false, true),
middleware.PreAuthorize(nil),
controller.NewNeHost.Info,
@@ -131,7 +131,7 @@ func Setup(router *gin.Engine) {
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.neHost", collectlogs.BUSINESS_TYPE_UPDATE)),
controller.NewNeHost.Edit,
)
neHostGroup.DELETE("/:hostIds",
neHostGroup.DELETE("/:id",
middleware.PreAuthorize(nil),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.neHost", collectlogs.BUSINESS_TYPE_DELETE)),
controller.NewNeHost.Remove,
@@ -165,7 +165,7 @@ func Setup(router *gin.Engine) {
middleware.PreAuthorize(nil),
controller.NewNeHostCmd.List,
)
neHostCmdGroup.GET("/:cmdId",
neHostCmdGroup.GET("/:id",
middleware.PreAuthorize(nil),
controller.NewNeHostCmd.Info,
)
@@ -179,7 +179,7 @@ func Setup(router *gin.Engine) {
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.neHostCmd", collectlogs.BUSINESS_TYPE_UPDATE)),
controller.NewNeHostCmd.Edit,
)
neHostCmdGroup.DELETE("/:cmdIds",
neHostCmdGroup.DELETE(":id",
middleware.PreAuthorize(nil),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.neHostCmd", collectlogs.BUSINESS_TYPE_DELETE)),
controller.NewNeHostCmd.Remove,
@@ -193,7 +193,7 @@ func Setup(router *gin.Engine) {
middleware.PreAuthorize(nil),
controller.NewNeVersion.List,
)
neVersionGroup.GET("/:versionId",
neVersionGroup.GET("/:id",
middleware.PreAuthorize(nil),
controller.NewNeVersion.Info,
)
@@ -211,7 +211,7 @@ func Setup(router *gin.Engine) {
middleware.PreAuthorize(nil),
controller.NewNeSoftware.List,
)
neSoftwareGroup.GET("/:softwareId",
neSoftwareGroup.GET("/:id",
middleware.PreAuthorize(nil),
controller.NewNeSoftware.Info,
)
@@ -225,7 +225,7 @@ func Setup(router *gin.Engine) {
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.neSoftware", collectlogs.BUSINESS_TYPE_UPDATE)),
controller.NewNeSoftware.Edit,
)
neSoftwareGroup.DELETE("/:softwareIds",
neSoftwareGroup.DELETE(":id",
middleware.PreAuthorize(nil),
collectlogs.OperateLog(collectlogs.OptionNew("log.operate.title.neSoftware", collectlogs.BUSINESS_TYPE_DELETE)),
controller.NewNeSoftware.Remove,
@@ -244,7 +244,7 @@ func Setup(router *gin.Engine) {
middleware.PreAuthorize(nil),
controller.NewNeLicense.List,
)
neLicenseGroup.GET("/:licenseId",
neLicenseGroup.GET("/:id",
middleware.PreAuthorize(nil),
controller.NewNeLicense.Info,
)
@@ -358,7 +358,7 @@ func Setup(router *gin.Engine) {
func InitLoad() {
// 启动时,清除缓存-网元类型
service.NewNeInfo.ClearNeCacheByNeType("*")
service.NewNeInfo.SelectNeInfoByRmuid("")
service.NewNeInfo.FindByRmuid("")
// 启动时,网元公共参数数据记录到全局变量
if para5GMap, err := service.NewNeInfo.NeConfPara5GRead(); para5GMap != nil && err == nil {
service.NewNeInfo.NeConfPara5GWirte(para5GMap, nil)

View File

@@ -3,7 +3,7 @@ package repository
import (
"time"
"be.ems/src/framework/datasource"
"be.ems/src/framework/database/db"
"be.ems/src/framework/logger"
"be.ems/src/modules/network_element/model"
)
@@ -16,7 +16,7 @@ type NeConfig struct{}
// SelectByPage 分页查询集合
func (r NeConfig) SelectByPage(query map[string]string) ([]model.NeConfig, int64) {
tx := datasource.DB("").Model(&model.NeConfig{})
tx := db.DB("").Model(&model.NeConfig{})
// 查询条件拼接
if v, ok := query["neType"]; ok && v != "" {
tx = tx.Where("ne_type = ?", v)
@@ -35,7 +35,7 @@ func (r NeConfig) SelectByPage(query map[string]string) ([]model.NeConfig, int64
}
// 查询数据分页
pageNum, pageSize := datasource.PageNumSize(query["pageNum"], query["pageSize"])
pageNum, pageSize := db.PageNumSize(query["pageNum"], query["pageSize"])
tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
err := tx.Find(&rows).Error
if err != nil {
@@ -45,9 +45,9 @@ func (r NeConfig) SelectByPage(query map[string]string) ([]model.NeConfig, int64
return rows, total
}
// SelectList 根据实体查询
func (r *NeConfig) SelectList(param model.NeConfig) []model.NeConfig {
tx := datasource.DB("").Model(&model.NeConfig{})
// Select 查询集合
func (r NeConfig) Select(param model.NeConfig) []model.NeConfig {
tx := db.DB("").Model(&model.NeConfig{})
// 查询条件拼接
if param.NeType != "" {
tx = tx.Where("ne_type = ?", param.NeType)
@@ -66,12 +66,12 @@ func (r *NeConfig) SelectList(param model.NeConfig) []model.NeConfig {
}
// SelectByIds 通过ID查询
func (r *NeConfig) SelectByIds(ids []string) []model.NeConfig {
func (r NeConfig) SelectByIds(ids []int64) []model.NeConfig {
rows := []model.NeConfig{}
if len(ids) <= 0 {
return rows
}
tx := datasource.DB("").Model(&model.NeConfig{})
tx := db.DB("").Model(&model.NeConfig{})
// 构建查询条件
tx = tx.Where("id in ?", ids)
// 查询数据
@@ -83,23 +83,23 @@ func (r *NeConfig) SelectByIds(ids []string) []model.NeConfig {
}
// Insert 新增信息
func (r *NeConfig) Insert(param model.NeConfig) string {
func (r NeConfig) Insert(param model.NeConfig) int64 {
param.UpdateTime = time.Now().UnixMilli()
// 执行插入
if err := datasource.DB("").Create(&param).Error; err != nil {
if err := db.DB("").Create(&param).Error; err != nil {
logger.Errorf("insert err => %v", err.Error())
return ""
return 0
}
return param.ID
}
// Update 修改信息
func (r *NeConfig) Update(param model.NeConfig) int64 {
if param.ID == "" {
func (r NeConfig) Update(param model.NeConfig) int64 {
if param.ID == 0 {
return 0
}
param.UpdateTime = time.Now().UnixMilli()
tx := datasource.DB("").Model(&model.NeConfig{})
tx := db.DB("").Model(&model.NeConfig{})
// 构建查询条件
tx = tx.Where("id = ?", param.ID)
tx = tx.Omit("id")
@@ -112,11 +112,11 @@ func (r *NeConfig) Update(param model.NeConfig) int64 {
}
// DeleteByIds 批量删除信息
func (r *NeConfig) DeleteByIds(ids []string) int64 {
func (r NeConfig) DeleteByIds(ids []int64) int64 {
if len(ids) <= 0 {
return 0
}
tx := datasource.DB("").Where("id in ?", ids)
tx := db.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.NeConfig{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error())
return 0

View File

@@ -1,262 +1,118 @@
package repository
import (
"strings"
"time"
"be.ems/src/framework/datasource"
"be.ems/src/framework/database/db"
"be.ems/src/framework/logger"
"be.ems/src/framework/utils/parse"
"be.ems/src/framework/utils/repo"
"be.ems/src/modules/network_element/model"
)
// 实例化数据层 NeConfigBackup 结构体
var NewNeConfigBackup = &NeConfigBackup{
selectSql: `select
id, ne_type, ne_id, name, path, remark, create_by, create_time, update_by, update_time
from ne_config_backup`,
resultMap: map[string]string{
"id": "ID",
"ne_type": "NeType",
"ne_id": "NeId",
"name": "Name",
"path": "Path",
"remark": "Remark",
"create_by": "CreateBy",
"create_time": "CreateTime",
"update_by": "UpdateBy",
"update_time": "UpdateTime",
},
}
var NewNeConfigBackup = &NeConfigBackup{}
// NeConfigBackup 网元配置文件备份记录 数据层处理
type NeConfigBackup struct {
// 查询视图对象SQL
selectSql string
// 结果字段与实体映射
resultMap map[string]string
}
type NeConfigBackup struct{}
// convertResultRows 将结果记录转实体结果组
func (r *NeConfigBackup) convertResultRows(rows []map[string]any) []model.NeConfigBackup {
arr := make([]model.NeConfigBackup, 0)
for _, row := range rows {
item := model.NeConfigBackup{}
for key, value := range row {
if keyMapper, ok := r.resultMap[key]; ok {
repo.SetFieldValue(&item, keyMapper, value)
}
}
arr = append(arr, item)
}
return arr
}
// SelectPage 根据条件分页查询字典类型
func (r *NeConfigBackup) SelectPage(query map[string]any) map[string]any {
// SelectByPage 分页查询集合
func (r NeConfigBackup) SelectByPage(query map[string]string) ([]model.NeConfigBackup, int64) {
tx := db.DB("").Model(&model.NeConfigBackup{})
// 查询条件拼接
var conditions []string
var params []any
if v, ok := query["neType"]; ok && v != "" {
conditions = append(conditions, "ne_type = ?")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("ne_type = ?", v)
}
if v, ok := query["neId"]; ok && v != "" {
conditions = append(conditions, "ne_id = ?")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("neId = ?", v)
}
if v, ok := query["name"]; ok && v != "" {
conditions = append(conditions, "name like concat(concat('%', ?), '%')")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("name like concat(concat('%', ?), '%')", v)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
// 查询结果
var total int64 = 0
rows := []model.NeConfigBackup{}
// 查询数量为0直接返回
if err := tx.Count(&total).Error; err != nil || total <= 0 {
return rows, total
}
result := map[string]any{
"total": 0,
"rows": []model.NeHost{},
}
// 查询数量 长度为0直接返回
totalSql := "select count(1) as 'total' from ne_config_backup"
totalRows, err := datasource.RawDB("", totalSql+whereSql, params)
// 查询数据分页
pageNum, pageSize := db.PageNumSize(query["pageNum"], query["pageSize"])
tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
err := tx.Order("id desc").Find(&rows).Error
if err != nil {
logger.Errorf("total err => %v", err)
return result
logger.Errorf("query find err => %v", err.Error())
return rows, total
}
total := parse.Number(totalRows[0]["total"])
if total == 0 {
return result
} else {
result["total"] = total
return rows, total
}
// SelectByIds 通过ID查询信息
func (r NeConfigBackup) SelectByIds(ids []int64) []model.NeConfigBackup {
rows := []model.NeConfigBackup{}
if len(ids) <= 0 {
return rows
}
// 分页
pageNum, pageSize := repo.PageNumSize(query["pageNum"], query["pageSize"])
pageSql := " order by id desc limit ?,? "
params = append(params, pageNum*pageSize)
params = append(params, pageSize)
tx := db.DB("").Model(&model.NeConfigBackup{})
// 构建查询条件
tx = tx.Where("id in ?", ids)
// 查询数据
querySql := r.selectSql + whereSql + pageSql
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
return result
}
// 转换实体
result["rows"] = r.convertResultRows(results)
return result
}
// SelectList 根据实体查询
func (r *NeConfigBackup) SelectList(item model.NeConfigBackup) []model.NeConfigBackup {
// 查询条件拼接
var conditions []string
var params []any
if item.NeType != "" {
conditions = append(conditions, "ne_type = ?")
params = append(params, item.NeType)
}
if item.NeId != "" {
conditions = append(conditions, "ne_id = ?")
params = append(params, item.NeId)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
}
// 查询数据
querySql := r.selectSql + whereSql + " order by id desc "
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
}
// 转换实体
return r.convertResultRows(results)
}
// SelectByIds 通过ID查询
func (r *NeConfigBackup) SelectByIds(cmdIds []string) []model.NeConfigBackup {
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
querySql := r.selectSql + " where id in (" + placeholder + ")"
parameters := repo.ConvertIdsSlice(cmdIds)
results, err := datasource.RawDB("", querySql, parameters)
if err != nil {
logger.Errorf("query err => %v", err)
return []model.NeConfigBackup{}
}
// 转换实体
return r.convertResultRows(results)
}
// Insert 新增信息
func (r *NeConfigBackup) Insert(item model.NeConfigBackup) string {
// 参数拼接
params := make(map[string]any)
if item.NeType != "" {
params["ne_type"] = item.NeType
}
if item.NeId != "" {
params["ne_id"] = item.NeId
}
if item.Name != "" {
params["name"] = item.Name
}
if item.Path != "" {
params["path"] = item.Path
}
if item.Remark != "" {
params["remark"] = item.Remark
}
if item.CreateBy != "" {
params["create_by"] = item.CreateBy
params["create_time"] = time.Now().UnixMilli()
}
// 构建执行语句
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
sql := "insert into ne_config_backup (" + strings.Join(keys, ",") + ")values(" + placeholder + ")"
db := datasource.DefaultDB()
// 开启事务
tx := db.Begin()
// 执行插入
err := tx.Exec(sql, values...).Error
if err != nil {
logger.Errorf("insert row : %v", err.Error())
tx.Rollback()
return ""
}
// 获取生成的自增 ID
var insertedID string
err = tx.Raw("select last_insert_id()").Row().Scan(&insertedID)
if err != nil {
logger.Errorf("insert last id : %v", err.Error())
tx.Rollback()
return ""
}
// 提交事务
tx.Commit()
return insertedID
}
// Update 修改信息
func (r *NeConfigBackup) Update(item model.NeConfigBackup) int64 {
// 参数拼接
params := make(map[string]any)
if item.NeType != "" {
params["ne_type"] = item.NeType
}
if item.NeId != "" {
params["ne_id"] = item.NeId
}
if item.Name != "" {
params["name"] = item.Name
}
if item.Path != "" {
params["path"] = item.Path
}
params["remark"] = item.Remark
if item.UpdateBy != "" {
params["update_by"] = item.UpdateBy
params["update_time"] = time.Now().UnixMilli()
}
// 构建执行语句
keys, values := repo.KeyValueByUpdate(params)
sql := "update ne_config_backup set " + strings.Join(keys, ",") + " where id = ?"
// 执行更新
values = append(values, item.ID)
rows, err := datasource.ExecDB("", sql, values)
if err != nil {
logger.Errorf("update row : %v", err.Error())
return 0
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// DeleteByIds 批量删除信息
func (r *NeConfigBackup) DeleteByIds(ids []string) int64 {
placeholder := repo.KeyPlaceholderByQuery(len(ids))
sql := "delete from ne_config_backup where id in (" + placeholder + ")"
parameters := repo.ConvertIdsSlice(ids)
results, err := datasource.ExecDB("", sql, parameters)
if err != nil {
logger.Errorf("delete err => %v", err)
// Insert 新增信息 返回新增数据ID
func (r NeConfigBackup) Insert(item model.NeConfigBackup) int64 {
if item.CreateBy != "" {
ms := time.Now().UnixMilli()
item.UpdateBy = item.CreateBy
item.UpdateTime = ms
item.CreateTime = ms
}
// 执行插入
if err := db.DB("").Create(&item).Error; err != nil {
logger.Errorf("insert err => %v", err.Error())
return 0
}
return results
return item.ID
}
// Update 修改信息 返回受影响行数
func (r NeConfigBackup) Update(item model.NeConfigBackup) int64 {
if item.ID <= 0 {
return 0
}
if item.UpdateBy != "" {
item.UpdateTime = time.Now().UnixMilli()
}
tx := db.DB("").Model(&model.NeConfigBackup{})
// 构建查询条件
tx = tx.Where("id = ?", item.ID)
tx = tx.Omit("id", "create_by", "create_time")
// 执行更新
if err := tx.Updates(item).Error; err != nil {
logger.Errorf("update err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// DeleteByIds 批量删除信息 返回受影响行数
func (r NeConfigBackup) DeleteByIds(ids []int64) int64 {
if len(ids) <= 0 {
return 0
}
if len(ids) <= 0 {
return 0
}
tx := db.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.NeConfigBackup{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error())
return 0
}
return tx.RowsAffected
}

View File

@@ -2,117 +2,47 @@ package repository
import (
"fmt"
"strings"
"time"
"be.ems/src/framework/datasource"
"be.ems/src/framework/database/db"
"be.ems/src/framework/logger"
"be.ems/src/framework/utils/parse"
"be.ems/src/framework/utils/repo"
"be.ems/src/modules/network_element/model"
)
// 实例化数据层 NeHost 结构体
var NewNeHost = &NeHost{
selectSql: `select
host_id, host_type, group_id, title, addr, port, user, auth_mode, password, private_key, pass_phrase, db_name, remark, create_by, create_time, update_by, update_time
from ne_host`,
resultMap: map[string]string{
"host_id": "HostID",
"host_type": "HostType",
"group_id": "GroupID",
"title": "Title",
"addr": "Addr",
"port": "Port",
"user": "User",
"auth_mode": "AuthMode",
"password": "Password",
"private_key": "PrivateKey",
"private_password": "PassPhrase",
"db_name": "DBName",
"remark": "Remark",
"create_by": "CreateBy",
"create_time": "CreateTime",
"update_by": "UpdateBy",
"update_time": "UpdateTime",
},
}
var NewNeHost = &NeHost{}
// NeHost 网元主机连接 数据层处理
type NeHost struct {
// 查询视图对象SQL
selectSql string
// 结果字段与实体映射
resultMap map[string]string
}
type NeHost struct{}
// convertResultRows 将结果记录转实体结果组
func (r *NeHost) convertResultRows(rows []map[string]any) []model.NeHost {
arr := make([]model.NeHost, 0)
for _, row := range rows {
item := model.NeHost{}
for key, value := range row {
if keyMapper, ok := r.resultMap[key]; ok {
repo.SetFieldValue(&item, keyMapper, value)
}
}
arr = append(arr, item)
}
return arr
}
// SelectPage 根据条件分页查询字典类型
func (r *NeHost) SelectPage(query map[string]any) map[string]any {
// SelectByPage 分页查询集合
func (r NeHost) SelectByPage(query map[string]string) ([]model.NeHost, int64) {
tx := db.DB("").Model(&model.NeHost{})
// 查询条件拼接
var conditions []string
var params []any
if v, ok := query["hostType"]; ok && v != "" {
conditions = append(conditions, "host_type = ?")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("host_type = ?", v)
}
if v, ok := query["groupId"]; ok && v != "" {
conditions = append(conditions, "group_id = ?")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("group_id = ?", v)
}
if v, ok := query["title"]; ok && v != "" {
conditions = append(conditions, "title like concat(?, '%')")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("title like concat(?, '%')", v)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
// 查询结果
var total int64 = 0
rows := []model.NeHost{}
// 查询数量为0直接返回
if err := tx.Count(&total).Error; err != nil || total <= 0 {
return rows, total
}
result := map[string]any{
"total": 0,
"rows": []model.NeHost{},
}
// 查询数量 长度为0直接返回
totalSql := "select count(1) as 'total' from ne_host"
totalRows, err := datasource.RawDB("", totalSql+whereSql, params)
if err != nil {
logger.Errorf("total err => %v", err)
return result
}
total := parse.Number(totalRows[0]["total"])
if total == 0 {
return result
} else {
result["total"] = total
}
// 分页
pageNum, pageSize := repo.PageNumSize(query["pageNum"], query["pageSize"])
pageSql := " limit ?,? "
params = append(params, pageNum*pageSize)
params = append(params, pageSize)
// 查询数据分页
pageNum, pageSize := db.PageNumSize(query["pageNum"], query["pageSize"])
tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
// 排序
orderSql := ""
if sv, ok := query["sortField"]; ok && sv != "" {
sortSql := fmt.Sprint(sv)
if sortSql == "updateTime" {
@@ -128,276 +58,120 @@ func (r *NeHost) SelectPage(query map[string]any) map[string]any {
sortSql += " asc "
}
}
orderSql = fmt.Sprintf(" order by %s ", sortSql)
tx = tx.Order(sortSql)
}
// 查询数据
querySql := r.selectSql + whereSql + orderSql + pageSql
results, err := datasource.RawDB("", querySql, params)
err := tx.Find(&rows).Error
if err != nil {
logger.Errorf("query err => %v", err)
return result
logger.Errorf("query find err => %v", err.Error())
return rows, total
}
// 转换实体
result["rows"] = r.convertResultRows(results)
return result
}
// SelectList 根据实体查询
func (r *NeHost) SelectList(neHost model.NeHost) []model.NeHost {
// 查询条件拼接
var conditions []string
var params []any
if neHost.HostType != "" {
conditions = append(conditions, "host_type = ?")
params = append(params, neHost.HostType)
}
if neHost.GroupID != "" {
conditions = append(conditions, "group_id = ?")
params = append(params, neHost.GroupID)
}
if neHost.Title != "" {
conditions = append(conditions, "title like concat(?, '%')")
params = append(params, neHost.Title)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
}
// 查询数据
querySql := r.selectSql + whereSql + " order by update_time asc "
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
}
// 转换实体
return r.convertResultRows(results)
return rows, total
}
// SelectByIds 通过ID查询
func (r *NeHost) SelectByIds(hostIds []string) []model.NeHost {
placeholder := repo.KeyPlaceholderByQuery(len(hostIds))
querySql := r.selectSql + " where host_id in (" + placeholder + ")"
parameters := repo.ConvertIdsSlice(hostIds)
results, err := datasource.RawDB("", querySql, parameters)
if err != nil {
logger.Errorf("query err => %v", err)
return []model.NeHost{}
func (r NeHost) SelectByIds(ids []int64) []model.NeHost {
rows := []model.NeHost{}
if len(ids) <= 0 {
return rows
}
// 转换实体
return r.convertResultRows(results)
}
// CheckUniqueNeHost 校验主机是否唯一
func (r *NeHost) CheckUniqueNeHost(neHost model.NeHost) string {
// 查询条件拼接
var conditions []string
var params []any
if neHost.HostType != "" {
conditions = append(conditions, "host_type = ?")
params = append(params, neHost.HostType)
}
if neHost.GroupID != "" {
conditions = append(conditions, "group_id = ?")
params = append(params, neHost.GroupID)
}
if neHost.Title != "" {
conditions = append(conditions, "title = ?")
params = append(params, neHost.Title)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
} else {
return ""
}
tx := db.DB("").Model(&model.NeHost{})
// 构建查询条件
tx = tx.Where("id in ?", ids)
// 查询数据
querySql := "select host_id as 'str' from ne_host " + whereSql + " limit 1"
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err %v", err)
return ""
}
if len(results) > 0 {
return fmt.Sprint(results[0]["str"])
}
return ""
}
// Insert 新增信息
func (r *NeHost) Insert(neHost model.NeHost) string {
// 参数拼接
params := make(map[string]any)
if neHost.HostType != "" {
params["host_type"] = neHost.HostType
}
if neHost.GroupID != "" {
params["group_id"] = neHost.GroupID
}
if neHost.Title != "" {
params["title"] = neHost.Title
}
if neHost.Addr != "" {
params["addr"] = neHost.Addr
}
if neHost.Port > 0 {
params["port"] = neHost.Port
}
if neHost.User != "" {
params["user"] = neHost.User
}
if neHost.AuthMode != "" {
params["auth_mode"] = neHost.AuthMode
}
if neHost.Password != "" {
params["password"] = neHost.Password
}
if neHost.PrivateKey != "" {
params["private_key"] = neHost.PrivateKey
}
if neHost.PassPhrase != "" {
params["pass_phrase"] = neHost.PassPhrase
}
if neHost.DBName != "" {
params["db_name"] = neHost.DBName
}
if neHost.Remark != "" {
params["remark"] = neHost.Remark
}
if neHost.CreateBy != "" {
params["create_by"] = neHost.CreateBy
params["create_time"] = time.Now().UnixMilli()
}
// 根据认证模式清除不必要的信息
if neHost.AuthMode == "0" {
params["private_key"] = ""
params["pass_phrase"] = ""
}
if neHost.AuthMode == "1" {
params["password"] = ""
}
if neHost.AuthMode == "2" {
params["password"] = ""
params["private_key"] = ""
params["pass_phrase"] = ""
}
// 构建执行语句
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
sql := "insert into ne_host (" + strings.Join(keys, ",") + ")values(" + placeholder + ")"
db := datasource.DefaultDB()
// 开启事务
tx := db.Begin()
// 执行插入
err := tx.Exec(sql, values...).Error
if err != nil {
logger.Errorf("insert row : %v", err.Error())
tx.Rollback()
return ""
}
// 获取生成的自增 ID
var insertedID string
err = tx.Raw("select last_insert_id()").Row().Scan(&insertedID)
if err != nil {
logger.Errorf("insert last id : %v", err.Error())
tx.Rollback()
return ""
}
// 提交事务
tx.Commit()
return insertedID
}
// Update 修改信息
func (r *NeHost) Update(neHost model.NeHost) int64 {
// 参数拼接
params := make(map[string]any)
if neHost.HostType != "" {
params["host_type"] = neHost.HostType
}
if neHost.GroupID != "" {
params["group_id"] = neHost.GroupID
}
if neHost.Title != "" {
params["title"] = neHost.Title
}
if neHost.Addr != "" {
params["addr"] = neHost.Addr
}
if neHost.Port > 0 {
params["port"] = neHost.Port
}
if neHost.User != "" {
params["user"] = neHost.User
}
if neHost.AuthMode != "" {
params["auth_mode"] = neHost.AuthMode
}
if neHost.Password != "" {
params["password"] = neHost.Password
}
if neHost.PrivateKey != "" {
params["private_key"] = neHost.PrivateKey
}
if neHost.PassPhrase != "" {
params["pass_phrase"] = neHost.PassPhrase
}
if neHost.DBName != "" {
params["db_name"] = neHost.DBName
}
params["remark"] = neHost.Remark
if neHost.UpdateBy != "" {
params["update_by"] = neHost.UpdateBy
params["update_time"] = time.Now().UnixMilli()
}
// 根据认证模式清除不必要的信息
if neHost.AuthMode == "0" {
params["private_key"] = ""
params["pass_phrase"] = ""
}
if neHost.AuthMode == "1" {
params["password"] = ""
}
if neHost.AuthMode == "2" {
params["password"] = ""
params["private_key"] = ""
params["pass_phrase"] = ""
}
// 构建执行语句
keys, values := repo.KeyValueByUpdate(params)
sql := "update ne_host set " + strings.Join(keys, ",") + " where host_id = ?"
// 执行更新
values = append(values, neHost.HostID)
rows, err := datasource.ExecDB("", sql, values)
if err != nil {
logger.Errorf("update row : %v", err.Error())
return 0
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// DeleteByIds 批量删除网元主机连接信息
func (r *NeHost) DeleteByIds(hostIds []string) int64 {
placeholder := repo.KeyPlaceholderByQuery(len(hostIds))
sql := "delete from ne_host where host_id in (" + placeholder + ")"
parameters := repo.ConvertIdsSlice(hostIds)
results, err := datasource.ExecDB("", sql, parameters)
if err != nil {
logger.Errorf("delete err => %v", err)
// Insert 新增信息
func (r NeHost) Insert(param model.NeHost) int64 {
param.UpdateTime = time.Now().UnixMilli()
// 根据认证模式清除不必要的信息
if param.AuthMode == "0" {
param.PrivateKey = ""
param.PassPhrase = ""
}
if param.AuthMode == "1" {
param.Password = ""
}
if param.AuthMode == "2" {
param.Password = ""
param.PrivateKey = ""
param.PassPhrase = ""
}
// 执行插入
if err := db.DB("").Create(&param).Error; err != nil {
logger.Errorf("insert err => %v", err.Error())
return 0
}
return results
return param.ID
}
// Update 修改信息
func (r NeHost) Update(param model.NeHost) int64 {
if param.ID == 0 {
return 0
}
// 根据认证模式清除不必要的信息
if param.AuthMode == "0" {
param.PrivateKey = ""
param.PassPhrase = ""
}
if param.AuthMode == "1" {
param.Password = ""
}
if param.AuthMode == "2" {
param.Password = ""
param.PrivateKey = ""
param.PassPhrase = ""
}
param.UpdateTime = time.Now().UnixMilli()
tx := db.DB("").Model(&model.NeHost{})
// 构建查询条件
tx = tx.Where("id = ?", param.ID)
tx = tx.Omit("id")
// 执行更新
if err := tx.Updates(param).Error; err != nil {
logger.Errorf("update err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// DeleteByIds 批量删除信息
func (r NeHost) DeleteByIds(ids []int64) int64 {
if len(ids) <= 0 {
return 0
}
tx := db.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.NeHost{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// CheckUnique 检查信息是否唯一 返回数据ID
func (r NeHost) CheckUnique(param model.NeHost) int64 {
tx := db.DB("").Model(&model.NeHost{})
// 查询条件拼接
if param.HostType != "" {
tx = tx.Where("host_type = ?", param.HostType)
}
if param.GroupID != "" {
tx = tx.Where("group_id = ?", param.GroupID)
}
if param.Title != "" {
tx = tx.Where("title = ?", param.Title)
}
// 查询数据
var id int64 = 0
if err := tx.Select("id").Limit(1).Find(&id).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return id
}
return id
}

View File

@@ -1,306 +1,130 @@
package repository
import (
"fmt"
"strings"
"time"
"be.ems/src/framework/datasource"
"be.ems/src/framework/database/db"
"be.ems/src/framework/logger"
"be.ems/src/framework/utils/parse"
"be.ems/src/framework/utils/repo"
"be.ems/src/modules/network_element/model"
)
// 实例化数据层 NeHostCmd 结构体
var NewNeHostCmd = &NeHostCmd{
selectSql: `select
cmd_id, cmd_type, group_id, title, command, remark, create_by, create_time, update_by, update_time
from ne_host_cmd`,
resultMap: map[string]string{
"cmd_id": "CmdID",
"cmd_type": "CmdType",
"group_id": "GroupID",
"title": "Title",
"command": "Command",
"remark": "Remark",
"create_by": "CreateBy",
"create_time": "CreateTime",
"update_by": "UpdateBy",
"update_time": "UpdateTime",
},
}
var NewNeHostCmd = &NeHostCmd{}
// NeHostCmd 网元主机连接 数据层处理
type NeHostCmd struct {
// 查询视图对象SQL
selectSql string
// 结果字段与实体映射
resultMap map[string]string
}
type NeHostCmd struct{}
// convertResultRows 将结果记录转实体结果组
func (r *NeHostCmd) convertResultRows(rows []map[string]any) []model.NeHostCmd {
arr := make([]model.NeHostCmd, 0)
for _, row := range rows {
item := model.NeHostCmd{}
for key, value := range row {
if keyMapper, ok := r.resultMap[key]; ok {
repo.SetFieldValue(&item, keyMapper, value)
}
}
arr = append(arr, item)
}
return arr
}
// SelectPage 根据条件分页查询字典类型
func (r *NeHostCmd) SelectPage(query map[string]any) map[string]any {
// SelectByPage 分页查询集合
func (r NeHostCmd) SelectByPage(query map[string]string) ([]model.NeHostCmd, int64) {
tx := db.DB("").Model(&model.NeHostCmd{})
// 查询条件拼接
var conditions []string
var params []any
if v, ok := query["cmdType"]; ok && v != "" {
conditions = append(conditions, "cmd_type = ?")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("cmd_type = ?", v)
}
if v, ok := query["groupId"]; ok && v != "" {
conditions = append(conditions, "group_id = ?")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("group_id = ?", v)
}
if v, ok := query["title"]; ok && v != "" {
conditions = append(conditions, "title like concat(?, '%')")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("title like concat(?, '%')", v)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
// 查询结果
var total int64 = 0
rows := []model.NeHostCmd{}
// 查询数量为0直接返回
if err := tx.Count(&total).Error; err != nil || total <= 0 {
return rows, total
}
result := map[string]any{
"total": 0,
"rows": []model.NeHost{},
}
// 查询数量 长度为0直接返回
totalSql := "select count(1) as 'total' from ne_host_cmd"
totalRows, err := datasource.RawDB("", totalSql+whereSql, params)
// 查询数据分页
pageNum, pageSize := db.PageNumSize(query["pageNum"], query["pageSize"])
tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
err := tx.Find(&rows).Error
if err != nil {
logger.Errorf("total err => %v", err)
return result
logger.Errorf("query find err => %v", err.Error())
return rows, total
}
total := parse.Number(totalRows[0]["total"])
if total == 0 {
return result
} else {
result["total"] = total
}
// 分页
pageNum, pageSize := repo.PageNumSize(query["pageNum"], query["pageSize"])
pageSql := " limit ?,? "
params = append(params, pageNum*pageSize)
params = append(params, pageSize)
// 查询数据
querySql := r.selectSql + whereSql + pageSql
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
return result
}
// 转换实体
result["rows"] = r.convertResultRows(results)
return result
}
// SelectList 根据实体查询
func (r *NeHostCmd) SelectList(neHostCmd model.NeHostCmd) []model.NeHostCmd {
// 查询条件拼接
var conditions []string
var params []any
if neHostCmd.CmdType != "" {
conditions = append(conditions, "cmd_type = ?")
params = append(params, neHostCmd.CmdType)
}
if neHostCmd.GroupID != "" {
conditions = append(conditions, "group_id = ?")
params = append(params, neHostCmd.GroupID)
}
if neHostCmd.Title != "" {
conditions = append(conditions, "title like concat(?, '%')")
params = append(params, neHostCmd.Title)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
}
// 查询数据
querySql := r.selectSql + whereSql + " order by update_time asc "
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
}
// 转换实体
return r.convertResultRows(results)
return rows, total
}
// SelectByIds 通过ID查询
func (r *NeHostCmd) SelectByIds(cmdIds []string) []model.NeHostCmd {
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
querySql := r.selectSql + " where cmd_id in (" + placeholder + ")"
parameters := repo.ConvertIdsSlice(cmdIds)
results, err := datasource.RawDB("", querySql, parameters)
if err != nil {
logger.Errorf("query err => %v", err)
return []model.NeHostCmd{}
func (r NeHostCmd) SelectByIds(ids []int64) []model.NeHostCmd {
rows := []model.NeHostCmd{}
if len(ids) <= 0 {
return rows
}
// 转换实体
return r.convertResultRows(results)
}
// CheckUniqueGroupTitle 校验同类型组内是否唯一
func (r *NeHostCmd) CheckUniqueGroupTitle(neHostCmd model.NeHostCmd) string {
// 查询条件拼接
var conditions []string
var params []any
if neHostCmd.CmdType != "" {
conditions = append(conditions, "cmd_type = ?")
params = append(params, neHostCmd.CmdType)
}
if neHostCmd.GroupID != "" {
conditions = append(conditions, "group_id = ?")
params = append(params, neHostCmd.GroupID)
}
if neHostCmd.Title != "" {
conditions = append(conditions, "title = ?")
params = append(params, neHostCmd.Title)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
} else {
return ""
}
tx := db.DB("").Model(&model.NeHostCmd{})
// 构建查询条件
tx = tx.Where("id in ?", ids)
// 查询数据
querySql := "select host_id as 'str' from ne_host " + whereSql + " limit 1"
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err %v", err)
return ""
}
if len(results) > 0 {
return fmt.Sprint(results[0]["str"])
}
return ""
}
// Insert 新增信息
func (r *NeHostCmd) Insert(neHostCmd model.NeHostCmd) string {
// 参数拼接
params := make(map[string]any)
if neHostCmd.CmdType != "" {
params["cmd_type"] = neHostCmd.CmdType
}
if neHostCmd.GroupID != "" {
params["group_id"] = neHostCmd.GroupID
}
if neHostCmd.Title != "" {
params["title"] = neHostCmd.Title
}
if neHostCmd.Command != "" {
params["command"] = neHostCmd.Command
}
if neHostCmd.Remark != "" {
params["remark"] = neHostCmd.Remark
}
if neHostCmd.CreateBy != "" {
params["create_by"] = neHostCmd.CreateBy
params["create_time"] = time.Now().UnixMilli()
}
// 构建执行语句
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
sql := "insert into ne_host_cmd (" + strings.Join(keys, ",") + ")values(" + placeholder + ")"
db := datasource.DefaultDB()
// 开启事务
tx := db.Begin()
// 执行插入
err := tx.Exec(sql, values...).Error
if err != nil {
logger.Errorf("insert row : %v", err.Error())
tx.Rollback()
return ""
}
// 获取生成的自增 ID
var insertedID string
err = tx.Raw("select last_insert_id()").Row().Scan(&insertedID)
if err != nil {
logger.Errorf("insert last id : %v", err.Error())
tx.Rollback()
return ""
}
// 提交事务
tx.Commit()
return insertedID
}
// Update 修改信息
func (r *NeHostCmd) Update(neHostCmd model.NeHostCmd) int64 {
// 参数拼接
params := make(map[string]any)
if neHostCmd.CmdType != "" {
params["cmd_type"] = neHostCmd.CmdType
}
if neHostCmd.GroupID != "" {
params["group_id"] = neHostCmd.GroupID
}
if neHostCmd.Title != "" {
params["title"] = neHostCmd.Title
}
if neHostCmd.Command != "" {
params["command"] = neHostCmd.Command
}
params["remark"] = neHostCmd.Remark
if neHostCmd.UpdateBy != "" {
params["update_by"] = neHostCmd.UpdateBy
params["update_time"] = time.Now().UnixMilli()
}
// 构建执行语句
keys, values := repo.KeyValueByUpdate(params)
sql := "update ne_host_cmd set " + strings.Join(keys, ",") + " where cmd_id = ?"
// 执行更新
values = append(values, neHostCmd.CmdID)
rows, err := datasource.ExecDB("", sql, values)
if err != nil {
logger.Errorf("update row : %v", err.Error())
return 0
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// DeleteByIds 批量删除信息
func (r *NeHostCmd) DeleteByIds(cmdIds []string) int64 {
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
sql := "delete from ne_host_cmd where cmd_id in (" + placeholder + ")"
parameters := repo.ConvertIdsSlice(cmdIds)
results, err := datasource.ExecDB("", sql, parameters)
if err != nil {
logger.Errorf("delete err => %v", err)
// Insert 新增信息
func (r NeHostCmd) Insert(param model.NeHostCmd) int64 {
param.UpdateTime = time.Now().UnixMilli()
// 执行插入
if err := db.DB("").Create(&param).Error; err != nil {
logger.Errorf("insert err => %v", err.Error())
return 0
}
return results
return param.ID
}
// Update 修改信息
func (r NeHostCmd) Update(param model.NeHostCmd) int64 {
if param.ID == 0 {
return 0
}
param.UpdateTime = time.Now().UnixMilli()
tx := db.DB("").Model(&model.NeHostCmd{})
// 构建查询条件
tx = tx.Where("id = ?", param.ID)
tx = tx.Omit("id")
// 执行更新
if err := tx.Updates(param).Error; err != nil {
logger.Errorf("update err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// DeleteByIds 批量删除信息
func (r NeHostCmd) DeleteByIds(ids []int64) int64 {
if len(ids) <= 0 {
return 0
}
tx := db.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.NeHostCmd{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// CheckUnique 检查信息是否唯一 返回数据ID
func (r NeHostCmd) CheckUnique(param model.NeHostCmd) int64 {
tx := db.DB("").Model(&model.NeHostCmd{})
// 查询条件拼接
if param.CmdType != "" {
tx = tx.Where("cmd_type = ?", param.CmdType)
}
if param.GroupID != "" {
tx = tx.Where("group_id = ?", param.GroupID)
}
if param.Title != "" {
tx = tx.Where("title = ?", param.Title)
}
// 查询数据
var id int64 = 0
if err := tx.Select("id").Limit(1).Find(&id).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return id
}
return id
}

View File

@@ -3,7 +3,7 @@ package repository
import (
"time"
"be.ems/src/framework/datasource"
"be.ems/src/framework/database/db"
"be.ems/src/framework/logger"
"be.ems/src/modules/network_element/model"
)
@@ -62,7 +62,7 @@ func (r NeInfo) neListSort(arr []model.NeInfo) []model.NeInfo {
// SelectByPage 分页查询集合
func (r NeInfo) SelectByPage(query map[string]string) ([]model.NeInfo, int64) {
tx := datasource.DB("").Model(&model.NeInfo{})
tx := db.DB("").Model(&model.NeInfo{})
// 查询条件拼接
if v, ok := query["neType"]; ok && v != "" {
tx = tx.Where("ne_type = ?", v)
@@ -84,7 +84,7 @@ func (r NeInfo) SelectByPage(query map[string]string) ([]model.NeInfo, int64) {
}
// 查询数据分页
pageNum, pageSize := datasource.PageNumSize(query["pageNum"], query["pageSize"])
pageNum, pageSize := db.PageNumSize(query["pageNum"], query["pageSize"])
tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
err := tx.Order("ne_type asc, ne_id asc").Find(&rows).Error
if err != nil {
@@ -94,23 +94,75 @@ func (r NeInfo) SelectByPage(query map[string]string) ([]model.NeInfo, int64) {
return r.neListSort(rows), total
}
// SelectNeInfoByNeTypeAndNeID 通过ne_type和ne_id查询网元信息
func (r NeInfo) SelectNeInfoByNeTypeAndNeID(neType, neID string) model.NeInfo {
tx := datasource.DB("").Model(&model.NeInfo{})
// 构建查询条件
tx = tx.Where("ne_type = ? and ne_id = ?", neType, neID)
// 查询数据
row := model.NeInfo{}
if err := tx.Limit(1).Find(&row).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return row
// SelectByIds 通过ID查询
func (r NeInfo) SelectByIds(ids []int64) []model.NeInfo {
rows := []model.NeInfo{}
if len(ids) <= 0 {
return rows
}
return row
tx := db.DB("").Model(&model.NeInfo{})
// 构建查询条件
tx = tx.Where("id in ?", ids)
// 查询数据
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// Insert 新增信息
func (r NeInfo) Insert(neInfo model.NeInfo) int64 {
if neInfo.CreateBy != "" {
ms := time.Now().UnixMilli()
neInfo.CreateTime = ms
neInfo.UpdateTime = ms
neInfo.UpdateBy = neInfo.CreateBy
}
tx := db.DB("").Create(&neInfo)
if err := tx.Error; err != nil {
logger.Errorf("CreateInBatches err => %v", err)
}
return neInfo.ID
}
// Update 修改信息
func (r NeInfo) Update(neInfo model.NeInfo) int64 {
if neInfo.ID <= 0 {
return 0
}
if neInfo.UpdateBy != "" {
neInfo.UpdateTime = time.Now().UnixMilli()
}
neInfo.UpdateTime = time.Now().UnixMilli()
tx := db.DB("").Model(&model.NeInfo{})
// 构建查询条件
tx = tx.Where("id = ?", neInfo.ID)
tx = tx.Omit("id", "create_by", "create_time")
// 执行更新
if err := tx.Updates(neInfo).Error; err != nil {
logger.Errorf("update err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// DeleteByIds 批量删除信息
func (r NeInfo) DeleteByIds(ids []int64) int64 {
if len(ids) <= 0 {
return 0
}
tx := db.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.NeInfo{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// SelectList 查询列表
func (r NeInfo) SelectList(neInfo model.NeInfo) []model.NeInfo {
tx := datasource.DB("").Model(&model.NeInfo{})
tx := db.DB("").Model(&model.NeInfo{})
// 构建查询条件
if neInfo.NeType != "" {
tx = tx.Where("ne_type = ?", neInfo.NeType)
@@ -128,26 +180,23 @@ func (r NeInfo) SelectList(neInfo model.NeInfo) []model.NeInfo {
return r.neListSort(rows)
}
// SelectByIds 通过ID查询
func (r NeInfo) SelectByIds(ids []string) []model.NeInfo {
rows := []model.NeInfo{}
if len(ids) <= 0 {
return rows
}
tx := datasource.DB("").Model(&model.NeInfo{})
// SelectNeInfoByNeTypeAndNeID 通过ne_type和ne_id查询网元信息
func (r NeInfo) SelectNeInfoByNeTypeAndNeID(neType, neID string) model.NeInfo {
tx := db.DB("").Model(&model.NeInfo{})
// 构建查询条件
tx = tx.Where("id in ?", ids)
tx = tx.Where("ne_type = ? and ne_id = ?", neType, neID)
// 查询数据
if err := tx.Find(&rows).Error; err != nil {
row := model.NeInfo{}
if err := tx.Limit(1).Find(&row).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
return row
}
return rows
return row
}
// CheckUniqueNeTypeAndNeId 校验同类型下标识是否唯一
func (r NeInfo) CheckUniqueNeTypeAndNeId(neInfo model.NeInfo) string {
tx := datasource.DB("").Model(&model.NeInfo{})
func (r NeInfo) CheckUniqueNeTypeAndNeId(neInfo model.NeInfo) int64 {
tx := db.DB("").Model(&model.NeInfo{})
// 查询条件拼接
if neInfo.NeType != "" {
tx = tx.Where("ne_type = ?", neInfo.NeType)
@@ -156,7 +205,7 @@ func (r NeInfo) CheckUniqueNeTypeAndNeId(neInfo model.NeInfo) string {
tx = tx.Where("ne_id = ?", neInfo.NeType)
}
// 查询数据
id := ""
var id int64 = 0
if err := tx.Limit(1).Select("id").Find(&id).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return id
@@ -164,48 +213,12 @@ func (r NeInfo) CheckUniqueNeTypeAndNeId(neInfo model.NeInfo) string {
return id
}
// Insert 新增信息
func (r *NeInfo) Insert(neInfo model.NeInfo) string {
if neInfo.CreateBy != "" {
ms := time.Now().UnixMilli()
neInfo.CreateTime = ms
neInfo.UpdateTime = ms
neInfo.UpdateBy = neInfo.CreateBy
}
tx := datasource.DefaultDB().Create(&neInfo)
if err := tx.Error; err != nil {
logger.Errorf("CreateInBatches err => %v", err)
}
return neInfo.ID
}
// Update 修改信息
func (r *NeInfo) Update(neInfo model.NeInfo) int64 {
if neInfo.ID == "" {
// UpdateState 修改状态
func (r NeInfo) UpdateState(id int64, status int64) int64 {
if id <= 0 {
return 0
}
if neInfo.UpdateBy != "" {
neInfo.UpdateTime = time.Now().UnixMilli()
}
neInfo.UpdateTime = time.Now().UnixMilli()
tx := datasource.DB("").Model(&model.NeInfo{})
// 构建查询条件
tx = tx.Where("id = ?", neInfo.ID)
tx = tx.Omit("id")
// 执行更新
if err := tx.Updates(neInfo).Error; err != nil {
logger.Errorf("update err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// Update 修改信息
func (r *NeInfo) UpdateState(id, status string) int64 {
if id == "" {
return 0
}
tx := datasource.DB("").Model(&model.NeInfo{})
tx := db.DB("").Model(&model.NeInfo{})
// 构建查询条件
tx = tx.Where("id = ?", id)
// 执行更新
@@ -215,16 +228,3 @@ func (r *NeInfo) UpdateState(id, status string) int64 {
}
return tx.RowsAffected
}
// DeleteByIds 批量删除网元信息
func (r NeInfo) DeleteByIds(ids []string) int64 {
if len(ids) <= 0 {
return 0
}
tx := datasource.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.NeInfo{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error())
return 0
}
return tx.RowsAffected
}

View File

@@ -1,297 +1,148 @@
package repository
import (
"strings"
"time"
"be.ems/src/framework/datasource"
"be.ems/src/framework/database/db"
"be.ems/src/framework/logger"
"be.ems/src/framework/utils/parse"
"be.ems/src/framework/utils/repo"
"be.ems/src/modules/network_element/model"
)
// 实例化数据层 NeLicense 结构体
var NewNeLicense = &NeLicense{
selectSql: `select
id, ne_type, ne_id, activation_request_code, license_path, serial_num, expiry_date, status, remark, create_by, create_time, update_by, update_time
from ne_license`,
resultMap: map[string]string{
"id": "ID",
"ne_type": "NeType",
"ne_id": "NeId",
"activation_request_code": "ActivationRequestCode",
"license_path": "LicensePath",
"serial_num": "SerialNum",
"expiry_date": "ExpiryDate",
"status": "Status",
"remark": "Remark",
"create_by": "CreateBy",
"create_time": "CreateTime",
"update_by": "UpdateBy",
"update_time": "UpdateTime",
},
}
var NewNeLicense = &NeLicense{}
// NeLicense 网元授权激活信息 数据层处理
type NeLicense struct {
// 查询视图对象SQL
selectSql string
// 结果字段与实体映射
resultMap map[string]string
}
type NeLicense struct{}
// convertResultRows 将结果记录转实体结果组
func (r *NeLicense) convertResultRows(rows []map[string]any) []model.NeLicense {
arr := make([]model.NeLicense, 0)
for _, row := range rows {
item := model.NeLicense{}
for key, value := range row {
if keyMapper, ok := r.resultMap[key]; ok {
repo.SetFieldValue(&item, keyMapper, value)
}
}
arr = append(arr, item)
}
return arr
}
// SelectPage 根据条件分页查询字典类型
func (r *NeLicense) SelectPage(query map[string]any) map[string]any {
// SelectByPage 分页查询集合
func (r NeLicense) SelectByPage(query map[string]string) ([]model.NeLicense, int64) {
tx := db.DB("").Model(&model.NeLicense{})
// 查询条件拼接
var conditions []string
var params []any
if v, ok := query["neType"]; ok && v != "" {
conditions = append(conditions, "ne_type = ?")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("ne_type = ?", v)
}
if v, ok := query["neId"]; ok && v != "" {
conditions = append(conditions, "ne_id = ?")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("ne_id = ?", v)
}
if v, ok := query["expiryDate"]; ok && v != "" {
conditions = append(conditions, "expiry_date = ?")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("expiry_date = ?", v)
}
if v, ok := query["serialNum"]; ok && v != "" {
tx = tx.Where("serial_num = ?", v)
}
if v, ok := query["createBy"]; ok && v != "" {
conditions = append(conditions, "create_by like concat(?, '%')")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("create_by like concat(?, '%')", v)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
// 查询结果
var total int64 = 0
rows := []model.NeLicense{}
// 查询数量为0直接返回
if err := tx.Count(&total).Error; err != nil || total <= 0 {
return rows, total
}
result := map[string]any{
"total": 0,
"rows": []model.NeHost{},
}
// 查询数量 长度为0直接返回
totalSql := "select count(1) as 'total' from ne_license"
totalRows, err := datasource.RawDB("", totalSql+whereSql, params)
// 查询数据分页
pageNum, pageSize := db.PageNumSize(query["pageNum"], query["pageSize"])
tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
tx = tx.Order("id desc")
err := tx.Find(&rows).Error
if err != nil {
logger.Errorf("total err => %v", err)
return result
logger.Errorf("query find err => %v", err.Error())
return rows, total
}
total := parse.Number(totalRows[0]["total"])
if total == 0 {
return result
} else {
result["total"] = total
}
// 分页
pageNum, pageSize := repo.PageNumSize(query["pageNum"], query["pageSize"])
pageSql := " limit ?,? "
params = append(params, pageNum*pageSize)
params = append(params, pageSize)
// 查询数据
querySql := r.selectSql + whereSql + pageSql
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
return result
}
// 转换实体
result["rows"] = r.convertResultRows(results)
return result
return rows, total
}
// SelectList 根据实体查询
func (r *NeLicense) SelectList(neLicense model.NeLicense) []model.NeLicense {
// Select 查询集合
func (r NeLicense) Select(param model.NeLicense) []model.NeLicense {
tx := db.DB("").Model(&model.NeLicense{})
// 查询条件拼接
var conditions []string
var params []any
if neLicense.NeType != "" {
conditions = append(conditions, "ne_type = ?")
params = append(params, neLicense.NeType)
if param.NeType != "" {
tx = tx.Where("ne_type = ?", param.NeType)
}
if neLicense.NeId != "" {
conditions = append(conditions, "ne_id = ?")
params = append(params, neLicense.NeId)
if param.NeId != "" {
tx = tx.Where("ne_id = ?", param.NeId)
}
if neLicense.ExpiryDate != "" {
conditions = append(conditions, "expiry_date = ?")
params = append(params, neLicense.ExpiryDate)
if param.ExpiryDate != "" {
tx = tx.Where("expiry_date = ?", param.ExpiryDate)
}
if neLicense.CreateBy != "" {
conditions = append(conditions, "create_by like concat(?, '%')")
params = append(params, neLicense.CreateBy)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
if param.CreateBy != "" {
tx = tx.Where("create_by like concat(?, '%')", param.CreateBy)
}
// 查询数据
querySql := r.selectSql + whereSql + " order by id asc "
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
}
// 转换实体
return r.convertResultRows(results)
}
// SelectByIds 通过ID查询
func (r *NeLicense) SelectByIds(cmdIds []string) []model.NeLicense {
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
querySql := r.selectSql + " where id in (" + placeholder + ")"
parameters := repo.ConvertIdsSlice(cmdIds)
results, err := datasource.RawDB("", querySql, parameters)
if err != nil {
logger.Errorf("query err => %v", err)
return []model.NeLicense{}
}
// 转换实体
return r.convertResultRows(results)
}
// Insert 新增信息
func (r *NeLicense) Insert(neLicense model.NeLicense) string {
// 参数拼接
params := make(map[string]any)
if neLicense.NeType != "" {
params["ne_type"] = neLicense.NeType
}
if neLicense.NeId != "" {
params["ne_id"] = neLicense.NeId
}
if neLicense.ActivationRequestCode != "" {
params["activation_request_code"] = neLicense.ActivationRequestCode
}
if neLicense.LicensePath != "" {
params["license_path"] = neLicense.LicensePath
}
if neLicense.SerialNum != "" {
params["serial_num"] = neLicense.SerialNum
}
if neLicense.ExpiryDate != "" {
params["expiry_date"] = neLicense.ExpiryDate
}
if neLicense.Status != "" {
params["status"] = neLicense.Status
}
if neLicense.Remark != "" {
params["remark"] = neLicense.Remark
}
if neLicense.CreateBy != "" {
params["create_by"] = neLicense.CreateBy
params["create_time"] = time.Now().UnixMilli()
}
// 构建执行语句
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
sql := "insert into ne_license (" + strings.Join(keys, ",") + ")values(" + placeholder + ")"
db := datasource.DefaultDB()
// 开启事务
tx := db.Begin()
// 执行插入
err := tx.Exec(sql, values...).Error
if err != nil {
logger.Errorf("insert row : %v", err.Error())
tx.Rollback()
return ""
}
// 获取生成的自增 ID
var insertedID string
err = tx.Raw("select last_insert_id()").Row().Scan(&insertedID)
if err != nil {
logger.Errorf("insert last id : %v", err.Error())
tx.Rollback()
return ""
}
// 提交事务
tx.Commit()
return insertedID
}
// Update 修改信息
func (r *NeLicense) Update(neLicense model.NeLicense) int64 {
// 参数拼接
params := make(map[string]any)
if neLicense.NeType != "" {
params["ne_type"] = neLicense.NeType
}
if neLicense.NeId != "" {
params["ne_id"] = neLicense.NeId
}
if neLicense.ActivationRequestCode != "" {
params["activation_request_code"] = neLicense.ActivationRequestCode
}
if neLicense.LicensePath != "" {
params["license_path"] = neLicense.LicensePath
}
if neLicense.SerialNum != "" {
params["serial_num"] = neLicense.SerialNum
}
if neLicense.ExpiryDate != "" {
params["expiry_date"] = neLicense.ExpiryDate
}
if neLicense.Status != "" {
params["status"] = neLicense.Status
}
if neLicense.Remark != "" {
params["remark"] = neLicense.Remark
}
if neLicense.UpdateBy != "" {
params["update_by"] = neLicense.UpdateBy
params["update_time"] = time.Now().UnixMilli()
}
// 构建执行语句
keys, values := repo.KeyValueByUpdate(params)
sql := "update ne_license set " + strings.Join(keys, ",") + " where id = ?"
// 执行更新
values = append(values, neLicense.ID)
rows, err := datasource.ExecDB("", sql, values)
if err != nil {
logger.Errorf("update row : %v", err.Error())
return 0
rows := []model.NeLicense{}
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// DeleteByIds 批量删除信息
func (r *NeLicense) DeleteByIds(cmdIds []string) int64 {
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
sql := "delete from ne_license where id in (" + placeholder + ")"
parameters := repo.ConvertIdsSlice(cmdIds)
results, err := datasource.ExecDB("", sql, parameters)
if err != nil {
logger.Errorf("delete err => %v", err)
// SelectByIds 通过ID查询
func (r NeLicense) SelectByIds(ids []int64) []model.NeLicense {
rows := []model.NeLicense{}
if len(ids) <= 0 {
return rows
}
tx := db.DB("").Model(&model.NeLicense{})
// 构建查询条件
tx = tx.Where("id in ?", ids)
// 查询数据
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// Insert 新增信息
func (r NeLicense) Insert(neInfo model.NeLicense) int64 {
if neInfo.CreateBy != "" {
ms := time.Now().UnixMilli()
neInfo.CreateTime = ms
neInfo.UpdateTime = ms
neInfo.UpdateBy = neInfo.CreateBy
}
tx := db.DB("").Create(&neInfo)
if err := tx.Error; err != nil {
logger.Errorf("CreateInBatches err => %v", err)
}
return neInfo.ID
}
// Update 修改信息
func (r NeLicense) Update(param model.NeLicense) int64 {
if param.ID <= 0 {
return 0
}
return results
if param.UpdateBy != "" {
param.UpdateTime = time.Now().UnixMilli()
}
param.UpdateTime = time.Now().UnixMilli()
tx := db.DB("").Model(&model.NeLicense{})
// 构建查询条件
tx = tx.Where("id = ?", param.ID)
tx = tx.Omit("id", "create_by", "create_time")
// 执行更新
if err := tx.Updates(param).Error; err != nil {
logger.Errorf("update err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// DeleteByIds 批量删除信息
func (r NeLicense) DeleteByIds(ids []int64) int64 {
if len(ids) <= 0 {
return 0
}
tx := db.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.NeLicense{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error())
return 0
}
return tx.RowsAffected
}

View File

@@ -1,317 +1,170 @@
package repository
import (
"fmt"
"strings"
"time"
"be.ems/src/framework/datasource"
"be.ems/src/framework/database/db"
"be.ems/src/framework/logger"
"be.ems/src/framework/utils/parse"
"be.ems/src/framework/utils/repo"
"be.ems/src/modules/network_element/model"
)
// 实例化数据层 NeSoftware 结构体
var NewNeSoftware = &NeSoftware{
selectSql: `select
id, ne_type, name, path, version, description, create_by, create_time, update_by, update_time
from ne_software`,
resultMap: map[string]string{
"id": "ID",
"ne_type": "NeType",
"name": "Name",
"path": "Path",
"version": "Version",
"description": "Description",
"create_by": "CreateBy",
"create_time": "CreateTime",
"update_by": "UpdateBy",
"update_time": "UpdateTime",
},
}
var NewNeSoftware = &NeSoftware{}
// NeSoftware 网元软件包信息 数据层处理
type NeSoftware struct {
// 查询视图对象SQL
selectSql string
// 结果字段与实体映射
resultMap map[string]string
}
type NeSoftware struct{}
// convertResultRows 将结果记录转实体结果组
func (r *NeSoftware) convertResultRows(rows []map[string]any) []model.NeSoftware {
arr := make([]model.NeSoftware, 0)
for _, row := range rows {
item := model.NeSoftware{}
for key, value := range row {
if keyMapper, ok := r.resultMap[key]; ok {
repo.SetFieldValue(&item, keyMapper, value)
}
}
arr = append(arr, item)
}
return arr
}
// SelectPage 根据条件分页查询字典类型
func (r *NeSoftware) SelectPage(query map[string]any) map[string]any {
// SelectByPage 分页查询集合
func (r NeSoftware) SelectByPage(query map[string]string) ([]model.NeSoftware, int64) {
tx := db.DB("").Model(&model.NeSoftware{})
// 查询条件拼接
var conditions []string
var params []any
if v, ok := query["neType"]; ok && v != "" {
softwareType := v.(string)
if strings.Contains(softwareType, ",") {
softwareTypeArr := strings.Split(softwareType, ",")
placeholder := repo.KeyPlaceholderByQuery(len(softwareTypeArr))
conditions = append(conditions, "ne_type in ("+placeholder+")")
parameters := repo.ConvertIdsSlice(softwareTypeArr)
params = append(params, parameters...)
if strings.Contains(v, ",") {
softwareTypeArr := strings.Split(v, ",")
tx = tx.Where("ne_type in ?", softwareTypeArr)
} else {
conditions = append(conditions, "ne_type = ?")
params = append(params, strings.Trim(softwareType, " "))
tx = tx.Where("ne_type = ?", v)
}
}
if v, ok := query["name"]; ok && v != "" {
conditions = append(conditions, "name like concat(?, '%')")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("name like concat(?, '%')", v)
}
if v, ok := query["version"]; ok && v != "" {
conditions = append(conditions, "version like concat(?, '%')")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("version like concat(?, '%')", v)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
// 查询结果
var total int64 = 0
rows := []model.NeSoftware{}
// 查询数量为0直接返回
if err := tx.Count(&total).Error; err != nil || total <= 0 {
return rows, total
}
result := map[string]any{
"total": 0,
"rows": []model.NeHost{},
}
// 查询数量 长度为0直接返回
totalSql := "select count(1) as 'total' from ne_software"
totalRows, err := datasource.RawDB("", totalSql+whereSql, params)
// 查询数据分页
pageNum, pageSize := db.PageNumSize(query["pageNum"], query["pageSize"])
tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
tx = tx.Order("id desc")
err := tx.Find(&rows).Error
if err != nil {
logger.Errorf("total err => %v", err)
return result
logger.Errorf("query find err => %v", err.Error())
return rows, total
}
total := parse.Number(totalRows[0]["total"])
if total == 0 {
return result
} else {
result["total"] = total
}
// 分页
pageNum, pageSize := repo.PageNumSize(query["pageNum"], query["pageSize"])
pageSql := " order by id desc limit ?,? "
params = append(params, pageNum*pageSize)
params = append(params, pageSize)
// 查询数据
querySql := r.selectSql + whereSql + pageSql
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
return result
}
// 转换实体
result["rows"] = r.convertResultRows(results)
return result
return rows, total
}
// SelectList 根据实体查询
func (r *NeSoftware) SelectList(neSoftware model.NeSoftware) []model.NeSoftware {
// Select 查询集合
func (r NeSoftware) Select(param model.NeSoftware) []model.NeSoftware {
tx := db.DB("").Model(&model.NeSoftware{})
// 查询条件拼接
var conditions []string
var params []any
if neSoftware.NeType != "" {
conditions = append(conditions, "ne_type = ?")
params = append(params, neSoftware.NeType)
if param.NeType != "" {
tx = tx.Where("ne_type = ?", param.NeType)
}
if neSoftware.Path != "" {
conditions = append(conditions, "path = ?")
params = append(params, neSoftware.Path)
if param.Path != "" {
tx = tx.Where("path = ?", param.Path)
}
if neSoftware.Version != "" {
conditions = append(conditions, "version = ?")
params = append(params, neSoftware.Version)
if param.Version != "" {
tx = tx.Where("version = ?", param.Version)
}
if neSoftware.Name != "" {
conditions = append(conditions, "name like concat(?, '%')")
params = append(params, neSoftware.Name)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
if param.Name != "" {
tx = tx.Where("name like concat(?, '%')", param.Name)
}
// 查询数据
querySql := r.selectSql + whereSql + " order by id desc "
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
}
// 转换实体
return r.convertResultRows(results)
}
// SelectByIds 通过ID查询
func (r *NeSoftware) SelectByIds(cmdIds []string) []model.NeSoftware {
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
querySql := r.selectSql + " where id in (" + placeholder + ")"
parameters := repo.ConvertIdsSlice(cmdIds)
results, err := datasource.RawDB("", querySql, parameters)
if err != nil {
logger.Errorf("query err => %v", err)
return []model.NeSoftware{}
}
// 转换实体
return r.convertResultRows(results)
}
// CheckUniqueTypeAndNameAndVersion 校验网元类型和文件名版本是否唯一
func (r *NeSoftware) CheckUniqueTypeAndNameAndVersion(neSoftware model.NeSoftware) string {
// 查询条件拼接
var conditions []string
var params []any
if neSoftware.NeType != "" {
conditions = append(conditions, "ne_type = ?")
params = append(params, neSoftware.NeType)
}
if neSoftware.Version != "" {
conditions = append(conditions, "version = ?")
params = append(params, neSoftware.Version)
}
if neSoftware.Name != "" {
conditions = append(conditions, "name = ?")
params = append(params, neSoftware.Name)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
} else {
return ""
}
// 查询数据
querySql := "select id as 'str' from ne_software " + whereSql + " limit 1"
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err %v", err)
return ""
}
if len(results) > 0 {
return fmt.Sprint(results[0]["str"])
}
return ""
}
// Insert 新增信息
func (r *NeSoftware) Insert(neSoftware model.NeSoftware) string {
// 参数拼接
params := make(map[string]any)
if neSoftware.NeType != "" {
params["ne_type"] = neSoftware.NeType
}
if neSoftware.Name != "" {
params["name"] = neSoftware.Name
}
if neSoftware.Path != "" {
params["path"] = neSoftware.Path
}
if neSoftware.Version != "" {
params["version"] = neSoftware.Version
}
params["description"] = neSoftware.Description
if neSoftware.CreateBy != "" {
params["create_by"] = neSoftware.CreateBy
params["create_time"] = time.Now().UnixMilli()
}
// 构建执行语句
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
sql := "insert into ne_software (" + strings.Join(keys, ",") + ")values(" + placeholder + ")"
db := datasource.DefaultDB()
// 开启事务
tx := db.Begin()
// 执行插入
err := tx.Exec(sql, values...).Error
if err != nil {
logger.Errorf("insert row : %v", err.Error())
tx.Rollback()
return ""
}
// 获取生成的自增 ID
var insertedID string
err = tx.Raw("select last_insert_id()").Row().Scan(&insertedID)
if err != nil {
logger.Errorf("insert last id : %v", err.Error())
tx.Rollback()
return ""
}
// 提交事务
tx.Commit()
return insertedID
}
// Update 修改信息
func (r *NeSoftware) Update(neSoftware model.NeSoftware) int64 {
// 参数拼接
params := make(map[string]any)
if neSoftware.NeType != "" {
params["ne_type"] = neSoftware.NeType
}
if neSoftware.Name != "" {
params["name"] = neSoftware.Name
}
if neSoftware.Path != "" {
params["path"] = neSoftware.Path
}
if neSoftware.Version != "" {
params["version"] = neSoftware.Version
}
params["description"] = neSoftware.Description
if neSoftware.UpdateBy != "" {
params["update_by"] = neSoftware.UpdateBy
params["update_time"] = time.Now().UnixMilli()
}
// 构建执行语句
keys, values := repo.KeyValueByUpdate(params)
sql := "update ne_software set " + strings.Join(keys, ",") + " where id = ?"
// 执行更新
values = append(values, neSoftware.ID)
rows, err := datasource.ExecDB("", sql, values)
if err != nil {
logger.Errorf("update row : %v", err.Error())
return 0
rows := []model.NeSoftware{}
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// DeleteByIds 批量删除信息
func (r *NeSoftware) DeleteByIds(cmdIds []string) int64 {
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
sql := "delete from ne_software where id in (" + placeholder + ")"
parameters := repo.ConvertIdsSlice(cmdIds)
results, err := datasource.ExecDB("", sql, parameters)
if err != nil {
logger.Errorf("delete err => %v", err)
// SelectByIds 通过ID查询
func (r NeSoftware) SelectByIds(ids []int64) []model.NeSoftware {
rows := []model.NeSoftware{}
if len(ids) <= 0 {
return rows
}
tx := db.DB("").Model(&model.NeSoftware{})
// 构建查询条件
tx = tx.Where("id in ?", ids)
// 查询数据
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// Insert 新增信息
func (r NeSoftware) Insert(param model.NeSoftware) int64 {
if param.CreateBy != "" {
ms := time.Now().UnixMilli()
param.CreateTime = ms
param.UpdateTime = ms
param.UpdateBy = param.CreateBy
}
tx := db.DB("").Create(&param)
if err := tx.Error; err != nil {
logger.Errorf("CreateInBatches err => %v", err)
}
return param.ID
}
// Update 修改信息
func (r NeSoftware) Update(param model.NeSoftware) int64 {
if param.ID <= 0 {
return 0
}
return results
if param.UpdateBy != "" {
param.UpdateTime = time.Now().UnixMilli()
}
param.UpdateTime = time.Now().UnixMilli()
tx := db.DB("").Model(&model.NeSoftware{})
// 构建查询条件
tx = tx.Where("id = ?", param.ID)
tx = tx.Omit("id", "create_by", "create_time")
// 执行更新
if err := tx.Updates(param).Error; err != nil {
logger.Errorf("update err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// DeleteByIds 批量删除信息
func (r NeSoftware) DeleteByIds(ids []int64) int64 {
if len(ids) <= 0 {
return 0
}
tx := db.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.NeSoftware{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// CheckUnique 检查信息是否唯一 返回数据ID
func (r NeSoftware) CheckUnique(param model.NeSoftware) int64 {
tx := db.DB("").Model(&model.NeSoftware{})
// 查询条件拼接
if param.NeType != "" {
tx = tx.Where("ne_type = ?", param.NeType)
}
if param.Path != "" {
tx = tx.Where("path = ?", param.Path)
}
if param.Version != "" {
tx = tx.Where("version = ?", param.Version)
}
// 查询数据
var id int64 = 0
if err := tx.Select("id").Limit(1).Find(&id).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return id
}
return id
}

View File

@@ -1,329 +1,148 @@
package repository
import (
"strings"
"time"
"be.ems/src/framework/datasource"
"be.ems/src/framework/database/db"
"be.ems/src/framework/logger"
"be.ems/src/framework/utils/parse"
"be.ems/src/framework/utils/repo"
"be.ems/src/modules/network_element/model"
)
// 实例化数据层 NeVersion 结构体
var NewNeVersion = &NeVersion{
selectSql: `select
id, ne_type, ne_id, name, version, path, pre_name, pre_version, pre_path, new_name, new_version, new_path, status, create_by, create_time, update_by, update_time
from ne_version`,
resultMap: map[string]string{
"id": "ID",
"ne_type": "NeType",
"ne_id": "NeId",
"name": "name",
"version": "Version",
"path": "Path",
"pre_name": "preName",
"pre_version": "PreVersion",
"pre_path": "PrePath",
"new_name": "NewName",
"new_version": "NewVersion",
"new_path": "NewPath",
"status": "Status",
"create_by": "CreateBy",
"create_time": "CreateTime",
"update_by": "UpdateBy",
"update_time": "UpdateTime",
},
}
var NewNeVersion = &NeVersion{}
// NeVersion 网元版本信息 数据层处理
type NeVersion struct {
// 查询视图对象SQL
selectSql string
// 结果字段与实体映射
resultMap map[string]string
}
type NeVersion struct{}
// convertResultRows 将结果记录转实体结果组
func (r *NeVersion) convertResultRows(rows []map[string]any) []model.NeVersion {
arr := make([]model.NeVersion, 0)
for _, row := range rows {
item := model.NeVersion{}
for key, value := range row {
if keyMapper, ok := r.resultMap[key]; ok {
repo.SetFieldValue(&item, keyMapper, value)
}
}
arr = append(arr, item)
}
return arr
}
// SelectPage 根据条件分页查询字典类型
func (r *NeVersion) SelectPage(query map[string]any) map[string]any {
// SelectByPage 分页查询集合
func (r NeVersion) SelectByPage(query map[string]string) ([]model.NeVersion, int64) {
tx := db.DB("").Model(&model.NeVersion{})
// 查询条件拼接
var conditions []string
var params []any
if v, ok := query["neType"]; ok && v != "" {
conditions = append(conditions, "ne_type = ?")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("ne_type = ?", v)
}
if v, ok := query["neId"]; ok && v != "" {
conditions = append(conditions, "ne_id = ?")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("ne_id = ?", v)
}
if v, ok := query["version"]; ok && v != "" {
conditions = append(conditions, "version like concat(?, '%')")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("version like concat(?, '%')", v)
}
if v, ok := query["path"]; ok && v != "" {
conditions = append(conditions, "path like concat(?, '%')")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("path like concat(?, '%')", v)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
// 查询结果
var total int64 = 0
rows := []model.NeVersion{}
// 查询数量为0直接返回
if err := tx.Count(&total).Error; err != nil || total <= 0 {
return rows, total
}
result := map[string]any{
"total": 0,
"rows": []model.NeHost{},
}
// 查询数量 长度为0直接返回
totalSql := "select count(1) as 'total' from ne_version"
totalRows, err := datasource.RawDB("", totalSql+whereSql, params)
// 查询数据分页
pageNum, pageSize := db.PageNumSize(query["pageNum"], query["pageSize"])
tx = tx.Limit(pageSize).Offset(pageSize * pageNum)
tx = tx.Order("update_time desc")
err := tx.Find(&rows).Error
if err != nil {
logger.Errorf("total err => %v", err)
return result
logger.Errorf("query find err => %v", err.Error())
return rows, total
}
total := parse.Number(totalRows[0]["total"])
if total == 0 {
return result
} else {
result["total"] = total
}
// 分页
pageNum, pageSize := repo.PageNumSize(query["pageNum"], query["pageSize"])
pageSql := " order by update_time desc limit ?,? "
params = append(params, pageNum*pageSize)
params = append(params, pageSize)
// 查询数据
querySql := r.selectSql + whereSql + pageSql
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
return result
}
// 转换实体
result["rows"] = r.convertResultRows(results)
return result
return rows, total
}
// SelectList 根据实体查询
func (r *NeVersion) SelectList(neVersion model.NeVersion) []model.NeVersion {
// Select 查询集合
func (r NeVersion) Select(param model.NeVersion) []model.NeVersion {
tx := db.DB("").Model(&model.NeSoftware{})
// 查询条件拼接
var conditions []string
var params []any
if neVersion.NeType != "" {
conditions = append(conditions, "ne_type = ?")
params = append(params, neVersion.NeType)
if param.NeType != "" {
tx = tx.Where("ne_type = ?", param.NeType)
}
if neVersion.NeId != "" {
conditions = append(conditions, "ne_id = ?")
params = append(params, neVersion.NeId)
if param.NeId != "" {
tx = tx.Where("ne_id = ?", param.NeId)
}
if neVersion.Version != "" {
conditions = append(conditions, "version like concat(?, '%')")
params = append(params, neVersion.Version)
if param.Version != "" {
tx = tx.Where("version like concat(?, '%')", param.Version)
}
if neVersion.Path != "" {
conditions = append(conditions, "path like concat(?, '%')")
params = append(params, neVersion.Path)
if param.Path != "" {
tx = tx.Where("path like concat(?, '%')", param.Path)
}
if neVersion.Status != "" {
conditions = append(conditions, "status = ?")
params = append(params, neVersion.Status)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
if param.Status != "" {
tx = tx.Where("status = ?", param.Status)
}
// 查询数据
querySql := r.selectSql + whereSql + " order by id asc "
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
}
// 转换实体
return r.convertResultRows(results)
}
// SelectByIds 通过ID查询
func (r *NeVersion) SelectByIds(cmdIds []string) []model.NeVersion {
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
querySql := r.selectSql + " where id in (" + placeholder + ")"
parameters := repo.ConvertIdsSlice(cmdIds)
results, err := datasource.RawDB("", querySql, parameters)
if err != nil {
logger.Errorf("query err => %v", err)
return []model.NeVersion{}
}
// 转换实体
return r.convertResultRows(results)
}
// Insert 新增信息
func (r *NeVersion) Insert(neVersion model.NeVersion) string {
// 参数拼接
params := make(map[string]any)
if neVersion.NeType != "" {
params["ne_type"] = neVersion.NeType
}
if neVersion.NeId != "" {
params["ne_id"] = neVersion.NeId
}
if neVersion.Name != "" {
params["name"] = neVersion.Name
}
if neVersion.Version != "" {
params["version"] = neVersion.Version
}
if neVersion.Path != "" {
params["path"] = neVersion.Path
}
if neVersion.PreName != "" {
params["pre_name"] = neVersion.PreName
}
if neVersion.PreVersion != "" {
params["pre_version"] = neVersion.PreVersion
}
if neVersion.PrePath != "" {
params["pre_path"] = neVersion.PrePath
}
if neVersion.NewName != "" {
params["new_name"] = neVersion.NewName
}
if neVersion.NewVersion != "" {
params["new_version"] = neVersion.NewVersion
}
if neVersion.NewPath != "" {
params["new_path"] = neVersion.NewPath
}
if neVersion.Status != "" {
params["status"] = neVersion.Status
}
if neVersion.CreateBy != "" {
params["create_by"] = neVersion.CreateBy
params["create_time"] = time.Now().UnixMilli()
}
// 构建执行语句
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
sql := "insert into ne_version (" + strings.Join(keys, ",") + ")values(" + placeholder + ")"
db := datasource.DefaultDB()
// 开启事务
tx := db.Begin()
// 执行插入
err := tx.Exec(sql, values...).Error
if err != nil {
logger.Errorf("insert row : %v", err.Error())
tx.Rollback()
return ""
}
// 获取生成的自增 ID
var insertedID string
err = tx.Raw("select last_insert_id()").Row().Scan(&insertedID)
if err != nil {
logger.Errorf("insert last id : %v", err.Error())
tx.Rollback()
return ""
}
// 提交事务
tx.Commit()
return insertedID
}
// Update 修改信息
func (r *NeVersion) Update(neVersion model.NeVersion) int64 {
// 参数拼接
params := make(map[string]any)
if neVersion.NeType != "" {
params["ne_type"] = neVersion.NeType
}
if neVersion.NeId != "" {
params["ne_id"] = neVersion.NeId
}
if neVersion.Name != "" {
params["name"] = neVersion.Name
}
if neVersion.Version != "" {
params["version"] = neVersion.Version
}
if neVersion.Path != "" {
params["path"] = neVersion.Path
}
if neVersion.PreName != "" {
params["pre_name"] = neVersion.PreName
}
if neVersion.PreVersion != "" {
params["pre_version"] = neVersion.PreVersion
}
if neVersion.PrePath != "" {
params["pre_path"] = neVersion.PrePath
}
if neVersion.NewName != "" {
params["new_name"] = neVersion.NewName
}
if neVersion.NewVersion != "" {
params["new_version"] = neVersion.NewVersion
}
if neVersion.NewPath != "" {
params["new_path"] = neVersion.NewPath
}
if neVersion.Status != "" {
params["status"] = neVersion.Status
}
if neVersion.UpdateBy != "" {
params["update_by"] = neVersion.UpdateBy
params["update_time"] = time.Now().UnixMilli()
}
// 构建执行语句
keys, values := repo.KeyValueByUpdate(params)
sql := "update ne_version set " + strings.Join(keys, ",") + " where id = ?"
// 执行更新
values = append(values, neVersion.ID)
rows, err := datasource.ExecDB("", sql, values)
if err != nil {
logger.Errorf("update row : %v", err.Error())
return 0
rows := []model.NeVersion{}
if err := tx.Order("id asc").Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// DeleteByIds 批量删除信息
func (r *NeVersion) DeleteByIds(cmdIds []string) int64 {
placeholder := repo.KeyPlaceholderByQuery(len(cmdIds))
sql := "delete from ne_version where id in (" + placeholder + ")"
parameters := repo.ConvertIdsSlice(cmdIds)
results, err := datasource.ExecDB("", sql, parameters)
if err != nil {
logger.Errorf("delete err => %v", err)
// SelectByIds 通过ID查询
func (r NeVersion) SelectByIds(ids []int64) []model.NeVersion {
rows := []model.NeVersion{}
if len(ids) <= 0 {
return rows
}
tx := db.DB("").Model(&model.NeVersion{})
// 构建查询条件
tx = tx.Where("id in ?", ids)
// 查询数据
if err := tx.Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
return rows
}
// Insert 新增信息
func (r NeVersion) Insert(param model.NeVersion) int64 {
if param.CreateBy != "" {
ms := time.Now().UnixMilli()
param.CreateTime = ms
param.UpdateTime = ms
param.UpdateBy = param.CreateBy
}
tx := db.DB("").Create(&param)
if err := tx.Error; err != nil {
logger.Errorf("CreateInBatches err => %v", err)
}
return param.ID
}
// Update 修改信息
func (r NeVersion) Update(param model.NeVersion) int64 {
if param.ID <= 0 {
return 0
}
return results
if param.UpdateBy != "" {
param.UpdateTime = time.Now().UnixMilli()
}
param.UpdateTime = time.Now().UnixMilli()
tx := db.DB("").Model(&model.NeVersion{})
// 构建查询条件
tx = tx.Where("id = ?", param.ID)
tx = tx.Omit("id", "create_by", "create_time")
// 执行更新
if err := tx.Updates(param).Error; err != nil {
logger.Errorf("update err => %v", err.Error())
return 0
}
return tx.RowsAffected
}
// DeleteByIds 批量删除信息
func (r NeVersion) DeleteByIds(ids []int64) int64 {
if len(ids) <= 0 {
return 0
}
tx := db.DB("").Where("id in ?", ids)
if err := tx.Delete(&model.NeVersion{}).Error; err != nil {
logger.Errorf("delete err => %v", err.Error())
return 0
}
return tx.RowsAffected
}

View File

@@ -5,8 +5,8 @@ import (
"fmt"
"strings"
"be.ems/src/framework/constants/cachekey"
"be.ems/src/framework/redis"
"be.ems/src/framework/constants"
"be.ems/src/framework/database/redis"
"be.ems/src/modules/network_element/model"
"be.ems/src/modules/network_element/repository"
)
@@ -25,7 +25,7 @@ type NeConfig struct {
func (r *NeConfig) RefreshByNeTypeAndNeID(neType string) []model.NeConfig {
// 多个
if neType == "" || neType == "*" {
neConfigList := r.neConfigRepository.SelectList(model.NeConfig{})
neConfigList := r.neConfigRepository.Select(model.NeConfig{})
if len(neConfigList) > 0 {
neConfigGroup := map[string][]model.NeConfig{}
for _, v := range neConfigList {
@@ -36,7 +36,7 @@ func (r *NeConfig) RefreshByNeTypeAndNeID(neType string) []model.NeConfig {
}
}
for k, v := range neConfigGroup {
key := fmt.Sprintf("%sNeConfig:%s", cachekey.NE_DATA_KEY, strings.ToUpper(k))
key := fmt.Sprintf("%s:NeConfig:%s", constants.CACHE_NE_DATA, strings.ToUpper(k))
redis.Del("", key)
if len(v) > 0 {
for i, item := range v {
@@ -53,9 +53,9 @@ func (r *NeConfig) RefreshByNeTypeAndNeID(neType string) []model.NeConfig {
return neConfigList
}
// 单个
key := fmt.Sprintf("%sNeConfig:%s", cachekey.NE_DATA_KEY, strings.ToUpper(neType))
key := fmt.Sprintf("%s:NeConfig:%s", constants.CACHE_NE_DATA, strings.ToUpper(neType))
redis.Del("", key)
neConfigList := r.neConfigRepository.SelectList(model.NeConfig{
neConfigList := r.neConfigRepository.Select(model.NeConfig{
NeType: neType,
})
if len(neConfigList) > 0 {
@@ -73,22 +73,21 @@ func (r *NeConfig) RefreshByNeTypeAndNeID(neType string) []model.NeConfig {
// ClearNeCacheByNeType 清除网元类型参数配置缓存
func (r *NeConfig) ClearNeCacheByNeType(neType string) bool {
key := fmt.Sprintf("%sNeConfig:%s", cachekey.NE_DATA_KEY, neType)
key := fmt.Sprintf("%s:NeConfig:%s", constants.CACHE_NE_DATA, neType)
if neType == "*" {
key = fmt.Sprintf("%sNeConfig:*", cachekey.NE_DATA_KEY)
key = fmt.Sprintf("%s:NeConfig:*", constants.CACHE_NE_DATA)
}
keys, err := redis.GetKeys("", key)
if err != nil {
return false
}
delOk, _ := redis.DelKeys("", keys)
return delOk
return redis.DelKeys("", keys) == nil
}
// SelectNeConfigByNeType 查询网元类型参数配置
func (r *NeConfig) SelectNeConfigByNeType(neType string) []model.NeConfig {
// FindByNeType 查询网元类型参数配置
func (r *NeConfig) FindByNeType(neType string) []model.NeConfig {
var neConfigList []model.NeConfig
key := fmt.Sprintf("%sNeConfig:%s", cachekey.NE_DATA_KEY, strings.ToUpper(neType))
key := fmt.Sprintf("%s:NeConfig:%s", constants.CACHE_NE_DATA, strings.ToUpper(neType))
jsonStr, _ := redis.Get("", key)
if len(jsonStr) > 7 {
err := json.Unmarshal([]byte(jsonStr), &neConfigList)
@@ -101,9 +100,9 @@ func (r *NeConfig) SelectNeConfigByNeType(neType string) []model.NeConfig {
return neConfigList
}
// SelectNeConfigByNeTypeAndParamName 查询网元类型参数配置By参数名
func (r *NeConfig) SelectNeConfigByNeTypeAndParamName(neType, paramName string) model.NeConfig {
neConfigList := r.SelectNeConfigByNeType(neType)
// FindByNeTypeAndParamName 查询网元类型参数配置By参数名
func (r *NeConfig) FindByNeTypeAndParamName(neType, paramName string) model.NeConfig {
neConfigList := r.FindByNeType(neType)
var neConfig model.NeConfig
for _, v := range neConfigList {
if v.ParamName == paramName {
@@ -114,22 +113,22 @@ func (r *NeConfig) SelectNeConfigByNeTypeAndParamName(neType, paramName string)
return neConfig
}
// SelectNeHostPage 分页查询列表数据
func (r *NeConfig) SelectPage(query map[string]string) ([]model.NeConfig, int64) {
// FindByPage 分页查询列表数据
func (r *NeConfig) FindByPage(query map[string]string) ([]model.NeConfig, int64) {
return r.neConfigRepository.SelectByPage(query)
}
// SelectConfigList 查询列表
func (r *NeConfig) SelectList(param model.NeConfig) []model.NeConfig {
return r.neConfigRepository.SelectList(param)
// Find 查询列表
func (r *NeConfig) Find(param model.NeConfig) []model.NeConfig {
return r.neConfigRepository.Select(param)
}
// SelectByIds 通过ID查询
func (r *NeConfig) SelectById(id string) model.NeConfig {
if id == "" {
// FindById 通过ID查询
func (r *NeConfig) FindById(id int64) model.NeConfig {
if id <= 0 {
return model.NeConfig{}
}
neHosts := r.neConfigRepository.SelectByIds([]string{id})
neHosts := r.neConfigRepository.SelectByIds([]int64{id})
if len(neHosts) > 0 {
return neHosts[0]
}
@@ -137,7 +136,7 @@ func (r *NeConfig) SelectById(id string) model.NeConfig {
}
// Insert 新增信息
func (r *NeConfig) Insert(param model.NeConfig) string {
func (r *NeConfig) Insert(param model.NeConfig) int64 {
return r.neConfigRepository.Insert(param)
}
@@ -147,7 +146,7 @@ func (r *NeConfig) Update(param model.NeConfig) int64 {
}
// DeleteByIds 批量删除信息
func (r *NeConfig) DeleteByIds(ids []string) (int64, error) {
func (r *NeConfig) DeleteByIds(ids []int64) (int64, error) {
// 检查是否存在
data := r.neConfigRepository.SelectByIds(ids)
if len(data) <= 0 {

View File

@@ -23,22 +23,17 @@ type NeConfigBackup struct {
neConfigBackupRepository *repository.NeConfigBackup // 网元配置文件备份记录
}
// SelectNeHostPage 分页查询列表数据
func (r *NeConfigBackup) SelectPage(query map[string]any) map[string]any {
return r.neConfigBackupRepository.SelectPage(query)
// FindByPage 分页查询列表数据
func (s NeConfigBackup) FindByPage(query map[string]string) ([]model.NeConfigBackup, int64) {
return s.neConfigBackupRepository.SelectByPage(query)
}
// SelectConfigList 查询列表
func (r *NeConfigBackup) SelectList(item model.NeConfigBackup) []model.NeConfigBackup {
return r.neConfigBackupRepository.SelectList(item)
}
// SelectByIds 通过ID查询
func (r *NeConfigBackup) SelectById(id string) model.NeConfigBackup {
if id == "" {
// FindById 通过ID查询
func (s NeConfigBackup) FindById(id int64) model.NeConfigBackup {
if id <= 0 {
return model.NeConfigBackup{}
}
arr := r.neConfigBackupRepository.SelectByIds([]string{id})
arr := s.neConfigBackupRepository.SelectByIds([]int64{id})
if len(arr) > 0 {
return arr[0]
}
@@ -46,33 +41,33 @@ func (r *NeConfigBackup) SelectById(id string) model.NeConfigBackup {
}
// Insert 新增信息
func (r *NeConfigBackup) Insert(item model.NeConfigBackup) string {
return r.neConfigBackupRepository.Insert(item)
func (s NeConfigBackup) Insert(item model.NeConfigBackup) int64 {
return s.neConfigBackupRepository.Insert(item)
}
// Update 修改信息
func (r *NeConfigBackup) Update(item model.NeConfigBackup) int64 {
return r.neConfigBackupRepository.Update(item)
func (s NeConfigBackup) Update(item model.NeConfigBackup) int64 {
return s.neConfigBackupRepository.Update(item)
}
// DeleteByIds 批量删除信息
func (r *NeConfigBackup) DeleteByIds(ids []string) (int64, error) {
func (s NeConfigBackup) DeleteByIds(ids []int64) (int64, error) {
// 检查是否存在
data := r.neConfigBackupRepository.SelectByIds(ids)
data := s.neConfigBackupRepository.SelectByIds(ids)
if len(data) <= 0 {
return 0, fmt.Errorf("neConfigBackup.noData")
}
if len(data) == len(ids) {
rows := r.neConfigBackupRepository.DeleteByIds(ids)
rows := s.neConfigBackupRepository.DeleteByIds(ids)
return rows, nil
}
// 删除信息失败!
return 0, fmt.Errorf("delete fail")
}
// NeConfigLocalToNe 网元配置文件复制到网元端覆盖
func (r *NeConfigBackup) NeConfigLocalToNe(neInfo model.NeInfo, localFile string) error {
// FileLocalToNe 网元配置文件复制到网元端覆盖
func (s NeConfigBackup) FileLocalToNe(neInfo model.NeInfo, localFile string) error {
neTypeLower := strings.ToLower(neInfo.NeType)
// 网管本地路径
omcPath := "/usr/local/etc/omc/ne_config"
@@ -108,7 +103,7 @@ func (r *NeConfigBackup) NeConfigLocalToNe(neInfo model.NeInfo, localFile string
// 配置复制到网元内
if neTypeLower == "ims" {
// ims目录
imsDirArr := [...]string{"bgcf", "icscf", "ismc", "mmtel", "mrf", "oam_manager.yaml", "pcscf", "scscf", "vars.cfg", "zlog"}
imsDirArr := [...]string{"bgcf", "icscf", "ismc", "mmtel", "mrf", "oam_manages.yaml", "pcscf", "scscf", "vars.cfg", "zlog"}
for _, v := range imsDirArr {
sshClient.RunCMD(fmt.Sprintf("sudo mkdir -p /usr/local/etc/ims && sudo cp -rf %s/ims/%s /usr/local/etc/ims/%v && sudo chmod 755 -R /usr/local/etc/ims/%s", neDirTemp, v, v, v))
}
@@ -137,8 +132,8 @@ func (r *NeConfigBackup) NeConfigLocalToNe(neInfo model.NeInfo, localFile string
return nil
}
// NeConfigNeToLocal 网元备份文件网元端复制到本地
func (r *NeConfigBackup) NeConfigNeToLocal(neInfo model.NeInfo) (string, error) {
// FileNeToLocal 网元备份文件网元端复制到本地
func (s NeConfigBackup) FileNeToLocal(neInfo model.NeInfo) (string, error) {
// 网元主机的SSH客户端
sshClient, err := NewNeInfo.NeRunSSHClient(neInfo.NeType, neInfo.NeId)
if err != nil {
@@ -166,7 +161,7 @@ func (r *NeConfigBackup) NeConfigNeToLocal(neInfo model.NeInfo) (string, error)
if neTypeLower == "ims" {
// ims目录
sshClient.RunCMD(fmt.Sprintf("mkdir -p %s/ims", neDirTemp))
imsDirArr := [...]string{"bgcf", "icscf", "ismc", "mmtel", "mrf", "oam_manager.yaml", "pcscf", "scscf", "vars.cfg", "zlog"}
imsDirArr := [...]string{"bgcf", "icscf", "ismc", "mmtel", "mrf", "oam_manages.yaml", "pcscf", "scscf", "vars.cfg", "zlog"}
for _, v := range imsDirArr {
sshClient.RunCMD(fmt.Sprintf("sudo cp -rf /usr/local/etc/ims/%s %s/ims", v, neDirTemp))
}

View File

@@ -20,23 +20,18 @@ type NeHost struct {
neHostRepository *repository.NeHost // 网元主机连接表
}
// SelectNeHostPage 分页查询列表数据
func (r *NeHost) SelectPage(query map[string]any) map[string]any {
return r.neHostRepository.SelectPage(query)
// FindByPage 分页查询列表数据
func (r NeHost) FindByPage(query map[string]string) ([]model.NeHost, int64) {
return r.neHostRepository.SelectByPage(query)
}
// SelectConfigList 查询列表
func (r *NeHost) SelectList(neHost model.NeHost) []model.NeHost {
return r.neHostRepository.SelectList(neHost)
}
// SelectByIds 通过ID查询
func (r *NeHost) SelectById(hostId string) model.NeHost {
// FindById 通过ID查询
func (r NeHost) FindById(hostId int64) model.NeHost {
neHost := model.NeHost{}
if hostId == "" {
if hostId <= 0 {
return neHost
}
neHosts := r.neHostRepository.SelectByIds([]string{hostId})
neHosts := r.neHostRepository.SelectByIds([]int64{hostId})
if len(neHosts) > 0 {
neHost := neHosts[0]
hostKey := config.Get("aes.hostKey").(string)
@@ -70,11 +65,11 @@ func (r *NeHost) SelectById(hostId string) model.NeHost {
}
// Insert 批量添加
func (r *NeHost) Inserts(neHosts []model.NeHost) int64 {
func (r NeHost) Inserts(neHosts []model.NeHost) int64 {
var num int64 = 0
for _, v := range neHosts {
hostId := r.neHostRepository.Insert(v)
if hostId != "" {
if hostId > 0 {
num += 1
}
}
@@ -82,13 +77,13 @@ func (r *NeHost) Inserts(neHosts []model.NeHost) int64 {
}
// Insert 新增信息
func (r *NeHost) Insert(neHost model.NeHost) string {
func (r NeHost) Insert(neHost model.NeHost) int64 {
hostKey := config.Get("aes.hostKey").(string)
if neHost.Password != "" {
passwordEn, err := crypto.AESEncryptBase64(neHost.Password, hostKey)
if err != nil {
logger.Errorf("insert encrypt: %v", err.Error())
return ""
return 0
}
neHost.Password = passwordEn
}
@@ -96,7 +91,7 @@ func (r *NeHost) Insert(neHost model.NeHost) string {
privateKeyEn, err := crypto.AESEncryptBase64(neHost.PrivateKey, hostKey)
if err != nil {
logger.Errorf("insert encrypt: %v", err.Error())
return ""
return 0
}
neHost.PrivateKey = privateKeyEn
}
@@ -104,7 +99,7 @@ func (r *NeHost) Insert(neHost model.NeHost) string {
passPhraseEn, err := crypto.AESEncryptBase64(neHost.PassPhrase, hostKey)
if err != nil {
logger.Errorf("insert encrypt: %v", err.Error())
return ""
return 0
}
neHost.PassPhrase = passPhraseEn
}
@@ -112,7 +107,7 @@ func (r *NeHost) Insert(neHost model.NeHost) string {
}
// Update 修改信息
func (r *NeHost) Update(neHost model.NeHost) int64 {
func (r NeHost) Update(neHost model.NeHost) int64 {
hostKey := config.Get("aes.hostKey").(string)
if neHost.Password != "" {
passwordEn, err := crypto.AESEncryptBase64(neHost.Password, hostKey)
@@ -142,7 +137,7 @@ func (r *NeHost) Update(neHost model.NeHost) int64 {
}
// DeleteByIds 批量删除网元主机连接信息
func (r *NeHost) DeleteByIds(hostIds []string) (int64, error) {
func (r NeHost) DeleteByIds(hostIds []int64) (int64, error) {
// 检查是否存在
ids := r.neHostRepository.SelectByIds(hostIds)
if len(ids) <= 0 {
@@ -165,8 +160,8 @@ func (r *NeHost) DeleteByIds(hostIds []string) (int64, error) {
}
// CheckUniqueHostTitle 校验分组组和主机名称是否唯一
func (r *NeHost) CheckUniqueHostTitle(groupId, title, hostType, hostId string) bool {
uniqueId := r.neHostRepository.CheckUniqueNeHost(model.NeHost{
func (r NeHost) CheckUniqueHostTitle(groupId, title, hostType string, hostId int64) bool {
uniqueId := r.neHostRepository.CheckUnique(model.NeHost{
HostType: hostType,
GroupID: groupId,
Title: title,
@@ -174,5 +169,5 @@ func (r *NeHost) CheckUniqueHostTitle(groupId, title, hostType, hostId string) b
if uniqueId == hostId {
return true
}
return uniqueId == ""
return uniqueId == 0
}

View File

@@ -17,22 +17,17 @@ type NeHostCmd struct {
neHostCmdRepository *repository.NeHostCmd // 网元主机命令表
}
// SelectNeHostPage 分页查询列表数据
func (r *NeHostCmd) SelectPage(query map[string]any) map[string]any {
return r.neHostCmdRepository.SelectPage(query)
// FindByPage 分页查询列表数据
func (r *NeHostCmd) FindByPage(query map[string]string) ([]model.NeHostCmd, int64) {
return r.neHostCmdRepository.SelectByPage(query)
}
// SelectConfigList 查询列表
func (r *NeHostCmd) SelectList(neHostCmd model.NeHostCmd) []model.NeHostCmd {
return r.neHostCmdRepository.SelectList(neHostCmd)
}
// SelectByIds 通过ID查询
func (r *NeHostCmd) SelectById(cmdId string) model.NeHostCmd {
if cmdId == "" {
// FindById 通过ID查询
func (r *NeHostCmd) FindById(id int64) model.NeHostCmd {
if id <= 0 {
return model.NeHostCmd{}
}
neHosts := r.neHostCmdRepository.SelectByIds([]string{cmdId})
neHosts := r.neHostCmdRepository.SelectByIds([]int64{id})
if len(neHosts) > 0 {
return neHosts[0]
}
@@ -40,7 +35,7 @@ func (r *NeHostCmd) SelectById(cmdId string) model.NeHostCmd {
}
// Insert 新增信息
func (r *NeHostCmd) Insert(neHostCmd model.NeHostCmd) string {
func (r *NeHostCmd) Insert(neHostCmd model.NeHostCmd) int64 {
return r.neHostCmdRepository.Insert(neHostCmd)
}
@@ -50,15 +45,15 @@ func (r *NeHostCmd) Update(neHostCmd model.NeHostCmd) int64 {
}
// DeleteByIds 批量删除信息
func (r *NeHostCmd) DeleteByIds(cmdIds []string) (int64, error) {
func (r *NeHostCmd) DeleteByIds(ids []int64) (int64, error) {
// 检查是否存在
ids := r.neHostCmdRepository.SelectByIds(cmdIds)
if len(ids) <= 0 {
rows := r.neHostCmdRepository.SelectByIds(ids)
if len(rows) <= 0 {
return 0, fmt.Errorf("neHostCmd.noData")
}
if len(ids) == len(cmdIds) {
rows := r.neHostCmdRepository.DeleteByIds(cmdIds)
if len(rows) == len(ids) {
rows := r.neHostCmdRepository.DeleteByIds(ids)
return rows, nil
}
// 删除信息失败!
@@ -66,8 +61,8 @@ func (r *NeHostCmd) DeleteByIds(cmdIds []string) (int64, error) {
}
// CheckUniqueGroupTitle 校验同类型组内是否唯一
func (r *NeHostCmd) CheckUniqueGroupTitle(groupId, title, cmdType, cmdId string) bool {
uniqueId := r.neHostCmdRepository.CheckUniqueGroupTitle(model.NeHostCmd{
func (r *NeHostCmd) CheckUniqueGroupTitle(groupId, title, cmdType string, cmdId int64) bool {
uniqueId := r.neHostCmdRepository.CheckUnique(model.NeHostCmd{
CmdType: cmdType,
GroupID: groupId,
Title: title,
@@ -75,5 +70,5 @@ func (r *NeHostCmd) CheckUniqueGroupTitle(groupId, title, cmdType, cmdId string)
if uniqueId == cmdId {
return true
}
return uniqueId == ""
return uniqueId == 0
}

View File

@@ -8,13 +8,13 @@ import (
"runtime"
"strings"
"be.ems/src/framework/constants/cachekey"
"be.ems/src/framework/constants"
"be.ems/src/framework/database/redis"
"be.ems/src/framework/logger"
"be.ems/src/framework/redis"
"be.ems/src/framework/ssh"
"be.ems/src/framework/telnet"
"be.ems/src/framework/utils/generate"
"be.ems/src/framework/utils/parse"
"be.ems/src/framework/utils/ssh"
neFetchlink "be.ems/src/modules/network_element/fetch_link"
"be.ems/src/modules/network_element/model"
"be.ems/src/modules/network_element/repository"
@@ -23,19 +23,21 @@ import (
// 实例化服务层 NeInfo 结构体
var NewNeInfo = &NeInfo{
neInfoRepository: repository.NewNeInfo,
neHostService: NewNeHost,
Para5GData: map[string]string{},
}
// 网元信息 服务层处理
type NeInfo struct {
neInfoRepository *repository.NeInfo // 网元信息数据信息
neHostService *NeHost // 网元主机连接服务
Para5GData map[string]string
}
// SelectNeInfoByNeTypeAndNeID 通过ne_type和ne_id查询网元信息
func (r *NeInfo) SelectNeInfoByNeTypeAndNeID(neType, neID string) model.NeInfo {
// FindByNeTypeAndNeID 通过ne_type和ne_id查询网元信息
func (r NeInfo) FindByNeTypeAndNeID(neType, neID string) model.NeInfo {
var neInfo model.NeInfo
key := fmt.Sprintf("%s%s:%s", cachekey.NE_KEY, strings.ToUpper(neType), neID)
key := fmt.Sprintf("%s:%s:%s", constants.CACHE_NE_INFO, strings.ToUpper(neType), neID)
jsonStr, _ := redis.Get("", key)
if len(jsonStr) > 7 {
err := json.Unmarshal([]byte(jsonStr), &neInfo)
@@ -44,7 +46,7 @@ func (r *NeInfo) SelectNeInfoByNeTypeAndNeID(neType, neID string) model.NeInfo {
}
} else {
neInfo = r.neInfoRepository.SelectNeInfoByNeTypeAndNeID(neType, neID)
if neInfo.ID != "" && neInfo.NeId == neID {
if neInfo.ID != 0 && neInfo.NeId == neID {
redis.Del("", key)
values, _ := json.Marshal(neInfo)
redis.Set("", key, string(values))
@@ -54,12 +56,12 @@ func (r *NeInfo) SelectNeInfoByNeTypeAndNeID(neType, neID string) model.NeInfo {
}
// RefreshByNeTypeAndNeID 通过ne_type和ne_id刷新redis中的缓存
func (r *NeInfo) RefreshByNeTypeAndNeID(neType, neID string) model.NeInfo {
func (r NeInfo) RefreshByNeTypeAndNeID(neType, neID string) model.NeInfo {
var neInfo model.NeInfo
key := fmt.Sprintf("%s%s:%s", cachekey.NE_KEY, strings.ToUpper(neType), neID)
key := fmt.Sprintf("%s:%s:%s", constants.CACHE_NE_INFO, strings.ToUpper(neType), neID)
redis.Del("", key)
neInfo = r.neInfoRepository.SelectNeInfoByNeTypeAndNeID(neType, neID)
if neInfo.ID != "" && neInfo.NeId == neID {
if neInfo.ID != 0 && neInfo.NeId == neID {
values, _ := json.Marshal(neInfo)
redis.Set("", key, string(values))
}
@@ -67,23 +69,22 @@ func (r *NeInfo) RefreshByNeTypeAndNeID(neType, neID string) model.NeInfo {
}
// ClearNeCacheByNeType 清除网元类型缓存
func (r *NeInfo) ClearNeCacheByNeType(neType string) bool {
key := fmt.Sprintf("%s*", cachekey.NE_KEY)
func (r NeInfo) ClearNeCacheByNeType(neType string) bool {
key := fmt.Sprintf("%s:*", constants.CACHE_NE_INFO)
if neType != "*" {
key = fmt.Sprintf("%s%s*", cachekey.NE_KEY, neType)
key = fmt.Sprintf("%s:%s*", constants.CACHE_NE_INFO, neType)
}
keys, err := redis.GetKeys("", key)
if err != nil {
return false
}
delOk, _ := redis.DelKeys("", keys)
return delOk
return redis.DelKeys("", keys) == nil
}
// SelectNeInfoByNeType 通过ne_type查询网元信息
func (r *NeInfo) SelectNeInfoByNeType(neType string) []model.NeInfo {
// FindByNeType 通过ne_type查询网元信息
func (r NeInfo) FindByNeType(neType string) []model.NeInfo {
neInfo := make([]model.NeInfo, 0)
key := fmt.Sprintf("%s%s:*", cachekey.NE_KEY, strings.ToUpper(neType))
key := fmt.Sprintf("%s:%s:*", constants.CACHE_NE_INFO, strings.ToUpper(neType))
jsonStr, _ := redis.Get("", key)
if len(jsonStr) > 7 {
err := json.Unmarshal([]byte(jsonStr), &neInfo)
@@ -93,7 +94,7 @@ func (r *NeInfo) SelectNeInfoByNeType(neType string) []model.NeInfo {
} else {
neInfo = r.neInfoRepository.SelectList(model.NeInfo{NeType: neType})
for _, v := range neInfo {
key := fmt.Sprintf("%s%s:%s", cachekey.NE_KEY, strings.ToUpper(v.NeType), v.NeId)
key := fmt.Sprintf("%s:%s:%s", constants.CACHE_NE_INFO, strings.ToUpper(v.NeType), v.NeId)
redis.Del("", key)
values, _ := json.Marshal(v)
redis.Set("", key, string(values))
@@ -102,10 +103,10 @@ func (r *NeInfo) SelectNeInfoByNeType(neType string) []model.NeInfo {
return neInfo
}
// SelectNeInfoByRmuid 通过rmUID查询网元信息
func (r *NeInfo) SelectNeInfoByRmuid(rmUid string) model.NeInfo {
// FindByRmuid 通过rmUID查询网元信息
func (r NeInfo) FindByRmuid(rmUid string) model.NeInfo {
var neInfo model.NeInfo
cacheKeys, _ := redis.GetKeys("", cachekey.NE_KEY+"*")
cacheKeys, _ := redis.GetKeys("", constants.CACHE_NE_INFO+":*")
if len(cacheKeys) > 0 {
for _, key := range cacheKeys {
var v model.NeInfo
@@ -119,9 +120,9 @@ func (r *NeInfo) SelectNeInfoByRmuid(rmUid string) model.NeInfo {
}
}
} else {
neInfos := r.SelectList(neInfo, false, false)
neInfos := r.Find(neInfo, false, false)
for _, v := range neInfos {
key := fmt.Sprintf("%s%s:%s", cachekey.NE_KEY, strings.ToUpper(v.NeType), v.NeId)
key := fmt.Sprintf("%s:%s:%s", constants.CACHE_NE_INFO, strings.ToUpper(v.NeType), v.NeId)
redis.Del("", key)
values, _ := json.Marshal(v)
redis.Set("", key, string(values))
@@ -133,10 +134,10 @@ func (r *NeInfo) SelectNeInfoByRmuid(rmUid string) model.NeInfo {
return neInfo
}
// SelectPage 根据条件分页查询
// FindByPage 根据条件分页查询
//
// bandStatus 带状态信息
func (r *NeInfo) SelectPage(query map[string]string, bandStatus bool) ([]model.NeInfo, int64) {
func (r NeInfo) FindByPage(query map[string]string, bandStatus bool) ([]model.NeInfo, int64) {
rows, total := r.neInfoRepository.SelectByPage(query)
// 网元直连读取网元服务状态
@@ -147,11 +148,11 @@ func (r *NeInfo) SelectPage(query map[string]string, bandStatus bool) ([]model.N
return rows, total
}
// SelectList 查询列表
// Find 查询列表
//
// bandStatus 带状态信息
// bandHost 带主机信息
func (r *NeInfo) SelectList(ne model.NeInfo, bandStatus bool, bandHost bool) []model.NeInfo {
func (r NeInfo) Find(ne model.NeInfo, bandStatus bool, bandHost bool) []model.NeInfo {
list := r.neInfoRepository.SelectList(ne)
// 网元直连读取网元服务状态
@@ -168,7 +169,7 @@ func (r *NeInfo) SelectList(ne model.NeInfo, bandStatus bool, bandHost bool) []m
}
// bandNeStatus 网元列表项数据带网元服务状态
func (r *NeInfo) bandNeStatus(arr *[]model.NeInfo) {
func (r NeInfo) bandNeStatus(arr *[]model.NeInfo) {
for i := range *arr {
v := (*arr)[i]
result, err := neFetchlink.NeState(v)
@@ -177,8 +178,8 @@ func (r *NeInfo) bandNeStatus(arr *[]model.NeInfo) {
"online": false,
}
// 网元状态设置为离线
if v.Status != "0" {
v.Status = "0"
if v.Status != 0 {
v.Status = 0
(*arr)[i].Status = v.Status
r.neInfoRepository.UpdateState(v.ID, v.Status)
}
@@ -187,13 +188,13 @@ func (r *NeInfo) bandNeStatus(arr *[]model.NeInfo) {
result["online"] = true
(*arr)[i].ServerState = result
// 网元状态设置为在线
status := "1"
var status int64 = 1
if parse.Boolean(result["standby"]) {
status = "3"
status = 3
}
// 下发网管配置信息给网元
if _, err = neFetchlink.NeConfigOMC(v); err != nil {
status = "2"
status = 2
}
(*arr)[i].Status = status
if v.Status != status {
@@ -203,7 +204,7 @@ func (r *NeInfo) bandNeStatus(arr *[]model.NeInfo) {
}
// bandNeHosts 网元列表项数据带网元主机信息
func (r *NeInfo) bandNeHosts(arr *[]model.NeInfo) {
func (r NeInfo) bandNeHosts(arr *[]model.NeInfo) {
for i := range *arr {
v := (*arr)[i]
if v.HostIDs != "" {
@@ -211,9 +212,10 @@ func (r *NeInfo) bandNeHosts(arr *[]model.NeInfo) {
if len(hostIds) <= 1 {
continue
}
for _, hostId := range hostIds {
neHost := NewNeHost.SelectById(hostId)
if neHost.HostID == "" || neHost.HostID != hostId {
for _, v := range hostIds {
hostId := parse.Number(v)
neHost := r.neHostService.FindById(hostId)
if neHost.ID == 0 || neHost.ID != hostId {
continue
}
(*arr)[i].Hosts = append((*arr)[i].Hosts, neHost)
@@ -222,14 +224,14 @@ func (r *NeInfo) bandNeHosts(arr *[]model.NeInfo) {
}
}
// SelectByIds 通过ID查询
// FindById 通过ID查询
//
// bandHost 带主机信息
func (r *NeInfo) SelectById(infoId string, bandHost bool) model.NeInfo {
if infoId == "" {
func (r NeInfo) FindById(id int64, bandHost bool) model.NeInfo {
if id <= 0 {
return model.NeInfo{}
}
neInfos := r.neInfoRepository.SelectByIds([]string{infoId})
neInfos := r.neInfoRepository.SelectByIds([]int64{id})
if len(neInfos) > 0 {
// 带主机信息
if neInfos[0].HostIDs != "" && bandHost {
@@ -241,7 +243,7 @@ func (r *NeInfo) SelectById(infoId string, bandHost bool) model.NeInfo {
}
// Insert 新增信息
func (r *NeInfo) Insert(neInfo model.NeInfo) string {
func (r NeInfo) Insert(neInfo model.NeInfo) int64 {
// 主机信息新增
if neInfo.Hosts != nil {
uuid := generate.Code(4)
@@ -250,16 +252,16 @@ func (r *NeInfo) Insert(neInfo model.NeInfo) string {
host.Title = neInfo.NeName + "_" + uuid
host.GroupID = "1"
host.CreateBy = neInfo.CreateBy
hostId := NewNeHost.Insert(host)
if hostId != "" {
hostIDs = append(hostIDs, hostId)
hostId := r.neHostService.Insert(host)
if hostId > 0 {
hostIDs = append(hostIDs, fmt.Sprint(hostId))
}
}
neInfo.HostIDs = strings.Join(hostIDs, ",")
}
insertId := r.neInfoRepository.Insert(neInfo)
if insertId != "" {
if insertId > 0 {
// 刷新缓存
r.RefreshByNeTypeAndNeID(neInfo.NeType, neInfo.NeId)
}
@@ -267,16 +269,16 @@ func (r *NeInfo) Insert(neInfo model.NeInfo) string {
}
// Update 修改信息
func (r *NeInfo) Update(neInfo model.NeInfo) int64 {
func (r NeInfo) Update(neInfo model.NeInfo) int64 {
// 主机信息更新
if neInfo.Hosts != nil {
uuid := generate.Code(4)
for _, host := range neInfo.Hosts {
if host.HostID != "" {
if host.ID != 0 {
host.Title = neInfo.NeName + "_" + uuid
host.GroupID = "1"
host.UpdateBy = neInfo.UpdateBy
NewNeHost.Update(host)
r.neHostService.Update(host)
}
}
}
@@ -290,33 +292,38 @@ func (r *NeInfo) Update(neInfo model.NeInfo) int64 {
}
// DeleteByIds 批量删除信息
func (r *NeInfo) DeleteByIds(infoIds []string) (int64, error) {
func (r NeInfo) DeleteByIds(ids []int64) (int64, error) {
// 检查是否存在
infos := r.neInfoRepository.SelectByIds(infoIds)
infos := r.neInfoRepository.SelectByIds(ids)
if len(infos) <= 0 {
return 0, fmt.Errorf("neHostCmd.noData")
}
if len(infos) == len(infoIds) {
if len(infos) == len(ids) {
for _, v := range infos {
// 主机信息删除
if v.HostIDs != "" {
NewNeHost.DeleteByIds(strings.Split(v.HostIDs, ","))
hostIds := make([]int64, 0)
arr := strings.Split(v.HostIDs, ",")
for _, hostId := range arr {
hostIds = append(hostIds, parse.Number(hostId))
}
r.neHostService.DeleteByIds(hostIds)
}
// 删除License
neLicense := NewNeLicense.SelectByNeTypeAndNeID(v.NeType, v.NeId)
neLicense := NewNeLicense.FindByNeTypeAndNeID(v.NeType, v.NeId)
if neLicense.NeId == v.NeId {
NewNeLicense.DeleteByIds([]string{neLicense.ID})
NewNeLicense.DeleteByIds([]int64{neLicense.ID})
}
// 删除Version
neVersion := NewNeVersion.SelectByNeTypeAndNeID(v.NeType, v.NeId)
neVersion := NewNeVersion.FindByNeTypeAndNeID(v.NeType, v.NeId)
if neVersion.NeId == v.NeId {
NewNeVersion.DeleteByIds([]string{neVersion.ID})
NewNeVersion.DeleteByIds([]int64{neVersion.ID})
}
// 缓存信息删除
redis.Del("", fmt.Sprintf("%s%s:%s", cachekey.NE_KEY, v.NeType, v.NeId))
redis.Del("", fmt.Sprintf("%s:%s:%s", constants.CACHE_NE_INFO, v.NeType, v.NeId))
}
rows := r.neInfoRepository.DeleteByIds(infoIds)
rows := r.neInfoRepository.DeleteByIds(ids)
return rows, nil
}
// 删除信息失败!
@@ -324,7 +331,7 @@ func (r *NeInfo) DeleteByIds(infoIds []string) (int64, error) {
}
// CheckUniqueNeTypeAndNeId 校验同类型下标识是否唯一
func (r *NeInfo) CheckUniqueNeTypeAndNeId(neType, neId, id string) bool {
func (r NeInfo) CheckUniqueNeTypeAndNeId(neType, neId string, id int64) bool {
uniqueId := r.neInfoRepository.CheckUniqueNeTypeAndNeId(model.NeInfo{
NeType: neType,
NeId: neId,
@@ -332,12 +339,12 @@ func (r *NeInfo) CheckUniqueNeTypeAndNeId(neType, neId, id string) bool {
if uniqueId == id {
return true
}
return uniqueId == ""
return uniqueId == 0
}
// NeRunSSHClient 网元主机的SSH客户端-为创建相关连接,注意结束后 Close()
func (r *NeInfo) NeRunSSHClient(neType, neId string) (*ssh.ConnSSH, error) {
neInfo := r.SelectNeInfoByNeTypeAndNeID(neType, neId)
func (r NeInfo) NeRunSSHClient(neType, neId string) (*ssh.ConnSSH, error) {
neInfo := r.FindByNeTypeAndNeID(neType, neId)
if neInfo.NeId != neId {
logger.Errorf("NeRunSSHClient NeType:%s NeID:%s not found", neType, neId)
return nil, fmt.Errorf("neinfo not found")
@@ -352,9 +359,9 @@ func (r *NeInfo) NeRunSSHClient(neType, neId string) (*ssh.ConnSSH, error) {
logger.Errorf("NeRunTelnetClient hosts id %s not found", neInfo.HostIDs)
return nil, fmt.Errorf("neinfo host id not found")
}
hostId := hostIds[0] // 网元主机ssh 022
neHost := NewNeHost.SelectById(hostId)
if neHost.HostID == "" || neHost.HostID != hostId {
hostId := parse.Number(hostIds[0]) // 网元主机ssh 022
neHost := r.neHostService.FindById(hostId)
if neHost.ID == 0 || neHost.ID != hostId {
logger.Errorf("NeRunTelnetClient Hosts %s not found", neInfo.HostIDs)
return nil, fmt.Errorf("neinfo host not found")
}
@@ -380,7 +387,7 @@ func (r *NeInfo) NeRunSSHClient(neType, neId string) (*ssh.ConnSSH, error) {
}
// NeRunSSHCmd 网元主机的SSH客户端发送cmd命令
func (r *NeInfo) NeRunSSHCmd(neType, neId, cmd string) (string, error) {
func (r NeInfo) NeRunSSHCmd(neType, neId, cmd string) (string, error) {
sshClient, err := r.NeRunSSHClient(neType, neId)
if err != nil {
return "", err
@@ -398,8 +405,8 @@ func (r *NeInfo) NeRunSSHCmd(neType, neId, cmd string) (string, error) {
// NeRunTelnetClient 网元主机的Telnet客户端-为创建相关连接,注意结束后 Close()
// num 是网元主机telnet 14100 25200UPF标准版
func (r *NeInfo) NeRunTelnetClient(neType, neId string, num int) (*telnet.ConnTelnet, error) {
neInfo := r.SelectNeInfoByNeTypeAndNeID(neType, neId)
func (r NeInfo) NeRunTelnetClient(neType, neId string, num int) (*telnet.ConnTelnet, error) {
neInfo := r.FindByNeTypeAndNeID(neType, neId)
if neInfo.NeId != neId {
logger.Errorf("NeRunTelnetClient NeType:%s NeID:%s not found", neType, neId)
return nil, fmt.Errorf("neinfo not found")
@@ -414,9 +421,9 @@ func (r *NeInfo) NeRunTelnetClient(neType, neId string, num int) (*telnet.ConnTe
logger.Errorf("NeRunTelnetClient hosts id %s not found", neInfo.HostIDs)
return nil, fmt.Errorf("neinfo host id not found")
}
hostId := hostIds[num] // 网元主机telnet 14100 25200
neHost := NewNeHost.SelectById(hostId)
if neHost.HostID == "" || neHost.HostID != hostId {
hostId := parse.Number(hostIds[num]) // 网元主机telnet 14100 25200
neHost := r.neHostService.FindById(hostId)
if neHost.ID == 0 || neHost.ID != hostId {
logger.Errorf("NeRunTelnetClient Hosts %s not found", neInfo.HostIDs)
return nil, fmt.Errorf("neinfo host not found")
}
@@ -434,8 +441,8 @@ func (r *NeInfo) NeRunTelnetClient(neType, neId string, num int) (*telnet.ConnTe
// NeRunRedisClient 网元主机的Redis客户端-为创建相关连接,注意结束后 Close()
// 暂时只有UDM有Redis配置项
func (r *NeInfo) NeRunRedisClient(neType, neId string) (*redis.ConnRedis, error) {
neInfo := r.SelectNeInfoByNeTypeAndNeID(neType, neId)
func (r NeInfo) NeRunRedisClient(neType, neId string) (*redis.ConnRedis, error) {
neInfo := r.FindByNeTypeAndNeID(neType, neId)
if neInfo.NeId != neId {
logger.Errorf("NeRunRedisClient NeType:%s NeID:%s not found", neType, neId)
return nil, fmt.Errorf("neinfo not found")
@@ -450,9 +457,9 @@ func (r *NeInfo) NeRunRedisClient(neType, neId string) (*redis.ConnRedis, error)
logger.Errorf("NeRunRedisClient hosts id %s not found", neInfo.HostIDs)
return nil, fmt.Errorf("neinfo host id not found")
}
hostId := hostIds[2]
neHost := NewNeHost.SelectById(hostId)
if neHost.HostID == "" || neHost.HostID != hostId {
hostId := parse.Number(hostIds[2])
neHost := r.neHostService.FindById(hostId)
if neHost.ID == 0 || neHost.ID != hostId {
logger.Errorf("NeRunRedisClient Hosts %s not found", neInfo.HostIDs)
return nil, fmt.Errorf("neinfo host not found")
}
@@ -469,7 +476,7 @@ func (r *NeInfo) NeRunRedisClient(neType, neId string) (*redis.ConnRedis, error)
}
// NeConfOAMReadSync 网元OAM配置文件读取
func (r *NeInfo) NeConfOAMReadSync(neType, neId string) (map[string]any, error) {
func (r NeInfo) NeConfOAMReadSync(neType, neId string) (map[string]any, error) {
oamData, err := r.neConfOAMRead(neType, neId, true)
if err != nil {
return nil, err
@@ -531,7 +538,7 @@ func (r *NeInfo) NeConfOAMReadSync(neType, neId string) (map[string]any, error)
}
// neConfOAMData 网元OAM配置文件默认格式数据
func (r *NeInfo) neConfOAMData() map[string]any {
func (r NeInfo) neConfOAMData() map[string]any {
return map[string]any{
"httpManageCfg": map[string]any{
"ipType": "ipv4",
@@ -574,7 +581,7 @@ func (r *NeInfo) neConfOAMData() map[string]any {
}
// neConfOAMRead 网元OAM配置文件读取 sync从网元端同步到本地
func (r *NeInfo) neConfOAMRead(neType, neId string, sync bool) (map[string]any, error) {
func (r NeInfo) neConfOAMRead(neType, neId string, sync bool) (map[string]any, error) {
neTypeLower := strings.ToLower(neType)
fileName := "oam_manager.yaml"
// 网管本地路径
@@ -629,7 +636,7 @@ func (r *NeInfo) neConfOAMRead(neType, neId string, sync bool) (map[string]any,
}
// neConfOAMWirte 网元OAM配置文件写入 content内容 sync同步到网元端
func (r *NeInfo) neConfOAMWirte(neType, neId string, content any, sync bool) error {
func (r NeInfo) neConfOAMWirte(neType, neId string, content any, sync bool) error {
neTypeLower := strings.ToLower(neType)
fileName := "oam_manager.yaml"
// 网管本地路径
@@ -674,7 +681,7 @@ func (r *NeInfo) neConfOAMWirte(neType, neId string, content any, sync bool) err
}
// NeConfOAMWirteSync 网元OAM配置文件生成并同步
func (r *NeInfo) NeConfOAMWirteSync(neInfo model.NeInfo, content map[string]any, sync bool) error {
func (r NeInfo) NeConfOAMWirteSync(neInfo model.NeInfo, content map[string]any, sync bool) error {
oamData, err := r.neConfOAMRead(neInfo.NeType, neInfo.NeId, false)
if oamData == nil || err != nil {
return fmt.Errorf("error read OAM file info")
@@ -782,7 +789,7 @@ func (r *NeInfo) NeConfOAMWirteSync(neInfo model.NeInfo, content map[string]any,
}
// NeConfPara5GRead 网元公共配置文件读取
func (r *NeInfo) NeConfPara5GRead() (map[string]any, error) {
func (r NeInfo) NeConfPara5GRead() (map[string]any, error) {
// 网管本地路径
omcFilePath := "/usr/local/etc/omc/para5G.yaml"
if runtime.GOOS == "windows" {
@@ -806,7 +813,7 @@ func (r *NeInfo) NeConfPara5GRead() (map[string]any, error) {
}
// NeConfPara5GWirte 网元公共配置文件写入 content内容 syncNE同步到网元端NeType@NeId
func (r *NeInfo) NeConfPara5GWirte(content map[string]any, syncNE []string) error {
func (r NeInfo) NeConfPara5GWirte(content map[string]any, syncNE []string) error {
// 网管本地路径
omcFilePath := "/usr/local/etc/omc/para5G.yaml"
if runtime.GOOS == "windows" {
@@ -859,7 +866,7 @@ func (r *NeInfo) NeConfPara5GWirte(content map[string]any, syncNE []string) erro
}
// NeConfPara5GConvert 网元公共配置数据转化 content网元公共配置文件读取内容
func (r *NeInfo) neConfPara5GDataConvert(content map[string]any) map[string]string {
func (r NeInfo) neConfPara5GDataConvert(content map[string]any) map[string]string {
defer func() {
if err := recover(); err != nil {
logger.Errorf("NeConfPara5GDataConvert panic: %v", err)

View File

@@ -23,22 +23,22 @@ type NeLicense struct {
neLicenseRepository *repository.NeLicense // 网元授权激活信息表
}
// SelectNeHostPage 分页查询列表数据
func (r *NeLicense) SelectPage(query map[string]any) map[string]any {
return r.neLicenseRepository.SelectPage(query)
// FindByPage 分页查询列表数据
func (r *NeLicense) FindByPage(query map[string]string) ([]model.NeLicense, int64) {
return r.neLicenseRepository.SelectByPage(query)
}
// SelectConfigList 查询列表
func (r *NeLicense) SelectList(neLicense model.NeLicense) []model.NeLicense {
return r.neLicenseRepository.SelectList(neLicense)
// Find 查询列表
func (r *NeLicense) Find(neLicense model.NeLicense) []model.NeLicense {
return r.neLicenseRepository.Select(neLicense)
}
// SelectByIds 通过ID查询
func (r *NeLicense) SelectById(id string) model.NeLicense {
if id == "" {
// FindById 通过ID查询
func (r *NeLicense) FindById(id int64) model.NeLicense {
if id <= 0 {
return model.NeLicense{}
}
neLicenses := r.neLicenseRepository.SelectByIds([]string{id})
neLicenses := r.neLicenseRepository.SelectByIds([]int64{id})
if len(neLicenses) > 0 {
return neLicenses[0]
}
@@ -46,7 +46,7 @@ func (r *NeLicense) SelectById(id string) model.NeLicense {
}
// Insert 新增信息
func (r *NeLicense) Insert(neLicense model.NeLicense) string {
func (r *NeLicense) Insert(neLicense model.NeLicense) int64 {
return r.neLicenseRepository.Insert(neLicense)
}
@@ -56,7 +56,7 @@ func (r *NeLicense) Update(neLicense model.NeLicense) int64 {
}
// DeleteByIds 批量删除信息
func (r *NeLicense) DeleteByIds(ids []string) (int64, error) {
func (r *NeLicense) DeleteByIds(ids []int64) (int64, error) {
// 检查是否存在
rowIds := r.neLicenseRepository.SelectByIds(ids)
if len(rowIds) <= 0 {
@@ -71,9 +71,9 @@ func (r *NeLicense) DeleteByIds(ids []string) (int64, error) {
return 0, fmt.Errorf("delete fail")
}
// SelectByTypeAndID 通过网元类型和网元ID查询
func (r *NeLicense) SelectByTypeAndID(neType, neId string) model.NeLicense {
neLicenses := r.neLicenseRepository.SelectList(model.NeLicense{
// FindByTypeAndID 通过网元类型和网元ID查询
func (r *NeLicense) FindByTypeAndID(neType, neId string) model.NeLicense {
neLicenses := r.neLicenseRepository.Select(model.NeLicense{
NeType: neType,
NeId: neId,
})
@@ -83,9 +83,9 @@ func (r *NeLicense) SelectByTypeAndID(neType, neId string) model.NeLicense {
return model.NeLicense{}
}
// SelectByNeTypeAndNeID 通过ne_type和ne_id查询信息
func (r *NeLicense) SelectByNeTypeAndNeID(neType, neId string) model.NeLicense {
neLicenses := r.neLicenseRepository.SelectList(model.NeLicense{
// FindByNeTypeAndNeID 通过ne_type和ne_id查询信息
func (r *NeLicense) FindByNeTypeAndNeID(neType, neId string) model.NeLicense {
neLicenses := r.neLicenseRepository.Select(model.NeLicense{
NeType: neType,
NeId: neId,
})
@@ -142,7 +142,7 @@ func (r *NeLicense) ReadLicenseInfo(neLicense model.NeLicense) (string, string)
// UploadLicense 授权文件上传到网元主机
func (r *NeLicense) UploadLicense(neLicense model.NeLicense) error {
// 检查文件是否存在
omcLicensePath := file.ParseUploadFilePath(neLicense.LicensePath)
omcLicensePath := file.ParseUploadFileAbsPath(neLicense.LicensePath)
if _, err := os.Stat(omcLicensePath); err != nil {
return fmt.Errorf("file read failure")
}

View File

@@ -12,29 +12,31 @@ import (
// 实例化服务层 NeSoftware 结构体
var NewNeSoftware = &NeSoftware{
neSoftwareRepository: repository.NewNeSoftware,
neVersionService: NewNeVersion,
}
// NeSoftware 网元软件包信息 服务层处理
type NeSoftware struct {
neSoftwareRepository *repository.NeSoftware // 网元软件包信息
neVersionService *NeVersion // 网元版本信息服务
}
// SelectNeHostPage 分页查询列表数据
func (r *NeSoftware) SelectPage(query map[string]any) map[string]any {
return r.neSoftwareRepository.SelectPage(query)
// FindByPage 分页查询列表数据
func (r NeSoftware) FindByPage(query map[string]string) ([]model.NeSoftware, int64) {
return r.neSoftwareRepository.SelectByPage(query)
}
// SelectConfigList 查询列表
func (r *NeSoftware) SelectList(neSoftware model.NeSoftware) []model.NeSoftware {
return r.neSoftwareRepository.SelectList(neSoftware)
// Find 查询列表
func (r NeSoftware) Find(neSoftware model.NeSoftware) []model.NeSoftware {
return r.neSoftwareRepository.Select(neSoftware)
}
// SelectByIds 通过ID查询
func (r *NeSoftware) SelectById(id string) model.NeSoftware {
if id == "" {
// FindById 通过ID查询
func (r NeSoftware) FindById(id int64) model.NeSoftware {
if id <= 0 {
return model.NeSoftware{}
}
neHosts := r.neSoftwareRepository.SelectByIds([]string{id})
neHosts := r.neSoftwareRepository.SelectByIds([]int64{id})
if len(neHosts) > 0 {
return neHosts[0]
}
@@ -42,11 +44,11 @@ func (r *NeSoftware) SelectById(id string) model.NeSoftware {
}
// Insert 新增信息
func (r *NeSoftware) Insert(neSoftware model.NeSoftware) string {
func (r NeSoftware) Insert(neSoftware model.NeSoftware) int64 {
inserId := r.neSoftwareRepository.Insert(neSoftware)
if inserId != "" {
if inserId > 0 {
// 更新同类型的新包版本
neVersions := NewNeVersion.SelectList(model.NeVersion{NeType: neSoftware.NeType}, false)
neVersions := r.neVersionService.Find(model.NeVersion{NeType: neSoftware.NeType}, false)
if len(neVersions) > 0 {
for _, neVersion := range neVersions {
neVersion.NewName = neSoftware.Name
@@ -54,7 +56,7 @@ func (r *NeSoftware) Insert(neSoftware model.NeSoftware) string {
neVersion.NewPath = neSoftware.Path
neVersion.Status = "3"
neVersion.UpdateBy = neSoftware.CreateBy
NewNeVersion.Update(neVersion)
r.neVersionService.Update(neVersion)
}
}
}
@@ -62,11 +64,11 @@ func (r *NeSoftware) Insert(neSoftware model.NeSoftware) string {
}
// Update 修改信息
func (r *NeSoftware) Update(neSoftware model.NeSoftware) int64 {
func (r NeSoftware) Update(neSoftware model.NeSoftware) int64 {
rows := r.neSoftwareRepository.Update(neSoftware)
if rows > 0 {
// 更新同类型的新包版本
neVersions := NewNeVersion.SelectList(model.NeVersion{
neVersions := r.neVersionService.Find(model.NeVersion{
NeType: neSoftware.NeType,
Status: "3",
}, false)
@@ -77,7 +79,7 @@ func (r *NeSoftware) Update(neSoftware model.NeSoftware) int64 {
neVersion.NewPath = neSoftware.Path
neVersion.Status = "3"
neVersion.UpdateBy = neSoftware.UpdateBy
NewNeVersion.Update(neVersion)
r.neVersionService.Update(neVersion)
}
}
}
@@ -85,7 +87,7 @@ func (r *NeSoftware) Update(neSoftware model.NeSoftware) int64 {
}
// DeleteByIds 批量删除信息
func (r *NeSoftware) DeleteByIds(ids []string) (int64, error) {
func (r NeSoftware) DeleteByIds(ids []int64) (int64, error) {
// 检查是否存在
rows := r.neSoftwareRepository.SelectByIds(ids)
if len(rows) <= 0 {
@@ -96,7 +98,7 @@ func (r *NeSoftware) DeleteByIds(ids []string) (int64, error) {
// 遍历软件包列表进行文件删除
for _, row := range rows {
// 检查文件是否存在
filePath := file.ParseUploadFilePath(row.Path)
filePath := file.ParseUploadFileAbsPath(row.Path)
if _, err := os.Stat(filePath); err != nil {
continue
}
@@ -111,8 +113,8 @@ func (r *NeSoftware) DeleteByIds(ids []string) (int64, error) {
}
// CheckUniqueTypeAndNameAndVersion 校验网元类型和文件名版本是否唯一
func (r *NeSoftware) CheckUniqueTypeAndNameAndVersion(neType, name, version, id string) bool {
uniqueId := r.neSoftwareRepository.CheckUniqueTypeAndNameAndVersion(model.NeSoftware{
func (r NeSoftware) CheckUniqueTypeAndNameAndVersion(neType, name, version string, id int64) bool {
uniqueId := r.neSoftwareRepository.CheckUnique(model.NeSoftware{
NeType: neType,
Name: name,
Version: version,
@@ -120,14 +122,14 @@ func (r *NeSoftware) CheckUniqueTypeAndNameAndVersion(neType, name, version, id
if uniqueId == id {
return true
}
return uniqueId == ""
return uniqueId == 0
}
// UpdateVersions 更新软件包对应网元的新版本
func (r *NeSoftware) UpdateVersions(neSoftware model.NeSoftware, neVersion model.NeVersion) int64 {
func (r NeSoftware) UpdateVersions(neSoftware model.NeSoftware, neVersion model.NeVersion) int64 {
var rows int64 = 0
// 更新同类型的新包版本
neVersions := NewNeVersion.SelectList(neVersion, false)
neVersions := r.neVersionService.Find(neVersion, false)
if len(neVersions) > 0 {
for _, v := range neVersions {
v.NewName = neSoftware.Name
@@ -135,7 +137,7 @@ func (r *NeSoftware) UpdateVersions(neSoftware model.NeSoftware, neVersion model
v.NewPath = neSoftware.Path
v.Status = "3"
v.UpdateBy = neVersion.UpdateBy
rows += NewNeVersion.Update(v)
rows += r.neVersionService.Update(v)
}
}
return rows

View File

@@ -7,8 +7,8 @@ import (
"strings"
"time"
"be.ems/src/framework/ssh"
"be.ems/src/framework/utils/file"
"be.ems/src/framework/utils/ssh"
neFetchlink "be.ems/src/modules/network_element/fetch_link"
"be.ems/src/modules/network_element/model"
"be.ems/src/modules/network_element/repository"
@@ -17,29 +17,30 @@ import (
// 实例化服务层 NeVersion 结构体
var NewNeVersion = &NeVersion{
neVersionRepository: repository.NewNeVersion,
neInfoService: NewNeInfo,
}
// NeVersion 网元版本信息 服务层处理
type NeVersion struct {
neVersionRepository *repository.NeVersion // 网元版本信息表
neInfoService *NeInfo // 网元信息数据信息
}
// SelectNeHostPage 分页查询列表数据
func (r *NeVersion) SelectPage(query map[string]any, checkVersion bool) map[string]any {
data := r.neVersionRepository.SelectPage(query)
// FindByPage 分页查询列表数据
func (r NeVersion) FindByPage(query map[string]string, checkVersion bool) ([]model.NeVersion, int64) {
rows, total := r.neVersionRepository.SelectByPage(query)
// 网元直连检查更新网元服务版本
if checkVersion {
rows := data["rows"].([]model.NeVersion)
r.checkNeVersion(&rows)
}
return data
return rows, total
}
// SelectConfigList 查询列表
func (r *NeVersion) SelectList(neVersion model.NeVersion, checkVersion bool) []model.NeVersion {
list := r.neVersionRepository.SelectList(neVersion)
// Find 查询列表
func (r NeVersion) Find(neVersion model.NeVersion, checkVersion bool) []model.NeVersion {
list := r.neVersionRepository.Select(neVersion)
// 网元直连检查更新网元服务版本
if checkVersion {
@@ -50,11 +51,11 @@ func (r *NeVersion) SelectList(neVersion model.NeVersion, checkVersion bool) []m
}
// checkNeVersion 网元列表检查更新网元版本
func (r *NeVersion) checkNeVersion(arr *[]model.NeVersion) {
func (r NeVersion) checkNeVersion(arr *[]model.NeVersion) {
for i := range *arr {
item := (*arr)[i]
// 查询网元获取IP
neInfo := NewNeInfo.SelectNeInfoByNeTypeAndNeID(item.NeType, item.NeId)
neInfo := r.neInfoService.FindByNeTypeAndNeID(item.NeType, item.NeId)
if neInfo.NeId != item.NeId || neInfo.IP == "" {
continue
}
@@ -80,12 +81,12 @@ func (r *NeVersion) checkNeVersion(arr *[]model.NeVersion) {
}
}
// SelectByIds 通过ID查询
func (r *NeVersion) SelectById(id string) model.NeVersion {
if id == "" {
// FindById 通过ID查询
func (r NeVersion) FindById(id int64) model.NeVersion {
if id <= 0 {
return model.NeVersion{}
}
neVersions := r.neVersionRepository.SelectByIds([]string{id})
neVersions := r.neVersionRepository.SelectByIds([]int64{id})
if len(neVersions) > 0 {
return neVersions[0]
}
@@ -93,17 +94,17 @@ func (r *NeVersion) SelectById(id string) model.NeVersion {
}
// Insert 新增信息
func (r *NeVersion) Insert(neVersion model.NeVersion) string {
func (r NeVersion) Insert(neVersion model.NeVersion) int64 {
return r.neVersionRepository.Insert(neVersion)
}
// Update 修改信息
func (r *NeVersion) Update(neVersion model.NeVersion) int64 {
func (r NeVersion) Update(neVersion model.NeVersion) int64 {
return r.neVersionRepository.Update(neVersion)
}
// DeleteByIds 批量删除信息
func (r *NeVersion) DeleteByIds(ids []string) (int64, error) {
func (r NeVersion) DeleteByIds(ids []int64) (int64, error) {
// 检查是否存在
rowIds := r.neVersionRepository.SelectByIds(ids)
if len(rowIds) <= 0 {
@@ -118,9 +119,9 @@ func (r *NeVersion) DeleteByIds(ids []string) (int64, error) {
return 0, fmt.Errorf("delete fail")
}
// SelectByNeTypeAndNeID 通过网元类型和网元ID查询
func (r *NeVersion) SelectByNeTypeAndNeID(neType, neId string) model.NeVersion {
neVersions := r.neVersionRepository.SelectList(model.NeVersion{
// FindByNeTypeAndNeID 通过网元类型和网元ID查询
func (r NeVersion) FindByNeTypeAndNeID(neType, neId string) model.NeVersion {
neVersions := r.neVersionRepository.Select(model.NeVersion{
NeType: neType,
NeId: neId,
})
@@ -133,9 +134,9 @@ func (r *NeVersion) SelectByNeTypeAndNeID(neType, neId string) model.NeVersion {
// Operate 操作版本上传到网元主机执行命令
//
// action 安装行为install upgrade rollback
func (r *NeVersion) Operate(action string, neVersion model.NeVersion, preinput map[string]string) (string, error) {
func (r NeVersion) Operate(action string, neVersion model.NeVersion, preinput map[string]string) (string, error) {
// 网元主机的SSH客户端
sshClient, err := NewNeInfo.NeRunSSHClient(neVersion.NeType, neVersion.NeId)
sshClient, err := r.neInfoService.NeRunSSHClient(neVersion.NeType, neVersion.NeId)
if err != nil {
return "", err
}
@@ -157,11 +158,11 @@ func (r *NeVersion) Operate(action string, neVersion model.NeVersion, preinput m
// ========= 安装时设置 =========
if action == "install" {
// 网元公共配置文件
para5GMap, err := NewNeInfo.NeConfPara5GRead()
para5GMap, err := r.neInfoService.NeConfPara5GRead()
if para5GMap == nil || err != nil {
return "", fmt.Errorf("error read para5G file info")
}
if err := NewNeInfo.NeConfPara5GWirte(para5GMap, []string{fmt.Sprintf("%s@%s", neVersion.NeType, neVersion.NeId)}); err != nil {
if err := r.neInfoService.NeConfPara5GWirte(para5GMap, []string{fmt.Sprintf("%s@%s", neVersion.NeType, neVersion.NeId)}); err != nil {
return "", fmt.Errorf("error wirte para5G file info")
}
}
@@ -188,7 +189,7 @@ func (r *NeVersion) Operate(action string, neVersion model.NeVersion, preinput m
}
// operateFile 操作版本-文件传输阶段
func (r *NeVersion) operateFile(sshClient *ssh.ConnSSH, softwarePath string) ([]string, error) {
func (r NeVersion) operateFile(sshClient *ssh.ConnSSH, softwarePath string) ([]string, error) {
// 网元主机的SSH客户端进行文件传输
sftpClient, err := sshClient.NewClientSFTP()
if err != nil {
@@ -209,7 +210,7 @@ func (r *NeVersion) operateFile(sshClient *ssh.ConnSSH, softwarePath string) ([]
for _, path := range softwarePaths {
// 检查文件是否存在
localFilePath := file.ParseUploadFilePath(path)
localFilePath := file.ParseUploadFileAbsPath(path)
if _, err := os.Stat(localFilePath); err != nil {
return nil, fmt.Errorf("file read failure")
}
@@ -231,7 +232,7 @@ func (r *NeVersion) operateFile(sshClient *ssh.ConnSSH, softwarePath string) ([]
}
// operateCommand 操作版本-命令生成阶段
func (r *NeVersion) operateCommand(action, neType string, neFilePaths []string) (string, []string, error) {
func (r NeVersion) operateCommand(action, neType string, neFilePaths []string) (string, []string, error) {
neTypeLower := strings.ToLower(neType)
// 命令终止结束标记
okFlagStr := fmt.Sprintf("%s version %s successful!", neTypeLower, action)
@@ -271,7 +272,7 @@ func (r *NeVersion) operateCommand(action, neType string, neFilePaths []string)
return okFlagStr, cmdStrArr, nil
} else if neType == "IMS" {
if action == "install" {
para5GData := NewNeInfo.Para5GData
para5GData := r.neInfoService.Para5GData
cmdStrArr = append(cmdStrArr, pkgCmdStr+" \n")
// 公网 PLMN地址
@@ -313,7 +314,7 @@ func (r *NeVersion) operateCommand(action, neType string, neFilePaths []string)
}
} else {
if action == "install" {
para5GData := NewNeInfo.Para5GData
para5GData := r.neInfoService.Para5GData
cmdStrArr = append(cmdStrArr, pkgCmdStr+" \n")
// AMF配置修改
@@ -560,14 +561,14 @@ func (r *NeVersion) operateCommand(action, neType string, neFilePaths []string)
if action == "install" && (neTypeLower == "ims" || neTypeLower == "udm") {
// adb
if strings.Contains(pkgCmdStr, "adb") {
para5GData := NewNeInfo.Para5GData
para5GData := r.neInfoService.Para5GData
cmdStrArr = append(cmdStrArr, "sudo cp /usr/local/etc/adb/default/adb.conf /usr/local/etc/adb/adb.conf \n")
cmdStrArr = append(cmdStrArr, fmt.Sprintf("sudo sed -i \"s/bind 127.0.0.1/bind %s/g\" /usr/local/etc/adb/adb.conf \n", para5GData["DB_IP"]))
cmdStrArr = append(cmdStrArr, "sudo service adb restart \n")
}
// kvdb
if strings.Contains(pkgCmdStr, "kvdb") {
para5GData := NewNeInfo.Para5GData
para5GData := r.neInfoService.Para5GData
cmdStrArr = append(cmdStrArr, "sudo cp /usr/local/etc/kvdb/default/kvdb.conf /usr/local/etc/kvdb/kvdb.conf \n")
cmdStrArr = append(cmdStrArr, fmt.Sprintf("sudo sed -i \"s/bind 127.0.0.1/bind %s/g\" /usr/local/etc/kvdb/kvdb.conf \n", para5GData["DB_IP"]))
cmdStrArr = append(cmdStrArr, "sudo service kvdb restart \n")
@@ -583,7 +584,7 @@ func (r *NeVersion) operateCommand(action, neType string, neFilePaths []string)
}
// operateRun 操作版本-执行阶段
func (r *NeVersion) operateRun(sshClient *ssh.ConnSSH, preinput map[string]string, cmdStrArr []string, neType string, okFlagStr string) (string, error) {
func (r NeVersion) operateRun(sshClient *ssh.ConnSSH, preinput map[string]string, cmdStrArr []string, neType string, okFlagStr string) (string, error) {
// ssh连接会话
clientSession, err := sshClient.NewClientSession(127, 42)
if err != nil {
@@ -673,23 +674,23 @@ func (r *NeVersion) operateRun(sshClient *ssh.ConnSSH, preinput map[string]strin
}
// operateDome 操作版本-完成阶段
func (r *NeVersion) operateDome(action string, neVersion model.NeVersion) error {
func (r NeVersion) operateDome(action string, neVersion model.NeVersion) error {
if action == "install" {
// 网元信息
neInfo := NewNeInfo.SelectNeInfoByNeTypeAndNeID(neVersion.NeType, neVersion.NeId)
neInfo := r.neInfoService.FindByNeTypeAndNeID(neVersion.NeType, neVersion.NeId)
if neInfo.NeId != neVersion.NeId {
return fmt.Errorf("error found neinfo")
}
// ========= 网元OAM配置文件 start ==========
if err := NewNeInfo.NeConfOAMWirteSync(neInfo, nil, true); err != nil {
if err := r.neInfoService.NeConfOAMWirteSync(neInfo, nil, true); err != nil {
return fmt.Errorf("error wirte OAM file info")
}
// ========= 网元OAM配置文件 end ===========
// SMSC配置修改 IMS/UDM 配置
if neInfo.NeType == "SMSC" {
para5GData := NewNeInfo.Para5GData
para5GData := r.neInfoService.Para5GData
mnc_mcc := fmt.Sprintf("mnc%s.mcc%s", para5GData["MNC_DOMAIN"], para5GData["MCC"])
smscHost := fmt.Sprintf("%s smsc.ims.%s.3gppnetwork.org", para5GData["SMSC_IP"], mnc_mcc)
smscHostCMD := fmt.Sprintf("grep -qxF '%s' /etc/hosts || echo '%s' | sudo tee -a /etc/hosts \n", smscHost, smscHost)
@@ -697,30 +698,30 @@ func (r *NeVersion) operateDome(action string, neVersion model.NeVersion) error
smsHost := fmt.Sprintf("sudo sed -i '/^%s smsc.*smsc$/c\\' /etc/hosts", para5GData["SIP_IP"])
// IMS 配置
imsNEs := NewNeInfo.SelectList(model.NeInfo{NeType: "IMS"}, false, false)
imsNEs := r.neInfoService.Find(model.NeInfo{NeType: "IMS"}, false, false)
for _, v := range imsNEs {
NewNeInfo.NeRunSSHCmd(v.NeType, v.NeId, smscIPCMD)
NewNeInfo.NeRunSSHCmd(v.NeType, v.NeId, smscHostCMD)
NewNeInfo.NeRunSSHCmd(v.NeType, v.NeId, smsHost)
NewNeInfo.NeRunSSHCmd(v.NeType, v.NeId, "sudo sed -i '/^#!define WITH_SMS/ s/^/#/' /usr/local/etc/ims/vars.cfg")
NewNeInfo.NeRunSSHCmd(v.NeType, v.NeId, "ims-stop || true && ims-start")
r.neInfoService.NeRunSSHCmd(v.NeType, v.NeId, smscIPCMD)
r.neInfoService.NeRunSSHCmd(v.NeType, v.NeId, smscHostCMD)
r.neInfoService.NeRunSSHCmd(v.NeType, v.NeId, smsHost)
r.neInfoService.NeRunSSHCmd(v.NeType, v.NeId, "sudo sed -i '/^#!define WITH_SMS/ s/^/#/' /usr/local/etc/ims/vars.cfg")
r.neInfoService.NeRunSSHCmd(v.NeType, v.NeId, "ims-stop || true && ims-start")
}
// UDM 配置
smscASName := fmt.Sprintf("sudo sed -i \"/- name: 'sms_as'/{n;s|serverName: .*|serverName: 'sip:%s:5060'|}\" /usr/local/etc/udm/as.yaml", para5GData["SMSC_IP"])
smscASAddress := fmt.Sprintf("sudo sed -i \"/- name: 'sms_as'/{n;n;n;s|diameterAddress: .*|diameterAddress: 'smsc.ims.%s.3gppnetwork.org'|}\" /usr/local/etc/udm/as.yaml", mnc_mcc)
udmNEs := NewNeInfo.SelectList(model.NeInfo{NeType: "UDM"}, false, false)
udmNEs := r.neInfoService.Find(model.NeInfo{NeType: "UDM"}, false, false)
for _, v := range udmNEs {
NewNeInfo.NeRunSSHCmd(v.NeType, v.NeId, smscIPCMD)
NewNeInfo.NeRunSSHCmd(v.NeType, v.NeId, smscHostCMD)
NewNeInfo.NeRunSSHCmd(v.NeType, v.NeId, smscASName)
NewNeInfo.NeRunSSHCmd(v.NeType, v.NeId, smscASAddress)
NewNeInfo.NeRunSSHCmd(v.NeType, v.NeId, "sudo service udm restart")
r.neInfoService.NeRunSSHCmd(v.NeType, v.NeId, smscIPCMD)
r.neInfoService.NeRunSSHCmd(v.NeType, v.NeId, smscHostCMD)
r.neInfoService.NeRunSSHCmd(v.NeType, v.NeId, smscASName)
r.neInfoService.NeRunSSHCmd(v.NeType, v.NeId, smscASAddress)
r.neInfoService.NeRunSSHCmd(v.NeType, v.NeId, "sudo service udm restart")
}
}
}
// 更新Version
verInfo := r.SelectByNeTypeAndNeID(neVersion.NeType, neVersion.NeId)
verInfo := r.FindByNeTypeAndNeID(neVersion.NeType, neVersion.NeId)
if verInfo.NeId == neVersion.NeId {
curName := verInfo.Name
curVersion := verInfo.Version