forked from heroiclabs/nakama
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
289 lines (250 loc) · 10.2 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
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
// Copyright 2018 The Nakama Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package main
import (
"context"
"database/sql"
"flag"
"fmt"
"math/rand"
"net/http"
"net/url"
"os"
"os/signal"
"runtime"
"strings"
"syscall"
"time"
"io/ioutil"
"path/filepath"
"github.com/gofrs/uuid"
"github.com/golang/protobuf/jsonpb"
"github.com/heroiclabs/nakama/ga"
"github.com/heroiclabs/nakama/migrate"
"github.com/heroiclabs/nakama/server"
"github.com/heroiclabs/nakama/social"
_ "github.com/jackc/pgx/stdlib"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
const cookieFilename = ".cookie"
var (
version string = "2.0.0"
commitID string = "dev"
// Shared utility components.
jsonpbMarshaler = &jsonpb.Marshaler{
EnumsAsInts: true,
EmitDefaults: false,
Indent: "",
OrigName: true,
}
jsonpbUnmarshaler = &jsonpb.Unmarshaler{
AllowUnknownFields: false,
}
)
func main() {
semver := fmt.Sprintf("%s+%s", version, commitID)
// Always set default timeout on HTTP client.
http.DefaultClient.Timeout = 1500 * time.Millisecond
// Initialize the global random obj with customs seed.
rand.Seed(time.Now().UnixNano())
tmpLogger := server.NewJSONLogger(os.Stdout, zapcore.InfoLevel, server.JSONFormat)
if len(os.Args) > 1 {
switch os.Args[1] {
case "--version":
fmt.Println(semver)
return
case "migrate":
migrate.Parse(os.Args[2:], tmpLogger)
case "check":
// Parse any command line args to look up runtime path.
// Use full config structure even if not all of its options are available in this command.
config := server.NewConfig(tmpLogger)
var runtimePath string
flags := flag.NewFlagSet("check", flag.ExitOnError)
flags.StringVar(&runtimePath, "runtime.path", filepath.Join(config.GetDataDir(), "modules"), "Path for the server to scan for Lua and Go library files.")
if err := flags.Parse(os.Args[2:]); err != nil {
tmpLogger.Fatal("Could not parse check flags.")
}
config.GetRuntime().Path = runtimePath
if err := server.CheckRuntime(tmpLogger, config); err != nil {
// Errors are already logged in the function above.
os.Exit(1)
}
return
}
}
config := server.ParseArgs(tmpLogger, os.Args)
logger, startupLogger := server.SetupLogging(tmpLogger, config)
configWarnings := server.CheckConfig(logger, config)
startupLogger.Info("Nakama starting")
startupLogger.Info("Node", zap.String("name", config.GetName()), zap.String("version", semver), zap.String("runtime", runtime.Version()), zap.Int("cpu", runtime.NumCPU()), zap.Int("proc", runtime.GOMAXPROCS(0)))
startupLogger.Info("Data directory", zap.String("path", config.GetDataDir()))
startupLogger.Info("Database connections", zap.Strings("dsns", config.GetDatabase().Addresses))
db, dbVersion := dbConnect(startupLogger, config)
startupLogger.Info("Database information", zap.String("version", dbVersion))
// Check migration status and fail fast if the schema has diverged.
migrate.StartupCheck(startupLogger, db)
// Access to social provider integrations.
socialClient := social.NewClient(5 * time.Second)
// Start up server components.
matchmaker := server.NewLocalMatchmaker(startupLogger, config.GetName())
sessionRegistry := server.NewLocalSessionRegistry()
tracker := server.StartLocalTracker(logger, config, sessionRegistry, jsonpbMarshaler)
router := server.NewLocalMessageRouter(sessionRegistry, tracker, jsonpbMarshaler)
leaderboardCache := server.NewLocalLeaderboardCache(logger, startupLogger, db)
leaderboardRankCache := server.NewLocalLeaderboardRankCache(startupLogger, db, config.GetLeaderboard(), leaderboardCache)
leaderboardScheduler := server.NewLocalLeaderboardScheduler(logger, db, leaderboardCache, leaderboardRankCache)
matchRegistry := server.NewLocalMatchRegistry(logger, startupLogger, config, tracker, router, config.GetName())
tracker.SetMatchJoinListener(matchRegistry.Join)
tracker.SetMatchLeaveListener(matchRegistry.Leave)
streamManager := server.NewLocalStreamManager(config, sessionRegistry, tracker)
runtime, err := server.NewRuntime(logger, startupLogger, db, jsonpbMarshaler, jsonpbUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, leaderboardScheduler, sessionRegistry, matchRegistry, tracker, streamManager, router)
if err != nil {
startupLogger.Fatal("Failed initializing runtime modules", zap.Error(err))
}
leaderboardScheduler.Start(runtime)
pipeline := server.NewPipeline(logger, config, db, jsonpbMarshaler, jsonpbUnmarshaler, sessionRegistry, matchRegistry, matchmaker, tracker, router, runtime)
metricsExporter := server.NewMetricsExporter(logger)
metrics := server.NewMetrics(logger, startupLogger, config, metricsExporter)
statusHandler := server.NewLocalStatusHandler(logger, sessionRegistry, matchRegistry, tracker, metricsExporter, config.GetName())
consoleServer := server.StartConsoleServer(logger, startupLogger, db, config, tracker, router, statusHandler, configWarnings, semver)
apiServer := server.StartApiServer(logger, startupLogger, db, jsonpbMarshaler, jsonpbUnmarshaler, config, socialClient, leaderboardCache, leaderboardRankCache, sessionRegistry, matchRegistry, matchmaker, tracker, router, pipeline, runtime)
gaenabled := len(os.Getenv("NAKAMA_TELEMETRY")) < 1
cookie := newOrLoadCookie(config)
const gacode = "UA-89792135-1"
var telemetryClient *http.Client
if gaenabled {
telemetryClient = &http.Client{
Timeout: 1500 * time.Millisecond,
}
runTelemetry(telemetryClient, gacode, cookie)
}
// Respect OS stop signals.
c := make(chan os.Signal, 2)
signal.Notify(c, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
startupLogger.Info("Startup done")
// Wait for a termination signal.
<-c
graceSeconds := config.GetShutdownGraceSec()
// If a shutdown grace period is allowed, prepare a timer.
var timer *time.Timer
timerCh := make(<-chan time.Time, 1)
if graceSeconds != 0 {
timer = time.NewTimer(time.Duration(graceSeconds) * time.Second)
timerCh = timer.C
startupLogger.Info("Shutdown started - use CTRL^C to force stop server", zap.Int("grace_period_sec", graceSeconds))
} else {
// No grace period.
startupLogger.Info("Shutdown started")
}
// Stop any running authoritative matches and do not accept any new ones.
select {
case <-matchRegistry.Stop(graceSeconds):
// Graceful shutdown has completed.
case <-timerCh:
// Timer has expired, terminate matches immediately.
startupLogger.Info("Shutdown grace period expired")
<-matchRegistry.Stop(0)
case <-c:
// A second interrupt has been received.
startupLogger.Info("Skipping graceful shutdown")
<-matchRegistry.Stop(0)
}
if timer != nil {
timer.Stop()
}
// Gracefully stop remaining server components.
apiServer.Stop()
consoleServer.Stop()
metrics.Stop(logger)
leaderboardScheduler.Stop()
tracker.Stop()
sessionRegistry.Stop()
if gaenabled {
_ = ga.SendSessionStop(telemetryClient, gacode, cookie)
}
startupLogger.Info("Shutdown complete")
os.Exit(0)
}
func dbConnect(multiLogger *zap.Logger, config server.Config) (*sql.DB, string) {
rawUrl := fmt.Sprintf("postgresql://%s", config.GetDatabase().Addresses[0])
parsedUrl, err := url.Parse(rawUrl)
if err != nil {
multiLogger.Fatal("Bad database connection URL", zap.Error(err))
}
query := parsedUrl.Query()
if len(query.Get("sslmode")) == 0 {
query.Set("sslmode", "disable")
parsedUrl.RawQuery = query.Encode()
}
if len(parsedUrl.User.Username()) < 1 {
parsedUrl.User = url.User("root")
}
if len(parsedUrl.Path) < 1 {
parsedUrl.Path = "/nakama"
}
multiLogger.Debug("Complete database connection URL", zap.String("raw_url", parsedUrl.String()))
db, err := sql.Open("pgx", parsedUrl.String())
if err != nil {
multiLogger.Fatal("Error connecting to database", zap.Error(err))
}
// Limit the time allowed to ping database and get version to 15 seconds total.
ctx, _ := context.WithTimeout(context.Background(), 15*time.Second)
if err = db.PingContext(ctx); err != nil {
if strings.HasSuffix(err.Error(), "does not exist (SQLSTATE 3D000)") {
multiLogger.Fatal("Database schema not found, run `nakama migrate up`", zap.Error(err))
}
multiLogger.Fatal("Error pinging database", zap.Error(err))
}
db.SetConnMaxLifetime(time.Millisecond * time.Duration(config.GetDatabase().ConnMaxLifetimeMs))
db.SetMaxOpenConns(config.GetDatabase().MaxOpenConns)
db.SetMaxIdleConns(config.GetDatabase().MaxIdleConns)
var dbVersion string
if err = db.QueryRowContext(ctx, "SELECT version()").Scan(&dbVersion); err != nil {
multiLogger.Fatal("Error querying database version", zap.Error(err))
}
return db, dbVersion
}
// Help improve Nakama by sending anonymous usage statistics.
//
// You can disable the telemetry completely before server start by setting the
// environment variable "NAKAMA_TELEMETRY" - i.e. NAKAMA_TELEMETRY=0 nakama
//
// These properties are collected:
// * A unique UUID v4 random identifier which is generated.
// * Version of Nakama being used which includes build metadata.
// * Amount of time the server ran for.
//
// This information is sent via Google Analytics which allows the Nakama team to
// analyze usage patterns and errors in order to help improve the server.
func runTelemetry(httpc *http.Client, gacode string, cookie string) {
if ga.SendSessionStart(httpc, gacode, cookie) != nil {
return
}
if ga.SendEvent(httpc, gacode, cookie, &ga.Event{Ec: "version", Ea: fmt.Sprintf("%s+%s", version, commitID)}) != nil {
return
}
_ = ga.SendEvent(httpc, gacode, cookie, &ga.Event{Ec: "variant", Ea: "nakama"})
}
func newOrLoadCookie(config server.Config) string {
filePath := filepath.FromSlash(config.GetDataDir() + "/" + cookieFilename)
b, err := ioutil.ReadFile(filePath)
cookie := uuid.FromBytesOrNil(b)
if err != nil || cookie == uuid.Nil {
cookie = uuid.Must(uuid.NewV4())
_ = ioutil.WriteFile(filePath, cookie.Bytes(), 0644)
}
return cookie.String()
}