forked from botlabs-gg/yagpdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server.go
457 lines (365 loc) · 11.1 KB
/
server.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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
package botrest
import (
"context"
"encoding/json"
"net/http"
"net/http/pprof"
"sort"
"strconv"
"sync"
"time"
"emperror.dev/errors"
"github.com/jonas747/discordgo"
"github.com/jonas747/dstate"
"github.com/jonas747/dutil"
"github.com/jonas747/retryableredis"
"github.com/jonas747/yagpdb/bot"
"github.com/jonas747/yagpdb/common"
"github.com/jonas747/yagpdb/common/config"
"goji.io"
"goji.io/pat"
)
func RegisterPlugin() {
common.RegisterPlugin(&Plugin{})
}
var (
_ bot.BotInitHandler = (*Plugin)(nil)
_ bot.BotStopperHandler = (*Plugin)(nil)
)
var confBotrestListenAddr = config.RegisterOption("yagpdb.botrest.listen_address", "botrest listening address, it will use the first port available above 5010", "127.0.0.1")
var serverLogger = common.GetFixedPrefixLogger("botrest_server")
type BotRestPlugin interface {
InitBotRestServer(mux *goji.Mux)
}
type Plugin struct {
srv *http.Server
srvMU sync.Mutex
}
func (p *Plugin) PluginInfo() *common.PluginInfo {
return &common.PluginInfo{
Name: "BotREST",
SysName: "botrest",
Category: common.PluginCategoryCore,
}
}
func (p *Plugin) BotInit() {
muxer := goji.NewMux()
muxer.HandleFunc(pat.Get("/:guild/guild"), HandleGuild)
muxer.HandleFunc(pat.Get("/:guild/botmember"), HandleBotMember)
muxer.HandleFunc(pat.Get("/:guild/members"), HandleGetMembers)
muxer.HandleFunc(pat.Get("/:guild/membercolors"), HandleGetMemberColors)
muxer.HandleFunc(pat.Get("/:guild/onlinecount"), HandleGetOnlineCount)
muxer.HandleFunc(pat.Get("/:guild/channelperms/:channel"), HandleChannelPermissions)
muxer.HandleFunc(pat.Get("/gw_status"), HandleGWStatus)
muxer.HandleFunc(pat.Post("/shard/:shard/reconnect"), HandleReconnectShard)
muxer.HandleFunc(pat.Get("/ping"), HandlePing)
// Debug stuff
muxer.HandleFunc(pat.Get("/debug/pprof/*"), pprof.Index)
muxer.HandleFunc(pat.Get("/debug/pprof"), pprof.Index)
muxer.HandleFunc(pat.Get("/debug2/pproff/cmdline"), pprof.Cmdline)
muxer.HandleFunc(pat.Get("/debug2/pproff/profile"), pprof.Profile)
muxer.HandleFunc(pat.Get("/debug2/pproff/symbol"), pprof.Symbol)
muxer.HandleFunc(pat.Get("/debug2/pproff/trace"), pprof.Trace)
for _, p := range common.Plugins {
if botRestPlugin, ok := p.(BotRestPlugin); ok {
botRestPlugin.InitBotRestServer(muxer)
}
}
p.srv = &http.Server{
Handler: muxer,
}
currentPort := 5010
go func() {
// listen address excluding port
listenAddr := confBotrestListenAddr.GetString()
if listenAddr == "" {
// default to safe loopback interface
listenAddr = "127.0.0.1"
}
for {
address := listenAddr + ":" + strconv.Itoa(currentPort)
serverLogger.Println("starting botrest on ", address)
p.srvMU.Lock()
p.srv.Addr = address
p.srvMU.Unlock()
err := p.srv.ListenAndServe()
if err != nil {
// Shutdown was called for graceful shutdown
if err == http.ErrServerClosed {
serverLogger.Info("server closed, shutting down...")
return
}
// Retry with a higher port until we succeed
serverLogger.WithError(err).Error("failed starting botrest http server on ", address, " trying again on next port")
currentPort++
time.Sleep(time.Millisecond)
continue
}
serverLogger.Println("botrest returned without any error")
break
}
}()
// Wait for the server address to stop changing
go func() {
lastAddr := ""
lastChange := time.Now()
for {
p.srvMU.Lock()
addr := p.srv.Addr
p.srvMU.Unlock()
if lastAddr != addr {
lastAddr = addr
time.Sleep(time.Second)
lastChange = time.Now()
continue
}
if time.Since(lastChange) > time.Second*5 {
// found avaiable port
go p.mapper(lastAddr)
return
}
time.Sleep(time.Second)
}
}()
}
func (p *Plugin) mapper(address string) {
t := time.NewTicker(time.Second * 10)
for {
p.mapAddressToShards(address)
<-t.C
}
}
func (p *Plugin) mapAddressToShards(address string) {
processShards := bot.GetProcessShards()
// serverLogger.Debug("mapping ", address, " to current process shards")
for _, shard := range processShards {
err := common.RedisPool.Do(retryableredis.Cmd(nil, "SET", RedisKeyShardAddressMapping(shard), address))
if err != nil {
serverLogger.WithError(err).Error("failed mapping botrest")
}
}
if bot.UsingOrchestrator {
err := common.RedisPool.Do(retryableredis.Cmd(nil, "SET", RedisKeyNodeAddressMapping(bot.NodeConn.GetIDLock()), address))
if err != nil {
serverLogger.WithError(err).Error("failed mapping node")
}
}
}
func (p *Plugin) StopBot(wg *sync.WaitGroup) {
p.srv.Shutdown(context.TODO())
wg.Done()
}
func ServeJson(w http.ResponseWriter, r *http.Request, data interface{}) {
err := json.NewEncoder(w).Encode(data)
if err != nil {
serverLogger.WithError(err).Error("Failed sending json")
}
}
// Returns true if an error occured
func ServerError(w http.ResponseWriter, r *http.Request, err error) bool {
if err == nil {
return false
}
encodedErr, _ := json.Marshal(err.Error())
w.WriteHeader(http.StatusInternalServerError)
w.Write(encodedErr)
return true
}
func HandleGuild(w http.ResponseWriter, r *http.Request) {
gId, _ := strconv.ParseInt(pat.Param(r, "guild"), 10, 64)
guild := bot.State.Guild(true, gId)
if guild == nil {
ServerError(w, r, errors.New("Guild not found"))
return
}
gCopy := guild.DeepCopy(true, true, false, true)
ServeJson(w, r, gCopy)
}
func HandleBotMember(w http.ResponseWriter, r *http.Request) {
gId, _ := strconv.ParseInt(pat.Param(r, "guild"), 10, 64)
guild := bot.State.Guild(true, gId)
if guild == nil {
ServerError(w, r, errors.New("Guild not found"))
return
}
member := guild.MemberDGoCopy(true, common.BotUser.ID)
if member == nil {
ServerError(w, r, errors.New("Bot Member not found"))
return
}
ServeJson(w, r, member)
}
func HandleGetMembers(w http.ResponseWriter, r *http.Request) {
gId, _ := strconv.ParseInt(pat.Param(r, "guild"), 10, 64)
uIDs, ok := r.URL.Query()["users"]
if !ok || len(uIDs) < 1 {
ServerError(w, r, errors.New("No id's provided"))
return
}
if len(uIDs) > 100 {
ServerError(w, r, errors.New("Too many ids provided"))
return
}
guild := bot.State.Guild(true, gId)
if guild == nil {
ServerError(w, r, errors.New("Guild not found"))
return
}
uIDsParsed := make([]int64, 0, len(uIDs))
for _, v := range uIDs {
parsed, _ := strconv.ParseInt(v, 10, 64)
uIDsParsed = append(uIDsParsed, parsed)
}
memberStates, _ := bot.GetMembers(gId, uIDsParsed...)
members := make([]*discordgo.Member, len(memberStates))
for i, v := range memberStates {
members[i] = v.DGoCopy()
}
ServeJson(w, r, members)
}
func HandleGetMemberColors(w http.ResponseWriter, r *http.Request) {
gId, _ := strconv.ParseInt(pat.Param(r, "guild"), 10, 64)
uIDs, ok := r.URL.Query()["users"]
if !ok || len(uIDs) < 1 {
ServerError(w, r, errors.New("No id's provided"))
return
}
if len(uIDs) > 100 {
ServerError(w, r, errors.New("Too many ids provided"))
return
}
guild := bot.State.Guild(true, gId)
if guild == nil {
ServerError(w, r, errors.New("Guild not found"))
return
}
uIDsParsed := make([]int64, 0, len(uIDs))
for _, v := range uIDs {
parsed, _ := strconv.ParseInt(v, 10, 64)
uIDsParsed = append(uIDsParsed, parsed)
}
memberStates, _ := bot.GetMembers(gId, uIDsParsed...)
guild.Lock()
defer guild.Unlock()
// Make sure the roles are in the proper order
sort.Sort(dutil.Roles(guild.Guild.Roles))
colors := make(map[string]int)
for _, ms := range memberStates {
// Find the highest role this user has with a color
for _, role := range guild.Guild.Roles {
if role.Color == 0 {
continue
}
if !common.ContainsInt64Slice(ms.Roles, role.ID) {
continue
}
// Bingo
colors[ms.StrID()] = role.Color
break
}
}
ServeJson(w, r, colors)
}
func HandleGetOnlineCount(w http.ResponseWriter, r *http.Request) {
gId, _ := strconv.ParseInt(pat.Param(r, "guild"), 10, 64)
guild := bot.State.Guild(true, gId)
if guild == nil {
ServerError(w, r, errors.New("Guild not found"))
return
}
count := 0
guild.RLock()
for _, ms := range guild.Members {
if ms.PresenceSet && ms.PresenceStatus != dstate.StatusNotSet && ms.PresenceStatus != dstate.StatusOffline {
count++
}
}
guild.RUnlock()
ServeJson(w, r, count)
}
func HandleChannelPermissions(w http.ResponseWriter, r *http.Request) {
gId, _ := strconv.ParseInt(pat.Param(r, "guild"), 10, 64)
cId, _ := strconv.ParseInt(pat.Param(r, "channel"), 10, 64)
guild := bot.State.Guild(true, gId)
if guild == nil {
ServerError(w, r, errors.New("Guild not found"))
return
}
perms, err := guild.MemberPermissions(true, cId, common.BotUser.ID)
if err != nil {
ServerError(w, r, errors.WithMessage(err, "Error calculating perms"))
return
}
ServeJson(w, r, perms)
}
func HandlePing(w http.ResponseWriter, r *http.Request) {
ServeJson(w, r, "pong")
}
type ShardStatus struct {
ShardID int `json:"shard_id"`
TotalEvents int64 `json:"total_events"`
EventsPerSecond float64 `json:"events_per_second"`
ConnStatus discordgo.GatewayStatus `json:"conn_status"`
LastHeartbeatSend time.Time `json:"last_heartbeat_send"`
LastHeartbeatAck time.Time `json:"last_heartbeat_ack"`
}
func HandleGWStatus(w http.ResponseWriter, r *http.Request) {
totalEventStats, periodEventStats := bot.EventLogger.GetStats()
numShards := bot.ShardManager.GetNumShards()
result := make([]*ShardStatus, 0, numShards)
processShards := bot.GetProcessShards()
for _, shardID := range processShards {
shard := bot.ShardManager.Sessions[shardID]
sumEvents := int64(0)
sumPeriodEvents := int64(0)
for j, _ := range totalEventStats[shardID] {
sumEvents += totalEventStats[shardID][j]
sumPeriodEvents += periodEventStats[shardID][j]
}
if shard == nil || shard.GatewayManager == nil {
result[shardID] = &ShardStatus{ConnStatus: discordgo.GatewayStatusDisconnected}
continue
}
beat, ack := shard.GatewayManager.HeartBeatStats()
result = append(result, &ShardStatus{
ShardID: shardID,
ConnStatus: shard.GatewayManager.Status(),
TotalEvents: sumEvents,
EventsPerSecond: float64(sumPeriodEvents) / bot.EventLoggerPeriodDuration.Seconds(),
LastHeartbeatSend: beat,
LastHeartbeatAck: ack,
})
}
ServeJson(w, r, result)
}
func HandleReconnectShard(w http.ResponseWriter, r *http.Request) {
sID := pat.Param(r, "shard")
forceReidentify := r.FormValue("reidentify") == "1"
if sID == "*" {
go RestartAll(forceReidentify)
ServeJson(w, r, "ok")
return
}
parsed, _ := strconv.ParseInt(sID, 10, 32)
shardcount := bot.ShardManager.GetNumShards()
if parsed < 0 || int(parsed) >= shardcount {
ServerError(w, r, errors.New("Unknown shard"))
return
}
err := bot.ShardManager.Sessions[parsed].GatewayManager.Reconnect(forceReidentify)
if err != nil {
ServerError(w, r, errors.WithMessage(err, "Reconnect"))
return
}
ServeJson(w, r, "ok")
}
func RestartAll(reidentify bool) {
serverLogger.Println("Reconnecting all shards re-identify:", reidentify)
for _, v := range bot.ShardManager.Sessions {
err := v.GatewayManager.Reconnect(reidentify)
if err != nil {
serverLogger.WithError(err).Error("Failed reconnecting shard")
}
time.Sleep(time.Second * 5)
}
}