Files
EdgeAPI/internal/db/models/server_dao.go

2611 lines
67 KiB
Go
Raw Normal View History

2020-07-22 22:17:53 +08:00
package models
import (
2020-09-15 14:44:11 +08:00
"encoding/json"
2020-07-29 19:02:28 +08:00
"errors"
2022-03-29 21:24:31 +08:00
teaconst "github.com/TeaOSLab/EdgeAPI/internal/const"
"github.com/TeaOSLab/EdgeAPI/internal/db/models/dns"
dbutils "github.com/TeaOSLab/EdgeAPI/internal/db/utils"
2021-11-11 14:16:42 +08:00
"github.com/TeaOSLab/EdgeAPI/internal/utils"
"github.com/TeaOSLab/EdgeAPI/internal/utils/numberutils"
"github.com/TeaOSLab/EdgeCommon/pkg/configutils"
2021-08-08 15:47:48 +08:00
"github.com/TeaOSLab/EdgeCommon/pkg/nodeconfigs"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
2020-09-13 20:37:28 +08:00
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
2020-07-22 22:17:53 +08:00
_ "github.com/go-sql-driver/mysql"
"github.com/iwind/TeaGo/Tea"
"github.com/iwind/TeaGo/dbs"
"github.com/iwind/TeaGo/lists"
"github.com/iwind/TeaGo/maps"
2020-11-11 21:32:25 +08:00
"github.com/iwind/TeaGo/rands"
2020-07-29 19:02:28 +08:00
"github.com/iwind/TeaGo/types"
timeutil "github.com/iwind/TeaGo/utils/time"
2021-06-25 11:05:02 +08:00
"regexp"
2020-09-30 17:46:43 +08:00
"strconv"
"strings"
"time"
2020-07-22 22:17:53 +08:00
)
const (
ServerStateEnabled = 1 // 已启用
ServerStateDisabled = 0 // 已禁用
)
type ServerDAO dbs.DAO
func NewServerDAO() *ServerDAO {
return dbs.NewDAO(&ServerDAO{
DAOObject: dbs.DAOObject{
DB: Tea.Env,
Table: "edgeServers",
Model: new(Server),
PkName: "id",
},
}).(*ServerDAO)
}
2020-10-13 20:05:13 +08:00
var SharedServerDAO *ServerDAO
func init() {
dbs.OnReady(func() {
SharedServerDAO = NewServerDAO()
})
}
2020-07-22 22:17:53 +08:00
2021-05-03 15:16:02 +08:00
// Init 初始化
2020-09-26 08:06:40 +08:00
func (this *ServerDAO) Init() {
_ = this.DAOObject.Init()
2020-09-26 08:06:40 +08:00
// 这里不处理增删改事件是为了避免Server修改本身的时候也要触发别的Server变更
}
2021-05-03 15:16:02 +08:00
// EnableServer 启用条目
func (this *ServerDAO) EnableServer(tx *dbs.Tx, id uint32) (rowsAffected int64, err error) {
return this.Query(tx).
2020-07-22 22:17:53 +08:00
Pk(id).
Set("state", ServerStateEnabled).
Update()
}
2021-05-03 15:16:02 +08:00
// DisableServer 禁用条目
2021-01-27 23:00:02 +08:00
func (this *ServerDAO) DisableServer(tx *dbs.Tx, serverId int64) (err error) {
_, err = this.Query(tx).
2021-01-27 23:00:02 +08:00
Pk(serverId).
2020-07-22 22:17:53 +08:00
Set("state", ServerStateDisabled).
Update()
if err != nil {
return err
}
// 删除对应的操作
err = this.NotifyDisable(tx, serverId)
if err != nil {
return err
}
2021-01-27 23:00:02 +08:00
err = this.NotifyUpdate(tx, serverId)
if err != nil {
return err
}
err = this.NotifyDNSUpdate(tx, serverId)
if err != nil {
return err
}
return nil
2020-07-22 22:17:53 +08:00
}
2021-05-03 15:16:02 +08:00
// FindEnabledServer 查找启用中的服务
func (this *ServerDAO) FindEnabledServer(tx *dbs.Tx, serverId int64) (*Server, error) {
result, err := this.Query(tx).
Pk(serverId).
2020-07-22 22:17:53 +08:00
Attr("state", ServerStateEnabled).
Find()
if result == nil {
return nil, err
}
return result.(*Server), err
}
2020-07-29 19:02:28 +08:00
2021-05-03 15:16:02 +08:00
// FindEnabledServerName 查找服务名称
2021-01-27 23:00:02 +08:00
func (this *ServerDAO) FindEnabledServerName(tx *dbs.Tx, serverId int64) (string, error) {
return this.Query(tx).
Pk(serverId).
State(ServerStateEnabled).
Result("name").
FindStringCol("")
}
2021-05-03 15:16:02 +08:00
// FindEnabledServerBasic 查找服务基本信息
func (this *ServerDAO) FindEnabledServerBasic(tx *dbs.Tx, serverId int64) (*Server, error) {
result, err := this.Query(tx).
Pk(serverId).
State(ServerStateEnabled).
Result("id", "name", "description", "isOn", "type", "clusterId").
Find()
if result == nil {
return nil, err
}
return result.(*Server), err
}
2021-05-03 15:16:02 +08:00
// FindEnabledServerType 查找服务类型
func (this *ServerDAO) FindEnabledServerType(tx *dbs.Tx, serverId int64) (string, error) {
return this.Query(tx).
2020-09-15 14:44:11 +08:00
Pk(serverId).
Result("type").
FindStringCol("")
}
2021-05-03 15:16:02 +08:00
// CreateServer 创建服务
func (this *ServerDAO) CreateServer(tx *dbs.Tx,
adminId int64,
userId int64,
serverType serverconfigs.ServerType,
name string,
description string,
serverNamesJSON []byte,
isAuditing bool,
auditingServerNamesJSON []byte,
httpJSON []byte,
httpsJSON []byte,
tcpJSON []byte,
tlsJSON []byte,
unixJSON []byte,
udpJSON []byte,
webId int64,
reverseProxyJSON []byte,
clusterId int64,
includeNodesJSON []byte,
excludeNodesJSON []byte,
2021-11-09 15:36:25 +08:00
groupIds []int64,
userPlanId int64) (serverId int64, err error) {
var op = NewServerOperator()
2020-07-29 19:02:28 +08:00
op.UserId = userId
op.AdminId = adminId
2020-09-13 20:37:28 +08:00
op.Name = name
op.Type = serverType
op.Description = description
2020-09-15 14:44:11 +08:00
if IsNotNull(serverNamesJSON) {
var serverNames = []*serverconfigs.ServerNameConfig{}
err := json.Unmarshal(serverNamesJSON, &serverNames)
if err != nil {
return 0, err
}
2020-09-15 14:44:11 +08:00
op.ServerNames = serverNamesJSON
plainServerNamesJSON, err := json.Marshal(serverconfigs.PlainServerNames(serverNames))
if err != nil {
return 0, err
}
op.PlainServerNames = plainServerNamesJSON
2020-09-15 14:44:11 +08:00
}
op.IsAuditing = isAuditing
op.AuditingAt = time.Now().Unix()
if len(auditingServerNamesJSON) > 0 {
op.AuditingServerNames = auditingServerNamesJSON
}
2020-09-21 11:37:17 +08:00
if IsNotNull(httpJSON) {
2020-09-15 14:44:11 +08:00
op.Http = httpJSON
}
2020-09-21 11:37:17 +08:00
if IsNotNull(httpsJSON) {
2020-09-15 14:44:11 +08:00
op.Https = httpsJSON
}
2020-09-21 11:37:17 +08:00
if IsNotNull(tcpJSON) {
2020-09-15 14:44:11 +08:00
op.Tcp = tcpJSON
}
2020-09-21 11:37:17 +08:00
if IsNotNull(tlsJSON) {
2020-09-15 14:44:11 +08:00
op.Tls = tlsJSON
}
2020-09-21 11:37:17 +08:00
if IsNotNull(unixJSON) {
2020-09-15 14:44:11 +08:00
op.Unix = unixJSON
}
2020-09-21 11:37:17 +08:00
if IsNotNull(udpJSON) {
2020-09-15 14:44:11 +08:00
op.Udp = udpJSON
2020-07-29 19:02:28 +08:00
}
2020-09-15 14:44:11 +08:00
op.WebId = webId
if IsNotNull(reverseProxyJSON) {
2020-09-21 11:37:17 +08:00
op.ReverseProxy = reverseProxyJSON
}
2020-09-15 14:44:11 +08:00
op.ClusterId = clusterId
if IsNotNull(includeNodesJSON) {
2020-07-29 19:02:28 +08:00
op.IncludeNodes = includeNodesJSON
}
if IsNotNull(excludeNodesJSON) {
2020-07-29 19:02:28 +08:00
op.ExcludeNodes = excludeNodesJSON
}
2020-09-27 18:41:15 +08:00
2020-10-29 21:37:56 +08:00
if len(groupIds) == 0 {
op.GroupIds = "[]"
} else {
groupIdsJSON, err := json.Marshal(groupIds)
if err != nil {
return 0, err
}
op.GroupIds = groupIdsJSON
}
2021-01-27 23:00:02 +08:00
dnsName, err := this.GenDNSName(tx)
2020-11-11 21:32:25 +08:00
if err != nil {
return 0, err
}
op.DnsName = dnsName
2021-11-09 15:36:25 +08:00
op.UserPlanId = userPlanId
2022-01-23 19:16:52 +08:00
op.LastUserPlanId = userPlanId
2021-11-09 15:36:25 +08:00
2020-07-29 19:02:28 +08:00
op.Version = 1
op.IsOn = 1
op.State = ServerStateEnabled
err = this.Save(tx, op)
2020-09-15 14:44:11 +08:00
if err != nil {
return 0, err
}
serverId = types.Int64(op.Id)
2020-09-26 11:21:43 +08:00
2021-10-10 16:29:50 +08:00
// 更新端口
err = this.NotifyServerPortsUpdate(tx, serverId)
if err != nil {
return serverId, err
}
2021-01-27 23:00:02 +08:00
// 通知配置更改
err = this.NotifyUpdate(tx, serverId)
2020-10-01 16:01:17 +08:00
if err != nil {
return 0, err
2020-09-26 11:21:43 +08:00
}
2021-01-27 23:00:02 +08:00
// 通知DNS更改
err = this.NotifyDNSUpdate(tx, serverId)
if err != nil {
return 0, err
}
2020-09-26 08:06:40 +08:00
return serverId, nil
2020-07-29 19:02:28 +08:00
}
2021-05-03 15:16:02 +08:00
// UpdateServerBasic 修改服务基本信息
func (this *ServerDAO) UpdateServerBasic(tx *dbs.Tx, serverId int64, name string, description string, clusterId int64, keepOldConfigs bool, isOn bool, groupIds []int64) error {
2020-07-29 19:02:28 +08:00
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
}
// 老的集群ID
oldClusterId, err := this.Query(tx).
Pk(serverId).
Result("clusterId").
FindInt64Col(0)
if err != nil {
return err
}
var op = NewServerOperator()
2020-07-29 19:02:28 +08:00
op.Id = serverId
2020-09-13 20:37:28 +08:00
op.Name = name
op.Description = description
2020-07-29 19:02:28 +08:00
op.ClusterId = clusterId
2020-09-28 16:25:39 +08:00
op.IsOn = isOn
2020-10-29 21:37:56 +08:00
if len(groupIds) == 0 {
op.GroupIds = "[]"
} else {
groupIdsJSON, err := json.Marshal(groupIds)
if err != nil {
return err
}
op.GroupIds = groupIdsJSON
}
err = this.Save(tx, op)
2020-09-26 08:06:40 +08:00
if err != nil {
return err
}
// 通知更新
err = this.NotifyUpdate(tx, serverId)
2020-09-28 16:25:39 +08:00
if err != nil {
return err
}
2021-01-27 23:00:02 +08:00
// 因为可能有isOn的原因所以需要修改
err = this.NotifyDNSUpdate(tx, serverId)
if err != nil {
return err
}
if clusterId != oldClusterId {
// 服务配置更新
if !keepOldConfigs {
err = this.NotifyClusterUpdate(tx, oldClusterId, serverId)
if err != nil {
return err
}
}
// DNS更新
// 这里不受 keepOldConfigs 的限制
err = this.NotifyClusterDNSUpdate(tx, oldClusterId, serverId)
if err != nil {
return err
}
}
return nil
2020-07-29 19:02:28 +08:00
}
2022-06-25 19:21:46 +08:00
// UpdateServerGroupIds 修改服务所在分组
func (this *ServerDAO) UpdateServerGroupIds(tx *dbs.Tx, serverId int64, groupIds []int64) error {
if groupIds == nil {
groupIds = []int64{}
}
groupIdsJSON, err := json.Marshal(groupIds)
if err != nil {
return err
}
err = this.Query(tx).
Pk(serverId).
Set("groupIds", groupIdsJSON).
UpdateQuickly()
if err != nil {
return err
}
return this.NotifyUpdate(tx, serverId)
}
2021-05-03 15:16:02 +08:00
// UpdateUserServerBasic 设置用户相关的基本信息
func (this *ServerDAO) UpdateUserServerBasic(tx *dbs.Tx, serverId int64, name string) error {
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
}
2022-06-25 19:21:46 +08:00
var op = NewServerOperator()
op.Id = serverId
op.Name = name
err := this.Save(tx, op)
if err != nil {
return err
}
return this.NotifyUpdate(tx, serverId)
}
2021-05-03 15:16:02 +08:00
// UpdateServerIsOn 修复服务是否启用
func (this *ServerDAO) UpdateServerIsOn(tx *dbs.Tx, serverId int64, isOn bool) error {
_, err := this.Query(tx).
Pk(serverId).
Set("isOn", isOn).
Update()
if err != nil {
return err
}
err = this.NotifyUpdate(tx, serverId)
if err != nil {
return err
}
return nil
}
2021-05-03 15:16:02 +08:00
// UpdateServerHTTP 修改HTTP配置
func (this *ServerDAO) UpdateServerHTTP(tx *dbs.Tx, serverId int64, config []byte) error {
2020-09-15 14:44:11 +08:00
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
}
if len(config) == 0 {
config = []byte("null")
}
_, err := this.Query(tx).
2020-09-15 14:44:11 +08:00
Pk(serverId).
Set("http", string(config)).
Update()
if err != nil {
return err
}
2020-09-26 08:06:40 +08:00
2021-10-10 16:29:50 +08:00
// 更新端口
err = this.NotifyServerPortsUpdate(tx, serverId)
if err != nil {
return err
}
return this.NotifyUpdate(tx, serverId)
2020-09-15 14:44:11 +08:00
}
2021-05-03 15:16:02 +08:00
// UpdateServerHTTPS 修改HTTPS配置
func (this *ServerDAO) UpdateServerHTTPS(tx *dbs.Tx, serverId int64, httpsJSON []byte) error {
2020-09-15 14:44:11 +08:00
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
}
2020-10-01 16:01:17 +08:00
if len(httpsJSON) == 0 {
httpsJSON = []byte("null")
2020-09-15 14:44:11 +08:00
}
_, err := this.Query(tx).
2020-09-15 14:44:11 +08:00
Pk(serverId).
2020-10-01 16:01:17 +08:00
Set("https", string(httpsJSON)).
2020-09-15 14:44:11 +08:00
Update()
if err != nil {
return err
}
2020-09-26 08:06:40 +08:00
2021-10-10 16:29:50 +08:00
// 更新端口
err = this.NotifyServerPortsUpdate(tx, serverId)
if err != nil {
return err
}
return this.NotifyUpdate(tx, serverId)
2020-09-15 14:44:11 +08:00
}
2021-05-03 15:16:02 +08:00
// UpdateServerTCP 修改TCP配置
func (this *ServerDAO) UpdateServerTCP(tx *dbs.Tx, serverId int64, config []byte) error {
2020-09-15 14:44:11 +08:00
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
}
if len(config) == 0 {
config = []byte("null")
}
_, err := this.Query(tx).
2020-09-15 14:44:11 +08:00
Pk(serverId).
Set("tcp", string(config)).
Update()
if err != nil {
return err
}
2020-09-26 08:06:40 +08:00
2021-10-10 16:29:50 +08:00
// 更新端口
err = this.NotifyServerPortsUpdate(tx, serverId)
if err != nil {
return err
}
return this.NotifyUpdate(tx, serverId)
2020-09-15 14:44:11 +08:00
}
2021-05-03 15:16:02 +08:00
// UpdateServerTLS 修改TLS配置
func (this *ServerDAO) UpdateServerTLS(tx *dbs.Tx, serverId int64, config []byte) error {
2020-09-15 14:44:11 +08:00
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
}
if len(config) == 0 {
config = []byte("null")
}
_, err := this.Query(tx).
2020-09-15 14:44:11 +08:00
Pk(serverId).
Set("tls", string(config)).
Update()
if err != nil {
return err
}
2020-09-26 08:06:40 +08:00
2021-10-10 16:29:50 +08:00
// 更新端口
err = this.NotifyServerPortsUpdate(tx, serverId)
if err != nil {
return err
}
return this.NotifyUpdate(tx, serverId)
2020-09-15 14:44:11 +08:00
}
2021-05-03 15:16:02 +08:00
// UpdateServerUnix 修改Unix配置
func (this *ServerDAO) UpdateServerUnix(tx *dbs.Tx, serverId int64, config []byte) error {
2020-09-15 14:44:11 +08:00
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
}
if len(config) == 0 {
config = []byte("null")
}
_, err := this.Query(tx).
2020-09-15 14:44:11 +08:00
Pk(serverId).
Set("unix", string(config)).
Update()
if err != nil {
return err
}
2020-09-26 08:06:40 +08:00
return this.NotifyUpdate(tx, serverId)
2020-09-15 14:44:11 +08:00
}
2021-05-03 15:16:02 +08:00
// UpdateServerUDP 修改UDP配置
func (this *ServerDAO) UpdateServerUDP(tx *dbs.Tx, serverId int64, config []byte) error {
2020-09-15 14:44:11 +08:00
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
}
if len(config) == 0 {
config = []byte("null")
}
_, err := this.Query(tx).
2020-09-15 14:44:11 +08:00
Pk(serverId).
Set("udp", string(config)).
Update()
if err != nil {
return err
}
2020-09-26 08:06:40 +08:00
2021-10-10 16:29:50 +08:00
// 更新端口
err = this.NotifyServerPortsUpdate(tx, serverId)
if err != nil {
return err
}
return this.NotifyUpdate(tx, serverId)
2020-09-15 14:44:11 +08:00
}
2021-05-03 15:16:02 +08:00
// UpdateServerWeb 修改Web配置
func (this *ServerDAO) UpdateServerWeb(tx *dbs.Tx, serverId int64, webId int64) error {
2020-09-15 14:44:11 +08:00
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
}
_, err := this.Query(tx).
2020-09-15 14:44:11 +08:00
Pk(serverId).
Set("webId", webId).
Update()
if err != nil {
return err
}
return this.NotifyUpdate(tx, serverId)
2020-09-15 14:44:11 +08:00
}
// UpdateServerDNS 修改DNS设置
func (this *ServerDAO) UpdateServerDNS(tx *dbs.Tx, serverId int64, supportCNAME bool) error {
if serverId <= 0 {
return errors.New("invalid serverId")
}
var op = NewServerOperator()
op.Id = serverId
op.SupportCNAME = supportCNAME
err := this.Save(tx, op)
if err != nil {
return err
}
return this.NotifyUpdate(tx, serverId)
}
2021-05-03 15:16:02 +08:00
// InitServerWeb 初始化Web配置
func (this *ServerDAO) InitServerWeb(tx *dbs.Tx, serverId int64) (int64, error) {
2020-09-16 09:09:21 +08:00
if serverId <= 0 {
return 0, errors.New("invalid serverId")
2020-09-16 09:09:21 +08:00
}
adminId, userId, err := this.FindServerAdminIdAndUserId(tx, serverId)
2020-12-18 21:18:53 +08:00
if err != nil {
return 0, err
}
webId, err := SharedHTTPWebDAO.CreateWeb(tx, adminId, userId, nil)
2020-09-16 09:09:21 +08:00
if err != nil {
return 0, err
}
_, err = this.Query(tx).
2020-09-16 09:09:21 +08:00
Pk(serverId).
Set("webId", webId).
Update()
if err != nil {
return 0, err
}
err = this.NotifyUpdate(tx, serverId)
2020-09-26 08:06:40 +08:00
if err != nil {
return webId, err
}
2020-09-16 09:09:21 +08:00
return webId, nil
}
2021-05-03 15:16:02 +08:00
// FindServerServerNames 查找ServerNames配置
func (this *ServerDAO) FindServerServerNames(tx *dbs.Tx, serverId int64) (serverNamesJSON []byte, isAuditing bool, auditingAt int64, auditingServerNamesJSON []byte, auditingResultJSON []byte, err error) {
if serverId <= 0 {
return
}
one, err := this.Query(tx).
Pk(serverId).
Result("serverNames", "isAuditing", "auditingAt", "auditingServerNames", "auditingResult").
Find()
if err != nil {
return nil, false, 0, nil, nil, err
}
if one == nil {
return
}
server := one.(*Server)
2022-03-22 22:11:32 +08:00
return server.ServerNames, server.IsAuditing, int64(server.AuditingAt), server.AuditingServerNames, server.AuditingResult, nil
}
2021-05-03 15:16:02 +08:00
// UpdateServerNames 修改ServerNames配置
func (this *ServerDAO) UpdateServerNames(tx *dbs.Tx, serverId int64, serverNamesJSON []byte) error {
2020-09-15 14:44:11 +08:00
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
}
op := NewServerOperator()
op.Id = serverId
if IsNull(serverNamesJSON) {
serverNamesJSON = []byte("[]")
} else {
var serverNames = []*serverconfigs.ServerNameConfig{}
err := json.Unmarshal(serverNamesJSON, &serverNames)
if err != nil {
return err
}
op.ServerNames = serverNamesJSON
plainServerNamesJSON, err := json.Marshal(serverconfigs.PlainServerNames(serverNames))
if err != nil {
return err
}
op.PlainServerNames = plainServerNamesJSON
2020-09-15 14:44:11 +08:00
}
op.ServerNames = serverNamesJSON
err := this.Save(tx, op)
2020-12-23 09:52:50 +08:00
if err != nil {
return err
}
return this.NotifyUpdate(tx, serverId)
}
2021-05-03 15:16:02 +08:00
// UpdateAuditingServerNames 修改域名审核
func (this *ServerDAO) UpdateAuditingServerNames(tx *dbs.Tx, serverId int64, isAuditing bool, auditingServerNamesJSON []byte) error {
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
}
op := NewServerOperator()
op.Id = serverId
op.IsAuditing = isAuditing
if isAuditing {
op.AuditingAt = time.Now().Unix()
}
if IsNull(auditingServerNamesJSON) {
op.AuditingServerNames = "[]"
} else {
op.AuditingServerNames = auditingServerNamesJSON
}
2020-12-23 09:52:50 +08:00
op.AuditingResult = `{"isOk":true}`
err := this.Save(tx, op)
2020-12-23 09:52:50 +08:00
if err != nil {
return err
}
return this.NotifyUpdate(tx, serverId)
}
2021-05-03 15:16:02 +08:00
// UpdateServerAuditing 修改域名审核结果
func (this *ServerDAO) UpdateServerAuditing(tx *dbs.Tx, serverId int64, result *pb.ServerNameAuditingResult) error {
if serverId <= 0 {
return errors.New("invalid serverId")
}
resultJSON, err := json.Marshal(maps.Map{
"isOk": result.IsOk,
"reason": result.Reason,
"createdAt": time.Now().Unix(),
})
2020-09-15 14:44:11 +08:00
if err != nil {
return err
}
2020-09-26 08:06:40 +08:00
auditingServerNamesJSON, err := this.Query(tx).
Pk(serverId).
Result("auditingServerNames").
FindJSONCol()
if err != nil {
return err
}
var op = NewServerOperator()
op.Id = serverId
op.IsAuditing = false
op.AuditingResult = resultJSON
if result.IsOk {
op.ServerNames = dbs.SQL("auditingServerNames")
if IsNotNull(auditingServerNamesJSON) {
var serverNames = []*serverconfigs.ServerNameConfig{}
err := json.Unmarshal(auditingServerNamesJSON, &serverNames)
if err != nil {
return err
}
plainServerNamesJSON, err := json.Marshal(serverconfigs.PlainServerNames(serverNames))
if err != nil {
return err
}
op.PlainServerNames = plainServerNamesJSON
} else {
op.PlainServerNames = "[]"
}
}
err = this.Save(tx, op)
if err != nil {
return err
}
2021-01-27 23:00:02 +08:00
err = this.NotifyUpdate(tx, serverId)
if err != nil {
return err
}
return this.NotifyDNSUpdate(tx, serverId)
2020-09-15 14:44:11 +08:00
}
2021-05-03 15:16:02 +08:00
// UpdateServerReverseProxy 修改反向代理配置
func (this *ServerDAO) UpdateServerReverseProxy(tx *dbs.Tx, serverId int64, config []byte) error {
2020-09-15 14:44:11 +08:00
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
}
2020-09-21 11:37:17 +08:00
op := NewServerOperator()
op.Id = serverId
op.ReverseProxy = JSONBytes(config)
err := this.Save(tx, op)
2020-09-15 14:44:11 +08:00
if err != nil {
return err
}
2020-09-26 08:06:40 +08:00
return this.NotifyUpdate(tx, serverId)
2020-09-15 14:44:11 +08:00
}
2021-05-03 15:16:02 +08:00
// CountAllEnabledServers 计算所有可用服务数量
func (this *ServerDAO) CountAllEnabledServers(tx *dbs.Tx) (int64, error) {
return this.Query(tx).
State(ServerStateEnabled).
Count()
}
2021-05-03 15:16:02 +08:00
// CountAllEnabledServersMatch 计算所有可用服务数量
// 参数:
// groupId 分组ID如果为-1则搜索没有分组的服务
func (this *ServerDAO) CountAllEnabledServersMatch(tx *dbs.Tx, groupId int64, keyword string, userId int64, clusterId int64, auditingFlag configutils.BoolState, protocolFamilies []string) (int64, error) {
query := this.Query(tx).
2020-10-31 15:21:29 +08:00
State(ServerStateEnabled)
if groupId > 0 {
query.Where("JSON_CONTAINS(groupIds, :groupId)").
Param("groupId", numberutils.FormatInt64(groupId))
} else if groupId < 0 { // 特殊的groupId
query.Where("JSON_LENGTH(groupIds)=0")
2020-10-31 15:21:29 +08:00
}
if len(keyword) > 0 {
2021-06-25 11:05:02 +08:00
if regexp.MustCompile(`^\d+$`).MatchString(keyword) {
2022-07-17 11:43:23 +08:00
query.Where("(id=:serverId OR name LIKE :keyword OR serverNames LIKE :keyword OR JSON_CONTAINS(http, :portRange, '$.listen') OR JSON_CONTAINS(https, :portRange, '$.listen') OR JSON_CONTAINS(tcp, :portRange, '$.listen') OR JSON_CONTAINS(tls, :portRange, '$.listen'))").
2021-06-25 11:05:02 +08:00
Param("portRange", maps.Map{"portRange": keyword}.AsJSON()).
2022-07-17 11:43:23 +08:00
Param("serverId", keyword).
Param("keyword", dbutils.QuoteLike(keyword))
2021-06-25 11:05:02 +08:00
} else {
query.Where("(name LIKE :keyword OR serverNames LIKE :keyword)").
Param("keyword", dbutils.QuoteLike(keyword))
2021-06-25 11:05:02 +08:00
}
2020-10-31 15:21:29 +08:00
}
2020-12-18 21:18:53 +08:00
if userId > 0 {
2020-12-15 16:53:31 +08:00
query.Attr("userId", userId)
}
if clusterId > 0 {
query.Attr("clusterId", clusterId)
}
if auditingFlag == configutils.BoolStateYes {
query.Attr("isAuditing", true)
}
var protocolConds = []string{}
for _, family := range protocolFamilies {
switch family {
case "http":
protocolConds = append(protocolConds, "(http IS NOT NULL OR https IS NOT NULL)")
case "tcp":
protocolConds = append(protocolConds, "(tcp IS NOT NULL OR tls IS NOT NULL)")
case "udp":
protocolConds = append(protocolConds, "(udp IS NOT NULL)")
}
}
if len(protocolConds) > 0 {
query.Where("(" + strings.Join(protocolConds, " OR ") + ")")
}
2020-10-31 15:21:29 +08:00
return query.Count()
2020-07-29 19:02:28 +08:00
}
2021-05-03 15:16:02 +08:00
// ListEnabledServersMatch 列出单页的服务
// 参数:
// groupId 分组ID如果为-1则搜索没有分组的服务
2022-04-15 12:14:59 +08:00
func (this *ServerDAO) ListEnabledServersMatch(tx *dbs.Tx, offset int64, size int64, groupId int64, keyword string, userId int64, clusterId int64, auditingFlag int32, protocolFamilies []string, order string) (result []*Server, err error) {
query := this.Query(tx).
2020-07-29 19:02:28 +08:00
State(ServerStateEnabled).
Offset(offset).
Limit(size).
2020-10-31 15:21:29 +08:00
Slice(&result)
if groupId > 0 {
query.Where("JSON_CONTAINS(groupIds, :groupId)").
Param("groupId", numberutils.FormatInt64(groupId))
} else if groupId < 0 { // 特殊的groupId
query.Where("JSON_LENGTH(groupIds)=0")
2020-10-31 15:21:29 +08:00
}
if len(keyword) > 0 {
2021-06-25 11:05:02 +08:00
if regexp.MustCompile(`^\d+$`).MatchString(keyword) {
2022-07-17 11:43:23 +08:00
query.Where("(id=:serverId OR name LIKE :keyword OR serverNames LIKE :keyword OR JSON_CONTAINS(http, :portRange, '$.listen') OR JSON_CONTAINS(https, :portRange, '$.listen') OR JSON_CONTAINS(tcp, :portRange, '$.listen') OR JSON_CONTAINS(tls, :portRange, '$.listen'))").
Param("portRange", string(maps.Map{"portRange": keyword}.AsJSON())).
2022-07-17 11:43:23 +08:00
Param("serverId", keyword).
Param("keyword", dbutils.QuoteLike(keyword))
2021-06-25 11:05:02 +08:00
} else {
query.Where("(name LIKE :keyword OR serverNames LIKE :keyword)").
Param("keyword", dbutils.QuoteLike(keyword))
2021-06-25 11:05:02 +08:00
}
2020-10-31 15:21:29 +08:00
}
2020-12-18 21:18:53 +08:00
if userId > 0 {
query.Attr("userId", userId)
}
if clusterId > 0 {
query.Attr("clusterId", clusterId)
}
if auditingFlag == 1 {
query.Attr("isAuditing", true)
}
var protocolConds = []string{}
for _, family := range protocolFamilies {
switch family {
case "http":
protocolConds = append(protocolConds, "(http IS NOT NULL OR https IS NOT NULL)")
case "tcp":
protocolConds = append(protocolConds, "(tcp IS NOT NULL OR tls IS NOT NULL)")
case "udp":
protocolConds = append(protocolConds, "(udp IS NOT NULL)")
}
}
if len(protocolConds) > 0 {
query.Where("(" + strings.Join(protocolConds, " OR ") + ")")
}
2020-10-31 15:21:29 +08:00
2022-04-15 12:14:59 +08:00
// 排序
var day = timeutil.Format("Ymd")
var minute = timeutil.FormatTime("His", time.Now().Unix()/300*300-300)
var selfTable = this.Table
var statTable = SharedServerDailyStatDAO.Table
var hasOnlyIds = false
switch order {
case "trafficOutAsc":
query.Result("id")
query.Join(SharedServerDailyStatDAO, dbs.QueryJoinLeft, selfTable+".id="+statTable+".serverId AND "+statTable+".day=:day AND "+statTable+".timeFrom=:minute")
query.Param("day", day)
query.Param("minute", minute)
query.Group(selfTable + ".id")
query.Asc("SUM(" + statTable + ".bytes)").
DescPk()
hasOnlyIds = true
case "trafficOutDesc":
query.Result("id")
query.Join(SharedServerDailyStatDAO, dbs.QueryJoinLeft, selfTable+".id="+statTable+".serverId AND "+statTable+".day=:day AND "+statTable+".timeFrom=:minute")
query.Param("day", day)
query.Param("minute", minute)
query.Group(selfTable + ".id")
query.Desc("SUM(" + statTable + ".bytes)").
DescPk()
hasOnlyIds = true
default:
query.DescPk()
}
2020-10-31 15:21:29 +08:00
_, err = query.FindAll()
2022-04-15 12:14:59 +08:00
if hasOnlyIds {
var newResult = []*Server{}
for _, one := range result {
server, err := this.Find(tx, one.Id)
if err != nil {
return nil, err
}
if server == nil {
continue
}
newResult = append(newResult, server.(*Server))
}
result = newResult
}
2020-07-29 19:02:28 +08:00
return
}
2020-08-21 12:32:33 +08:00
2021-05-03 15:16:02 +08:00
// FindAllEnabledServersWithNode 获取节点中的所有服务
func (this *ServerDAO) FindAllEnabledServersWithNode(tx *dbs.Tx, nodeId int64) (result []*Server, err error) {
2021-07-31 22:23:11 +08:00
// 节点所在主集群
clusterIds, err := SharedNodeDAO.FindEnabledAndOnNodeClusterIds(tx, nodeId)
2020-08-21 12:32:33 +08:00
if err != nil {
return nil, err
}
2021-07-31 22:23:11 +08:00
for _, clusterId := range clusterIds {
ones, err := this.Query(tx).
Attr("clusterId", clusterId).
State(ServerStateEnabled).
AscPk().
FindAll()
if err != nil {
return nil, err
}
for _, one := range ones {
result = append(result, one.(*Server))
}
2020-08-21 12:32:33 +08:00
}
return
}
2021-05-03 15:16:02 +08:00
// FindAllEnabledServerIds 获取所有的服务ID
func (this *ServerDAO) FindAllEnabledServerIds(tx *dbs.Tx) (serverIds []int64, err error) {
ones, err := this.Query(tx).
2020-09-26 08:06:40 +08:00
State(ServerStateEnabled).
AscPk().
ResultPk().
FindAll()
for _, one := range ones {
serverIds = append(serverIds, int64(one.(*Server).Id))
}
return
}
2021-05-03 15:16:02 +08:00
// FindAllEnabledServerIdsWithUserId 获取某个用户的所有的服务ID
func (this *ServerDAO) FindAllEnabledServerIdsWithUserId(tx *dbs.Tx, userId int64) (serverIds []int64, err error) {
ones, err := this.Query(tx).
State(ServerStateEnabled).
Attr("userId", userId).
AscPk().
ResultPk().
FindAll()
for _, one := range ones {
serverIds = append(serverIds, int64(one.(*Server).Id))
}
return
}
// FindAllEnabledServerIdsWithGroupId 获取某个分组下的所有的服务ID
func (this *ServerDAO) FindAllEnabledServerIdsWithGroupId(tx *dbs.Tx, groupId int64) (serverIds []int64, err error) {
ones, err := this.Query(tx).
State(ServerStateEnabled).
Where("JSON_CONTAINS(groupIds, :groupId)").
Param("groupId", numberutils.FormatInt64(groupId)).
AscPk().
ResultPk().
FindAll()
for _, one := range ones {
serverIds = append(serverIds, int64(one.(*Server).Id))
}
return
}
// FindServerGroupIds 获取服务的分组ID
func (this *ServerDAO) FindServerGroupIds(tx *dbs.Tx, serverId int64) ([]int64, error) {
if serverId <= 0 {
return nil, nil
}
groupIdsString, err := this.Query(tx).
Pk(serverId).
Result("groupIds").
FindStringCol("")
if err != nil {
return nil, err
}
if len(groupIdsString) == 0 {
return nil, nil
}
var result = []int64{}
err = json.Unmarshal([]byte(groupIdsString), &result)
if err != nil {
return result, err
}
return result, nil
}
2021-05-03 15:16:02 +08:00
// FindServerNodeFilters 查找服务的搜索条件
func (this *ServerDAO) FindServerNodeFilters(tx *dbs.Tx, serverId int64) (isOk bool, clusterId int64, err error) {
one, err := this.Query(tx).
2020-09-26 08:06:40 +08:00
Pk(serverId).
Result("clusterId").
Find()
if err != nil {
return false, 0, err
}
if one == nil {
isOk = false
return
}
server := one.(*Server)
return true, int64(server.ClusterId), nil
}
2021-08-01 14:56:08 +08:00
// ComposeServerConfigWithServerId 构造服务的Config
2021-11-10 14:54:27 +08:00
func (this *ServerDAO) ComposeServerConfigWithServerId(tx *dbs.Tx, serverId int64, forNode bool) (*serverconfigs.ServerConfig, error) {
server, err := this.FindEnabledServer(tx, serverId)
2020-09-15 14:44:11 +08:00
if err != nil {
return nil, err
}
if server == nil {
return nil, ErrNotFound
2020-09-15 14:44:11 +08:00
}
2021-11-10 14:54:27 +08:00
return this.ComposeServerConfig(tx, server, nil, forNode)
2021-08-01 14:56:08 +08:00
}
// ComposeServerConfig 构造服务的Config
2021-11-10 14:54:27 +08:00
// forNode 是否是节点请求
2021-11-11 14:16:42 +08:00
func (this *ServerDAO) ComposeServerConfig(tx *dbs.Tx, server *Server, cacheMap *utils.CacheMap, forNode bool) (*serverconfigs.ServerConfig, error) {
2021-08-01 14:56:08 +08:00
if server == nil {
return nil, ErrNotFound
}
2020-09-15 14:44:11 +08:00
2021-08-22 11:35:33 +08:00
if cacheMap == nil {
2021-11-11 14:16:42 +08:00
cacheMap = utils.NewCacheMap()
}
var cacheKey = this.Table + ":ComposeServerConfig:" + types.String(server.Id)
cache, ok := cacheMap.Get(cacheKey)
if ok {
return cache.(*serverconfigs.ServerConfig), nil
2021-08-22 11:35:33 +08:00
}
var config = &serverconfigs.ServerConfig{}
2021-08-01 14:56:08 +08:00
config.Id = int64(server.Id)
2021-08-01 11:13:46 +08:00
config.ClusterId = int64(server.ClusterId)
config.UserId = int64(server.UserId)
2020-09-15 14:44:11 +08:00
config.Type = server.Type
2022-03-22 21:45:07 +08:00
config.IsOn = server.IsOn
2020-09-15 14:44:11 +08:00
config.Name = server.Name
config.Description = server.Description
var groupConfig *serverconfigs.ServerGroupConfig
for _, groupId := range server.DecodeGroupIds() {
groupConfig1, err := SharedServerGroupDAO.ComposeGroupConfig(tx, groupId, cacheMap)
if err != nil {
return nil, err
}
if groupConfig1 == nil {
continue
}
groupConfig = groupConfig1
break
}
config.Group = groupConfig
2020-09-15 14:44:11 +08:00
// ServerNames
if IsNotNull(server.ServerNames) {
var serverNames = []*serverconfigs.ServerNameConfig{}
err := json.Unmarshal(server.ServerNames, &serverNames)
2020-09-15 14:44:11 +08:00
if err != nil {
return nil, err
}
config.ServerNames = serverNames
}
2020-11-17 16:53:58 +08:00
// CNAME
config.SupportCNAME = server.SupportCNAME == 1
2020-11-17 16:53:58 +08:00
if server.ClusterId > 0 && len(server.DnsName) > 0 {
2021-08-22 11:35:33 +08:00
clusterDNS, err := SharedNodeClusterDAO.FindClusterDNSInfo(tx, int64(server.ClusterId), cacheMap)
2020-11-17 16:53:58 +08:00
if err != nil {
return nil, err
}
if clusterDNS != nil && clusterDNS.DnsDomainId > 0 {
clusterDNSConfig, err := clusterDNS.DecodeDNSConfig()
2020-11-17 16:53:58 +08:00
if err != nil {
return nil, err
}
2022-07-17 17:08:28 +08:00
domain, err := dns.SharedDNSDomainDAO.FindEnabledDNSDomain(tx, int64(clusterDNS.DnsDomainId), cacheMap)
if err != nil {
return nil, err
}
if domain != nil {
var cname = server.DnsName + "." + domain.Name
config.CNameDomain = cname
if clusterDNSConfig.CNameAsDomain {
config.CNameAsDomain = true
config.AliasServerNames = append(config.AliasServerNames, cname)
}
2020-11-17 16:53:58 +08:00
}
}
}
2020-09-15 14:44:11 +08:00
// HTTP
if IsNotNull(server.Http) {
var httpConfig = &serverconfigs.HTTPProtocolConfig{}
err := json.Unmarshal(server.Http, httpConfig)
2020-09-15 14:44:11 +08:00
if err != nil {
return nil, err
}
config.HTTP = httpConfig
}
// HTTPS
if IsNotNull(server.Https) {
var httpsConfig = &serverconfigs.HTTPSProtocolConfig{}
err := json.Unmarshal(server.Https, httpsConfig)
2020-09-15 14:44:11 +08:00
if err != nil {
return nil, err
}
2020-09-30 17:46:43 +08:00
// SSL
2020-10-01 16:01:17 +08:00
if httpsConfig.SSLPolicyRef != nil && httpsConfig.SSLPolicyRef.SSLPolicyId > 0 {
2021-08-22 11:35:33 +08:00
sslPolicyConfig, err := SharedSSLPolicyDAO.ComposePolicyConfig(tx, httpsConfig.SSLPolicyRef.SSLPolicyId, cacheMap)
2020-09-30 17:46:43 +08:00
if err != nil {
return nil, err
}
if sslPolicyConfig != nil {
httpsConfig.SSLPolicy = sslPolicyConfig
}
}
2020-09-15 14:44:11 +08:00
config.HTTPS = httpsConfig
}
// TCP
if IsNotNull(server.Tcp) {
var tcpConfig = &serverconfigs.TCPProtocolConfig{}
err := json.Unmarshal(server.Tcp, tcpConfig)
2020-09-15 14:44:11 +08:00
if err != nil {
return nil, err
}
config.TCP = tcpConfig
}
// TLS
if IsNotNull(server.Tls) {
var tlsConfig = &serverconfigs.TLSProtocolConfig{}
err := json.Unmarshal(server.Tls, tlsConfig)
2020-09-15 14:44:11 +08:00
if err != nil {
return nil, err
}
2020-09-30 17:46:43 +08:00
// SSL
if tlsConfig.SSLPolicyRef != nil {
2021-08-22 11:35:33 +08:00
sslPolicyConfig, err := SharedSSLPolicyDAO.ComposePolicyConfig(tx, tlsConfig.SSLPolicyRef.SSLPolicyId, cacheMap)
2020-09-30 17:46:43 +08:00
if err != nil {
return nil, err
}
if sslPolicyConfig != nil {
tlsConfig.SSLPolicy = sslPolicyConfig
}
}
2020-09-15 14:44:11 +08:00
config.TLS = tlsConfig
}
// Unix
if IsNotNull(server.Unix) {
var unixConfig = &serverconfigs.UnixProtocolConfig{}
err := json.Unmarshal(server.Unix, unixConfig)
2020-09-15 14:44:11 +08:00
if err != nil {
return nil, err
}
config.Unix = unixConfig
}
// UDP
if IsNotNull(server.Udp) {
var udpConfig = &serverconfigs.UDPProtocolConfig{}
err := json.Unmarshal(server.Udp, udpConfig)
2020-09-15 14:44:11 +08:00
if err != nil {
return nil, err
}
config.UDP = udpConfig
}
// Web
if server.WebId > 0 {
2021-08-22 11:35:33 +08:00
webConfig, err := SharedHTTPWebDAO.ComposeWebConfig(tx, int64(server.WebId), cacheMap)
2020-09-15 14:44:11 +08:00
if err != nil {
return nil, err
}
if webConfig != nil {
config.Web = webConfig
}
}
// ReverseProxy
2020-09-21 11:37:17 +08:00
if IsNotNull(server.ReverseProxy) {
var reverseProxyRef = &serverconfigs.ReverseProxyRef{}
err := json.Unmarshal(server.ReverseProxy, reverseProxyRef)
2020-09-21 11:37:17 +08:00
if err != nil {
return nil, err
}
config.ReverseProxyRef = reverseProxyRef
2021-08-22 11:35:33 +08:00
reverseProxyConfig, err := SharedReverseProxyDAO.ComposeReverseProxyConfig(tx, reverseProxyRef.ReverseProxyId, cacheMap)
2020-09-15 14:44:11 +08:00
if err != nil {
return nil, err
}
if reverseProxyConfig != nil {
config.ReverseProxy = reverseProxyConfig
}
}
2021-08-01 14:56:08 +08:00
// WAF策略
var clusterId = int64(server.ClusterId)
2021-08-22 11:35:33 +08:00
httpFirewallPolicyId, err := SharedNodeClusterDAO.FindClusterHTTPFirewallPolicyId(tx, clusterId, cacheMap)
2021-08-01 14:56:08 +08:00
if err != nil {
return nil, err
}
if httpFirewallPolicyId > 0 {
config.HTTPFirewallPolicyId = httpFirewallPolicyId
}
// 缓存策略
2021-08-22 11:35:33 +08:00
httpCachePolicyId, err := SharedNodeClusterDAO.FindClusterHTTPCachePolicyId(tx, clusterId, cacheMap)
2021-08-01 14:56:08 +08:00
if err != nil {
return nil, err
}
if httpCachePolicyId > 0 {
config.HTTPCachePolicyId = httpCachePolicyId
}
2021-11-09 17:36:54 +08:00
// traffic limit
if len(server.TrafficLimit) > 0 {
var trafficLimitConfig = &serverconfigs.TrafficLimitConfig{}
err = json.Unmarshal(server.TrafficLimit, trafficLimitConfig)
if err != nil {
return nil, err
}
2021-11-09 17:36:54 +08:00
config.TrafficLimit = trafficLimitConfig
}
2021-11-09 15:36:25 +08:00
// 用户套餐
2021-11-10 14:54:27 +08:00
if forNode && server.UserPlanId > 0 {
userPlan, err := SharedUserPlanDAO.FindEnabledUserPlan(tx, int64(server.UserPlanId), cacheMap)
2021-11-09 15:36:25 +08:00
if err != nil {
return nil, err
}
2022-03-22 21:45:07 +08:00
if userPlan != nil && userPlan.IsOn {
2021-11-09 15:36:25 +08:00
if len(userPlan.DayTo) == 0 {
userPlan.DayTo = DefaultUserPlanMaxDay
}
2021-11-09 17:36:54 +08:00
// 套餐是否依然有效
plan, err := SharedPlanDAO.FindEnabledPlan(tx, int64(userPlan.PlanId))
if err != nil {
return nil, err
}
if plan != nil {
config.UserPlan = &serverconfigs.UserPlanConfig{
DayTo: userPlan.DayTo,
Plan: &serverconfigs.PlanConfig{
2021-11-28 20:11:36 +08:00
Id: int64(plan.Id),
Name: plan.Name,
},
2021-11-09 17:36:54 +08:00
}
if len(plan.TrafficLimit) > 0 && (config.TrafficLimit == nil || !config.TrafficLimit.IsOn) {
var trafficLimitConfig = &serverconfigs.TrafficLimitConfig{}
err = json.Unmarshal(plan.TrafficLimit, trafficLimitConfig)
2021-11-09 17:36:54 +08:00
if err != nil {
return nil, err
}
config.TrafficLimit = trafficLimitConfig
}
2021-11-09 15:36:25 +08:00
}
}
}
2021-11-10 14:54:27 +08:00
if config.TrafficLimit != nil && config.TrafficLimit.IsOn && !config.TrafficLimit.IsEmpty() {
if len(server.TrafficLimitStatus) > 0 {
var status = &serverconfigs.TrafficLimitStatus{}
err = json.Unmarshal(server.TrafficLimitStatus, status)
2021-11-10 14:54:27 +08:00
if err != nil {
return nil, err
}
if status.IsValid() {
config.TrafficLimitStatus = status
}
}
}
2022-03-29 21:24:31 +08:00
// UAM
if teaconst.IsPlus && IsNotNull(server.Uam) {
var uamConfig = &serverconfigs.UAMConfig{}
err = json.Unmarshal(server.Uam, uamConfig)
if err != nil {
return nil, err
}
if uamConfig.IsOn {
config.UAM = uamConfig
}
}
2021-11-11 14:16:42 +08:00
if cacheMap != nil {
cacheMap.Put(cacheKey, config)
}
2020-09-15 14:44:11 +08:00
return config, nil
}
2021-05-03 15:16:02 +08:00
// FindReverseProxyRef 根据条件获取反向代理配置
func (this *ServerDAO) FindReverseProxyRef(tx *dbs.Tx, serverId int64) (*serverconfigs.ReverseProxyRef, error) {
reverseProxy, err := this.Query(tx).
2020-09-15 14:44:11 +08:00
Pk(serverId).
Result("reverseProxy").
FindStringCol("")
if err != nil {
return nil, err
}
if len(reverseProxy) == 0 || reverseProxy == "null" {
return nil, nil
}
2020-09-21 11:37:17 +08:00
config := &serverconfigs.ReverseProxyRef{}
2020-09-15 14:44:11 +08:00
err = json.Unmarshal([]byte(reverseProxy), config)
return config, err
}
2020-09-13 20:37:28 +08:00
2021-05-03 15:16:02 +08:00
// FindServerWebId 查找Server对应的WebId
func (this *ServerDAO) FindServerWebId(tx *dbs.Tx, serverId int64) (int64, error) {
webId, err := this.Query(tx).
2020-09-16 20:29:18 +08:00
Pk(serverId).
Result("webId").
FindIntCol(0)
if err != nil {
return 0, err
}
return int64(webId), nil
}
2021-05-03 15:16:02 +08:00
// CountAllEnabledServersWithSSLPolicyIds 计算使用SSL策略的所有服务数量
func (this *ServerDAO) CountAllEnabledServersWithSSLPolicyIds(tx *dbs.Tx, sslPolicyIds []int64) (count int64, err error) {
2020-09-30 17:46:43 +08:00
if len(sslPolicyIds) == 0 {
return
}
policyStringIds := []string{}
for _, policyId := range sslPolicyIds {
policyStringIds = append(policyStringIds, strconv.FormatInt(policyId, 10))
}
return this.Query(tx).
2020-09-30 17:46:43 +08:00
State(ServerStateEnabled).
Where("(FIND_IN_SET(JSON_EXTRACT(https, '$.sslPolicyRef.sslPolicyId'), :policyIds) OR FIND_IN_SET(JSON_EXTRACT(tls, '$.sslPolicyRef.sslPolicyId'), :policyIds))").
Param("policyIds", strings.Join(policyStringIds, ",")).
Count()
}
2021-05-03 15:16:02 +08:00
// FindAllEnabledServersWithSSLPolicyIds 查找使用某个SSL策略的所有服务
func (this *ServerDAO) FindAllEnabledServersWithSSLPolicyIds(tx *dbs.Tx, sslPolicyIds []int64) (result []*Server, err error) {
2020-09-30 17:46:43 +08:00
if len(sslPolicyIds) == 0 {
return
}
policyStringIds := []string{}
for _, policyId := range sslPolicyIds {
policyStringIds = append(policyStringIds, strconv.FormatInt(policyId, 10))
}
_, err = this.Query(tx).
2020-09-30 17:46:43 +08:00
State(ServerStateEnabled).
Result("id", "name", "https", "tls", "isOn", "type").
Where("(FIND_IN_SET(JSON_EXTRACT(https, '$.sslPolicyRef.sslPolicyId'), :policyIds) OR FIND_IN_SET(JSON_EXTRACT(tls, '$.sslPolicyRef.sslPolicyId'), :policyIds))").
Param("policyIds", strings.Join(policyStringIds, ",")).
Slice(&result).
AscPk().
FindAll()
return
}
2021-05-03 15:16:02 +08:00
// FindAllEnabledServerIdsWithSSLPolicyIds 查找使用某个SSL策略的所有服务Id
func (this *ServerDAO) FindAllEnabledServerIdsWithSSLPolicyIds(tx *dbs.Tx, sslPolicyIds []int64) (result []int64, err error) {
if len(sslPolicyIds) == 0 {
return
}
for _, policyId := range sslPolicyIds {
ones, err := this.Query(tx).
State(ServerStateEnabled).
ResultPk().
Where("(JSON_CONTAINS(https, :jsonQuery) OR JSON_CONTAINS(tls, :jsonQuery))").
Param("jsonQuery", maps.Map{"sslPolicyRef": maps.Map{"sslPolicyId": policyId}}.AsJSON()).
FindAll()
if err != nil {
return nil, err
}
for _, one := range ones {
serverId := int64(one.(*Server).Id)
if !lists.ContainsInt64(result, serverId) {
result = append(result, serverId)
}
}
}
return
}
// ExistEnabledUserServerWithSSLPolicyId 检查是否存在某个用户的策略
func (this *ServerDAO) ExistEnabledUserServerWithSSLPolicyId(tx *dbs.Tx, userId int64, sslPolicyId int64) (bool, error) {
return this.Query(tx).
State(ServerStateEnabled).
Attr("userId", userId).
Where("(JSON_CONTAINS(https, :jsonQuery) OR JSON_CONTAINS(tls, :jsonQuery))").
Param("jsonQuery", maps.Map{"sslPolicyRef": maps.Map{"sslPolicyId": sslPolicyId}}.AsJSON()).
Exist()
}
2021-05-03 15:16:02 +08:00
// CountEnabledServersWithWebIds 计算使用某个缓存策略的所有服务数量
func (this *ServerDAO) CountEnabledServersWithWebIds(tx *dbs.Tx, webIds []int64) (count int64, err error) {
2020-10-02 17:22:32 +08:00
if len(webIds) == 0 {
return
}
return this.Query(tx).
2020-10-02 17:22:32 +08:00
State(ServerStateEnabled).
Attr("webId", webIds).
Reuse(false).
2020-10-02 17:22:32 +08:00
Count()
}
2021-05-03 15:16:02 +08:00
// FindAllEnabledServersWithWebIds 查找使用某个缓存策略的所有服务
func (this *ServerDAO) FindAllEnabledServersWithWebIds(tx *dbs.Tx, webIds []int64) (result []*Server, err error) {
2020-10-02 17:22:32 +08:00
if len(webIds) == 0 {
return
}
_, err = this.Query(tx).
2020-10-02 17:22:32 +08:00
State(ServerStateEnabled).
Attr("webId", webIds).
Reuse(false).
2020-10-02 17:22:32 +08:00
AscPk().
Slice(&result).
FindAll()
return
}
2021-05-03 15:16:02 +08:00
// CountAllEnabledServersWithNodeClusterId 计算使用某个集群的所有服务数量
func (this *ServerDAO) CountAllEnabledServersWithNodeClusterId(tx *dbs.Tx, clusterId int64) (int64, error) {
return this.Query(tx).
2020-10-25 16:22:44 +08:00
State(ServerStateEnabled).
Attr("clusterId", clusterId).
Count()
}
2021-05-03 15:16:02 +08:00
// CountAllEnabledServersWithGroupId 计算使用某个分组的服务数量
2022-01-05 20:12:37 +08:00
func (this *ServerDAO) CountAllEnabledServersWithGroupId(tx *dbs.Tx, groupId int64, userId int64) (int64, error) {
var query = this.Query(tx).
State(ServerStateEnabled)
if userId > 0 {
query.Attr("userId", userId)
}
return query.
Where("JSON_CONTAINS(groupIds, :groupId)").
Param("groupId", numberutils.FormatInt64(groupId)).
Count()
}
2021-05-03 15:16:02 +08:00
// FindAllServerDNSNamesWithDNSDomainId 查询使用某个DNS域名的所有服务域名
func (this *ServerDAO) FindAllServerDNSNamesWithDNSDomainId(tx *dbs.Tx, dnsDomainId int64) ([]string, error) {
clusterIds, err := SharedNodeClusterDAO.FindAllEnabledClusterIdsWithDNSDomainId(tx, dnsDomainId)
if err != nil {
return nil, err
}
if len(clusterIds) == 0 {
return nil, nil
}
ones, err := this.Query(tx).
State(ServerStateEnabled).
Attr("isOn", true).
Attr("clusterId", clusterIds).
Result("dnsName").
Reuse(false). // 避免因为IN语句造成内存占用过多
FindAll()
if err != nil {
return nil, err
}
result := []string{}
for _, one := range ones {
dnsName := one.(*Server).DnsName
if len(dnsName) == 0 {
continue
}
result = append(result, dnsName)
}
return result, nil
}
2021-05-03 15:16:02 +08:00
// FindAllServersDNSWithClusterId 获取某个集群下的服务DNS信息
func (this *ServerDAO) FindAllServersDNSWithClusterId(tx *dbs.Tx, clusterId int64) (result []*Server, err error) {
_, err = this.Query(tx).
2020-11-14 11:05:43 +08:00
State(ServerStateEnabled).
Attr("isOn", true).
Attr("isAuditing", false). // 不在审核中
2020-11-14 11:05:43 +08:00
Attr("clusterId", clusterId).
Result("id", "name", "dnsName").
DescPk().
Slice(&result).
FindAll()
return
}
2021-10-17 17:12:30 +08:00
// FindAllEnabledServersWithDomain 根据域名查找服务
// TODO 需要改成使用plainServerNames
2021-10-17 17:12:30 +08:00
func (this *ServerDAO) FindAllEnabledServersWithDomain(tx *dbs.Tx, domain string) (result []*Server, err error) {
if len(domain) == 0 {
return
}
_, err = this.Query(tx).
State(ServerStateEnabled).
Where("(JSON_CONTAINS(serverNames, :domain1) OR JSON_CONTAINS(serverNames, :domain2))").
Param("domain1", maps.Map{"name": domain}.AsJSON()).
Param("domain2", maps.Map{"subNames": domain}.AsJSON()).
Slice(&result).
DescPk().
FindAll()
if err != nil {
return nil, err
}
// 支持泛解析
var countPieces = strings.Count(domain, ".")
for {
var index = strings.Index(domain, ".")
if index > 0 {
domain = domain[index+1:]
var search = strings.Repeat("*.", countPieces-strings.Count(domain, ".")) + domain
_, err = this.Query(tx).
State(ServerStateEnabled).
Where("(JSON_CONTAINS(serverNames, :domain1) OR JSON_CONTAINS(serverNames, :domain2))").
Param("domain1", maps.Map{"name": search}.AsJSON()).
Param("domain2", maps.Map{"subNames": search}.AsJSON()).
Slice(&result).
DescPk().
FindAll()
if err != nil {
return
}
if len(result) > 0 {
return
}
} else {
break
}
}
return
}
// FindEnabledServerWithDomain 根据域名查找服务集群ID
func (this *ServerDAO) FindEnabledServerWithDomain(tx *dbs.Tx, domain string) (server *Server, err error) {
if len(domain) == 0 {
return
}
one, err := this.Query(tx).
State(ServerStateEnabled).
Where("JSON_CONTAINS(plainServerNames, :domain)").
Param("domain", strconv.Quote(domain)).
Result("id", "userId", "clusterId").
AscPk().
Find()
if err != nil {
return nil, err
}
if one != nil {
return one.(*Server), nil
}
// 尝试泛解析
var dotIndex = strings.Index(domain, ".")
if dotIndex > 0 {
var wildcardDomain = "*." + domain[dotIndex+1:]
one, err = this.Query(tx).
State(ServerStateEnabled).
Where("JSON_CONTAINS(plainServerNames, :domain)").
Param("domain", strconv.Quote(wildcardDomain)).
Result("id", "userId", "clusterId").
AscPk().
Find()
if err != nil {
return nil, err
}
if one != nil {
return one.(*Server), nil
}
}
return
}
2021-05-03 15:16:02 +08:00
// GenerateServerDNSName 重新生成子域名
func (this *ServerDAO) GenerateServerDNSName(tx *dbs.Tx, serverId int64) (string, error) {
2020-11-14 11:05:43 +08:00
if serverId <= 0 {
return "", errors.New("invalid serverId")
}
2021-01-27 23:00:02 +08:00
dnsName, err := this.GenDNSName(tx)
2020-11-14 11:05:43 +08:00
if err != nil {
return "", err
}
op := NewServerOperator()
op.Id = serverId
op.DnsName = dnsName
err = this.Save(tx, op)
if err != nil {
return "", err
}
2020-11-14 11:05:43 +08:00
err = this.NotifyUpdate(tx, serverId)
if err != nil {
return "", err
}
2021-01-27 23:00:02 +08:00
err = this.NotifyDNSUpdate(tx, serverId)
if err != nil {
return "", err
}
return dnsName, nil
2020-08-21 12:32:33 +08:00
}
2020-11-11 21:32:25 +08:00
2021-05-03 15:16:02 +08:00
// FindServerClusterId 查询当前服务的集群ID
func (this *ServerDAO) FindServerClusterId(tx *dbs.Tx, serverId int64) (int64, error) {
return this.Query(tx).
Pk(serverId).
Result("clusterId").
FindInt64Col(0)
}
2021-05-03 15:16:02 +08:00
// FindServerDNSName 查询服务的DNS名称
func (this *ServerDAO) FindServerDNSName(tx *dbs.Tx, serverId int64) (string, error) {
return this.Query(tx).
2020-11-16 23:30:47 +08:00
Pk(serverId).
Result("dnsName").
FindStringCol("")
}
// FindServerSupportCNAME 查询服务是否支持CNAME
func (this *ServerDAO) FindServerSupportCNAME(tx *dbs.Tx, serverId int64) (bool, error) {
supportCNAME, err := this.Query(tx).
Pk(serverId).
Result("supportCNAME").
FindIntCol(0)
if err != nil {
return false, err
}
return supportCNAME == 1, nil
}
2021-05-03 15:16:02 +08:00
// FindStatelessServerDNS 查询服务的DNS相关信息并且不关注状态
2021-01-27 23:00:02 +08:00
func (this *ServerDAO) FindStatelessServerDNS(tx *dbs.Tx, serverId int64) (*Server, error) {
one, err := this.Query(tx).
Pk(serverId).
Result("id", "dnsName", "isOn", "state", "clusterId").
Find()
if err != nil || one == nil {
return nil, err
}
return one.(*Server), nil
}
2021-05-03 15:16:02 +08:00
// FindServerAdminIdAndUserId 获取当前服务的管理员ID和用户ID
func (this *ServerDAO) FindServerAdminIdAndUserId(tx *dbs.Tx, serverId int64) (adminId int64, userId int64, err error) {
one, err := this.Query(tx).
2020-12-18 21:18:53 +08:00
Pk(serverId).
Result("adminId", "userId").
Find()
if err != nil {
return 0, 0, err
}
if one == nil {
return 0, 0, nil
}
return int64(one.(*Server).AdminId), int64(one.(*Server).UserId), nil
}
2021-07-11 18:05:57 +08:00
// FindServerUserId 查找服务的用户ID
func (this *ServerDAO) FindServerUserId(tx *dbs.Tx, serverId int64) (userId int64, err error) {
one, _, err := this.Query(tx).
Pk(serverId).
Result("userId").
FindOne()
if err != nil || one == nil {
return 0, err
}
return one.GetInt64("userId"), nil
}
2021-11-09 15:36:25 +08:00
// FindServerUserPlanId 查找服务的套餐ID
func (this *ServerDAO) FindServerUserPlanId(tx *dbs.Tx, serverId int64) (userPlanId int64, err error) {
return this.Query(tx).
Pk(serverId).
Result("userPlanId").
FindInt64Col(0)
}
2021-05-03 15:16:02 +08:00
// CheckUserServer 检查用户服务
func (this *ServerDAO) CheckUserServer(tx *dbs.Tx, userId int64, serverId int64) error {
if serverId <= 0 || userId <= 0 {
return ErrNotFound
}
ok, err := this.Query(tx).
Pk(serverId).
Attr("userId", userId).
Exist()
if err != nil {
return err
}
if !ok {
return ErrNotFound
}
return nil
}
2021-05-03 15:16:02 +08:00
// UpdateUserServersClusterId 设置一个用户下的所有服务的所属集群
func (this *ServerDAO) UpdateUserServersClusterId(tx *dbs.Tx, userId int64, oldClusterId, newClusterId int64) error {
_, err := this.Query(tx).
Attr("userId", userId).
Attr("userPlanId", 0).
Set("clusterId", newClusterId).
Update()
if err != nil {
return err
}
if oldClusterId > 0 {
err = SharedNodeTaskDAO.CreateClusterTask(tx, nodeconfigs.NodeRoleNode, oldClusterId, 0, NodeTaskTypeConfigChanged)
if err != nil {
return err
}
err = SharedNodeTaskDAO.CreateClusterTask(tx, nodeconfigs.NodeRoleNode, oldClusterId, 0, NodeTaskTypeIPItemChanged)
if err != nil {
return err
}
err = dns.SharedDNSTaskDAO.CreateClusterTask(tx, oldClusterId, dns.DNSTaskTypeClusterChange)
if err != nil {
return err
}
}
if newClusterId > 0 {
err = SharedNodeTaskDAO.CreateClusterTask(tx, nodeconfigs.NodeRoleNode, newClusterId, 0, NodeTaskTypeConfigChanged)
if err != nil {
return err
}
err = SharedNodeTaskDAO.CreateClusterTask(tx, nodeconfigs.NodeRoleNode, newClusterId, 0, NodeTaskTypeIPItemChanged)
if err != nil {
return err
}
err = dns.SharedDNSTaskDAO.CreateClusterTask(tx, newClusterId, dns.DNSTaskTypeClusterChange)
if err != nil {
return err
}
}
return err
}
2021-05-03 15:16:02 +08:00
// FindAllEnabledServersWithUserId 查找用户的所有的服务
func (this *ServerDAO) FindAllEnabledServersWithUserId(tx *dbs.Tx, userId int64) (result []*Server, err error) {
_, err = this.Query(tx).
State(ServerStateEnabled).
Attr("userId", userId).
DescPk().
Slice(&result).
FindAll()
return
}
2021-05-03 15:16:02 +08:00
// FindEnabledServerIdWithWebId 根据WebId查找ServerId
2021-01-10 17:34:35 +08:00
func (this *ServerDAO) FindEnabledServerIdWithWebId(tx *dbs.Tx, webId int64) (serverId int64, err error) {
if webId <= 0 {
return 0, nil
}
return this.Query(tx).
State(ServerStateEnabled).
Attr("webId", webId).
ResultPk().
FindInt64Col(0)
}
2021-05-03 15:16:02 +08:00
// FindEnabledServerIdWithReverseProxyId 查找包含某个反向代理的Server
func (this *ServerDAO) FindEnabledServerIdWithReverseProxyId(tx *dbs.Tx, reverseProxyId int64) (serverId int64, err error) {
return this.Query(tx).
State(ServerStateEnabled).
Where("JSON_CONTAINS(reverseProxy, :jsonQuery)").
Param("jsonQuery", maps.Map{"reverseProxyId": reverseProxyId}.AsJSON()).
ResultPk().
FindInt64Col(0)
}
// CheckPortIsUsing 检查端口是否被使用
// protocolFamily支持tcp和udp
func (this *ServerDAO) CheckPortIsUsing(tx *dbs.Tx, clusterId int64, protocolFamily string, port int, excludeServerId int64, excludeProtocol string) (bool, error) {
// 检查是否在别的协议中
if excludeServerId > 0 {
one, err := this.Query(tx).
Pk(excludeServerId).
Result("tcp", "tls", "udp", "http", "https").
Find()
if err != nil {
return false, err
}
if one != nil {
var server = one.(*Server)
for _, protocol := range []string{"http", "https", "tcp", "tls", "udp"} {
if protocol == excludeProtocol {
continue
}
switch protocol {
case "http":
if protocolFamily == "tcp" && lists.ContainsInt(server.DecodeHTTPPorts(), port) {
return true, nil
}
case "https":
if protocolFamily == "tcp" && lists.ContainsInt(server.DecodeHTTPSPorts(), port) {
return true, nil
}
case "tcp":
if protocolFamily == "tcp" && lists.ContainsInt(server.DecodeTCPPorts(), port) {
return true, nil
}
case "tls":
if protocolFamily == "tcp" && lists.ContainsInt(server.DecodeTLSPorts(), port) {
return true, nil
}
case "udp":
// 不需要判断
}
}
}
}
// 其他服务中
query := this.Query(tx).
Attr("clusterId", clusterId).
2021-10-10 16:29:50 +08:00
State(ServerStateEnabled).
Param("port", types.String(port))
if excludeServerId <= 0 {
switch protocolFamily {
case "tcp", "http", "":
query.Where("JSON_CONTAINS(tcpPorts, :port)")
case "udp":
query.Where("JSON_CONTAINS(udpPorts, :port)")
}
} else {
switch protocolFamily {
case "tcp", "http", "":
query.Where("(id!=:serverId AND JSON_CONTAINS(tcpPorts, :port))")
case "udp":
query.Where("(id!=:serverId AND JSON_CONTAINS(udpPorts, :port))")
}
query.Param("serverId", excludeServerId)
}
return query.
Exist()
}
2021-05-03 15:16:02 +08:00
// ExistServerNameInCluster 检查ServerName是否已存在
2021-02-06 21:19:19 +08:00
func (this *ServerDAO) ExistServerNameInCluster(tx *dbs.Tx, clusterId int64, serverName string, excludeServerId int64) (bool, error) {
query := this.Query(tx).
Attr("clusterId", clusterId).
Where("(JSON_CONTAINS(serverNames, :jsonQuery1) OR JSON_CONTAINS(serverNames, :jsonQuery2))").
Param("jsonQuery1", maps.Map{"name": serverName}.AsJSON()).
Param("jsonQuery2", maps.Map{"subNames": serverName}.AsJSON())
if excludeServerId > 0 {
query.Neq("id", excludeServerId)
}
query.State(ServerStateEnabled)
return query.Exist()
}
2021-05-03 15:16:02 +08:00
// GenDNSName 生成DNS Name
2021-01-27 23:00:02 +08:00
func (this *ServerDAO) GenDNSName(tx *dbs.Tx) (string, error) {
for {
dnsName := rands.HexString(8)
exist, err := this.Query(tx).
Attr("dnsName", dnsName).
Exist()
if err != nil {
return "", err
}
if !exist {
return dnsName, nil
}
}
}
2021-05-03 15:16:02 +08:00
// FindLatestServers 查询最近访问的服务
func (this *ServerDAO) FindLatestServers(tx *dbs.Tx, size int64) (result []*Server, err error) {
itemTable := SharedLatestItemDAO.Table
itemType := LatestItemTypeServer
_, err = this.Query(tx).
Result(this.Table+".id", this.Table+".name").
Join(SharedLatestItemDAO, dbs.QueryJoinRight, this.Table+".id="+itemTable+".itemId AND "+itemTable+".itemType='"+itemType+"'").
Asc("CEIL((UNIX_TIMESTAMP() - " + itemTable + ".updatedAt) / (7 * 86400))"). // 优先一个星期以内的
Desc(itemTable + ".count").
State(NodeClusterStateEnabled).
Limit(size).
Slice(&result).
FindAll()
return
}
// FindNearbyServersInGroup 查找所属分组附近的服务
func (this *ServerDAO) FindNearbyServersInGroup(tx *dbs.Tx, groupId int64, serverId int64, size int64) (result []*Server, err error) {
// 之前的
ones, err := SharedServerDAO.Query(tx).
Result("id", "name", "isOn").
State(ServerStateEnabled).
Where("JSON_CONTAINS(groupIds, :groupId)").
Param("groupId", numberutils.FormatInt64(groupId)).
Gte("id", serverId).
Limit(size).
AscPk().
FindAll()
if err != nil {
return nil, err
}
lists.Reverse(ones)
for _, one := range ones {
result = append(result, one.(*Server))
}
// 之后的
ones, err = SharedServerDAO.Query(tx).
Result("id", "name", "isOn").
State(ServerStateEnabled).
Where("JSON_CONTAINS(groupIds, :groupId)").
Param("groupId", numberutils.FormatInt64(groupId)).
Lt("id", serverId).
Limit(size).
DescPk().
FindAll()
if err != nil {
return nil, err
}
for _, one := range ones {
result = append(result, one.(*Server))
}
return
}
// FindNearbyServersInCluster 查找所属集群附近的服务
func (this *ServerDAO) FindNearbyServersInCluster(tx *dbs.Tx, clusterId int64, serverId int64, size int64) (result []*Server, err error) {
// 之前的
ones, err := SharedServerDAO.Query(tx).
Result("id", "name", "isOn").
State(ServerStateEnabled).
Attr("clusterId", clusterId).
Gte("id", serverId).
Limit(size).
AscPk().
FindAll()
if err != nil {
return nil, err
}
lists.Reverse(ones)
for _, one := range ones {
result = append(result, one.(*Server))
}
// 之后的
ones, err = SharedServerDAO.Query(tx).
Result("id", "name", "isOn").
State(ServerStateEnabled).
Attr("clusterId", clusterId).
Lt("id", serverId).
Limit(size).
DescPk().
FindAll()
if err != nil {
return nil, err
}
for _, one := range ones {
result = append(result, one.(*Server))
}
return
}
2021-09-06 08:12:48 +08:00
// FindFirstHTTPOrHTTPSPortWithClusterId 获取集群中第一个HTTP或者HTTPS端口
func (this *ServerDAO) FindFirstHTTPOrHTTPSPortWithClusterId(tx *dbs.Tx, clusterId int64) (int, error) {
one, _, err := this.Query(tx).
Result("JSON_EXTRACT(http, '$.listen[*].portRange') AS httpPort, JSON_EXTRACT(https, '$.listen[*].portRange') AS httpsPort").
Attr("clusterId", clusterId).
State(ServerStateEnabled).
Attr("isOn", 1).
Where("((JSON_CONTAINS(http, :queryJSON) AND JSON_EXTRACT(http, '$.listen[*].portRange') IS NOT NULL) OR (JSON_CONTAINS(https, :queryJSON) AND JSON_EXTRACT(https, '$.listen[*].portRange') IS NOT NULL))").
Param("queryJSON", "{\"isOn\":true}").
FindOne()
if err != nil {
return 0, err
}
httpPortString := one.GetString("httpPort")
if len(httpPortString) > 0 {
var ports = []string{}
err = json.Unmarshal([]byte(httpPortString), &ports)
if err != nil {
return 0, err
}
if len(ports) > 0 {
2021-10-10 16:29:50 +08:00
var port = ports[0]
if strings.Contains(port, "-") { // IP范围
return types.Int(port[:strings.Index(port, "-")]), nil
}
return types.Int(port), nil
2021-09-06 08:12:48 +08:00
}
}
httpsPortString := one.GetString("httpsPort")
if len(httpsPortString) > 0 {
var ports = []string{}
err = json.Unmarshal([]byte(httpsPortString), &ports)
if err != nil {
return 0, err
}
2021-10-10 16:29:50 +08:00
var port = ports[0]
if strings.Contains(port, "-") { // IP范围
return types.Int(port[:strings.Index(port, "-")]), nil
2021-09-06 08:12:48 +08:00
}
2021-10-10 16:29:50 +08:00
return types.Int(port), nil
2021-09-06 08:12:48 +08:00
}
return 0, nil
}
2021-10-10 16:29:50 +08:00
// NotifyServerPortsUpdate 通知服务端口变化
func (this *ServerDAO) NotifyServerPortsUpdate(tx *dbs.Tx, serverId int64) error {
one, err := this.Query(tx).
Pk(serverId).
Result("tcp", "tls", "udp", "http", "https").
Find()
if err != nil {
return err
}
if one == nil {
return nil
}
var server = one.(*Server)
// HTTP
var tcpListens = []*serverconfigs.NetworkAddressConfig{}
var udpListens = []*serverconfigs.NetworkAddressConfig{}
if IsNotNull(server.Http) {
2021-10-10 16:29:50 +08:00
httpConfig := &serverconfigs.HTTPProtocolConfig{}
err := json.Unmarshal(server.Http, httpConfig)
2021-10-10 16:29:50 +08:00
if err != nil {
return err
}
tcpListens = append(tcpListens, httpConfig.Listen...)
}
// HTTPS
if IsNotNull(server.Https) {
2021-10-10 16:29:50 +08:00
httpsConfig := &serverconfigs.HTTPSProtocolConfig{}
err := json.Unmarshal(server.Https, httpsConfig)
2021-10-10 16:29:50 +08:00
if err != nil {
return err
}
tcpListens = append(tcpListens, httpsConfig.Listen...)
}
// TCP
if IsNotNull(server.Tcp) {
2021-10-10 16:29:50 +08:00
tcpConfig := &serverconfigs.TCPProtocolConfig{}
err := json.Unmarshal(server.Tcp, tcpConfig)
2021-10-10 16:29:50 +08:00
if err != nil {
return err
}
tcpListens = append(tcpListens, tcpConfig.Listen...)
}
// TLS
if IsNotNull(server.Tls) {
2021-10-10 16:29:50 +08:00
tlsConfig := &serverconfigs.TLSProtocolConfig{}
err := json.Unmarshal(server.Tls, tlsConfig)
2021-10-10 16:29:50 +08:00
if err != nil {
return err
}
tcpListens = append(tcpListens, tlsConfig.Listen...)
}
// UDP
if IsNotNull(server.Udp) {
2021-10-10 16:29:50 +08:00
udpConfig := &serverconfigs.UDPProtocolConfig{}
err := json.Unmarshal(server.Udp, udpConfig)
2021-10-10 16:29:50 +08:00
if err != nil {
return err
}
udpListens = append(udpListens, udpConfig.Listen...)
}
var tcpPorts = []int{}
for _, listen := range tcpListens {
_ = listen.Init()
if listen.MinPort > 0 && listen.MaxPort > 0 && listen.MinPort <= listen.MaxPort {
for i := listen.MinPort; i <= listen.MaxPort; i++ {
if !lists.ContainsInt(tcpPorts, i) {
tcpPorts = append(tcpPorts, i)
}
}
}
}
tcpPortsJSON, err := json.Marshal(tcpPorts)
if err != nil {
return err
}
var udpPorts = []int{}
for _, listen := range udpListens {
_ = listen.Init()
if listen.MinPort > 0 && listen.MaxPort > 0 && listen.MinPort <= listen.MaxPort {
for i := listen.MinPort; i <= listen.MaxPort; i++ {
if !lists.ContainsInt(udpPorts, i) {
udpPorts = append(udpPorts, i)
}
}
}
}
udpPortsJSON, err := json.Marshal(udpPorts)
if err != nil {
return err
}
return this.Query(tx).
Pk(serverId).
Set("tcpPorts", string(tcpPortsJSON)).
Set("udpPorts", string(udpPortsJSON)).
UpdateQuickly()
}
2021-11-09 17:36:54 +08:00
// FindServerTrafficLimitConfig 查找服务的流量限制
2021-11-11 14:16:42 +08:00
func (this *ServerDAO) FindServerTrafficLimitConfig(tx *dbs.Tx, serverId int64, cacheMap *utils.CacheMap) (*serverconfigs.TrafficLimitConfig, error) {
if cacheMap == nil {
2021-11-11 14:16:42 +08:00
cacheMap = utils.NewCacheMap()
}
2021-11-09 17:36:54 +08:00
var cacheKey = this.Table + ":FindServerTrafficLimitConfig:" + types.String(serverId)
2021-11-11 14:16:42 +08:00
result, ok := cacheMap.Get(cacheKey)
if ok {
2021-11-09 17:36:54 +08:00
return result.(*serverconfigs.TrafficLimitConfig), nil
}
2021-11-10 14:54:27 +08:00
serverOne, err := this.Query(tx).
Pk(serverId).
2021-11-09 17:36:54 +08:00
Result("trafficLimit").
2021-11-10 14:54:27 +08:00
Find()
if err != nil {
return nil, err
}
2021-11-09 17:36:54 +08:00
var limit = &serverconfigs.TrafficLimitConfig{}
2021-11-10 14:54:27 +08:00
if serverOne == nil {
return limit, nil
}
2021-11-10 14:54:27 +08:00
var trafficLimit = serverOne.(*Server).TrafficLimit
if len(trafficLimit) > 0 {
err = json.Unmarshal([]byte(trafficLimit), limit)
if err != nil {
return nil, err
}
}
2021-11-11 14:16:42 +08:00
if cacheMap != nil {
cacheMap.Put(cacheKey, limit)
}
return limit, nil
}
2021-11-10 14:54:27 +08:00
// CalculateServerTrafficLimitConfig 计算服务的流量限制
// TODO 优化性能
2021-11-11 14:16:42 +08:00
func (this *ServerDAO) CalculateServerTrafficLimitConfig(tx *dbs.Tx, serverId int64, cacheMap *utils.CacheMap) (*serverconfigs.TrafficLimitConfig, error) {
2021-11-10 14:54:27 +08:00
if cacheMap == nil {
2021-11-11 14:16:42 +08:00
cacheMap = utils.NewCacheMap()
2021-11-10 14:54:27 +08:00
}
var cacheKey = this.Table + ":FindServerTrafficLimitConfig:" + types.String(serverId)
2021-11-11 14:16:42 +08:00
result, ok := cacheMap.Get(cacheKey)
2021-11-10 14:54:27 +08:00
if ok {
return result.(*serverconfigs.TrafficLimitConfig), nil
}
serverOne, err := this.Query(tx).
Pk(serverId).
Result("trafficLimit", "userPlanId").
Find()
if err != nil {
return nil, err
}
var limitConfig = &serverconfigs.TrafficLimitConfig{}
if serverOne == nil {
return limitConfig, nil
}
var trafficLimit = serverOne.(*Server).TrafficLimit
var userPlanId = int64(serverOne.(*Server).UserPlanId)
if len(trafficLimit) == 0 {
if userPlanId > 0 {
userPlan, err := SharedUserPlanDAO.FindEnabledUserPlan(tx, userPlanId, cacheMap)
if err != nil {
return nil, err
}
if userPlan != nil {
planLimit, err := SharedPlanDAO.FindEnabledPlanTrafficLimit(tx, int64(userPlan.PlanId), cacheMap)
if err != nil {
return nil, err
}
if planLimit != nil {
return planLimit, nil
}
}
}
return limitConfig, nil
}
err = json.Unmarshal(trafficLimit, limitConfig)
2021-11-10 14:54:27 +08:00
if err != nil {
return nil, err
}
if !limitConfig.IsOn {
if userPlanId > 0 {
userPlan, err := SharedUserPlanDAO.FindEnabledUserPlan(tx, userPlanId, cacheMap)
if err != nil {
return nil, err
}
if userPlan != nil {
planLimit, err := SharedPlanDAO.FindEnabledPlanTrafficLimit(tx, int64(userPlan.PlanId), cacheMap)
if err != nil {
return nil, err
}
if planLimit != nil {
return planLimit, nil
}
}
}
}
2021-11-11 14:16:42 +08:00
if cacheMap != nil {
cacheMap.Put(cacheKey, limitConfig)
}
2021-11-10 14:54:27 +08:00
return limitConfig, nil
}
2021-11-09 17:36:54 +08:00
// UpdateServerTrafficLimitConfig 修改服务的流量限制
func (this *ServerDAO) UpdateServerTrafficLimitConfig(tx *dbs.Tx, serverId int64, trafficLimitConfig *serverconfigs.TrafficLimitConfig) error {
if serverId <= 0 {
return errors.New("invalid serverId")
}
2021-11-09 17:36:54 +08:00
limitJSON, err := json.Marshal(trafficLimitConfig)
if err != nil {
return err
}
err = this.Query(tx).
Pk(serverId).
2021-11-09 17:36:54 +08:00
Set("trafficLimit", limitJSON).
UpdateQuickly()
if err != nil {
return err
}
// 更新状态
2021-11-09 17:36:54 +08:00
return this.UpdateServerTrafficLimitStatus(tx, trafficLimitConfig, serverId, true)
}
2021-12-12 11:46:23 +08:00
// UpdateServerTrafficLimitStatus 修改服务的流量限制状态
2021-11-09 17:36:54 +08:00
func (this *ServerDAO) UpdateServerTrafficLimitStatus(tx *dbs.Tx, trafficLimitConfig *serverconfigs.TrafficLimitConfig, serverId int64, isUpdatingConfig bool) error {
if !trafficLimitConfig.IsOn {
if isUpdatingConfig {
return this.NotifyUpdate(tx, serverId)
}
return nil
}
2021-11-10 14:54:27 +08:00
serverOne, err := this.Query(tx).
Pk(serverId).
2021-11-10 14:54:27 +08:00
Result("trafficLimitStatus", "totalTraffic", "totalDailyTraffic", "totalMonthlyTraffic", "trafficDay", "trafficMonth").
Find()
if err != nil {
return err
}
2021-11-10 14:54:27 +08:00
if serverOne == nil {
return nil
}
var server = serverOne.(*Server)
2021-11-09 17:36:54 +08:00
var oldStatus = &serverconfigs.TrafficLimitStatus{}
if IsNotNull(server.TrafficLimitStatus) {
err = json.Unmarshal(server.TrafficLimitStatus, oldStatus)
if err != nil {
return err
}
// 如果已经达到限制了,而且还在有效期,那就没必要再更新
if !isUpdatingConfig && oldStatus.IsValid() {
return nil
}
}
var untilDay = ""
// daily
2021-11-09 17:36:54 +08:00
if trafficLimitConfig.DailyBytes() > 0 {
2021-11-10 14:54:27 +08:00
if server.TrafficDay == timeutil.Format("Ymd") && server.TotalDailyTraffic >= float64(trafficLimitConfig.DailyBytes())/1024/1024/1024 {
untilDay = timeutil.Format("Ymd")
}
}
// monthly
2021-11-10 14:54:27 +08:00
if server.TrafficMonth == timeutil.Format("Ym") && trafficLimitConfig.MonthlyBytes() > 0 {
if server.TotalMonthlyTraffic >= float64(trafficLimitConfig.MonthlyBytes())/1024/1024/1024 {
untilDay = timeutil.Format("Ym32")
}
}
// totally
2021-11-09 17:36:54 +08:00
if trafficLimitConfig.TotalBytes() > 0 {
2021-11-10 14:54:27 +08:00
if server.TotalTraffic >= float64(trafficLimitConfig.TotalBytes())/1024/1024/1024 {
untilDay = "30000101"
}
}
var isChanged = oldStatus.UntilDay != untilDay
if isChanged {
2021-11-09 17:36:54 +08:00
statusJSON, err := json.Marshal(&serverconfigs.TrafficLimitStatus{UntilDay: untilDay})
if err != nil {
return err
}
err = this.Query(tx).
Pk(serverId).
2021-11-09 17:36:54 +08:00
Set("trafficLimitStatus", statusJSON).
UpdateQuickly()
if err != nil {
return err
}
return this.NotifyUpdate(tx, serverId)
}
if isUpdatingConfig {
return this.NotifyUpdate(tx, serverId)
}
return nil
}
2021-11-09 17:36:54 +08:00
// IncreaseServerTotalTraffic 增加服务的总流量
func (this *ServerDAO) IncreaseServerTotalTraffic(tx *dbs.Tx, serverId int64, bytes int64) error {
var gb = float64(bytes) / 1024 / 1024 / 1024
2021-11-10 14:54:27 +08:00
var day = timeutil.Format("Ymd")
var month = timeutil.Format("Ym")
return this.Query(tx).
Pk(serverId).
2021-11-10 14:54:27 +08:00
Set("totalDailyTraffic", dbs.SQL("IF(trafficDay=:day, totalDailyTraffic, 0)+:trafficGB")).
Set("totalMonthlyTraffic", dbs.SQL("IF(trafficMonth=:month, totalMonthlyTraffic, 0)+:trafficGB")).
2021-11-09 17:36:54 +08:00
Set("totalTraffic", dbs.SQL("totalTraffic+:trafficGB")).
2021-11-10 14:54:27 +08:00
Set("trafficDay", day).
Set("trafficMonth", month).
Param("day", day).
Param("month", month).
2021-11-09 17:36:54 +08:00
Param("trafficGB", gb).
UpdateQuickly()
}
2021-11-09 17:36:54 +08:00
// ResetServerTotalTraffic 重置服务总流量
func (this *ServerDAO) ResetServerTotalTraffic(tx *dbs.Tx, serverId int64) error {
return this.Query(tx).
Pk(serverId).
2021-11-10 14:54:27 +08:00
Set("totalDailyTraffic", 0).
Set("totalMonthlyTraffic", 0).
UpdateQuickly()
}
2021-11-28 20:11:36 +08:00
// FindEnabledServerIdWithUserPlanId 查找使用某个套餐的服务ID
2021-11-09 15:36:25 +08:00
func (this *ServerDAO) FindEnabledServerIdWithUserPlanId(tx *dbs.Tx, userPlanId int64) (int64, error) {
return this.Query(tx).
State(ServerStateEnabled).
Attr("userPlanId", userPlanId).
ResultPk().
FindInt64Col(0)
}
2021-11-28 20:11:36 +08:00
// FindEnabledServerWithUserPlanId 查找使用某个套餐的服务
func (this *ServerDAO) FindEnabledServerWithUserPlanId(tx *dbs.Tx, userPlanId int64) (*Server, error) {
one, err := this.Query(tx).
State(ServerStateEnabled).
Attr("userPlanId", userPlanId).
Result("id", "name", "serverNames", "type").
Find()
if err != nil || one == nil {
return nil, err
}
return one.(*Server), nil
}
2021-11-09 15:36:25 +08:00
// UpdateServersClusterIdWithPlanId 修改套餐所在集群
func (this *ServerDAO) UpdateServersClusterIdWithPlanId(tx *dbs.Tx, planId int64, clusterId int64) error {
return this.Query(tx).
Where("userPlanId IN (SELECT id FROM "+SharedUserPlanDAO.Table+" WHERE planId=:planId AND state=1)").
Param("planId", planId).
Set("clusterId", clusterId).
UpdateQuickly()
}
// UpdateServerUserPlanId 设置服务所属套餐
func (this *ServerDAO) UpdateServerUserPlanId(tx *dbs.Tx, serverId int64, userPlanId int64) error {
2021-11-28 20:11:36 +08:00
// 取消套餐
if userPlanId <= 0 {
// 所属用户
userId, err := this.Query(tx).
Pk(serverId).
Result("userId").
FindInt64Col(0)
if err != nil {
return err
}
if userId <= 0 {
return errors.New("can not cancel the server plan, because the server has no user")
}
clusterId, err := SharedUserDAO.FindUserClusterId(tx, userId)
if err != nil {
return err
}
if clusterId <= 0 {
return errors.New("can not cancel the server plan, because the server use does not have a cluster")
}
err = this.Query(tx).
Pk(serverId).
Set("userPlanId", userPlanId).
Set("clusterId", clusterId).
UpdateQuickly()
if err != nil {
return err
}
return this.NotifyUpdate(tx, serverId)
}
// 设置新套餐
2021-11-10 14:54:27 +08:00
userPlan, err := SharedUserPlanDAO.FindEnabledUserPlan(tx, userPlanId, nil)
2021-11-09 15:36:25 +08:00
if err != nil {
return err
}
if userPlan == nil {
return errors.New("can not find user plan with id '" + types.String(userPlanId) + "'")
}
plan, err := SharedPlanDAO.FindEnabledPlan(tx, int64(userPlan.PlanId))
if err != nil {
return err
}
if plan == nil {
return errors.New("can not find plan with id '" + types.String(userPlan.PlanId) + "'")
}
err = this.Query(tx).
Pk(serverId).
Set("userPlanId", userPlanId).
2022-01-23 19:16:52 +08:00
Set("lastUserPlanId", userPlanId).
2021-11-09 15:36:25 +08:00
Set("clusterId", plan.ClusterId).
UpdateQuickly()
if err != nil {
return err
}
return this.NotifyUpdate(tx, serverId)
}
2022-01-23 19:16:52 +08:00
// FindServerLastUserPlanIdAndUserId 查找最后使用的套餐
func (this *ServerDAO) FindServerLastUserPlanIdAndUserId(tx *dbs.Tx, serverId int64) (userPlanId int64, userId int64, err error) {
one, err := this.Query(tx).
Pk(serverId).
Result("lastUserPlanId", "userId").
Find()
if err != nil || one == nil {
return 0, 0, err
}
return int64(one.(*Server).LastUserPlanId), int64(one.(*Server).UserId), nil
}
2022-03-29 21:24:31 +08:00
// UpdateServerUAM 开启UAM
func (this *ServerDAO) UpdateServerUAM(tx *dbs.Tx, serverId int64, uamConfig *serverconfigs.UAMConfig) error {
if uamConfig == nil {
return nil
}
configJSON, err := json.Marshal(uamConfig)
if err != nil {
return err
}
err = this.Query(tx).
Pk(serverId).
Set("uam", configJSON).
UpdateQuickly()
if err != nil {
return err
}
return this.NotifyUpdate(tx, serverId)
}
// FindServerUAM 查找服务的UAM配置
func (this *ServerDAO) FindServerUAM(tx *dbs.Tx, serverId int64) ([]byte, error) {
return this.Query(tx).
Pk(serverId).
Result("uam").
FindJSONCol()
}
// NotifyUpdate 同步服务所在的集群
func (this *ServerDAO) NotifyUpdate(tx *dbs.Tx, serverId int64) error {
// 创建任务
clusterId, err := this.FindServerClusterId(tx, serverId)
if err != nil {
return err
}
if clusterId == 0 {
return nil
}
return SharedNodeTaskDAO.CreateClusterTask(tx, nodeconfigs.NodeRoleNode, clusterId, serverId, NodeTaskTypeConfigChanged)
}
// NotifyClusterUpdate 同步指定的集群
func (this *ServerDAO) NotifyClusterUpdate(tx *dbs.Tx, clusterId, serverId int64) error {
if clusterId <= 0 {
return nil
}
return SharedNodeTaskDAO.CreateClusterTask(tx, nodeconfigs.NodeRoleNode, clusterId, serverId, NodeTaskTypeConfigChanged)
}
// NotifyDNSUpdate 通知当前集群DNS更新
2021-01-27 23:00:02 +08:00
func (this *ServerDAO) NotifyDNSUpdate(tx *dbs.Tx, serverId int64) error {
clusterId, err := this.Query(tx).
Pk(serverId).
Result("clusterId").
FindInt64Col(0) // 这里不需要加服务状态条件因为我们即使删除也要删除对应的服务的DNS解析
if err != nil {
return err
}
if clusterId <= 0 {
return nil
}
2021-08-22 11:35:33 +08:00
dnsInfo, err := SharedNodeClusterDAO.FindClusterDNSInfo(tx, clusterId, nil)
2021-01-27 23:00:02 +08:00
if err != nil {
return err
}
if dnsInfo == nil {
return nil
}
if len(dnsInfo.DnsName) == 0 || dnsInfo.DnsDomainId <= 0 {
return nil
2020-11-11 21:32:25 +08:00
}
return dns.SharedDNSTaskDAO.CreateServerTask(tx, clusterId, serverId, dns.DNSTaskTypeServerChange)
}
// NotifyClusterDNSUpdate 通知某个集群中的DNS更新
func (this *ServerDAO) NotifyClusterDNSUpdate(tx *dbs.Tx, clusterId int64, serverId int64) error {
dnsInfo, err := SharedNodeClusterDAO.FindClusterDNSInfo(tx, clusterId, nil)
if err != nil {
return err
}
if dnsInfo == nil {
return nil
}
if len(dnsInfo.DnsName) == 0 || dnsInfo.DnsDomainId <= 0 {
return nil
}
return dns.SharedDNSTaskDAO.CreateServerTask(tx, clusterId, serverId, dns.DNSTaskTypeServerChange)
2020-11-11 21:32:25 +08:00
}
// NotifyDisable 通知禁用
func (this *ServerDAO) NotifyDisable(tx *dbs.Tx, serverId int64) error {
// 禁用缓存策略相关的内容
policyIds, err := SharedHTTPFirewallPolicyDAO.FindFirewallPolicyIdsWithServerId(tx, serverId)
if err != nil {
return err
}
for _, policyId := range policyIds {
err = SharedHTTPFirewallPolicyDAO.DisableHTTPFirewallPolicy(tx, policyId)
if err != nil {
return err
}
err = SharedHTTPFirewallPolicyDAO.NotifyDisable(tx, policyId)
if err != nil {
return err
}
}
return nil
}