Compare commits

...

14 Commits

Author SHA1 Message Date
刘祥超
03da451d17 更新版本号为v0.1 2021-05-13 14:37:32 +08:00
刘祥超
946a9f373c 节点可以单独设置缓存的磁盘、内存容量 2021-05-12 21:39:08 +08:00
刘祥超
ff31d98f78 移除一处日志 2021-05-12 16:10:41 +08:00
刘祥超
c49d64eaee 更新SQL 2021-05-12 15:08:18 +08:00
刘祥超
68f390a73b 数据看板中增加升级信息 2021-05-11 22:48:04 +08:00
刘祥超
66a748cc26 服务支持fastcgi 2021-05-10 21:13:32 +08:00
刘祥超
b0339266e1 默认集群自动生成uniqueId和secret 2021-05-06 11:04:30 +08:00
刘祥超
ebdb181361 实现阈值通知消息 2021-05-05 19:50:55 +08:00
刘祥超
63f011c6c8 实现基础的阈值设置 2021-05-04 21:02:31 +08:00
刘祥超
43fbd7a404 记录和显示最近常用的服务 2021-05-03 15:16:02 +08:00
刘祥超
75192b6a6e 记录和显示最近常用的集群 2021-05-03 11:32:43 +08:00
刘祥超
d88ad9b3a1 实现基本的监控图表 2021-04-29 16:48:09 +08:00
刘祥超
b94fdf11cc 变更版本号 2021-04-18 21:25:05 +08:00
刘祥超
2eb249ad0f 增加SSH认证测试相关API 2021-04-18 21:19:34 +08:00
48 changed files with 2182 additions and 418 deletions

View File

