Skip to content

Commit

Permalink
game graceful stop on k8s
Browse files Browse the repository at this point in the history
  • Loading branch information
panshiqu committed Aug 30, 2024
1 parent 55e7603 commit 4c28839
Show file tree
Hide file tree
Showing 5 changed files with 31 additions and 9 deletions.
16 changes: 10 additions & 6 deletions game_server/frame/manager.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import (
"fmt"
"log/slog"
"sync"
"sync/atomic"

"github.com/panshiqu/golang/utils"
"github.com/panshiqu/server/game_server/define"
Expand All @@ -15,7 +16,7 @@ var rMtx sync.Mutex
var rooms map[int64]*Room

// 停服后不创建房间
var stopped bool
var stopped atomic.Bool

// 等待所有房间协程
var wgRoom sync.WaitGroup
Expand All @@ -38,7 +39,7 @@ func NewRoom(id int64, name string) (*Room, error) {
return r, nil
}

if stopped {
if stopped.Load() {
return nil, define.ErrServerStopped
}

Expand All @@ -63,16 +64,19 @@ func DelRoom(id int64) {
}

func Stop() {
stopped.Store(true)

wgRoom.Wait()
}

func Disband() {
rMtx.Lock()
stopped = true
defer rMtx.Unlock()

// 解散现有房间
for _, v := range rooms {
v.chDisband <- define.DisbandSystem
}
rMtx.Unlock()

wgRoom.Wait()
}

func NewUser(id int64) *User {
Expand Down
6 changes: 6 additions & 0 deletions game_server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,12 @@ func main() {
go func() {
utils.WaitSignal(os.Interrupt, syscall.SIGTERM)

go func() {
utils.WaitSignal(os.Interrupt, syscall.SIGTERM)

frame.Disband()
}()

frame.Stop()

s.GracefulStop()
Expand Down
2 changes: 1 addition & 1 deletion gate_server/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -202,7 +202,7 @@ func main() {
var rwmutex sync.RWMutex

// 用户-会话,支持对已连接即订阅的用户推送消息譬如充值
// 用户多个设备连接保留所有会话,遍历关闭从而优雅退出
// 用户多个设备连接保留所有会话,遍历关闭从而优雅停服
var sessions map[int64][]*Session

func init() {
Expand Down
14 changes: 13 additions & 1 deletion k8s/dice.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,23 @@ spec:
labels:
game: dice
spec:
terminationGracePeriodSeconds: 150
containers:
- image: panshiqu/game_server:1.0
- image: panshiqu/game_server:1.2
name: game
ports:
- containerPort: 60001
lifecycle:
preStop:
exec:
# killall发送SIGTERM,开始计时
# 等到A:2分钟(sleep 120)系统发送SIGTERM
# 等到B:2分半(terminationGracePeriodSeconds)系统发送SIGKILL
# 若B远小于A,B时发送SIGTERM,B+2时发送SIGKILL,宽限延长2秒
command:
- sh
- -c
- killall server && sleep 120
volumeMounts:
- mountPath: /work
name: work
Expand Down
2 changes: 1 addition & 1 deletion k8s/gate.yaml
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ spec:
app: gate
spec:
containers:
- image: panshiqu/gate_server:1.0
- image: panshiqu/gate_server:1.2
name: gate
env:
# kubectl create secret generic jwt --from-literal=key=ZGVmYXVsdF9rZXk=
Expand Down

0 comments on commit 4c28839

Please sign in to comment.