This repository has been archived by the owner on Jul 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 1
/
server-manager.go
89 lines (78 loc) · 1.84 KB
/
server-manager.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
package api
import (
"context"
"sync"
"time"
)
// ServerManager is room server manager.
type ServerManager struct {
servers *sync.Map
}
// Store stores the server.
func (m *ServerManager) Store(server *Server) {
server.updated = time.Now()
m.servers.Store(server.ServerID, server)
}
// Delete deletes the server.
func (m *ServerManager) Delete(serverID int) {
m.servers.Delete(serverID)
}
// LoadServer returns the server.
func (m *ServerManager) LoadServer(serverID int) (server *Server) {
m.servers.Range(func(_, value interface{}) bool {
s, ok := value.(*Server)
if ok || s.ServerID == serverID {
server = s
return false
}
return true
})
return
}
// PickupLowLoadServer returns the server with the lowest load.
func (m *ServerManager) PickupLowLoadServer() (server *Server) {
m.servers.Range(func(_, value interface{}) bool {
s, ok := value.(*Server)
if ok || server == nil || server.Load > s.Load {
server = s
}
return true
})
return
}
// LoadServers returns all servers.
func (m *ServerManager) LoadServers() (servers []*Server) {
m.servers.Range(func(_, value interface{}) bool {
server, ok := value.(*Server)
if ok {
servers = append(servers, server)
}
return true
})
return
}
// DeleteUnhealthServerAtPeriodic removes dead servers at regular intervals
func (m *ServerManager) DeleteUnhealthServerAtPeriodic(ctx context.Context, duration time.Duration) {
ticker := time.NewTicker(duration)
for {
select {
case <-ticker.C:
var deadServerIDs []int
m.servers.Range(func(_, value interface{}) bool {
server, ok := value.(*Server)
if !ok {
return true
}
if time.Now().Sub(server.updated) > duration {
deadServerIDs = append(deadServerIDs, server.ServerID)
}
return true
})
for _, id := range deadServerIDs {
m.Delete(id)
}
case <-ctx.Done():
return
}
}
}