forked from topfreegames/pitaya
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapp.go
328 lines (284 loc) · 8.97 KB
/
app.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
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
// Copyright (c) nano Author and TFG Co. All Rights Reserved.
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
package pitaya
import (
"fmt"
"math/rand"
"os"
"os/signal"
"reflect"
"syscall"
"time"
"github.com/google/uuid"
"github.com/topfreegames/pitaya/acceptor"
"github.com/topfreegames/pitaya/cluster"
"github.com/topfreegames/pitaya/component"
"github.com/topfreegames/pitaya/internal/codec"
"github.com/topfreegames/pitaya/internal/message"
"github.com/topfreegames/pitaya/logger"
"github.com/topfreegames/pitaya/module"
"github.com/topfreegames/pitaya/protos"
"github.com/topfreegames/pitaya/route"
"github.com/topfreegames/pitaya/serialize"
"github.com/topfreegames/pitaya/serialize/protobuf"
"github.com/topfreegames/pitaya/session"
)
// App is the base app struct
type App struct {
server *cluster.Server
debug bool
startAt time.Time
dieChan chan bool
acceptors []acceptor.Acceptor
heartbeat time.Duration
packetDecoder codec.PacketDecoder
packetEncoder codec.PacketEncoder
serializer serialize.Serializer
serviceDiscovery cluster.ServiceDiscovery
rpcServer cluster.RPCServer
rpcClient cluster.RPCClient
onSessionBind func(*session.Session)
}
var (
app = &App{
server: &cluster.Server{
ID: uuid.New().String(),
Type: "game",
Data: map[string]string{},
Frontend: true,
},
debug: false,
startAt: time.Now(),
dieChan: make(chan bool),
acceptors: []acceptor.Acceptor{},
heartbeat: 30 * time.Second,
packetDecoder: codec.NewPomeloPacketDecoder(),
packetEncoder: codec.NewPomeloPacketEncoder(),
serializer: protobuf.NewSerializer(),
}
log = logger.Log
)
// GetApp gets the app
func GetApp() *App {
return app
}
// AddAcceptor adds a new acceptor to app
func AddAcceptor(ac acceptor.Acceptor) {
app.acceptors = append(app.acceptors, ac)
}
// SetDebug toggles debug on/off
func SetDebug(debug bool) {
app.debug = debug
}
// SetPacketDecoder changes the decoder used to parse messages received
func SetPacketDecoder(d codec.PacketDecoder) {
app.packetDecoder = d
}
// SetPacketEncoder changes the encoder used to package outgoing messages
func SetPacketEncoder(e codec.PacketEncoder) {
app.packetEncoder = e
}
// SetHeartbeatTime sets the heartbeat time
func SetHeartbeatTime(interval time.Duration) {
app.heartbeat = interval
}
// SetRPCServer to be used
func SetRPCServer(s cluster.RPCServer) {
//TODO
app.rpcServer = s
if reflect.TypeOf(s) == reflect.TypeOf(&cluster.NatsRPCServer{}) {
session.SetOnSessionBind(func(s *session.Session) {
app.rpcServer.(*cluster.NatsRPCServer).SubscribeToUserMessages(s.UID())
})
}
}
// SetRPCClient to be used
func SetRPCClient(s cluster.RPCClient) {
app.rpcClient = s
}
// SetServiceDiscoveryClient to be used
func SetServiceDiscoveryClient(s cluster.ServiceDiscovery) {
app.serviceDiscovery = s
}
// SetSerializer customize application serializer, which automatically Marshal
// and UnMarshal handler payload
func SetSerializer(seri serialize.Serializer) {
app.serializer = seri
}
// SetServerType sets the server type
// TODO need to specify in start
func SetServerType(t string) {
app.server.Type = t
}
// SetServerData sets the server data that will be broadcasted using service discovery to other servers
// TODO need to specify in start
func SetServerData(data map[string]string) {
app.server.Data = data
}
func startDefaultSD() {
// initialize default service discovery
// TODO remove this, force specifying
var err error
app.serviceDiscovery, err = cluster.NewEtcdServiceDiscovery(
[]string{"localhost:2379"},
time.Duration(5)*time.Second,
"pitaya/",
time.Duration(20)*time.Second,
time.Duration(60)*time.Second,
time.Duration(120)*time.Second,
app.server,
)
if err != nil {
log.Fatalf("error starting cluster service discovery component: %s", err.Error())
}
}
func startDefaultRPCServer() {
// initialize default rpc server
// TODO remove this, force specifying
var err error
SetRPCServer(cluster.NewNatsRPCServer(
"nats://localhost:4222",
app.server,
))
if err != nil {
log.Fatalf("error starting cluster rpc server component: %s", err.Error())
}
}
func startDefaultRPCClient() {
// initialize default rpc client
// TODO remove this, force specifying
var err error
app.rpcClient = cluster.NewNatsRPCClient(
"nats://localhost:4222",
app.server,
)
if err != nil {
log.Fatalf("error starting cluster rpc client component: %s", err.Error())
}
}
// Start starts the app
// TODO fix non cluster mode
func Start(isFrontend bool) {
app.server.Frontend = isFrontend
if app.serviceDiscovery == nil {
log.Warn("creating default service discovery because cluster mode is enabled, if you want to specify yours, use pitaya.SetServiceDiscoveryClient")
startDefaultSD()
}
if app.rpcServer == nil {
log.Warn("creating default rpc server because cluster mode is enabled, if you want to specify yours, use pitaya.SetRPCServer")
startDefaultRPCServer()
}
if app.rpcClient == nil {
log.Warn("creating default rpc client because cluster mode is enabled, if you want to specify yours, use pitaya.SetRPCClient")
startDefaultRPCClient()
RegisterModule(app.serviceDiscovery, "serviceDiscovery")
RegisterModule(app.rpcServer, "rpcServer")
RegisterModule(app.rpcClient, "rpcClient")
}
listen()
sg := make(chan os.Signal)
signal.Notify(sg, syscall.SIGINT, syscall.SIGQUIT, syscall.SIGKILL)
// stop server
select {
case <-app.dieChan:
log.Warn("The app will shutdown in a few seconds")
case s := <-sg:
log.Warn("got signal", s)
}
log.Warn("server is stopping...")
shutdownModules()
// shutdown all components registered by application, that
// call by reverse order against register
shutdownComponents()
}
func listen() {
hbdEncode()
startupComponents()
// create global ticker instance, timer precision could be customized
// by SetTimerPrecision
globalTicker = time.NewTicker(timerPrecision)
log.Infof("starting server %s:%s", app.server.Type, app.server.ID)
// startup logic dispatcher
go handler.dispatch()
for _, acc := range app.acceptors {
a := acc
// gets connections from every acceptor and tell handlerservice to handle them
go func() {
for conn := range a.GetConnChan() {
go handler.handle(conn)
}
}()
go func() {
a.ListenAndServe()
}()
log.Infof("listening with acceptor %s on addr %s", reflect.TypeOf(a), a.GetAddr())
}
startModules()
// this handles remote messages
// TODO probably this shouldnt be here :/
if app.rpcServer != nil {
// TODO config concurrency, should this be done this way?
processMsgConcurrency := 100
for i := 0; i < processMsgConcurrency; i++ {
go processRemoteMessages(i)
// TODO: use same parellelism?
go processUserPush()
}
}
}
// TODO own file?
func remoteCall(rpcType protos.RPCType, route *route.Route, session *session.Session, msg *message.Message) ([]byte, error) {
svType := route.SvType
//TODO this logic should be elsewhere, routing should be changeable
serversOfType, err := app.serviceDiscovery.GetServersByType(svType)
if err != nil {
return nil, err
}
s := rand.NewSource(time.Now().Unix())
r := rand.New(s)
server := serversOfType[r.Intn(len(serversOfType))]
res, err := app.rpcClient.Call(rpcType, route, session, msg, server)
if err != nil {
return nil, err
}
return res, err
}
// SetDictionary set routes map, TODO(warning): set dictionary in runtime would be a dangerous operation!!!!!!
func SetDictionary(dict map[string]uint16) {
message.SetDictionary(dict)
}
// Register register a component with options
func Register(c component.Component, options ...component.Option) {
comps = append(comps, regComp{c, options})
}
// RegisterModule register a module
func RegisterModule(m module.Module, name string) error {
if _, ok := modules[name]; ok {
return fmt.Errorf(
"a module names %s was already registered", name,
)
}
modules[name] = m
return nil
}
// Shutdown send a signal to let 'pitaya' shutdown itself.
func Shutdown() {
close(app.dieChan)
}