@@ -1,7 +1,7 @@
package teaconst
const (
Version = "0.0.13"
Version = "0.1.0"
ProductName = "Edge API"
ProcessName = "edge-api"
@@ -15,4 +15,11 @@ const (
ErrServer = "服务器出了点小问题,请稍后重试"
SystemdServiceName = "edge-api"
// 其他节点版本号,用来检测是否有需要升级的节点
NodeVersion = "0.1.0"
UserNodeVersion = "0.0.7"
AuthorityNodeVersion = "0.0.1"
MonitorNodeVersion = "0.0.1"
)

View File

@@ -3,6 +3,7 @@ package models
import (
"encoding/json"
"errors"
"github.com/TeaOSLab/EdgeAPI/internal/utils"
_ "github.com/go-sql-driver/mysql"
"github.com/iwind/TeaGo/Tea"
"github.com/iwind/TeaGo/dbs"
@@ -38,7 +39,7 @@ func init() {
})
}
// 启用条目
// EnableAPINode 启用条目
func (this *APINodeDAO) EnableAPINode(tx *dbs.Tx, id int64) error {
_, err := this.Query(tx).
Pk(id).
@@ -47,7 +48,7 @@ func (this *APINodeDAO) EnableAPINode(tx *dbs.Tx, id int64) error {
return err
}
// 禁用条目
// DisableAPINode 禁用条目
func (this *APINodeDAO) DisableAPINode(tx *dbs.Tx, id int64) error {
_, err := this.Query(tx).
Pk(id).
@@ -56,7 +57,7 @@ func (this *APINodeDAO) DisableAPINode(tx *dbs.Tx, id int64) error {
return err
}
// 查找启用中的条目
// FindEnabledAPINode 查找启用中的条目
func (this *APINodeDAO) FindEnabledAPINode(tx *dbs.Tx, id int64) (*APINode, error) {
result, err := this.Query(tx).
Pk(id).
@@ -68,7 +69,7 @@ func (this *APINodeDAO) FindEnabledAPINode(tx *dbs.Tx, id int64) (*APINode, erro
return result.(*APINode), err
}
// 根据ID和Secret查找节点
// FindEnabledAPINodeWithUniqueIdAndSecret 根据ID和Secret查找节点
func (this *APINodeDAO) FindEnabledAPINodeWithUniqueIdAndSecret(tx *dbs.Tx, uniqueId string, secret string) (*APINode, error) {
one, err := this.Query(tx).
State(APINodeStateEnabled).
@@ -81,7 +82,7 @@ func (this *APINodeDAO) FindEnabledAPINodeWithUniqueIdAndSecret(tx *dbs.Tx, uniq
return one.(*APINode), nil
}
// 根据主键查找名称
// FindAPINodeName 根据主键查找名称
func (this *APINodeDAO) FindAPINodeName(tx *dbs.Tx, id int64) (string, error) {
return this.Query(tx).
Pk(id).
@@ -89,7 +90,7 @@ func (this *APINodeDAO) FindAPINodeName(tx *dbs.Tx, id int64) (string, error) {
FindStringCol("")
}
// 创建API节点
// CreateAPINode 创建API节点
func (this *APINodeDAO) CreateAPINode(tx *dbs.Tx, name string, description string, httpJSON []byte, httpsJSON []byte, restIsOn bool, restHTTPJSON []byte, restHTTPSJSON []byte, accessAddrsJSON []byte, isOn bool) (nodeId int64, err error) {
uniqueId, err := this.genUniqueId(tx)
if err != nil {
@@ -134,7 +135,7 @@ func (this *APINodeDAO) CreateAPINode(tx *dbs.Tx, name string, description strin
return types.Int64(op.Id), nil
}
// 修改API节点
// UpdateAPINode 修改API节点
func (this *APINodeDAO) UpdateAPINode(tx *dbs.Tx, nodeId int64, name string, description string, httpJSON []byte, httpsJSON []byte, restIsOn bool, restHTTPJSON []byte, restHTTPSJSON []byte, accessAddrsJSON []byte, isOn bool) error {
if nodeId <= 0 {
return errors.New("invalid nodeId")
@@ -177,7 +178,7 @@ func (this *APINodeDAO) UpdateAPINode(tx *dbs.Tx, nodeId int64, name string, des
return err
}
// 列出所有可用API节点
// FindAllEnabledAPINodes 列出所有可用API节点
func (this *APINodeDAO) FindAllEnabledAPINodes(tx *dbs.Tx) (result []*APINode, err error) {
_, err = this.Query(tx).
Attr("clusterId", 0). // 非集群专用
@@ -189,7 +190,7 @@ func (this *APINodeDAO) FindAllEnabledAPINodes(tx *dbs.Tx) (result []*APINode, e
return
}
// 列出所有可用而且启用的API节点
// FindAllEnabledAndOnAPINodes 列出所有可用而且启用的API节点
func (this *APINodeDAO) FindAllEnabledAndOnAPINodes(tx *dbs.Tx) (result []*APINode, err error) {
_, err = this.Query(tx).
Attr("clusterId", 0). // 非集群专用
@@ -202,14 +203,14 @@ func (this *APINodeDAO) FindAllEnabledAndOnAPINodes(tx *dbs.Tx) (result []*APINo
return
}
// 计算API节点数量
// CountAllEnabledAPINodes 计算API节点数量
func (this *APINodeDAO) CountAllEnabledAPINodes(tx *dbs.Tx) (int64, error) {
return this.Query(tx).
State(APINodeStateEnabled).
Count()
}
// 列出单页的API节点
// ListEnabledAPINodes 列出单页的API节点
func (this *APINodeDAO) ListEnabledAPINodes(tx *dbs.Tx, offset int64, size int64) (result []*APINode, err error) {
_, err = this.Query(tx).
Attr("clusterId", 0). // 非集群专用
@@ -223,7 +224,7 @@ func (this *APINodeDAO) ListEnabledAPINodes(tx *dbs.Tx, offset int64, size int64
return
}
// 根据主机名和端口获取ID
// FindEnabledAPINodeIdWithAddr 根据主机名和端口获取ID
func (this *APINodeDAO) FindEnabledAPINodeIdWithAddr(tx *dbs.Tx, protocol string, host string, port int) (int64, error) {
addr := maps.Map{
"protocol": protocol,
@@ -250,7 +251,7 @@ func (this *APINodeDAO) FindEnabledAPINodeIdWithAddr(tx *dbs.Tx, protocol string
return int64(one.(*APINode).Id), nil
}
// 设置API节点状态
// UpdateAPINodeStatus 设置API节点状态
func (this *APINodeDAO) UpdateAPINodeStatus(tx *dbs.Tx, apiNodeId int64, statusJSON []byte) error {
_, err := this.Query(tx).
Pk(apiNodeId).
@@ -275,3 +276,13 @@ func (this *APINodeDAO) genUniqueId(tx *dbs.Tx) (string, error) {
return uniqueId, nil
}
}
// CountAllLowerVersionNodes 计算所有节点中低于某个版本的节点数量
func (this *APINodeDAO) CountAllLowerVersionNodes(tx *dbs.Tx, version string) (int64, error) {
return this.Query(tx).
State(APINodeStateEnabled).
Where("status IS NOT NULL").
Where("(JSON_EXTRACT(status, '$.buildVersionCode') IS NULL OR JSON_EXTRACT(status, '$.buildVersionCode')<:version)").
Param("version", utils.VersionToLong(version)).
Count()
}

View File

@@ -3,6 +3,7 @@ package authority
import (
"github.com/TeaOSLab/EdgeAPI/internal/db/models"
"github.com/TeaOSLab/EdgeAPI/internal/errors"
"github.com/TeaOSLab/EdgeAPI/internal/utils"
_ "github.com/go-sql-driver/mysql"
"github.com/iwind/TeaGo/Tea"
"github.com/iwind/TeaGo/dbs"
@@ -196,3 +197,13 @@ func (this *AuthorityNodeDAO) UpdateNodeStatus(tx *dbs.Tx, nodeId int64, statusJ
Update()
return err
}
// CountAllLowerVersionNodes 计算所有节点中低于某个版本的节点数量
func (this *AuthorityNodeDAO) CountAllLowerVersionNodes(tx *dbs.Tx, version string) (int64, error) {
return this.Query(tx).
State(AuthorityNodeStateEnabled).
Where("status IS NOT NULL").
Where("(JSON_EXTRACT(status, '$.buildVersionCode') IS NULL OR JSON_EXTRACT(status, '$.buildVersionCode')<:version)").
Param("version", utils.VersionToLong(version)).
Count()
}

View File

@@ -0,0 +1,201 @@
package models
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAPI/internal/errors"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/shared"
_ "github.com/go-sql-driver/mysql"
"github.com/iwind/TeaGo/Tea"
"github.com/iwind/TeaGo/dbs"
"github.com/iwind/TeaGo/types"
)
const (
HTTPFastcgiStateEnabled = 1 // 已启用
HTTPFastcgiStateDisabled = 0 // 已禁用
)
type HTTPFastcgiDAO dbs.DAO
func NewHTTPFastcgiDAO() *HTTPFastcgiDAO {
return dbs.NewDAO(&HTTPFastcgiDAO{
DAOObject: dbs.DAOObject{
DB: Tea.Env,
Table: "edgeHTTPFastcgis",
Model: new(HTTPFastcgi),
PkName: "id",
},
}).(*HTTPFastcgiDAO)
}
var SharedHTTPFastcgiDAO *HTTPFastcgiDAO
func init() {
dbs.OnReady(func() {
SharedHTTPFastcgiDAO = NewHTTPFastcgiDAO()
})
}
// EnableHTTPFastcgi 启用条目
func (this *HTTPFastcgiDAO) EnableHTTPFastcgi(tx *dbs.Tx, id int64) error {
_, err := this.Query(tx).
Pk(id).
Set("state", HTTPFastcgiStateEnabled).
Update()
return err
}
// DisableHTTPFastcgi 禁用条目
func (this *HTTPFastcgiDAO) DisableHTTPFastcgi(tx *dbs.Tx, id int64) error {
_, err := this.Query(tx).
Pk(id).
Set("state", HTTPFastcgiStateDisabled).
Update()
return err
}
// FindEnabledHTTPFastcgi 查找启用中的条目
func (this *HTTPFastcgiDAO) FindEnabledHTTPFastcgi(tx *dbs.Tx, id int64) (*HTTPFastcgi, error) {
result, err := this.Query(tx).
Pk(id).
Attr("state", HTTPFastcgiStateEnabled).
Find()
if result == nil {
return nil, err
}
return result.(*HTTPFastcgi), err
}
// ComposeFastcgiConfig 组合配置
func (this *HTTPFastcgiDAO) ComposeFastcgiConfig(tx *dbs.Tx, fastcgiId int64) (*serverconfigs.HTTPFastcgiConfig, error) {
if fastcgiId <= 0 {
return nil, nil
}
fastcgi, err := this.FindEnabledHTTPFastcgi(tx, fastcgiId)
if err != nil {
return nil, err
}
if fastcgi == nil {
return nil, nil
}
config := &serverconfigs.HTTPFastcgiConfig{}
config.Id = int64(fastcgi.Id)
config.IsOn = fastcgi.IsOn == 1
config.Address = fastcgi.Address
if IsNotNull(fastcgi.Params) {
params := []*serverconfigs.HTTPFastcgiParam{}
err = json.Unmarshal([]byte(fastcgi.Params), &params)
if err != nil {
return nil, err
}
config.Params = params
}
if IsNotNull(fastcgi.ReadTimeout) {
duration := &shared.TimeDuration{}
err = json.Unmarshal([]byte(fastcgi.ReadTimeout), duration)
if err != nil {
return nil, err
}
config.ReadTimeout = duration
}
if IsNotNull(fastcgi.ConnTimeout) {
duration := &shared.TimeDuration{}
err = json.Unmarshal([]byte(fastcgi.ConnTimeout), duration)
if err != nil {
return nil, err
}
config.ConnTimeout = duration
}
if fastcgi.PoolSize > 0 {
config.PoolSize = types.Int(fastcgi.PoolSize)
}
config.PathInfoPattern = fastcgi.PathInfoPattern
return config, nil
}
// CreateFastcgi 创建Fastcgi
func (this *HTTPFastcgiDAO) CreateFastcgi(tx *dbs.Tx, adminId int64, userId int64, isOn bool, address string, paramsJSON []byte, readTimeoutJSON []byte, connTimeoutJSON []byte, poolSize int32, pathInfoPattern string) (int64, error) {
op := NewHTTPFastcgiOperator()
op.AdminId = adminId
op.UserId = userId
op.IsOn = isOn
op.Address = address
if len(paramsJSON) > 0 {
op.Params = paramsJSON
}
if len(readTimeoutJSON) > 0 {
op.ReadTimeout = readTimeoutJSON
}
if len(connTimeoutJSON) > 0 {
op.ConnTimeout = connTimeoutJSON
}
op.PoolSize = poolSize
op.PathInfoPattern = pathInfoPattern
op.State = HTTPFastcgiStateEnabled
return this.SaveInt64(tx, op)
}
// UpdateFastcgi 修改Fastcgi
func (this *HTTPFastcgiDAO) UpdateFastcgi(tx *dbs.Tx, fastcgiId int64, isOn bool, address string, paramsJSON []byte, readTimeoutJSON []byte, connTimeoutJSON []byte, poolSize int32, pathInfoPattern string) error {
if fastcgiId <= 0 {
return errors.New("invalid 'fastcgiId'")
}
op := NewHTTPFastcgiOperator()
op.Id = fastcgiId
op.IsOn = isOn
op.Address = address
if len(paramsJSON) > 0 {
op.Params = paramsJSON
}
if len(readTimeoutJSON) > 0 {
op.ReadTimeout = readTimeoutJSON
}
if len(connTimeoutJSON) > 0 {
op.ConnTimeout = connTimeoutJSON
}
op.PoolSize = poolSize
op.PathInfoPattern = pathInfoPattern
err := this.Save(tx, op)
if err != nil {
return err
}
return this.NotifyUpdate(tx, fastcgiId)
}
// CheckUserFastcgi 检查用户Fastcgi权限
func (this *HTTPFastcgiDAO) CheckUserFastcgi(tx *dbs.Tx, userId int64, fastcgiId int64) error {
if userId <= 0 || fastcgiId <= 0 {
return errors.New("permission error")
}
exists, err := this.Query(tx).
Pk(fastcgiId).
Attr("userId", userId).
State(HTTPFastcgiStateEnabled).
Exist()
if err != nil {
return err
}
if !exists {
return errors.New("permission error")
}
return nil
}
// NotifyUpdate 通知更新
func (this *HTTPFastcgiDAO) NotifyUpdate(tx *dbs.Tx, fastcgiId int64) error {
webId, err := SharedHTTPWebDAO.FindEnabledWebIdWithFastcgiId(tx, fastcgiId)
if err != nil {
return err
}
if webId > 0 {
return SharedHTTPWebDAO.NotifyUpdate(tx, webId)
}
return nil
}

View File

@@ -0,0 +1,6 @@
package models
import (
_ "github.com/go-sql-driver/mysql"
_ "github.com/iwind/TeaGo/bootstrap"
)

View File

@@ -0,0 +1,34 @@
package models
// HTTPFastcgi Fastcgi设置
type HTTPFastcgi struct {
Id uint64 `field:"id"` // ID
AdminId uint32 `field:"adminId"` // 管理员ID
UserId uint32 `field:"userId"` // 用户ID
IsOn uint8 `field:"isOn"` // 是否启用
Address string `field:"address"` // 地址
Params string `field:"params"` // 参数
ReadTimeout string `field:"readTimeout"` // 读取超时
ConnTimeout string `field:"connTimeout"` // 连接超时
PoolSize uint32 `field:"poolSize"` // 连接池尺寸
PathInfoPattern string `field:"pathInfoPattern"` // PATH_INFO匹配
State uint8 `field:"state"` // 状态
}
type HTTPFastcgiOperator struct {
Id interface{} // ID
AdminId interface{} // 管理员ID
UserId interface{} // 用户ID
IsOn interface{} // 是否启用
Address interface{} // 地址
Params interface{} // 参数
ReadTimeout interface{} // 读取超时
ConnTimeout interface{} // 连接超时
PoolSize interface{} // 连接池尺寸
PathInfoPattern interface{} // PATH_INFO匹配
State interface{} // 状态
}
func NewHTTPFastcgiOperator() *HTTPFastcgiOperator {
return &HTTPFastcgiOperator{}
}

View File

@@ -0,0 +1 @@
package models

View File

@@ -44,7 +44,7 @@ func (this *HTTPWebDAO) Init() {
_ = this.DAOObject.Init()
}
// 启用条目
// EnableHTTPWeb 启用条目
func (this *HTTPWebDAO) EnableHTTPWeb(tx *dbs.Tx, id int64) error {
_, err := this.Query(tx).
Pk(id).
@@ -53,7 +53,7 @@ func (this *HTTPWebDAO) EnableHTTPWeb(tx *dbs.Tx, id int64) error {
return err
}
// 禁用条目
// DisableHTTPWeb 禁用条目
func (this *HTTPWebDAO) DisableHTTPWeb(tx *dbs.Tx, id int64) error {
_, err := this.Query(tx).
Pk(id).
@@ -62,7 +62,7 @@ func (this *HTTPWebDAO) DisableHTTPWeb(tx *dbs.Tx, id int64) error {
return err
}
// 查找启用中的条目
// FindEnabledHTTPWeb 查找启用中的条目
func (this *HTTPWebDAO) FindEnabledHTTPWeb(tx *dbs.Tx, id int64) (*HTTPWeb, error) {
result, err := this.Query(tx).
Pk(id).
@@ -74,7 +74,7 @@ func (this *HTTPWebDAO) FindEnabledHTTPWeb(tx *dbs.Tx, id int64) (*HTTPWeb, erro
return result.(*HTTPWeb), err
}
// 组合配置
// ComposeWebConfig 组合配置
func (this *HTTPWebDAO) ComposeWebConfig(tx *dbs.Tx, webId int64) (*serverconfigs.HTTPWebConfig, error) {
web, err := SharedHTTPWebDAO.FindEnabledHTTPWeb(tx, webId)
if err != nil {
@@ -323,10 +323,34 @@ func (this *HTTPWebDAO) ComposeWebConfig(tx *dbs.Tx, webId int64) (*serverconfig
config.HostRedirects = redirects
}
// Fastcgi
if IsNotNull(web.Fastcgi) {
ref := &serverconfigs.HTTPFastcgiRef{}
err = json.Unmarshal([]byte(web.Fastcgi), ref)
if err != nil {
return nil, err
}
config.FastcgiRef = ref
if len(ref.FastcgiIds) > 0 {
list := []*serverconfigs.HTTPFastcgiConfig{}
for _, fastcgiId := range ref.FastcgiIds {
fastcgiConfig, err := SharedHTTPFastcgiDAO.ComposeFastcgiConfig(tx, fastcgiId)
if err != nil {
return nil, err
}
if fastcgiConfig != nil {
list = append(list, fastcgiConfig)
}
}
config.FastcgiList = list
}
}
return config, nil
}
// 创建Web配置
// CreateWeb 创建Web配置
func (this *HTTPWebDAO) CreateWeb(tx *dbs.Tx, adminId int64, userId int64, rootJSON []byte) (int64, error) {
op := NewHTTPWebOperator()
op.State = HTTPWebStateEnabled
@@ -342,7 +366,7 @@ func (this *HTTPWebDAO) CreateWeb(tx *dbs.Tx, adminId int64, userId int64, rootJ
return types.Int64(op.Id), nil
}
// 修改Web配置
// UpdateWeb 修改Web配置
func (this *HTTPWebDAO) UpdateWeb(tx *dbs.Tx, webId int64, rootJSON []byte) error {
if webId <= 0 {
return errors.New("invalid webId")
@@ -358,7 +382,7 @@ func (this *HTTPWebDAO) UpdateWeb(tx *dbs.Tx, webId int64, rootJSON []byte) erro
return this.NotifyUpdate(tx, webId)
}
// 修改Gzip配置
// UpdateWebGzip 修改Gzip配置
func (this *HTTPWebDAO) UpdateWebGzip(tx *dbs.Tx, webId int64, gzipJSON []byte) error {
if webId <= 0 {
return errors.New("invalid webId")
@@ -374,7 +398,7 @@ func (this *HTTPWebDAO) UpdateWebGzip(tx *dbs.Tx, webId int64, gzipJSON []byte)
return this.NotifyUpdate(tx, webId)
}
// 修改字符编码
// UpdateWebCharset 修改字符编码
func (this *HTTPWebDAO) UpdateWebCharset(tx *dbs.Tx, webId int64, charsetJSON []byte) error {
if webId <= 0 {
return errors.New("invalid webId")
@@ -390,7 +414,7 @@ func (this *HTTPWebDAO) UpdateWebCharset(tx *dbs.Tx, webId int64, charsetJSON []
return this.NotifyUpdate(tx, webId)
}
// 更改请求Header策略
// UpdateWebRequestHeaderPolicy 更改请求Header策略
func (this *HTTPWebDAO) UpdateWebRequestHeaderPolicy(tx *dbs.Tx, webId int64, headerPolicyJSON []byte) error {
if webId <= 0 {
return errors.New("invalid webId")
@@ -406,7 +430,7 @@ func (this *HTTPWebDAO) UpdateWebRequestHeaderPolicy(tx *dbs.Tx, webId int64, he
return this.NotifyUpdate(tx, webId)
}
// 更改响应Header策略
// UpdateWebResponseHeaderPolicy 更改响应Header策略
func (this *HTTPWebDAO) UpdateWebResponseHeaderPolicy(tx *dbs.Tx, webId int64, headerPolicyJSON []byte) error {
if webId <= 0 {
return errors.New("invalid webId")
@@ -422,7 +446,7 @@ func (this *HTTPWebDAO) UpdateWebResponseHeaderPolicy(tx *dbs.Tx, webId int64, h
return this.NotifyUpdate(tx, webId)
}
// 更改特殊页面配置
// UpdateWebPages 更改特殊页面配置
func (this *HTTPWebDAO) UpdateWebPages(tx *dbs.Tx, webId int64, pagesJSON []byte) error {
if webId <= 0 {
return errors.New("invalid webId")
@@ -438,7 +462,7 @@ func (this *HTTPWebDAO) UpdateWebPages(tx *dbs.Tx, webId int64, pagesJSON []byte
return this.NotifyUpdate(tx, webId)
}
// 更改Shutdown配置
// UpdateWebShutdown 更改Shutdown配置
func (this *HTTPWebDAO) UpdateWebShutdown(tx *dbs.Tx, webId int64, shutdownJSON []byte) error {
if webId <= 0 {
return errors.New("invalid webId")
@@ -454,7 +478,7 @@ func (this *HTTPWebDAO) UpdateWebShutdown(tx *dbs.Tx, webId int64, shutdownJSON
return this.NotifyUpdate(tx, webId)
}
// 更改访问日志策略
// UpdateWebAccessLogConfig 更改访问日志策略
func (this *HTTPWebDAO) UpdateWebAccessLogConfig(tx *dbs.Tx, webId int64, accessLogJSON []byte) error {
if webId <= 0 {
return errors.New("invalid webId")
@@ -470,7 +494,7 @@ func (this *HTTPWebDAO) UpdateWebAccessLogConfig(tx *dbs.Tx, webId int64, access
return this.NotifyUpdate(tx, webId)
}
// 更改统计配置
// UpdateWebStat 更改统计配置
func (this *HTTPWebDAO) UpdateWebStat(tx *dbs.Tx, webId int64, statJSON []byte) error {
if webId <= 0 {
return errors.New("invalid webId")
@@ -486,7 +510,7 @@ func (this *HTTPWebDAO) UpdateWebStat(tx *dbs.Tx, webId int64, statJSON []byte)
return this.NotifyUpdate(tx, webId)
}
// 更改缓存配置
// UpdateWebCache 更改缓存配置
func (this *HTTPWebDAO) UpdateWebCache(tx *dbs.Tx, webId int64, cacheJSON []byte) error {
if webId <= 0 {
return errors.New("invalid webId")
@@ -502,7 +526,7 @@ func (this *HTTPWebDAO) UpdateWebCache(tx *dbs.Tx, webId int64, cacheJSON []byte
return this.NotifyUpdate(tx, webId)
}
// 更改防火墙配置
// UpdateWebFirewall 更改防火墙配置
func (this *HTTPWebDAO) UpdateWebFirewall(tx *dbs.Tx, webId int64, firewallJSON []byte) error {
if webId <= 0 {
return errors.New("invalid webId")
@@ -518,7 +542,7 @@ func (this *HTTPWebDAO) UpdateWebFirewall(tx *dbs.Tx, webId int64, firewallJSON
return this.NotifyUpdate(tx, webId)
}
// 更改路径规则配置
// UpdateWebLocations 更改路径规则配置
func (this *HTTPWebDAO) UpdateWebLocations(tx *dbs.Tx, webId int64, locationsJSON []byte) error {
if webId <= 0 {
return errors.New("invalid webId")
@@ -534,7 +558,7 @@ func (this *HTTPWebDAO) UpdateWebLocations(tx *dbs.Tx, webId int64, locationsJSO
return this.NotifyUpdate(tx, webId)
}
// 更改跳转到HTTPS设置
// UpdateWebRedirectToHTTPS 更改跳转到HTTPS设置
func (this *HTTPWebDAO) UpdateWebRedirectToHTTPS(tx *dbs.Tx, webId int64, redirectToHTTPSJSON []byte) error {
if webId <= 0 {
return errors.New("invalid webId")
@@ -550,7 +574,7 @@ func (this *HTTPWebDAO) UpdateWebRedirectToHTTPS(tx *dbs.Tx, webId int64, redire
return this.NotifyUpdate(tx, webId)
}
// 修改Websocket设置
// UpdateWebsocket 修改Websocket设置
func (this *HTTPWebDAO) UpdateWebsocket(tx *dbs.Tx, webId int64, websocketJSON []byte) error {
if webId <= 0 {
return errors.New("invalid webId")
@@ -566,7 +590,23 @@ func (this *HTTPWebDAO) UpdateWebsocket(tx *dbs.Tx, webId int64, websocketJSON [
return this.NotifyUpdate(tx, webId)
}
// 修改重写规则设置
// UpdateWebFastcgi 修改Fastcgi设置
func (this *HTTPWebDAO) UpdateWebFastcgi(tx *dbs.Tx, webId int64, fastcgiJSON []byte) error {
if webId <= 0 {
return errors.New("invalid webId")
}
op := NewHTTPWebOperator()
op.Id = webId
op.Fastcgi = JSONBytes(fastcgiJSON)
err := this.Save(tx, op)
if err != nil {
return err
}
return this.NotifyUpdate(tx, webId)
}
// UpdateWebRewriteRules 修改重写规则设置
func (this *HTTPWebDAO) UpdateWebRewriteRules(tx *dbs.Tx, webId int64, rewriteRulesJSON []byte) error {
if webId <= 0 {
return errors.New("invalid webId")
@@ -582,7 +622,7 @@ func (this *HTTPWebDAO) UpdateWebRewriteRules(tx *dbs.Tx, webId int64, rewriteRu
return this.NotifyUpdate(tx, webId)
}
// 根据缓存策略ID查找所有的WebId
// FindAllWebIdsWithCachePolicyId 根据缓存策略ID查找所有的WebId
func (this *HTTPWebDAO) FindAllWebIdsWithCachePolicyId(tx *dbs.Tx, cachePolicyId int64) ([]int64, error) {
ones, err := this.Query(tx).
State(HTTPWebStateEnabled).
@@ -626,7 +666,7 @@ func (this *HTTPWebDAO) FindAllWebIdsWithCachePolicyId(tx *dbs.Tx, cachePolicyId
return result, nil
}
// 根据防火墙策略ID查找所有的WebId
// FindAllWebIdsWithHTTPFirewallPolicyId 根据防火墙策略ID查找所有的WebId
func (this *HTTPWebDAO) FindAllWebIdsWithHTTPFirewallPolicyId(tx *dbs.Tx, firewallPolicyId int64) ([]int64, error) {
ones, err := this.Query(tx).
State(HTTPWebStateEnabled).
@@ -673,7 +713,7 @@ func (this *HTTPWebDAO) FindAllWebIdsWithHTTPFirewallPolicyId(tx *dbs.Tx, firewa
return result, nil
}
// 查找包含某个Location的Web
// FindEnabledWebIdWithLocationId 查找包含某个Location的Web
func (this *HTTPWebDAO) FindEnabledWebIdWithLocationId(tx *dbs.Tx, locationId int64) (webId int64, err error) {
return this.Query(tx).
State(HTTPWebStateEnabled).
@@ -683,7 +723,7 @@ func (this *HTTPWebDAO) FindEnabledWebIdWithLocationId(tx *dbs.Tx, locationId in
FindInt64Col(0)
}
// 查找包含某个重写规则的Web
// FindEnabledWebIdWithRewriteRuleId 查找包含某个重写规则的Web
func (this *HTTPWebDAO) FindEnabledWebIdWithRewriteRuleId(tx *dbs.Tx, rewriteRuleId int64) (webId int64, err error) {
return this.Query(tx).
State(HTTPWebStateEnabled).
@@ -693,7 +733,7 @@ func (this *HTTPWebDAO) FindEnabledWebIdWithRewriteRuleId(tx *dbs.Tx, rewriteRul
FindInt64Col(0)
}
// 查找包含某个页面的Web
// FindEnabledWebIdWithPageId 查找包含某个页面的Web
func (this *HTTPWebDAO) FindEnabledWebIdWithPageId(tx *dbs.Tx, pageId int64) (webId int64, err error) {
return this.Query(tx).
State(HTTPWebStateEnabled).
@@ -703,7 +743,7 @@ func (this *HTTPWebDAO) FindEnabledWebIdWithPageId(tx *dbs.Tx, pageId int64) (we
FindInt64Col(0)
}
// 查找包含某个Header的Web
// FindEnabledWebIdWithHeaderPolicyId 查找包含某个Header的Web
func (this *HTTPWebDAO) FindEnabledWebIdWithHeaderPolicyId(tx *dbs.Tx, headerPolicyId int64) (webId int64, err error) {
return this.Query(tx).
State(HTTPWebStateEnabled).
@@ -713,7 +753,7 @@ func (this *HTTPWebDAO) FindEnabledWebIdWithHeaderPolicyId(tx *dbs.Tx, headerPol
FindInt64Col(0)
}
// 查找包含某个Gzip配置的Web
// FindEnabledWebIdWithGzipId 查找包含某个Gzip配置的Web
func (this *HTTPWebDAO) FindEnabledWebIdWithGzipId(tx *dbs.Tx, gzipId int64) (webId int64, err error) {
return this.Query(tx).
State(HTTPWebStateEnabled).
@@ -723,7 +763,7 @@ func (this *HTTPWebDAO) FindEnabledWebIdWithGzipId(tx *dbs.Tx, gzipId int64) (we
FindInt64Col(0)
}
// 查找包含某个Websocket配置的Web
// FindEnabledWebIdWithWebsocketId 查找包含某个Websocket配置的Web
func (this *HTTPWebDAO) FindEnabledWebIdWithWebsocketId(tx *dbs.Tx, websocketId int64) (webId int64, err error) {
return this.Query(tx).
State(HTTPWebStateEnabled).
@@ -733,7 +773,17 @@ func (this *HTTPWebDAO) FindEnabledWebIdWithWebsocketId(tx *dbs.Tx, websocketId
FindInt64Col(0)
}
// 查找使用此Web的Server
// FindEnabledWebIdWithFastcgiId 查找包含某个Fastcgi配置的Web
func (this *HTTPWebDAO) FindEnabledWebIdWithFastcgiId(tx *dbs.Tx, fastcgiId int64) (webId int64, err error) {
return this.Query(tx).
State(HTTPWebStateEnabled).
ResultPk().
Where("JSON_CONTAINS(fastcgi, :jsonQuery)").
Param("jsonQuery", maps.Map{"fastcgiIds": fastcgiId}.AsJSON()).
FindInt64Col(0)
}
// FindWebServerId 查找使用此Web的Server
func (this *HTTPWebDAO) FindWebServerId(tx *dbs.Tx, webId int64) (serverId int64, err error) {
if webId <= 0 {
return 0, nil
@@ -766,7 +816,7 @@ func (this *HTTPWebDAO) FindWebServerId(tx *dbs.Tx, webId int64) (serverId int64
return this.FindWebServerId(tx, webId)
}
// 检查用户权限
// CheckUserWeb 检查用户权限
func (this *HTTPWebDAO) CheckUserWeb(tx *dbs.Tx, userId int64, webId int64) error {
serverId, err := this.FindWebServerId(tx, webId)
if err != nil {
@@ -778,7 +828,7 @@ func (this *HTTPWebDAO) CheckUserWeb(tx *dbs.Tx, userId int64, webId int64) erro
return SharedServerDAO.CheckUserServer(tx, userId, serverId)
}
// 设置主机跳转
// UpdateWebHostRedirects 设置主机跳转
func (this *HTTPWebDAO) UpdateWebHostRedirects(tx *dbs.Tx, webId int64, hostRedirects []*serverconfigs.HTTPHostRedirectConfig) error {
if webId <= 0 {
return errors.New("invalid ")
@@ -801,7 +851,7 @@ func (this *HTTPWebDAO) UpdateWebHostRedirects(tx *dbs.Tx, webId int64, hostRedi
return this.NotifyUpdate(tx, webId)
}
// 查找主机跳转
// FindWebHostRedirects 查找主机跳转
func (this *HTTPWebDAO) FindWebHostRedirects(tx *dbs.Tx, webId int64) ([]byte, error) {
col, err := this.Query(tx).
Pk(webId).
@@ -813,7 +863,7 @@ func (this *HTTPWebDAO) FindWebHostRedirects(tx *dbs.Tx, webId int64) ([]byte, e
return []byte(col), nil
}
// 通知更新
// NotifyUpdate 通知更新
func (this *HTTPWebDAO) NotifyUpdate(tx *dbs.Tx, webId int64) error {
serverId, err := this.FindWebServerId(tx, webId)
if err != nil {

View File

@@ -1,6 +1,6 @@
package models
// HTTP Web
// HTTPWeb HTTP Web
type HTTPWeb struct {
Id uint32 `field:"id"` // ID
IsOn uint8 `field:"isOn"` // 是否启用
@@ -27,6 +27,7 @@ type HTTPWeb struct {
Websocket string `field:"websocket"` // Websocket设置
RewriteRules string `field:"rewriteRules"` // 重写规则配置
HostRedirects string `field:"hostRedirects"` // 域名跳转
Fastcgi string `field:"fastcgi"` // Fastcgi配置
}
type HTTPWebOperator struct {
@@ -55,6 +56,7 @@ type HTTPWebOperator struct {
Websocket interface{} // Websocket设置
RewriteRules interface{} // 重写规则配置
HostRedirects interface{} // 域名跳转
Fastcgi interface{} // Fastcgi配置
}
func NewHTTPWebOperator() *HTTPWebOperator {

View File

@@ -0,0 +1,51 @@
package models
import (
_ "github.com/go-sql-driver/mysql"
"github.com/iwind/TeaGo/Tea"
"github.com/iwind/TeaGo/dbs"
"github.com/iwind/TeaGo/maps"
"time"
)
type LatestItemType = string
const (
LatestItemTypeCluster LatestItemType = "cluster"
LatestItemTypeServer LatestItemType = "server"
)
type LatestItemDAO dbs.DAO
func NewLatestItemDAO() *LatestItemDAO {
return dbs.NewDAO(&LatestItemDAO{
DAOObject: dbs.DAOObject{
DB: Tea.Env,
Table: "edgeLatestItems",
Model: new(LatestItem),
PkName: "id",
},
}).(*LatestItemDAO)
}
var SharedLatestItemDAO *LatestItemDAO
func init() {
dbs.OnReady(func() {
SharedLatestItemDAO = NewLatestItemDAO()
})
}
// IncreaseItemCount 增加数量
func (this *LatestItemDAO) IncreaseItemCount(tx *dbs.Tx, itemType LatestItemType, itemId int64) error {
return this.Query(tx).
InsertOrUpdateQuickly(maps.Map{
"itemType": itemType,
"itemId": itemId,
"count": 1,
"updatedAt": time.Now().Unix(),
}, maps.Map{
"count": dbs.SQL("count+1"),
"updatedAt": time.Now().Unix(),
})
}

View File

@@ -0,0 +1,6 @@
package models
import (
_ "github.com/go-sql-driver/mysql"
_ "github.com/iwind/TeaGo/bootstrap"
)

View File

@@ -0,0 +1,22 @@
package models
// LatestItem 最近的条目统计
type LatestItem struct {
Id uint64 `field:"id"` // ID
ItemType string `field:"itemType"` // Item类型
ItemId uint64 `field:"itemId"` // itemID
Count uint64 `field:"count"` // 数量
UpdatedAt uint64 `field:"updatedAt"` // 更新时间
}
type LatestItemOperator struct {
Id interface{} // ID
ItemType interface{} // Item类型
ItemId interface{} // itemID
Count interface{} // 数量
UpdatedAt interface{} // 更新时间
}
func NewLatestItemOperator() *LatestItemOperator {
return &LatestItemOperator{}
}

View File

@@ -0,0 +1 @@
package models

View File

@@ -37,6 +37,7 @@ const (
MessageTypeLogCapacityOverflow MessageType = "LogCapacityOverflow" // 日志超出最大限制
MessageTypeServerNamesAuditingSuccess MessageType = "ServerNamesAuditingSuccess" // 服务域名审核成功
MessageTypeServerNamesAuditingFailed MessageType = "ServerNamesAuditingFailed" // 服务域名审核失败
MessageTypeThresholdSatisfied MessageType = "ThresholdSatisfied" // 满足阈值
)
type MessageDAO dbs.DAO
@@ -112,7 +113,20 @@ func (this *MessageDAO) CreateClusterMessage(tx *dbs.Tx, clusterId int64, messag
// CreateNodeMessage 创建节点消息
func (this *MessageDAO) CreateNodeMessage(tx *dbs.Tx, clusterId int64, nodeId int64, messageType MessageType, level string, subject string, body string, paramsJSON []byte) error {
_, err := this.createMessage(tx, clusterId, nodeId, messageType, level, subject, body, paramsJSON)
// 检查N分钟内是否已经发送过
hash := this.calHash(subject, body, paramsJSON)
exists, err := this.Query(tx).
Attr("hash", hash).
Gt("createdAt", time.Now().Unix()-10*60). // 10分钟
Exist()
if err != nil {
return err
}
if exists {
return nil
}
_, err = this.createMessage(tx, clusterId, nodeId, messageType, level, subject, body, paramsJSON)
if err != nil {
return err
}
@@ -144,11 +158,6 @@ func (this *MessageDAO) CreateNodeMessage(tx *dbs.Tx, clusterId int64, nodeId in
// CreateMessage 创建普通消息
func (this *MessageDAO) CreateMessage(tx *dbs.Tx, adminId int64, userId int64, messageType MessageType, level string, subject string, body string, paramsJSON []byte) error {
h := md5.New()
h.Write([]byte(body))
h.Write(paramsJSON)
hash := fmt.Sprintf("%x", h.Sum(nil))
op := NewMessageOperator()
op.AdminId = adminId
op.UserId = userId
@@ -169,7 +178,7 @@ func (this *MessageDAO) CreateMessage(tx *dbs.Tx, adminId int64, userId int64, m
op.State = MessageStateEnabled
op.IsRead = false
op.Day = timeutil.Format("Ymd")
op.Hash = hash
op.Hash = this.calHash(subject, body, paramsJSON)
err := this.Save(tx, op)
if err != nil {
return err
@@ -278,11 +287,6 @@ func (this *MessageDAO) CheckMessageUser(tx *dbs.Tx, messageId int64, adminId in
// 创建消息
func (this *MessageDAO) createMessage(tx *dbs.Tx, clusterId int64, nodeId int64, messageType MessageType, level string, subject string, body string, paramsJSON []byte) (int64, error) {
h := md5.New()
h.Write([]byte(body))
h.Write(paramsJSON)
hash := fmt.Sprintf("%x", h.Sum(nil))
// TODO 检查同样的消息最近是否发送过
// 创建新消息
@@ -309,7 +313,7 @@ func (this *MessageDAO) createMessage(tx *dbs.Tx, clusterId int64, nodeId int64,
op.State = MessageStateEnabled
op.CreatedAt = time.Now().Unix()
op.Day = timeutil.Format("Ymd")
op.Hash = hash
op.Hash = this.calHash(subject, body, paramsJSON)
err := this.Save(tx, op)
if err != nil {
@@ -317,3 +321,12 @@ func (this *MessageDAO) createMessage(tx *dbs.Tx, clusterId int64, nodeId int64,
}
return types.Int64(op.Id), nil
}
// 计算Hash
func (this *MessageDAO) calHash(subject string, body string, paramsJSON []byte) string {
h := md5.New()
h.Write([]byte(subject))
h.Write([]byte(body))
h.Write(paramsJSON)
return fmt.Sprintf("%x", h.Sum(nil))
}

View File

@@ -97,8 +97,8 @@ func (this *MessageReceiverDAO) CreateReceiver(tx *dbs.Tx, target MessageTaskTar
return this.SaveInt64(tx, op)
}
// FindAllReceivers 查询接收人
func (this *MessageReceiverDAO) FindAllReceivers(tx *dbs.Tx, target MessageTaskTarget, messageType string) (result []*MessageReceiver, err error) {
// FindAllEnabledReceivers 查询接收人
func (this *MessageReceiverDAO) FindAllEnabledReceivers(tx *dbs.Tx, target MessageTaskTarget, messageType string) (result []*MessageReceiver, err error) {
query := this.Query(tx)
if len(messageType) > 0 {
query.Attr("type", []string{"*", messageType}) // *表示所有的
@@ -113,3 +113,17 @@ func (this *MessageReceiverDAO) FindAllReceivers(tx *dbs.Tx, target MessageTaskT
FindAll()
return
}
// CountAllEnabledReceivers 计算接收人数量
func (this *MessageReceiverDAO) CountAllEnabledReceivers(tx *dbs.Tx, target MessageTaskTarget, messageType string) (int64, error) {
query := this.Query(tx)
if len(messageType) > 0 {
query.Attr("type", []string{"*", messageType}) // *表示所有的
}
return query.
Attr("clusterId", target.ClusterId).
Attr("nodeId", target.NodeId).
Attr("serverId", target.ServerId).
State(MessageReceiverStateEnabled).
Count()
}

View File

@@ -118,7 +118,7 @@ func (this *MessageTaskDAO) UpdateMessageTaskStatus(tx *dbs.Tx, taskId int64, st
// CreateMessageTasks 从集群、节点或者服务中创建任务
func (this *MessageTaskDAO) CreateMessageTasks(tx *dbs.Tx, target MessageTaskTarget, messageType MessageType, subject string, body string) error {
receivers, err := SharedMessageReceiverDAO.FindAllReceivers(tx, target, messageType)
receivers, err := SharedMessageReceiverDAO.FindAllEnabledReceivers(tx, target, messageType)
if err != nil {
return err
}

View File

@@ -2,6 +2,7 @@ package models
import (
"github.com/TeaOSLab/EdgeAPI/internal/errors"
"github.com/TeaOSLab/EdgeAPI/internal/utils"
_ "github.com/go-sql-driver/mysql"
"github.com/iwind/TeaGo/Tea"
"github.com/iwind/TeaGo/dbs"
@@ -195,3 +196,13 @@ func (this *MonitorNodeDAO) UpdateNodeStatus(tx *dbs.Tx, nodeId int64, statusJSO
Update()
return err
}
// CountAllLowerVersionNodes 计算所有节点中低于某个版本的节点数量
func (this *MonitorNodeDAO) CountAllLowerVersionNodes(tx *dbs.Tx, version string) (int64, error) {
return this.Query(tx).
State(MonitorNodeStateEnabled).
Where("status IS NOT NULL").
Where("(JSON_EXTRACT(status, '$.buildVersionCode') IS NULL OR JSON_EXTRACT(status, '$.buildVersionCode')<:version)").
Param("version", utils.VersionToLong(version)).
Count()
}

View File

@@ -44,7 +44,7 @@ func init() {
})
}
// 启用条目
// EnableNodeCluster 启用条目
func (this *NodeClusterDAO) EnableNodeCluster(tx *dbs.Tx, id int64) error {
_, err := this.Query(tx).
Pk(id).
@@ -53,7 +53,7 @@ func (this *NodeClusterDAO) EnableNodeCluster(tx *dbs.Tx, id int64) error {
return err
}
// 禁用条目
// DisableNodeCluster 禁用条目
func (this *NodeClusterDAO) DisableNodeCluster(tx *dbs.Tx, id int64) error {
_, err := this.Query(tx).
Pk(id).
@@ -62,7 +62,7 @@ func (this *NodeClusterDAO) DisableNodeCluster(tx *dbs.Tx, id int64) error {
return err
}
// 查找集群
// FindEnabledNodeCluster 查找集群
func (this *NodeClusterDAO) FindEnabledNodeCluster(tx *dbs.Tx, id int64) (*NodeCluster, error) {
result, err := this.Query(tx).
Pk(id).
@@ -74,7 +74,7 @@ func (this *NodeClusterDAO) FindEnabledNodeCluster(tx *dbs.Tx, id int64) (*NodeC
return result.(*NodeCluster), err
}
// 根据UniqueId获取ID
// FindEnabledClusterIdWithUniqueId 根据UniqueId获取ID
// TODO 增加缓存
func (this *NodeClusterDAO) FindEnabledClusterIdWithUniqueId(tx *dbs.Tx, uniqueId string) (int64, error) {
return this.Query(tx).
@@ -84,7 +84,7 @@ func (this *NodeClusterDAO) FindEnabledClusterIdWithUniqueId(tx *dbs.Tx, uniqueI
FindInt64Col(0)
}
// 根据主键查找名称
// FindNodeClusterName 根据主键查找名称
func (this *NodeClusterDAO) FindNodeClusterName(tx *dbs.Tx, id int64) (string, error) {
return this.Query(tx).
Pk(id).
@@ -92,7 +92,7 @@ func (this *NodeClusterDAO) FindNodeClusterName(tx *dbs.Tx, id int64) (string, e
FindStringCol("")
}
// 查找所有可用的集群
// FindAllEnableClusters 查找所有可用的集群
func (this *NodeClusterDAO) FindAllEnableClusters(tx *dbs.Tx) (result []*NodeCluster, err error) {
_, err = this.Query(tx).
State(NodeClusterStateEnabled).
@@ -103,7 +103,7 @@ func (this *NodeClusterDAO) FindAllEnableClusters(tx *dbs.Tx) (result []*NodeClu
return
}
// 查找所有可用的集群Ids
// FindAllEnableClusterIds 查找所有可用的集群Ids
func (this *NodeClusterDAO) FindAllEnableClusterIds(tx *dbs.Tx) (result []int64, err error) {
ones, err := this.Query(tx).
State(NodeClusterStateEnabled).
@@ -118,7 +118,7 @@ func (this *NodeClusterDAO) FindAllEnableClusterIds(tx *dbs.Tx) (result []int64,
return
}
// 创建集群
// CreateCluster 创建集群
func (this *NodeClusterDAO) CreateCluster(tx *dbs.Tx, adminId int64, name string, grantId int64, installDir string, dnsDomainId int64, dnsName string, cachePolicyId int64, httpFirewallPolicyId int64, systemServices map[string]maps.Map) (clusterId int64, err error) {
uniqueId, err := this.GenUniqueId(tx)
if err != nil {
@@ -176,7 +176,7 @@ func (this *NodeClusterDAO) CreateCluster(tx *dbs.Tx, adminId int64, name string
return types.Int64(op.Id), nil
}
// 修改集群
// UpdateCluster 修改集群
func (this *NodeClusterDAO) UpdateCluster(tx *dbs.Tx, clusterId int64, name string, grantId int64, installDir string) error {
if clusterId <= 0 {
return errors.New("invalid clusterId")
@@ -190,7 +190,7 @@ func (this *NodeClusterDAO) UpdateCluster(tx *dbs.Tx, clusterId int64, name stri
return err
}
// 计算所有集群数量
// CountAllEnabledClusters 计算所有集群数量
func (this *NodeClusterDAO) CountAllEnabledClusters(tx *dbs.Tx, keyword string) (int64, error) {
query := this.Query(tx).
State(NodeClusterStateEnabled)
@@ -201,7 +201,7 @@ func (this *NodeClusterDAO) CountAllEnabledClusters(tx *dbs.Tx, keyword string)
return query.Count()
}
// 列出单页集群
// ListEnabledClusters 列出单页集群
func (this *NodeClusterDAO) ListEnabledClusters(tx *dbs.Tx, keyword string, offset, size int64) (result []*NodeCluster, err error) {
query := this.Query(tx).
State(NodeClusterStateEnabled)
@@ -218,7 +218,7 @@ func (this *NodeClusterDAO) ListEnabledClusters(tx *dbs.Tx, keyword string, offs
return
}
// 查找所有API节点地址
// FindAllAPINodeAddrsWithCluster 查找所有API节点地址
func (this *NodeClusterDAO) FindAllAPINodeAddrsWithCluster(tx *dbs.Tx, clusterId int64) (result []string, err error) {
one, err := this.Query(tx).
Pk(clusterId).
@@ -274,7 +274,7 @@ func (this *NodeClusterDAO) FindAllAPINodeAddrsWithCluster(tx *dbs.Tx, clusterId
return result, nil
}
// 查找健康检查设置
// FindClusterHealthCheckConfig 查找健康检查设置
func (this *NodeClusterDAO) FindClusterHealthCheckConfig(tx *dbs.Tx, clusterId int64) (*serverconfigs.HealthCheckConfig, error) {
col, err := this.Query(tx).
Pk(clusterId).
@@ -295,7 +295,7 @@ func (this *NodeClusterDAO) FindClusterHealthCheckConfig(tx *dbs.Tx, clusterId i
return config, nil
}
// 修改健康检查设置
// UpdateClusterHealthCheck 修改健康检查设置
func (this *NodeClusterDAO) UpdateClusterHealthCheck(tx *dbs.Tx, clusterId int64, healthCheckJSON []byte) error {
if clusterId <= 0 {
return errors.New("invalid clusterId '" + strconv.FormatInt(clusterId, 10) + "'")
@@ -310,7 +310,7 @@ func (this *NodeClusterDAO) UpdateClusterHealthCheck(tx *dbs.Tx, clusterId int64
return this.NotifyUpdate(tx, clusterId)
}
// 计算使用某个认证的集群数量
// CountAllEnabledClustersWithGrantId 计算使用某个认证的集群数量
func (this *NodeClusterDAO) CountAllEnabledClustersWithGrantId(tx *dbs.Tx, grantId int64) (int64, error) {
return this.Query(tx).
State(NodeClusterStateEnabled).
@@ -318,7 +318,7 @@ func (this *NodeClusterDAO) CountAllEnabledClustersWithGrantId(tx *dbs.Tx, grant
Count()
}
// 获取使用某个认证的所有集群
// FindAllEnabledClustersWithGrantId 获取使用某个认证的所有集群
func (this *NodeClusterDAO) FindAllEnabledClustersWithGrantId(tx *dbs.Tx, grantId int64) (result []*NodeCluster, err error) {
_, err = this.Query(tx).
State(NodeClusterStateEnabled).
@@ -329,7 +329,7 @@ func (this *NodeClusterDAO) FindAllEnabledClustersWithGrantId(tx *dbs.Tx, grantI
return
}
// 计算使用某个DNS服务商的集群数量
// CountAllEnabledClustersWithDNSProviderId 计算使用某个DNS服务商的集群数量
func (this *NodeClusterDAO) CountAllEnabledClustersWithDNSProviderId(tx *dbs.Tx, dnsProviderId int64) (int64, error) {
return this.Query(tx).
State(NodeClusterStateEnabled).
@@ -338,7 +338,7 @@ func (this *NodeClusterDAO) CountAllEnabledClustersWithDNSProviderId(tx *dbs.Tx,
Count()
}
// 获取所有使用某个DNS服务商的集群
// FindAllEnabledClustersWithDNSProviderId 获取所有使用某个DNS服务商的集群
func (this *NodeClusterDAO) FindAllEnabledClustersWithDNSProviderId(tx *dbs.Tx, dnsProviderId int64) (result []*NodeCluster, err error) {
_, err = this.Query(tx).
State(NodeClusterStateEnabled).
@@ -350,7 +350,7 @@ func (this *NodeClusterDAO) FindAllEnabledClustersWithDNSProviderId(tx *dbs.Tx,
return
}
// 计算使用某个DNS域名的集群数量
// CountAllEnabledClustersWithDNSDomainId 计算使用某个DNS域名的集群数量
func (this *NodeClusterDAO) CountAllEnabledClustersWithDNSDomainId(tx *dbs.Tx, dnsDomainId int64) (int64, error) {
return this.Query(tx).
State(NodeClusterStateEnabled).
@@ -358,7 +358,7 @@ func (this *NodeClusterDAO) CountAllEnabledClustersWithDNSDomainId(tx *dbs.Tx, d
Count()
}
// 查询使用某个DNS域名的集群ID列表
// FindAllEnabledClusterIdsWithDNSDomainId 查询使用某个DNS域名的集群ID列表
func (this *NodeClusterDAO) FindAllEnabledClusterIdsWithDNSDomainId(tx *dbs.Tx, dnsDomainId int64) ([]int64, error) {
ones, err := this.Query(tx).
State(NodeClusterStateEnabled).
@@ -375,7 +375,7 @@ func (this *NodeClusterDAO) FindAllEnabledClusterIdsWithDNSDomainId(tx *dbs.Tx,
return result, nil
}
// 查询使用某个DNS域名的所有集群域名
// FindAllEnabledClustersWithDNSDomainId 查询使用某个DNS域名的所有集群域名
func (this *NodeClusterDAO) FindAllEnabledClustersWithDNSDomainId(tx *dbs.Tx, dnsDomainId int64) (result []*NodeCluster, err error) {
_, err = this.Query(tx).
State(NodeClusterStateEnabled).
@@ -386,7 +386,7 @@ func (this *NodeClusterDAO) FindAllEnabledClustersWithDNSDomainId(tx *dbs.Tx, dn
return
}
// 查询已经设置了域名的集群
// FindAllEnabledClustersHaveDNSDomain 查询已经设置了域名的集群
func (this *NodeClusterDAO) FindAllEnabledClustersHaveDNSDomain(tx *dbs.Tx) (result []*NodeCluster, err error) {
_, err = this.Query(tx).
State(NodeClusterStateEnabled).
@@ -397,7 +397,7 @@ func (this *NodeClusterDAO) FindAllEnabledClustersHaveDNSDomain(tx *dbs.Tx) (res
return
}
// 查找集群的认证ID
// FindClusterGrantId 查找集群的认证ID
func (this *NodeClusterDAO) FindClusterGrantId(tx *dbs.Tx, clusterId int64) (int64, error) {
return this.Query(tx).
Pk(clusterId).
@@ -405,7 +405,7 @@ func (this *NodeClusterDAO) FindClusterGrantId(tx *dbs.Tx, clusterId int64) (int
FindInt64Col(0)
}
// 查找DNS信息
// FindClusterDNSInfo 查找DNS信息
func (this *NodeClusterDAO) FindClusterDNSInfo(tx *dbs.Tx, clusterId int64) (*NodeCluster, error) {
one, err := this.Query(tx).
Pk(clusterId).
@@ -420,7 +420,7 @@ func (this *NodeClusterDAO) FindClusterDNSInfo(tx *dbs.Tx, clusterId int64) (*No
return one.(*NodeCluster), nil
}
// 检查某个子域名是否可用
// ExistClusterDNSName 检查某个子域名是否可用
func (this *NodeClusterDAO) ExistClusterDNSName(tx *dbs.Tx, dnsName string, excludeClusterId int64) (bool, error) {
return this.Query(tx).
Attr("dnsName", dnsName).
@@ -430,7 +430,7 @@ func (this *NodeClusterDAO) ExistClusterDNSName(tx *dbs.Tx, dnsName string, excl
Exist()
}
// 修改集群DNS相关信息
// UpdateClusterDNS 修改集群DNS相关信息
func (this *NodeClusterDAO) UpdateClusterDNS(tx *dbs.Tx, clusterId int64, dnsName string, dnsDomainId int64, nodesAutoSync bool, serversAutoSync bool) error {
if clusterId <= 0 {
return errors.New("invalid clusterId")
@@ -461,7 +461,7 @@ func (this *NodeClusterDAO) UpdateClusterDNS(tx *dbs.Tx, clusterId int64, dnsNam
return this.NotifyDNSUpdate(tx, clusterId)
}
// 检查集群的DNS问题
// CheckClusterDNS 检查集群的DNS问题
func (this *NodeClusterDAO) CheckClusterDNS(tx *dbs.Tx, cluster *NodeCluster) (issues []*pb.DNSIssue, err error) {
clusterId := int64(cluster.Id)
domainId := int64(cluster.DnsDomainId)
@@ -573,7 +573,7 @@ func (this *NodeClusterDAO) CheckClusterDNS(tx *dbs.Tx, cluster *NodeCluster) (i
return
}
// 查找集群所属管理员
// FindClusterAdminId 查找集群所属管理员
func (this *NodeClusterDAO) FindClusterAdminId(tx *dbs.Tx, clusterId int64) (int64, error) {
return this.Query(tx).
Pk(clusterId).
@@ -581,7 +581,7 @@ func (this *NodeClusterDAO) FindClusterAdminId(tx *dbs.Tx, clusterId int64) (int
FindInt64Col(0)
}
// 查找集群的TOA设置
// FindClusterTOAConfig 查找集群的TOA设置
func (this *NodeClusterDAO) FindClusterTOAConfig(tx *dbs.Tx, clusterId int64) (*nodeconfigs.TOAConfig, error) {
toa, err := this.Query(tx).
Pk(clusterId).
@@ -602,7 +602,7 @@ func (this *NodeClusterDAO) FindClusterTOAConfig(tx *dbs.Tx, clusterId int64) (*
return config, nil
}
// 修改集群的TOA设置
// UpdateClusterTOA 修改集群的TOA设置
func (this *NodeClusterDAO) UpdateClusterTOA(tx *dbs.Tx, clusterId int64, toaJSON []byte) error {
if clusterId <= 0 {
return errors.New("invalid clusterId")
@@ -617,7 +617,7 @@ func (this *NodeClusterDAO) UpdateClusterTOA(tx *dbs.Tx, clusterId int64, toaJSO
return this.NotifyUpdate(tx, clusterId)
}
// 计算使用某个缓存策略的集群数量
// CountAllEnabledNodeClustersWithHTTPCachePolicyId 计算使用某个缓存策略的集群数量
func (this *NodeClusterDAO) CountAllEnabledNodeClustersWithHTTPCachePolicyId(tx *dbs.Tx, httpCachePolicyId int64) (int64, error) {
return this.Query(tx).
State(NodeClusterStateEnabled).
@@ -625,7 +625,7 @@ func (this *NodeClusterDAO) CountAllEnabledNodeClustersWithHTTPCachePolicyId(tx
Count()
}
// 查找使用缓存策略的所有集群
// FindAllEnabledNodeClustersWithHTTPCachePolicyId 查找使用缓存策略的所有集群
func (this *NodeClusterDAO) FindAllEnabledNodeClustersWithHTTPCachePolicyId(tx *dbs.Tx, httpCachePolicyId int64) (result []*NodeCluster, err error) {
_, err = this.Query(tx).
State(NodeClusterStateEnabled).
@@ -636,7 +636,7 @@ func (this *NodeClusterDAO) FindAllEnabledNodeClustersWithHTTPCachePolicyId(tx *
return
}
// 计算使用某个WAF策略的集群数量
// CountAllEnabledNodeClustersWithHTTPFirewallPolicyId 计算使用某个WAF策略的集群数量
func (this *NodeClusterDAO) CountAllEnabledNodeClustersWithHTTPFirewallPolicyId(tx *dbs.Tx, httpFirewallPolicyId int64) (int64, error) {
return this.Query(tx).
State(NodeClusterStateEnabled).
@@ -644,7 +644,7 @@ func (this *NodeClusterDAO) CountAllEnabledNodeClustersWithHTTPFirewallPolicyId(
Count()
}
// 查找使用WAF策略的所有集群
// FindAllEnabledNodeClustersWithHTTPFirewallPolicyId 查找使用WAF策略的所有集群
func (this *NodeClusterDAO) FindAllEnabledNodeClustersWithHTTPFirewallPolicyId(tx *dbs.Tx, httpFirewallPolicyId int64) (result []*NodeCluster, err error) {
_, err = this.Query(tx).
State(NodeClusterStateEnabled).
@@ -655,7 +655,7 @@ func (this *NodeClusterDAO) FindAllEnabledNodeClustersWithHTTPFirewallPolicyId(t
return
}
// 查找使用WAF策略的所有集群Ids
// FindAllEnabledNodeClusterIdsWithHTTPFirewallPolicyId 查找使用WAF策略的所有集群Ids
func (this *NodeClusterDAO) FindAllEnabledNodeClusterIdsWithHTTPFirewallPolicyId(tx *dbs.Tx, httpFirewallPolicyId int64) (result []int64, err error) {
ones, err := this.Query(tx).
State(NodeClusterStateEnabled).
@@ -668,7 +668,7 @@ func (this *NodeClusterDAO) FindAllEnabledNodeClusterIdsWithHTTPFirewallPolicyId
return
}
// 查找使用缓存策略的所有集群Ids
// FindAllEnabledNodeClusterIdsWithCachePolicyId 查找使用缓存策略的所有集群Ids
func (this *NodeClusterDAO) FindAllEnabledNodeClusterIdsWithCachePolicyId(tx *dbs.Tx, cachePolicyId int64) (result []int64, err error) {
ones, err := this.Query(tx).
State(NodeClusterStateEnabled).
@@ -681,7 +681,7 @@ func (this *NodeClusterDAO) FindAllEnabledNodeClusterIdsWithCachePolicyId(tx *db
return
}
// 获取集群的WAF策略ID
// FindClusterHTTPFirewallPolicyId 获取集群的WAF策略ID
func (this *NodeClusterDAO) FindClusterHTTPFirewallPolicyId(tx *dbs.Tx, clusterId int64) (int64, error) {
return this.Query(tx).
Pk(clusterId).
@@ -689,7 +689,7 @@ func (this *NodeClusterDAO) FindClusterHTTPFirewallPolicyId(tx *dbs.Tx, clusterI
FindInt64Col(0)
}
// 设置集群的缓存策略
// UpdateNodeClusterHTTPCachePolicyId 设置集群的缓存策略
func (this *NodeClusterDAO) UpdateNodeClusterHTTPCachePolicyId(tx *dbs.Tx, clusterId int64, httpCachePolicyId int64) error {
_, err := this.Query(tx).
Pk(clusterId).
@@ -701,7 +701,7 @@ func (this *NodeClusterDAO) UpdateNodeClusterHTTPCachePolicyId(tx *dbs.Tx, clust
return this.NotifyUpdate(tx, clusterId)
}
// 获取集群的缓存策略ID
// FindClusterHTTPCachePolicyId 获取集群的缓存策略ID
func (this *NodeClusterDAO) FindClusterHTTPCachePolicyId(tx *dbs.Tx, clusterId int64) (int64, error) {
return this.Query(tx).
Pk(clusterId).
@@ -709,7 +709,7 @@ func (this *NodeClusterDAO) FindClusterHTTPCachePolicyId(tx *dbs.Tx, clusterId i
FindInt64Col(0)
}
// 设置集群的WAF策略
// UpdateNodeClusterHTTPFirewallPolicyId 设置集群的WAF策略
func (this *NodeClusterDAO) UpdateNodeClusterHTTPFirewallPolicyId(tx *dbs.Tx, clusterId int64, httpFirewallPolicyId int64) error {
_, err := this.Query(tx).
Pk(clusterId).
@@ -721,7 +721,7 @@ func (this *NodeClusterDAO) UpdateNodeClusterHTTPFirewallPolicyId(tx *dbs.Tx, cl
return this.NotifyUpdate(tx, clusterId)
}
// 修改集群的系统服务设置
// UpdateNodeClusterSystemService 修改集群的系统服务设置
func (this *NodeClusterDAO) UpdateNodeClusterSystemService(tx *dbs.Tx, clusterId int64, serviceType nodeconfigs.SystemServiceType, params maps.Map) error {
if clusterId <= 0 {
return errors.New("invalid clusterId")
@@ -760,7 +760,7 @@ func (this *NodeClusterDAO) UpdateNodeClusterSystemService(tx *dbs.Tx, clusterId
return this.NotifyUpdate(tx, clusterId)
}
// 查找集群的系统服务设置
// FindNodeClusterSystemServiceParams 查找集群的系统服务设置
func (this *NodeClusterDAO) FindNodeClusterSystemServiceParams(tx *dbs.Tx, clusterId int64, serviceType nodeconfigs.SystemServiceType) (params maps.Map, err error) {
if clusterId <= 0 {
return nil, errors.New("invalid clusterId")
@@ -782,7 +782,7 @@ func (this *NodeClusterDAO) FindNodeClusterSystemServiceParams(tx *dbs.Tx, clust
return servicesMap[serviceType], nil
}
// 查找集群的所有服务设置
// FindNodeClusterSystemServices 查找集群的所有服务设置
func (this *NodeClusterDAO) FindNodeClusterSystemServices(tx *dbs.Tx, clusterId int64) (services map[string]maps.Map, err error) {
if clusterId <= 0 {
return nil, errors.New("invalid clusterId")
@@ -804,7 +804,7 @@ func (this *NodeClusterDAO) FindNodeClusterSystemServices(tx *dbs.Tx, clusterId
return servicesMap, nil
}
// 生成唯一ID
// GenUniqueId 生成唯一ID
func (this *NodeClusterDAO) GenUniqueId(tx *dbs.Tx) (string, error) {
for {
uniqueId := rands.HexString(32)
@@ -821,12 +821,28 @@ func (this *NodeClusterDAO) GenUniqueId(tx *dbs.Tx) (string, error) {
}
}
// 通知更新
// FindLatestNodeClusters 查询最近访问的集群
func (this *NodeClusterDAO) FindLatestNodeClusters(tx *dbs.Tx, size int64) (result []*NodeCluster, err error) {
itemTable := SharedLatestItemDAO.Table
itemType := LatestItemTypeCluster
_, 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
}
// NotifyUpdate 通知更新
func (this *NodeClusterDAO) NotifyUpdate(tx *dbs.Tx, clusterId int64) error {
return SharedNodeTaskDAO.CreateClusterTask(tx, clusterId, NodeTaskTypeConfigChanged)
}
// 通知DNS更新
// NotifyDNSUpdate 通知DNS更新
// TODO 更新新的DNS解析记录的同时需要删除老的DNS解析记录
func (this *NodeClusterDAO) NotifyDNSUpdate(tx *dbs.Tx, clusterId int64) error {
err := dns.SharedDNSTaskDAO.CreateClusterTask(tx, clusterId, dns.DNSTaskTypeClusterChange)

View File

@@ -9,6 +9,7 @@ import (
"github.com/TeaOSLab/EdgeCommon/pkg/configutils"
"github.com/TeaOSLab/EdgeCommon/pkg/nodeconfigs"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/shared"
"github.com/TeaOSLab/EdgeCommon/pkg/systemconfigs"
_ "github.com/go-sql-driver/mysql"
"github.com/iwind/TeaGo/Tea"
@@ -161,7 +162,7 @@ func (this *NodeDAO) CreateNode(tx *dbs.Tx, adminId int64, name string, clusterI
}
// UpdateNode 修改节点
func (this *NodeDAO) UpdateNode(tx *dbs.Tx, nodeId int64, name string, clusterId int64, groupId int64, regionId int64, maxCPU int32, isOn bool) error {
func (this *NodeDAO) UpdateNode(tx *dbs.Tx, nodeId int64, name string, clusterId int64, groupId int64, regionId int64, maxCPU int32, isOn bool, maxCacheDiskCapacityJSON []byte, maxCacheMemoryCapacityJSON []byte) error {
if nodeId <= 0 {
return errors.New("invalid nodeId")
}
@@ -174,6 +175,12 @@ func (this *NodeDAO) UpdateNode(tx *dbs.Tx, nodeId int64, name string, clusterId
op.LatestVersion = dbs.SQL("latestVersion+1")
op.MaxCPU = maxCPU
op.IsOn = isOn
if len(maxCacheDiskCapacityJSON) > 0 {
op.MaxCacheDiskCapacity = maxCacheDiskCapacityJSON
}
if len(maxCacheMemoryCapacityJSON) > 0 {
op.MaxCacheMemoryCapacity = maxCacheMemoryCapacityJSON
}
err := this.Save(tx, op)
if err != nil {
return err
@@ -558,6 +565,29 @@ func (this *NodeDAO) ComposeNodeConfig(tx *dbs.Tx, nodeId int64) (*nodeconfigs.N
}
}
// 缓存最大容量设置
if len(node.MaxCacheDiskCapacity) > 0 {
capacity := &shared.SizeCapacity{}
err = json.Unmarshal([]byte(node.MaxCacheDiskCapacity), capacity)
if err != nil {
return nil, err
}
if capacity.Count > 0 {
config.MaxCacheDiskCapacity = capacity
}
}
if len(node.MaxCacheMemoryCapacity) > 0 {
capacity := &shared.SizeCapacity{}
err = json.Unmarshal([]byte(node.MaxCacheMemoryCapacity), capacity)
if err != nil {
return nil, err
}
if capacity.Count > 0 {
config.MaxCacheMemoryCapacity = capacity
}
}
// TOA
toaConfig, err := SharedNodeClusterDAO.FindClusterTOAConfig(tx, clusterId)
if err != nil {
@@ -692,7 +722,7 @@ func (this *NodeDAO) FindAllNotInstalledNodesWithClusterId(tx *dbs.Tx, clusterId
return
}
// CountAllLowerVersionNodesWithClusterId 计算所有低于某个版本的节点数量
// CountAllLowerVersionNodesWithClusterId 计算单个集群中所有低于某个版本的节点数量
func (this *NodeDAO) CountAllLowerVersionNodesWithClusterId(tx *dbs.Tx, clusterId int64, os string, arch string, version string) (int64, error) {
return this.Query(tx).
State(NodeStateEnabled).
@@ -707,7 +737,7 @@ func (this *NodeDAO) CountAllLowerVersionNodesWithClusterId(tx *dbs.Tx, clusterI
Count()
}
// FindAllLowerVersionNodesWithClusterId 查找所有低于某个版本的节点
// FindAllLowerVersionNodesWithClusterId 查找单个集群中所有低于某个版本的节点
func (this *NodeDAO) FindAllLowerVersionNodesWithClusterId(tx *dbs.Tx, clusterId int64, os string, arch string, version string) (result []*Node, err error) {
_, err = this.Query(tx).
State(NodeStateEnabled).
@@ -725,6 +755,17 @@ func (this *NodeDAO) FindAllLowerVersionNodesWithClusterId(tx *dbs.Tx, clusterId
return
}
// CountAllLowerVersionNodes 计算所有集群中低于某个版本的节点数量
func (this *NodeDAO) CountAllLowerVersionNodes(tx *dbs.Tx, version string) (int64, error) {
return this.Query(tx).
State(NodeStateEnabled).
Where("clusterId IN (SELECT id FROM "+SharedNodeClusterDAO.Table+" WHERE state=1)").
Where("status IS NOT NULL").
Where("(JSON_EXTRACT(status, '$.buildVersionCode') IS NULL OR JSON_EXTRACT(status, '$.buildVersionCode')<:version)").
Param("version", utils.VersionToLong(version)).
Count()
}
// CountAllEnabledNodesWithGroupId 查找某个节点分组下的所有节点数量
func (this *NodeDAO) CountAllEnabledNodesWithGroupId(tx *dbs.Tx, groupId int64) (int64, error) {
return this.Query(tx).

View File

@@ -1,62 +1,66 @@
package models
// 节点
// Node 节点
type Node struct {
Id uint32 `field:"id"` // ID
AdminId uint32 `field:"adminId"` // 管理员ID
UserId uint32 `field:"userId"` // 用户ID
IsOn uint8 `field:"isOn"` // 是否启用
IsUp uint8 `field:"isUp"` // 是否在线
CountUp uint32 `field:"countUp"` // 连续在线次数
CountDown uint32 `field:"countDown"` // 连续下线次数
IsActive uint8 `field:"isActive"` // 是否活跃
UniqueId string `field:"uniqueId"` // 节点ID
Secret string `field:"secret"` // 密钥
Name string `field:"name"` // 节点名
Code string `field:"code"` // 代号
ClusterId uint32 `field:"clusterId"` // 集群ID
RegionId uint32 `field:"regionId"` // 区域ID
GroupId uint32 `field:"groupId"` // 分组ID
CreatedAt uint64 `field:"createdAt"` // 创建时间
Status string `field:"status"` // 最新的状态
Version uint32 `field:"version"` // 当前版本号
LatestVersion uint32 `field:"latestVersion"` // 最后版本号
InstallDir string `field:"installDir"` // 安装目录
IsInstalled uint8 `field:"isInstalled"` // 是否已安装
InstallStatus string `field:"installStatus"` // 安装状态
State uint8 `field:"state"` // 状态
ConnectedAPINodes string `field:"connectedAPINodes"` // 当前连接的API节点
MaxCPU uint32 `field:"maxCPU"` // 可以使用的最多CPU
DnsRoutes string `field:"dnsRoutes"` // DNS线路设置
Id uint32 `field:"id"` // ID
AdminId uint32 `field:"adminId"` // 管理员ID
UserId uint32 `field:"userId"` // 用户ID
IsOn uint8 `field:"isOn"` // 是否启用
IsUp uint8 `field:"isUp"` // 是否在线
CountUp uint32 `field:"countUp"` // 连续在线次数
CountDown uint32 `field:"countDown"` // 连续下线次数
IsActive uint8 `field:"isActive"` // 是否活跃
UniqueId string `field:"uniqueId"` // 节点ID
Secret string `field:"secret"` // 密钥
Name string `field:"name"` // 节点名
Code string `field:"code"` // 代号
ClusterId uint32 `field:"clusterId"` // 集群ID
RegionId uint32 `field:"regionId"` // 区域ID
GroupId uint32 `field:"groupId"` // 分组ID
CreatedAt uint64 `field:"createdAt"` // 创建时间
Status string `field:"status"` // 最新的状态
Version uint32 `field:"version"` // 当前版本号
LatestVersion uint32 `field:"latestVersion"` // 最后版本号
InstallDir string `field:"installDir"` // 安装目录
IsInstalled uint8 `field:"isInstalled"` // 是否已安装
InstallStatus string `field:"installStatus"` // 安装状态
State uint8 `field:"state"` // 状态
ConnectedAPINodes string `field:"connectedAPINodes"` // 当前连接的API节点
MaxCPU uint32 `field:"maxCPU"` // 可以使用的最多CPU
DnsRoutes string `field:"dnsRoutes"` // DNS线路设置
MaxCacheDiskCapacity string `field:"maxCacheDiskCapacity"` // 硬盘缓存容量
MaxCacheMemoryCapacity string `field:"maxCacheMemoryCapacity"` // 内存缓存容量
}
type NodeOperator struct {
Id interface{} // ID
AdminId interface{} // 管理员ID
UserId interface{} // 用户ID
IsOn interface{} // 是否启用
IsUp interface{} // 是否在线
CountUp interface{} // 连续在线次数
CountDown interface{} // 连续下线次数
IsActive interface{} // 是否活跃
UniqueId interface{} // 节点ID
Secret interface{} // 密钥
Name interface{} // 节点名
Code interface{} // 代号
ClusterId interface{} // 集群ID
RegionId interface{} // 区域ID
GroupId interface{} // 分组ID
CreatedAt interface{} // 创建时间
Status interface{} // 最新的状态
Version interface{} // 当前版本号
LatestVersion interface{} // 最后版本号
InstallDir interface{} // 安装目录
IsInstalled interface{} // 是否已安装
InstallStatus interface{} // 安装状态
State interface{} // 状态
ConnectedAPINodes interface{} // 当前连接的API节点
MaxCPU interface{} // 可以使用的最多CPU
DnsRoutes interface{} // DNS线路设置
Id interface{} // ID
AdminId interface{} // 管理员ID
UserId interface{} // 用户ID
IsOn interface{} // 是否启用
IsUp interface{} // 是否在线
CountUp interface{} // 连续在线次数
CountDown interface{} // 连续下线次数
IsActive interface{} // 是否活跃
UniqueId interface{} // 节点ID
Secret interface{} // 密钥
Name interface{} // 节点名
Code interface{} // 代号
ClusterId interface{} // 集群ID
RegionId interface{} // 区域ID
GroupId interface{} // 分组ID
CreatedAt interface{} // 创建时间
Status interface{} // 最新的状态
Version interface{} // 当前版本号
LatestVersion interface{} // 最后版本号
InstallDir interface{} // 安装目录
IsInstalled interface{} // 是否已安装
InstallStatus interface{} // 安装状态
State interface{} // 状态
ConnectedAPINodes interface{} // 当前连接的API节点
MaxCPU interface{} // 可以使用的最多CPU
DnsRoutes interface{} // DNS线路设置
MaxCacheDiskCapacity interface{} // 硬盘缓存容量
MaxCacheMemoryCapacity interface{} // 内存缓存容量
}
func NewNodeOperator() *NodeOperator {

View File

@@ -0,0 +1,271 @@
package models
import (
"fmt"
"github.com/TeaOSLab/EdgeAPI/internal/errors"
"github.com/TeaOSLab/EdgeCommon/pkg/nodeconfigs"
_ "github.com/go-sql-driver/mysql"
"github.com/iwind/TeaGo/Tea"
"github.com/iwind/TeaGo/dbs"
"github.com/iwind/TeaGo/maps"
"github.com/iwind/TeaGo/types"
timeutil "github.com/iwind/TeaGo/utils/time"
"strings"
"time"
)
const (
NodeThresholdStateEnabled = 1 // 已启用
NodeThresholdStateDisabled = 0 // 已禁用
)
type NodeThresholdDAO dbs.DAO
func NewNodeThresholdDAO() *NodeThresholdDAO {
return dbs.NewDAO(&NodeThresholdDAO{
DAOObject: dbs.DAOObject{
DB: Tea.Env,
Table: "edgeNodeThresholds",
Model: new(NodeThreshold),
PkName: "id",
},
}).(*NodeThresholdDAO)
}
var SharedNodeThresholdDAO *NodeThresholdDAO
func init() {
dbs.OnReady(func() {
SharedNodeThresholdDAO = NewNodeThresholdDAO()
})
}
// EnableNodeThreshold 启用条目
func (this *NodeThresholdDAO) EnableNodeThreshold(tx *dbs.Tx, id int64) error {
_, err := this.Query(tx).
Pk(id).
Set("state", NodeThresholdStateEnabled).
Update()
return err
}
// DisableNodeThreshold 禁用条目
func (this *NodeThresholdDAO) DisableNodeThreshold(tx *dbs.Tx, id int64) error {
_, err := this.Query(tx).
Pk(id).
Set("state", NodeThresholdStateDisabled).
Update()
return err
}
// FindEnabledNodeThreshold 查找启用中的条目
func (this *NodeThresholdDAO) FindEnabledNodeThreshold(tx *dbs.Tx, id int64) (*NodeThreshold, error) {
result, err := this.Query(tx).
Pk(id).
Attr("state", NodeThresholdStateEnabled).
Find()
if result == nil {
return nil, err
}
return result.(*NodeThreshold), err
}
// CreateThreshold 创建阈值
func (this *NodeThresholdDAO) CreateThreshold(tx *dbs.Tx, role string, clusterId int64, nodeId int64, item nodeconfigs.NodeValueItem, param string, operator nodeconfigs.NodeValueOperator, valueJSON []byte, message string, sumMethod nodeconfigs.NodeValueSumMethod, duration int32, durationUnit nodeconfigs.NodeValueDurationUnit, notifyDuration int32) (int64, error) {
op := NewNodeThresholdOperator()
op.Role = role
op.ClusterId = clusterId
op.NodeId = nodeId
op.Item = item
op.Param = param
op.Operator = operator
op.Value = valueJSON
op.Message = message
op.SumMethod = sumMethod
op.Duration = duration
op.DurationUnit = durationUnit
op.NotifyDuration = notifyDuration
op.IsOn = true
op.State = NodeThresholdStateEnabled
return this.SaveInt64(tx, op)
}
// UpdateThreshold 修改阈值
func (this *NodeThresholdDAO) UpdateThreshold(tx *dbs.Tx, thresholdId int64, item nodeconfigs.NodeValueItem, param string, operator nodeconfigs.NodeValueOperator, valueJSON []byte, message string, sumMethod nodeconfigs.NodeValueSumMethod, duration int32, durationUnit nodeconfigs.NodeValueDurationUnit, notifyDuration int32, isOn bool) error {
if thresholdId <= 0 {
return errors.New("invalid thresholdId")
}
op := NewNodeThresholdOperator()
op.Id = thresholdId
op.Item = item
op.Param = param
op.Operator = operator
op.Value = valueJSON
op.Message = message
op.SumMethod = sumMethod
op.Duration = duration
op.DurationUnit = durationUnit
op.NotifyDuration = notifyDuration
op.IsOn = isOn
return this.Save(tx, op)
}
// FindAllEnabledThresholds 列出所有阈值
func (this *NodeThresholdDAO) FindAllEnabledThresholds(tx *dbs.Tx, role string, clusterId int64, nodeId int64) (result []*NodeThreshold, err error) {
if clusterId <= 0 && nodeId <= 0 {
return
}
query := this.Query(tx)
if clusterId > 0 {
query.Attr("clusterId", clusterId)
}
if nodeId > 0 {
query.Attr("nodeId", nodeId)
}
query.State(NodeThresholdStateEnabled)
query.Slice(&result)
_, err = query.
Attr("role", role).
Asc("IF(nodeId>0, 1, 0)").
Desc("order").
AscPk().
FindAll()
return
}
// FindAllEnabledAndOnClusterThresholds 查询集群专属的阈值设置
func (this *NodeThresholdDAO) FindAllEnabledAndOnClusterThresholds(tx *dbs.Tx, role string, clusterId int64, item string) (result []*NodeThreshold, err error) {
if clusterId <= 0 {
return
}
_, err = this.Query(tx).
Attr("role", role).
Attr("clusterId", clusterId).
Attr("nodeId", 0).
Attr("item", item).
Attr("isOn", true).
State(NodeThresholdStateEnabled).
Desc("order").
AscPk().
Slice(&result).
FindAll()
return
}
// FindAllEnabledAndOnNodeThresholds 查询节点专属的阈值设置
func (this *NodeThresholdDAO) FindAllEnabledAndOnNodeThresholds(tx *dbs.Tx, role string, nodeId int64, item string) (result []*NodeThreshold, err error) {
if nodeId <= 0 {
return
}
_, err = this.Query(tx).
Attr("role", role).
Attr("nodeId", nodeId).
Attr("item", item).
Attr("isOn", true).
State(NodeThresholdStateEnabled).
Desc("order").
AscPk().
Slice(&result).
FindAll()
return
}
// CountAllEnabledThresholds 计算阈值的数量
func (this *NodeThresholdDAO) CountAllEnabledThresholds(tx *dbs.Tx, clusterId int64, nodeId int64) (int64, error) {
if clusterId <= 0 && nodeId <= 0 {
return 0, nil
}
query := this.Query(tx)
if clusterId > 0 {
query.Attr("clusterId", clusterId)
}
if nodeId > 0 {
query.Attr("nodeId", nodeId)
}
query.State(NodeThresholdStateEnabled)
return query.Count()
}
// FireNodeThreshold 触发相关阈值设置
func (this *NodeThresholdDAO) FireNodeThreshold(tx *dbs.Tx, role string, nodeId int64, item string) error {
clusterId, err := SharedNodeDAO.FindNodeClusterId(tx, nodeId)
if err != nil {
return err
}
if clusterId == 0 {
return nil
}
// 集群相关阈值
var thresholds []*NodeThreshold
{
clusterThresholds, err := this.FindAllEnabledAndOnClusterThresholds(tx, role, clusterId, item)
if err != nil {
return err
}
thresholds = append(thresholds, clusterThresholds...)
}
// 节点相关阈值
{
nodeThresholds, err := this.FindAllEnabledAndOnNodeThresholds(tx, role, nodeId, item)
if err != nil {
return err
}
thresholds = append(thresholds, nodeThresholds...)
}
if len(thresholds) > 0 {
for _, threshold := range thresholds {
if len(threshold.Param) == 0 || threshold.Duration <= 0 {
continue
}
paramValue, err := SharedNodeValueDAO.SumValues(tx, role, nodeId, item, threshold.Param, threshold.SumMethod, types.Int32(threshold.Duration), threshold.DurationUnit)
if err != nil {
return err
}
originValue := nodeconfigs.UnmarshalNodeValue([]byte(threshold.Value))
thresholdValue := types.Float64(originValue)
isMatched := nodeconfigs.CompareNodeValue(threshold.Operator, paramValue, thresholdValue)
if isMatched {
// TODO 执行其他动作
// 是否已经通知过
if threshold.NotifyDuration > 0 && threshold.NotifiedAt > 0 && time.Now().Unix()-int64(threshold.NotifiedAt) < int64(threshold.NotifyDuration*60) {
continue
}
// 创建消息
nodeName, err := SharedNodeDAO.FindNodeName(tx, nodeId)
if err != nil {
return err
}
itemName := nodeconfigs.FindNodeValueItemName(threshold.Item)
paramName := nodeconfigs.FindNodeValueItemParamName(threshold.Item, threshold.Param)
operatorName := nodeconfigs.FindNodeValueOperatorName(threshold.Operator)
subject := "节点 \"" + nodeName + "\" " + itemName + " 达到阈值"
body := "节点 \"" + nodeName + "\" " + itemName + " 达到阈值\n阈值设置" + paramName + " " + operatorName + " " + originValue + "\n当前值" + fmt.Sprintf("%.2f", paramValue) + "\n触发时间" + timeutil.Format("Y-m-d H:i:s")
if len(threshold.Message) > 0 {
body = threshold.Message
body = strings.Replace(body, "${item.name}", itemName, -1)
body = strings.Replace(body, "${value}", fmt.Sprintf("%.2f", paramValue), -1)
}
err = SharedMessageDAO.CreateNodeMessage(tx, clusterId, nodeId, MessageTypeThresholdSatisfied, MessageLevelWarning, subject, body, maps.Map{}.AsJSON())
if err != nil {
return err
}
// 设置通知时间
_, err = this.Query(tx).
Pk(threshold.Id).
Set("notifiedAt", time.Now().Unix()).
Update()
if err != nil {
return err
}
}
}
}
return nil
}

View File

@@ -0,0 +1,6 @@
package models
import (
_ "github.com/go-sql-driver/mysql"
_ "github.com/iwind/TeaGo/bootstrap"
)

View File

@@ -0,0 +1,46 @@
package models
// NodeThreshold 集群阈值设置
type NodeThreshold struct {
Id uint64 `field:"id"` // ID
Role string `field:"role"` // 节点角色
ClusterId uint32 `field:"clusterId"` // 集群ID
NodeId uint32 `field:"nodeId"` // 节点ID
IsOn uint8 `field:"isOn"` // 是否启用
Item string `field:"item"` // 监控项
Param string `field:"param"` // 参数
Operator string `field:"operator"` // 操作符
Value string `field:"value"` // 对比值
Message string `field:"message"` // 消息内容
NotifyDuration uint32 `field:"notifyDuration"` // 通知间隔
NotifiedAt uint32 `field:"notifiedAt"` // 上次通知时间
Duration uint32 `field:"duration"` // 时间段
DurationUnit string `field:"durationUnit"` // 时间段单位
SumMethod string `field:"sumMethod"` // 聚合方法
Order uint32 `field:"order"` // 排序
State uint8 `field:"state"` // 状态
}
type NodeThresholdOperator struct {
Id interface{} // ID
Role interface{} // 节点角色
ClusterId interface{} // 集群ID
NodeId interface{} // 节点ID
IsOn interface{} // 是否启用
Item interface{} // 监控项
Param interface{} // 参数
Operator interface{} // 操作符
Value interface{} // 对比值
Message interface{} // 消息内容
NotifyDuration interface{} // 通知间隔
NotifiedAt interface{} // 上次通知时间
Duration interface{} // 时间段
DurationUnit interface{} // 时间段单位
SumMethod interface{} // 聚合方法
Order interface{} // 排序
State interface{} // 状态
}
func NewNodeThresholdOperator() *NodeThresholdOperator {
return &NodeThresholdOperator{}
}

View File

@@ -0,0 +1 @@
package models

View File

@@ -0,0 +1,120 @@
package models
import (
"github.com/TeaOSLab/EdgeAPI/internal/errors"
"github.com/TeaOSLab/EdgeCommon/pkg/nodeconfigs"
_ "github.com/go-sql-driver/mysql"
"github.com/iwind/TeaGo/Tea"
"github.com/iwind/TeaGo/dbs"
"github.com/iwind/TeaGo/maps"
timeutil "github.com/iwind/TeaGo/utils/time"
"time"
)
type NodeValueDAO dbs.DAO
func NewNodeValueDAO() *NodeValueDAO {
return dbs.NewDAO(&NodeValueDAO{
DAOObject: dbs.DAOObject{
DB: Tea.Env,
Table: "edgeNodeValues",
Model: new(NodeValue),
PkName: "id",
},
}).(*NodeValueDAO)
}
var SharedNodeValueDAO *NodeValueDAO
func init() {
dbs.OnReady(func() {
SharedNodeValueDAO = NewNodeValueDAO()
})
}
// CreateValue 创建值
func (this *NodeValueDAO) CreateValue(tx *dbs.Tx, role NodeRole, nodeId int64, item string, valueJSON []byte, createdAt int64) error {
day := timeutil.FormatTime("Ymd", createdAt)
hour := timeutil.FormatTime("YmdH", createdAt)
minute := timeutil.FormatTime("YmdHi", createdAt)
return this.Query(tx).
InsertOrUpdateQuickly(maps.Map{
"role": role,
"nodeId": nodeId,
"item": item,
"value": valueJSON,
"createdAt": createdAt,
"day": day,
"hour": hour,
"minute": minute,
}, maps.Map{
"value": valueJSON,
})
}
// DeleteExpiredValues 清除数据
func (this *NodeValueDAO) DeleteExpiredValues(tx *dbs.Tx) error {
// 删除N天之前的所有数据
expiredDays := 100
day := timeutil.Format("Ymd", time.Now().AddDate(0, 0, -expiredDays))
_, err := this.Query(tx).
Where("day<:day").
Param("day", day).
Delete()
if err != nil {
return err
}
return nil
}
// ListValues 列出最近的的数据
func (this *NodeValueDAO) ListValues(tx *dbs.Tx, role string, nodeId int64, item string, timeRange nodeconfigs.NodeValueRange) (result []*NodeValue, err error) {
query := this.Query(tx).
Attr("role", role).
Attr("nodeId", nodeId).
Attr("item", item)
switch timeRange {
// TODO 支持更多的时间范围
case nodeconfigs.NodeValueRangeMinute:
fromMinute := timeutil.FormatTime("YmdHi", time.Now().Unix()-3600) // 一个小时之前的
query.Gte("minute", fromMinute)
default:
err = errors.New("invalid 'range' value: '" + timeRange + "'")
return
}
_, err = query.Slice(&result).
FindAll()
return
}
// SumValues 计算某项参数值
func (this *NodeValueDAO) SumValues(tx *dbs.Tx, role string, nodeId int64, item string, param string, method nodeconfigs.NodeValueSumMethod, duration int32, durationUnit nodeconfigs.NodeValueDurationUnit) (float64, error) {
if duration <= 0 {
return 0, nil
}
query := this.Query(tx).
Attr("role", role).
Attr("nodeId", nodeId).
Attr("item", item)
switch method {
case nodeconfigs.NodeValueSumMethodAvg:
query.Result("AVG(JSON_EXTRACT(value, '$." + param + "'))")
case nodeconfigs.NodeValueSumMethodSum:
query.Result("SUM(JSON_EXTRACT(value, '$." + param + "'))")
default:
query.Result("AVG(JSON_EXTRACT(value, '$." + param + "'))")
}
switch durationUnit {
case nodeconfigs.NodeValueDurationUnitMinute:
fromMinute := timeutil.FormatTime("YmdHi", time.Now().Unix()-int64(duration * 60))
query.Gte("minute", fromMinute)
default:
fromMinute := timeutil.FormatTime("YmdHi", time.Now().Unix()-int64(duration * 60))
query.Gte("minute", fromMinute)
}
return query.FindFloat64Col(0)
}

View File

@@ -0,0 +1,21 @@
package models
import (
_ "github.com/go-sql-driver/mysql"
_ "github.com/iwind/TeaGo/bootstrap"
"github.com/iwind/TeaGo/maps"
"testing"
"time"
)
func TestNodeValueDAO_CreateValue(t *testing.T) {
dao := NewNodeValueDAO()
m := maps.Map{
"hello": "world12344",
}
err := dao.CreateValue(nil, NodeRoleNode, 1, "test", m.AsJSON(), time.Now().Unix())
if err != nil {
t.Fatal(err)
}
t.Log("ok")
}

View File

@@ -0,0 +1,30 @@
package models
// NodeValue 节点监控数据
type NodeValue struct {
Id uint64 `field:"id"` // ID
NodeId uint32 `field:"nodeId"` // 节点ID
Role string `field:"role"` // 节点角色
Item string `field:"item"` // 监控项
Value string `field:"value"` // 数据
CreatedAt uint64 `field:"createdAt"` // 创建时间
Day string `field:"day"` // 日期
Hour string `field:"hour"` // 小时
Minute string `field:"minute"` // 分钟
}
type NodeValueOperator struct {
Id interface{} // ID
NodeId interface{} // 节点ID
Role interface{} // 节点角色
Item interface{} // 监控项
Value interface{} // 数据
CreatedAt interface{} // 创建时间
Day interface{} // 日期
Hour interface{} // 小时
Minute interface{} // 分钟
}
func NewNodeValueOperator() *NodeValueOperator {
return &NodeValueOperator{}
}

View File

@@ -0,0 +1 @@
package models

View File

@@ -49,14 +49,14 @@ func init() {
})
}
// 初始化
// Init 初始化
func (this *ServerDAO) Init() {
this.DAOObject.Init()
// 这里不处理增删改事件是为了避免Server修改本身的时候也要触发别的Server变更
}
// 启用条目
// EnableServer 启用条目
func (this *ServerDAO) EnableServer(tx *dbs.Tx, id uint32) (rowsAffected int64, err error) {
return this.Query(tx).
Pk(id).
@@ -64,7 +64,7 @@ func (this *ServerDAO) EnableServer(tx *dbs.Tx, id uint32) (rowsAffected int64,
Update()
}
// 禁用条目
// DisableServer 禁用条目
func (this *ServerDAO) DisableServer(tx *dbs.Tx, serverId int64) (err error) {
_, err = this.Query(tx).
Pk(serverId).
@@ -85,7 +85,7 @@ func (this *ServerDAO) DisableServer(tx *dbs.Tx, serverId int64) (err error) {
return nil
}
// 查找启用中的服务
// FindEnabledServer 查找启用中的服务
func (this *ServerDAO) FindEnabledServer(tx *dbs.Tx, serverId int64) (*Server, error) {
result, err := this.Query(tx).
Pk(serverId).
@@ -97,7 +97,7 @@ func (this *ServerDAO) FindEnabledServer(tx *dbs.Tx, serverId int64) (*Server, e
return result.(*Server), err
}
// 查找服务名称
// FindEnabledServerName 查找服务名称
func (this *ServerDAO) FindEnabledServerName(tx *dbs.Tx, serverId int64) (string, error) {
return this.Query(tx).
Pk(serverId).
@@ -106,7 +106,7 @@ func (this *ServerDAO) FindEnabledServerName(tx *dbs.Tx, serverId int64) (string
FindStringCol("")
}
// 查找服务基本信息
// FindEnabledServerBasic 查找服务基本信息
func (this *ServerDAO) FindEnabledServerBasic(tx *dbs.Tx, serverId int64) (*Server, error) {
result, err := this.Query(tx).
Pk(serverId).
@@ -119,7 +119,7 @@ func (this *ServerDAO) FindEnabledServerBasic(tx *dbs.Tx, serverId int64) (*Serv
return result.(*Server), err
}
// 查找服务类型
// FindEnabledServerType 查找服务类型
func (this *ServerDAO) FindEnabledServerType(tx *dbs.Tx, serverId int64) (string, error) {
return this.Query(tx).
Pk(serverId).
@@ -127,7 +127,7 @@ func (this *ServerDAO) FindEnabledServerType(tx *dbs.Tx, serverId int64) (string
FindStringCol("")
}
// 创建服务
// CreateServer 创建服务
func (this *ServerDAO) CreateServer(tx *dbs.Tx,
adminId int64,
userId int64,
@@ -236,7 +236,7 @@ func (this *ServerDAO) CreateServer(tx *dbs.Tx,
return serverId, nil
}
// 修改服务基本信息
// UpdateServerBasic 修改服务基本信息
func (this *ServerDAO) UpdateServerBasic(tx *dbs.Tx, serverId int64, name string, description string, clusterId int64, isOn bool, groupIds []int64) error {
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
@@ -273,7 +273,7 @@ func (this *ServerDAO) UpdateServerBasic(tx *dbs.Tx, serverId int64, name string
return this.NotifyDNSUpdate(tx, serverId)
}
// 设置用户相关的基本信息
// 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")
@@ -290,7 +290,7 @@ func (this *ServerDAO) UpdateUserServerBasic(tx *dbs.Tx, serverId int64, name st
return this.NotifyUpdate(tx, serverId)
}
// 修复服务是否启用
// UpdateServerIsOn 修复服务是否启用
func (this *ServerDAO) UpdateServerIsOn(tx *dbs.Tx, serverId int64, isOn bool) error {
_, err := this.Query(tx).
Pk(serverId).
@@ -308,7 +308,7 @@ func (this *ServerDAO) UpdateServerIsOn(tx *dbs.Tx, serverId int64, isOn bool) e
return nil
}
// 修改服务配置
// UpdateServerConfig 修改服务配置
func (this *ServerDAO) UpdateServerConfig(tx *dbs.Tx, serverId int64, configJSON []byte, updateMd5 bool) (isChanged bool, err error) {
if serverId <= 0 {
return false, errors.New("serverId should not be smaller than 0")
@@ -351,7 +351,7 @@ func (this *ServerDAO) UpdateServerConfig(tx *dbs.Tx, serverId int64, configJSON
return true, err
}
// 修改HTTP配置
// UpdateServerHTTP 修改HTTP配置
func (this *ServerDAO) UpdateServerHTTP(tx *dbs.Tx, serverId int64, config []byte) error {
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
@@ -370,7 +370,7 @@ func (this *ServerDAO) UpdateServerHTTP(tx *dbs.Tx, serverId int64, config []byt
return this.NotifyUpdate(tx, serverId)
}
// 修改HTTPS配置
// UpdateServerHTTPS 修改HTTPS配置
func (this *ServerDAO) UpdateServerHTTPS(tx *dbs.Tx, serverId int64, httpsJSON []byte) error {
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
@@ -389,7 +389,7 @@ func (this *ServerDAO) UpdateServerHTTPS(tx *dbs.Tx, serverId int64, httpsJSON [
return this.NotifyUpdate(tx, serverId)
}
// 修改TCP配置
// UpdateServerTCP 修改TCP配置
func (this *ServerDAO) UpdateServerTCP(tx *dbs.Tx, serverId int64, config []byte) error {
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
@@ -408,7 +408,7 @@ func (this *ServerDAO) UpdateServerTCP(tx *dbs.Tx, serverId int64, config []byte
return this.NotifyUpdate(tx, serverId)
}
// 修改TLS配置
// UpdateServerTLS 修改TLS配置
func (this *ServerDAO) UpdateServerTLS(tx *dbs.Tx, serverId int64, config []byte) error {
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
@@ -427,7 +427,7 @@ func (this *ServerDAO) UpdateServerTLS(tx *dbs.Tx, serverId int64, config []byte
return this.NotifyUpdate(tx, serverId)
}
// 修改Unix配置
// UpdateServerUnix 修改Unix配置
func (this *ServerDAO) UpdateServerUnix(tx *dbs.Tx, serverId int64, config []byte) error {
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
@@ -446,7 +446,7 @@ func (this *ServerDAO) UpdateServerUnix(tx *dbs.Tx, serverId int64, config []byt
return this.NotifyUpdate(tx, serverId)
}
// 修改UDP配置
// UpdateServerUDP 修改UDP配置
func (this *ServerDAO) UpdateServerUDP(tx *dbs.Tx, serverId int64, config []byte) error {
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
@@ -465,7 +465,7 @@ func (this *ServerDAO) UpdateServerUDP(tx *dbs.Tx, serverId int64, config []byte
return this.NotifyUpdate(tx, serverId)
}
// 修改Web配置
// UpdateServerWeb 修改Web配置
func (this *ServerDAO) UpdateServerWeb(tx *dbs.Tx, serverId int64, webId int64) error {
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
@@ -480,7 +480,7 @@ func (this *ServerDAO) UpdateServerWeb(tx *dbs.Tx, serverId int64, webId int64)
return this.NotifyUpdate(tx, serverId)
}
// 初始化Web配置
// InitServerWeb 初始化Web配置
func (this *ServerDAO) InitServerWeb(tx *dbs.Tx, serverId int64) (int64, error) {
if serverId <= 0 {
return 0, errors.New("serverId should not be smaller than 0")
@@ -512,7 +512,7 @@ func (this *ServerDAO) InitServerWeb(tx *dbs.Tx, serverId int64) (int64, error)
return webId, nil
}
// 查找ServerNames配置
// FindServerServerNames 查找ServerNames配置
func (this *ServerDAO) FindServerServerNames(tx *dbs.Tx, serverId int64) (serverNamesJSON []byte, isAuditing bool, auditingServerNamesJSON []byte, auditingResultJSON []byte, err error) {
if serverId <= 0 {
return
@@ -531,7 +531,7 @@ func (this *ServerDAO) FindServerServerNames(tx *dbs.Tx, serverId int64) (server
return []byte(server.ServerNames), server.IsAuditing == 1, []byte(server.AuditingServerNames), []byte(server.AuditingResult), nil
}
// 修改ServerNames配置
// UpdateServerNames 修改ServerNames配置
func (this *ServerDAO) UpdateServerNames(tx *dbs.Tx, serverId int64, serverNames []byte) error {
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
@@ -551,7 +551,7 @@ func (this *ServerDAO) UpdateServerNames(tx *dbs.Tx, serverId int64, serverNames
return this.NotifyUpdate(tx, serverId)
}
// 修改域名审核
// 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")
@@ -573,7 +573,7 @@ func (this *ServerDAO) UpdateAuditingServerNames(tx *dbs.Tx, serverId int64, isA
return this.NotifyUpdate(tx, serverId)
}
// 修改域名审核结果
// UpdateServerAuditing 修改域名审核结果
func (this *ServerDAO) UpdateServerAuditing(tx *dbs.Tx, serverId int64, result *pb.ServerNameAuditingResult) error {
if serverId <= 0 {
return errors.New("invalid serverId")
@@ -608,7 +608,7 @@ func (this *ServerDAO) UpdateServerAuditing(tx *dbs.Tx, serverId int64, result *
return this.NotifyDNSUpdate(tx, serverId)
}
// 修改反向代理配置
// UpdateServerReverseProxy 修改反向代理配置
func (this *ServerDAO) UpdateServerReverseProxy(tx *dbs.Tx, serverId int64, config []byte) error {
if serverId <= 0 {
return errors.New("serverId should not be smaller than 0")
@@ -624,14 +624,14 @@ func (this *ServerDAO) UpdateServerReverseProxy(tx *dbs.Tx, serverId int64, conf
return this.NotifyUpdate(tx, serverId)
}
// 计算所有可用服务数量
// CountAllEnabledServers 计算所有可用服务数量
func (this *ServerDAO) CountAllEnabledServers(tx *dbs.Tx) (int64, error) {
return this.Query(tx).
State(ServerStateEnabled).
Count()
}
// 计算所有可用服务数量
// CountAllEnabledServersMatch 计算所有可用服务数量
func (this *ServerDAO) CountAllEnabledServersMatch(tx *dbs.Tx, groupId int64, keyword string, userId int64, clusterId int64, auditingFlag configutils.BoolState, protocolFamily string) (int64, error) {
query := this.Query(tx).
State(ServerStateEnabled)
@@ -660,7 +660,7 @@ func (this *ServerDAO) CountAllEnabledServersMatch(tx *dbs.Tx, groupId int64, ke
return query.Count()
}
// 列出单页的服务
// ListEnabledServersMatch 列出单页的服务
func (this *ServerDAO) ListEnabledServersMatch(tx *dbs.Tx, offset int64, size int64, groupId int64, keyword string, userId int64, clusterId int64, auditingFlag int32, protocolFamily string) (result []*Server, err error) {
query := this.Query(tx).
State(ServerStateEnabled).
@@ -696,7 +696,7 @@ func (this *ServerDAO) ListEnabledServersMatch(tx *dbs.Tx, offset int64, size in
return
}
// 获取节点中的所有服务
// FindAllEnabledServersWithNode 获取节点中的所有服务
func (this *ServerDAO) FindAllEnabledServersWithNode(tx *dbs.Tx, nodeId int64) (result []*Server, err error) {
// 节点所在集群
clusterId, err := SharedNodeDAO.FindNodeClusterId(tx, nodeId)
@@ -716,7 +716,7 @@ func (this *ServerDAO) FindAllEnabledServersWithNode(tx *dbs.Tx, nodeId int64) (
return
}
// 获取所有的服务ID
// FindAllEnabledServerIds 获取所有的服务ID
func (this *ServerDAO) FindAllEnabledServerIds(tx *dbs.Tx) (serverIds []int64, err error) {
ones, err := this.Query(tx).
State(ServerStateEnabled).
@@ -729,7 +729,7 @@ func (this *ServerDAO) FindAllEnabledServerIds(tx *dbs.Tx) (serverIds []int64, e
return
}
// 获取某个用户的所有的服务ID
// FindAllEnabledServerIdsWithUserId 获取某个用户的所有的服务ID
func (this *ServerDAO) FindAllEnabledServerIdsWithUserId(tx *dbs.Tx, userId int64) (serverIds []int64, err error) {
ones, err := this.Query(tx).
State(ServerStateEnabled).
@@ -743,7 +743,7 @@ func (this *ServerDAO) FindAllEnabledServerIdsWithUserId(tx *dbs.Tx, userId int6
return
}
// 查找服务的搜索条件
// FindServerNodeFilters 查找服务的搜索条件
func (this *ServerDAO) FindServerNodeFilters(tx *dbs.Tx, serverId int64) (isOk bool, clusterId int64, err error) {
one, err := this.Query(tx).
Pk(serverId).
@@ -760,7 +760,7 @@ func (this *ServerDAO) FindServerNodeFilters(tx *dbs.Tx, serverId int64) (isOk b
return true, int64(server.ClusterId), nil
}
// 构造服务的Config
// ComposeServerConfig 构造服务的Config
func (this *ServerDAO) ComposeServerConfig(tx *dbs.Tx, serverId int64) (*serverconfigs.ServerConfig, error) {
server, err := this.FindEnabledServer(tx, serverId)
if err != nil {
@@ -921,7 +921,7 @@ func (this *ServerDAO) ComposeServerConfig(tx *dbs.Tx, serverId int64) (*serverc
return config, nil
}
// 更新服务的Config配置
// RenewServerConfig 更新服务的Config配置
func (this *ServerDAO) RenewServerConfig(tx *dbs.Tx, serverId int64, updateMd5 bool) (isChanged bool, err error) {
serverConfig, err := this.ComposeServerConfig(tx, serverId)
if err != nil {
@@ -934,7 +934,7 @@ func (this *ServerDAO) RenewServerConfig(tx *dbs.Tx, serverId int64, updateMd5 b
return this.UpdateServerConfig(tx, serverId, data, updateMd5)
}
// 根据条件获取反向代理配置
// FindReverseProxyRef 根据条件获取反向代理配置
func (this *ServerDAO) FindReverseProxyRef(tx *dbs.Tx, serverId int64) (*serverconfigs.ReverseProxyRef, error) {
reverseProxy, err := this.Query(tx).
Pk(serverId).
@@ -951,7 +951,7 @@ func (this *ServerDAO) FindReverseProxyRef(tx *dbs.Tx, serverId int64) (*serverc
return config, err
}
// 查找Server对应的WebId
// FindServerWebId 查找Server对应的WebId
func (this *ServerDAO) FindServerWebId(tx *dbs.Tx, serverId int64) (int64, error) {
webId, err := this.Query(tx).
Pk(serverId).
@@ -963,7 +963,7 @@ func (this *ServerDAO) FindServerWebId(tx *dbs.Tx, serverId int64) (int64, error
return int64(webId), nil
}
// 计算使用SSL策略的所有服务数量
// CountAllEnabledServersWithSSLPolicyIds 计算使用SSL策略的所有服务数量
func (this *ServerDAO) CountAllEnabledServersWithSSLPolicyIds(tx *dbs.Tx, sslPolicyIds []int64) (count int64, err error) {
if len(sslPolicyIds) == 0 {
return
@@ -979,7 +979,7 @@ func (this *ServerDAO) CountAllEnabledServersWithSSLPolicyIds(tx *dbs.Tx, sslPol
Count()
}
// 查找使用某个SSL策略的所有服务
// FindAllEnabledServersWithSSLPolicyIds 查找使用某个SSL策略的所有服务
func (this *ServerDAO) FindAllEnabledServersWithSSLPolicyIds(tx *dbs.Tx, sslPolicyIds []int64) (result []*Server, err error) {
if len(sslPolicyIds) == 0 {
return
@@ -999,7 +999,7 @@ func (this *ServerDAO) FindAllEnabledServersWithSSLPolicyIds(tx *dbs.Tx, sslPoli
return
}
// 查找使用某个SSL策略的所有服务Id
// FindAllEnabledServerIdsWithSSLPolicyIds 查找使用某个SSL策略的所有服务Id
func (this *ServerDAO) FindAllEnabledServerIdsWithSSLPolicyIds(tx *dbs.Tx, sslPolicyIds []int64) (result []int64, err error) {
if len(sslPolicyIds) == 0 {
return
@@ -1025,7 +1025,7 @@ func (this *ServerDAO) FindAllEnabledServerIdsWithSSLPolicyIds(tx *dbs.Tx, sslPo
return
}
// 计算使用某个缓存策略的所有服务数量
// CountEnabledServersWithWebIds 计算使用某个缓存策略的所有服务数量
func (this *ServerDAO) CountEnabledServersWithWebIds(tx *dbs.Tx, webIds []int64) (count int64, err error) {
if len(webIds) == 0 {
return
@@ -1037,7 +1037,7 @@ func (this *ServerDAO) CountEnabledServersWithWebIds(tx *dbs.Tx, webIds []int64)
Count()
}
// 查找使用某个缓存策略的所有服务
// FindAllEnabledServersWithWebIds 查找使用某个缓存策略的所有服务
func (this *ServerDAO) FindAllEnabledServersWithWebIds(tx *dbs.Tx, webIds []int64) (result []*Server, err error) {
if len(webIds) == 0 {
return
@@ -1052,7 +1052,7 @@ func (this *ServerDAO) FindAllEnabledServersWithWebIds(tx *dbs.Tx, webIds []int6
return
}
// 计算使用某个集群的所有服务数量
// CountAllEnabledServersWithNodeClusterId 计算使用某个集群的所有服务数量
func (this *ServerDAO) CountAllEnabledServersWithNodeClusterId(tx *dbs.Tx, clusterId int64) (int64, error) {
return this.Query(tx).
State(ServerStateEnabled).
@@ -1060,7 +1060,7 @@ func (this *ServerDAO) CountAllEnabledServersWithNodeClusterId(tx *dbs.Tx, clust
Count()
}
// 计算使用某个分组的服务数量
// CountAllEnabledServersWithGroupId 计算使用某个分组的服务数量
func (this *ServerDAO) CountAllEnabledServersWithGroupId(tx *dbs.Tx, groupId int64) (int64, error) {
return this.Query(tx).
State(ServerStateEnabled).
@@ -1069,7 +1069,7 @@ func (this *ServerDAO) CountAllEnabledServersWithGroupId(tx *dbs.Tx, groupId int
Count()
}
// 查询使用某个DNS域名的所有服务域名
// FindAllServerDNSNamesWithDNSDomainId 查询使用某个DNS域名的所有服务域名
func (this *ServerDAO) FindAllServerDNSNamesWithDNSDomainId(tx *dbs.Tx, dnsDomainId int64) ([]string, error) {
clusterIds, err := SharedNodeClusterDAO.FindAllEnabledClusterIdsWithDNSDomainId(tx, dnsDomainId)
if err != nil {
@@ -1099,7 +1099,7 @@ func (this *ServerDAO) FindAllServerDNSNamesWithDNSDomainId(tx *dbs.Tx, dnsDomai
return result, nil
}
// 获取某个集群下的服务DNS信息
// FindAllServersDNSWithClusterId 获取某个集群下的服务DNS信息
func (this *ServerDAO) FindAllServersDNSWithClusterId(tx *dbs.Tx, clusterId int64) (result []*Server, err error) {
_, err = this.Query(tx).
State(ServerStateEnabled).
@@ -1113,7 +1113,7 @@ func (this *ServerDAO) FindAllServersDNSWithClusterId(tx *dbs.Tx, clusterId int6
return
}
// 重新生成子域名
// GenerateServerDNSName 重新生成子域名
func (this *ServerDAO) GenerateServerDNSName(tx *dbs.Tx, serverId int64) (string, error) {
if serverId <= 0 {
return "", errors.New("invalid serverId")
@@ -1143,7 +1143,7 @@ func (this *ServerDAO) GenerateServerDNSName(tx *dbs.Tx, serverId int64) (string
return dnsName, nil
}
// 查询当前服务的集群ID
// FindServerClusterId 查询当前服务的集群ID
func (this *ServerDAO) FindServerClusterId(tx *dbs.Tx, serverId int64) (int64, error) {
return this.Query(tx).
Pk(serverId).
@@ -1151,7 +1151,7 @@ func (this *ServerDAO) FindServerClusterId(tx *dbs.Tx, serverId int64) (int64, e
FindInt64Col(0)
}
// 查询服务的DNS名称
// FindServerDNSName 查询服务的DNS名称
func (this *ServerDAO) FindServerDNSName(tx *dbs.Tx, serverId int64) (string, error) {
return this.Query(tx).
Pk(serverId).
@@ -1159,7 +1159,7 @@ func (this *ServerDAO) FindServerDNSName(tx *dbs.Tx, serverId int64) (string, er
FindStringCol("")
}
// 查询服务的DNS相关信息并且不关注状态
// FindStatelessServerDNS 查询服务的DNS相关信息并且不关注状态
func (this *ServerDAO) FindStatelessServerDNS(tx *dbs.Tx, serverId int64) (*Server, error) {
one, err := this.Query(tx).
Pk(serverId).
@@ -1171,7 +1171,7 @@ func (this *ServerDAO) FindStatelessServerDNS(tx *dbs.Tx, serverId int64) (*Serv
return one.(*Server), nil
}
// 获取当前服务的管理员ID和用户ID
// FindServerAdminIdAndUserId 获取当前服务的管理员ID和用户ID
func (this *ServerDAO) FindServerAdminIdAndUserId(tx *dbs.Tx, serverId int64) (adminId int64, userId int64, err error) {
one, err := this.Query(tx).
Pk(serverId).
@@ -1186,7 +1186,7 @@ func (this *ServerDAO) FindServerAdminIdAndUserId(tx *dbs.Tx, serverId int64) (a
return int64(one.(*Server).AdminId), int64(one.(*Server).UserId), nil
}
// 检查用户服务
// CheckUserServer 检查用户服务
func (this *ServerDAO) CheckUserServer(tx *dbs.Tx, userId int64, serverId int64) error {
if serverId <= 0 || userId <= 0 {
return ErrNotFound
@@ -1204,7 +1204,7 @@ func (this *ServerDAO) CheckUserServer(tx *dbs.Tx, userId int64, serverId int64)
return nil
}
// 设置一个用户下的所有服务的所属集群
// UpdateUserServersClusterId 设置一个用户下的所有服务的所属集群
func (this *ServerDAO) UpdateUserServersClusterId(tx *dbs.Tx, userId int64, clusterId int64) error {
// 之前的cluster
oldClusterId, err := SharedUserDAO.FindUserClusterId(tx, userId)
@@ -1248,7 +1248,7 @@ func (this *ServerDAO) UpdateUserServersClusterId(tx *dbs.Tx, userId int64, clus
return err
}
// 查找用户的所有的服务
// FindAllEnabledServersWithUserId 查找用户的所有的服务
func (this *ServerDAO) FindAllEnabledServersWithUserId(tx *dbs.Tx, userId int64) (result []*Server, err error) {
_, err = this.Query(tx).
State(ServerStateEnabled).
@@ -1259,7 +1259,7 @@ func (this *ServerDAO) FindAllEnabledServersWithUserId(tx *dbs.Tx, userId int64)
return
}
// 根据WebId查找ServerId
// FindEnabledServerIdWithWebId 根据WebId查找ServerId
func (this *ServerDAO) FindEnabledServerIdWithWebId(tx *dbs.Tx, webId int64) (serverId int64, err error) {
if webId <= 0 {
return 0, nil
@@ -1271,7 +1271,7 @@ func (this *ServerDAO) FindEnabledServerIdWithWebId(tx *dbs.Tx, webId int64) (se
FindInt64Col(0)
}
// 查找包含某个反向代理的Server
// FindEnabledServerIdWithReverseProxyId 查找包含某个反向代理的Server
func (this *ServerDAO) FindEnabledServerIdWithReverseProxyId(tx *dbs.Tx, reverseProxyId int64) (serverId int64, err error) {
return this.Query(tx).
State(ServerStateEnabled).
@@ -1281,7 +1281,7 @@ func (this *ServerDAO) FindEnabledServerIdWithReverseProxyId(tx *dbs.Tx, reverse
FindInt64Col(0)
}
// 检查端口是否被使用
// CheckPortIsUsing 检查端口是否被使用
func (this *ServerDAO) CheckPortIsUsing(tx *dbs.Tx, clusterId int64, port int, excludeServerId int64, excludeProtocol string) (bool, error) {
listen := maps.Map{
"portRange": strconv.Itoa(port),
@@ -1321,7 +1321,7 @@ func (this *ServerDAO) CheckPortIsUsing(tx *dbs.Tx, clusterId int64, port int, e
Exist()
}
// 检查ServerName是否已存在
// ExistServerNameInCluster 检查ServerName是否已存在
func (this *ServerDAO) ExistServerNameInCluster(tx *dbs.Tx, clusterId int64, serverName string, excludeServerId int64) (bool, error) {
query := this.Query(tx).
Attr("clusterId", clusterId).
@@ -1335,7 +1335,7 @@ func (this *ServerDAO) ExistServerNameInCluster(tx *dbs.Tx, clusterId int64, ser
return query.Exist()
}
// 生成DNS Name
// GenDNSName 生成DNS Name
func (this *ServerDAO) GenDNSName(tx *dbs.Tx) (string, error) {
for {
dnsName := rands.HexString(8)
@@ -1351,7 +1351,23 @@ func (this *ServerDAO) GenDNSName(tx *dbs.Tx) (string, error) {
}
}
// 同步集群
// 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
}
// NotifyUpdate 同步集群
func (this *ServerDAO) NotifyUpdate(tx *dbs.Tx, serverId int64) error {
// 更新配置
_, err := this.RenewServerConfig(tx, serverId, true)
@@ -1370,7 +1386,7 @@ func (this *ServerDAO) NotifyUpdate(tx *dbs.Tx, serverId int64) error {
return SharedNodeTaskDAO.CreateClusterTask(tx, clusterId, NodeTaskTypeConfigChanged)
}
// 通知DNS更新
// NotifyDNSUpdate 通知DNS更新
func (this *ServerDAO) NotifyDNSUpdate(tx *dbs.Tx, serverId int64) error {
clusterId, err := this.Query(tx).
Pk(serverId).

View File

@@ -3,6 +3,7 @@ package models
import (
"encoding/json"
"github.com/TeaOSLab/EdgeAPI/internal/errors"
"github.com/TeaOSLab/EdgeAPI/internal/utils"
_ "github.com/go-sql-driver/mysql"
"github.com/iwind/TeaGo/Tea"
"github.com/iwind/TeaGo/dbs"
@@ -38,7 +39,7 @@ func init() {
})
}
// 启用条目
// EnableUserNode 启用条目
func (this *UserNodeDAO) EnableUserNode(tx *dbs.Tx, id uint32) error {
_, err := this.Query(tx).
Pk(id).
@@ -47,7 +48,7 @@ func (this *UserNodeDAO) EnableUserNode(tx *dbs.Tx, id uint32) error {
return err
}
// 禁用条目
// DisableUserNode 禁用条目
func (this *UserNodeDAO) DisableUserNode(tx *dbs.Tx, id int64) error {
_, err := this.Query(tx).
Pk(id).
@@ -56,7 +57,7 @@ func (this *UserNodeDAO) DisableUserNode(tx *dbs.Tx, id int64) error {
return err
}
// 查找启用中的条目
// FindEnabledUserNode 查找启用中的条目
func (this *UserNodeDAO) FindEnabledUserNode(tx *dbs.Tx, id int64) (*UserNode, error) {
result, err := this.Query(tx).
Pk(id).
@@ -68,7 +69,7 @@ func (this *UserNodeDAO) FindEnabledUserNode(tx *dbs.Tx, id int64) (*UserNode, e
return result.(*UserNode), err
}
// 根据主键查找名称
// FindUserNodeName 根据主键查找名称
func (this *UserNodeDAO) FindUserNodeName(tx *dbs.Tx, id int64) (string, error) {
return this.Query(tx).
Pk(id).
@@ -76,7 +77,7 @@ func (this *UserNodeDAO) FindUserNodeName(tx *dbs.Tx, id int64) (string, error)
FindStringCol("")
}
// 列出所有可用用户节点
// FindAllEnabledUserNodes 列出所有可用用户节点
func (this *UserNodeDAO) FindAllEnabledUserNodes(tx *dbs.Tx) (result []*UserNode, err error) {
_, err = this.Query(tx).
State(UserNodeStateEnabled).
@@ -87,14 +88,14 @@ func (this *UserNodeDAO) FindAllEnabledUserNodes(tx *dbs.Tx) (result []*UserNode
return
}
// 计算用户节点数量
// CountAllEnabledUserNodes 计算用户节点数量
func (this *UserNodeDAO) CountAllEnabledUserNodes(tx *dbs.Tx) (int64, error) {
return this.Query(tx).
State(UserNodeStateEnabled).
Count()
}
// 列出单页的用户节点
// ListEnabledUserNodes 列出单页的用户节点
func (this *UserNodeDAO) ListEnabledUserNodes(tx *dbs.Tx, offset int64, size int64) (result []*UserNode, err error) {
_, err = this.Query(tx).
State(UserNodeStateEnabled).
@@ -107,7 +108,7 @@ func (this *UserNodeDAO) ListEnabledUserNodes(tx *dbs.Tx, offset int64, size int
return
}
// 根据主机名和端口获取ID
// FindEnabledUserNodeIdWithAddr 根据主机名和端口获取ID
func (this *UserNodeDAO) FindEnabledUserNodeIdWithAddr(tx *dbs.Tx, protocol string, host string, port int) (int64, error) {
addr := maps.Map{
"protocol": protocol,
@@ -134,7 +135,7 @@ func (this *UserNodeDAO) FindEnabledUserNodeIdWithAddr(tx *dbs.Tx, protocol stri
return int64(one.(*UserNode).Id), nil
}
// 创建用户节点
// CreateUserNode 创建用户节点
func (this *UserNodeDAO) CreateUserNode(tx *dbs.Tx, name string, description string, httpJSON []byte, httpsJSON []byte, accessAddrsJSON []byte, isOn bool) (nodeId int64, err error) {
uniqueId, err := this.GenUniqueId(tx)
if err != nil {
@@ -172,7 +173,7 @@ func (this *UserNodeDAO) CreateUserNode(tx *dbs.Tx, name string, description str
return types.Int64(op.Id), nil
}
// 修改用户节点
// UpdateUserNode 修改用户节点
func (this *UserNodeDAO) UpdateUserNode(tx *dbs.Tx, nodeId int64, name string, description string, httpJSON []byte, httpsJSON []byte, accessAddrsJSON []byte, isOn bool) error {
if nodeId <= 0 {
return errors.New("invalid nodeId")
@@ -204,7 +205,7 @@ func (this *UserNodeDAO) UpdateUserNode(tx *dbs.Tx, nodeId int64, name string, d
return err
}
// 根据唯一ID获取节点信息
// FindEnabledUserNodeWithUniqueId 根据唯一ID获取节点信息
func (this *UserNodeDAO) FindEnabledUserNodeWithUniqueId(tx *dbs.Tx, uniqueId string) (*UserNode, error) {
result, err := this.Query(tx).
Attr("uniqueId", uniqueId).
@@ -216,7 +217,7 @@ func (this *UserNodeDAO) FindEnabledUserNodeWithUniqueId(tx *dbs.Tx, uniqueId st
return result.(*UserNode), err
}
// 根据唯一ID获取节点ID
// FindEnabledUserNodeIdWithUniqueId 根据唯一ID获取节点ID
func (this *UserNodeDAO) FindEnabledUserNodeIdWithUniqueId(tx *dbs.Tx, uniqueId string) (int64, error) {
return this.Query(tx).
Attr("uniqueId", uniqueId).
@@ -225,7 +226,7 @@ func (this *UserNodeDAO) FindEnabledUserNodeIdWithUniqueId(tx *dbs.Tx, uniqueId
FindInt64Col(0)
}
// 生成唯一ID
// GenUniqueId 生成唯一ID
func (this *UserNodeDAO) GenUniqueId(tx *dbs.Tx) (string, error) {
for {
uniqueId := rands.HexString(32)
@@ -242,7 +243,7 @@ func (this *UserNodeDAO) GenUniqueId(tx *dbs.Tx) (string, error) {
}
}
// 更改节点状态
// UpdateNodeStatus 更改节点状态
func (this *UserNodeDAO) UpdateNodeStatus(tx *dbs.Tx, nodeId int64, statusJSON []byte) error {
if len(statusJSON) == 0 {
return nil
@@ -253,3 +254,13 @@ func (this *UserNodeDAO) UpdateNodeStatus(tx *dbs.Tx, nodeId int64, statusJSON [
Update()
return err
}
// CountAllLowerVersionNodes 计算所有节点中低于某个版本的节点数量
func (this *UserNodeDAO) CountAllLowerVersionNodes(tx *dbs.Tx, version string) (int64, error) {
return this.Query(tx).
State(UserNodeStateEnabled).
Where("status IS NOT NULL").
Where("(JSON_EXTRACT(status, '$.buildVersionCode') IS NULL OR JSON_EXTRACT(status, '$.buildVersionCode')<:version)").
Param("version", utils.VersionToLong(version)).
Count()
}

View File

@@ -250,6 +250,7 @@ func (this *APINode) listenRPC(listener net.Listener, tlsConfig *tls.Config) err
pb.RegisterUserAccessKeyServiceServer(rpcServer, &services.UserAccessKeyService{})
pb.RegisterSysLockerServiceServer(rpcServer, &services.SysLockerService{})
pb.RegisterNodeTaskServiceServer(rpcServer, &services.NodeTaskService{})
pb.RegisterNodeValueServiceServer(rpcServer, &services.NodeValueService{})
pb.RegisterDBServiceServer(rpcServer, &services.DBService{})
pb.RegisterServerRegionCityMonthlyStatServiceServer(rpcServer, &services.ServerRegionCityMonthlyStatService{})
pb.RegisterServerRegionCountryMonthlyStatServiceServer(rpcServer, &services.ServerRegionCountryMonthlyStatService{})
@@ -263,6 +264,9 @@ func (this *APINode) listenRPC(listener net.Listener, tlsConfig *tls.Config) err
pb.RegisterMonitorNodeServiceServer(rpcServer, &services.MonitorNodeService{})
pb.RegisterAuthorityKeyServiceServer(rpcServer, &services.AuthorityKeyService{})
pb.RegisterAuthorityNodeServiceServer(rpcServer, &services.AuthorityNodeService{})
pb.RegisterLatestItemServiceServer(rpcServer, &services.LatestItemService{})
pb.RegisterNodeThresholdServiceServer(rpcServer, &services.NodeThresholdService{})
pb.RegisterHTTPFastcgiServiceServer(rpcServer, &services.HTTPFastcgiService{})
err := rpcServer.Serve(listener)
if err != nil {
return errors.New("[API_NODE]start rpc failed: " + err.Error())
@@ -288,7 +292,7 @@ func (this *APINode) checkDB() error {
return err
} else {
if i%10 == 0 { // 这让提示不会太多
logs.Println("[API_NODE]reconnecting to database (" + fmt.Sprintf("%.1f", float32(i * 100)/float32(maxTries+1)) + "%) ...")
logs.Println("[API_NODE]reconnecting to database (" + fmt.Sprintf("%.1f", float32(i*100)/float32(maxTries+1)) + "%) ...")
}
time.Sleep(1 * time.Second)
}

View File

@@ -3,7 +3,9 @@ package services
import (
"context"
"encoding/json"
teaconst "github.com/TeaOSLab/EdgeAPI/internal/const"
"github.com/TeaOSLab/EdgeAPI/internal/db/models"
"github.com/TeaOSLab/EdgeAPI/internal/db/models/authority"
"github.com/TeaOSLab/EdgeAPI/internal/db/models/stats"
"github.com/TeaOSLab/EdgeAPI/internal/errors"
rpcutils "github.com/TeaOSLab/EdgeAPI/internal/rpc/utils"
@@ -14,13 +16,14 @@ import (
"time"
)
// AdminService 管理员相关服务
type AdminService struct {
BaseService
debug bool
}
// 登录
// LoginAdmin 登录
func (this *AdminService) LoginAdmin(ctx context.Context, req *pb.LoginAdminRequest) (*pb.LoginAdminResponse, error) {
_, _, err := rpcutils.ValidateRequest(ctx)
if err != nil {
@@ -57,7 +60,7 @@ func (this *AdminService) LoginAdmin(ctx context.Context, req *pb.LoginAdminRequ
}, nil
}
// 检查管理员是否存在
// CheckAdminExists 检查管理员是否存在
func (this *AdminService) CheckAdminExists(ctx context.Context, req *pb.CheckAdminExistsRequest) (*pb.CheckAdminExistsResponse, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
if err != nil {
@@ -82,7 +85,7 @@ func (this *AdminService) CheckAdminExists(ctx context.Context, req *pb.CheckAdm
}, nil
}
// 检查用户名是否存在
// CheckAdminUsername 检查用户名是否存在
func (this *AdminService) CheckAdminUsername(ctx context.Context, req *pb.CheckAdminUsernameRequest) (*pb.CheckAdminUsernameResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -100,7 +103,7 @@ func (this *AdminService) CheckAdminUsername(ctx context.Context, req *pb.CheckA
return &pb.CheckAdminUsernameResponse{Exists: exists}, nil
}
// 获取管理员名称
// FindAdminFullname 获取管理员名称
func (this *AdminService) FindAdminFullname(ctx context.Context, req *pb.FindAdminFullnameRequest) (*pb.FindAdminFullnameResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -121,7 +124,7 @@ func (this *AdminService) FindAdminFullname(ctx context.Context, req *pb.FindAdm
}, nil
}
// 获取管理员信息
// FindEnabledAdmin 获取管理员信息
func (this *AdminService) FindEnabledAdmin(ctx context.Context, req *pb.FindEnabledAdminRequest) (*pb.FindEnabledAdminResponse, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
if err != nil {
@@ -186,7 +189,7 @@ func (this *AdminService) FindEnabledAdmin(ctx context.Context, req *pb.FindEnab
return &pb.FindEnabledAdminResponse{Admin: result}, nil
}
// 创建或修改管理员
// CreateOrUpdateAdmin 创建或修改管理员
func (this *AdminService) CreateOrUpdateAdmin(ctx context.Context, req *pb.CreateOrUpdateAdminRequest) (*pb.CreateOrUpdateAdminResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin, rpcutils.UserTypeAPI)
@@ -214,7 +217,7 @@ func (this *AdminService) CreateOrUpdateAdmin(ctx context.Context, req *pb.Creat
return &pb.CreateOrUpdateAdminResponse{AdminId: adminId}, nil
}
// 修改管理员信息
// UpdateAdminInfo 修改管理员信息
func (this *AdminService) UpdateAdminInfo(ctx context.Context, req *pb.UpdateAdminInfoRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin, rpcutils.UserTypeAPI)
@@ -231,7 +234,7 @@ func (this *AdminService) UpdateAdminInfo(ctx context.Context, req *pb.UpdateAdm
return this.Success()
}
// 修改管理员登录信息
// UpdateAdminLogin 修改管理员登录信息
func (this *AdminService) UpdateAdminLogin(ctx context.Context, req *pb.UpdateAdminLoginRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin, rpcutils.UserTypeAPI)
@@ -256,7 +259,7 @@ func (this *AdminService) UpdateAdminLogin(ctx context.Context, req *pb.UpdateAd
return this.Success()
}
// 获取所有管理员的权限列表
// FindAllAdminModules 获取所有管理员的权限列表
func (this *AdminService) FindAllAdminModules(ctx context.Context, req *pb.FindAllAdminModulesRequest) (*pb.FindAllAdminModulesResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -302,7 +305,7 @@ func (this *AdminService) FindAllAdminModules(ctx context.Context, req *pb.FindA
return &pb.FindAllAdminModulesResponse{AdminModules: result}, nil
}
// 创建管理员
// CreateAdmin 创建管理员
func (this *AdminService) CreateAdmin(ctx context.Context, req *pb.CreateAdminRequest) (*pb.CreateAdminResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -321,7 +324,7 @@ func (this *AdminService) CreateAdmin(ctx context.Context, req *pb.CreateAdminRe
return &pb.CreateAdminResponse{AdminId: adminId}, nil
}
// 修改管理员
// UpdateAdmin 修改管理员
func (this *AdminService) UpdateAdmin(ctx context.Context, req *pb.UpdateAdminRequest) (*pb.RPCSuccess, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -340,7 +343,7 @@ func (this *AdminService) UpdateAdmin(ctx context.Context, req *pb.UpdateAdminRe
return this.Success()
}
// 计算管理员数量
// CountAllEnabledAdmins 计算管理员数量
func (this *AdminService) CountAllEnabledAdmins(ctx context.Context, req *pb.CountAllEnabledAdminsRequest) (*pb.RPCCountResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -358,7 +361,7 @@ func (this *AdminService) CountAllEnabledAdmins(ctx context.Context, req *pb.Cou
return this.SuccessCount(count)
}
// 列出单页的管理员
// ListEnabledAdmins 列出单页的管理员
func (this *AdminService) ListEnabledAdmins(ctx context.Context, req *pb.ListEnabledAdminsRequest) (*pb.ListEnabledAdminsResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -407,7 +410,7 @@ func (this *AdminService) ListEnabledAdmins(ctx context.Context, req *pb.ListEna
return &pb.ListEnabledAdminsResponse{Admins: result}, nil
}
// 删除管理员
// DeleteAdmin 删除管理员
func (this *AdminService) DeleteAdmin(ctx context.Context, req *pb.DeleteAdminRequest) (*pb.RPCSuccess, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -428,7 +431,7 @@ func (this *AdminService) DeleteAdmin(ctx context.Context, req *pb.DeleteAdminRe
return this.Success()
}
// 检查是否需要输入OTP
// CheckAdminOTPWithUsername 检查是否需要输入OTP
func (this *AdminService) CheckAdminOTPWithUsername(ctx context.Context, req *pb.CheckAdminOTPWithUsernameRequest) (*pb.CheckAdminOTPWithUsernameResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -456,7 +459,7 @@ func (this *AdminService) CheckAdminOTPWithUsername(ctx context.Context, req *pb
return &pb.CheckAdminOTPWithUsernameResponse{RequireOTP: otpIsOn}, nil
}
// 取得管理员Dashboard数据
// ComposeAdminDashboard 取得管理员Dashboard数据
func (this *AdminService) ComposeAdminDashboard(ctx context.Context, req *pb.ComposeAdminDashboardRequest) (*pb.ComposeAdminDashboardResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -543,5 +546,70 @@ func (this *AdminService) ComposeAdminDashboard(ctx context.Context, req *pb.Com
})
}
// 边缘节点升级信息
{
upgradeInfo := &pb.ComposeAdminDashboardResponse_UpgradeInfo{
NewVersion: teaconst.NodeVersion,
}
countNodes, err := models.SharedNodeDAO.CountAllLowerVersionNodes(tx, upgradeInfo.NewVersion)
if err != nil {
return nil, err
}
upgradeInfo.CountNodes = countNodes
resp.NodeUpgradeInfo = upgradeInfo
}
// 监控节点升级信息
{
upgradeInfo := &pb.ComposeAdminDashboardResponse_UpgradeInfo{
NewVersion: teaconst.MonitorNodeVersion,
}
countNodes, err := models.SharedMonitorNodeDAO.CountAllLowerVersionNodes(tx, upgradeInfo.NewVersion)
if err != nil {
return nil, err
}
upgradeInfo.CountNodes = countNodes
resp.MonitorNodeUpgradeInfo = upgradeInfo
}
// 认证节点升级信息
{
upgradeInfo := &pb.ComposeAdminDashboardResponse_UpgradeInfo{
NewVersion: teaconst.AuthorityNodeVersion,
}
countNodes, err := authority.SharedAuthorityNodeDAO.CountAllLowerVersionNodes(tx, upgradeInfo.NewVersion)
if err != nil {
return nil, err
}
upgradeInfo.CountNodes = countNodes
resp.AuthorityNodeUpgradeInfo = upgradeInfo
}
// 用户节点升级信息
{
upgradeInfo := &pb.ComposeAdminDashboardResponse_UpgradeInfo{
NewVersion: teaconst.UserNodeVersion,
}
countNodes, err := models.SharedUserNodeDAO.CountAllLowerVersionNodes(tx, upgradeInfo.NewVersion)
if err != nil {
return nil, err
}
upgradeInfo.CountNodes = countNodes
resp.UserNodeUpgradeInfo = upgradeInfo
}
// API节点升级信息
{
upgradeInfo := &pb.ComposeAdminDashboardResponse_UpgradeInfo{
NewVersion: teaconst.Version,
}
countNodes, err := models.SharedAPINodeDAO.CountAllLowerVersionNodes(tx, upgradeInfo.NewVersion)
if err != nil {
return nil, err
}
upgradeInfo.CountNodes = countNodes
resp.ApiNodeUpgradeInfo = upgradeInfo
}
return resp, nil
}

View File

@@ -0,0 +1,112 @@
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package services
import (
"context"
"encoding/json"
"github.com/TeaOSLab/EdgeAPI/internal/db/models"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/iwind/TeaGo/types"
)
// HTTPFastcgiService HTTP Fastcgi服务
type HTTPFastcgiService struct {
BaseService
}
// CreateHTTPFastcgi 创建Fastcgi
func (this *HTTPFastcgiService) CreateHTTPFastcgi(ctx context.Context, req *pb.CreateHTTPFastcgiRequest) (*pb.CreateHTTPFastcgiResponse, error) {
adminId, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
if err != nil {
return nil, err
}
var tx = this.NullTx()
fastcgiId, err := models.SharedHTTPFastcgiDAO.CreateFastcgi(tx, adminId, userId, req.IsOn, req.Address, req.ParamsJSON, req.ReadTimeoutJSON, req.ConnTimeoutJSON, req.PoolSize, req.PathInfoPattern)
if err != nil {
return nil, err
}
return &pb.CreateHTTPFastcgiResponse{HttpFastcgiId: fastcgiId}, nil
}
// UpdateHTTPFastcgi 修改Fastcgi
func (this *HTTPFastcgiService) UpdateHTTPFastcgi(ctx context.Context, req *pb.UpdateHTTPFastcgiRequest) (*pb.RPCSuccess, error) {
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
if err != nil {
return nil, err
}
var tx = this.NullTx()
if userId > 0 {
err = models.SharedHTTPFastcgiDAO.CheckUserFastcgi(tx, userId, req.HttpFastcgiId)
if err != nil {
return nil, err
}
}
err = models.SharedHTTPFastcgiDAO.UpdateFastcgi(tx, req.HttpFastcgiId, req.IsOn, req.Address, req.ParamsJSON, req.ReadTimeoutJSON, req.ConnTimeoutJSON, req.PoolSize, req.PathInfoPattern)
if err != nil {
return nil, err
}
return this.Success()
}
// FindEnabledHTTPFastcgi 获取Fastcgi详情
func (this *HTTPFastcgiService) FindEnabledHTTPFastcgi(ctx context.Context, req *pb.FindEnabledHTTPFastcgiRequest) (*pb.FindEnabledHTTPFastcgiResponse, error) {
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
if err != nil {
return nil, err
}
var tx = this.NullTx()
if userId > 0 {
err = models.SharedHTTPFastcgiDAO.CheckUserFastcgi(tx, userId, req.HttpFastcgiId)
if err != nil {
return nil, err
}
}
fastcgi, err := models.SharedHTTPFastcgiDAO.FindEnabledHTTPFastcgi(tx, req.HttpFastcgiId)
if err != nil {
return nil, err
}
if fastcgi == nil {
return &pb.FindEnabledHTTPFastcgiResponse{HttpFastcgi: nil}, nil
}
return &pb.FindEnabledHTTPFastcgiResponse{HttpFastcgi: &pb.HTTPFastcgi{
Id: int64(fastcgi.Id),
IsOn: fastcgi.IsOn == 1,
Address: fastcgi.Address,
ParamsJSON: []byte(fastcgi.Params),
ReadTimeoutJSON: []byte(fastcgi.ReadTimeout),
ConnTimeoutJSON: []byte(fastcgi.ConnTimeout),
PoolSize: types.Int32(fastcgi.PoolSize),
PathInfoPattern: fastcgi.PathInfoPattern,
}}, nil
}
// FindEnabledHTTPFastcgiConfig 获取Fastcgi配置
func (this *HTTPFastcgiService) FindEnabledHTTPFastcgiConfig(ctx context.Context, req *pb.FindEnabledHTTPFastcgiConfigRequest) (*pb.FindEnabledHTTPFastcgiConfigResponse, error) {
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
if err != nil {
return nil, err
}
var tx = this.NullTx()
if userId > 0 {
err = models.SharedHTTPFastcgiDAO.CheckUserFastcgi(tx, userId, req.HttpFastcgiId)
if err != nil {
return nil, err
}
}
config, err := models.SharedHTTPFastcgiDAO.ComposeFastcgiConfig(tx, req.HttpFastcgiId)
if err != nil {
return nil, err
}
configJSON, err := json.Marshal(config)
if err != nil {
return nil, err
}
return &pb.FindEnabledHTTPFastcgiConfigResponse{HttpFastcgiJSON: configJSON}, nil
}

View File

@@ -14,7 +14,7 @@ type HTTPWebService struct {
BaseService
}
// 创建Web配置
// CreateHTTPWeb 创建Web配置
func (this *HTTPWebService) CreateHTTPWeb(ctx context.Context, req *pb.CreateHTTPWebRequest) (*pb.CreateHTTPWebResponse, error) {
// 校验请求
adminId, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -32,7 +32,7 @@ func (this *HTTPWebService) CreateHTTPWeb(ctx context.Context, req *pb.CreateHTT
return &pb.CreateHTTPWebResponse{WebId: webId}, nil
}
// 查找Web配置
// FindEnabledHTTPWeb 查找Web配置
func (this *HTTPWebService) FindEnabledHTTPWeb(ctx context.Context, req *pb.FindEnabledHTTPWebRequest) (*pb.FindEnabledHTTPWebResponse, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -65,7 +65,7 @@ func (this *HTTPWebService) FindEnabledHTTPWeb(ctx context.Context, req *pb.Find
return &pb.FindEnabledHTTPWebResponse{Web: result}, nil
}
// 查找Web配置
// FindEnabledHTTPWebConfig 查找Web配置
func (this *HTTPWebService) FindEnabledHTTPWebConfig(ctx context.Context, req *pb.FindEnabledHTTPWebConfigRequest) (*pb.FindEnabledHTTPWebConfigResponse, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -95,7 +95,7 @@ func (this *HTTPWebService) FindEnabledHTTPWebConfig(ctx context.Context, req *p
return &pb.FindEnabledHTTPWebConfigResponse{WebJSON: configJSON}, nil
}
// 修改Web配置
// UpdateHTTPWeb 修改Web配置
func (this *HTTPWebService) UpdateHTTPWeb(ctx context.Context, req *pb.UpdateHTTPWebRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -121,7 +121,7 @@ func (this *HTTPWebService) UpdateHTTPWeb(ctx context.Context, req *pb.UpdateHTT
return this.Success()
}
// 修改Gzip配置
// UpdateHTTPWebGzip 修改Gzip配置
func (this *HTTPWebService) UpdateHTTPWebGzip(ctx context.Context, req *pb.UpdateHTTPWebGzipRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -147,7 +147,7 @@ func (this *HTTPWebService) UpdateHTTPWebGzip(ctx context.Context, req *pb.Updat
return this.Success()
}
// 修改字符集配置
// UpdateHTTPWebCharset 修改字符集配置
func (this *HTTPWebService) UpdateHTTPWebCharset(ctx context.Context, req *pb.UpdateHTTPWebCharsetRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -172,7 +172,7 @@ func (this *HTTPWebService) UpdateHTTPWebCharset(ctx context.Context, req *pb.Up
return this.Success()
}
// 更改请求Header策略
// UpdateHTTPWebRequestHeader 更改请求Header策略
func (this *HTTPWebService) UpdateHTTPWebRequestHeader(ctx context.Context, req *pb.UpdateHTTPWebRequestHeaderRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -198,7 +198,7 @@ func (this *HTTPWebService) UpdateHTTPWebRequestHeader(ctx context.Context, req
return this.Success()
}
// 更改响应Header策略
// UpdateHTTPWebResponseHeader 更改响应Header策略
func (this *HTTPWebService) UpdateHTTPWebResponseHeader(ctx context.Context, req *pb.UpdateHTTPWebResponseHeaderRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -224,7 +224,7 @@ func (this *HTTPWebService) UpdateHTTPWebResponseHeader(ctx context.Context, req
return this.Success()
}
// 更改Shutdown
// UpdateHTTPWebShutdown 更改Shutdown
func (this *HTTPWebService) UpdateHTTPWebShutdown(ctx context.Context, req *pb.UpdateHTTPWebShutdownRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -249,7 +249,7 @@ func (this *HTTPWebService) UpdateHTTPWebShutdown(ctx context.Context, req *pb.U
return this.Success()
}
// 更改Pages
// UpdateHTTPWebPages 更改Pages
func (this *HTTPWebService) UpdateHTTPWebPages(ctx context.Context, req *pb.UpdateHTTPWebPagesRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -274,7 +274,7 @@ func (this *HTTPWebService) UpdateHTTPWebPages(ctx context.Context, req *pb.Upda
return this.Success()
}
// 更改访问日志配置
// UpdateHTTPWebAccessLog 更改访问日志配置
func (this *HTTPWebService) UpdateHTTPWebAccessLog(ctx context.Context, req *pb.UpdateHTTPWebAccessLogRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -299,7 +299,7 @@ func (this *HTTPWebService) UpdateHTTPWebAccessLog(ctx context.Context, req *pb.
return this.Success()
}
// 更改统计配置
// UpdateHTTPWebStat 更改统计配置
func (this *HTTPWebService) UpdateHTTPWebStat(ctx context.Context, req *pb.UpdateHTTPWebStatRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -324,7 +324,7 @@ func (this *HTTPWebService) UpdateHTTPWebStat(ctx context.Context, req *pb.Updat
return this.Success()
}
// 更改缓存配置
// UpdateHTTPWebCache 更改缓存配置
func (this *HTTPWebService) UpdateHTTPWebCache(ctx context.Context, req *pb.UpdateHTTPWebCacheRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -350,7 +350,7 @@ func (this *HTTPWebService) UpdateHTTPWebCache(ctx context.Context, req *pb.Upda
return this.Success()
}
// 更改防火墙设置
// UpdateHTTPWebFirewall 更改防火墙设置
func (this *HTTPWebService) UpdateHTTPWebFirewall(ctx context.Context, req *pb.UpdateHTTPWebFirewallRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -376,7 +376,7 @@ func (this *HTTPWebService) UpdateHTTPWebFirewall(ctx context.Context, req *pb.U
return this.Success()
}
// 更改路径规则设置
// UpdateHTTPWebLocations 更改路径规则设置
func (this *HTTPWebService) UpdateHTTPWebLocations(ctx context.Context, req *pb.UpdateHTTPWebLocationsRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -402,7 +402,7 @@ func (this *HTTPWebService) UpdateHTTPWebLocations(ctx context.Context, req *pb.
return this.Success()
}
// 更改跳转到HTTPS设置
// UpdateHTTPWebRedirectToHTTPS 更改跳转到HTTPS设置
func (this *HTTPWebService) UpdateHTTPWebRedirectToHTTPS(ctx context.Context, req *pb.UpdateHTTPWebRedirectToHTTPSRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -427,7 +427,7 @@ func (this *HTTPWebService) UpdateHTTPWebRedirectToHTTPS(ctx context.Context, re
return this.Success()
}
// 更改Websocket设置
// UpdateHTTPWebWebsocket 更改Websocket设置
func (this *HTTPWebService) UpdateHTTPWebWebsocket(ctx context.Context, req *pb.UpdateHTTPWebWebsocketRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -451,7 +451,31 @@ func (this *HTTPWebService) UpdateHTTPWebWebsocket(ctx context.Context, req *pb.
return this.Success()
}
// 更改重写规则设置
// UpdateHTTPWebFastcgi 更改Fastcgi设置
func (this *HTTPWebService) UpdateHTTPWebFastcgi(ctx context.Context, req *pb.UpdateHTTPWebFastcgiRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
if err != nil {
return nil, err
}
if userId > 0 {
err = models.SharedHTTPWebDAO.CheckUserWeb(nil, userId, req.WebId)
if err != nil {
return nil, err
}
}
tx := this.NullTx()
err = models.SharedHTTPWebDAO.UpdateWebFastcgi(tx, req.WebId, req.FastcgiJSON)
if err != nil {
return nil, err
}
return this.Success()
}
// UpdateHTTPWebRewriteRules 更改重写规则设置
func (this *HTTPWebService) UpdateHTTPWebRewriteRules(ctx context.Context, req *pb.UpdateHTTPWebRewriteRulesRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -475,7 +499,7 @@ func (this *HTTPWebService) UpdateHTTPWebRewriteRules(ctx context.Context, req *
return this.Success()
}
// 更改主机跳转设置
// UpdateHTTPWebHostRedirects 更改主机跳转设置
func (this *HTTPWebService) UpdateHTTPWebHostRedirects(ctx context.Context, req *pb.UpdateHTTPWebHostRedirectsRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -515,7 +539,7 @@ func (this *HTTPWebService) UpdateHTTPWebHostRedirects(ctx context.Context, req
return this.Success()
}
// 查找主机跳转设置
// FindHTTPWebHostRedirects 查找主机跳转设置
func (this *HTTPWebService) FindHTTPWebHostRedirects(ctx context.Context, req *pb.FindHTTPWebHostRedirectsRequest) (*pb.FindHTTPWebHostRedirectsResponse, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)

View File

@@ -0,0 +1,28 @@
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package services
import (
"context"
"github.com/TeaOSLab/EdgeAPI/internal/db/models"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
)
// LatestItemService 最近使用的条目服务
type LatestItemService struct {
BaseService
}
// IncreaseLatestItem 记录最近使用的条目
func (this *LatestItemService) IncreaseLatestItem(ctx context.Context, req *pb.IncreaseLatestItemRequest) (*pb.RPCSuccess, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
var tx = this.NullTx()
err = models.SharedLatestItemDAO.IncreaseItemCount(tx, req.ItemType, req.ItemId)
if err != nil {
return nil, err
}
return this.Success()
}

View File

@@ -56,15 +56,15 @@ func (this *MessageReceiverService) UpdateMessageReceivers(ctx context.Context,
return this.Success()
}
// FindAllMessageReceivers 查找接收者
func (this *MessageReceiverService) FindAllMessageReceivers(ctx context.Context, req *pb.FindAllMessageReceiversRequest) (*pb.FindAllMessageReceiversResponse, error) {
// FindAllEnabledMessageReceivers 查找接收者
func (this *MessageReceiverService) FindAllEnabledMessageReceivers(ctx context.Context, req *pb.FindAllEnabledMessageReceiversRequest) (*pb.FindAllEnabledMessageReceiversResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
var tx = this.NullTx()
receivers, err := models.SharedMessageReceiverDAO.FindAllReceivers(tx, models.MessageTaskTarget{
receivers, err := models.SharedMessageReceiverDAO.FindAllEnabledReceivers(tx, models.MessageTaskTarget{
ClusterId: req.NodeClusterId,
NodeId: req.NodeId,
ServerId: req.ServerId,
@@ -152,7 +152,7 @@ func (this *MessageReceiverService) FindAllMessageReceivers(ctx context.Context,
MessageRecipientGroup: pbRecipientGroup,
})
}
return &pb.FindAllMessageReceiversResponse{MessageReceivers: pbReceivers}, nil
return &pb.FindAllEnabledMessageReceiversResponse{MessageReceivers: pbReceivers}, nil
}
// DeleteMessageReceiver 删除接收者
@@ -169,3 +169,22 @@ func (this *MessageReceiverService) DeleteMessageReceiver(ctx context.Context, r
}
return this.Success()
}
// CountAllEnabledMessageReceivers 计算接收者数量
func (this *MessageReceiverService) CountAllEnabledMessageReceivers(ctx context.Context, req *pb.CountAllEnabledMessageReceiversRequest) (*pb.RPCCountResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
var tx = this.NullTx()
count, err := models.SharedMessageReceiverDAO.CountAllEnabledReceivers(tx, models.MessageTaskTarget{
ClusterId: req.NodeClusterId,
NodeId: req.NodeId,
ServerId: req.ServerId,
}, "")
if err != nil {
return nil, err
}
return this.SuccessCount(count)
}

View File

@@ -12,18 +12,19 @@ import (
"github.com/TeaOSLab/EdgeAPI/internal/utils/numberutils"
"github.com/TeaOSLab/EdgeCommon/pkg/configutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/TeaOSLab/EdgeCommon/pkg/serverconfigs/shared"
"github.com/iwind/TeaGo/logs"
"github.com/iwind/TeaGo/types"
stringutil "github.com/iwind/TeaGo/utils/string"
"net"
)
// 边缘节点相关服务
// NodeService 边缘节点相关服务
type NodeService struct {
BaseService
}
// 创建节点
// CreateNode 创建节点
func (this *NodeService) CreateNode(ctx context.Context, req *pb.CreateNodeRequest) (*pb.CreateNodeResponse, error) {
adminId, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -60,7 +61,7 @@ func (this *NodeService) CreateNode(ctx context.Context, req *pb.CreateNodeReque
}, nil
}
// 注册集群节点
// RegisterClusterNode 注册集群节点
func (this *NodeService) RegisterClusterNode(ctx context.Context, req *pb.RegisterClusterNodeRequest) (*pb.RegisterClusterNodeResponse, error) {
// 校验请求
_, clusterId, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeCluster)
@@ -105,7 +106,7 @@ func (this *NodeService) RegisterClusterNode(ctx context.Context, req *pb.Regist
}, nil
}
// 计算节点数量
// CountAllEnabledNodes 计算节点数量
func (this *NodeService) CountAllEnabledNodes(ctx context.Context, req *pb.CountAllEnabledNodesRequest) (*pb.RPCCountResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -123,7 +124,7 @@ func (this *NodeService) CountAllEnabledNodes(ctx context.Context, req *pb.Count
return this.SuccessCount(count)
}
// 计算匹配的节点数量
// CountAllEnabledNodesMatch 计算匹配的节点数量
func (this *NodeService) CountAllEnabledNodesMatch(ctx context.Context, req *pb.CountAllEnabledNodesMatchRequest) (*pb.RPCCountResponse, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
if err != nil {
@@ -139,7 +140,7 @@ func (this *NodeService) CountAllEnabledNodesMatch(ctx context.Context, req *pb.
return this.SuccessCount(count)
}
// 列出单页的节点
// ListEnabledNodesMatch 列出单页的节点
func (this *NodeService) ListEnabledNodesMatch(ctx context.Context, req *pb.ListEnabledNodesMatchRequest) (*pb.ListEnabledNodesMatchResponse, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
if err != nil {
@@ -268,7 +269,7 @@ func (this *NodeService) ListEnabledNodesMatch(ctx context.Context, req *pb.List
}, nil
}
// 查找一个集群下的所有节点
// FindAllEnabledNodesWithClusterId 查找一个集群下的所有节点
func (this *NodeService) FindAllEnabledNodesWithClusterId(ctx context.Context, req *pb.FindAllEnabledNodesWithClusterIdRequest) (*pb.FindAllEnabledNodesWithClusterIdResponse, error) {
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
if err != nil {
@@ -308,7 +309,7 @@ func (this *NodeService) FindAllEnabledNodesWithClusterId(ctx context.Context, r
return &pb.FindAllEnabledNodesWithClusterIdResponse{Nodes: result}, nil
}
// 删除节点
// DeleteNode 删除节点
func (this *NodeService) DeleteNode(ctx context.Context, req *pb.DeleteNodeRequest) (*pb.RPCSuccess, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
if err != nil {
@@ -331,7 +332,7 @@ func (this *NodeService) DeleteNode(ctx context.Context, req *pb.DeleteNodeReque
return this.Success()
}
// 修改节点
// UpdateNode 修改节点
func (this *NodeService) UpdateNode(ctx context.Context, req *pb.UpdateNodeRequest) (*pb.RPCSuccess, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
if err != nil {
@@ -340,7 +341,29 @@ func (this *NodeService) UpdateNode(ctx context.Context, req *pb.UpdateNodeReque
tx := this.NullTx()
err = models.SharedNodeDAO.UpdateNode(tx, req.NodeId, req.Name, req.NodeClusterId, req.GroupId, req.RegionId, req.MaxCPU, req.IsOn)
var maxCacheDiskCapacityJSON []byte
if req.MaxCacheDiskCapacity != nil {
maxCacheDiskCapacityJSON, err = json.Marshal(&shared.SizeCapacity{
Count: req.MaxCacheDiskCapacity.Count,
Unit: req.MaxCacheDiskCapacity.Unit,
})
if err != nil {
return nil, err
}
}
var maxCacheMemoryCapacityJSON []byte
if req.MaxCacheMemoryCapacity != nil {
maxCacheMemoryCapacityJSON, err = json.Marshal(&shared.SizeCapacity{
Count: req.MaxCacheMemoryCapacity.Count,
Unit: req.MaxCacheMemoryCapacity.Unit,
})
if err != nil {
return nil, err
}
}
err = models.SharedNodeDAO.UpdateNode(tx, req.NodeId, req.Name, req.NodeClusterId, req.GroupId, req.RegionId, req.MaxCPU, req.IsOn, maxCacheDiskCapacityJSON, maxCacheMemoryCapacityJSON)
if err != nil {
return nil, err
}
@@ -377,7 +400,7 @@ func (this *NodeService) UpdateNode(ctx context.Context, req *pb.UpdateNodeReque
return this.Success()
}
// 列出单个节点
// FindEnabledNode 列出单个节点
func (this *NodeService) FindEnabledNode(ctx context.Context, req *pb.FindEnabledNodeRequest) (*pb.FindEnabledNodeResponse, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
if err != nil {
@@ -463,6 +486,26 @@ func (this *NodeService) FindEnabledNode(ctx context.Context, req *pb.FindEnable
}
}
// 最大硬盘容量
var pbMaxCacheDiskCapacity *pb.SizeCapacity
if len(node.MaxCacheDiskCapacity) > 0 {
pbMaxCacheDiskCapacity = &pb.SizeCapacity{}
err = json.Unmarshal([]byte(node.MaxCacheDiskCapacity), pbMaxCacheDiskCapacity)
if err != nil {
return nil, err
}
}
// 最大内存容量
var pbMaxCacheMemoryCapacity *pb.SizeCapacity
if len(node.MaxCacheMemoryCapacity) > 0 {
pbMaxCacheMemoryCapacity = &pb.SizeCapacity{}
err = json.Unmarshal([]byte(node.MaxCacheMemoryCapacity), pbMaxCacheMemoryCapacity)
if err != nil {
return nil, err
}
}
return &pb.FindEnabledNodeResponse{Node: &pb.Node{
Id: int64(node.Id),
Name: node.Name,
@@ -477,16 +520,18 @@ func (this *NodeService) FindEnabledNode(ctx context.Context, req *pb.FindEnable
Id: int64(node.ClusterId),
Name: clusterName,
},
Login: respLogin,
InstallStatus: installStatusResult,
MaxCPU: types.Int32(node.MaxCPU),
IsOn: node.IsOn == 1,
Group: pbGroup,
Region: pbRegion,
Login: respLogin,
InstallStatus: installStatusResult,
MaxCPU: types.Int32(node.MaxCPU),
IsOn: node.IsOn == 1,
Group: pbGroup,
Region: pbRegion,
MaxCacheDiskCapacity: pbMaxCacheDiskCapacity,
MaxCacheMemoryCapacity: pbMaxCacheMemoryCapacity,
}}, nil
}
// 组合节点配置
// FindCurrentNodeConfig 组合节点配置
func (this *NodeService) FindCurrentNodeConfig(ctx context.Context, req *pb.FindCurrentNodeConfigRequest) (*pb.FindCurrentNodeConfigResponse, error) {
_ = req
@@ -520,7 +565,7 @@ func (this *NodeService) FindCurrentNodeConfig(ctx context.Context, req *pb.Find
return &pb.FindCurrentNodeConfigResponse{IsChanged: true, NodeJSON: data}, nil
}
// 更新节点状态
// UpdateNodeStatus 更新节点状态
func (this *NodeService) UpdateNodeStatus(ctx context.Context, req *pb.UpdateNodeStatusRequest) (*pb.RPCSuccess, error) {
// 校验节点
_, nodeId, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeNode)
@@ -545,7 +590,7 @@ func (this *NodeService) UpdateNodeStatus(ctx context.Context, req *pb.UpdateNod
return this.Success()
}
// 修改节点安装状态
// UpdateNodeIsInstalled 修改节点安装状态
func (this *NodeService) UpdateNodeIsInstalled(ctx context.Context, req *pb.UpdateNodeIsInstalledRequest) (*pb.RPCSuccess, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
if err != nil {
@@ -562,7 +607,7 @@ func (this *NodeService) UpdateNodeIsInstalled(ctx context.Context, req *pb.Upda
return this.Success()
}
// 安装节点
// InstallNode 安装节点
func (this *NodeService) InstallNode(ctx context.Context, req *pb.InstallNodeRequest) (*pb.InstallNodeResponse, error) {
// 校验节点
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -580,7 +625,7 @@ func (this *NodeService) InstallNode(ctx context.Context, req *pb.InstallNodeReq
return &pb.InstallNodeResponse{}, nil
}
// 升级节点
// UpgradeNode 升级节点
func (this *NodeService) UpgradeNode(ctx context.Context, req *pb.UpgradeNodeRequest) (*pb.UpgradeNodeResponse, error) {
// 校验节点
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -620,7 +665,7 @@ func (this *NodeService) UpgradeNode(ctx context.Context, req *pb.UpgradeNodeReq
return &pb.UpgradeNodeResponse{}, nil
}
// 启动节点
// StartNode 启动节点
func (this *NodeService) StartNode(ctx context.Context, req *pb.StartNodeRequest) (*pb.StartNodeResponse, error) {
// 校验节点
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -639,7 +684,7 @@ func (this *NodeService) StartNode(ctx context.Context, req *pb.StartNodeRequest
return &pb.StartNodeResponse{IsOk: true}, nil
}
// 停止节点
// StopNode 停止节点
func (this *NodeService) StopNode(ctx context.Context, req *pb.StopNodeRequest) (*pb.StopNodeResponse, error) {
// 校验节点
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -658,7 +703,7 @@ func (this *NodeService) StopNode(ctx context.Context, req *pb.StopNodeRequest)
return &pb.StopNodeResponse{IsOk: true}, nil
}
// 更改节点连接的API节点信息
// UpdateNodeConnectedAPINodes 更改节点连接的API节点信息
func (this *NodeService) UpdateNodeConnectedAPINodes(ctx context.Context, req *pb.UpdateNodeConnectedAPINodesRequest) (*pb.RPCSuccess, error) {
// 校验节点
_, nodeId, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeNode)
@@ -676,7 +721,7 @@ func (this *NodeService) UpdateNodeConnectedAPINodes(ctx context.Context, req *p
return this.Success()
}
// 计算使用某个认证的节点数量
// CountAllEnabledNodesWithGrantId 计算使用某个认证的节点数量
func (this *NodeService) CountAllEnabledNodesWithGrantId(ctx context.Context, req *pb.CountAllEnabledNodesWithGrantIdRequest) (*pb.RPCCountResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -693,7 +738,7 @@ func (this *NodeService) CountAllEnabledNodesWithGrantId(ctx context.Context, re
return this.SuccessCount(count)
}
// 查找使用某个认证的所有节点
// FindAllEnabledNodesWithGrantId 查找使用某个认证的所有节点
func (this *NodeService) FindAllEnabledNodesWithGrantId(ctx context.Context, req *pb.FindAllEnabledNodesWithGrantIdRequest) (*pb.FindAllEnabledNodesWithGrantIdResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -733,7 +778,7 @@ func (this *NodeService) FindAllEnabledNodesWithGrantId(ctx context.Context, req
return &pb.FindAllEnabledNodesWithGrantIdResponse{Nodes: result}, nil
}
// 计算没有安装的节点数量
// CountAllNotInstalledNodesWithClusterId 计算没有安装的节点数量
func (this *NodeService) CountAllNotInstalledNodesWithClusterId(ctx context.Context, req *pb.CountAllNotInstalledNodesWithClusterIdRequest) (*pb.RPCCountResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -747,7 +792,7 @@ func (this *NodeService) CountAllNotInstalledNodesWithClusterId(ctx context.Cont
return this.SuccessCount(count)
}
// 列出所有未安装的节点
// FindAllNotInstalledNodesWithClusterId 列出所有未安装的节点
func (this *NodeService) FindAllNotInstalledNodesWithClusterId(ctx context.Context, req *pb.FindAllNotInstalledNodesWithClusterIdRequest) (*pb.FindAllNotInstalledNodesWithClusterIdResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -829,7 +874,7 @@ func (this *NodeService) FindAllNotInstalledNodesWithClusterId(ctx context.Conte
return &pb.FindAllNotInstalledNodesWithClusterIdResponse{Nodes: result}, nil
}
// 计算需要升级的节点数量
// CountAllUpgradeNodesWithClusterId 计算需要升级的节点数量
func (this *NodeService) CountAllUpgradeNodesWithClusterId(ctx context.Context, req *pb.CountAllUpgradeNodesWithClusterIdRequest) (*pb.RPCCountResponse, error) {
// 校验请求
_, err := this.ValidateAdmin(ctx, 0)
@@ -852,7 +897,7 @@ func (this *NodeService) CountAllUpgradeNodesWithClusterId(ctx context.Context,
return this.SuccessCount(total)
}
// 列出所有需要升级的节点
// FindAllUpgradeNodesWithClusterId 列出所有需要升级的节点
func (this *NodeService) FindAllUpgradeNodesWithClusterId(ctx context.Context, req *pb.FindAllUpgradeNodesWithClusterIdRequest) (*pb.FindAllUpgradeNodesWithClusterIdResponse, error) {
// 校验请求
_, err := this.ValidateAdmin(ctx, 0)
@@ -958,7 +1003,7 @@ func (this *NodeService) FindAllUpgradeNodesWithClusterId(ctx context.Context, r
}, nil
}
// 读取节点安装状态
// FindNodeInstallStatus 读取节点安装状态
func (this *NodeService) FindNodeInstallStatus(ctx context.Context, req *pb.FindNodeInstallStatusRequest) (*pb.FindNodeInstallStatusResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -987,7 +1032,7 @@ func (this *NodeService) FindNodeInstallStatus(ctx context.Context, req *pb.Find
return &pb.FindNodeInstallStatusResponse{InstallStatus: pbInstallStatus}, nil
}
// 修改节点登录信息
// UpdateNodeLogin 修改节点登录信息
func (this *NodeService) UpdateNodeLogin(ctx context.Context, req *pb.UpdateNodeLoginRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -1026,7 +1071,7 @@ func (this *NodeService) CountAllEnabledNodesWithNodeGroupId(ctx context.Context
return this.SuccessCount(count)
}
// 取得某个集群下的所有节点
// FindAllEnabledNodesDNSWithClusterId 取得某个集群下的所有节点
func (this *NodeService) FindAllEnabledNodesDNSWithClusterId(ctx context.Context, req *pb.FindAllEnabledNodesDNSWithClusterIdRequest) (*pb.FindAllEnabledNodesDNSWithClusterIdResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -1098,7 +1143,7 @@ func (this *NodeService) FindAllEnabledNodesDNSWithClusterId(ctx context.Context
return &pb.FindAllEnabledNodesDNSWithClusterIdResponse{Nodes: result}, nil
}
// 查找单个节点的域名解析信息
// FindEnabledNodeDNS 查找单个节点的域名解析信息
func (this *NodeService) FindEnabledNodeDNS(ctx context.Context, req *pb.FindEnabledNodeDNSRequest) (*pb.FindEnabledNodeDNSResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -1170,7 +1215,7 @@ func (this *NodeService) FindEnabledNodeDNS(ctx context.Context, req *pb.FindEna
}, nil
}
// 修改节点的DNS解析信息
// UpdateNodeDNS 修改节点的DNS解析信息
func (this *NodeService) UpdateNodeDNS(ctx context.Context, req *pb.UpdateNodeDNSRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -1224,7 +1269,7 @@ func (this *NodeService) UpdateNodeDNS(ctx context.Context, req *pb.UpdateNodeDN
return this.Success()
}
// 计算某个区域下的节点数量
// CountAllEnabledNodesWithNodeRegionId 计算某个区域下的节点数量
func (this *NodeService) CountAllEnabledNodesWithNodeRegionId(ctx context.Context, req *pb.CountAllEnabledNodesWithNodeRegionIdRequest) (*pb.RPCCountResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -1240,7 +1285,7 @@ func (this *NodeService) CountAllEnabledNodesWithNodeRegionId(ctx context.Contex
return this.SuccessCount(count)
}
// 根据一组ID获取节点信息
// FindEnabledNodesWithIds 根据一组ID获取节点信息
func (this *NodeService) FindEnabledNodesWithIds(ctx context.Context, req *pb.FindEnabledNodesWithIdsRequest) (*pb.FindEnabledNodesWithIdsResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -1269,7 +1314,7 @@ func (this *NodeService) FindEnabledNodesWithIds(ctx context.Context, req *pb.Fi
return &pb.FindEnabledNodesWithIdsResponse{Nodes: pbNodes}, nil
}
// 检查新版本
// CheckNodeLatestVersion 检查新版本
func (this *NodeService) CheckNodeLatestVersion(ctx context.Context, req *pb.CheckNodeLatestVersionRequest) (*pb.CheckNodeLatestVersionResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -1288,7 +1333,7 @@ func (this *NodeService) CheckNodeLatestVersion(ctx context.Context, req *pb.Che
return &pb.CheckNodeLatestVersionResponse{HasNewVersion: false}, nil
}
// 设置节点上线状态
// UpdateNodeUp 设置节点上线状态
func (this *NodeService) UpdateNodeUp(ctx context.Context, req *pb.UpdateNodeUpRequest) (*pb.RPCSuccess, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {

View File

@@ -22,7 +22,7 @@ type NodeClusterService struct {
BaseService
}
// 创建集群
// CreateNodeCluster 创建集群
func (this *NodeClusterService) CreateNodeCluster(ctx context.Context, req *pb.CreateNodeClusterRequest) (*pb.CreateNodeClusterResponse, error) {
adminId, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -53,7 +53,7 @@ func (this *NodeClusterService) CreateNodeCluster(ctx context.Context, req *pb.C
return &pb.CreateNodeClusterResponse{NodeClusterId: clusterId}, nil
}
// 修改集群
// UpdateNodeCluster 修改集群
func (this *NodeClusterService) UpdateNodeCluster(ctx context.Context, req *pb.UpdateNodeClusterRequest) (*pb.RPCSuccess, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
if err != nil {
@@ -70,7 +70,7 @@ func (this *NodeClusterService) UpdateNodeCluster(ctx context.Context, req *pb.U
return this.Success()
}
// 禁用集群
// DeleteNodeCluster 禁用集群
func (this *NodeClusterService) DeleteNodeCluster(ctx context.Context, req *pb.DeleteNodeClusterRequest) (*pb.RPCSuccess, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
if err != nil {
@@ -93,7 +93,7 @@ func (this *NodeClusterService) DeleteNodeCluster(ctx context.Context, req *pb.D
return this.Success()
}
// 查找单个集群
// FindEnabledNodeCluster 查找单个集群
func (this *NodeClusterService) FindEnabledNodeCluster(ctx context.Context, req *pb.FindEnabledNodeClusterRequest) (*pb.FindEnabledNodeClusterResponse, error) {
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
if err != nil {
@@ -130,7 +130,7 @@ func (this *NodeClusterService) FindEnabledNodeCluster(ctx context.Context, req
}}, nil
}
// 查找集群的API节点信息
// FindAPINodesWithNodeCluster 查找集群的API节点信息
func (this *NodeClusterService) FindAPINodesWithNodeCluster(ctx context.Context, req *pb.FindAPINodesWithNodeClusterRequest) (*pb.FindAPINodesWithNodeClusterResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -184,7 +184,7 @@ func (this *NodeClusterService) FindAPINodesWithNodeCluster(ctx context.Context,
return result, nil
}
// 查找所有可用的集群
// FindAllEnabledNodeClusters 查找所有可用的集群
func (this *NodeClusterService) FindAllEnabledNodeClusters(ctx context.Context, req *pb.FindAllEnabledNodeClustersRequest) (*pb.FindAllEnabledNodeClustersResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -215,7 +215,7 @@ func (this *NodeClusterService) FindAllEnabledNodeClusters(ctx context.Context,
}, nil
}
// 计算所有集群数量
// CountAllEnabledNodeClusters 计算所有集群数量
func (this *NodeClusterService) CountAllEnabledNodeClusters(ctx context.Context, req *pb.CountAllEnabledNodeClustersRequest) (*pb.RPCCountResponse, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
if err != nil {
@@ -232,7 +232,7 @@ func (this *NodeClusterService) CountAllEnabledNodeClusters(ctx context.Context,
return this.SuccessCount(count)
}
// 列出单页集群
// ListEnabledNodeClusters 列出单页集群
func (this *NodeClusterService) ListEnabledNodeClusters(ctx context.Context, req *pb.ListEnabledNodeClustersRequest) (*pb.ListEnabledNodeClustersResponse, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
if err != nil {
@@ -264,7 +264,7 @@ func (this *NodeClusterService) ListEnabledNodeClusters(ctx context.Context, req
return &pb.ListEnabledNodeClustersResponse{NodeClusters: result}, nil
}
// 查找集群的健康检查配置
// FindNodeClusterHealthCheckConfig 查找集群的健康检查配置
func (this *NodeClusterService) FindNodeClusterHealthCheckConfig(ctx context.Context, req *pb.FindNodeClusterHealthCheckConfigRequest) (*pb.FindNodeClusterHealthCheckConfigResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -285,7 +285,7 @@ func (this *NodeClusterService) FindNodeClusterHealthCheckConfig(ctx context.Con
return &pb.FindNodeClusterHealthCheckConfigResponse{HealthCheckJSON: configJSON}, nil
}
// 修改集群健康检查设置
// UpdateNodeClusterHealthCheck 修改集群健康检查设置
func (this *NodeClusterService) UpdateNodeClusterHealthCheck(ctx context.Context, req *pb.UpdateNodeClusterHealthCheckRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -302,7 +302,7 @@ func (this *NodeClusterService) UpdateNodeClusterHealthCheck(ctx context.Context
return this.Success()
}
// 执行健康检查
// ExecuteNodeClusterHealthCheck 执行健康检查
func (this *NodeClusterService) ExecuteNodeClusterHealthCheck(ctx context.Context, req *pb.ExecuteNodeClusterHealthCheckRequest) (*pb.ExecuteNodeClusterHealthCheckResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -331,7 +331,7 @@ func (this *NodeClusterService) ExecuteNodeClusterHealthCheck(ctx context.Contex
return &pb.ExecuteNodeClusterHealthCheckResponse{Results: pbResults}, nil
}
// 计算使用某个认证的集群数量
// CountAllEnabledNodeClustersWithGrantId 计算使用某个认证的集群数量
func (this *NodeClusterService) CountAllEnabledNodeClustersWithGrantId(ctx context.Context, req *pb.CountAllEnabledNodeClustersWithGrantIdRequest) (*pb.RPCCountResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -348,7 +348,7 @@ func (this *NodeClusterService) CountAllEnabledNodeClustersWithGrantId(ctx conte
return this.SuccessCount(count)
}
// 查找使用某个认证的所有集群
// FindAllEnabledNodeClustersWithGrantId 查找使用某个认证的所有集群
func (this *NodeClusterService) FindAllEnabledNodeClustersWithGrantId(ctx context.Context, req *pb.FindAllEnabledNodeClustersWithGrantIdRequest) (*pb.FindAllEnabledNodeClustersWithGrantIdResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -376,7 +376,7 @@ func (this *NodeClusterService) FindAllEnabledNodeClustersWithGrantId(ctx contex
return &pb.FindAllEnabledNodeClustersWithGrantIdResponse{NodeClusters: result}, nil
}
// 查找集群的DNS配置
// FindEnabledNodeClusterDNS 查找集群的DNS配置
func (this *NodeClusterService) FindEnabledNodeClusterDNS(ctx context.Context, req *pb.FindEnabledNodeClusterDNSRequest) (*pb.FindEnabledNodeClusterDNSResponse, error) {
// 校验请求
_, _, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -454,7 +454,7 @@ func (this *NodeClusterService) FindEnabledNodeClusterDNS(ctx context.Context, r
}, nil
}
// 计算使用某个DNS服务商的集群数量
// CountAllEnabledNodeClustersWithDNSProviderId 计算使用某个DNS服务商的集群数量
func (this *NodeClusterService) CountAllEnabledNodeClustersWithDNSProviderId(ctx context.Context, req *pb.CountAllEnabledNodeClustersWithDNSProviderIdRequest) (*pb.RPCCountResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -471,7 +471,7 @@ func (this *NodeClusterService) CountAllEnabledNodeClustersWithDNSProviderId(ctx
return this.SuccessCount(count)
}
// 计算使用某个DNS域名的集群数量
// CountAllEnabledNodeClustersWithDNSDomainId 计算使用某个DNS域名的集群数量
func (this *NodeClusterService) CountAllEnabledNodeClustersWithDNSDomainId(ctx context.Context, req *pb.CountAllEnabledNodeClustersWithDNSDomainIdRequest) (*pb.RPCCountResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -488,7 +488,7 @@ func (this *NodeClusterService) CountAllEnabledNodeClustersWithDNSDomainId(ctx c
return this.SuccessCount(count)
}
// 查找使用某个域名的所有集群
// FindAllEnabledNodeClustersWithDNSDomainId 查找使用某个域名的所有集群
func (this *NodeClusterService) FindAllEnabledNodeClustersWithDNSDomainId(ctx context.Context, req *pb.FindAllEnabledNodeClustersWithDNSDomainIdRequest) (*pb.FindAllEnabledNodeClustersWithDNSDomainIdResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -515,7 +515,7 @@ func (this *NodeClusterService) FindAllEnabledNodeClustersWithDNSDomainId(ctx co
return &pb.FindAllEnabledNodeClustersWithDNSDomainIdResponse{NodeClusters: result}, nil
}
// 检查集群域名是否已经被使用
// CheckNodeClusterDNSName 检查集群域名是否已经被使用
func (this *NodeClusterService) CheckNodeClusterDNSName(ctx context.Context, req *pb.CheckNodeClusterDNSNameRequest) (*pb.CheckNodeClusterDNSNameResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -532,7 +532,7 @@ func (this *NodeClusterService) CheckNodeClusterDNSName(ctx context.Context, req
return &pb.CheckNodeClusterDNSNameResponse{IsUsed: exists}, nil
}
// 修改集群的域名设置
// UpdateNodeClusterDNS 修改集群的域名设置
func (this *NodeClusterService) UpdateNodeClusterDNS(ctx context.Context, req *pb.UpdateNodeClusterDNSRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -549,7 +549,7 @@ func (this *NodeClusterService) UpdateNodeClusterDNS(ctx context.Context, req *p
return this.Success()
}
// 检查集群的DNS是否有变化
// CheckNodeClusterDNSChanges 检查集群的DNS是否有变化
func (this *NodeClusterService) CheckNodeClusterDNSChanges(ctx context.Context, req *pb.CheckNodeClusterDNSChangesRequest) (*pb.CheckNodeClusterDNSChangesResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -590,7 +590,7 @@ func (this *NodeClusterService) CheckNodeClusterDNSChanges(ctx context.Context,
return &pb.CheckNodeClusterDNSChangesResponse{IsChanged: len(changes) > 0}, nil
}
// 查找集群的TOA配置
// FindEnabledNodeClusterTOA 查找集群的TOA配置
func (this *NodeClusterService) FindEnabledNodeClusterTOA(ctx context.Context, req *pb.FindEnabledNodeClusterTOARequest) (*pb.FindEnabledNodeClusterTOAResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -612,7 +612,7 @@ func (this *NodeClusterService) FindEnabledNodeClusterTOA(ctx context.Context, r
return &pb.FindEnabledNodeClusterTOAResponse{ToaJSON: configJSON}, nil
}
// 修改集群的TOA设置
// UpdateNodeClusterTOA 修改集群的TOA设置
func (this *NodeClusterService) UpdateNodeClusterTOA(ctx context.Context, req *pb.UpdateNodeClusterTOARequest) (*pb.RPCSuccess, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -631,7 +631,7 @@ func (this *NodeClusterService) UpdateNodeClusterTOA(ctx context.Context, req *p
return this.Success()
}
// 计算使用某个缓存策略的集群数量
// CountAllEnabledNodeClustersWithHTTPCachePolicyId 计算使用某个缓存策略的集群数量
func (this *NodeClusterService) CountAllEnabledNodeClustersWithHTTPCachePolicyId(ctx context.Context, req *pb.CountAllEnabledNodeClustersWithHTTPCachePolicyIdRequest) (*pb.RPCCountResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -647,7 +647,7 @@ func (this *NodeClusterService) CountAllEnabledNodeClustersWithHTTPCachePolicyId
return this.SuccessCount(count)
}
// 查找使用缓存策略的所有集群
// FindAllEnabledNodeClustersWithHTTPCachePolicyId 查找使用缓存策略的所有集群
func (this *NodeClusterService) FindAllEnabledNodeClustersWithHTTPCachePolicyId(ctx context.Context, req *pb.FindAllEnabledNodeClustersWithHTTPCachePolicyIdRequest) (*pb.FindAllEnabledNodeClustersWithHTTPCachePolicyIdResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -672,7 +672,7 @@ func (this *NodeClusterService) FindAllEnabledNodeClustersWithHTTPCachePolicyId(
}, nil
}
// 计算使用某个WAF策略的集群数量
// CountAllEnabledNodeClustersWithHTTPFirewallPolicyId 计算使用某个WAF策略的集群数量
func (this *NodeClusterService) CountAllEnabledNodeClustersWithHTTPFirewallPolicyId(ctx context.Context, req *pb.CountAllEnabledNodeClustersWithHTTPFirewallPolicyIdRequest) (*pb.RPCCountResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -688,7 +688,7 @@ func (this *NodeClusterService) CountAllEnabledNodeClustersWithHTTPFirewallPolic
return this.SuccessCount(count)
}
// 查找使用WAF策略的所有集群
// FindAllEnabledNodeClustersWithHTTPFirewallPolicyId 查找使用WAF策略的所有集群
func (this *NodeClusterService) FindAllEnabledNodeClustersWithHTTPFirewallPolicyId(ctx context.Context, req *pb.FindAllEnabledNodeClustersWithHTTPFirewallPolicyIdRequest) (*pb.FindAllEnabledNodeClustersWithHTTPFirewallPolicyIdResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -713,7 +713,7 @@ func (this *NodeClusterService) FindAllEnabledNodeClustersWithHTTPFirewallPolicy
}, nil
}
// 修改集群的缓存策略
// UpdateNodeClusterHTTPCachePolicyId 修改集群的缓存策略
func (this *NodeClusterService) UpdateNodeClusterHTTPCachePolicyId(ctx context.Context, req *pb.UpdateNodeClusterHTTPCachePolicyIdRequest) (*pb.RPCSuccess, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -730,7 +730,7 @@ func (this *NodeClusterService) UpdateNodeClusterHTTPCachePolicyId(ctx context.C
return this.Success()
}
// 修改集群的WAF策略
// UpdateNodeClusterHTTPFirewallPolicyId 修改集群的WAF策略
func (this *NodeClusterService) UpdateNodeClusterHTTPFirewallPolicyId(ctx context.Context, req *pb.UpdateNodeClusterHTTPFirewallPolicyIdRequest) (*pb.RPCSuccess, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -747,7 +747,7 @@ func (this *NodeClusterService) UpdateNodeClusterHTTPFirewallPolicyId(ctx contex
return this.Success()
}
// 修改集群的系统服务设置
// UpdateNodeClusterSystemService 修改集群的系统服务设置
func (this *NodeClusterService) UpdateNodeClusterSystemService(ctx context.Context, req *pb.UpdateNodeClusterSystemServiceRequest) (*pb.RPCSuccess, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -771,7 +771,7 @@ func (this *NodeClusterService) UpdateNodeClusterSystemService(ctx context.Conte
return this.Success()
}
// 查找集群的系统服务设置
// FindNodeClusterSystemService 查找集群的系统服务设置
func (this *NodeClusterService) FindNodeClusterSystemService(ctx context.Context, req *pb.FindNodeClusterSystemServiceRequest) (*pb.FindNodeClusterSystemServiceResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -793,7 +793,7 @@ func (this *NodeClusterService) FindNodeClusterSystemService(ctx context.Context
return &pb.FindNodeClusterSystemServiceResponse{ParamsJSON: paramsJSON}, nil
}
// 获取集群中可以使用的端口
// FindFreePortInNodeCluster 获取集群中可以使用的端口
func (this *NodeClusterService) FindFreePortInNodeCluster(ctx context.Context, req *pb.FindFreePortInNodeClusterRequest) (*pb.FindFreePortInNodeClusterResponse, error) {
_, _, err := this.ValidateAdminAndUser(ctx, 0, 0)
if err != nil {
@@ -851,7 +851,7 @@ func (this *NodeClusterService) FindFreePortInNodeCluster(ctx context.Context, r
return nil, errors.New("can not find random port")
}
// 检查端口是否已经被使用
// CheckPortIsUsingInNodeCluster 检查端口是否已经被使用
func (this *NodeClusterService) CheckPortIsUsingInNodeCluster(ctx context.Context, req *pb.CheckPortIsUsingInNodeClusterRequest) (*pb.CheckPortIsUsingInNodeClusterResponse, error) {
_, _, err := this.ValidateAdminAndUser(ctx, 0, 0)
if err != nil {
@@ -865,3 +865,25 @@ func (this *NodeClusterService) CheckPortIsUsingInNodeCluster(ctx context.Contex
}
return &pb.CheckPortIsUsingInNodeClusterResponse{IsUsing: isUsing}, nil
}
// FindLatestNodeClusters 查找最近访问的集群
func (this *NodeClusterService) FindLatestNodeClusters(ctx context.Context, req *pb.FindLatestNodeClustersRequest) (*pb.FindLatestNodeClustersResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
var tx = this.NullTx()
clusters, err := models.SharedNodeClusterDAO.FindLatestNodeClusters(tx, req.Size)
if err != nil {
return nil, err
}
pbClusters := []*pb.NodeCluster{}
for _, cluster := range clusters {
pbClusters = append(pbClusters, &pb.NodeCluster{
Id: int64(cluster.Id),
Name: cluster.Name,
})
}
return &pb.FindLatestNodeClustersResponse{NodeClusters: pbClusters}, nil
}

View File

@@ -3,15 +3,20 @@ package services
import (
"context"
"errors"
"fmt"
"github.com/TeaOSLab/EdgeAPI/internal/db/models"
rpcutils "github.com/TeaOSLab/EdgeAPI/internal/rpc/utils"
"github.com/TeaOSLab/EdgeAPI/internal/utils/numberutils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"golang.org/x/crypto/ssh"
"net"
"time"
)
type NodeGrantService struct {
BaseService
}
// CreateNodeGrant 创建认证
func (this *NodeGrantService) CreateNodeGrant(ctx context.Context, req *pb.CreateNodeGrantRequest) (*pb.CreateNodeGrantResponse, error) {
adminId, err := this.ValidateAdmin(ctx, 0)
if err != nil {
@@ -25,40 +30,43 @@ func (this *NodeGrantService) CreateNodeGrant(ctx context.Context, req *pb.Creat
return nil, err
}
return &pb.CreateNodeGrantResponse{
GrantId: grantId,
NodeGrantId: grantId,
}, err
}
// UpdateNodeGrant 修改认证
func (this *NodeGrantService) UpdateNodeGrant(ctx context.Context, req *pb.UpdateNodeGrantRequest) (*pb.RPCSuccess, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
if req.GrantId <= 0 {
if req.NodeGrantId <= 0 {
return nil, errors.New("wrong grantId")
}
tx := this.NullTx()
err = models.SharedNodeGrantDAO.UpdateGrant(tx, req.GrantId, req.Name, req.Method, req.Username, req.Password, req.PrivateKey, req.Description, req.NodeId)
err = models.SharedNodeGrantDAO.UpdateGrant(tx, req.NodeGrantId, req.Name, req.Method, req.Username, req.Password, req.PrivateKey, req.Description, req.NodeId)
return this.Success()
}
// DisableNodeGrant 禁用认证
func (this *NodeGrantService) DisableNodeGrant(ctx context.Context, req *pb.DisableNodeGrantRequest) (*pb.DisableNodeGrantResponse, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
tx := this.NullTx()
err = models.SharedNodeGrantDAO.DisableNodeGrant(tx, req.GrantId)
err = models.SharedNodeGrantDAO.DisableNodeGrant(tx, req.NodeGrantId)
return &pb.DisableNodeGrantResponse{}, err
}
// CountAllEnabledNodeGrants 计算认证的数量
func (this *NodeGrantService) CountAllEnabledNodeGrants(ctx context.Context, req *pb.CountAllEnabledNodeGrantsRequest) (*pb.RPCCountResponse, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
@@ -72,8 +80,9 @@ func (this *NodeGrantService) CountAllEnabledNodeGrants(ctx context.Context, req
return this.SuccessCount(count)
}
// ListEnabledNodeGrants 列出单页认证
func (this *NodeGrantService) ListEnabledNodeGrants(ctx context.Context, req *pb.ListEnabledNodeGrantsRequest) (*pb.ListEnabledNodeGrantsResponse, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
@@ -98,12 +107,12 @@ func (this *NodeGrantService) ListEnabledNodeGrants(ctx context.Context, req *pb
})
}
return &pb.ListEnabledNodeGrantsResponse{Grants: result}, nil
return &pb.ListEnabledNodeGrantsResponse{NodeGrants: result}, nil
}
// 列出所有认证信息
// FindAllEnabledNodeGrants 列出所有认证信息
func (this *NodeGrantService) FindAllEnabledNodeGrants(ctx context.Context, req *pb.FindAllEnabledNodeGrantsRequest) (*pb.FindAllEnabledNodeGrantsResponse, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
@@ -125,23 +134,24 @@ func (this *NodeGrantService) FindAllEnabledNodeGrants(ctx context.Context, req
})
}
return &pb.FindAllEnabledNodeGrantsResponse{Grants: result}, nil
return &pb.FindAllEnabledNodeGrantsResponse{NodeGrants: result}, nil
}
func (this *NodeGrantService) FindEnabledGrant(ctx context.Context, req *pb.FindEnabledGrantRequest) (*pb.FindEnabledGrantResponse, error) {
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
// FindEnabledNodeGrant 获取单个认证信息
func (this *NodeGrantService) FindEnabledNodeGrant(ctx context.Context, req *pb.FindEnabledNodeGrantRequest) (*pb.FindEnabledNodeGrantResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
grant, err := models.SharedNodeGrantDAO.FindEnabledNodeGrant(this.NullTx(), req.GrantId)
grant, err := models.SharedNodeGrantDAO.FindEnabledNodeGrant(this.NullTx(), req.NodeGrantId)
if err != nil {
return nil, err
}
if grant == nil {
return &pb.FindEnabledGrantResponse{}, nil
return &pb.FindEnabledNodeGrantResponse{}, nil
}
return &pb.FindEnabledGrantResponse{Grant: &pb.NodeGrant{
return &pb.FindEnabledNodeGrantResponse{NodeGrant: &pb.NodeGrant{
Id: int64(grant.Id),
Name: grant.Name,
Method: grant.Method,
@@ -153,3 +163,97 @@ func (this *NodeGrantService) FindEnabledGrant(ctx context.Context, req *pb.Find
NodeId: int64(grant.NodeId),
}}, nil
}
// TestNodeGrant 测试连接
func (this *NodeGrantService) TestNodeGrant(ctx context.Context, req *pb.TestNodeGrantRequest) (*pb.TestNodeGrantResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
var hostKeyCallback ssh.HostKeyCallback = nil
resp := &pb.TestNodeGrantResponse{
IsOk: false,
Error: "",
}
var tx = this.NullTx()
grant, err := models.SharedNodeGrantDAO.FindEnabledNodeGrant(tx, req.NodeGrantId)
if err != nil {
return nil, err
}
if grant == nil {
resp.Error = "can not find grant with id '" + numberutils.FormatInt64(req.NodeGrantId) + "'"
return resp, nil
}
// 检查参数
if len(req.Host) == 0 {
resp.Error = "'host' should not be empty"
return resp, nil
}
if req.Port <= 0 {
resp.Error = "'port' should be greater than 0"
return resp, nil
}
if len(grant.Password) == 0 && len(grant.PrivateKey) == 0 {
resp.Error = "require user 'password' or 'privateKey'"
return resp, nil
}
// 不使用known_hosts
if hostKeyCallback == nil {
hostKeyCallback = func(hostname string, remote net.Addr, key ssh.PublicKey) error {
return nil
}
}
// 认证
methods := []ssh.AuthMethod{}
if len(grant.Password) > 0 {
{
authMethod := ssh.Password(grant.Password)
methods = append(methods, authMethod)
}
{
authMethod := ssh.KeyboardInteractive(func(user, instruction string, questions []string, echos []bool) (answers []string, err error) {
if len(questions) == 0 {
return []string{}, nil
}
return []string{grant.Password}, nil
})
methods = append(methods, authMethod)
}
} else {
signer, err := ssh.ParsePrivateKey([]byte(grant.PrivateKey))
if err != nil {
resp.Error = "parse private key: " + err.Error()
return resp, nil
}
authMethod := ssh.PublicKeys(signer)
methods = append(methods, authMethod)
}
// SSH客户端
config := &ssh.ClientConfig{
User: grant.Username,
Auth: methods,
HostKeyCallback: hostKeyCallback,
Timeout: 5 * time.Second, // TODO 后期可以设置这个超时时间
}
sshClient, err := ssh.Dial("tcp", req.Host+":"+fmt.Sprintf("%d", req.Port), config)
if err != nil {
resp.Error = "connect failed: " + err.Error()
return resp, nil
}
defer func() {
_ = sshClient.Close()
}()
resp.IsOk = true
return resp, nil
}

View File

@@ -8,7 +8,6 @@ import (
"github.com/TeaOSLab/EdgeAPI/internal/db/models"
"github.com/TeaOSLab/EdgeAPI/internal/errors"
rpcutils "github.com/TeaOSLab/EdgeAPI/internal/rpc/utils"
"github.com/TeaOSLab/EdgeAPI/internal/utils/numberutils"
"github.com/TeaOSLab/EdgeCommon/pkg/messageconfigs"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/iwind/TeaGo/logs"
@@ -94,7 +93,7 @@ func (this *NodeService) NodeStream(server pb.NodeService_NodeStreamServer) erro
}
}
logs.Println("[RPC]accepted node '" + numberutils.FormatInt64(nodeId) + "' connection")
//logs.Println("[RPC]accepted node '" + numberutils.FormatInt64(nodeId) + "' connection")
tx := this.NullTx()

View File

@@ -0,0 +1,171 @@
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package services
import (
"context"
"github.com/TeaOSLab/EdgeAPI/internal/db/models"
rpcutils "github.com/TeaOSLab/EdgeAPI/internal/rpc/utils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
"github.com/iwind/TeaGo/types"
)
// NodeThresholdService 节点阈值服务
type NodeThresholdService struct {
BaseService
}
// CreateNodeThreshold 创建阈值
func (this *NodeThresholdService) CreateNodeThreshold(ctx context.Context, req *pb.CreateNodeThresholdRequest) (*pb.CreateNodeThresholdResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
var tx = this.NullTx()
thresholdId, err := models.SharedNodeThresholdDAO.CreateThreshold(tx, rpcutils.UserTypeNode, req.NodeClusterId, req.NodeId, req.Item, req.Param, req.Operator, req.ValueJSON, req.Message, req.SumMethod, req.Duration, req.DurationUnit, req.NotifyDuration)
if err != nil {
return nil, err
}
return &pb.CreateNodeThresholdResponse{NodeThresholdId: thresholdId}, nil
}
// UpdateNodeThreshold 创建阈值
func (this *NodeThresholdService) UpdateNodeThreshold(ctx context.Context, req *pb.UpdateNodeThresholdRequest) (*pb.RPCSuccess, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
var tx = this.NullTx()
err = models.SharedNodeThresholdDAO.UpdateThreshold(tx, req.NodeThresholdId, req.Item, req.Param, req.Operator, req.ValueJSON, req.Message, req.SumMethod, req.Duration, req.DurationUnit, req.NotifyDuration, req.IsOn)
if err != nil {
return nil, err
}
return this.Success()
}
// DeleteNodeThreshold 删除阈值
func (this *NodeThresholdService) DeleteNodeThreshold(ctx context.Context, req *pb.DeleteNodeThresholdRequest) (*pb.RPCSuccess, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
var tx = this.NullTx()
err = models.SharedNodeThresholdDAO.DisableNodeThreshold(tx, req.NodeThresholdId)
if err != nil {
return nil, err
}
return this.Success()
}
// FindAllEnabledNodeThresholds 查询阈值
func (this *NodeThresholdService) FindAllEnabledNodeThresholds(ctx context.Context, req *pb.FindAllEnabledNodeThresholdsRequest) (*pb.FindAllEnabledNodeThresholdsResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
var tx = this.NullTx()
pbThresholds := []*pb.NodeThreshold{}
thresholds, err := models.SharedNodeThresholdDAO.FindAllEnabledThresholds(tx, req.Role, req.NodeClusterId, req.NodeId)
if err != nil {
return nil, err
}
for _, threshold := range thresholds {
// 节点信息
var pbNode *pb.Node = nil
if threshold.NodeId > 0 {
nodeName, err := models.SharedNodeDAO.FindNodeName(tx, int64(threshold.NodeId))
if err != nil {
return nil, err
}
if len(nodeName) == 0 {
continue
}
pbNode = &pb.Node{
Id: int64(threshold.NodeId),
Name: nodeName,
}
}
pbThresholds = append(pbThresholds, &pb.NodeThreshold{
Id: int64(threshold.Id),
ClusterId: int64(threshold.ClusterId),
Node: pbNode,
Item: threshold.Item,
Param: threshold.Param,
Operator: threshold.Operator,
ValueJSON: []byte(threshold.Value),
Message: threshold.Message,
Duration: types.Int32(threshold.Duration),
DurationUnit: threshold.DurationUnit,
SumMethod: threshold.SumMethod,
NotifyDuration: int32(threshold.NotifyDuration),
IsOn: threshold.IsOn == 1,
})
}
return &pb.FindAllEnabledNodeThresholdsResponse{NodeThresholds: pbThresholds}, nil
}
// CountAllEnabledNodeThresholds 计算阈值数量
func (this *NodeThresholdService) CountAllEnabledNodeThresholds(ctx context.Context, req *pb.CountAllEnabledNodeThresholdsRequest) (*pb.RPCCountResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
var tx = this.NullTx()
count, err := models.SharedNodeThresholdDAO.CountAllEnabledThresholds(tx, req.NodeClusterId, req.NodeId)
if err != nil {
return nil, err
}
return this.SuccessCount(count)
}
// FindEnabledNodeThreshold 查询单个阈值详情
func (this *NodeThresholdService) FindEnabledNodeThreshold(ctx context.Context, req *pb.FindEnabledNodeThresholdRequest) (*pb.FindEnabledNodeThresholdResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
var tx = this.NullTx()
threshold, err := models.SharedNodeThresholdDAO.FindEnabledNodeThreshold(tx, req.NodeThresholdId)
if err != nil {
return nil, err
}
if threshold == nil {
return &pb.FindEnabledNodeThresholdResponse{NodeThreshold: nil}, nil
}
// 节点信息
var pbNode *pb.Node = nil
if threshold.NodeId > 0 {
nodeName, err := models.SharedNodeDAO.FindNodeName(tx, int64(threshold.NodeId))
if err != nil {
return nil, err
}
if len(nodeName) == 0 {
return &pb.FindEnabledNodeThresholdResponse{NodeThreshold: nil}, nil
}
pbNode = &pb.Node{
Id: int64(threshold.NodeId),
Name: nodeName,
}
}
return &pb.FindEnabledNodeThresholdResponse{NodeThreshold: &pb.NodeThreshold{
Id: int64(threshold.Id),
ClusterId: int64(threshold.ClusterId),
Node: pbNode,
Item: threshold.Item,
Param: threshold.Param,
Operator: threshold.Operator,
ValueJSON: []byte(threshold.Value),
Message: threshold.Message,
Duration: types.Int32(threshold.Duration),
DurationUnit: threshold.DurationUnit,
SumMethod: threshold.SumMethod,
NotifyDuration: int32(threshold.NotifyDuration),
IsOn: threshold.IsOn == 1,
}}, nil
}

View File

@@ -0,0 +1,59 @@
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package services
import (
"context"
"github.com/TeaOSLab/EdgeAPI/internal/db/models"
rpcutils "github.com/TeaOSLab/EdgeAPI/internal/rpc/utils"
"github.com/TeaOSLab/EdgeCommon/pkg/rpc/pb"
)
type NodeValueService struct {
BaseService
}
// CreateNodeValue 记录数据
func (this *NodeValueService) CreateNodeValue(ctx context.Context, req *pb.CreateNodeValueRequest) (*pb.RPCSuccess, error) {
role, nodeId, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeNode)
if err != nil {
return nil, err
}
var tx = this.NullTx()
err = models.SharedNodeValueDAO.CreateValue(tx, role, nodeId, req.Item, req.ValueJSON, req.CreatedAt)
if err != nil {
return nil, err
}
// 触发阈值
err = models.SharedNodeThresholdDAO.FireNodeThreshold(tx, role, nodeId, req.Item)
if err != nil {
return nil, err
}
return this.Success()
}
// ListNodeValues 读取数据
func (this *NodeValueService) ListNodeValues(ctx context.Context, req *pb.ListNodeValuesRequest) (*pb.ListNodeValuesResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
var tx = this.NullTx()
values, err := models.SharedNodeValueDAO.ListValues(tx, req.Role, req.NodeId, req.Item, req.Range)
if err != nil {
return nil, err
}
pbValues := []*pb.NodeValue{}
for _, value := range values {
pbValues = append(pbValues, &pb.NodeValue{
ValueJSON: []byte(value.Value),
CreatedAt: int64(value.CreatedAt),
})
}
return &pb.ListNodeValuesResponse{NodeValues: pbValues}, nil
}

View File

@@ -20,7 +20,7 @@ type ServerService struct {
BaseService
}
// 创建服务
// CreateServer 创建服务
func (this *ServerService) CreateServer(ctx context.Context, req *pb.CreateServerRequest) (*pb.CreateServerResponse, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, req.UserId)
@@ -90,7 +90,7 @@ func (this *ServerService) CreateServer(ctx context.Context, req *pb.CreateServe
return &pb.CreateServerResponse{ServerId: serverId}, nil
}
// 修改服务基本信息
// UpdateServerBasic 修改服务基本信息
func (this *ServerService) UpdateServerBasic(ctx context.Context, req *pb.UpdateServerBasicRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, err := this.ValidateAdmin(ctx, 0)
@@ -121,7 +121,7 @@ func (this *ServerService) UpdateServerBasic(ctx context.Context, req *pb.Update
return this.Success()
}
// 修改服务是否启用
// UpdateServerIsOn 修改服务是否启用
func (this *ServerService) UpdateServerIsOn(ctx context.Context, req *pb.UpdateServerIsOnRequest) (*pb.RPCSuccess, error) {
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
if err != nil {
@@ -143,7 +143,7 @@ func (this *ServerService) UpdateServerIsOn(ctx context.Context, req *pb.UpdateS
return this.Success()
}
// 修改HTTP服务
// UpdateServerHTTP 修改HTTP服务
func (this *ServerService) UpdateServerHTTP(ctx context.Context, req *pb.UpdateServerHTTPRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -169,7 +169,7 @@ func (this *ServerService) UpdateServerHTTP(ctx context.Context, req *pb.UpdateS
return this.Success()
}
// 修改HTTPS服务
// UpdateServerHTTPS 修改HTTPS服务
func (this *ServerService) UpdateServerHTTPS(ctx context.Context, req *pb.UpdateServerHTTPSRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -195,7 +195,7 @@ func (this *ServerService) UpdateServerHTTPS(ctx context.Context, req *pb.Update
return this.Success()
}
// 修改TCP服务
// UpdateServerTCP 修改TCP服务
func (this *ServerService) UpdateServerTCP(ctx context.Context, req *pb.UpdateServerTCPRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -221,7 +221,7 @@ func (this *ServerService) UpdateServerTCP(ctx context.Context, req *pb.UpdateSe
return this.Success()
}
// 修改TLS服务
// UpdateServerTLS 修改TLS服务
func (this *ServerService) UpdateServerTLS(ctx context.Context, req *pb.UpdateServerTLSRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -247,7 +247,7 @@ func (this *ServerService) UpdateServerTLS(ctx context.Context, req *pb.UpdateSe
return this.Success()
}
// 修改Unix服务
// UpdateServerUnix 修改Unix服务
func (this *ServerService) UpdateServerUnix(ctx context.Context, req *pb.UpdateServerUnixRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -270,7 +270,7 @@ func (this *ServerService) UpdateServerUnix(ctx context.Context, req *pb.UpdateS
return this.Success()
}
// 修改UDP服务
// UpdateServerUDP 修改UDP服务
func (this *ServerService) UpdateServerUDP(ctx context.Context, req *pb.UpdateServerUDPRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -293,7 +293,7 @@ func (this *ServerService) UpdateServerUDP(ctx context.Context, req *pb.UpdateSe
return this.Success()
}
// 修改Web服务
// UpdateServerWeb 修改Web服务
func (this *ServerService) UpdateServerWeb(ctx context.Context, req *pb.UpdateServerWebRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -319,7 +319,7 @@ func (this *ServerService) UpdateServerWeb(ctx context.Context, req *pb.UpdateSe
return this.Success()
}
// 修改反向代理服务
// UpdateServerReverseProxy 修改反向代理服务
func (this *ServerService) UpdateServerReverseProxy(ctx context.Context, req *pb.UpdateServerReverseProxyRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -345,7 +345,7 @@ func (this *ServerService) UpdateServerReverseProxy(ctx context.Context, req *pb
return this.Success()
}
// 查找服务的域名设置
// FindServerNames 查找服务的域名设置
func (this *ServerService) FindServerNames(ctx context.Context, req *pb.FindServerNamesRequest) (*pb.FindServerNamesResponse, error) {
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
if err != nil {
@@ -385,7 +385,7 @@ func (this *ServerService) FindServerNames(ctx context.Context, req *pb.FindServ
}, nil
}
// 修改域名服务
// UpdateServerNames 修改域名服务
func (this *ServerService) UpdateServerNames(ctx context.Context, req *pb.UpdateServerNamesRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -423,7 +423,7 @@ func (this *ServerService) UpdateServerNames(ctx context.Context, req *pb.Update
return this.Success()
}
// 审核服务的域名设置
// UpdateServerNamesAuditing 审核服务的域名设置
func (this *ServerService) UpdateServerNamesAuditing(ctx context.Context, req *pb.UpdateServerNamesAuditingRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, err := this.ValidateAdmin(ctx, 0)
@@ -469,7 +469,7 @@ func (this *ServerService) UpdateServerNamesAuditing(ctx context.Context, req *p
return this.Success()
}
// 计算服务数量
// CountAllEnabledServersMatch 计算服务数量
func (this *ServerService) CountAllEnabledServersMatch(ctx context.Context, req *pb.CountAllEnabledServersMatchRequest) (*pb.RPCCountResponse, error) {
// 校验请求
_, _, err := this.ValidateAdminAndUser(ctx, 0, req.UserId)
@@ -487,7 +487,7 @@ func (this *ServerService) CountAllEnabledServersMatch(ctx context.Context, req
return this.SuccessCount(count)
}
// 列出单页服务
// ListEnabledServersMatch 列出单页服务
func (this *ServerService) ListEnabledServersMatch(ctx context.Context, req *pb.ListEnabledServersMatchRequest) (*pb.ListEnabledServersMatchResponse, error) {
// 校验请求
_, _, err := this.ValidateAdminAndUser(ctx, 0, req.UserId)
@@ -588,7 +588,7 @@ func (this *ServerService) ListEnabledServersMatch(ctx context.Context, req *pb.
return &pb.ListEnabledServersMatchResponse{Servers: result}, nil
}
// 禁用某服务
// DeleteServer 禁用某服务
func (this *ServerService) DeleteServer(ctx context.Context, req *pb.DeleteServerRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -614,7 +614,7 @@ func (this *ServerService) DeleteServer(ctx context.Context, req *pb.DeleteServe
return this.Success()
}
// 查找单个服务
// FindEnabledServer 查找单个服务
func (this *ServerService) FindEnabledServer(ctx context.Context, req *pb.FindEnabledServerRequest) (*pb.FindEnabledServerResponse, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -716,7 +716,7 @@ func (this *ServerService) FindEnabledServer(ctx context.Context, req *pb.FindEn
}}, nil
}
// 查找服务配置
// FindEnabledServerConfig 查找服务配置
func (this *ServerService) FindEnabledServerConfig(ctx context.Context, req *pb.FindEnabledServerConfigRequest) (*pb.FindEnabledServerConfigResponse, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -749,7 +749,7 @@ func (this *ServerService) FindEnabledServerConfig(ctx context.Context, req *pb.
return &pb.FindEnabledServerConfigResponse{ServerJSON: configJSON}, nil
}
// 查找服务的服务类型
// FindEnabledServerType 查找服务的服务类型
func (this *ServerService) FindEnabledServerType(ctx context.Context, req *pb.FindEnabledServerTypeRequest) (*pb.FindEnabledServerTypeResponse, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -775,7 +775,7 @@ func (this *ServerService) FindEnabledServerType(ctx context.Context, req *pb.Fi
return &pb.FindEnabledServerTypeResponse{Type: serverType}, nil
}
// 查找反向代理设置
// FindAndInitServerReverseProxyConfig 查找反向代理设置
func (this *ServerService) FindAndInitServerReverseProxyConfig(ctx context.Context, req *pb.FindAndInitServerReverseProxyConfigRequest) (*pb.FindAndInitServerReverseProxyConfigResponse, error) {
// 校验请求
adminId, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -828,7 +828,7 @@ func (this *ServerService) FindAndInitServerReverseProxyConfig(ctx context.Conte
return &pb.FindAndInitServerReverseProxyConfigResponse{ReverseProxyJSON: configJSON, ReverseProxyRefJSON: refJSON}, nil
}
// 初始化Web设置
// FindAndInitServerWebConfig 初始化Web设置
func (this *ServerService) FindAndInitServerWebConfig(ctx context.Context, req *pb.FindAndInitServerWebConfigRequest) (*pb.FindAndInitServerWebConfigResponse, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -869,7 +869,7 @@ func (this *ServerService) FindAndInitServerWebConfig(ctx context.Context, req *
return &pb.FindAndInitServerWebConfigResponse{WebJSON: configJSON}, nil
}
// 计算使用某个SSL证书的服务数量
// CountAllEnabledServersWithSSLCertId 计算使用某个SSL证书的服务数量
func (this *ServerService) CountAllEnabledServersWithSSLCertId(ctx context.Context, req *pb.CountAllEnabledServersWithSSLCertIdRequest) (*pb.RPCCountResponse, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -899,7 +899,7 @@ func (this *ServerService) CountAllEnabledServersWithSSLCertId(ctx context.Conte
return this.SuccessCount(count)
}
// 查找使用某个SSL证书的所有服务
// FindAllEnabledServersWithSSLCertId 查找使用某个SSL证书的所有服务
func (this *ServerService) FindAllEnabledServersWithSSLCertId(ctx context.Context, req *pb.FindAllEnabledServersWithSSLCertIdRequest) (*pb.FindAllEnabledServersWithSSLCertIdResponse, error) {
// 校验请求
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -937,7 +937,7 @@ func (this *ServerService) FindAllEnabledServersWithSSLCertId(ctx context.Contex
return &pb.FindAllEnabledServersWithSSLCertIdResponse{Servers: result}, nil
}
// 计算运行在某个集群上的所有服务数量
// CountAllEnabledServersWithNodeClusterId 计算运行在某个集群上的所有服务数量
func (this *ServerService) CountAllEnabledServersWithNodeClusterId(ctx context.Context, req *pb.CountAllEnabledServersWithNodeClusterIdRequest) (*pb.RPCCountResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -954,7 +954,7 @@ func (this *ServerService) CountAllEnabledServersWithNodeClusterId(ctx context.C
return this.SuccessCount(count)
}
// 计算使用某个分组的服务数量
// CountAllEnabledServersWithGroupId 计算使用某个分组的服务数量
func (this *ServerService) CountAllEnabledServersWithGroupId(ctx context.Context, req *pb.CountAllEnabledServersWithGroupIdRequest) (*pb.RPCCountResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -971,8 +971,8 @@ func (this *ServerService) CountAllEnabledServersWithGroupId(ctx context.Context
return this.SuccessCount(count)
}
// 通知更新
func (this *ServerService) NotifyServersChange(ctx context.Context, req *pb.NotifyServersChangeRequest) (*pb.NotifyServersChangeResponse, error) {
// NotifyServersChange 通知更新
func (this *ServerService) NotifyServersChange(ctx context.Context, _ *pb.NotifyServersChangeRequest) (*pb.NotifyServersChangeResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
if err != nil {
@@ -995,7 +995,7 @@ func (this *ServerService) NotifyServersChange(ctx context.Context, req *pb.Noti
return &pb.NotifyServersChangeResponse{}, nil
}
// 取得某个集群下的所有服务相关的DNS
// FindAllEnabledServersDNSWithClusterId 取得某个集群下的所有服务相关的DNS
func (this *ServerService) FindAllEnabledServersDNSWithClusterId(ctx context.Context, req *pb.FindAllEnabledServersDNSWithClusterIdRequest) (*pb.FindAllEnabledServersDNSWithClusterIdResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -1031,7 +1031,7 @@ func (this *ServerService) FindAllEnabledServersDNSWithClusterId(ctx context.Con
return &pb.FindAllEnabledServersDNSWithClusterIdResponse{Servers: result}, nil
}
// 查找单个服务的DNS信息
// FindEnabledServerDNS 查找单个服务的DNS信息
func (this *ServerService) FindEnabledServerDNS(ctx context.Context, req *pb.FindEnabledServerDNSRequest) (*pb.FindEnabledServerDNSResponse, error) {
// 校验请求
_, _, err := this.ValidateAdminAndUser(ctx, 0, 0)
@@ -1079,7 +1079,7 @@ func (this *ServerService) FindEnabledServerDNS(ctx context.Context, req *pb.Fin
}, nil
}
// 检查服务是否属于某个用户
// CheckUserServer 检查服务是否属于某个用户
func (this *ServerService) CheckUserServer(ctx context.Context, req *pb.CheckUserServerRequest) (*pb.RPCSuccess, error) {
userId, err := this.ValidateUser(ctx)
if err != nil {
@@ -1095,7 +1095,7 @@ func (this *ServerService) CheckUserServer(ctx context.Context, req *pb.CheckUse
return this.Success()
}
// 查找一个用户下的所有域名列表
// FindAllEnabledServerNamesWithUserId 查找一个用户下的所有域名列表
func (this *ServerService) FindAllEnabledServerNamesWithUserId(ctx context.Context, req *pb.FindAllEnabledServerNamesWithUserIdRequest) (*pb.FindAllEnabledServerNamesWithUserIdResponse, error) {
_, _, err := this.ValidateAdminAndUser(ctx, 0, req.UserId)
if err != nil {
@@ -1128,7 +1128,7 @@ func (this *ServerService) FindAllEnabledServerNamesWithUserId(ctx context.Conte
return &pb.FindAllEnabledServerNamesWithUserIdResponse{ServerNames: serverNames}, nil
}
// 查找服务基本信息
// FindEnabledUserServerBasic 查找服务基本信息
func (this *ServerService) FindEnabledUserServerBasic(ctx context.Context, req *pb.FindEnabledUserServerBasicRequest) (*pb.FindEnabledUserServerBasicResponse, error) {
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
if err != nil {
@@ -1170,7 +1170,7 @@ func (this *ServerService) FindEnabledUserServerBasic(ctx context.Context, req *
}}, nil
}
// 修改用户服务基本信息
// UpdateEnabledUserServerBasic 修改用户服务基本信息
func (this *ServerService) UpdateEnabledUserServerBasic(ctx context.Context, req *pb.UpdateEnabledUserServerBasicRequest) (*pb.RPCSuccess, error) {
_, userId, err := this.ValidateAdminAndUser(ctx, 0, 0)
if err != nil {
@@ -1194,7 +1194,7 @@ func (this *ServerService) UpdateEnabledUserServerBasic(ctx context.Context, req
return this.Success()
}
// 上传待统计数据
// UploadServerHTTPRequestStat 上传待统计数据
func (this *ServerService) UploadServerHTTPRequestStat(ctx context.Context, req *pb.UploadServerHTTPRequestStatRequest) (*pb.RPCSuccess, error) {
_, err := this.ValidateNode(ctx)
if err != nil {
@@ -1369,7 +1369,7 @@ func (this *ServerService) UploadServerHTTPRequestStat(ctx context.Context, req
return this.Success()
}
// 检查域名是否已经存在
// CheckServerNameDuplicationInNodeCluster 检查域名是否已经存在
func (this *ServerService) CheckServerNameDuplicationInNodeCluster(ctx context.Context, req *pb.CheckServerNameDuplicationInNodeClusterRequest) (*pb.CheckServerNameDuplicationInNodeClusterResponse, error) {
_, _, err := this.ValidateAdminAndUser(ctx, 0, 0)
if err != nil {
@@ -1395,3 +1395,25 @@ func (this *ServerService) CheckServerNameDuplicationInNodeCluster(ctx context.C
return &pb.CheckServerNameDuplicationInNodeClusterResponse{DuplicatedServerNames: duplicatedServerNames}, nil
}
// FindLatestServers 查找最近访问的服务
func (this *ServerService) FindLatestServers(ctx context.Context, req *pb.FindLatestServersRequest) (*pb.FindLatestServersResponse, error) {
_, err := this.ValidateAdmin(ctx, 0)
if err != nil {
return nil, err
}
var tx = this.NullTx()
servers, err := models.SharedServerDAO.FindLatestServers(tx, req.Size)
if err != nil {
return nil, err
}
pbServers := []*pb.Server{}
for _, server := range servers {
pbServers = append(pbServers, &pb.Server{
Id: int64(server.Id),
Name: server.Name,
})
}
return &pb.FindLatestServersResponse{Servers: pbServers}, nil
}

View File

@@ -13,7 +13,7 @@ type HTTPGzipService struct {
BaseService
}
// 创建Gzip配置
// CreateHTTPGzip 创建Gzip配置
func (this *HTTPGzipService) CreateHTTPGzip(ctx context.Context, req *pb.CreateHTTPGzipRequest) (*pb.CreateHTTPGzipResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -50,10 +50,10 @@ func (this *HTTPGzipService) CreateHTTPGzip(ctx context.Context, req *pb.CreateH
return nil, err
}
return &pb.CreateHTTPGzipResponse{GzipId: gzipId}, nil
return &pb.CreateHTTPGzipResponse{HttpGzipId: gzipId}, nil
}
// 查找Gzip
// FindEnabledHTTPGzipConfig 查找Gzip
func (this *HTTPGzipService) FindEnabledHTTPGzipConfig(ctx context.Context, req *pb.FindEnabledGzipConfigRequest) (*pb.FindEnabledGzipConfigResponse, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -63,7 +63,7 @@ func (this *HTTPGzipService) FindEnabledHTTPGzipConfig(ctx context.Context, req
tx := this.NullTx()
config, err := models.SharedHTTPGzipDAO.ComposeGzipConfig(tx, req.GzipId)
config, err := models.SharedHTTPGzipDAO.ComposeGzipConfig(tx, req.HttpGzipId)
if err != nil {
return nil, err
}
@@ -72,10 +72,10 @@ func (this *HTTPGzipService) FindEnabledHTTPGzipConfig(ctx context.Context, req
if err != nil {
return nil, err
}
return &pb.FindEnabledGzipConfigResponse{GzipJSON: configData}, nil
return &pb.FindEnabledGzipConfigResponse{HttpGzipJSON: configData}, nil
}
// 修改Gzip配置
// UpdateHTTPGzip 修改Gzip配置
func (this *HTTPGzipService) UpdateHTTPGzip(ctx context.Context, req *pb.UpdateHTTPGzipRequest) (*pb.RPCSuccess, error) {
// 校验请求
_, _, err := rpcutils.ValidateRequest(ctx, rpcutils.UserTypeAdmin)
@@ -107,7 +107,7 @@ func (this *HTTPGzipService) UpdateHTTPGzip(ctx context.Context, req *pb.UpdateH
tx := this.NullTx()
err = models.SharedHTTPGzipDAO.UpdateGzip(tx, req.GzipId, int(req.Level), minLengthJSON, maxLengthJSON, req.CondsJSON)
err = models.SharedHTTPGzipDAO.UpdateGzip(tx, req.HttpGzipId, int(req.Level), minLengthJSON, maxLengthJSON, req.CondsJSON)
if err != nil {
return nil, err
}

File diff suppressed because one or more lines are too long

View File

@@ -198,7 +198,7 @@ func (this *SQLExecutor) checkCluster(db *dbs.DB) error {
}
// 创建默认集群
_, err = db.Exec("INSERT INTO edgeNodeClusters (name, useAllAPINodes, state) VALUES (?, ?, ?)", "默认集群", 1, 1)
_, err = db.Exec("INSERT INTO edgeNodeClusters (name, useAllAPINodes, state, uniqueId, secret) VALUES (?, ?, ?, ?, ?)", "默认集群", 1, 1, rands.HexString(32), rands.String(32))
if err != nil {
return err
}

View File

@@ -0,0 +1,43 @@
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package tasks
import (
"github.com/TeaOSLab/EdgeAPI/internal/db/models"
"github.com/TeaOSLab/EdgeAPI/internal/remotelogs"
"github.com/iwind/TeaGo/Tea"
"github.com/iwind/TeaGo/dbs"
"time"
)
func init() {
dbs.OnReady(func() {
go NewMonitorItemValueTask().Start()
})
}
// MonitorItemValueTask 节点监控数值任务
type MonitorItemValueTask struct {
}
// NewMonitorItemValueTask 获取新对象
func NewMonitorItemValueTask() *MonitorItemValueTask {
return &MonitorItemValueTask{}
}
func (this *MonitorItemValueTask) Start() {
ticker := time.NewTicker(24 * time.Hour)
if Tea.IsTesting() {
ticker = time.NewTicker(1 * time.Minute)
}
for range ticker.C {
err := this.Loop()
if err != nil {
remotelogs.Error("MonitorItemValueTask", err.Error())
}
}
}
func (this *MonitorItemValueTask) Loop() error {
return models.SharedNodeValueDAO.DeleteExpiredValues(nil)
}

View File

@@ -0,0 +1,19 @@
// Copyright 2021 Liuxiangchao iwind.liu@gmail.com. All rights reserved.
package tasks
import (
"github.com/iwind/TeaGo/dbs"
"testing"
)
func TestMonitorItemValueTask_Loop(t *testing.T) {
dbs.NotifyReady()
task := NewMonitorItemValueTask()
err := task.Loop()
if err != nil {
t.Fatal(err)
}
t.Log("ok")
}