Merge remote-tracking branch 'origin/main' into multi-tenant

This commit is contained in:
TsMask
2025-01-11 12:00:19 +08:00
141 changed files with 1560 additions and 12496 deletions

View File

@@ -1,7 +1,6 @@
package src
import (
"embed"
"fmt"
"be.ems/src/framework/config"
@@ -20,34 +19,19 @@ import (
"be.ems/src/modules/trace"
"be.ems/src/modules/ws"
"github.com/chenjiandongx/ginprom"
"github.com/gin-gonic/gin"
"github.com/prometheus/client_golang/prometheus/promhttp"
)
//go:embed assets/*
var assetsDir embed.FS
// 路由函数句柄,交给由 http.ListenAndServe(addr, router)
// AppEngine 路由函数句柄,交给由 http.ListenAndServe(addr, router)
func AppEngine() *gin.Engine {
app := initAppEngine()
// TODO 不建议在主分支中加入
// 性能分析监控
if promEnabled := config.Get("pprof.enabled"); promEnabled != nil && promEnabled.(bool) {
app.Use(ginprom.PromMiddleware(nil))
app.GET("/metrics", ginprom.PromHandler(promhttp.Handler()))
}
// 初始全局默认
initDefeat(app)
// 初始模块路由
initModulesRoute(app)
// 设置程序内全局资源访问
config.SetAssetsDirFS(assetsDir)
// 首次安装启动记录
machine.Launch()
@@ -56,26 +40,6 @@ func AppEngine() *gin.Engine {
return app
}
// 运行服务程序 main.go
//
// func main() {
// src.ConfigurationInit()
// if err := src.RunServer(); err != nil {
// src.ConfigurationClose()
// }
// }
func RunServer() error {
app := AppEngine()
// 读取服务配置
app.ForwardedByClientIP = config.Get("server.proxy").(bool)
addr := fmt.Sprintf(":%d", config.Get("server.port").(int))
// 启动服务
fmt.Printf("\nopen http://localhost%s \n\n", addr)
return app.Run(addr)
}
// 初始应用引擎
func initAppEngine() *gin.Engine {
var app *gin.Engine

View File

@@ -1,9 +1,11 @@
# 应用服务配置
server:
# 服务端口
port: 33030
# 是否开启代理
proxy: false
# 运行版本 standards/lite/tenants
runVersion: "standards"
# 运行模式 system/docker
runMode: "system"
# 日志
logger:

View File

@@ -1,6 +1,5 @@
# 应用服务配置
server:
port: 33040
proxy: true
# 日志
@@ -10,10 +9,13 @@ logger:
# 静态文件配置, 相对项目根路径或填绝对路径
staticFile:
# 默认资源dir目录需要预先创建
default:
prefix: "/static"
dir: "C:/usr/local/omc/static"
# 文件上传资源目录映射,与项目目录同级
upload:
prefix: "/upload"
dir: "C:/usr/local/omc/upload"
# security 安全

View File

@@ -1,6 +1,5 @@
# 应用服务配置
server:
port: 33030
proxy: true
# security 安全

View File

@@ -1,6 +1,8 @@
package src
import (
"embed"
"be.ems/src/framework/config"
"be.ems/src/framework/cron"
"be.ems/src/framework/datasource"
@@ -8,10 +10,16 @@ import (
"be.ems/src/framework/redis"
)
//go:embed config/*.yaml
var configDir embed.FS
//go:embed assets/*
var assetsDir embed.FS
// 配置中心初始加载
func ConfigurationInit() {
// 初始配置参数
config.InitConfig()
config.InitConfig(configDir, assetsDir)
// 初始程序日志
logger.InitLogger()
// 连接数据库实例

View File

@@ -8,18 +8,20 @@ import (
"os"
"time"
libConfig "be.ems/src/lib_features/config"
"github.com/spf13/pflag"
"github.com/spf13/viper"
libConfig "be.ems/lib/config"
libGlobal "be.ems/lib/global"
)
//go:embed config/*.yaml
var configFiles embed.FS
var cfg *viper.Viper
// 初始化程序配置
func InitConfig() {
func InitConfig(configDir, assetsDir embed.FS) {
cfg = viper.New()
initFlag()
initViper()
initViper(configDir, assetsDir)
}
// 指定参数绑定
@@ -28,7 +30,7 @@ func initFlag() {
pflag.String("env", "prod", "Specify Run Environment Configuration local or prod")
// --c /etc/restconf.yaml
// -c /etc/restconf.yaml
pConfig := pflag.StringP("config", "c", "./etc/restconf.yaml", "Specify Configuration File")
pflag.StringP("config", "c", "./etc/restconf.yaml", "Specify Configuration File")
// --version
// -V
pVersion := pflag.BoolP("version", "V", false, "Output program version")
@@ -39,7 +41,7 @@ func initFlag() {
// 参数固定输出
if *pVersion {
buildInfo := libConfig.BuildInfo()
buildInfo := fmt.Sprintf("OMC version: %s\n%s\n%s\n\n", libGlobal.Version, libGlobal.BuildTime, libGlobal.GoVer)
fmt.Println(buildInfo)
os.Exit(1)
}
@@ -48,113 +50,130 @@ func initFlag() {
os.Exit(1)
}
// 外层lib和features使用的配置
libConfig.ConfigRead(*pConfig)
viper.BindPFlags(pflag.CommandLine)
cfg.BindPFlags(pflag.CommandLine)
}
// 配置文件读取
func initViper() {
// 在当前工作目录中寻找配置
// viper.AddConfigPath("config")
// viper.AddConfigPath("src/config")
func initViper(configDir, assetsDir embed.FS) {
// 如果配置文件名中没有扩展名则需要设置Type
viper.SetConfigType("yaml")
cfg.SetConfigType("yaml")
// 从 embed.FS 中读取默认配置文件内容
configDefault, err := configFiles.ReadFile("config/config.default.yaml")
configDefault, err := configDir.ReadFile("config/config.default.yaml")
if err != nil {
log.Fatalf("ReadFile config default file: %s", err)
return
}
// 设置默认配置文件内容到 viper
err = viper.ReadConfig(bytes.NewReader(configDefault))
err = cfg.ReadConfig(bytes.NewReader(configDefault))
if err != nil {
log.Fatalf("NewReader config default file: %s", err)
return
}
// // 配置文件的名称(无扩展名)
// viper.SetConfigName("config.default")
// // 读取默认配置文件
// if err := viper.ReadInConfig(); err != nil {
// log.Fatalf("fatal error config default file: %s", err)
// }
env := viper.GetString("env")
// 加载运行环境配置
env := cfg.GetString("env")
if env != "local" && env != "prod" {
log.Fatalf("fatal error config env for local or prod : %s", env)
}
log.Printf("Current service environment operation configuration => %s \n", env)
// 加载运行配置文件合并相同配置
if env == "prod" {
// viper.SetConfigName("config.prod")
// 从 embed.FS 中读取默认配置文件内容
configProd, err := configFiles.ReadFile("config/config.prod.yaml")
if err != nil {
log.Fatalf("ReadFile config prod file: %s", err)
return
}
// 设置默认配置文件内容到 viper
err = viper.MergeConfig(bytes.NewReader(configProd))
if err != nil {
log.Fatalf("NewReader config prod file: %s", err)
return
}
} else {
// viper.SetConfigName("config.local")
// 从 embed.FS 中读取默认配置文件内容
configLocal, err := configFiles.ReadFile("config/config.local.yaml")
if err != nil {
log.Fatalf("ReadFile config local file: %s", err)
return
}
// 设置默认配置文件内容到 viper
err = viper.MergeConfig(bytes.NewReader(configLocal))
if err != nil {
log.Fatalf("NewReader config local file: %s", err)
return
}
envPath := "config/config.prod.yaml"
if env == "local" {
envPath = "config/config.local.yaml"
}
// 从 embed.FS 中读取默认配置文件内容
configEnv, err := configDir.ReadFile(envPath)
if err != nil {
log.Fatalf("ReadFile config local file: %s", err)
return
}
// 设置默认配置文件内容到 viper
err = cfg.MergeConfig(bytes.NewReader(configEnv))
if err != nil {
log.Fatalf("NewReader config local file: %s", err)
return
}
// if err := viper.MergeInConfig(); err != nil {
// log.Fatalf("fatal error config MergeInConfig: %s", err)
// }
// 合并外层lib和features使用配置
libConfig.ConfigInMerge()
// 合并外使用配置
configFile := cfg.GetString("config")
if configFile != "" {
configInMerge(configFile)
}
// 记录程序开始运行的时间点
viper.Set("runTime", time.Now())
cfg.Set("runTime", time.Now())
// 设置程序内全局资源访问
cfg.Set("AssetsDir", assetsDir)
}
// 配置文件读取进行内部参数合并
func configInMerge(configFile string) {
// 指定配置文件读取序列化
libConfig.ReadConfig(configFile)
uriPrefix := libConfig.GetYamlConfig().OMC.UriPrefix
if uriPrefix != "" {
libConfig.UriPrefix = uriPrefix
}
if libConfig.GetYamlConfig().TestConfig.Enabled {
libConfig.ReadTestConfigYaml(libConfig.GetYamlConfig().TestConfig.File)
}
// 配置文件读取
var v = viper.New()
// 设置配置文件路径
v.SetConfigFile(configFile)
v.SetConfigType("yaml")
// 读取配置文件
if err := v.ReadInConfig(); err != nil {
fmt.Printf("failure to read configuration file: %v \n", err)
return
}
// 合并外层lib和features使用配置
for key, value := range v.AllSettings() {
// 跳过配置
if key == "testconfig" || key == "logger" {
continue
}
// 数据库配置
if key == "database" {
item := value.(map[string]any)
defaultItem := cfg.GetStringMap("gorm.datasource.default")
defaultItem["type"] = item["type"]
defaultItem["host"] = item["host"]
defaultItem["port"] = item["port"]
defaultItem["username"] = item["user"]
defaultItem["password"] = item["password"]
defaultItem["database"] = item["name"]
continue
}
cfg.Set(key, value)
}
}
// Env 获取运行服务环境
// local prod
func Env() string {
return viper.GetString("env")
return cfg.GetString("env")
}
// RunTime 程序开始运行的时间
func RunTime() time.Time {
return viper.GetTime("runTime")
return cfg.GetTime("runTime")
}
// Get 获取配置信息
//
// Get("server.port")
// Get("server.proxy")
func Get(key string) any {
return viper.Get(key)
return cfg.Get(key)
}
// GetAssetsDirFS 访问程序内全局资源访问
func GetAssetsDirFS() embed.FS {
return viper.Get("AssetsDir").(embed.FS)
}
// SetAssetsDirFS 设置程序内全局资源访问
func SetAssetsDirFS(assetsDir embed.FS) {
viper.Set("AssetsDir", assetsDir)
return cfg.Get("AssetsDir").(embed.FS)
}
// IsAdmin 用户是否为管理员
@@ -165,7 +184,7 @@ func IsAdmin(userID string) bool {
// 从本地配置获取user信息
admins := Get("user.adminList").([]any)
for _, s := range admins {
if s.(string) == userID {
if fmt.Sprint(s) == userID {
return true
}
}

View File

@@ -3,15 +3,15 @@ package logger
import (
"log"
"github.com/spf13/viper"
"be.ems/src/framework/config"
)
var logWriter *Logger
// 初始程序日志
func InitLogger() {
env := viper.GetString("env")
conf := viper.GetStringMap("logger")
env := config.Get("env").(string)
conf := config.Get("logger").(map[string]any)
fileDir := conf["filedir"].(string)
fileName := conf["filename"].(string)
level := conf["level"].(int)

View File

@@ -1,53 +0,0 @@
package libfeatures
import (
"fmt"
libConf "be.ems/lib/core/conf"
libGlobal "be.ems/lib/global"
libConfig "be.ems/restagent/config"
"github.com/spf13/viper"
)
// BuildInfo 程序-V查看编译版本号信息
func BuildInfo() string {
return fmt.Sprintf("OMC restagent version: %s\n%s\n%s\n\n", libGlobal.Version, libGlobal.BuildTime, libGlobal.GoVer)
}
// ConfigRead 指定配置文件读取
func ConfigRead(configFile string) {
// 外层lib和features使用的配置
libConfig.ReadConfig(configFile)
uriPrefix := libConfig.GetYamlConfig().OMC.UriPrefix
if uriPrefix != "" {
libConfig.UriPrefix = uriPrefix
}
if libConfig.GetYamlConfig().TestConfig.Enabled {
libConfig.ReadTestConfigYaml(libConfig.GetYamlConfig().TestConfig.File)
}
// 外层lib和features使用配置
libConf.InitConfig(configFile)
}
// 配置文件读取进行内部参数合并
func ConfigInMerge() {
// 合并外层lib和features使用配置
for key, value := range libConf.AllSettings() {
// 跳过配置
if key == "testconfig" || key == "rest" || key == "logger" {
continue
}
// 数据库配置
if key == "database" {
item := value.(map[string]any)
defaultItem := viper.GetStringMap("gorm.datasource.default")
defaultItem["host"] = item["host"]
defaultItem["port"] = item["port"]
defaultItem["username"] = item["user"]
defaultItem["password"] = item["password"]
defaultItem["database"] = item["name"]
continue
}
viper.Set(key, value)
}
}

View File

@@ -1,4 +0,0 @@
# 外层 lib 和 features 粘合层
- config.go 配置合并: restagent.yaml 文件内容,主要是数据库配置

View File

@@ -25,6 +25,15 @@ type ChartGraphController struct {
// 获取关系图组名
//
// GET /groups
//
// @Tags chart
// @Accept json
// @Produce json
// @Success 200 {object} map[string]any "data"
// @Security ApiKeyAuth
// @Summary Get relationship graph group name
// @Description Get relationship graph group name
// @Router /chart/graph/groups [get]
func (s *ChartGraphController) GroupNames(c *gin.Context) {
data := s.chartGraphService.SelectGroup()
c.JSON(200, result.OkData(data))
@@ -33,6 +42,17 @@ func (s *ChartGraphController) GroupNames(c *gin.Context) {
// 获取关系图数据
//
// GET /
//
// @Tags chart
// @Accept json
// @Produce json
// @Param group query string true "Group"
// @Param type query string true "Type oneof=node edge combo" Enums(node, edge, combo)
// @Success 200 {object} map[string]any "data"
// @Security ApiKeyAuth
// @Summary Getting Relationship Map Data
// @Description Getting Relationship Map Data
// @Router /chart/graph [get]
func (s *ChartGraphController) Load(c *gin.Context) {
language := ctx.AcceptLanguage(c)
var querys struct {
@@ -51,6 +71,16 @@ func (s *ChartGraphController) Load(c *gin.Context) {
// 保存关系图数据
//
// POST /
//
// @Tags chart
// @Accept json
// @Produce json
// @Param data body map[string]any true "{group:'',data:{nodes:[],edges:[],combos:[]}}"
// @Success 200 {object} map[string]any "data"
// @Security ApiKeyAuth
// @Summary Saving Relationship Diagram Data
// @Description Saving Relationship Diagram Data
// @Router /chart/graph/ [post]
func (s *ChartGraphController) Save(c *gin.Context) {
language := ctx.AcceptLanguage(c)
var body struct {
@@ -83,6 +113,16 @@ func (s *ChartGraphController) Save(c *gin.Context) {
// 删除关系图数据
//
// DELETE /:group
//
// @Tags chart
// @Accept json
// @Produce json
// @Param group path string true "Group"
// @Success 200 {object} map[string]any "data"
// @Security ApiKeyAuth
// @Summary Deleting Relationship Diagram Data
// @Description Deleting Relationship Diagram Data
// @Router /chart/graph/:group [delete]
func (s *ChartGraphController) Delete(c *gin.Context) {
language := ctx.AcceptLanguage(c)
group := c.Param("group")

View File

@@ -20,6 +20,14 @@ type IndexController struct{}
// 根路由
//
// GET /
//
// @Tags common
// @Accept json
// @Produce json
// @Success 200 {object} map[string]any "data"
// @Summary Root Route
// @Description Root Route
// @Router / [get]
func (s *IndexController) Handler(c *gin.Context) {
name := "OMC"
version := libGlobal.Version

View File

@@ -6,10 +6,10 @@ import (
"strings"
"time"
"be.ems/lib/config"
"be.ems/lib/dborm"
"be.ems/lib/global"
"be.ems/lib/log"
"be.ems/restagent/config"
"be.ems/src/framework/cron"
)

View File

@@ -9,10 +9,10 @@ import (
"time"
"be.ems/features/fm"
"be.ems/lib/config"
"be.ems/lib/dborm"
"be.ems/lib/global"
"be.ems/lib/log"
"be.ems/restagent/config"
"be.ems/src/framework/cron"
"github.com/go-resty/resty/v2"
)

View File

@@ -7,9 +7,9 @@ import (
"strings"
"time"
"be.ems/lib/config"
"be.ems/lib/dborm"
"be.ems/lib/log"
"be.ems/restagent/config"
"be.ems/src/framework/cron"
"github.com/go-resty/resty/v2"
)

View File

@@ -7,6 +7,8 @@ import (
"runtime"
"strings"
"github.com/gin-gonic/gin"
"be.ems/src/framework/i18n"
"be.ems/src/framework/utils/ctx"
"be.ems/src/framework/utils/file"
@@ -14,8 +16,6 @@ import (
"be.ems/src/framework/utils/ssh"
"be.ems/src/framework/vo/result"
neService "be.ems/src/modules/network_element/service"
"github.com/gin-gonic/gin"
"github.com/gin-gonic/gin/binding"
)
// 实例化控制层 NeActionController 结构体
@@ -34,6 +34,15 @@ type NeActionController struct {
// 从本地到网元发送文件
//
// POST /pushFile
//
// @Tags network_element
// @Accept json
// @Produce json
// @Success 200 {object} map[string]any{} "data"
// @Security ApiKeyAuth
// @Summary Sending files from local to network elements
// @Description Sending files from local to network elements
// @Router /ne/action/pushFile [post]
func (s *NeActionController) PushFile(c *gin.Context) {
language := ctx.AcceptLanguage(c)
var body struct {
@@ -42,7 +51,7 @@ func (s *NeActionController) PushFile(c *gin.Context) {
UploadPath string `json:"uploadPath" binding:"required"`
DelTemp bool `json:"delTemp"` // 删除本地临时文件
}
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return
}
@@ -331,7 +340,7 @@ func (s *NeActionController) Service(c *gin.Context) {
NeID string `json:"neId" binding:"required"`
Action string `json:"action" binding:"required,oneof=start restart stop reboot poweroff"` // 操作行为
}
if err := c.ShouldBindBodyWith(&body, binding.JSON); err != nil {
if err := c.ShouldBindBodyWithJSON(&body); err != nil {
c.JSON(400, result.CodeMsg(400, i18n.TKey(language, "app.common.err400")))
return
}

View File

@@ -233,13 +233,13 @@ func (s *NeInfoController) OAMFileWrite(c *gin.Context) {
//
// GET /list
func (s *NeInfoController) List(c *gin.Context) {
querys := ctx.QueryMap(c)
query := ctx.QueryMapString(c)
bandStatus := false
if v, ok := querys["bandStatus"]; ok && v != nil {
if v, ok := query["bandStatus"]; ok {
bandStatus = parse.Boolean(v)
}
data := s.neInfoService.SelectPage(querys, bandStatus)
c.JSON(200, result.Ok(data))
rows, total := s.neInfoService.SelectPage(query, bandStatus)
c.JSON(200, result.Ok(map[string]any{"rows": rows, "total": total}))
}
// 网元信息
@@ -289,11 +289,13 @@ func (s *NeInfoController) Add(c *gin.Context) {
if err != nil {
body.Status = "0"
} else {
// 网元状态设置为在线
body.Status = "1"
if parse.Boolean(body.ServerState["standby"]) {
body.Status = "3"
}
// 下发网管配置信息给网元
_, err = neFetchlink.NeConfigOMC(body)
if err == nil {
body.Status = "1"
} else {
if _, err = neFetchlink.NeConfigOMC(body); err != nil {
body.Status = "2"
}
}
@@ -380,11 +382,13 @@ func (s *NeInfoController) Edit(c *gin.Context) {
if err != nil {
body.Status = "0"
} else {
// 网元状态设置为在线
body.Status = "1"
if parse.Boolean(body.ServerState["standby"]) {
body.Status = "3"
}
// 下发网管配置信息给网元
_, err = neFetchlink.NeConfigOMC(body)
if err == nil {
body.Status = "1"
} else {
if _, err = neFetchlink.NeConfigOMC(body); err != nil {
body.Status = "2"
}
}

View File

@@ -27,10 +27,10 @@ func NeConfigOMC(neInfo model.NeInfo) (map[string]any, error) {
var resData map[string]any
if err != nil {
errStr := err.Error()
logger.Warnf("NeConfigOMC Put \"%s\"", neUrl)
if strings.HasPrefix(errStr, "201") || strings.HasPrefix(errStr, "204") {
return resData, nil
}
logger.Warnf("NeConfigOMC Put \"%s\"", neUrl)
logger.Errorf("NeConfigOMC %s", errStr)
return nil, fmt.Errorf("NeService Config OMC Update API Error")
}

View File

@@ -45,6 +45,7 @@ func NeState(neInfo model.NeInfo) (map[string]any, error) {
"neName": neInfo.NeName,
"neIP": neInfo.IP,
"refreshTime": time.Now().UnixMilli(), // 获取时间
"standby": resData["standby"], // 是否备用服务
"version": resData["version"],
"capability": resData["capability"],
"sn": resData["serialNum"],

View File

@@ -2,31 +2,36 @@ package model
// NeInfo 网元信息对象 ne_info
type NeInfo 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"`
RmUID string `json:"rmUid" gorm:"rm_uid"`
NeName string `json:"neName" gorm:"ne_name"`
IP string `json:"ip" gorm:"ip" binding:"required"`
Port int64 `json:"port" gorm:"port" binding:"required,number,max=65535,min=1"`
PvFlag string `json:"pvFlag" gorm:"pv_flag" binding:"oneof=PNF VNF"` // ''PNF'',''VNF''
Province string `json:"province" gorm:"province"` // 省份地域
VendorName string `json:"vendorName" gorm:"vendor_name"`
Dn string `json:"dn" gorm:"dn"`
NeAddress string `json:"neAddress" gorm:"ne_address"` // MAC地址
HostIDs string `json:"hostIds" gorm:"host_ids"` // 网元主机ID组 数据格式(ssh,telnet) UDM(ssh,telnet,redis) UPF(ssh,telnet,telnet)
Status string `json:"status" gorm:"status"` // 0离线 1在线 2配置待下发
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 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"` // 更新时间
// ====== 非数据库字段属性 ======
// 服务状态
ServerState map[string]any `json:"serverState,omitempty"`
ServerState map[string]any `json:"serverState,omitempty" gorm:"-"`
// 主机对象组
Hosts []NeHost `json:"hosts,omitempty"`
Hosts []NeHost `json:"hosts,omitempty" gorm:"-"`
}
// TableName 表名称
func (*NeInfo) TableName() string {
return "ne_info"
}

View File

@@ -1,94 +1,50 @@
package repository
import (
"fmt"
"strings"
"time"
"be.ems/src/framework/datasource"
"be.ems/src/framework/logger"
"be.ems/src/framework/utils/parse"
"be.ems/src/framework/utils/repo"
"be.ems/src/modules/network_element/model"
)
// neListSort 网元列表预设排序
var neListSort = []string{
"OMC",
"IMS",
"AMF",
"AUSF",
"UDR",
"UDM",
"SMF",
"PCF",
"NSSF",
"NRF",
"UPF",
"LMF",
"NEF",
"MME",
"N3IWF",
"MOCNGW",
"SMSC",
"SMSF",
"CBC",
"CHF",
"HLR",
"SGWC",
}
// 实例化数据层 NeInfo 结构体
var NewNeInfo = &NeInfo{
selectSql: `select id, ne_type, ne_id, rm_uid, ne_name, ip, port, pv_flag, province, vendor_name, dn, ne_address, host_ids, status, remark, create_by, create_time, update_by, update_time from ne_info`,
resultMap: map[string]string{
"id": "ID",
"ne_type": "NeType",
"ne_id": "NeId",
"rm_uid": "RmUID",
"ne_name": "NeName",
"ip": "IP",
"port": "Port",
"pv_flag": "PvFlag",
"province": "Province",
"vendor_name": "VendorName",
"dn": "Dn",
"ne_address": "NeAddress",
"host_ids": "HostIDs",
"status": "Status",
"remark": "Remark",
"create_by": "CreateBy",
"create_time": "CreateTime",
"update_by": "UpdateBy",
"update_time": "UpdateTime",
},
}
var NewNeInfo = &NeInfo{}
// NeInfo 网元信息表 数据层处理
type NeInfo struct {
// 查询视图对象SQL
selectSql string
// 结果字段与实体映射
resultMap map[string]string
}
type NeInfo struct{}
// convertResultRows 将结果记录转实体结果组
func (r *NeInfo) convertResultRows(rows []map[string]any) []model.NeInfo {
arr := make([]model.NeInfo, 0)
for _, row := range rows {
item := model.NeInfo{}
for key, value := range row {
if keyMapper, ok := r.resultMap[key]; ok {
repo.SetFieldValue(&item, keyMapper, value)
}
}
arr = append(arr, item)
// neListSort 网元列表预设排序
func (r NeInfo) neListSort(arr []model.NeInfo) []model.NeInfo {
// neListSort 网元列表预设排序
var list = []string{
"OMC",
"IMS",
"AMF",
"AUSF",
"UDR",
"UDM",
"SMF",
"PCF",
"NSSF",
"NRF",
"UPF",
"LMF",
"NEF",
"MME",
"N3IWF",
"MOCNGW",
"SMSC",
"SMSF",
"CBC",
"CHF",
"HLR",
"SGWC",
}
// 创建优先级映射
priority := make(map[string]int)
for i, v := range neListSort {
for i, v := range list {
priority[v] = i
}
// 冒泡排序
@@ -101,310 +57,174 @@ func (r *NeInfo) convertResultRows(rows []map[string]any) []model.NeInfo {
}
}
}
return arr
}
// SelectNeInfoByNeTypeAndNeID 通过ne_type和ne_id查询网元信息
func (r *NeInfo) SelectNeInfoByNeTypeAndNeID(neType, neID string) model.NeInfo {
querySql := r.selectSql + " where ne_type = ? and ne_id = ?"
results, err := datasource.RawDB("", querySql, []any{neType, neID})
if err != nil {
logger.Errorf("query err => %v", err)
return model.NeInfo{}
}
// 转换实体
rows := r.convertResultRows(results)
if len(rows) > 0 {
return rows[0]
}
return model.NeInfo{}
}
// SelectPage 根据条件分页查询
func (r *NeInfo) SelectPage(query map[string]any) map[string]any {
// SelectByPage 分页查询集合
func (r NeInfo) SelectByPage(query map[string]string) ([]model.NeInfo, int64) {
tx := datasource.DB("").Model(&model.NeInfo{})
// 查询条件拼接
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["rmUid"]; ok && v != "" {
conditions = append(conditions, "rmUid like concat(?, '%')")
params = append(params, strings.Trim(v.(string), " "))
tx = tx.Where("rmUid like concat(?, '%')", v)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
// 查询结果
var total int64 = 0
rows := []model.NeInfo{}
// 查询数量为0直接返回
if err := tx.Count(&total).Error; err != nil || total <= 0 {
return rows, total
}
result := map[string]any{
"total": 0,
"rows": []model.NeInfo{},
}
// 查询数量 长度为0直接返回
totalSql := "select count(1) as 'total' from ne_info"
totalRows, err := datasource.RawDB("", totalSql+whereSql, params)
// 查询数据分页
pageNum, pageSize := datasource.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 {
logger.Errorf("total err => %v", err)
return result
}
total := parse.Number(totalRows[0]["total"])
if total == 0 {
return result
} else {
result["total"] = total
logger.Errorf("query find err => %v", err.Error())
return rows, total
}
return r.neListSort(rows), total
}
// 分页
pageNum, pageSize := repo.PageNumSize(query["pageNum"], query["pageSize"])
pageSql := " limit ?,? "
params = append(params, pageNum*pageSize)
params = append(params, pageSize)
// 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)
// 查询数据
querySql := r.selectSql + whereSql + " order by ne_type asc, ne_id asc " + pageSql
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
return result
row := model.NeInfo{}
if err := tx.Limit(1).Find(&row).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return row
}
// 转换实体
result["rows"] = r.convertResultRows(results)
return result
return row
}
// SelectList 查询列表
func (r *NeInfo) SelectList(neInfo model.NeInfo) []model.NeInfo {
// 查询条件拼接
var conditions []string
var params []any
func (r NeInfo) SelectList(neInfo model.NeInfo) []model.NeInfo {
tx := datasource.DB("").Model(&model.NeInfo{})
// 构建查询条件
if neInfo.NeType != "" {
conditions = append(conditions, "ne_type = ?")
params = append(params, neInfo.NeType)
tx = tx.Where("ne_type = ?", neInfo.NeType)
}
if neInfo.NeId != "" {
conditions = append(conditions, "ne_id = ?")
params = append(params, neInfo.NeId)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
tx = tx.Where("ne_id = ?", neInfo.NeId)
}
// 查询数据
querySql := r.selectSql + whereSql + " order by ne_type asc, ne_id asc "
results, err := datasource.RawDB("", querySql, params)
if err != nil {
logger.Errorf("query err => %v", err)
rows := []model.NeInfo{}
if err := tx.Order("ne_type asc, ne_id asc").Find(&rows).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return rows
}
// 转换实体
return r.convertResultRows(results)
return r.neListSort(rows)
}
// SelectByIds 通过ID查询
func (r *NeInfo) SelectByIds(infoIds []string) []model.NeInfo {
placeholder := repo.KeyPlaceholderByQuery(len(infoIds))
querySql := r.selectSql + " where id in (" + placeholder + ")"
parameters := repo.ConvertIdsSlice(infoIds)
results, err := datasource.RawDB("", querySql, parameters)
if err != nil {
logger.Errorf("query err => %v", err)
return []model.NeInfo{}
func (r NeInfo) SelectByIds(ids []string) []model.NeInfo {
rows := []model.NeInfo{}
if len(ids) <= 0 {
return rows
}
// 转换实体
return r.convertResultRows(results)
}
// CheckUniqueNeTypeAndNeId 校验同类型下标识是否唯一
func (r *NeInfo) CheckUniqueNeTypeAndNeId(neInfo model.NeInfo) string {
// 查询条件拼接
var conditions []string
var params []any
if neInfo.NeType != "" {
conditions = append(conditions, "ne_type = ?")
params = append(params, neInfo.NeType)
}
if neInfo.NeId != "" {
conditions = append(conditions, "ne_id = ?")
params = append(params, neInfo.NeId)
}
// 构建查询条件语句
whereSql := ""
if len(conditions) > 0 {
whereSql += " where " + strings.Join(conditions, " and ")
} else {
return ""
}
tx := datasource.DB("").Model(&model.NeInfo{})
// 构建查询条件
tx = tx.Where("id in ?", ids)
// 查询数据
querySql := "select id as 'str' from ne_info " + 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 *NeInfo) Insert(neInfo model.NeInfo) string {
// 参数拼接
params := make(map[string]any)
if neInfo.NeType != "" {
params["ne_type"] = neInfo.NeType
}
if neInfo.NeId != "" {
params["ne_id"] = neInfo.NeId
}
if neInfo.RmUID != "" {
params["rm_uid"] = neInfo.RmUID
}
if neInfo.NeName != "" {
params["ne_name"] = neInfo.NeName
}
if neInfo.IP != "" {
params["ip"] = neInfo.IP
}
if neInfo.Port > 0 {
params["port"] = neInfo.Port
}
if neInfo.PvFlag != "" {
params["pv_flag"] = neInfo.PvFlag
}
if neInfo.Province != "" {
params["province"] = neInfo.Province
}
if neInfo.VendorName != "" {
params["vendor_name"] = neInfo.VendorName
}
if neInfo.Dn != "" {
params["dn"] = neInfo.Dn
}
if neInfo.NeAddress != "" {
params["ne_address"] = neInfo.NeAddress
}
if neInfo.HostIDs != "" {
params["host_ids"] = neInfo.HostIDs
}
if neInfo.Status != "" {
params["status"] = neInfo.Status
}
if neInfo.Remark != "" {
params["remark"] = neInfo.Remark
}
if neInfo.CreateBy != "" {
params["create_by"] = neInfo.CreateBy
params["create_time"] = time.Now().UnixMilli()
}
// 构建执行语句
keys, placeholder, values := repo.KeyPlaceholderValueByInsert(params)
sql := "insert into ne_info (" + 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 *NeInfo) Update(neInfo model.NeInfo) int64 {
// 参数拼接
params := make(map[string]any)
if neInfo.NeType != "" {
params["ne_type"] = neInfo.NeType
}
if neInfo.NeId != "" {
params["ne_id"] = neInfo.NeId
}
if neInfo.RmUID != "" {
params["rm_uid"] = neInfo.RmUID
}
if neInfo.NeName != "" {
params["ne_name"] = neInfo.NeName
}
if neInfo.IP != "" {
params["ip"] = neInfo.IP
}
if neInfo.Port > 0 {
params["port"] = neInfo.Port
}
if neInfo.PvFlag != "" {
params["pv_flag"] = neInfo.PvFlag
}
params["province"] = neInfo.Province
params["vendor_name"] = neInfo.VendorName
params["dn"] = neInfo.Dn
params["ne_address"] = neInfo.NeAddress
if neInfo.HostIDs != "" {
params["host_ids"] = neInfo.HostIDs
}
params["remark"] = neInfo.Remark
if neInfo.Status != "" {
params["status"] = neInfo.Status
}
if neInfo.UpdateBy != "" {
params["update_by"] = neInfo.UpdateBy
params["update_time"] = time.Now().UnixMilli()
}
// 构建执行语句
keys, values := repo.KeyValueByUpdate(params)
sql := "update ne_info set " + strings.Join(keys, ",") + " where id = ?"
// 执行更新
values = append(values, neInfo.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 *NeInfo) DeleteByIds(infoIds []string) int64 {
placeholder := repo.KeyPlaceholderByQuery(len(infoIds))
sql := "delete from ne_info where id in (" + placeholder + ")"
parameters := repo.ConvertIdsSlice(infoIds)
results, err := datasource.ExecDB("", sql, parameters)
if err != nil {
logger.Errorf("delete err => %v", err)
// CheckUniqueNeTypeAndNeId 校验同类型下标识是否唯一
func (r NeInfo) CheckUniqueNeTypeAndNeId(neInfo model.NeInfo) string {
tx := datasource.DB("").Model(&model.NeInfo{})
// 查询条件拼接
if neInfo.NeType != "" {
tx = tx.Where("ne_type = ?", neInfo.NeType)
}
if neInfo.NeId != "" {
tx = tx.Where("ne_id = ?", neInfo.NeType)
}
// 查询数据
id := ""
if err := tx.Limit(1).Select("id").Find(&id).Error; err != nil {
logger.Errorf("query find err => %v", err.Error())
return id
}
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 == "" {
return 0
}
return results
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 = tx.Where("id = ?", id)
// 执行更新
if err := tx.UpdateColumn("status", status).Error; err != nil {
logger.Errorf("update err => %v", err.Error())
return 0
}
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

@@ -135,16 +135,15 @@ func (r *NeInfo) SelectNeInfoByRmuid(rmUid string) model.NeInfo {
// SelectPage 根据条件分页查询
//
// bandStatus 带状态信息
func (r *NeInfo) SelectPage(query map[string]any, bandStatus bool) map[string]any {
data := r.neInfoRepository.SelectPage(query)
func (r *NeInfo) SelectPage(query map[string]string, bandStatus bool) ([]model.NeInfo, int64) {
rows, total := r.neInfoRepository.SelectByPage(query)
// 网元直连读取网元服务状态
if bandStatus {
rows := data["rows"].([]model.NeInfo)
r.bandNeStatus(&rows)
}
return data
return rows, total
}
// SelectList 查询列表
@@ -180,23 +179,24 @@ func (r *NeInfo) bandNeStatus(arr *[]model.NeInfo) {
if v.Status != "0" {
v.Status = "0"
(*arr)[i].Status = v.Status
r.neInfoRepository.Update(v)
r.neInfoRepository.UpdateState(v.ID, v.Status)
}
continue
}
result["online"] = true
(*arr)[i].ServerState = result
// 网元状态设置为在线
if v.Status != "1" {
// 下发网管配置信息给网元
_, err = neFetchlink.NeConfigOMC(v)
if err == nil {
v.Status = "1"
} else {
v.Status = "2"
}
(*arr)[i].Status = v.Status
r.neInfoRepository.Update(v)
status := "1"
if parse.Boolean(result["standby"]) {
status = "3"
}
// 下发网管配置信息给网元
if _, err = neFetchlink.NeConfigOMC(v); err != nil {
status = "2"
}
(*arr)[i].Status = status
if v.Status != status {
r.neInfoRepository.UpdateState(v.ID, status)
}
}
}