forked from topfreegames/pitaya
-
Notifications
You must be signed in to change notification settings - Fork 0
/
builder.go
321 lines (293 loc) · 10.3 KB
/
builder.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
package pitaya
import (
"github.com/google/uuid"
"github.com/topfreegames/pitaya/v2/acceptor"
"github.com/topfreegames/pitaya/v2/agent"
"github.com/topfreegames/pitaya/v2/cluster"
"github.com/topfreegames/pitaya/v2/config"
"github.com/topfreegames/pitaya/v2/conn/codec"
"github.com/topfreegames/pitaya/v2/conn/message"
"github.com/topfreegames/pitaya/v2/defaultpipelines"
"github.com/topfreegames/pitaya/v2/groups"
"github.com/topfreegames/pitaya/v2/logger"
"github.com/topfreegames/pitaya/v2/metrics"
"github.com/topfreegames/pitaya/v2/metrics/models"
"github.com/topfreegames/pitaya/v2/pipeline"
"github.com/topfreegames/pitaya/v2/router"
"github.com/topfreegames/pitaya/v2/serialize"
"github.com/topfreegames/pitaya/v2/serialize/json"
"github.com/topfreegames/pitaya/v2/service"
"github.com/topfreegames/pitaya/v2/session"
"github.com/topfreegames/pitaya/v2/worker"
)
// Builder holds dependency instances for a pitaya App
type Builder struct {
acceptors []acceptor.Acceptor
Config config.BuilderConfig
DieChan chan bool
PacketDecoder codec.PacketDecoder
PacketEncoder codec.PacketEncoder
MessageEncoder *message.MessagesEncoder
Serializer serialize.Serializer
Router *router.Router
RPCClient cluster.RPCClient
RPCServer cluster.RPCServer
MetricsReporters []metrics.Reporter
Server *cluster.Server
ServerMode ServerMode
ServiceDiscovery cluster.ServiceDiscovery
Groups groups.GroupService
SessionPool session.SessionPool
Worker *worker.Worker
HandlerHooks *pipeline.HandlerHooks
}
// PitayaBuilder Builder interface
type PitayaBuilder interface {
Build() Pitaya
}
// NewBuilderWithConfigs return a builder instance with default dependency instances for a pitaya App
// with configs defined by a config file (config.Config) and default paths (see documentation).
func NewBuilderWithConfigs(
isFrontend bool,
serverType string,
serverMode ServerMode,
serverMetadata map[string]string,
conf *config.Config,
) *Builder {
builderConfig := config.NewBuilderConfig(conf)
customMetrics := config.NewCustomMetricsSpec(conf)
prometheusConfig := config.NewPrometheusConfig(conf)
statsdConfig := config.NewStatsdConfig(conf)
etcdSDConfig := config.NewEtcdServiceDiscoveryConfig(conf)
natsRPCServerConfig := config.NewNatsRPCServerConfig(conf)
natsRPCClientConfig := config.NewNatsRPCClientConfig(conf)
workerConfig := config.NewWorkerConfig(conf)
enqueueOpts := config.NewEnqueueOpts(conf)
groupServiceConfig := config.NewMemoryGroupConfig(conf)
return NewBuilder(
isFrontend,
serverType,
serverMode,
serverMetadata,
*builderConfig,
*customMetrics,
*prometheusConfig,
*statsdConfig,
*etcdSDConfig,
*natsRPCServerConfig,
*natsRPCClientConfig,
*workerConfig,
*enqueueOpts,
*groupServiceConfig,
)
}
// NewDefaultBuilder return a builder instance with default dependency instances for a pitaya App,
// with default configs
func NewDefaultBuilder(isFrontend bool, serverType string, serverMode ServerMode, serverMetadata map[string]string, builderConfig config.BuilderConfig) *Builder {
customMetrics := config.NewDefaultCustomMetricsSpec()
prometheusConfig := config.NewDefaultPrometheusConfig()
statsdConfig := config.NewDefaultStatsdConfig()
etcdSDConfig := config.NewDefaultEtcdServiceDiscoveryConfig()
natsRPCServerConfig := config.NewDefaultNatsRPCServerConfig()
natsRPCClientConfig := config.NewDefaultNatsRPCClientConfig()
workerConfig := config.NewDefaultWorkerConfig()
enqueueOpts := config.NewDefaultEnqueueOpts()
groupServiceConfig := config.NewDefaultMemoryGroupConfig()
return NewBuilder(
isFrontend,
serverType,
serverMode,
serverMetadata,
builderConfig,
*customMetrics,
*prometheusConfig,
*statsdConfig,
*etcdSDConfig,
*natsRPCServerConfig,
*natsRPCClientConfig,
*workerConfig,
*enqueueOpts,
*groupServiceConfig,
)
}
// NewBuilder return a builder instance with default dependency instances for a pitaya App,
// with configs explicitly defined
func NewBuilder(isFrontend bool,
serverType string,
serverMode ServerMode,
serverMetadata map[string]string,
config config.BuilderConfig,
customMetrics models.CustomMetricsSpec,
prometheusConfig config.PrometheusConfig,
statsdConfig config.StatsdConfig,
etcdSDConfig config.EtcdServiceDiscoveryConfig,
natsRPCServerConfig config.NatsRPCServerConfig,
natsRPCClientConfig config.NatsRPCClientConfig,
workerConfig config.WorkerConfig,
enqueueOpts config.EnqueueOpts,
groupServiceConfig config.MemoryGroupConfig,
) *Builder {
server := cluster.NewServer(uuid.New().String(), serverType, isFrontend, serverMetadata)
dieChan := make(chan bool)
metricsReporters := []metrics.Reporter{}
if config.Metrics.Prometheus.Enabled {
metricsReporters = addDefaultPrometheus(prometheusConfig, customMetrics, metricsReporters, serverType)
}
if config.Metrics.Statsd.Enabled {
metricsReporters = addDefaultStatsd(statsdConfig, metricsReporters, serverType)
}
handlerHooks := pipeline.NewHandlerHooks()
if config.DefaultPipelines.StructValidation.Enabled {
configureDefaultPipelines(handlerHooks)
}
sessionPool := session.NewSessionPool()
var serviceDiscovery cluster.ServiceDiscovery
var rpcServer cluster.RPCServer
var rpcClient cluster.RPCClient
if serverMode == Cluster {
var err error
serviceDiscovery, err = cluster.NewEtcdServiceDiscovery(etcdSDConfig, server, dieChan)
if err != nil {
logger.Log.Fatalf("error creating default cluster service discovery component: %s", err.Error())
}
rpcServer, err = cluster.NewNatsRPCServer(natsRPCServerConfig, server, metricsReporters, dieChan, sessionPool)
if err != nil {
logger.Log.Fatalf("error setting default cluster rpc server component: %s", err.Error())
}
rpcClient, err = cluster.NewNatsRPCClient(natsRPCClientConfig, server, metricsReporters, dieChan)
if err != nil {
logger.Log.Fatalf("error setting default cluster rpc client component: %s", err.Error())
}
}
worker, err := worker.NewWorker(workerConfig, enqueueOpts)
if err != nil {
logger.Log.Fatalf("error creating default worker: %s", err.Error())
}
gsi := groups.NewMemoryGroupService(groupServiceConfig)
if err != nil {
panic(err)
}
return &Builder{
acceptors: []acceptor.Acceptor{},
Config: config,
DieChan: dieChan,
PacketDecoder: codec.NewPomeloPacketDecoder(),
PacketEncoder: codec.NewPomeloPacketEncoder(),
MessageEncoder: message.NewMessagesEncoder(config.Pitaya.Handler.Messages.Compression),
Serializer: json.NewSerializer(),
Router: router.New(),
RPCClient: rpcClient,
RPCServer: rpcServer,
MetricsReporters: metricsReporters,
Server: server,
ServerMode: serverMode,
Groups: gsi,
HandlerHooks: handlerHooks,
ServiceDiscovery: serviceDiscovery,
SessionPool: sessionPool,
Worker: worker,
}
}
// AddAcceptor adds a new acceptor to app
func (builder *Builder) AddAcceptor(ac acceptor.Acceptor) {
if !builder.Server.Frontend {
logger.Log.Error("tried to add an acceptor to a backend server, skipping")
return
}
builder.acceptors = append(builder.acceptors, ac)
}
// Build returns a valid App instance
func (builder *Builder) Build() Pitaya {
handlerPool := service.NewHandlerPool()
var remoteService *service.RemoteService
if builder.ServerMode == Standalone {
if builder.ServiceDiscovery != nil || builder.RPCClient != nil || builder.RPCServer != nil {
panic("Standalone mode can't have RPC or service discovery instances")
}
} else {
if !(builder.ServiceDiscovery != nil && builder.RPCClient != nil && builder.RPCServer != nil) {
panic("Cluster mode must have RPC and service discovery instances")
}
builder.Router.SetServiceDiscovery(builder.ServiceDiscovery)
remoteService = service.NewRemoteService(
builder.RPCClient,
builder.RPCServer,
builder.ServiceDiscovery,
builder.PacketEncoder,
builder.Serializer,
builder.Router,
builder.MessageEncoder,
builder.Server,
builder.SessionPool,
builder.HandlerHooks,
handlerPool,
)
builder.RPCServer.SetPitayaServer(remoteService)
}
agentFactory := agent.NewAgentFactory(builder.DieChan,
builder.PacketDecoder,
builder.PacketEncoder,
builder.Serializer,
builder.Config.Pitaya.Heartbeat.Interval,
builder.MessageEncoder,
builder.Config.Pitaya.Buffer.Agent.Messages,
builder.SessionPool,
builder.MetricsReporters,
)
handlerService := service.NewHandlerService(
builder.PacketDecoder,
builder.Serializer,
builder.Config.Pitaya.Buffer.Handler.LocalProcess,
builder.Config.Pitaya.Buffer.Handler.RemoteProcess,
builder.Server,
remoteService,
agentFactory,
builder.MetricsReporters,
builder.HandlerHooks,
handlerPool,
)
return NewApp(
builder.ServerMode,
builder.Serializer,
builder.acceptors,
builder.DieChan,
builder.Router,
builder.Server,
builder.RPCClient,
builder.RPCServer,
builder.Worker,
builder.ServiceDiscovery,
remoteService,
handlerService,
builder.Groups,
builder.SessionPool,
builder.MetricsReporters,
builder.Config.Pitaya,
)
}
// NewDefaultApp returns a default pitaya app instance
func NewDefaultApp(isFrontend bool, serverType string, serverMode ServerMode, serverMetadata map[string]string, config config.BuilderConfig) Pitaya {
builder := NewDefaultBuilder(isFrontend, serverType, serverMode, serverMetadata, config)
return builder.Build()
}
func configureDefaultPipelines(handlerHooks *pipeline.HandlerHooks) {
handlerHooks.BeforeHandler.PushBack(defaultpipelines.StructValidatorInstance.Validate)
}
func addDefaultPrometheus(config config.PrometheusConfig, customMetrics models.CustomMetricsSpec, reporters []metrics.Reporter, serverType string) []metrics.Reporter {
prometheus, err := CreatePrometheusReporter(serverType, config, customMetrics)
if err != nil {
logger.Log.Errorf("failed to start prometheus metrics reporter, skipping %v", err)
} else {
reporters = append(reporters, prometheus)
}
return reporters
}
func addDefaultStatsd(config config.StatsdConfig, reporters []metrics.Reporter, serverType string) []metrics.Reporter {
statsd, err := CreateStatsdReporter(serverType, config)
if err != nil {
logger.Log.Errorf("failed to start statsd metrics reporter, skipping %v", err)
} else {
reporters = append(reporters, statsd)
}
return reporters
}