-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathserverpool.go
More file actions
72 lines (64 loc) · 1.72 KB
/
serverpool.go
File metadata and controls
72 lines (64 loc) · 1.72 KB
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
package main
import (
"log"
"net/url"
"sync/atomic"
)
type ServerPool struct {
backends []*Backend
current uint64
}
// AddBackend to the server pool
func (s *ServerPool) AddBackend(backend *Backend) {
s.backends = append(s.backends, backend)
}
// NextIndex atomically increase the counter and return an index
func (s *ServerPool) NextIndex() int {
return int(atomic.AddUint64(&s.current, uint64(1)) % uint64(len(s.backends)))
}
// MarkBackendStatus changes a status of a backend
func (s *ServerPool) MarkBackendStatus(backendUrl *url.URL, alive bool) {
for _, b := range s.backends {
if b.URL.String() == backendUrl.String() {
b.SetAlive(alive)
break
}
}
}
// GetNextPeer returns next active peer to take a connection
func (s *ServerPool) GetNextPeer() *Backend {
// loop entire backends to find out an Alive backend
next := s.NextIndex()
l := len(s.backends) + next // start from next and move a full cycle
for i := next; i < l; i++ {
idx := i % len(s.backends) // take an index by modding
if s.backends[idx].IsAlive() { // if we have an alive backend, use it and store if its not the original one
if i != next {
atomic.StoreUint64(&s.current, uint64(idx))
}
return s.backends[idx]
}
}
return nil
}
func (s *ServerPool) GetPeer(roomId int) *Backend {
// Good To Make Dynamic
serverId := (roomId - 1) / 10000
log.Printf("serverId: %v", serverId)
if serverId <= len(s.backends) {
return s.backends[serverId]
}
return nil
}
// HealthCheck pings the backends and update the status
func (s *ServerPool) HealthCheck() {
for _, b := range s.backends {
status := "up"
alive := isBackendAlive(b.URL)
b.SetAlive(alive)
if !alive {
status = "down"
}
log.Printf("%s [%s]\n", b.URL, status)
}
}