feat: 网元状态3待机判断standby

This commit is contained in:
TsMask
2025-01-10 18:44:12 +08:00
parent 18eef7093f
commit 7939e78a38
6 changed files with 225 additions and 395 deletions

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 {
// 下发网管配置信息给网元
_, err = neFetchlink.NeConfigOMC(body)
if err == nil {
// 网元状态设置为在线
body.Status = "1"
} else {
if parse.Boolean(body.ServerState["standby"]) {
body.Status = "3"
}
// 下发网管配置信息给网元
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 {
// 下发网管配置信息给网元
_, err = neFetchlink.NeConfigOMC(body)
if err == nil {
// 网元状态设置为在线
body.Status = "1"
} else {
if parse.Boolean(body.ServerState["standby"]) {
body.Status = "3"
}
// 下发网管配置信息给网元
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,19 +1,23 @@
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"
)
// 实例化数据层 NeInfo 结构体
var NewNeInfo = &NeInfo{}
// NeInfo 网元信息表 数据层处理
type NeInfo struct{}
// neListSort 网元列表预设排序
var neListSort = []string{
func (r NeInfo) neListSort(arr []model.NeInfo) []model.NeInfo {
// neListSort 网元列表预设排序
var list = []string{
"OMC",
"IMS",
"AMF",
@@ -36,59 +40,11 @@ var neListSort = []string{
"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",
},
}
// NeInfo 网元信息表 数据层处理
type NeInfo struct {
// 查询视图对象SQL
selectSql string
// 结果字段与实体映射
resultMap map[string]string
}
// 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)
}
// 创建优先级映射
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)
}
// 转换实体
return r.convertResultRows(results)
}
// 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{}
}
// 转换实体
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 ""
}
// 查询数据
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
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 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)
// 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{})
// 构建查询条件
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
}
// 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"
status := "1"
if parse.Boolean(result["standby"]) {
status = "3"
}
(*arr)[i].Status = v.Status
r.neInfoRepository.Update(v)
// 下发网管配置信息给网元
if _, err = neFetchlink.NeConfigOMC(v); err != nil {
status = "2"
}
(*arr)[i].Status = status
if v.Status != status {
r.neInfoRepository.UpdateState(v.ID, status)
}
}
}