-
Notifications
You must be signed in to change notification settings - Fork 4
/
main.go
165 lines (153 loc) · 4.33 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
package main
import (
"bufio"
"context"
"flag"
"fmt"
"github.com/fish-tennis/gentity"
"github.com/fish-tennis/gnet"
"github.com/fish-tennis/gserver/gameserver"
"github.com/fish-tennis/gserver/gateserver"
"github.com/fish-tennis/gserver/internal"
"github.com/fish-tennis/gserver/logger"
"github.com/fish-tennis/gserver/loginserver"
"gopkg.in/natefinch/lumberjack.v2"
"log/slog"
"math/rand"
"os"
"os/exec"
"os/signal"
"path/filepath"
"runtime"
"strings"
"syscall"
"time"
)
func main() {
defer func() {
if err := recover(); err != nil {
panic(err)
}
}()
isDaemon := false
configFile := ""
// 配置文件名格式: serverType_xxx.json
flag.StringVar(&configFile, "conf", "", "server's config file")
flag.BoolVar(&isDaemon, "d", false, "daemon mode")
flag.Parse()
if isDaemon {
daemon()
return
}
runtime.GOMAXPROCS(runtime.NumCPU())
rand.Seed(time.Now().UnixNano())
// 根据命令行参数 创建不同的服务器实例
baseFileName := filepath.Base(configFile) // login_test.yaml
baseFileName = strings.TrimSuffix(baseFileName, filepath.Ext(baseFileName)) // login_test
serverType := getServerTypeFromConfigFile(configFile) // login
initLog(baseFileName, !isDaemon)
ctx, cancel := context.WithCancel(context.Background())
server := createServer(ctx, serverType, configFile)
gentity.SetApplication(server)
// 服务器初始化
if !server.Init(ctx, configFile) {
panic("server init error")
}
// 服务器运行
server.Run(ctx)
// 监听系统的kill信号
signalKillNotify := make(chan os.Signal, 1)
signal.Notify(signalKillNotify, os.Interrupt, os.Kill, syscall.SIGTERM)
if !isDaemon {
// 加一个控制台输入,以方便调试
go func() {
consoleReader := bufio.NewReader(os.Stdin)
for {
lineBytes, _, _ := consoleReader.ReadLine()
line := strings.ToLower(string(lineBytes))
logger.Info("line:%v", line)
if line == "close" || line == "exit" {
logger.Info("kill by console input")
// 模拟一个kill信号,以方便测试服务器退出流程
signalKillNotify <- os.Kill
return
}
}
}()
}
// 阻塞等待系统关闭信号
logger.Info("wait for kill signal")
select {
case <-signalKillNotify:
logger.Info("signalKillNotify, cancel ctx")
// 通知所有协程关闭,所有监听<-ctx.Done()的地方会收到通知
cancel()
break
}
// 清理
server.Exit()
}
func daemon() {
args := os.Args[1:]
for i := 0; i < len(args); i++ {
if args[i] == "-d=true" {
args[i] = "-d=false"
break
}
}
cmd := exec.Command(os.Args[0], args...)
cmd.Start()
fmt.Println("[PID]", cmd.Process.Pid)
os.Exit(0)
}
func initLog(logFileName string, useStdOutput bool) {
gnet.SetLogger(logger.GetLogger(), gnet.DebugLevel)
gentity.SetLogger(logger.GetLogger(), gnet.DebugLevel)
os.Mkdir("log", 0750)
// 日志轮转与切割
fileLogger := &lumberjack.Logger{
Filename: fmt.Sprintf("log/%v.log", logFileName),
MaxSize: 10,
MaxBackups: 100,
MaxAge: 7,
Compress: false,
LocalTime: true,
}
// 建议使用slog
debugLevel := &slog.LevelVar{}
debugLevel.Set(slog.LevelDebug)
slog.SetDefault(slog.New(logger.NewJsonHandlerWithStdOutput(fileLogger, &slog.HandlerOptions{
AddSource: true,
Level: debugLevel,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if a.Key == slog.SourceKey {
source := a.Value.Any().(*slog.Source)
source.Function = ""
source.File = logger.GetShortFileName(source.File)
}
return a
},
}, useStdOutput)))
}
// 从配置文件名解析出服务器类型
func getServerTypeFromConfigFile(configFile string) string {
baseFileName := filepath.Base(configFile)
idx := strings.Index(baseFileName, "_") // login_test.yaml
if idx > 0 {
return baseFileName[0:idx]
}
idx = strings.Index(baseFileName, ".") // login.yaml
return baseFileName[0:idx]
}
// 创建相应类型的服务器
func createServer(ctx context.Context, serverType, configFile string) gentity.Application {
switch strings.ToLower(serverType) {
case strings.ToLower(internal.ServerType_Gate):
return gateserver.NewGateServer(ctx, configFile)
case strings.ToLower(internal.ServerType_Login):
return loginserver.NewLoginServer(ctx, configFile)
case strings.ToLower(internal.ServerType_Game):
return gameserver.NewGameServer(ctx, configFile)
}
panic("err server type")
}