完善开服、停服、白名单、不停机更新流程

This commit is contained in:
flswld committed 2023-10-15 17:28:13 +08:00
1 parent ef8408adf8
commit 3af603dcaa
28 files changed
+425 -117

No files matched your search

+4 -2
View File
@@ -1,6 +1,8 @@
CUR_DIR=$(shell pwd)
VERSION=1.0.0
ifeq ($(VERSION),)
VERSION=1.0.0
endif
.PHONY: all
all: build
@@ -16,7 +18,7 @@ clean:
# 构建服务器二进制文件
.PHONY: build
build:
mkdir -p bin && go build -ldflags "-X main.Version=$(VERSION)" -o ./bin/ ./cmd/...
mkdir -p bin && go build -ldflags "-X main.VERSION=$(VERSION)" -o ./bin/ ./cmd/...
# 清理镜像
.PHONY: docker_clean
+2
View File
@@ -18,6 +18,7 @@ import (
)
var APPID string
var APPVERSION string
func Run(ctx context.Context, configFile string) error {
config.InitConfig(configFile)
@@ -31,6 +32,7 @@ func Run(ctx context.Context, configFile string) error {
// 注册到节点服务器
rsp, err := discoveryClient.RegisterServer(context.TODO(), &api.RegisterServerReq{
ServerType: api.ANTICHEAT,
AppVersion: APPVERSION,
})
if err != nil {
return err
+3
View File
@@ -15,11 +15,14 @@ var (
config = flag.String("config", "application.toml", "config file")
)
var VERSION = "UNKNOWN"
func main() {
flag.Parse()
go func() {
_ = statsviz_serve.Serve("0.0.0.0:5678")
}()
app.APPVERSION = VERSION
err := app.Run(context.TODO(), *config)
if err != nil {
fmt.Println(err)
+3
View File
@@ -15,11 +15,14 @@ var (
config = flag.String("config", "application.toml", "config file")
)
var VERSION = "UNKNOWN"
func main() {
flag.Parse()
go func() {
_ = statsviz_serve.Serve("0.0.0.0:2345")
}()
app.APPVERSION = VERSION
err := app.Run(context.TODO(), *config)
if err != nil {
fmt.Println(err)
+3
View File
@@ -15,11 +15,14 @@ var (
config = flag.String("config", "application.toml", "config file")
)
var VERSION = "UNKNOWN"
func main() {
flag.Parse()
go func() {
_ = statsviz_serve.Serve("0.0.0.0:3456")
}()
app.APPVERSION = VERSION
err := app.Run(context.TODO(), *config)
if err != nil {
fmt.Println(err)
+3
View File
@@ -15,11 +15,14 @@ var (
config = flag.String("config", "application.toml", "config file")
)
var VERSION = "UNKNOWN"
func main() {
flag.Parse()
go func() {
_ = statsviz_serve.Serve("0.0.0.0:4567")
}()
app.APPVERSION = VERSION
err := app.Run(context.TODO(), *config)
if err != nil {
fmt.Println(err)
+1
View File
@@ -10,6 +10,7 @@ import (
func AnticheatCmd() *cobra.Command {
var cfg string
app.APPVERSION = VERSION
c := &cobra.Command{
Use: "anticheat",
Short: "anticheat server",
+1
View File
@@ -10,6 +10,7 @@ import (
func DispatchCmd() *cobra.Command {
var cfg string
app.APPVERSION = VERSION
c := &cobra.Command{
Use: "dispatch",
Short: "dispatch server",
+1
View File
@@ -10,6 +10,7 @@ import (
func GateCmd() *cobra.Command {
var cfg string
app.APPVERSION = VERSION
c := &cobra.Command{
Use: "gate",
Short: "gate server",
+1
View File
@@ -10,6 +10,7 @@ import (
func GSCmd() *cobra.Command {
var cfg string
app.APPVERSION = VERSION
c := &cobra.Command{
Use: "gs",
Short: "game server",
+2
View File
@@ -13,6 +13,8 @@ var (
config = flag.String("config", "application.toml", "config file")
)
var VERSION = "UNKNOWN"
func main() {
rootCmd := &cobra.Command{
Use: "hk4e",
+1
View File
@@ -10,6 +10,7 @@ import (
func PathfindingCmd() *cobra.Command {
var cfg string
app.APPVERSION = VERSION
c := &cobra.Command{
Use: "pathfinding",
Short: "pathfinding server",
+3
View File
@@ -15,11 +15,14 @@ var (
config = flag.String("config", "application.toml", "config file")
)
var VERSION = "UNKNOWN"
func main() {
flag.Parse()
go func() {
_ = statsviz_serve.Serve("0.0.0.0:6789")
}()
app.APPVERSION = VERSION
err := app.Run(context.TODO(), *config)
if err != nil {
fmt.Println(err)
+3
View File
@@ -13,8 +13,11 @@ var (
config = flag.String("config", "application.toml", "config file")
)
var VERSION = "UNKNOWN"
func main() {
flag.Parse()
app.APPVERSION = VERSION
err := app.Run(context.TODO(), *config)
if err != nil {
fmt.Println(err)
+2
View File
@@ -18,6 +18,7 @@ import (
)
var APPID string
var APPVERSION string
func Run(ctx context.Context, configFile string) error {
config.InitConfig(configFile)
@@ -31,6 +32,7 @@ func Run(ctx context.Context, configFile string) error {
// 注册到节点服务器
rsp, err := discoveryClient.RegisterServer(context.TODO(), &api.RegisterServerReq{
ServerType: api.DISPATCH,
AppVersion: APPVERSION,
})
if err != nil {
return err
+55 -9
View File
@@ -5,6 +5,8 @@ import (
"net"
"net/http"
"strconv"
"sync"
"time"
"hk4e/common/config"
"hk4e/common/mq"
@@ -19,21 +21,24 @@ import (
)
type Controller struct {
db *dao.Dao
discovery *rpc.DiscoveryClient
signRsaKey []byte
encRsaKeyMap map[string][]byte
pwdRsaKey []byte
ec2b *random.Ec2b
messageQueue *mq.MessageQueue
db *dao.Dao
discoveryClient *rpc.DiscoveryClient
signRsaKey []byte
encRsaKeyMap map[string][]byte
pwdRsaKey []byte
ec2b *random.Ec2b
messageQueue *mq.MessageQueue
gateServerMap *sync.Map
stopServerInfo *api.StopServerInfo
whiteList *api.GetWhiteListRsp
}
func NewController(db *dao.Dao, discovery *rpc.DiscoveryClient, messageQueue *mq.MessageQueue) (r *Controller) {
r = new(Controller)
r.db = db
r.discovery = discovery
r.discoveryClient = discovery
r.signRsaKey, r.encRsaKeyMap, r.pwdRsaKey = region.LoadRegionRsaKey()
rsp, err := r.discovery.GetRegionEc2B(context.TODO(), &api.NullMsg{})
rsp, err := r.discoveryClient.GetRegionEc2B(context.TODO(), &api.NullMsg{})
if err != nil {
logger.Error("get region ec2b error: %v", err)
return nil
@@ -45,7 +50,14 @@ func NewController(db *dao.Dao, discovery *rpc.DiscoveryClient, messageQueue *mq
}
r.ec2b = ec2b
r.messageQueue = messageQueue
r.gateServerMap = new(sync.Map)
r.stopServerInfo = nil
r.whiteList = nil
go r.registerRouter()
r.syncWhiteList()
go r.autoSyncWhiteList()
r.syncStopServerInfo()
go r.autoSyncStopServerInfo()
return r
}
@@ -175,3 +187,37 @@ func (c *Controller) registerRouter() {
logger.Error("gin run error: %v", err)
}
}
func (c *Controller) autoSyncStopServerInfo() {
ticker := time.NewTicker(time.Minute * 1)
for {
<-ticker.C
c.syncStopServerInfo()
}
}
func (c *Controller) syncStopServerInfo() {
stopServerInfo, err := c.discoveryClient.GetStopServerInfo(context.TODO(), &api.NullMsg{})
if err != nil {
logger.Error("get stop server info error: %v", err)
return
}
c.stopServerInfo = stopServerInfo
}
func (c *Controller) autoSyncWhiteList() {
ticker := time.NewTicker(time.Minute * 1)
for {
<-ticker.C
c.syncWhiteList()
}
}
func (c *Controller) syncWhiteList() {
whiteList, err := c.discoveryClient.GetWhiteList(context.TODO(), &api.NullMsg{})
if err != nil {
logger.Error("get white list error: %v", err)
return
}
c.whiteList = whiteList
}
+42 -15
View File
@@ -11,6 +11,7 @@ import (
"net/http"
"net/url"
"os"
"time"
"hk4e/common/config"
"hk4e/common/mq"
@@ -144,6 +145,11 @@ func GetRegionCurr(ec2b *random.Ec2b, gateServerAddr *api.GateServerAddr, stopSe
return regionCurr
}
type GateServerInfo struct {
addr *api.GateServerAddr
timestamp int64
}
// dispatch请求错误响应
func (c *Controller) dispatchReqErrorRsp(ctx *gin.Context, dispatchLevel uint8) {
if dispatchLevel == 1 {
@@ -191,24 +197,45 @@ func (c *Controller) queryCurRegion(ctx *gin.Context) {
c.dispatchReqErrorRsp(ctx, 2)
return
}
gateServerAddr, err := c.discovery.GetGateServerAddr(ctx.Request.Context(), &api.GetGateServerAddrReq{
Version: versionStr,
})
if err != nil {
logger.Error("get gate server addr error: %v", err)
c.dispatchReqErrorRsp(ctx, 2)
return
}
var regionCurr *proto.QueryCurrRegionHttpRsp = nil
if !config.GetConfig().Hk4e.ForwardModeEnable {
clientIp := ctx.ClientIP()
stopServerInfo, err := c.discovery.GetStopServerInfo(ctx.Request.Context(), &api.GetStopServerInfoReq{ClientIpAddr: clientIp})
var gateServerAddr *api.GateServerAddr = nil
var err error = nil
now := time.Now().Unix()
inst, exist := c.gateServerMap.Load(versionStr)
if !exist || (exist && now-inst.(*GateServerInfo).timestamp > 60) {
gateServerAddr, err = c.discoveryClient.GetGateServerAddr(ctx.Request.Context(), &api.GetGateServerAddrReq{
GameVersion: versionStr,
})
if err != nil {
logger.Error("get stop server info error: %v", err)
logger.Error("get gate server addr error: %v", err)
c.dispatchReqErrorRsp(ctx, 2)
return
}
regionCurr = GetRegionCurr(c.ec2b, gateServerAddr, stopServerInfo)
c.gateServerMap.Store(versionStr, &GateServerInfo{
addr: gateServerAddr,
timestamp: now,
})
} else {
gateServerAddr = inst.(*GateServerInfo).addr
}
var regionCurr *proto.QueryCurrRegionHttpRsp = nil
if !config.GetConfig().Hk4e.ForwardModeEnable {
if !c.stopServerInfo.StopServer {
regionCurr = GetRegionCurr(c.ec2b, gateServerAddr, &api.StopServerInfo{StopServer: false})
} else {
clientIp := ctx.ClientIP()
isWhiteList := false
for _, ipAddr := range c.whiteList.IpAddrList {
if ipAddr == clientIp {
isWhiteList = true
break
}
}
if isWhiteList {
regionCurr = GetRegionCurr(c.ec2b, gateServerAddr, &api.StopServerInfo{StopServer: false})
} else {
regionCurr = GetRegionCurr(c.ec2b, gateServerAddr, c.stopServerInfo)
}
}
} else {
regionCurr, err = c.queryCurRegionForwardMode(version, gateServerAddr)
if err != nil {
@@ -438,7 +465,7 @@ func (c *Controller) queryCurRegionForwardMode(version int, gateServerAddr *api.
return nil, err
}
logger.Debug("QueryCurrRegionHttpRsp: %+v", queryCurrRegionHttpRsp)
robotServerAppId, err := c.discovery.GetServerAppId(context.TODO(), &api.GetServerAppIdReq{
robotServerAppId, err := c.discoveryClient.GetServerAppId(context.TODO(), &api.GetServerAppIdReq{
ServerType: api.ROBOT,
})
if err != nil {
+3 -1
View File
@@ -20,6 +20,7 @@ import (
)
var APPID string
var APPVERSION string
func Run(ctx context.Context, configFile string) error {
config.InitConfig(configFile)
@@ -33,13 +34,14 @@ func Run(ctx context.Context, configFile string) error {
// 注册到节点服务器
rsp, err := discoveryClient.RegisterServer(context.TODO(), &api.RegisterServerReq{
ServerType: api.GATE,
AppVersion: APPVERSION,
GateServerAddr: &api.GateServerAddr{
KcpAddr: config.GetConfig().Hk4e.KcpAddr,
KcpPort: uint32(config.GetConfig().Hk4e.KcpPort),
MqAddr: config.GetConfig().Hk4e.GateTcpMqAddr,
MqPort: uint32(config.GetConfig().Hk4e.GateTcpMqPort),
},
Version: strings.Split(config.GetConfig().Hk4e.Version, ","),
GameVersionList: strings.Split(config.GetConfig().Hk4e.Version, ","),
})
if err != nil {
return err
+93 -10
View File
@@ -51,12 +51,17 @@ type KcpEvent struct {
}
type KcpConnManager struct {
kcpListener *kcp.Listener
db *dao.Dao
discovery *rpc.DiscoveryClient // 节点服务器rpc客户端
messageQueue *mq.MessageQueue // 消息队列
globalGsOnlineMap map[uint32]string // 全服玩家在线表
globalGsOnlineMapLock sync.RWMutex
kcpListener *kcp.Listener
db *dao.Dao
discoveryClient *rpc.DiscoveryClient // 节点服务器rpc客户端
messageQueue *mq.MessageQueue // 消息队列
globalGsOnlineMap map[uint32]string // 全服玩家在线表
globalGsOnlineMapLock sync.RWMutex
minLoadGsServerAppId string
minLoadAnticheatServerAppId string
minLoadPathfindingServerAppId string
stopServerInfo *api.StopServerInfo
whiteList *api.GetWhiteListRsp
// 会话
sessionIdCounter uint32
sessionMap map[uint32]*Session
@@ -80,9 +85,14 @@ func NewKcpConnManager(db *dao.Dao, messageQueue *mq.MessageQueue, discovery *rp
r := new(KcpConnManager)
r.kcpListener = nil
r.db = db
r.discovery = discovery
r.discoveryClient = discovery
r.messageQueue = messageQueue
r.globalGsOnlineMap = make(map[uint32]string)
r.minLoadGsServerAppId = ""
r.minLoadAnticheatServerAppId = ""
r.minLoadPathfindingServerAppId = ""
r.stopServerInfo = nil
r.whiteList = nil
r.sessionIdCounter = 0
r.sessionMap = make(map[uint32]*Session)
r.sessionUserIdMap = make(map[uint32]*Session)
@@ -105,7 +115,7 @@ func (k *KcpConnManager) run() error {
// 读取密钥相关文件
k.signRsaKey, k.encRsaKeyMap, _ = region.LoadRegionRsaKey()
// key
rsp, err := k.discovery.GetRegionEc2B(context.TODO(), &api.NullMsg{})
rsp, err := k.discoveryClient.GetRegionEc2B(context.TODO(), &api.NullMsg{})
if err != nil {
logger.Error("get region ec2b error: %v", err)
return err
@@ -151,6 +161,12 @@ func (k *KcpConnManager) run() error {
}
k.syncGlobalGsOnlineMap()
go k.autoSyncGlobalGsOnlineMap()
k.syncMinLoadServerAppid()
go k.autoSyncMinLoadServerAppid()
k.syncWhiteList()
go k.autoSyncWhiteList()
k.syncStopServerInfo()
go k.autoSyncStopServerInfo()
go func() {
for {
kcpEvent := <-k.kcpEventChan
@@ -263,7 +279,7 @@ func (k *KcpConnManager) acceptHandle(tcpMode bool, kcpListener *kcp.Listener, t
tcpRttLastSendTime: 0,
}
if config.GetConfig().Hk4e.ForwardModeEnable {
robotServerAppId, err := k.discovery.GetServerAppId(context.TODO(), &api.GetServerAppIdReq{
robotServerAppId, err := k.discoveryClient.GetServerAppId(context.TODO(), &api.GetServerAppIdReq{
ServerType: api.ROBOT,
})
if err != nil {
@@ -656,7 +672,7 @@ func (k *KcpConnManager) autoSyncGlobalGsOnlineMap() {
}
func (k *KcpConnManager) syncGlobalGsOnlineMap() {
rsp, err := k.discovery.GetGlobalGsOnlineMap(context.TODO(), nil)
rsp, err := k.discoveryClient.GetGlobalGsOnlineMap(context.TODO(), nil)
if err != nil {
logger.Error("get global gs online map error: %v", err)
return
@@ -671,3 +687,70 @@ func (k *KcpConnManager) syncGlobalGsOnlineMap() {
k.globalGsOnlineMapLock.Unlock()
logger.Info("sync global gs online map finish, len: %v", copyMapLen)
}
func (k *KcpConnManager) autoSyncMinLoadServerAppid() {
ticker := time.NewTicker(time.Second * 15)
for {
<-ticker.C
k.syncMinLoadServerAppid()
}
}
func (k *KcpConnManager) syncMinLoadServerAppid() {
gsServerAppId, err := k.discoveryClient.GetServerAppId(context.TODO(), &api.GetServerAppIdReq{
ServerType: api.GS,
})
if err != nil {
logger.Error("get gs server appid error: %v", err)
return
}
k.minLoadGsServerAppId = gsServerAppId.AppId
anticheatServerAppId, err := k.discoveryClient.GetServerAppId(context.TODO(), &api.GetServerAppIdReq{
ServerType: api.ANTICHEAT,
})
if err != nil {
return
}
k.minLoadAnticheatServerAppId = anticheatServerAppId.AppId
pathfindingServerAppId, err := k.discoveryClient.GetServerAppId(context.TODO(), &api.GetServerAppIdReq{
ServerType: api.PATHFINDING,
})
if err != nil {
return
}
k.minLoadPathfindingServerAppId = pathfindingServerAppId.AppId
}
func (k *KcpConnManager) autoSyncStopServerInfo() {
ticker := time.NewTicker(time.Minute * 1)
for {
<-ticker.C
k.syncStopServerInfo()
}
}
func (k *KcpConnManager) syncStopServerInfo() {
stopServerInfo, err := k.discoveryClient.GetStopServerInfo(context.TODO(), &api.NullMsg{})
if err != nil {
logger.Error("get stop server info error: %v", err)
return
}
k.stopServerInfo = stopServerInfo
}
func (k *KcpConnManager) autoSyncWhiteList() {
ticker := time.NewTicker(time.Minute * 1)
for {
<-ticker.C
k.syncWhiteList()
}
}
func (k *KcpConnManager) syncWhiteList() {
whiteList, err := k.discoveryClient.GetWhiteList(context.TODO(), &api.NullMsg{})
if err != nil {
logger.Error("get white list error: %v", err)
return
}
k.whiteList = whiteList
}
+16 -28
View File
@@ -502,7 +502,7 @@ func (k *KcpConnManager) doGateLogin(req *proto.GetPlayerTokenReq, session *Sess
}
if account == nil {
// 注册账号与uid关联
getNextUidRsp, err := k.discovery.GetNextUid(context.TODO(), &api.NullMsg{})
getNextUidRsp, err := k.discoveryClient.GetNextUid(context.TODO(), &api.NullMsg{})
if err != nil {
logger.Error("get next uid error: %v, openId: %v", err, req.AccountUid)
return k.loginFailRsp(0, proto.Retcode_RET_SVR_ERROR, false, 0)
@@ -527,13 +527,17 @@ func (k *KcpConnManager) doGateLogin(req *proto.GetPlayerTokenReq, session *Sess
addr := session.conn.RemoteAddr()
addrSplit := strings.Split(addr, ":")
clientIp := addrSplit[0]
stopServerInfo, err := k.discovery.GetStopServerInfo(context.TODO(), &api.GetStopServerInfoReq{ClientIpAddr: clientIp})
if err != nil {
logger.Error("get stop server info error: %v, uid: %v", err, uid)
return k.loginFailRsp(0, proto.Retcode_RET_SVR_ERROR, false, 0)
}
if stopServerInfo.StopServer {
return k.loginFailRsp(uid, proto.Retcode_RET_STOP_SERVER, false, 0)
if k.stopServerInfo.StopServer {
isWhiteList := false
for _, ipAddr := range k.whiteList.IpAddrList {
if ipAddr == clientIp {
isWhiteList = true
break
}
}
if !isWhiteList {
return k.loginFailRsp(uid, proto.Retcode_RET_STOP_SERVER, false, 0)
}
}
clientConnNum := atomic.LoadInt32(&CLIENT_CONN_NUM)
if clientConnNum > MaxClientConnNumLimit {
@@ -595,28 +599,12 @@ func (k *KcpConnManager) doGateLogin(req *proto.GetPlayerTokenReq, session *Sess
k.SetSession(session, session.sessionId, session.userId)
k.createSessionChan <- session
// 绑定各个服务器appid
gsServerAppId, err := k.discovery.GetServerAppId(context.TODO(), &api.GetServerAppIdReq{
ServerType: api.GS,
})
if err != nil {
logger.Error("get gs server appid error: %v, uid: %v", err, uid)
if k.minLoadGsServerAppId == "" {
return k.loginFailRsp(0, proto.Retcode_RET_SVR_ERROR, false, 0)
}
session.gsServerAppId = gsServerAppId.AppId
anticheatServerAppId, err := k.discovery.GetServerAppId(context.TODO(), &api.GetServerAppIdReq{
ServerType: api.ANTICHEAT,
})
if err != nil {
logger.Error("get anticheat server appid error: %v, uid: %v", err, uid)
}
session.anticheatServerAppId = anticheatServerAppId.AppId
pathfindingServerAppId, err := k.discovery.GetServerAppId(context.TODO(), &api.GetServerAppIdReq{
ServerType: api.PATHFINDING,
})
if err != nil {
logger.Error("get pathfinding server appid error: %v, uid: %v", err, uid)
}
session.pathfindingServerAppId = pathfindingServerAppId.AppId
session.gsServerAppId = k.minLoadGsServerAppId
session.anticheatServerAppId = k.minLoadAnticheatServerAppId
session.pathfindingServerAppId = k.minLoadPathfindingServerAppId
logger.Debug("session gs appid: %v, uid: %v", session.gsServerAppId, uid)
logger.Debug("session anticheat appid: %v, uid: %v", session.anticheatServerAppId, uid)
logger.Debug("session pathfinding appid: %v, uid: %v", session.pathfindingServerAppId, uid)
+1
View File
@@ -62,6 +62,7 @@ func (c *Controller) registerRouter() {
engine.GET("/server/white/list", c.serverWhiteList)
engine.POST("/server/white/add", c.serverWhiteAdd)
engine.POST("/server/white/del", c.serverWhiteDel)
engine.POST("/server/dispatch/cancel", c.serverDispatchCancel)
port := config.GetConfig().HttpPort
addr := ":" + strconv.Itoa(int(port))
err := engine.Run(addr)
+23 -1
View File
@@ -10,7 +10,7 @@ import (
)
func (c *Controller) serverStopState(ctx *gin.Context) {
stopServerInfo, err := c.discoveryClient.GetStopServerInfo(ctx.Request.Context(), &api.GetStopServerInfoReq{ClientIpAddr: ""})
stopServerInfo, err := c.discoveryClient.GetStopServerInfo(ctx.Request.Context(), &api.NullMsg{})
if err != nil {
logger.Error("get stop server info error: %v", err)
ctx.JSON(http.StatusOK, &CommonRsp{Code: -1, Msg: "", Data: err})
@@ -100,3 +100,25 @@ func (c *Controller) serverWhiteDel(ctx *gin.Context) {
}
ctx.JSON(http.StatusOK, &CommonRsp{Code: 0, Msg: "", Data: nil})
}
type ServerDispatchCancel struct {
AppVersion string `json:"app_version"`
}
func (c *Controller) serverDispatchCancel(ctx *gin.Context) {
req := new(ServerDispatchCancel)
err := ctx.ShouldBindJSON(req)
if err != nil {
ctx.JSON(http.StatusOK, &CommonRsp{Code: -1, Msg: "", Data: err})
return
}
_, err = c.discoveryClient.ServerDispatchCancel(ctx.Request.Context(), &api.ServerDispatchCancelReq{
AppVersion: req.AppVersion,
})
if err != nil {
logger.Error("server dispatch cancel error: %v", err)
ctx.JSON(http.StatusOK, &CommonRsp{Code: -1, Msg: "", Data: err})
return
}
ctx.JSON(http.StatusOK, &CommonRsp{Code: 0, Msg: "", Data: nil})
}
+2
View File
@@ -23,6 +23,7 @@ import (
)
var APPID string
var APPVERSION string
var GSID uint32
func Run(ctx context.Context, configFile string) error {
@@ -37,6 +38,7 @@ func Run(ctx context.Context, configFile string) error {
// 注册到节点服务器
rsp, err := discoveryClient.RegisterServer(context.TODO(), &api.RegisterServerReq{
ServerType: api.GS,
AppVersion: APPVERSION,
})
if err != nil {
return err
+11 -8
View File
@@ -25,7 +25,7 @@ service Discovery {
// 获取全服玩家GS在线列表
rpc GetGlobalGsOnlineMap (NullMsg) returns (GlobalGsOnlineMap) {}
// 获取停服维护信息
rpc GetStopServerInfo (GetStopServerInfoReq) returns (StopServerInfo) {}
rpc GetStopServerInfo (NullMsg) returns (StopServerInfo) {}
// 修改停服维护信息
rpc SetStopServerInfo (StopServerInfo) returns (NullMsg) {}
// 获取停服维护白名单
@@ -34,6 +34,8 @@ service Discovery {
rpc SetWhiteList (SetWhiteListReq) returns (NullMsg) {}
// 获取下一个自增uid
rpc GetNextUid (NullMsg) returns (GetNextUidRsp) {}
// 取消调度指定app版本的所有服务器
rpc ServerDispatchCancel (ServerDispatchCancelReq) returns (NullMsg) {}
}
message NullMsg {
@@ -49,8 +51,9 @@ message GetServerAppIdRsp {
message RegisterServerReq {
string server_type = 1;
GateServerAddr gate_server_addr = 2;
repeated string version = 3;
string app_version = 2;
GateServerAddr gate_server_addr = 3;
repeated string game_version_list = 4;
}
message RegisterServerRsp {
@@ -70,7 +73,7 @@ message KeepaliveServerReq {
}
message GetGateServerAddrReq {
string version = 1;
string game_version = 1;
}
message GetMainGameServerAppIdRsp {
@@ -102,10 +105,6 @@ message GlobalGsOnlineMap {
map<uint32, string> online_map = 1;
}
message GetStopServerInfoReq {
string client_ip_addr = 1;
}
message StopServerInfo {
bool stop_server = 1;
uint32 start_time = 2;
@@ -124,3 +123,7 @@ message SetWhiteListReq {
message GetNextUidRsp {
uint32 uid = 1;
}
message ServerDispatchCancelReq {
string app_version = 1;
}
+52 -15
View File
@@ -2,6 +2,7 @@ package dao
import (
"context"
"errors"
"go.mongodb.org/mongo-driver/bson"
"go.mongodb.org/mongo-driver/bson/primitive"
@@ -10,14 +11,12 @@ import (
type Region struct {
ID primitive.ObjectID `bson:"_id,omitempty"`
RegionId uint32 `bson:"region_id"`
Ec2bData []byte `bson:"ec2b_data"`
NextUid uint32 `bson:"next_uid"`
}
func (d *Dao) InsertRegion(region *Region) error {
db := d.db.Collection("region")
region.RegionId = 1
_, err := db.InsertOne(context.TODO(), region)
if err != nil {
return err
@@ -25,21 +24,11 @@ func (d *Dao) InsertRegion(region *Region) error {
return nil
}
func (d *Dao) DeleteRegion() error {
db := d.db.Collection("region")
_, err := db.DeleteOne(context.TODO(), bson.D{{"region_id", 1}})
if err != nil {
return err
}
return nil
}
func (d *Dao) UpdateRegion(region *Region) error {
db := d.db.Collection("region")
region.RegionId = 1
_, err := db.UpdateMany(
context.TODO(),
bson.D{{"region_id", 1}},
bson.D{},
bson.D{{"$set", region}},
)
if err != nil {
@@ -52,12 +41,12 @@ func (d *Dao) QueryRegion() (*Region, error) {
db := d.db.Collection("region")
result := db.FindOne(
context.TODO(),
bson.D{{"region_id", 1}},
bson.D{},
)
region := new(Region)
err := result.Decode(region)
if err != nil {
if err == mongo.ErrNoDocuments {
if errors.Is(err, mongo.ErrNoDocuments) {
return nil, nil
} else {
return nil, err
@@ -65,3 +54,51 @@ func (d *Dao) QueryRegion() (*Region, error) {
}
return region, nil
}
type StopServerInfo struct {
ID primitive.ObjectID `bson:"_id,omitempty"`
StopServer bool `bson:"stop_server"`
StartTime uint32 `bson:"start_time"`
EndTime uint32 `bson:"end_time"`
IpAddrWhiteList []string `bson:"ip_addr_white_list"`
}
func (d *Dao) InsertStopServerInfo(stopServerInfo *StopServerInfo) error {
db := d.db.Collection("stop_server_info")
_, err := db.InsertOne(context.TODO(), stopServerInfo)
if err != nil {
return err
}
return nil
}
func (d *Dao) UpdateStopServerInfo(stopServerInfo *StopServerInfo) error {
db := d.db.Collection("stop_server_info")
_, err := db.UpdateMany(
context.TODO(),
bson.D{},
bson.D{{"$set", stopServerInfo}},
)
if err != nil {
return err
}
return nil
}
func (d *Dao) QueryStopServerInfo() (*StopServerInfo, error) {
db := d.db.Collection("stop_server_info")
result := db.FindOne(
context.TODO(),
bson.D{},
)
stopServerInfo := new(StopServerInfo)
err := result.Decode(stopServerInfo)
if err != nil {
if errors.Is(err, mongo.ErrNoDocuments) {
return nil, nil
} else {
return nil, err
}
}
return stopServerInfo, nil
}
+90 -28
View File
@@ -4,7 +4,6 @@ import (
"context"
"errors"
"math"
"sort"
"strings"
"sync"
"sync/atomic"
@@ -28,14 +27,16 @@ var _ api.DiscoveryNATSRPCServer = (*DiscoveryService)(nil)
type ServerInstance struct {
serverType string // 服务器类型
appId string // appid
appVersion string // app版本
gateServerKcpAddr string // 网关kcp地址
gateServerKcpPort uint32 // 网关kcp端口
gateServerMqAddr string // 网关tcp直连消息队列地址
gateServerMqPort uint32 // 网关tcp直连消息队列端口
version []string // 网关支持的客户端协议版本
gameVersionList []string // 网关支持的客户端协议版本
lastAliveTime int64 // 最后保活时间
gsId uint32 // 游戏服务器编号
loadCount uint32 // 负载数
dispatchCancel bool // 是否取消调度
}
// StopServerInfo 停服信息
@@ -93,12 +94,34 @@ func NewDiscoveryService(db *dao.Dao, messageQueue *mq.MessageQueue) (*Discovery
r.serverInstanceMap[api.DISPATCH] = new(sync.Map)
r.serverAppIdMap = new(sync.Map)
r.globalGsOnlineMap = new(sync.Map)
stopServerInfo, err := r.db.QueryStopServerInfo()
if err != nil {
logger.Error("load stop server info from db error: %v", err)
return nil, err
}
if stopServerInfo == nil {
logger.Info("init stop server info")
stopServerInfo = &dao.StopServerInfo{
StopServer: true,
StartTime: uint32(time.Now().Unix()),
EndTime: uint32(time.Now().AddDate(10, 0, 0).Unix()),
IpAddrWhiteList: make([]string, 0),
}
err := r.db.InsertStopServerInfo(stopServerInfo)
if err != nil {
logger.Error("save stop server info to db error: %v", err)
return nil, err
}
}
r.stopServerInfo = &StopServerInfo{
stopServer: false,
startTime: 0,
endTime: 0,
stopServer: stopServerInfo.StopServer,
startTime: stopServerInfo.StartTime,
endTime: stopServerInfo.EndTime,
ipAddrWhiteList: make(map[string]struct{}),
}
for _, ipAddr := range stopServerInfo.IpAddrWhiteList {
r.stopServerInfo.ipAddrWhiteList[ipAddr] = struct{}{}
}
r.messageQueue = messageQueue
go r.removeDeadServer()
go r.broadcastReceiver()
@@ -113,7 +136,20 @@ func (s *DiscoveryService) close() {
err := s.db.UpdateRegion(region)
if err != nil {
logger.Error("save region to db error: %v", err)
return
}
ipAddrWhiteList := make([]string, 0)
for ipAddr := range s.stopServerInfo.ipAddrWhiteList {
ipAddrWhiteList = append(ipAddrWhiteList, ipAddr)
}
stopServerInfo := &dao.StopServerInfo{
StopServer: s.stopServerInfo.stopServer,
StartTime: s.stopServerInfo.startTime,
EndTime: s.stopServerInfo.endTime,
IpAddrWhiteList: ipAddrWhiteList,
}
err = s.db.UpdateStopServerInfo(stopServerInfo)
if err != nil {
logger.Error("save stop server info to db error: %v", err)
}
}
@@ -155,10 +191,12 @@ func (s *DiscoveryService) RegisterServer(ctx context.Context, req *api.Register
}
}
inst := &ServerInstance{
serverType: req.ServerType,
appId: appId,
lastAliveTime: time.Now().Unix(),
loadCount: 0,
serverType: req.ServerType,
appId: appId,
appVersion: req.AppVersion,
lastAliveTime: time.Now().Unix(),
loadCount: 0,
dispatchCancel: false,
}
if req.ServerType == api.GATE {
logger.Info("register new gate server, ip: %v, port: %v", req.GateServerAddr.KcpAddr, req.GateServerAddr.KcpPort)
@@ -166,7 +204,7 @@ func (s *DiscoveryService) RegisterServer(ctx context.Context, req *api.Register
inst.gateServerKcpPort = req.GateServerAddr.KcpPort
inst.gateServerMqAddr = req.GateServerAddr.MqAddr
inst.gateServerMqPort = req.GateServerAddr.MqPort
inst.version = req.Version
inst.gameVersionList = req.GameVersionList
}
instMap.Store(appId, inst)
logger.Info("new server appid is: %v", appId)
@@ -232,6 +270,7 @@ func (s *DiscoveryService) KeepaliveServer(ctx context.Context, req *api.Keepali
serverInstance := inst.(*ServerInstance)
serverInstance.lastAliveTime = time.Now().Unix()
serverInstance.loadCount = req.LoadCount
logger.Debug("server instance: %+v", serverInstance)
return &api.NullMsg{}, nil
}
@@ -251,6 +290,9 @@ func (s *DiscoveryService) GetServerAppId(ctx context.Context, req *api.GetServe
} else {
inst = s.getRandomServerInstance(instMap)
}
if inst == nil {
return nil, errors.New("no server found")
}
logger.Debug("get server appid is: %v", inst.appId)
return &api.GetServerAppIdRsp{
AppId: inst.appId,
@@ -278,8 +320,8 @@ func (s *DiscoveryService) GetGateServerAddr(ctx context.Context, req *api.GetGa
versionInstMap := sync.Map{}
instMap.Range(func(key, value any) bool {
serverInstance := value.(*ServerInstance)
for _, version := range serverInstance.version {
if version == req.Version {
for _, gameVersion := range serverInstance.gameVersionList {
if gameVersion == req.GameVersion {
versionInstMap.Store(key, serverInstance)
return true
}
@@ -290,6 +332,9 @@ func (s *DiscoveryService) GetGateServerAddr(ctx context.Context, req *api.GetGa
return nil, errors.New("no gate server found")
}
inst := s.getMinLoadServerInstance(&versionInstMap)
if inst == nil {
return nil, errors.New("no gate server found")
}
logger.Debug("get gate server addr is, ip: %v, port: %v", inst.gateServerKcpAddr, inst.gateServerKcpPort)
return &api.GateServerAddr{
KcpAddr: inst.gateServerKcpAddr,
@@ -363,14 +408,9 @@ func (s *DiscoveryService) GetGlobalGsOnlineMap(ctx context.Context, req *api.Nu
}
// GetStopServerInfo 获取停服维护信息
func (s *DiscoveryService) GetStopServerInfo(ctx context.Context, req *api.GetStopServerInfoReq) (*api.StopServerInfo, error) {
stopServer := s.stopServerInfo.stopServer
_, exist := s.stopServerInfo.ipAddrWhiteList[req.ClientIpAddr]
if exist {
stopServer = false
}
func (s *DiscoveryService) GetStopServerInfo(ctx context.Context, req *api.NullMsg) (*api.StopServerInfo, error) {
return &api.StopServerInfo{
StopServer: stopServer,
StopServer: s.stopServerInfo.stopServer,
StartTime: s.stopServerInfo.startTime,
EndTime: s.stopServerInfo.endTime,
}, nil
@@ -416,15 +456,33 @@ func (s *DiscoveryService) GetNextUid(ctx context.Context, req *api.NullMsg) (*a
}, nil
}
// ServerDispatchCancel 取消调度指定app版本的所有服务器
func (s *DiscoveryService) ServerDispatchCancel(ctx context.Context, req *api.ServerDispatchCancelReq) (*api.NullMsg, error) {
for _, instMap := range s.serverInstanceMap {
instMap.Range(func(appid, inst any) bool {
serverInstance := inst.(*ServerInstance)
if serverInstance.appVersion == req.AppVersion {
serverInstance.dispatchCancel = true
}
return true
})
}
return &api.NullMsg{}, nil
}
func (s *DiscoveryService) getRandomServerInstance(instMap *sync.Map) *ServerInstance {
instList := make([]*ServerInstance, 0)
instMap.Range(func(key, value any) bool {
instList = append(instList, value.(*ServerInstance))
serverInstance := value.(*ServerInstance)
if serverInstance.dispatchCancel {
return true
}
instList = append(instList, serverInstance)
return true
})
sort.Slice(instList, func(i, j int) bool {
return instList[i].appId < instList[j].appId
})
if len(instList) == 0 {
return nil
}
index := random.GetRandomInt32(0, int32(len(instList)-1))
inst := instList[index]
return inst
@@ -433,12 +491,16 @@ func (s *DiscoveryService) getRandomServerInstance(instMap *sync.Map) *ServerIns
func (s *DiscoveryService) getMinLoadServerInstance(instMap *sync.Map) *ServerInstance {
instList := make([]*ServerInstance, 0)
instMap.Range(func(key, value any) bool {
instList = append(instList, value.(*ServerInstance))
serverInstance := value.(*ServerInstance)
if serverInstance.dispatchCancel {
return true
}
instList = append(instList, serverInstance)
return true
})
sort.Slice(instList, func(i, j int) bool {
return instList[i].appId < instList[j].appId
})
if len(instList) == 0 {
return nil
}
minLoadInstIndex := 0
minLoadInstCount := math.MaxUint32
for index, inst := range instList {
+2
View File
@@ -17,6 +17,7 @@ import (
)
var APPID string
var APPVERSION string
func Run(ctx context.Context, configFile string) error {
config.InitConfig(configFile)
@@ -30,6 +31,7 @@ func Run(ctx context.Context, configFile string) error {
// 注册到节点服务器
rsp, err := discoveryClient.RegisterServer(context.TODO(), &api.RegisterServerReq{
ServerType: api.PATHFINDING,
AppVersion: APPVERSION,
})
if err != nil {
return err
+2
View File
@@ -32,6 +32,7 @@ import (
)
var APPID string
var APPVERSION string
func Run(ctx context.Context, configFile string) error {
config.InitConfig(configFile)
@@ -52,6 +53,7 @@ func Run(ctx context.Context, configFile string) error {
// 注册到节点服务器
rsp, err := discoveryClient.RegisterServer(context.TODO(), &api.RegisterServerReq{
ServerType: api.ROBOT,
AppVersion: APPVERSION,
})
if err != nil {
logger.Error("register to node server error: %v", err)